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