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