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