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