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