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