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