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