Merge pull request #8265 from nupplaphil/task/add_license
[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-dev');
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 (local_user() && DI::pConfig()->get(local_user(), 'system', 'ignore_info')) {
344                 return;
345         }
346
347         if (empty($_SESSION['sysmsg_info'])) {
348                 $_SESSION['sysmsg_info'] = [];
349         }
350         if ($a->interactive) {
351                 $_SESSION['sysmsg_info'][] = $s;
352         }
353 }
354
355 function feed_birthday($uid, $tz)
356 {
357         /**
358          * Determine the next birthday, but only if the birthday is published
359          * in the default profile. We _could_ also look for a private profile that the
360          * recipient can see, but somebody could get mad at us if they start getting
361          * public birthday greetings when they haven't made this info public.
362          *
363          * Assuming we are able to publish this info, we are then going to convert
364          * the start time from the owner's timezone to UTC.
365          *
366          * This will potentially solve the problem found with some social networks
367          * where birthdays are converted to the viewer's timezone and salutations from
368          * elsewhere in the world show up on the wrong day. We will convert it to the
369          * viewer's timezone also, but first we are going to convert it from the birthday
370          * person's timezone to GMT - so the viewer may find the birthday starting at
371          * 6:00PM the day before, but that will correspond to midnight to the birthday person.
372          */
373         $birthday = '';
374
375         if (!strlen($tz)) {
376                 $tz = 'UTC';
377         }
378
379         $profile = DBA::selectFirst('profile', ['dob'], ['uid' => $uid]);
380         if (DBA::isResult($profile)) {
381                 $tmp_dob = substr($profile['dob'], 5);
382                 if (intval($tmp_dob)) {
383                         $y = DateTimeFormat::timezoneNow($tz, 'Y');
384                         $bd = $y . '-' . $tmp_dob . ' 00:00';
385                         $t_dob = strtotime($bd);
386                         $now = strtotime(DateTimeFormat::timezoneNow($tz));
387                         if ($t_dob < $now) {
388                                 $bd = $y + 1 . '-' . $tmp_dob . ' 00:00';
389                         }
390                         $birthday = DateTimeFormat::convert($bd, 'UTC', $tz, DateTimeFormat::ATOM);
391                 }
392         }
393
394         return $birthday;
395 }
396
397 /**
398  * Check if current user has admin role.
399  *
400  * @return bool true if user is an admin
401  */
402 function is_site_admin()
403 {
404         $a = DI::app();
405
406         $admin_email = DI::config()->get('config', 'admin_email');
407
408         $adminlist = explode(',', str_replace(' ', '', $admin_email));
409
410         return local_user() && $admin_email && in_array($a->user['email'] ?? '', $adminlist);
411 }
412
413 function explode_querystring($query)
414 {
415         $arg_st = strpos($query, '?');
416         if ($arg_st !== false) {
417                 $base = substr($query, 0, $arg_st);
418                 $arg_st += 1;
419         } else {
420                 $base = '';
421                 $arg_st = 0;
422         }
423
424         $args = explode('&', substr($query, $arg_st));
425         foreach ($args as $k => $arg) {
426                 /// @TODO really compare type-safe here?
427                 if ($arg === '') {
428                         unset($args[$k]);
429                 }
430         }
431         $args = array_values($args);
432
433         if (!$base) {
434                 $base = $args[0];
435                 unset($args[0]);
436                 $args = array_values($args);
437         }
438
439         return [
440                 'base' => $base,
441                 'args' => $args,
442         ];
443 }
444
445 /**
446  * Returns the complete URL of the current page, e.g.: http(s)://something.com/network
447  *
448  * Taken from http://webcheatsheet.com/php/get_current_page_url.php
449  */
450 function curPageURL()
451 {
452         $pageURL = 'http';
453         if (!empty($_SERVER["HTTPS"]) && ($_SERVER["HTTPS"] == "on")) {
454                 $pageURL .= "s";
455         }
456
457         $pageURL .= "://";
458
459         if ($_SERVER["SERVER_PORT"] != "80" && $_SERVER["SERVER_PORT"] != "443") {
460                 $pageURL .= $_SERVER["SERVER_NAME"] . ":" . $_SERVER["SERVER_PORT"] . $_SERVER["REQUEST_URI"];
461         } else {
462                 $pageURL .= $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"];
463         }
464         return $pageURL;
465 }
466
467 function get_temppath()
468 {
469         $temppath = DI::config()->get("system", "temppath");
470
471         if (($temppath != "") && System::isDirectoryUsable($temppath)) {
472                 // We have a temp path and it is usable
473                 return BasePath::getRealPath($temppath);
474         }
475
476         // We don't have a working preconfigured temp path, so we take the system path.
477         $temppath = sys_get_temp_dir();
478
479         // Check if it is usable
480         if (($temppath != "") && System::isDirectoryUsable($temppath)) {
481                 // Always store the real path, not the path through symlinks
482                 $temppath = BasePath::getRealPath($temppath);
483
484                 // To avoid any interferences with other systems we create our own directory
485                 $new_temppath = $temppath . "/" . DI::baseUrl()->getHostname();
486                 if (!is_dir($new_temppath)) {
487                         /// @TODO There is a mkdir()+chmod() upwards, maybe generalize this (+ configurable) into a function/method?
488                         mkdir($new_temppath);
489                 }
490
491                 if (System::isDirectoryUsable($new_temppath)) {
492                         // The new path is usable, we are happy
493                         DI::config()->set("system", "temppath", $new_temppath);
494                         return $new_temppath;
495                 } else {
496                         // We can't create a subdirectory, strange.
497                         // But the directory seems to work, so we use it but don't store it.
498                         return $temppath;
499                 }
500         }
501
502         // Reaching this point means that the operating system is configured badly.
503         return '';
504 }
505
506 function get_cachefile($file, $writemode = true)
507 {
508         $cache = get_itemcachepath();
509
510         if ((!$cache) || (!is_dir($cache))) {
511                 return "";
512         }
513
514         $subfolder = $cache . "/" . substr($file, 0, 2);
515
516         $cachepath = $subfolder . "/" . $file;
517
518         if ($writemode) {
519                 if (!is_dir($subfolder)) {
520                         mkdir($subfolder);
521                         chmod($subfolder, 0777);
522                 }
523         }
524
525         return $cachepath;
526 }
527
528 function clear_cache($basepath = "", $path = "")
529 {
530         if ($path == "") {
531                 $basepath = get_itemcachepath();
532                 $path = $basepath;
533         }
534
535         if (($path == "") || (!is_dir($path))) {
536                 return;
537         }
538
539         if (substr(realpath($path), 0, strlen($basepath)) != $basepath) {
540                 return;
541         }
542
543         $cachetime = (int) DI::config()->get('system', 'itemcache_duration');
544         if ($cachetime == 0) {
545                 $cachetime = 86400;
546         }
547
548         if (is_writable($path)) {
549                 if ($dh = opendir($path)) {
550                         while (($file = readdir($dh)) !== false) {
551                                 $fullpath = $path . "/" . $file;
552                                 if ((filetype($fullpath) == "dir") && ($file != ".") && ($file != "..")) {
553                                         clear_cache($basepath, $fullpath);
554                                 }
555                                 if ((filetype($fullpath) == "file") && (filectime($fullpath) < (time() - $cachetime))) {
556                                         unlink($fullpath);
557                                 }
558                         }
559                         closedir($dh);
560                 }
561         }
562 }
563
564 function get_itemcachepath()
565 {
566         // Checking, if the cache is deactivated
567         $cachetime = (int) DI::config()->get('system', 'itemcache_duration');
568         if ($cachetime < 0) {
569                 return "";
570         }
571
572         $itemcache = DI::config()->get('system', 'itemcache');
573         if (($itemcache != "") && System::isDirectoryUsable($itemcache)) {
574                 return BasePath::getRealPath($itemcache);
575         }
576
577         $temppath = get_temppath();
578
579         if ($temppath != "") {
580                 $itemcache = $temppath . "/itemcache";
581                 if (!file_exists($itemcache) && !is_dir($itemcache)) {
582                         mkdir($itemcache);
583                 }
584
585                 if (System::isDirectoryUsable($itemcache)) {
586                         DI::config()->set("system", "itemcache", $itemcache);
587                         return $itemcache;
588                 }
589         }
590         return "";
591 }
592
593 /**
594  * Returns the path where spool files are stored
595  *
596  * @return string Spool path
597  */
598 function get_spoolpath()
599 {
600         $spoolpath = DI::config()->get('system', 'spoolpath');
601         if (($spoolpath != "") && System::isDirectoryUsable($spoolpath)) {
602                 // We have a spool path and it is usable
603                 return $spoolpath;
604         }
605
606         // We don't have a working preconfigured spool path, so we take the temp path.
607         $temppath = get_temppath();
608
609         if ($temppath != "") {
610                 // To avoid any interferences with other systems we create our own directory
611                 $spoolpath = $temppath . "/spool";
612                 if (!is_dir($spoolpath)) {
613                         mkdir($spoolpath);
614                 }
615
616                 if (System::isDirectoryUsable($spoolpath)) {
617                         // The new path is usable, we are happy
618                         DI::config()->set("system", "spoolpath", $spoolpath);
619                         return $spoolpath;
620                 } else {
621                         // We can't create a subdirectory, strange.
622                         // But the directory seems to work, so we use it but don't store it.
623                         return $temppath;
624                 }
625         }
626
627         // Reaching this point means that the operating system is configured badly.
628         return "";
629 }
630
631 if (!function_exists('exif_imagetype')) {
632         function exif_imagetype($file)
633         {
634                 $size = getimagesize($file);
635                 return $size[2];
636         }
637 }
638
639 function validate_include(&$file)
640 {
641         $orig_file = $file;
642
643         $file = realpath($file);
644
645         if (strpos($file, getcwd()) !== 0) {
646                 return false;
647         }
648
649         $file = str_replace(getcwd() . "/", "", $file, $count);
650         if ($count != 1) {
651                 return false;
652         }
653
654         if ($orig_file !== $file) {
655                 return false;
656         }
657
658         $valid = false;
659         if (strpos($file, "include/") === 0) {
660                 $valid = true;
661         }
662
663         if (strpos($file, "addon/") === 0) {
664                 $valid = true;
665         }
666
667         // Simply return flag
668         return $valid;
669 }