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