wrong release ...
[friendica.git/.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\Core\Protocol;
21 use Friendica\Core\System;
22 use Friendica\Database\DBA;
23 use Friendica\DI;
24 use Friendica\Model\Contact;
25 use Friendica\Model\Term;
26 use Friendica\Util\BasePath;
27 use Friendica\Util\DateTimeFormat;
28
29 define('FRIENDICA_PLATFORM',     'Friendica');
30 define('FRIENDICA_CODENAME',     'Dalmatian Bellflower');
31 define('FRIENDICA_VERSION',      '2020.03-dev');
32 define('DFRN_PROTOCOL_VERSION',  '2.23');
33 define('NEW_UPDATE_ROUTINE_VERSION', 1170);
34
35 /**
36  * Constant with a HTML line break.
37  *
38  * Contains a HTML line break (br) element and a real carriage return with line
39  * feed for the source.
40  * This can be used in HTML and JavaScript where needed a line break.
41  */
42 define('EOL',                    "<br />\r\n");
43
44 /**
45  * Image storage quality.
46  *
47  * Lower numbers save space at cost of image detail.
48  * For ease of upgrade, please do not change here. Set system.jpegquality = n in config/local.config.php,
49  * where n is between 1 and 100, and with very poor results below about 50
50  */
51 define('JPEG_QUALITY',            100);
52
53 /**
54  * system.png_quality = n where is between 0 (uncompressed) to 9
55  */
56 define('PNG_QUALITY',             8);
57
58 /**
59  * An alternate way of limiting picture upload sizes. Specify the maximum pixel
60  * length that pictures are allowed to be (for non-square pictures, it will apply
61  * to the longest side). Pictures longer than this length will be resized to be
62  * this length (on the longest side, the other side will be scaled appropriately).
63  * Modify this value using
64  *
65  * 'system' => [
66  *      'max_image_length' => 'n',
67  *      ...
68  * ],
69  *
70  * in config/local.config.php
71  *
72  * If you don't want to set a maximum length, set to -1. The default value is
73  * defined by 'MAX_IMAGE_LENGTH' below.
74  */
75 define('MAX_IMAGE_LENGTH',        -1);
76
77 /**
78  * Not yet used
79  */
80 define('DEFAULT_DB_ENGINE',  'InnoDB');
81
82 /** @deprecated since version 2019.03, please use \Friendica\Module\Register::CLOSED instead */
83 define('REGISTER_CLOSED',        \Friendica\Module\Register::CLOSED);
84 /** @deprecated since version 2019.03, please use \Friendica\Module\Register::APPROVE instead */
85 define('REGISTER_APPROVE',       \Friendica\Module\Register::APPROVE);
86 /** @deprecated since version 2019.03, please use \Friendica\Module\Register::OPEN instead */
87 define('REGISTER_OPEN',          \Friendica\Module\Register::OPEN);
88
89 /**
90  * @name CP
91  *
92  * Type of the community page
93  * @{
94  */
95 define('CP_NO_INTERNAL_COMMUNITY', -2);
96 define('CP_NO_COMMUNITY_PAGE',     -1);
97 define('CP_USERS_ON_SERVER',        0);
98 define('CP_GLOBAL_COMMUNITY',       1);
99 define('CP_USERS_AND_GLOBAL',       2);
100 /**
101  * @}
102  */
103
104 /**
105  * These numbers are used in stored permissions
106  * and existing allocations MUST NEVER BE CHANGED
107  * OR RE-ASSIGNED! You may only add to them.
108  */
109 $netgroup_ids = [
110         Protocol::DFRN     => (-1),
111         Protocol::ZOT      => (-2),
112         Protocol::OSTATUS  => (-3),
113         Protocol::FEED     => (-4),
114         Protocol::DIASPORA => (-5),
115         Protocol::MAIL     => (-6),
116         Protocol::FACEBOOK => (-8),
117         Protocol::LINKEDIN => (-9),
118         Protocol::XMPP     => (-10),
119         Protocol::MYSPACE  => (-11),
120         Protocol::GPLUS    => (-12),
121         Protocol::PUMPIO   => (-13),
122         Protocol::TWITTER  => (-14),
123         Protocol::DIASPORA2 => (-15),
124         Protocol::STATUSNET => (-16),
125         Protocol::NEWS      => (-18),
126         Protocol::ICALENDAR => (-19),
127         Protocol::PNUT      => (-20),
128
129         Protocol::PHANTOM  => (-127),
130 ];
131
132 /**
133  * Maximum number of "people who like (or don't like) this"  that we will list by name
134  */
135 define('MAX_LIKERS',    75);
136
137 /**
138  * @name Notify
139  *
140  * Email notification options
141  * @{
142  */
143 /** @deprecated since 2020.03, use Notify\Type::INTRO instead */
144 define('NOTIFY_INTRO',        1);
145 /** @deprecated since 2020.03, use Notify\Type::CONFIRM instead */
146 define('NOTIFY_CONFIRM',      2);
147 /** @deprecated since 2020.03, use Notify\Type::WALL instead */
148 define('NOTIFY_WALL',         4);
149 /** @deprecated since 2020.03, use Notify\Type::COMMENT instead */
150 define('NOTIFY_COMMENT',      8);
151 /** @deprecated since 2020.03, use Notify\Type::MAIL instead */
152 define('NOTIFY_MAIL',        16);
153 /** @deprecated since 2020.03, use Notify\Type::SUGGEST instead */
154 define('NOTIFY_SUGGEST',     32);
155 /** @deprecated since 2020.03, use Notify\Type::PROFILE instead */
156 define('NOTIFY_PROFILE',     64);
157 /** @deprecated since 2020.03, use Notify\Type::TAG_SELF instead */
158 define('NOTIFY_TAGSELF',    128);
159 /** @deprecated since 2020.03, use Notify\Type::TAG_SHARE instead */
160 define('NOTIFY_TAGSHARE',   256);
161 /** @deprecated since 2020.03, use Notify\Type::POKE instead */
162 define('NOTIFY_POKE',       512);
163 /** @deprecated since 2020.03, use Notify\Type::SHARE instead */
164 define('NOTIFY_SHARE',     1024);
165
166 /** @deprecated since 2020.12, use Notify\Type::SYSTEM instead */
167 define('NOTIFY_SYSTEM',   32768);
168 /* @}*/
169
170
171 /** @deprecated since 2019.03, use Term::UNKNOWN instead */
172 define('TERM_UNKNOWN',   Term::UNKNOWN);
173 /** @deprecated since 2019.03, use Term::HASHTAG instead */
174 define('TERM_HASHTAG',   Term::HASHTAG);
175 /** @deprecated since 2019.03, use Term::MENTION instead */
176 define('TERM_MENTION',   Term::MENTION);
177 /** @deprecated since 2019.03, use Term::CATEGORY instead */
178 define('TERM_CATEGORY',  Term::CATEGORY);
179 /** @deprecated since 2019.03, use Term::PCATEGORY instead */
180 define('TERM_PCATEGORY', Term::PCATEGORY);
181 /** @deprecated since 2019.03, use Term::FILE instead */
182 define('TERM_FILE',      Term::FILE);
183 /** @deprecated since 2019.03, use Term::SAVEDSEARCH instead */
184 define('TERM_SAVEDSEARCH', Term::SAVEDSEARCH);
185 /** @deprecated since 2019.03, use Term::CONVERSATION instead */
186 define('TERM_CONVERSATION', Term::CONVERSATION);
187
188 /** @deprecated since 2019.03, use Term::OBJECT_TYPE_POST instead */
189 define('TERM_OBJ_POST',  Term::OBJECT_TYPE_POST);
190 /** @deprecated since 2019.03, use Term::OBJECT_TYPE_PHOTO instead */
191 define('TERM_OBJ_PHOTO', Term::OBJECT_TYPE_PHOTO);
192
193 /**
194  * @name Gravity
195  *
196  * Item weight for query ordering
197  * @{
198  */
199 define('GRAVITY_PARENT',       0);
200 define('GRAVITY_ACTIVITY',     3);
201 define('GRAVITY_COMMENT',      6);
202 define('GRAVITY_UNKNOWN',      9);
203 /* @}*/
204
205 /**
206  * @name Priority
207  *
208  * Process priority for the worker
209  * @{
210  */
211 define('PRIORITY_UNDEFINED',   0);
212 define('PRIORITY_CRITICAL',   10);
213 define('PRIORITY_HIGH',       20);
214 define('PRIORITY_MEDIUM',     30);
215 define('PRIORITY_LOW',        40);
216 define('PRIORITY_NEGLIGIBLE', 50);
217 /* @}*/
218
219 /**
220  * @name Social Relay settings
221  *
222  * See here: https://github.com/jaywink/social-relay
223  * and here: https://wiki.diasporafoundation.org/Relay_servers_for_public_posts
224  * @{
225  */
226 define('SR_SCOPE_NONE', '');
227 define('SR_SCOPE_ALL',  'all');
228 define('SR_SCOPE_TAGS', 'tags');
229 /* @}*/
230
231 // Normally this constant is defined - but not if "pcntl" isn't installed
232 if (!defined("SIGTERM")) {
233         define("SIGTERM", 15);
234 }
235
236 /**
237  * Depending on the PHP version this constant does exist - or not.
238  * See here: http://php.net/manual/en/curl.constants.php#117928
239  */
240 if (!defined('CURLE_OPERATION_TIMEDOUT')) {
241         define('CURLE_OPERATION_TIMEDOUT', CURLE_OPERATION_TIMEOUTED);
242 }
243
244 /**
245  * Returns the user id of locally logged in user or false.
246  *
247  * @return int|bool user id or false
248  */
249 function local_user()
250 {
251         if (!empty($_SESSION['authenticated']) && !empty($_SESSION['uid'])) {
252                 return intval($_SESSION['uid']);
253         }
254         return false;
255 }
256
257 /**
258  * Returns the public contact id of logged in user or false.
259  *
260  * @return int|bool public contact id or false
261  */
262 function public_contact()
263 {
264         static $public_contact_id = false;
265
266         if (!$public_contact_id && !empty($_SESSION['authenticated'])) {
267                 if (!empty($_SESSION['my_address'])) {
268                         // Local user
269                         $public_contact_id = intval(Contact::getIdForURL($_SESSION['my_address'], 0, true));
270                 } elseif (!empty($_SESSION['visitor_home'])) {
271                         // Remote user
272                         $public_contact_id = intval(Contact::getIdForURL($_SESSION['visitor_home'], 0, true));
273                 }
274         } elseif (empty($_SESSION['authenticated'])) {
275                 $public_contact_id = false;
276         }
277
278         return $public_contact_id;
279 }
280
281 /**
282  * Returns contact id of authenticated site visitor or false
283  *
284  * @return int|bool visitor_id or false
285  */
286 function remote_user()
287 {
288         if (empty($_SESSION['authenticated'])) {
289                 return false;
290         }
291
292         if (!empty($_SESSION['visitor_id'])) {
293                 return intval($_SESSION['visitor_id']);
294         }
295
296         return false;
297 }
298
299 /**
300  * Show an error message to user.
301  *
302  * This function save text in session, to be shown to the user at next page load
303  *
304  * @param string $s - Text of notice
305  */
306 function notice($s)
307 {
308         if (empty($_SESSION)) {
309                 return;
310         }
311
312         $a = DI::app();
313         if (empty($_SESSION['sysmsg'])) {
314                 $_SESSION['sysmsg'] = [];
315         }
316         if ($a->interactive) {
317                 $_SESSION['sysmsg'][] = $s;
318         }
319 }
320
321 /**
322  * Show an info message to user.
323  *
324  * This function save text in session, to be shown to the user at next page load
325  *
326  * @param string $s - Text of notice
327  */
328 function info($s)
329 {
330         $a = DI::app();
331
332         if (local_user() && DI::pConfig()->get(local_user(), 'system', 'ignore_info')) {
333                 return;
334         }
335
336         if (empty($_SESSION['sysmsg_info'])) {
337                 $_SESSION['sysmsg_info'] = [];
338         }
339         if ($a->interactive) {
340                 $_SESSION['sysmsg_info'][] = $s;
341         }
342 }
343
344 function feed_birthday($uid, $tz)
345 {
346         /**
347          * Determine the next birthday, but only if the birthday is published
348          * in the default profile. We _could_ also look for a private profile that the
349          * recipient can see, but somebody could get mad at us if they start getting
350          * public birthday greetings when they haven't made this info public.
351          *
352          * Assuming we are able to publish this info, we are then going to convert
353          * the start time from the owner's timezone to UTC.
354          *
355          * This will potentially solve the problem found with some social networks
356          * where birthdays are converted to the viewer's timezone and salutations from
357          * elsewhere in the world show up on the wrong day. We will convert it to the
358          * viewer's timezone also, but first we are going to convert it from the birthday
359          * person's timezone to GMT - so the viewer may find the birthday starting at
360          * 6:00PM the day before, but that will correspond to midnight to the birthday person.
361          */
362         $birthday = '';
363
364         if (!strlen($tz)) {
365                 $tz = 'UTC';
366         }
367
368         $profile = DBA::selectFirst('profile', ['dob'], ['uid' => $uid]);
369         if (DBA::isResult($profile)) {
370                 $tmp_dob = substr($profile['dob'], 5);
371                 if (intval($tmp_dob)) {
372                         $y = DateTimeFormat::timezoneNow($tz, 'Y');
373                         $bd = $y . '-' . $tmp_dob . ' 00:00';
374                         $t_dob = strtotime($bd);
375                         $now = strtotime(DateTimeFormat::timezoneNow($tz));
376                         if ($t_dob < $now) {
377                                 $bd = $y + 1 . '-' . $tmp_dob . ' 00:00';
378                         }
379                         $birthday = DateTimeFormat::convert($bd, 'UTC', $tz, DateTimeFormat::ATOM);
380                 }
381         }
382
383         return $birthday;
384 }
385
386 /**
387  * Check if current user has admin role.
388  *
389  * @return bool true if user is an admin
390  */
391 function is_site_admin()
392 {
393         $a = DI::app();
394
395         $admin_email = DI::config()->get('config', 'admin_email');
396
397         $adminlist = explode(',', str_replace(' ', '', $admin_email));
398
399         return local_user() && $admin_email && in_array($a->user['email'] ?? '', $adminlist);
400 }
401
402 function explode_querystring($query)
403 {
404         $arg_st = strpos($query, '?');
405         if ($arg_st !== false) {
406                 $base = substr($query, 0, $arg_st);
407                 $arg_st += 1;
408         } else {
409                 $base = '';
410                 $arg_st = 0;
411         }
412
413         $args = explode('&', substr($query, $arg_st));
414         foreach ($args as $k => $arg) {
415                 /// @TODO really compare type-safe here?
416                 if ($arg === '') {
417                         unset($args[$k]);
418                 }
419         }
420         $args = array_values($args);
421
422         if (!$base) {
423                 $base = $args[0];
424                 unset($args[0]);
425                 $args = array_values($args);
426         }
427
428         return [
429                 'base' => $base,
430                 'args' => $args,
431         ];
432 }
433
434 /**
435  * Returns the complete URL of the current page, e.g.: http(s)://something.com/network
436  *
437  * Taken from http://webcheatsheet.com/php/get_current_page_url.php
438  */
439 function curPageURL()
440 {
441         $pageURL = 'http';
442         if (!empty($_SERVER["HTTPS"]) && ($_SERVER["HTTPS"] == "on")) {
443                 $pageURL .= "s";
444         }
445
446         $pageURL .= "://";
447
448         if ($_SERVER["SERVER_PORT"] != "80" && $_SERVER["SERVER_PORT"] != "443") {
449                 $pageURL .= $_SERVER["SERVER_NAME"] . ":" . $_SERVER["SERVER_PORT"] . $_SERVER["REQUEST_URI"];
450         } else {
451                 $pageURL .= $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"];
452         }
453         return $pageURL;
454 }
455
456 function get_temppath()
457 {
458         $temppath = DI::config()->get("system", "temppath");
459
460         if (($temppath != "") && System::isDirectoryUsable($temppath)) {
461                 // We have a temp path and it is usable
462                 return BasePath::getRealPath($temppath);
463         }
464
465         // We don't have a working preconfigured temp path, so we take the system path.
466         $temppath = sys_get_temp_dir();
467
468         // Check if it is usable
469         if (($temppath != "") && System::isDirectoryUsable($temppath)) {
470                 // Always store the real path, not the path through symlinks
471                 $temppath = BasePath::getRealPath($temppath);
472
473                 // To avoid any interferences with other systems we create our own directory
474                 $new_temppath = $temppath . "/" . DI::baseUrl()->getHostname();
475                 if (!is_dir($new_temppath)) {
476                         /// @TODO There is a mkdir()+chmod() upwards, maybe generalize this (+ configurable) into a function/method?
477                         mkdir($new_temppath);
478                 }
479
480                 if (System::isDirectoryUsable($new_temppath)) {
481                         // The new path is usable, we are happy
482                         DI::config()->set("system", "temppath", $new_temppath);
483                         return $new_temppath;
484                 } else {
485                         // We can't create a subdirectory, strange.
486                         // But the directory seems to work, so we use it but don't store it.
487                         return $temppath;
488                 }
489         }
490
491         // Reaching this point means that the operating system is configured badly.
492         return '';
493 }
494
495 function get_cachefile($file, $writemode = true)
496 {
497         $cache = get_itemcachepath();
498
499         if ((!$cache) || (!is_dir($cache))) {
500                 return "";
501         }
502
503         $subfolder = $cache . "/" . substr($file, 0, 2);
504
505         $cachepath = $subfolder . "/" . $file;
506
507         if ($writemode) {
508                 if (!is_dir($subfolder)) {
509                         mkdir($subfolder);
510                         chmod($subfolder, 0777);
511                 }
512         }
513
514         return $cachepath;
515 }
516
517 function clear_cache($basepath = "", $path = "")
518 {
519         if ($path == "") {
520                 $basepath = get_itemcachepath();
521                 $path = $basepath;
522         }
523
524         if (($path == "") || (!is_dir($path))) {
525                 return;
526         }
527
528         if (substr(realpath($path), 0, strlen($basepath)) != $basepath) {
529                 return;
530         }
531
532         $cachetime = (int) DI::config()->get('system', 'itemcache_duration');
533         if ($cachetime == 0) {
534                 $cachetime = 86400;
535         }
536
537         if (is_writable($path)) {
538                 if ($dh = opendir($path)) {
539                         while (($file = readdir($dh)) !== false) {
540                                 $fullpath = $path . "/" . $file;
541                                 if ((filetype($fullpath) == "dir") && ($file != ".") && ($file != "..")) {
542                                         clear_cache($basepath, $fullpath);
543                                 }
544                                 if ((filetype($fullpath) == "file") && (filectime($fullpath) < (time() - $cachetime))) {
545                                         unlink($fullpath);
546                                 }
547                         }
548                         closedir($dh);
549                 }
550         }
551 }
552
553 function get_itemcachepath()
554 {
555         // Checking, if the cache is deactivated
556         $cachetime = (int) DI::config()->get('system', 'itemcache_duration');
557         if ($cachetime < 0) {
558                 return "";
559         }
560
561         $itemcache = DI::config()->get('system', 'itemcache');
562         if (($itemcache != "") && System::isDirectoryUsable($itemcache)) {
563                 return BasePath::getRealPath($itemcache);
564         }
565
566         $temppath = get_temppath();
567
568         if ($temppath != "") {
569                 $itemcache = $temppath . "/itemcache";
570                 if (!file_exists($itemcache) && !is_dir($itemcache)) {
571                         mkdir($itemcache);
572                 }
573
574                 if (System::isDirectoryUsable($itemcache)) {
575                         DI::config()->set("system", "itemcache", $itemcache);
576                         return $itemcache;
577                 }
578         }
579         return "";
580 }
581
582 /**
583  * Returns the path where spool files are stored
584  *
585  * @return string Spool path
586  */
587 function get_spoolpath()
588 {
589         $spoolpath = DI::config()->get('system', 'spoolpath');
590         if (($spoolpath != "") && System::isDirectoryUsable($spoolpath)) {
591                 // We have a spool path and it is usable
592                 return $spoolpath;
593         }
594
595         // We don't have a working preconfigured spool path, so we take the temp path.
596         $temppath = get_temppath();
597
598         if ($temppath != "") {
599                 // To avoid any interferences with other systems we create our own directory
600                 $spoolpath = $temppath . "/spool";
601                 if (!is_dir($spoolpath)) {
602                         mkdir($spoolpath);
603                 }
604
605                 if (System::isDirectoryUsable($spoolpath)) {
606                         // The new path is usable, we are happy
607                         DI::config()->set("system", "spoolpath", $spoolpath);
608                         return $spoolpath;
609                 } else {
610                         // We can't create a subdirectory, strange.
611                         // But the directory seems to work, so we use it but don't store it.
612                         return $temppath;
613                 }
614         }
615
616         // Reaching this point means that the operating system is configured badly.
617         return "";
618 }
619
620 if (!function_exists('exif_imagetype')) {
621         function exif_imagetype($file)
622         {
623                 $size = getimagesize($file);
624                 return $size[2];
625         }
626 }
627
628 function validate_include(&$file)
629 {
630         $orig_file = $file;
631
632         $file = realpath($file);
633
634         if (strpos($file, getcwd()) !== 0) {
635                 return false;
636         }
637
638         $file = str_replace(getcwd() . "/", "", $file, $count);
639         if ($count != 1) {
640                 return false;
641         }
642
643         if ($orig_file !== $file) {
644                 return false;
645         }
646
647         $valid = false;
648         if (strpos($file, "include/") === 0) {
649                 $valid = true;
650         }
651
652         if (strpos($file, "addon/") === 0) {
653                 $valid = true;
654         }
655
656         // Simply return flag
657         return $valid;
658 }