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