]> git.mxchange.org Git - friendica.git/blob - boot.php
Merge pull request #5998 from annando/ap-queue
[friendica.git] / boot.php
1 <?php
2 /**
3  * @file boot.php
4  * This file defines some global constants and includes the central App class.
5  */
6
7 /**
8  * Friendica
9  *
10  * Friendica is a communications platform for integrated social communications
11  * utilising decentralised communications and linkage to several indie social
12  * projects - as well as popular mainstream providers.
13  *
14  * Our mission is to free our friends and families from the clutches of
15  * data-harvesting corporations, and pave the way to a future where social
16  * communications are free and open and flow between alternate providers as
17  * easily as email does today.
18  */
19
20 require_once __DIR__ . DIRECTORY_SEPARATOR . 'vendor' . DIRECTORY_SEPARATOR . 'autoload.php';
21
22 use Friendica\App;
23 use Friendica\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.12-dev');
43 define('DFRN_PROTOCOL_VERSION',  '2.23');
44 define('NEW_UPDATE_ROUTINE_VERSION', 1170);
45
46 /**
47  * @brief Constants for the database update check
48  */
49 const DB_UPDATE_NOT_CHECKED = 0; // Database check wasn't executed before
50 const DB_UPDATE_SUCCESSFUL = 1;  // Database check was successful
51 const DB_UPDATE_FAILED = 2;      // Database check failed
52
53 /**
54  * @brief Constant with a HTML line break.
55  *
56  * Contains a HTML line break (br) element and a real carriage return with line
57  * feed for the source.
58  * This can be used in HTML and JavaScript where needed a line break.
59  */
60 define('EOL',                    "<br />\r\n");
61
62 /**
63  * @brief Image storage quality.
64  *
65  * Lower numbers save space at cost of image detail.
66  * For ease of upgrade, please do not change here. Set [system] jpegquality = n in config/local.ini.php,
67  * where n is between 1 and 100, and with very poor results below about 50
68  */
69 define('JPEG_QUALITY',            100);
70
71 /**
72  * [system] png_quality = n where is between 0 (uncompressed) to 9
73  */
74 define('PNG_QUALITY',             8);
75
76 /**
77  * An alternate way of limiting picture upload sizes. Specify the maximum pixel
78  * length that pictures are allowed to be (for non-square pictures, it will apply
79  * to the longest side). Pictures longer than this length will be resized to be
80  * this length (on the longest side, the other side will be scaled appropriately).
81  * Modify this value using
82  *
83  * [system]
84  * max_image_length = n;
85  *
86  * in config/local.ini.php
87  *
88  * If you don't want to set a maximum length, set to -1. The default value is
89  * defined by 'MAX_IMAGE_LENGTH' below.
90  */
91 define('MAX_IMAGE_LENGTH',        -1);
92
93 /**
94  * Not yet used
95  */
96 define('DEFAULT_DB_ENGINE',  'InnoDB');
97
98 /**
99  * @name SSL Policy
100  *
101  * SSL redirection policies
102  * @{
103  */
104 define('SSL_POLICY_NONE',         0);
105 define('SSL_POLICY_FULL',         1);
106 define('SSL_POLICY_SELFSIGN',     2);
107 /* @}*/
108
109 /**
110  * @name Logger
111  *
112  * log levels
113  * @{
114  */
115 define('LOGGER_WARNING',         0);
116 define('LOGGER_INFO',            1);
117 define('LOGGER_TRACE',           2);
118 define('LOGGER_DEBUG',           3);
119 define('LOGGER_DATA',            4);
120 define('LOGGER_ALL',             5);
121 /* @}*/
122
123 /**
124  * @name Register
125  *
126  * Registration policies
127  * @{
128  */
129 define('REGISTER_CLOSED',        0);
130 define('REGISTER_APPROVE',       1);
131 define('REGISTER_OPEN',          2);
132 /**
133  * @}
134 */
135
136 /**
137  * @name Update
138  *
139  * DB update return values
140  * @{
141  */
142 define('UPDATE_SUCCESS', 0);
143 define('UPDATE_FAILED',  1);
144 /**
145  * @}
146  */
147
148 /**
149  * @name CP
150  *
151  * Type of the community page
152  * @{
153  */
154 define('CP_NO_INTERNAL_COMMUNITY', -2);
155 define('CP_NO_COMMUNITY_PAGE',     -1);
156 define('CP_USERS_ON_SERVER',        0);
157 define('CP_GLOBAL_COMMUNITY',       1);
158 define('CP_USERS_AND_GLOBAL',       2);
159 /**
160  * @}
161  */
162
163 /**
164  * These numbers are used in stored permissions
165  * and existing allocations MUST NEVER BE CHANGED
166  * OR RE-ASSIGNED! You may only add to them.
167  */
168 $netgroup_ids = [
169         Protocol::DFRN     => (-1),
170         Protocol::ZOT      => (-2),
171         Protocol::OSTATUS  => (-3),
172         Protocol::FEED     => (-4),
173         Protocol::DIASPORA => (-5),
174         Protocol::MAIL     => (-6),
175         Protocol::FACEBOOK => (-8),
176         Protocol::LINKEDIN => (-9),
177         Protocol::XMPP     => (-10),
178         Protocol::MYSPACE  => (-11),
179         Protocol::GPLUS    => (-12),
180         Protocol::PUMPIO   => (-13),
181         Protocol::TWITTER  => (-14),
182         Protocol::DIASPORA2 => (-15),
183         Protocol::STATUSNET => (-16),
184         Protocol::NEWS      => (-18),
185         Protocol::ICALENDAR => (-19),
186         Protocol::PNUT      => (-20),
187
188         Protocol::PHANTOM  => (-127),
189 ];
190
191 /**
192  * Maximum number of "people who like (or don't like) this"  that we will list by name
193  */
194 define('MAX_LIKERS',    75);
195
196 /**
197  * @name Notify
198  *
199  * Email notification options
200  * @{
201  */
202 define('NOTIFY_INTRO',    0x0001);
203 define('NOTIFY_CONFIRM',  0x0002);
204 define('NOTIFY_WALL',     0x0004);
205 define('NOTIFY_COMMENT',  0x0008);
206 define('NOTIFY_MAIL',     0x0010);
207 define('NOTIFY_SUGGEST',  0x0020);
208 define('NOTIFY_PROFILE',  0x0040);
209 define('NOTIFY_TAGSELF',  0x0080);
210 define('NOTIFY_TAGSHARE', 0x0100);
211 define('NOTIFY_POKE',     0x0200);
212 define('NOTIFY_SHARE',    0x0400);
213
214 define('SYSTEM_EMAIL',    0x4000);
215
216 define('NOTIFY_SYSTEM',   0x8000);
217 /* @}*/
218
219
220 /**
221  * @name Term
222  *
223  * Tag/term types
224  * @{
225  */
226 define('TERM_UNKNOWN',   0);
227 define('TERM_HASHTAG',   1);
228 define('TERM_MENTION',   2);
229 define('TERM_CATEGORY',  3);
230 define('TERM_PCATEGORY', 4);
231 define('TERM_FILE',      5);
232 define('TERM_SAVEDSEARCH', 6);
233 define('TERM_CONVERSATION', 7);
234
235 define('TERM_OBJ_POST',  1);
236 define('TERM_OBJ_PHOTO', 2);
237
238 /**
239  * @name Namespaces
240  *
241  * Various namespaces we may need to parse
242  * @{
243  */
244 define('NAMESPACE_ZOT',             'http://purl.org/zot');
245 define('NAMESPACE_DFRN',            'http://purl.org/macgirvin/dfrn/1.0');
246 define('NAMESPACE_THREAD',          'http://purl.org/syndication/thread/1.0');
247 define('NAMESPACE_TOMB',            'http://purl.org/atompub/tombstones/1.0');
248 define('NAMESPACE_ACTIVITY',        'http://activitystrea.ms/spec/1.0/');
249 define('NAMESPACE_ACTIVITY_SCHEMA', 'http://activitystrea.ms/schema/1.0/');
250 define('NAMESPACE_MEDIA',           'http://purl.org/syndication/atommedia');
251 define('NAMESPACE_SALMON_ME',       'http://salmon-protocol.org/ns/magic-env');
252 define('NAMESPACE_OSTATUSSUB',      'http://ostatus.org/schema/1.0/subscribe');
253 define('NAMESPACE_GEORSS',          'http://www.georss.org/georss');
254 define('NAMESPACE_POCO',            'http://portablecontacts.net/spec/1.0');
255 define('NAMESPACE_FEED',            'http://schemas.google.com/g/2010#updates-from');
256 define('NAMESPACE_OSTATUS',         'http://ostatus.org/schema/1.0');
257 define('NAMESPACE_STATUSNET',       'http://status.net/schema/api/1/');
258 define('NAMESPACE_ATOM1',           'http://www.w3.org/2005/Atom');
259 define('NAMESPACE_MASTODON',        'http://mastodon.social/schema/1.0');
260 /* @}*/
261
262 /**
263  * @name Activity
264  *
265  * Activity stream defines
266  * @{
267  */
268 define('ACTIVITY_LIKE',        NAMESPACE_ACTIVITY_SCHEMA . 'like');
269 define('ACTIVITY_DISLIKE',     NAMESPACE_DFRN            . '/dislike');
270 define('ACTIVITY_ATTEND',      NAMESPACE_ZOT             . '/activity/attendyes');
271 define('ACTIVITY_ATTENDNO',    NAMESPACE_ZOT             . '/activity/attendno');
272 define('ACTIVITY_ATTENDMAYBE', NAMESPACE_ZOT             . '/activity/attendmaybe');
273
274 define('ACTIVITY_OBJ_HEART',   NAMESPACE_DFRN            . '/heart');
275
276 define('ACTIVITY_FRIEND',      NAMESPACE_ACTIVITY_SCHEMA . 'make-friend');
277 define('ACTIVITY_REQ_FRIEND',  NAMESPACE_ACTIVITY_SCHEMA . 'request-friend');
278 define('ACTIVITY_UNFRIEND',    NAMESPACE_ACTIVITY_SCHEMA . 'remove-friend');
279 define('ACTIVITY_FOLLOW',      NAMESPACE_ACTIVITY_SCHEMA . 'follow');
280 define('ACTIVITY_UNFOLLOW',    NAMESPACE_ACTIVITY_SCHEMA . 'stop-following');
281 define('ACTIVITY_JOIN',        NAMESPACE_ACTIVITY_SCHEMA . 'join');
282
283 define('ACTIVITY_POST',        NAMESPACE_ACTIVITY_SCHEMA . 'post');
284 define('ACTIVITY_UPDATE',      NAMESPACE_ACTIVITY_SCHEMA . 'update');
285 define('ACTIVITY_TAG',         NAMESPACE_ACTIVITY_SCHEMA . 'tag');
286 define('ACTIVITY_FAVORITE',    NAMESPACE_ACTIVITY_SCHEMA . 'favorite');
287 define('ACTIVITY_UNFAVORITE',  NAMESPACE_ACTIVITY_SCHEMA . 'unfavorite');
288 define('ACTIVITY_SHARE',       NAMESPACE_ACTIVITY_SCHEMA . 'share');
289 define('ACTIVITY_DELETE',      NAMESPACE_ACTIVITY_SCHEMA . 'delete');
290
291 define('ACTIVITY_POKE',        NAMESPACE_ZOT . '/activity/poke');
292
293 define('ACTIVITY_OBJ_BOOKMARK', NAMESPACE_ACTIVITY_SCHEMA . 'bookmark');
294 define('ACTIVITY_OBJ_COMMENT', NAMESPACE_ACTIVITY_SCHEMA . 'comment');
295 define('ACTIVITY_OBJ_NOTE',    NAMESPACE_ACTIVITY_SCHEMA . 'note');
296 define('ACTIVITY_OBJ_PERSON',  NAMESPACE_ACTIVITY_SCHEMA . 'person');
297 define('ACTIVITY_OBJ_IMAGE',   NAMESPACE_ACTIVITY_SCHEMA . 'image');
298 define('ACTIVITY_OBJ_PHOTO',   NAMESPACE_ACTIVITY_SCHEMA . 'photo');
299 define('ACTIVITY_OBJ_VIDEO',   NAMESPACE_ACTIVITY_SCHEMA . 'video');
300 define('ACTIVITY_OBJ_P_PHOTO', NAMESPACE_ACTIVITY_SCHEMA . 'profile-photo');
301 define('ACTIVITY_OBJ_ALBUM',   NAMESPACE_ACTIVITY_SCHEMA . 'photo-album');
302 define('ACTIVITY_OBJ_EVENT',   NAMESPACE_ACTIVITY_SCHEMA . 'event');
303 define('ACTIVITY_OBJ_GROUP',   NAMESPACE_ACTIVITY_SCHEMA . 'group');
304 define('ACTIVITY_OBJ_TAGTERM', NAMESPACE_DFRN            . '/tagterm');
305 define('ACTIVITY_OBJ_PROFILE', NAMESPACE_DFRN            . '/profile');
306 define('ACTIVITY_OBJ_QUESTION', 'http://activityschema.org/object/question');
307 /* @}*/
308
309 /**
310  * @name Gravity
311  *
312  * Item weight for query ordering
313  * @{
314  */
315 define('GRAVITY_PARENT',       0);
316 define('GRAVITY_ACTIVITY',     3);
317 define('GRAVITY_COMMENT',      6);
318 define('GRAVITY_UNKNOWN',      9);
319 /* @}*/
320
321 /**
322  * @name Priority
323  *
324  * Process priority for the worker
325  * @{
326  */
327 define('PRIORITY_UNDEFINED',   0);
328 define('PRIORITY_CRITICAL',   10);
329 define('PRIORITY_HIGH',       20);
330 define('PRIORITY_MEDIUM',     30);
331 define('PRIORITY_LOW',        40);
332 define('PRIORITY_NEGLIGIBLE', 50);
333 /* @}*/
334
335 /**
336  * @name Social Relay settings
337  *
338  * See here: https://github.com/jaywink/social-relay
339  * and here: https://wiki.diasporafoundation.org/Relay_servers_for_public_posts
340  * @{
341  */
342 define('SR_SCOPE_NONE', '');
343 define('SR_SCOPE_ALL',  'all');
344 define('SR_SCOPE_TAGS', 'tags');
345 /* @}*/
346
347 // Normally this constant is defined - but not if "pcntl" isn't installed
348 if (!defined("SIGTERM")) {
349         define("SIGTERM", 15);
350 }
351
352 /**
353  * Depending on the PHP version this constant does exist - or not.
354  * See here: http://php.net/manual/en/curl.constants.php#117928
355  */
356 if (!defined('CURLE_OPERATION_TIMEDOUT')) {
357         define('CURLE_OPERATION_TIMEDOUT', CURLE_OPERATION_TIMEOUTED);
358 }
359
360 /**
361  * @brief Retrieve the App structure
362  *
363  * Useful in functions which require it but don't get it passed to them
364  *
365  * @return App
366  */
367 function get_app()
368 {
369         return BaseObject::getApp();
370 }
371
372 /**
373  * @brief Multi-purpose function to check variable state.
374  *
375  * Usage: x($var) or $x($array, 'key')
376  *
377  * returns false if variable/key is not set
378  * if variable is set, returns 1 if has 'non-zero' value, otherwise returns 0.
379  * e.g. x('') or x(0) returns 0;
380  *
381  * @param string|array $s variable to check
382  * @param string       $k key inside the array to check
383  *
384  * @return bool|int
385  */
386 function x($s, $k = null)
387 {
388         if ($k != null) {
389                 if ((is_array($s)) && (array_key_exists($k, $s))) {
390                         if ($s[$k]) {
391                                 return (int) 1;
392                         }
393                         return (int) 0;
394                 }
395                 return false;
396         } else {
397                 if (isset($s)) {
398                         if ($s) {
399                                 return (int) 1;
400                         }
401                         return (int) 0;
402                 }
403                 return false;
404         }
405 }
406
407 /**
408  * Return the provided variable value if it exists and is truthy or the provided
409  * default value instead.
410  *
411  * Works with initialized variables and potentially uninitialized array keys
412  *
413  * Usages:
414  * - defaults($var, $default)
415  * - defaults($array, 'key', $default)
416  *
417  * @brief Returns a defaut value if the provided variable or array key is falsy
418  * @see x()
419  * @return mixed
420  */
421 function defaults() {
422         $args = func_get_args();
423
424         if (count($args) < 2) {
425                 throw new BadFunctionCallException('defaults() requires at least 2 parameters');
426         }
427         if (count($args) > 3) {
428                 throw new BadFunctionCallException('defaults() cannot use more than 3 parameters');
429         }
430         if (count($args) === 3 && is_null($args[1])) {
431                 throw new BadFunctionCallException('defaults($arr, $key, $def) $key is null');
432         }
433
434         $default = array_pop($args);
435
436         if (call_user_func_array('x', $args)) {
437                 if (count($args) === 1) {
438                         $return = $args[0];
439                 } else {
440                         $return = $args[0][$args[1]];
441                 }
442         } else {
443                 $return = $default;
444         }
445
446         return $return;
447 }
448
449 /**
450  * @brief Function to check if request was an AJAX (xmlhttprequest) request.
451  *
452  * @param boolean $via_worker boolean Is the check run via the worker?
453  */
454 function check_db($via_worker)
455 {
456         $build = Config::get('system', 'build');
457
458         if (empty($build)) {
459                 Config::set('system', 'build', DB_UPDATE_VERSION - 1);
460                 $build = DB_UPDATE_VERSION - 1;
461         }
462
463         // We don't support upgrading from very old versions anymore
464         if ($build < NEW_UPDATE_ROUTINE_VERSION) {
465                 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.');
466         }
467
468         if ($build < DB_UPDATE_VERSION) {
469                 // When we cannot execute the database update via the worker, we will do it directly
470                 if (!Worker::add(PRIORITY_CRITICAL, 'DBUpdate') && $via_worker) {
471                         update_db();
472                 }
473         }
474 }
475
476 /**
477  * @brief Automatic database updates
478  * @param object $a App
479  */
480 function update_db()
481 {
482         $build = Config::get('system', 'build');
483
484         if (empty($build) || ($build > DB_UPDATE_VERSION)) {
485                 $build = DB_UPDATE_VERSION - 1;
486                 Config::set('system', 'build', $build);
487         }
488
489         if ($build != DB_UPDATE_VERSION) {
490                 require_once 'update.php';
491
492                 $stored = intval($build);
493                 $current = intval(DB_UPDATE_VERSION);
494                 if ($stored < $current) {
495                         Config::load('database');
496
497                         // Compare the current structure with the defined structure
498                         $t = Config::get('database', 'dbupdate_' . DB_UPDATE_VERSION);
499                         if (!is_null($t)) {
500                                 return;
501                         }
502
503                         // run the pre_update_nnnn functions in update.php
504                         for ($x = $stored + 1; $x <= $current; $x++) {
505                                 $r = run_update_function($x, 'pre_update');
506                                 if (!$r) {
507                                         break;
508                                 }
509                         }
510
511                         Config::set('database', 'dbupdate_' . DB_UPDATE_VERSION, time());
512
513                         // update the structure in one call
514                         $retval = DBStructure::update(false, true);
515                         if ($retval) {
516                                 DBStructure::updateFail(
517                                         DB_UPDATE_VERSION,
518                                         $retval
519                                 );
520                                 return;
521                         } else {
522                                 Config::set('database', 'dbupdate_' . DB_UPDATE_VERSION, 'success');
523                         }
524
525                         // run the update_nnnn functions in update.php
526                         for ($x = $stored + 1; $x <= $current; $x++) {
527                                 $r = run_update_function($x, 'update');
528                                 if (!$r) {
529                                         break;
530                                 }
531                         }
532                 }
533         }
534
535         return;
536 }
537
538 function run_update_function($x, $prefix)
539 {
540         $funcname = $prefix . '_' . $x;
541
542         if (function_exists($funcname)) {
543                 // There could be a lot of processes running or about to run.
544                 // We want exactly one process to run the update command.
545                 // So store the fact that we're taking responsibility
546                 // after first checking to see if somebody else already has.
547                 // If the update fails or times-out completely you may need to
548                 // delete the config entry to try again.
549
550                 $t = Config::get('database', $funcname);
551                 if (!is_null($t)) {
552                         return false;
553                 }
554                 Config::set('database', $funcname, time());
555
556                 // call the specific update
557                 $retval = $funcname();
558
559                 if ($retval) {
560                         //send the administrator an e-mail
561                         DBStructure::updateFail(
562                                 $x,
563                                 L10n::t('Update %s failed. See error logs.', $x)
564                         );
565                         return false;
566                 } else {
567                         Config::set('database', $funcname, 'success');
568
569                         if ($prefix == 'update') {
570                                 Config::set('system', 'build', $x);
571                         }
572
573                         return true;
574                 }
575         } else {
576                 Config::set('database', $funcname, 'success');
577
578                 if ($prefix == 'update') {
579                         Config::set('system', 'build', $x);
580                 }
581
582                 return true;
583         }
584 }
585
586 /**
587  * @brief Used to end the current process, after saving session state.
588  * @deprecated
589  */
590 function killme()
591 {
592         exit();
593 }
594
595 /**
596  * @brief Returns the user id of locally logged in user or false.
597  *
598  * @return int|bool user id or false
599  */
600 function local_user()
601 {
602         if (!empty($_SESSION['authenticated']) && !empty($_SESSION['uid'])) {
603                 return intval($_SESSION['uid']);
604         }
605         return false;
606 }
607
608 /**
609  * @brief Returns the public contact id of logged in user or false.
610  *
611  * @return int|bool public contact id or false
612  */
613 function public_contact()
614 {
615         static $public_contact_id = false;
616
617         if (!$public_contact_id && x($_SESSION, 'authenticated')) {
618                 if (x($_SESSION, 'my_address')) {
619                         // Local user
620                         $public_contact_id = intval(Contact::getIdForURL($_SESSION['my_address'], 0, true));
621                 } elseif (x($_SESSION, 'visitor_home')) {
622                         // Remote user
623                         $public_contact_id = intval(Contact::getIdForURL($_SESSION['visitor_home'], 0, true));
624                 }
625         } elseif (!x($_SESSION, 'authenticated')) {
626                 $public_contact_id = false;
627         }
628
629         return $public_contact_id;
630 }
631
632 /**
633  * @brief Returns contact id of authenticated site visitor or false
634  *
635  * @return int|bool visitor_id or false
636  */
637 function remote_user()
638 {
639         // You cannot be both local and remote.
640         // Unncommented by rabuzarus because remote authentication to local
641         // profiles wasn't possible anymore (2018-04-12).
642 //      if (local_user()) {
643 //              return false;
644 //      }
645
646         if (empty($_SESSION)) {
647                 return false;
648         }
649
650         if (x($_SESSION, 'authenticated') && x($_SESSION, 'visitor_id')) {
651                 return intval($_SESSION['visitor_id']);
652         }
653         return false;
654 }
655
656 /**
657  * @brief Show an error message to user.
658  *
659  * This function save text in session, to be shown to the user at next page load
660  *
661  * @param string $s - Text of notice
662  */
663 function notice($s)
664 {
665         if (empty($_SESSION)) {
666                 return;
667         }
668
669         $a = get_app();
670         if (!x($_SESSION, 'sysmsg')) {
671                 $_SESSION['sysmsg'] = [];
672         }
673         if ($a->interactive) {
674                 $_SESSION['sysmsg'][] = $s;
675         }
676 }
677
678 /**
679  * @brief Show an info message to user.
680  *
681  * This function save text in session, to be shown to the user at next page load
682  *
683  * @param string $s - Text of notice
684  */
685 function info($s)
686 {
687         $a = get_app();
688
689         if (local_user() && PConfig::get(local_user(), 'system', 'ignore_info')) {
690                 return;
691         }
692
693         if (!x($_SESSION, 'sysmsg_info')) {
694                 $_SESSION['sysmsg_info'] = [];
695         }
696         if ($a->interactive) {
697                 $_SESSION['sysmsg_info'][] = $s;
698         }
699 }
700
701 function feed_birthday($uid, $tz)
702 {
703         /**
704          * Determine the next birthday, but only if the birthday is published
705          * in the default profile. We _could_ also look for a private profile that the
706          * recipient can see, but somebody could get mad at us if they start getting
707          * public birthday greetings when they haven't made this info public.
708          *
709          * Assuming we are able to publish this info, we are then going to convert
710          * the start time from the owner's timezone to UTC.
711          *
712          * This will potentially solve the problem found with some social networks
713          * where birthdays are converted to the viewer's timezone and salutations from
714          * elsewhere in the world show up on the wrong day. We will convert it to the
715          * viewer's timezone also, but first we are going to convert it from the birthday
716          * person's timezone to GMT - so the viewer may find the birthday starting at
717          * 6:00PM the day before, but that will correspond to midnight to the birthday person.
718          */
719         $birthday = '';
720
721         if (!strlen($tz)) {
722                 $tz = 'UTC';
723         }
724
725         $profile = DBA::selectFirst('profile', ['dob'], ['is-default' => true, 'uid' => $uid]);
726         if (DBA::isResult($profile)) {
727                 $tmp_dob = substr($profile['dob'], 5);
728                 if (intval($tmp_dob)) {
729                         $y = DateTimeFormat::timezoneNow($tz, 'Y');
730                         $bd = $y . '-' . $tmp_dob . ' 00:00';
731                         $t_dob = strtotime($bd);
732                         $now = strtotime(DateTimeFormat::timezoneNow($tz));
733                         if ($t_dob < $now) {
734                                 $bd = $y + 1 . '-' . $tmp_dob . ' 00:00';
735                         }
736                         $birthday = DateTimeFormat::convert($bd, 'UTC', $tz, DateTimeFormat::ATOM);
737                 }
738         }
739
740         return $birthday;
741 }
742
743 /**
744  * @brief Check if current user has admin role.
745  *
746  * @return bool true if user is an admin
747  */
748 function is_site_admin()
749 {
750         $a = get_app();
751
752         $admin_email = Config::get('config', 'admin_email');
753
754         $adminlist = explode(',', str_replace(' ', '', $admin_email));
755
756         return local_user() && $admin_email && in_array(defaults($a->user, 'email', ''), $adminlist);
757 }
758
759 /**
760  * @brief Returns querystring as string from a mapped array.
761  *
762  * @param array  $params mapped array with query parameters
763  * @param string $name   of parameter, default null
764  *
765  * @return string
766  */
767 function build_querystring($params, $name = null)
768 {
769         $ret = "";
770         foreach ($params as $key => $val) {
771                 if (is_array($val)) {
772                         /// @TODO maybe not compare against null, use is_null()
773                         if ($name == null) {
774                                 $ret .= build_querystring($val, $key);
775                         } else {
776                                 $ret .= build_querystring($val, $name . "[$key]");
777                         }
778                 } else {
779                         $val = urlencode($val);
780                         /// @TODO maybe not compare against null, use is_null()
781                         if ($name != null) {
782                                 /// @TODO two string concated, can be merged to one
783                                 $ret .= $name . "[$key]" . "=$val&";
784                         } else {
785                                 $ret .= "$key=$val&";
786                         }
787                 }
788         }
789         return $ret;
790 }
791
792 function explode_querystring($query)
793 {
794         $arg_st = strpos($query, '?');
795         if ($arg_st !== false) {
796                 $base = substr($query, 0, $arg_st);
797                 $arg_st += 1;
798         } else {
799                 $base = '';
800                 $arg_st = 0;
801         }
802
803         $args = explode('&', substr($query, $arg_st));
804         foreach ($args as $k => $arg) {
805                 /// @TODO really compare type-safe here?
806                 if ($arg === '') {
807                         unset($args[$k]);
808                 }
809         }
810         $args = array_values($args);
811
812         if (!$base) {
813                 $base = $args[0];
814                 unset($args[0]);
815                 $args = array_values($args);
816         }
817
818         return [
819                 'base' => $base,
820                 'args' => $args,
821         ];
822 }
823
824 /**
825  * Returns the complete URL of the current page, e.g.: http(s)://something.com/network
826  *
827  * Taken from http://webcheatsheet.com/php/get_current_page_url.php
828  */
829 function curPageURL()
830 {
831         $pageURL = 'http';
832         if (!empty($_SERVER["HTTPS"]) && ($_SERVER["HTTPS"] == "on")) {
833                 $pageURL .= "s";
834         }
835
836         $pageURL .= "://";
837
838         if ($_SERVER["SERVER_PORT"] != "80" && $_SERVER["SERVER_PORT"] != "443") {
839                 $pageURL .= $_SERVER["SERVER_NAME"] . ":" . $_SERVER["SERVER_PORT"] . $_SERVER["REQUEST_URI"];
840         } else {
841                 $pageURL .= $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"];
842         }
843         return $pageURL;
844 }
845
846 function random_digits($digits)
847 {
848         $rn = '';
849         for ($i = 0; $i < $digits; $i++) {
850                 /// @TODO Avoid rand/mt_rand, when it comes to cryptography, they are generating predictable (seedable) numbers.
851                 $rn .= rand(0, 9);
852         }
853         return $rn;
854 }
855
856 function get_server()
857 {
858         $server = Config::get("system", "directory");
859
860         if ($server == "") {
861                 $server = "https://dir.friendica.social";
862         }
863
864         return $server;
865 }
866
867 function get_temppath()
868 {
869         $a = get_app();
870
871         $temppath = Config::get("system", "temppath");
872
873         if (($temppath != "") && App::isDirectoryUsable($temppath)) {
874                 // We have a temp path and it is usable
875                 return App::getRealPath($temppath);
876         }
877
878         // We don't have a working preconfigured temp path, so we take the system path.
879         $temppath = sys_get_temp_dir();
880
881         // Check if it is usable
882         if (($temppath != "") && App::isDirectoryUsable($temppath)) {
883                 // Always store the real path, not the path through symlinks
884                 $temppath = App::getRealPath($temppath);
885
886                 // To avoid any interferences with other systems we create our own directory
887                 $new_temppath = $temppath . "/" . $a->getHostName();
888                 if (!is_dir($new_temppath)) {
889                         /// @TODO There is a mkdir()+chmod() upwards, maybe generalize this (+ configurable) into a function/method?
890                         mkdir($new_temppath);
891                 }
892
893                 if (App::isDirectoryUsable($new_temppath)) {
894                         // The new path is usable, we are happy
895                         Config::set("system", "temppath", $new_temppath);
896                         return $new_temppath;
897                 } else {
898                         // We can't create a subdirectory, strange.
899                         // But the directory seems to work, so we use it but don't store it.
900                         return $temppath;
901                 }
902         }
903
904         // Reaching this point means that the operating system is configured badly.
905         return '';
906 }
907
908 function get_cachefile($file, $writemode = true)
909 {
910         $cache = get_itemcachepath();
911
912         if ((!$cache) || (!is_dir($cache))) {
913                 return "";
914         }
915
916         $subfolder = $cache . "/" . substr($file, 0, 2);
917
918         $cachepath = $subfolder . "/" . $file;
919
920         if ($writemode) {
921                 if (!is_dir($subfolder)) {
922                         mkdir($subfolder);
923                         chmod($subfolder, 0777);
924                 }
925         }
926
927         return $cachepath;
928 }
929
930 function clear_cache($basepath = "", $path = "")
931 {
932         if ($path == "") {
933                 $basepath = get_itemcachepath();
934                 $path = $basepath;
935         }
936
937         if (($path == "") || (!is_dir($path))) {
938                 return;
939         }
940
941         if (substr(realpath($path), 0, strlen($basepath)) != $basepath) {
942                 return;
943         }
944
945         $cachetime = (int) Config::get('system', 'itemcache_duration');
946         if ($cachetime == 0) {
947                 $cachetime = 86400;
948         }
949
950         if (is_writable($path)) {
951                 if ($dh = opendir($path)) {
952                         while (($file = readdir($dh)) !== false) {
953                                 $fullpath = $path . "/" . $file;
954                                 if ((filetype($fullpath) == "dir") && ($file != ".") && ($file != "..")) {
955                                         clear_cache($basepath, $fullpath);
956                                 }
957                                 if ((filetype($fullpath) == "file") && (filectime($fullpath) < (time() - $cachetime))) {
958                                         unlink($fullpath);
959                                 }
960                         }
961                         closedir($dh);
962                 }
963         }
964 }
965
966 function get_itemcachepath()
967 {
968         // Checking, if the cache is deactivated
969         $cachetime = (int) Config::get('system', 'itemcache_duration');
970         if ($cachetime < 0) {
971                 return "";
972         }
973
974         $itemcache = Config::get('system', 'itemcache');
975         if (($itemcache != "") && App::isDirectoryUsable($itemcache)) {
976                 return App::getRealPath($itemcache);
977         }
978
979         $temppath = get_temppath();
980
981         if ($temppath != "") {
982                 $itemcache = $temppath . "/itemcache";
983                 if (!file_exists($itemcache) && !is_dir($itemcache)) {
984                         mkdir($itemcache);
985                 }
986
987                 if (App::isDirectoryUsable($itemcache)) {
988                         Config::set("system", "itemcache", $itemcache);
989                         return $itemcache;
990                 }
991         }
992         return "";
993 }
994
995 /**
996  * @brief Returns the path where spool files are stored
997  *
998  * @return string Spool path
999  */
1000 function get_spoolpath()
1001 {
1002         $spoolpath = Config::get('system', 'spoolpath');
1003         if (($spoolpath != "") && App::isDirectoryUsable($spoolpath)) {
1004                 // We have a spool path and it is usable
1005                 return $spoolpath;
1006         }
1007
1008         // We don't have a working preconfigured spool path, so we take the temp path.
1009         $temppath = get_temppath();
1010
1011         if ($temppath != "") {
1012                 // To avoid any interferences with other systems we create our own directory
1013                 $spoolpath = $temppath . "/spool";
1014                 if (!is_dir($spoolpath)) {
1015                         mkdir($spoolpath);
1016                 }
1017
1018                 if (App::isDirectoryUsable($spoolpath)) {
1019                         // The new path is usable, we are happy
1020                         Config::set("system", "spoolpath", $spoolpath);
1021                         return $spoolpath;
1022                 } else {
1023                         // We can't create a subdirectory, strange.
1024                         // But the directory seems to work, so we use it but don't store it.
1025                         return $temppath;
1026                 }
1027         }
1028
1029         // Reaching this point means that the operating system is configured badly.
1030         return "";
1031 }
1032
1033 if (!function_exists('exif_imagetype')) {
1034         function exif_imagetype($file)
1035         {
1036                 $size = getimagesize($file);
1037                 return $size[2];
1038         }
1039 }
1040
1041 function validate_include(&$file)
1042 {
1043         $orig_file = $file;
1044
1045         $file = realpath($file);
1046
1047         if (strpos($file, getcwd()) !== 0) {
1048                 return false;
1049         }
1050
1051         $file = str_replace(getcwd() . "/", "", $file, $count);
1052         if ($count != 1) {
1053                 return false;
1054         }
1055
1056         if ($orig_file !== $file) {
1057                 return false;
1058         }
1059
1060         $valid = false;
1061         if (strpos($file, "include/") === 0) {
1062                 $valid = true;
1063         }
1064
1065         if (strpos($file, "addon/") === 0) {
1066                 $valid = true;
1067         }
1068
1069         // Simply return flag
1070         return $valid;
1071 }
1072
1073 /**
1074  * @brief Get the data which is needed for infinite scroll
1075  *
1076  * For invinite scroll we need the page number of the actual page
1077  * and the the URI where the content of the next page comes from.
1078  * This data is needed for the js part in main.js.
1079  * Note: infinite scroll does only work for the network page (module)
1080  *
1081  * @param string $module The name of the module (e.g. "network")
1082  * @return array Of infinite scroll data
1083  *      'pageno' => $pageno The number of the actual page
1084  *      'reload_uri' => $reload_uri The URI of the content we have to load
1085  */
1086 function infinite_scroll_data($module)
1087 {
1088         if (PConfig::get(local_user(), 'system', 'infinite_scroll')
1089                 && $module == 'network'
1090                 && defaults($_GET, 'mode', '') != 'minimal'
1091         ) {
1092                 // get the page number
1093                 $pageno = defaults($_GET, 'page', 1);
1094
1095                 $reload_uri = "";
1096
1097                 // try to get the uri from which we load the content
1098                 foreach ($_GET as $param => $value) {
1099                         if (($param != "page") && ($param != "q")) {
1100                                 $reload_uri .= "&" . $param . "=" . urlencode($value);
1101                         }
1102                 }
1103
1104                 $a = get_app();
1105                 if ($a->page_offset != "" && !strstr($reload_uri, "&offset=")) {
1106                         $reload_uri .= "&offset=" . urlencode($a->page_offset);
1107                 }
1108
1109                 $arr = ["pageno" => $pageno, "reload_uri" => $reload_uri];
1110
1111                 return $arr;
1112         }
1113 }