typos
[friendica.git/.git] / boot.php
1 <?php
2 /**
3  * @file boot.php
4  * This file defines some global constants and includes the central App class.
5  */
6
7 /**
8  * Friendica
9  *
10  * Friendica is a communications platform for integrated social communications
11  * utilising decentralised communications and linkage to several indie social
12  * projects - as well as popular mainstream providers.
13  *
14  * Our mission is to free our friends and families from the clutches of
15  * data-harvesting corporations, and pave the way to a future where social
16  * communications are free and open and flow between alternate providers as
17  * easily as email does today.
18  */
19
20 require_once __DIR__ . DIRECTORY_SEPARATOR . 'vendor' . DIRECTORY_SEPARATOR . 'autoload.php';
21
22 use Friendica\App;
23 use Friendica\BaseObject;
24 use Friendica\Core\Addon;
25 use Friendica\Core\Cache;
26 use Friendica\Core\Config;
27 use Friendica\Core\L10n;
28 use Friendica\Core\PConfig;
29 use Friendica\Core\Protocol;
30 use Friendica\Core\System;
31 use Friendica\Core\Worker;
32 use Friendica\Database\DBM;
33 use Friendica\Database\DBStructure;
34 use Friendica\Model\Contact;
35 use Friendica\Model\Conversation;
36 use Friendica\Util\DateTimeFormat;
37
38 require_once 'include/text.php';
39
40 define('FRIENDICA_PLATFORM',     'Friendica');
41 define('FRIENDICA_CODENAME',     'The Tazmans Flax-lily');
42 define('FRIENDICA_VERSION',      '2018-05-dev');
43 define('DFRN_PROTOCOL_VERSION',  '2.23');
44 define('DB_UPDATE_VERSION',      1259);
45 define('NEW_UPDATE_ROUTINE_VERSION', 1170);
46
47 /**
48  * @brief Constants for the database update check
49  */
50 const DB_UPDATE_NOT_CHECKED = 0; // Database check wasn't executed before
51 const DB_UPDATE_SUCCESSFUL = 1;  // Database check was successful
52 const DB_UPDATE_FAILED = 2;      // Database check failed
53
54 /**
55  * @brief Constant with a HTML line break.
56  *
57  * Contains a HTML line break (br) element and a real carriage return with line
58  * feed for the source.
59  * This can be used in HTML and JavaScript where needed a line break.
60  */
61 define('EOL',                    "<br />\r\n");
62
63 /**
64  * @brief Image storage quality.
65  *
66  * Lower numbers save space at cost of image detail.
67  * For ease of upgrade, please do not change here. Change jpeg quality with
68  * $a->config['system']['jpeg_quality'] = n;
69  * in .htconfig.php, where n is netween 1 and 100, and with very poor results
70  * below about 50
71  */
72 define('JPEG_QUALITY',            100);
73
74 /**
75  * $a->config['system']['png_quality'] from 0 (uncompressed) to 9
76  */
77 define('PNG_QUALITY',             8);
78
79 /**
80  * An alternate way of limiting picture upload sizes. Specify the maximum pixel
81  * length that pictures are allowed to be (for non-square pictures, it will apply
82  * to the longest side). Pictures longer than this length will be resized to be
83  * this length (on the longest side, the other side will be scaled appropriately).
84  * Modify this value using
85  *
86  *    $a->config['system']['max_image_length'] = n;
87  *
88  * in .htconfig.php
89  *
90  * If you don't want to set a maximum length, set to -1. The default value is
91  * defined by 'MAX_IMAGE_LENGTH' below.
92  */
93 define('MAX_IMAGE_LENGTH',        -1);
94
95 /**
96  * Not yet used
97  */
98 define('DEFAULT_DB_ENGINE',  'InnoDB');
99
100 /**
101  * @name SSL Policy
102  *
103  * SSL redirection policies
104  * @{
105  */
106 define('SSL_POLICY_NONE',         0);
107 define('SSL_POLICY_FULL',         1);
108 define('SSL_POLICY_SELFSIGN',     2);
109 /* @}*/
110
111 /**
112  * @name Logger
113  *
114  * log levels
115  * @{
116  */
117 define('LOGGER_NORMAL',          0);
118 define('LOGGER_TRACE',           1);
119 define('LOGGER_DEBUG',           2);
120 define('LOGGER_DATA',            3);
121 define('LOGGER_ALL',             4);
122 /* @}*/
123
124 /**
125  * @name Cache
126  * @deprecated since version 3.6
127  * @see Cache
128  *
129  * Cache levels
130  * @{
131  */
132 define('CACHE_MONTH',            Cache::MONTH);
133 define('CACHE_WEEK',             Cache::WEEK);
134 define('CACHE_DAY',              Cache::DAY);
135 define('CACHE_HOUR',             Cache::HOUR);
136 define('CACHE_HALF_HOUR',        Cache::HALF_HOUR);
137 define('CACHE_QUARTER_HOUR',     Cache::QUARTER_HOUR);
138 define('CACHE_FIVE_MINUTES',     Cache::FIVE_MINUTES);
139 define('CACHE_MINUTE',           Cache::MINUTE);
140 /* @}*/
141
142 /**
143  * @name Register
144  *
145  * Registration policies
146  * @{
147  */
148 define('REGISTER_CLOSED',        0);
149 define('REGISTER_APPROVE',       1);
150 define('REGISTER_OPEN',          2);
151 /**
152  * @}
153 */
154
155 /**
156  * @name Contact_is
157  *
158  * Relationship types
159  * @{
160  */
161 define('CONTACT_IS_FOLLOWER', 1);
162 define('CONTACT_IS_SHARING',  2);
163 define('CONTACT_IS_FRIEND',   3);
164 /**
165  *  @}
166  */
167
168 /**
169  * @name Update
170  *
171  * DB update return values
172  * @{
173  */
174 define('UPDATE_SUCCESS', 0);
175 define('UPDATE_FAILED',  1);
176 /**
177  * @}
178  */
179
180 /**
181  * @name page/profile types
182  *
183  * PAGE_NORMAL is a typical personal profile account
184  * PAGE_SOAPBOX automatically approves all friend requests as CONTACT_IS_SHARING, (readonly)
185  * PAGE_COMMUNITY automatically approves all friend requests as CONTACT_IS_SHARING, but with
186  *      write access to wall and comments (no email and not included in page owner's ACL lists)
187  * PAGE_FREELOVE automatically approves all friend requests as full friends (CONTACT_IS_FRIEND).
188  *
189  * @{
190  */
191 define('PAGE_NORMAL',            0);
192 define('PAGE_SOAPBOX',           1);
193 define('PAGE_COMMUNITY',         2);
194 define('PAGE_FREELOVE',          3);
195 define('PAGE_BLOG',              4);
196 define('PAGE_PRVGROUP',          5);
197 /**
198  * @}
199  */
200
201 /**
202  * @name account types
203  *
204  * ACCOUNT_TYPE_PERSON - the account belongs to a person
205  *      Associated page types: PAGE_NORMAL, PAGE_SOAPBOX, PAGE_FREELOVE
206  *
207  * ACCOUNT_TYPE_ORGANISATION - the account belongs to an organisation
208  *      Associated page type: PAGE_SOAPBOX
209  *
210  * ACCOUNT_TYPE_NEWS - the account is a news reflector
211  *      Associated page type: PAGE_SOAPBOX
212  *
213  * ACCOUNT_TYPE_COMMUNITY - the account is community forum
214  *      Associated page types: PAGE_COMMUNITY, PAGE_PRVGROUP
215  * @{
216  */
217 define('ACCOUNT_TYPE_PERSON',      0);
218 define('ACCOUNT_TYPE_ORGANISATION', 1);
219 define('ACCOUNT_TYPE_NEWS',        2);
220 define('ACCOUNT_TYPE_COMMUNITY',   3);
221 /**
222  * @}
223  */
224
225 /**
226  * @name CP
227  *
228  * Type of the community page
229  * @{
230  */
231 define('CP_NO_COMMUNITY_PAGE',  -1);
232 define('CP_USERS_ON_SERVER',     0);
233 define('CP_GLOBAL_COMMUNITY',    1);
234 define('CP_USERS_AND_GLOBAL',    2);
235 /**
236  * @}
237  */
238
239 /**
240  * @name Protocols
241  * @deprecated since version 3.6
242  * @see Conversation
243  *
244  * Different protocols that we are storing
245  * @{
246  */
247 define('PROTOCOL_UNKNOWN'        , Conversation::PROTOCOL_UNKNOWN);
248 define('PROTOCOL_DFRN'           , Conversation::PROTOCOL_DFRN);
249 define('PROTOCOL_DIASPORA'       , Conversation::PROTOCOL_DIASPORA);
250 define('PROTOCOL_OSTATUS_SALMON' , Conversation::PROTOCOL_OSTATUS_SALMON);
251 define('PROTOCOL_OSTATUS_FEED'   , Conversation::PROTOCOL_OSTATUS_FEED);    // Deprecated
252 define('PROTOCOL_GS_CONVERSATION', Conversation::PROTOCOL_GS_CONVERSATION); // Deprecated
253 define('PROTOCOL_SPLITTED_CONV'  , Conversation::PROTOCOL_SPLITTED_CONV);
254 /**
255  * @}
256  */
257
258 /**
259  * @name Network constants
260  * @deprecated since version 3.6
261  * @see Protocol
262  *
263  * Network and protocol family types
264  * @{
265  */
266 define('NETWORK_DFRN'     , Protocol::DFRN);      // Friendica, Mistpark, other DFRN implementations
267 define('NETWORK_ZOT'      , Protocol::ZOT);       // Zot! - Currently unsupported
268 define('NETWORK_OSTATUS'  , Protocol::OSTATUS);   // GNU-social, Pleroma, Mastodon, other OStatus implementations
269 define('NETWORK_FEED'     , Protocol::FEED);      // RSS/Atom feeds with no known "post/notify" protocol
270 define('NETWORK_DIASPORA' , Protocol::DIASPORA);  // Diaspora
271 define('NETWORK_MAIL'     , Protocol::MAIL);      // IMAP/POP
272 define('NETWORK_FACEBOOK' , Protocol::FACEBOOK);  // Facebook API
273 define('NETWORK_LINKEDIN' , Protocol::LINKEDIN);  // LinkedIn
274 define('NETWORK_XMPP'     , Protocol::XMPP);      // XMPP - Currently unsupported
275 define('NETWORK_MYSPACE'  , Protocol::MYSPACE);   // MySpace - Currently unsupported
276 define('NETWORK_GPLUS'    , Protocol::GPLUS);     // Google+
277 define('NETWORK_PUMPIO'   , Protocol::PUMPIO);    // pump.io
278 define('NETWORK_TWITTER'  , Protocol::TWITTER);   // Twitter
279 define('NETWORK_DIASPORA2', Protocol::DIASPORA2); // Diaspora connector
280 define('NETWORK_STATUSNET', Protocol::STATUSNET); // Statusnet connector
281 define('NETWORK_APPNET'   , Protocol::APPNET);    // app.net - Dead protocol
282 define('NETWORK_NEWS'     , Protocol::NEWS);      // Network News Transfer Protocol - Currently unsupported
283 define('NETWORK_ICALENDAR', Protocol::ICALENDAR); // iCalendar - Currently unsupported
284 define('NETWORK_PNUT'     , Protocol::PNUT);      // pnut.io - Currently unsupported
285 define('NETWORK_PHANTOM'  , Protocol::PHANTOM);   // Place holder
286 /**
287  * @}
288  */
289
290 /**
291  * These numbers are used in stored permissions
292  * and existing allocations MUST NEVER BE CHANGED
293  * OR RE-ASSIGNED! You may only add to them.
294  */
295 $netgroup_ids = [
296         NETWORK_DFRN     => (-1),
297         NETWORK_ZOT      => (-2),
298         NETWORK_OSTATUS  => (-3),
299         NETWORK_FEED     => (-4),
300         NETWORK_DIASPORA => (-5),
301         NETWORK_MAIL     => (-6),
302         NETWORK_FACEBOOK => (-8),
303         NETWORK_LINKEDIN => (-9),
304         NETWORK_XMPP     => (-10),
305         NETWORK_MYSPACE  => (-11),
306         NETWORK_GPLUS    => (-12),
307         NETWORK_PUMPIO   => (-13),
308         NETWORK_TWITTER  => (-14),
309         NETWORK_DIASPORA2 => (-15),
310         NETWORK_STATUSNET => (-16),
311         NETWORK_APPNET    => (-17),
312         NETWORK_NEWS      => (-18),
313         NETWORK_ICALENDAR => (-19),
314         NETWORK_PNUT      => (-20),
315
316         NETWORK_PHANTOM  => (-127),
317 ];
318
319 /**
320  * Maximum number of "people who like (or don't like) this"  that we will list by name
321  */
322 define('MAX_LIKERS',    75);
323
324 /**
325  * Communication timeout
326  */
327 define('ZCURL_TIMEOUT', (-1));
328
329 /**
330  * @name Notify
331  *
332  * Email notification options
333  * @{
334  */
335 define('NOTIFY_INTRO',    0x0001);
336 define('NOTIFY_CONFIRM',  0x0002);
337 define('NOTIFY_WALL',     0x0004);
338 define('NOTIFY_COMMENT',  0x0008);
339 define('NOTIFY_MAIL',     0x0010);
340 define('NOTIFY_SUGGEST',  0x0020);
341 define('NOTIFY_PROFILE',  0x0040);
342 define('NOTIFY_TAGSELF',  0x0080);
343 define('NOTIFY_TAGSHARE', 0x0100);
344 define('NOTIFY_POKE',     0x0200);
345 define('NOTIFY_SHARE',    0x0400);
346
347 define('SYSTEM_EMAIL',    0x4000);
348
349 define('NOTIFY_SYSTEM',   0x8000);
350 /* @}*/
351
352
353 /**
354  * @name Term
355  *
356  * Tag/term types
357  * @{
358  */
359 define('TERM_UNKNOWN',   0);
360 define('TERM_HASHTAG',   1);
361 define('TERM_MENTION',   2);
362 define('TERM_CATEGORY',  3);
363 define('TERM_PCATEGORY', 4);
364 define('TERM_FILE',      5);
365 define('TERM_SAVEDSEARCH', 6);
366 define('TERM_CONVERSATION', 7);
367
368 define('TERM_OBJ_POST',  1);
369 define('TERM_OBJ_PHOTO', 2);
370
371 /**
372  * @name Namespaces
373  *
374  * Various namespaces we may need to parse
375  * @{
376  */
377 define('NAMESPACE_ZOT',             'http://purl.org/zot');
378 define('NAMESPACE_DFRN',            'http://purl.org/macgirvin/dfrn/1.0');
379 define('NAMESPACE_THREAD',          'http://purl.org/syndication/thread/1.0');
380 define('NAMESPACE_TOMB',            'http://purl.org/atompub/tombstones/1.0');
381 define('NAMESPACE_ACTIVITY',        'http://activitystrea.ms/spec/1.0/');
382 define('NAMESPACE_ACTIVITY_SCHEMA', 'http://activitystrea.ms/schema/1.0/');
383 define('NAMESPACE_MEDIA',           'http://purl.org/syndication/atommedia');
384 define('NAMESPACE_SALMON_ME',       'http://salmon-protocol.org/ns/magic-env');
385 define('NAMESPACE_OSTATUSSUB',      'http://ostatus.org/schema/1.0/subscribe');
386 define('NAMESPACE_GEORSS',          'http://www.georss.org/georss');
387 define('NAMESPACE_POCO',            'http://portablecontacts.net/spec/1.0');
388 define('NAMESPACE_FEED',            'http://schemas.google.com/g/2010#updates-from');
389 define('NAMESPACE_OSTATUS',         'http://ostatus.org/schema/1.0');
390 define('NAMESPACE_STATUSNET',       'http://status.net/schema/api/1/');
391 define('NAMESPACE_ATOM1',           'http://www.w3.org/2005/Atom');
392 define('NAMESPACE_MASTODON',        'http://mastodon.social/schema/1.0');
393 /* @}*/
394
395 /**
396  * @name Activity
397  *
398  * Activity stream defines
399  * @{
400  */
401 define('ACTIVITY_LIKE',        NAMESPACE_ACTIVITY_SCHEMA . 'like');
402 define('ACTIVITY_DISLIKE',     NAMESPACE_DFRN            . '/dislike');
403 define('ACTIVITY_ATTEND',      NAMESPACE_ZOT             . '/activity/attendyes');
404 define('ACTIVITY_ATTENDNO',    NAMESPACE_ZOT             . '/activity/attendno');
405 define('ACTIVITY_ATTENDMAYBE', NAMESPACE_ZOT             . '/activity/attendmaybe');
406
407 define('ACTIVITY_OBJ_HEART',   NAMESPACE_DFRN            . '/heart');
408
409 define('ACTIVITY_FRIEND',      NAMESPACE_ACTIVITY_SCHEMA . 'make-friend');
410 define('ACTIVITY_REQ_FRIEND',  NAMESPACE_ACTIVITY_SCHEMA . 'request-friend');
411 define('ACTIVITY_UNFRIEND',    NAMESPACE_ACTIVITY_SCHEMA . 'remove-friend');
412 define('ACTIVITY_FOLLOW',      NAMESPACE_ACTIVITY_SCHEMA . 'follow');
413 define('ACTIVITY_UNFOLLOW',    NAMESPACE_ACTIVITY_SCHEMA . 'stop-following');
414 define('ACTIVITY_JOIN',        NAMESPACE_ACTIVITY_SCHEMA . 'join');
415
416 define('ACTIVITY_POST',        NAMESPACE_ACTIVITY_SCHEMA . 'post');
417 define('ACTIVITY_UPDATE',      NAMESPACE_ACTIVITY_SCHEMA . 'update');
418 define('ACTIVITY_TAG',         NAMESPACE_ACTIVITY_SCHEMA . 'tag');
419 define('ACTIVITY_FAVORITE',    NAMESPACE_ACTIVITY_SCHEMA . 'favorite');
420 define('ACTIVITY_UNFAVORITE',  NAMESPACE_ACTIVITY_SCHEMA . 'unfavorite');
421 define('ACTIVITY_SHARE',       NAMESPACE_ACTIVITY_SCHEMA . 'share');
422 define('ACTIVITY_DELETE',      NAMESPACE_ACTIVITY_SCHEMA . 'delete');
423
424 define('ACTIVITY_POKE',        NAMESPACE_ZOT . '/activity/poke');
425
426 define('ACTIVITY_OBJ_BOOKMARK', NAMESPACE_ACTIVITY_SCHEMA . 'bookmark');
427 define('ACTIVITY_OBJ_COMMENT', NAMESPACE_ACTIVITY_SCHEMA . 'comment');
428 define('ACTIVITY_OBJ_NOTE',    NAMESPACE_ACTIVITY_SCHEMA . 'note');
429 define('ACTIVITY_OBJ_PERSON',  NAMESPACE_ACTIVITY_SCHEMA . 'person');
430 define('ACTIVITY_OBJ_IMAGE',   NAMESPACE_ACTIVITY_SCHEMA . 'image');
431 define('ACTIVITY_OBJ_PHOTO',   NAMESPACE_ACTIVITY_SCHEMA . 'photo');
432 define('ACTIVITY_OBJ_VIDEO',   NAMESPACE_ACTIVITY_SCHEMA . 'video');
433 define('ACTIVITY_OBJ_P_PHOTO', NAMESPACE_ACTIVITY_SCHEMA . 'profile-photo');
434 define('ACTIVITY_OBJ_ALBUM',   NAMESPACE_ACTIVITY_SCHEMA . 'photo-album');
435 define('ACTIVITY_OBJ_EVENT',   NAMESPACE_ACTIVITY_SCHEMA . 'event');
436 define('ACTIVITY_OBJ_GROUP',   NAMESPACE_ACTIVITY_SCHEMA . 'group');
437 define('ACTIVITY_OBJ_TAGTERM', NAMESPACE_DFRN            . '/tagterm');
438 define('ACTIVITY_OBJ_PROFILE', NAMESPACE_DFRN            . '/profile');
439 define('ACTIVITY_OBJ_QUESTION', 'http://activityschema.org/object/question');
440 /* @}*/
441
442 /**
443  * @name Gravity
444  *
445  * Item weight for query ordering
446  * @{
447  */
448 define('GRAVITY_PARENT',       0);
449 define('GRAVITY_LIKE',         3);
450 define('GRAVITY_COMMENT',      6);
451 /* @}*/
452
453 /**
454  * @name Priority
455  *
456  * Process priority for the worker
457  * @{
458  */
459 define('PRIORITY_UNDEFINED',   0);
460 define('PRIORITY_CRITICAL',   10);
461 define('PRIORITY_HIGH',       20);
462 define('PRIORITY_MEDIUM',     30);
463 define('PRIORITY_LOW',        40);
464 define('PRIORITY_NEGLIGIBLE', 50);
465 /* @}*/
466
467 /**
468  * @name Social Relay settings
469  *
470  * See here: https://github.com/jaywink/social-relay
471  * and here: https://wiki.diasporafoundation.org/Relay_servers_for_public_posts
472  * @{
473  */
474 define('SR_SCOPE_NONE', '');
475 define('SR_SCOPE_ALL',  'all');
476 define('SR_SCOPE_TAGS', 'tags');
477 /* @}*/
478
479 /**
480  * Lowest possible date time value
481  */
482 define('NULL_DATE', '0001-01-01 00:00:00');
483
484 // Normally this constant is defined - but not if "pcntl" isn't installed
485 if (!defined("SIGTERM")) {
486         define("SIGTERM", 15);
487 }
488
489 /**
490  * Depending on the PHP version this constant does exist - or not.
491  * See here: http://php.net/manual/en/curl.constants.php#117928
492  */
493 if (!defined('CURLE_OPERATION_TIMEDOUT')) {
494         define('CURLE_OPERATION_TIMEDOUT', CURLE_OPERATION_TIMEOUTED);
495 }
496 /**
497  * Reverse the effect of magic_quotes_gpc if it is enabled.
498  * Please disable magic_quotes_gpc so we don't have to do this.
499  * See http://php.net/manual/en/security.magicquotes.disabling.php
500  */
501 function startup()
502 {
503         error_reporting(E_ERROR | E_WARNING | E_PARSE);
504
505         set_time_limit(0);
506
507         // This has to be quite large to deal with embedded private photos
508         ini_set('pcre.backtrack_limit', 500000);
509
510         if (get_magic_quotes_gpc()) {
511                 $process = [&$_GET, &$_POST, &$_COOKIE, &$_REQUEST];
512                 while (list($key, $val) = each($process)) {
513                         foreach ($val as $k => $v) {
514                                 unset($process[$key][$k]);
515                                 if (is_array($v)) {
516                                         $process[$key][stripslashes($k)] = $v;
517                                         $process[] = &$process[$key][stripslashes($k)];
518                                 } else {
519                                         $process[$key][stripslashes($k)] = stripslashes($v);
520                                 }
521                         }
522                 }
523                 unset($process);
524         }
525 }
526
527 /**
528  * @brief Retrieve the App structure
529  *
530  * Useful in functions which require it but don't get it passed to them
531  *
532  * @return App
533  */
534 function get_app()
535 {
536         global $a;
537
538         if (empty($a)) {
539                 $a = new App(dirname(__DIR__));
540                 BaseObject::setApp($a);
541         }
542
543         return $a;
544 }
545
546 /**
547  * @brief Multi-purpose function to check variable state.
548  *
549  * Usage: x($var) or $x($array, 'key')
550  *
551  * returns false if variable/key is not set
552  * if variable is set, returns 1 if has 'non-zero' value, otherwise returns 0.
553  * e.g. x('') or x(0) returns 0;
554  *
555  * @param string|array $s variable to check
556  * @param string       $k key inside the array to check
557  *
558  * @return bool|int
559  */
560 function x($s, $k = null)
561 {
562         if ($k != null) {
563                 if ((is_array($s)) && (array_key_exists($k, $s))) {
564                         if ($s[$k]) {
565                                 return (int) 1;
566                         }
567                         return (int) 0;
568                 }
569                 return false;
570         } else {
571                 if (isset($s)) {
572                         if ($s) {
573                                 return (int) 1;
574                         }
575                         return (int) 0;
576                 }
577                 return false;
578         }
579 }
580
581 /**
582  * Return the provided variable value if it exists and is truthy or the provided
583  * default value instead.
584  *
585  * Works with initialized variables and potentially uninitialized array keys
586  *
587  * Usages:
588  * - defaults($var, $default)
589  * - defaults($array, 'key', $default)
590  *
591  * @brief Returns a defaut value if the provided variable or array key is falsy
592  * @see x()
593  * @return mixed
594  */
595 function defaults() {
596         $args = func_get_args();
597
598         if (count($args) < 2) {
599                 throw new BadFunctionCallException('defaults() requires at least 2 parameters');
600         }
601         if (count($args) > 3) {
602                 throw new BadFunctionCallException('defaults() cannot use more than 3 parameters');
603         }
604         if (count($args) === 3 && is_null($args[1])) {
605                 throw new BadFunctionCallException('defaults($arr, $key, $def) $key is null');
606         }
607
608         $default = array_pop($args);
609
610         if (call_user_func_array('x', $args)) {
611                 if (count($args) === 1) {
612                         $return = $args[0];
613                 } else {
614                         $return = $args[0][$args[1]];
615                 }
616         } else {
617                 $return = $default;
618         }
619
620         return $return;
621 }
622
623 /**
624  * @brief Returns the baseurl.
625  *
626  * @see System::baseUrl()
627  *
628  * @return string
629  * @TODO Function is deprecated and only used in some addons
630  */
631 function z_root()
632 {
633         return System::baseUrl();
634 }
635
636 /**
637  * @brief Return absolut URL for given $path.
638  *
639  * @param string $path given path
640  *
641  * @return string
642  */
643 function absurl($path)
644 {
645         if (strpos($path, '/') === 0) {
646                 return z_path() . $path;
647         }
648         return $path;
649 }
650
651 /**
652  * @brief Function to check if request was an AJAX (xmlhttprequest) request.
653  *
654  * @return boolean
655  */
656 function is_ajax()
657 {
658         return (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');
659 }
660
661 /**
662  * @brief Function to check if request was an AJAX (xmlhttprequest) request.
663  *
664  * @param boolean $via_worker boolean Is the check run via the worker?
665  */
666 function check_db($via_worker)
667 {
668         $build = Config::get('system', 'build');
669
670         if (empty($build)) {
671                 Config::set('system', 'build', DB_UPDATE_VERSION - 1);
672                 $build = DB_UPDATE_VERSION - 1;
673         }
674
675         // We don't support upgrading from very old versions anymore
676         if ($build < NEW_UPDATE_ROUTINE_VERSION) {
677                 die('You try to update from a version prior to database version 1170. The direct upgrade path is not supported. Please update to version 3.5.4 before updating to this version.');
678         }
679
680         if ($build < DB_UPDATE_VERSION) {
681                 // When we cannot execute the database update via the worker, we will do it directly
682                 if (!Worker::add(PRIORITY_CRITICAL, 'DBUpdate') && $via_worker) {
683                         update_db();
684                 }
685         }
686 }
687
688 /**
689  * Sets the base url for use in cmdline programs which don't have
690  * $_SERVER variables
691  *
692  * @param object $a App
693  */
694 function check_url(App $a)
695 {
696         $url = Config::get('system', 'url');
697
698         // if the url isn't set or the stored url is radically different
699         // than the currently visited url, store the current value accordingly.
700         // "Radically different" ignores common variations such as http vs https
701         // and www.example.com vs example.com.
702         // We will only change the url to an ip address if there is no existing setting
703
704         if (empty($url) || (!link_compare($url, System::baseUrl())) && (!preg_match("/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/", $a->get_hostname))) {
705                 Config::set('system', 'url', System::baseUrl());
706         }
707
708         return;
709 }
710
711 /**
712  * @brief Automatic database updates
713  * @param object $a App
714  */
715 function update_db()
716 {
717         $build = Config::get('system', 'build');
718
719         if (empty($build) || ($build > DB_UPDATE_VERSION)) {
720                 $build = DB_UPDATE_VERSION - 1;
721                 Config::set('system', 'build', $build);
722         }
723
724         if ($build != DB_UPDATE_VERSION) {
725                 require_once 'update.php';
726
727                 $stored = intval($build);
728                 $current = intval(DB_UPDATE_VERSION);
729                 if ($stored < $current) {
730                         Config::load('database');
731
732                         // Compare the current structure with the defined structure
733                         $t = Config::get('database', 'dbupdate_' . DB_UPDATE_VERSION);
734                         if (!is_null($t)) {
735                                 return;
736                         }
737
738                         Config::set('database', 'dbupdate_' . DB_UPDATE_VERSION, time());
739
740                         // run update routine
741                         // it update the structure in one call
742                         $retval = DBStructure::update(false, true);
743                         if ($retval) {
744                                 DBStructure::updateFail(
745                                         DB_UPDATE_VERSION,
746                                         $retval
747                                 );
748                                 return;
749                         } else {
750                                 Config::set('database', 'dbupdate_' . DB_UPDATE_VERSION, 'success');
751                         }
752
753                         // run any left update_nnnn functions in update.php
754                         for ($x = $stored + 1; $x <= $current; $x++) {
755                                 $r = run_update_function($x);
756                                 if (!$r) {
757                                         break;
758                                 }
759                         }
760                 }
761         }
762
763         return;
764 }
765
766 function run_update_function($x)
767 {
768         if (function_exists('update_' . $x)) {
769                 // There could be a lot of processes running or about to run.
770                 // We want exactly one process to run the update command.
771                 // So store the fact that we're taking responsibility
772                 // after first checking to see if somebody else already has.
773                 // If the update fails or times-out completely you may need to
774                 // delete the config entry to try again.
775
776                 $t = Config::get('database', 'update_' . $x);
777                 if (!is_null($t)) {
778                         return false;
779                 }
780                 Config::set('database', 'update_' . $x, time());
781
782                 // call the specific update
783
784                 $func = 'update_' . $x;
785                 $retval = $func();
786
787                 if ($retval) {
788                         //send the administrator an e-mail
789                         DBStructure::updateFail(
790                                 $x,
791                                 L10n::t('Update %s failed. See error logs.', $x)
792                         );
793                         return false;
794                 } else {
795                         Config::set('database', 'update_' . $x, 'success');
796                         Config::set('system', 'build', $x);
797                         return true;
798                 }
799         } else {
800                 Config::set('database', 'update_' . $x, 'success');
801                 Config::set('system', 'build', $x);
802                 return true;
803         }
804 }
805
806 /**
807  * @brief Synchronise addons:
808  *
809  * $a->config['system']['addon'] contains a comma-separated list of names
810  * of addons which are used on this system.
811  * Go through the database list of already installed addons, and if we have
812  * an entry, but it isn't in the config list, call the uninstall procedure
813  * and mark it uninstalled in the database (for now we'll remove it).
814  * Then go through the config list and if we have a addon that isn't installed,
815  * call the install procedure and add it to the database.
816  *
817  * @param object $a App
818  */
819 function check_addons(App $a)
820 {
821         $r = q("SELECT * FROM `addon` WHERE `installed` = 1");
822         if (DBM::is_result($r)) {
823                 $installed = $r;
824         } else {
825                 $installed = [];
826         }
827
828         $addons = Config::get('system', 'addon');
829         $addons_arr = [];
830
831         if ($addons) {
832                 $addons_arr = explode(',', str_replace(' ', '', $addons));
833         }
834
835         $a->addons = $addons_arr;
836
837         $installed_arr = [];
838
839         if (count($installed)) {
840                 foreach ($installed as $i) {
841                         if (!in_array($i['name'], $addons_arr)) {
842                                 Addon::uninstall($i['name']);
843                         } else {
844                                 $installed_arr[] = $i['name'];
845                         }
846                 }
847         }
848
849         if (count($addons_arr)) {
850                 foreach ($addons_arr as $p) {
851                         if (!in_array($p, $installed_arr)) {
852                                 Addon::install($p);
853                         }
854                 }
855         }
856
857         Addon::loadHooks();
858
859         return;
860 }
861
862 function get_guid($size = 16, $prefix = '')
863 {
864         if (is_bool($prefix) && !$prefix) {
865                 $prefix = '';
866         } elseif ($prefix == '') {
867                 $a = get_app();
868                 $prefix = hash('crc32', $a->get_hostname());
869         }
870
871         while (strlen($prefix) < ($size - 13)) {
872                 $prefix .= mt_rand();
873         }
874
875         if ($size >= 24) {
876                 $prefix = substr($prefix, 0, $size - 22);
877                 return str_replace('.', '', uniqid($prefix, true));
878         } else {
879                 $prefix = substr($prefix, 0, max($size - 13, 0));
880                 return uniqid($prefix);
881         }
882 }
883
884 /**
885  * @brief Used to end the current process, after saving session state.
886  * @deprecated
887  */
888 function killme()
889 {
890         exit();
891 }
892
893 /**
894  * @brief Redirect to another URL and terminate this process.
895  */
896 function goaway($path)
897 {
898         if (strstr(normalise_link($path), 'http://')) {
899                 $url = $path;
900         } else {
901                 $url = System::baseUrl() . '/' . ltrim($path, '/');
902         }
903
904         header("Location: $url");
905         killme();
906 }
907
908 /**
909  * @brief Returns the user id of locally logged in user or false.
910  *
911  * @return int|bool user id or false
912  */
913 function local_user()
914 {
915         if (x($_SESSION, 'authenticated') && x($_SESSION, 'uid')) {
916                 return intval($_SESSION['uid']);
917         }
918         return false;
919 }
920
921 /**
922  * @brief Returns the public contact id of logged in user or false.
923  *
924  * @return int|bool public contact id or false
925  */
926 function public_contact()
927 {
928         static $public_contact_id = false;
929
930         if (!$public_contact_id && x($_SESSION, 'authenticated')) {
931                 if (x($_SESSION, 'my_address')) {
932                         // Local user
933                         $public_contact_id = intval(Contact::getIdForURL($_SESSION['my_address'], 0, true));
934                 } elseif (x($_SESSION, 'visitor_home')) {
935                         // Remote user
936                         $public_contact_id = intval(Contact::getIdForURL($_SESSION['visitor_home'], 0, true));
937                 }
938         } elseif (!x($_SESSION, 'authenticated')) {
939                 $public_contact_id = false;
940         }
941
942         return $public_contact_id;
943 }
944
945 /**
946  * @brief Returns contact id of authenticated site visitor or false
947  *
948  * @return int|bool visitor_id or false
949  */
950 function remote_user()
951 {
952         // You cannot be both local and remote
953         if (local_user()) {
954                 return false;
955         }
956         if (x($_SESSION, 'authenticated') && x($_SESSION, 'visitor_id')) {
957                 return intval($_SESSION['visitor_id']);
958         }
959         return false;
960 }
961
962 /**
963  * @brief Show an error message to user.
964  *
965  * This function save text in session, to be shown to the user at next page load
966  *
967  * @param string $s - Text of notice
968  */
969 function notice($s)
970 {
971         $a = get_app();
972         if (!x($_SESSION, 'sysmsg')) {
973                 $_SESSION['sysmsg'] = [];
974         }
975         if ($a->interactive) {
976                 $_SESSION['sysmsg'][] = $s;
977         }
978 }
979
980 /**
981  * @brief Show an info message to user.
982  *
983  * This function save text in session, to be shown to the user at next page load
984  *
985  * @param string $s - Text of notice
986  */
987 function info($s)
988 {
989         $a = get_app();
990
991         if (local_user() && PConfig::get(local_user(), 'system', 'ignore_info')) {
992                 return;
993         }
994
995         if (!x($_SESSION, 'sysmsg_info')) {
996                 $_SESSION['sysmsg_info'] = [];
997         }
998         if ($a->interactive) {
999                 $_SESSION['sysmsg_info'][] = $s;
1000         }
1001 }
1002
1003 /**
1004  * @brief Wrapper around config to limit the text length of an incoming message
1005  *
1006  * @return int
1007  */
1008 function get_max_import_size()
1009 {
1010         $a = get_app();
1011         return (x($a->config, 'max_import_size') ? $a->config['max_import_size'] : 0);
1012 }
1013
1014
1015 function current_theme()
1016 {
1017         $app_base_themes = ['duepuntozero', 'dispy', 'quattro'];
1018
1019         $a = get_app();
1020
1021         $page_theme = null;
1022
1023         // Find the theme that belongs to the user whose stuff we are looking at
1024
1025         if ($a->profile_uid && ($a->profile_uid != local_user())) {
1026                 $r = q(
1027                         "select theme from user where uid = %d limit 1",
1028                         intval($a->profile_uid)
1029                 );
1030                 if (DBM::is_result($r)) {
1031                         $page_theme = $r[0]['theme'];
1032                 }
1033         }
1034
1035         // Allow folks to over-rule user themes and always use their own on their own site.
1036         // This works only if the user is on the same server
1037
1038         if ($page_theme && local_user() && (local_user() != $a->profile_uid)) {
1039                 if (PConfig::get(local_user(), 'system', 'always_my_theme')) {
1040                         $page_theme = null;
1041                 }
1042         }
1043
1044 //              $mobile_detect = new Mobile_Detect();
1045 //              $is_mobile = $mobile_detect->isMobile() || $mobile_detect->isTablet();
1046         $is_mobile = $a->is_mobile || $a->is_tablet;
1047
1048         $standard_system_theme = Config::get('system', 'theme', '');
1049         $standard_theme_name = ((isset($_SESSION) && x($_SESSION, 'theme')) ? $_SESSION['theme'] : $standard_system_theme);
1050
1051         if ($is_mobile) {
1052                 if (isset($_SESSION['show-mobile']) && !$_SESSION['show-mobile']) {
1053                         $theme_name = $standard_theme_name;
1054                 } else {
1055                         $system_theme = Config::get('system', 'mobile-theme', '');
1056                         if ($system_theme == '') {
1057                                 $system_theme = $standard_system_theme;
1058                         }
1059                         $theme_name = ((isset($_SESSION) && x($_SESSION, 'mobile-theme')) ? $_SESSION['mobile-theme'] : $system_theme);
1060
1061                         if ($theme_name === '---') {
1062                                 // user has selected to have the mobile theme be the same as the normal one
1063                                 $theme_name = $standard_theme_name;
1064
1065                                 if ($page_theme) {
1066                                         $theme_name = $page_theme;
1067                                 }
1068                         }
1069                 }
1070         } else {
1071                 $theme_name = $standard_theme_name;
1072
1073                 if ($page_theme) {
1074                         $theme_name = $page_theme;
1075                 }
1076         }
1077
1078         if ($theme_name
1079                 && (file_exists('view/theme/' . $theme_name . '/style.css')
1080                 || file_exists('view/theme/' . $theme_name . '/style.php'))
1081         ) {
1082                 return($theme_name);
1083         }
1084
1085         foreach ($app_base_themes as $t) {
1086                 if (file_exists('view/theme/' . $t . '/style.css')
1087                         || file_exists('view/theme/' . $t . '/style.php')
1088                 ) {
1089                         return($t);
1090                 }
1091         }
1092
1093         $fallback = array_merge(glob('view/theme/*/style.css'), glob('view/theme/*/style.php'));
1094         if (count($fallback)) {
1095                 return (str_replace('view/theme/', '', substr($fallback[0], 0, -10)));
1096         }
1097
1098         /// @TODO No final return statement?
1099 }
1100
1101 /**
1102  * @brief Return full URL to theme which is currently in effect.
1103  *
1104  * Provide a sane default if nothing is chosen or the specified theme does not exist.
1105  *
1106  * @return string
1107  */
1108 function current_theme_url()
1109 {
1110         $a = get_app();
1111
1112         $t = current_theme();
1113
1114         $opts = (($a->profile_uid) ? '?f=&puid=' . $a->profile_uid : '');
1115         if (file_exists('view/theme/' . $t . '/style.php')) {
1116                 return('view/theme/' . $t . '/style.pcss' . $opts);
1117         }
1118
1119         return('view/theme/' . $t . '/style.css');
1120 }
1121
1122 function feed_birthday($uid, $tz)
1123 {
1124         /**
1125          * Determine the next birthday, but only if the birthday is published
1126          * in the default profile. We _could_ also look for a private profile that the
1127          * recipient can see, but somebody could get mad at us if they start getting
1128          * public birthday greetings when they haven't made this info public.
1129          *
1130          * Assuming we are able to publish this info, we are then going to convert
1131          * the start time from the owner's timezone to UTC.
1132          *
1133          * This will potentially solve the problem found with some social networks
1134          * where birthdays are converted to the viewer's timezone and salutations from
1135          * elsewhere in the world show up on the wrong day. We will convert it to the
1136          * viewer's timezone also, but first we are going to convert it from the birthday
1137          * person's timezone to GMT - so the viewer may find the birthday starting at
1138          * 6:00PM the day before, but that will correspond to midnight to the birthday person.
1139          */
1140         $birthday = '';
1141
1142         if (!strlen($tz)) {
1143                 $tz = 'UTC';
1144         }
1145
1146         $p = q(
1147                 "SELECT `dob` FROM `profile` WHERE `is-default` = 1 AND `uid` = %d LIMIT 1",
1148                 intval($uid)
1149         );
1150
1151         if (DBM::is_result($p)) {
1152                 $tmp_dob = substr($p[0]['dob'], 5);
1153                 if (intval($tmp_dob)) {
1154                         $y = DateTimeFormat::timezoneNow($tz, 'Y');
1155                         $bd = $y . '-' . $tmp_dob . ' 00:00';
1156                         $t_dob = strtotime($bd);
1157                         $now = strtotime(DateTimeFormat::timezoneNow($tz));
1158                         if ($t_dob < $now) {
1159                                 $bd = $y + 1 . '-' . $tmp_dob . ' 00:00';
1160                         }
1161                         $birthday = DateTimeFormat::convert($bd, 'UTC', $tz, DateTimeFormat::ATOM);
1162                 }
1163         }
1164
1165         return $birthday;
1166 }
1167
1168 /**
1169  * @brief Check if current user has admin role.
1170  *
1171  * @return bool true if user is an admin
1172  */
1173 function is_site_admin()
1174 {
1175         $a = get_app();
1176
1177         $adminlist = explode(",", str_replace(" ", "", $a->config['admin_email']));
1178
1179         //if(local_user() && x($a->user,'email') && x($a->config,'admin_email') && ($a->user['email'] === $a->config['admin_email']))
1180         if (local_user() && x($a->user, 'email') && x($a->config, 'admin_email') && in_array($a->user['email'], $adminlist)) {
1181                 return true;
1182         }
1183         return false;
1184 }
1185
1186 /**
1187  * @brief Returns querystring as string from a mapped array.
1188  *
1189  * @param array  $params mapped array with query parameters
1190  * @param string $name   of parameter, default null
1191  *
1192  * @return string
1193  */
1194 function build_querystring($params, $name = null)
1195 {
1196         $ret = "";
1197         foreach ($params as $key => $val) {
1198                 if (is_array($val)) {
1199                         /// @TODO maybe not compare against null, use is_null()
1200                         if ($name == null) {
1201                                 $ret .= build_querystring($val, $key);
1202                         } else {
1203                                 $ret .= build_querystring($val, $name . "[$key]");
1204                         }
1205                 } else {
1206                         $val = urlencode($val);
1207                         /// @TODO maybe not compare against null, use is_null()
1208                         if ($name != null) {
1209                                 /// @TODO two string concated, can be merged to one
1210                                 $ret .= $name . "[$key]" . "=$val&";
1211                         } else {
1212                                 $ret .= "$key=$val&";
1213                         }
1214                 }
1215         }
1216         return $ret;
1217 }
1218
1219 function explode_querystring($query)
1220 {
1221         $arg_st = strpos($query, '?');
1222         if ($arg_st !== false) {
1223                 $base = substr($query, 0, $arg_st);
1224                 $arg_st += 1;
1225         } else {
1226                 $base = '';
1227                 $arg_st = 0;
1228         }
1229
1230         $args = explode('&', substr($query, $arg_st));
1231         foreach ($args as $k => $arg) {
1232                 /// @TODO really compare type-safe here?
1233                 if ($arg === '') {
1234                         unset($args[$k]);
1235                 }
1236         }
1237         $args = array_values($args);
1238
1239         if (!$base) {
1240                 $base = $args[0];
1241                 unset($args[0]);
1242                 $args = array_values($args);
1243         }
1244
1245         return [
1246                 'base' => $base,
1247                 'args' => $args,
1248         ];
1249 }
1250
1251 /**
1252  * Returns the complete URL of the current page, e.g.: http(s)://something.com/network
1253  *
1254  * Taken from http://webcheatsheet.com/php/get_current_page_url.php
1255  */
1256 function curPageURL()
1257 {
1258         $pageURL = 'http';
1259         if ($_SERVER["HTTPS"] == "on") {
1260                 $pageURL .= "s";
1261         }
1262
1263         $pageURL .= "://";
1264
1265         if ($_SERVER["SERVER_PORT"] != "80" && $_SERVER["SERVER_PORT"] != "443") {
1266                 $pageURL .= $_SERVER["SERVER_NAME"] . ":" . $_SERVER["SERVER_PORT"] . $_SERVER["REQUEST_URI"];
1267         } else {
1268                 $pageURL .= $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"];
1269         }
1270         return $pageURL;
1271 }
1272
1273 function random_digits($digits)
1274 {
1275         $rn = '';
1276         for ($i = 0; $i < $digits; $i++) {
1277                 /// @TODO rand() is different to mt_rand() and maybe lesser "random"
1278                 $rn .= rand(0, 9);
1279         }
1280         return $rn;
1281 }
1282
1283 function get_server()
1284 {
1285         $server = Config::get("system", "directory");
1286
1287         if ($server == "") {
1288                 $server = "http://dir.friendica.social";
1289         }
1290
1291         return($server);
1292 }
1293
1294 function get_temppath()
1295 {
1296         $a = get_app();
1297
1298         $temppath = Config::get("system", "temppath");
1299
1300         if (($temppath != "") && App::directory_usable($temppath)) {
1301                 // We have a temp path and it is usable
1302                 return App::realpath($temppath);
1303         }
1304
1305         // We don't have a working preconfigured temp path, so we take the system path.
1306         $temppath = sys_get_temp_dir();
1307
1308         // Check if it is usable
1309         if (($temppath != "") && App::directory_usable($temppath)) {
1310                 // Always store the real path, not the path through symlinks
1311                 $temppath = App::realpath($temppath);
1312
1313                 // To avoid any interferences with other systems we create our own directory
1314                 $new_temppath = $temppath . "/" . $a->get_hostname();
1315                 if (!is_dir($new_temppath)) {
1316                         /// @TODO There is a mkdir()+chmod() upwards, maybe generalize this (+ configurable) into a function/method?
1317                         mkdir($new_temppath);
1318                 }
1319
1320                 if (App::directory_usable($new_temppath)) {
1321                         // The new path is usable, we are happy
1322                         Config::set("system", "temppath", $new_temppath);
1323                         return $new_temppath;
1324                 } else {
1325                         // We can't create a subdirectory, strange.
1326                         // But the directory seems to work, so we use it but don't store it.
1327                         return $temppath;
1328                 }
1329         }
1330
1331         // Reaching this point means that the operating system is configured badly.
1332         return '';
1333 }
1334
1335 function get_cachefile($file, $writemode = true)
1336 {
1337         $cache = get_itemcachepath();
1338
1339         if ((!$cache) || (!is_dir($cache))) {
1340                 return("");
1341         }
1342
1343         $subfolder = $cache . "/" . substr($file, 0, 2);
1344
1345         $cachepath = $subfolder . "/" . $file;
1346
1347         if ($writemode) {
1348                 if (!is_dir($subfolder)) {
1349                         mkdir($subfolder);
1350                         chmod($subfolder, 0777);
1351                 }
1352         }
1353
1354         /// @TODO no need to put braces here
1355         return $cachepath;
1356 }
1357
1358 function clear_cache($basepath = "", $path = "")
1359 {
1360         if ($path == "") {
1361                 $basepath = get_itemcachepath();
1362                 $path = $basepath;
1363         }
1364
1365         if (($path == "") || (!is_dir($path))) {
1366                 return;
1367         }
1368
1369         if (substr(realpath($path), 0, strlen($basepath)) != $basepath) {
1370                 return;
1371         }
1372
1373         $cachetime = (int) Config::get('system', 'itemcache_duration');
1374         if ($cachetime == 0) {
1375                 $cachetime = 86400;
1376         }
1377
1378         if (is_writable($path)) {
1379                 if ($dh = opendir($path)) {
1380                         while (($file = readdir($dh)) !== false) {
1381                                 $fullpath = $path . "/" . $file;
1382                                 if ((filetype($fullpath) == "dir") && ($file != ".") && ($file != "..")) {
1383                                         clear_cache($basepath, $fullpath);
1384                                 }
1385                                 if ((filetype($fullpath) == "file") && (filectime($fullpath) < (time() - $cachetime))) {
1386                                         unlink($fullpath);
1387                                 }
1388                         }
1389                         closedir($dh);
1390                 }
1391         }
1392 }
1393
1394 function get_itemcachepath()
1395 {
1396         // Checking, if the cache is deactivated
1397         $cachetime = (int) Config::get('system', 'itemcache_duration');
1398         if ($cachetime < 0) {
1399                 return "";
1400         }
1401
1402         $itemcache = Config::get('system', 'itemcache');
1403         if (($itemcache != "") && App::directory_usable($itemcache)) {
1404                 return App::realpath($itemcache);
1405         }
1406
1407         $temppath = get_temppath();
1408
1409         if ($temppath != "") {
1410                 $itemcache = $temppath . "/itemcache";
1411                 if (!file_exists($itemcache) && !is_dir($itemcache)) {
1412                         mkdir($itemcache);
1413                 }
1414
1415                 if (App::directory_usable($itemcache)) {
1416                         Config::set("system", "itemcache", $itemcache);
1417                         return $itemcache;
1418                 }
1419         }
1420         return "";
1421 }
1422
1423 /**
1424  * @brief Returns the path where spool files are stored
1425  *
1426  * @return string Spool path
1427  */
1428 function get_spoolpath()
1429 {
1430         $spoolpath = Config::get('system', 'spoolpath');
1431         if (($spoolpath != "") && App::directory_usable($spoolpath)) {
1432                 // We have a spool path and it is usable
1433                 return $spoolpath;
1434         }
1435
1436         // We don't have a working preconfigured spool path, so we take the temp path.
1437         $temppath = get_temppath();
1438
1439         if ($temppath != "") {
1440                 // To avoid any interferences with other systems we create our own directory
1441                 $spoolpath = $temppath . "/spool";
1442                 if (!is_dir($spoolpath)) {
1443                         mkdir($spoolpath);
1444                 }
1445
1446                 if (App::directory_usable($spoolpath)) {
1447                         // The new path is usable, we are happy
1448                         Config::set("system", "spoolpath", $spoolpath);
1449                         return $spoolpath;
1450                 } else {
1451                         // We can't create a subdirectory, strange.
1452                         // But the directory seems to work, so we use it but don't store it.
1453                         return $temppath;
1454                 }
1455         }
1456
1457         // Reaching this point means that the operating system is configured badly.
1458         return "";
1459 }
1460
1461
1462 if (!function_exists('exif_imagetype')) {
1463         function exif_imagetype($file)
1464         {
1465                 $size = getimagesize($file);
1466                 return $size[2];
1467         }
1468 }
1469
1470 function validate_include(&$file)
1471 {
1472         $orig_file = $file;
1473
1474         $file = realpath($file);
1475
1476         if (strpos($file, getcwd()) !== 0) {
1477                 return false;
1478         }
1479
1480         $file = str_replace(getcwd() . "/", "", $file, $count);
1481         if ($count != 1) {
1482                 return false;
1483         }
1484
1485         if ($orig_file !== $file) {
1486                 return false;
1487         }
1488
1489         $valid = false;
1490         if (strpos($file, "include/") === 0) {
1491                 $valid = true;
1492         }
1493
1494         if (strpos($file, "addon/") === 0) {
1495                 $valid = true;
1496         }
1497
1498         // Simply return flag
1499         return ($valid);
1500 }
1501
1502 function current_load()
1503 {
1504         if (!function_exists('sys_getloadavg')) {
1505                 return false;
1506         }
1507
1508         $load_arr = sys_getloadavg();
1509
1510         if (!is_array($load_arr)) {
1511                 return false;
1512         }
1513
1514         return max($load_arr[0], $load_arr[1]);
1515 }
1516
1517 /**
1518  * @brief get c-style args
1519  *
1520  * @return int
1521  */
1522 function argc()
1523 {
1524         return get_app()->argc;
1525 }
1526
1527 /**
1528  * @brief Returns the value of a argv key
1529  *
1530  * @param int $x argv key
1531  * @return string Value of the argv key
1532  */
1533 function argv($x)
1534 {
1535         if (array_key_exists($x, get_app()->argv)) {
1536                 return get_app()->argv[$x];
1537         }
1538
1539         return '';
1540 }
1541
1542 /**
1543  * @brief Get the data which is needed for infinite scroll
1544  *
1545  * For invinite scroll we need the page number of the actual page
1546  * and the the URI where the content of the next page comes from.
1547  * This data is needed for the js part in main.js.
1548  * Note: infinite scroll does only work for the network page (module)
1549  *
1550  * @param string $module The name of the module (e.g. "network")
1551  * @return array Of infinite scroll data
1552  *      'pageno' => $pageno The number of the actual page
1553  *      'reload_uri' => $reload_uri The URI of the content we have to load
1554  */
1555 function infinite_scroll_data($module)
1556 {
1557         if (PConfig::get(local_user(), 'system', 'infinite_scroll')
1558                 && $module == 'network'
1559                 && defaults($_GET, 'mode', '') != 'minimal'
1560         ) {
1561                 // get the page number
1562                 $pageno = defaults($_GET, 'page', 1);
1563
1564                 $reload_uri = "";
1565
1566                 // try to get the uri from which we load the content
1567                 foreach ($_GET as $param => $value) {
1568                         if (($param != "page") && ($param != "q")) {
1569                                 $reload_uri .= "&" . $param . "=" . urlencode($value);
1570                         }
1571                 }
1572
1573                 $a = get_app();
1574                 if ($a->page_offset != "" && !strstr($reload_uri, "&offset=")) {
1575                         $reload_uri .= "&offset=" . urlencode($a->page_offset);
1576                 }
1577
1578                 $arr = ["pageno" => $pageno, "reload_uri" => $reload_uri];
1579
1580                 return $arr;
1581         }
1582 }