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