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