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