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