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