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