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