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