]> git.mxchange.org Git - friendica.git/blob - boot.php
Merge remote-tracking branch 'upstream/develop' into term2tag
[friendica.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',     'Red Hot Poker');
42 define('FRIENDICA_VERSION',      '2020.06-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  * @name Gravity
183  *
184  * Item weight for query ordering
185  * @{
186  */
187 define('GRAVITY_PARENT',       0);
188 define('GRAVITY_ACTIVITY',     3);
189 define('GRAVITY_COMMENT',      6);
190 define('GRAVITY_UNKNOWN',      9);
191 /* @}*/
192
193 /**
194  * @name Priority
195  *
196  * Process priority for the worker
197  * @{
198  */
199 define('PRIORITY_UNDEFINED',   0);
200 define('PRIORITY_CRITICAL',   10);
201 define('PRIORITY_HIGH',       20);
202 define('PRIORITY_MEDIUM',     30);
203 define('PRIORITY_LOW',        40);
204 define('PRIORITY_NEGLIGIBLE', 50);
205 /* @}*/
206
207 /**
208  * @name Social Relay settings
209  *
210  * See here: https://github.com/jaywink/social-relay
211  * and here: https://wiki.diasporafoundation.org/Relay_servers_for_public_posts
212  * @{
213  */
214 define('SR_SCOPE_NONE', '');
215 define('SR_SCOPE_ALL',  'all');
216 define('SR_SCOPE_TAGS', 'tags');
217 /* @}*/
218
219 // Normally this constant is defined - but not if "pcntl" isn't installed
220 if (!defined("SIGTERM")) {
221         define("SIGTERM", 15);
222 }
223
224 /**
225  * Depending on the PHP version this constant does exist - or not.
226  * See here: http://php.net/manual/en/curl.constants.php#117928
227  */
228 if (!defined('CURLE_OPERATION_TIMEDOUT')) {
229         define('CURLE_OPERATION_TIMEDOUT', CURLE_OPERATION_TIMEOUTED);
230 }
231
232 /**
233  * Returns the user id of locally logged in user or false.
234  *
235  * @return int|bool user id or false
236  */
237 function local_user()
238 {
239         if (!empty($_SESSION['authenticated']) && !empty($_SESSION['uid'])) {
240                 return intval($_SESSION['uid']);
241         }
242         return false;
243 }
244
245 /**
246  * Returns the public contact id of logged in user or false.
247  *
248  * @return int|bool public contact id or false
249  */
250 function public_contact()
251 {
252         static $public_contact_id = false;
253
254         if (!$public_contact_id && !empty($_SESSION['authenticated'])) {
255                 if (!empty($_SESSION['my_address'])) {
256                         // Local user
257                         $public_contact_id = intval(Contact::getIdForURL($_SESSION['my_address'], 0, true));
258                 } elseif (!empty($_SESSION['visitor_home'])) {
259                         // Remote user
260                         $public_contact_id = intval(Contact::getIdForURL($_SESSION['visitor_home'], 0, true));
261                 }
262         } elseif (empty($_SESSION['authenticated'])) {
263                 $public_contact_id = false;
264         }
265
266         return $public_contact_id;
267 }
268
269 /**
270  * Returns contact id of authenticated site visitor or false
271  *
272  * @return int|bool visitor_id or false
273  */
274 function remote_user()
275 {
276         if (empty($_SESSION['authenticated'])) {
277                 return false;
278         }
279
280         if (!empty($_SESSION['visitor_id'])) {
281                 return intval($_SESSION['visitor_id']);
282         }
283
284         return false;
285 }
286
287 /**
288  * Show an error message to user.
289  *
290  * This function save text in session, to be shown to the user at next page load
291  *
292  * @param string $s - Text of notice
293  */
294 function notice($s)
295 {
296         if (empty($_SESSION)) {
297                 return;
298         }
299
300         $a = DI::app();
301         if (empty($_SESSION['sysmsg'])) {
302                 $_SESSION['sysmsg'] = [];
303         }
304         if ($a->interactive) {
305                 $_SESSION['sysmsg'][] = $s;
306         }
307 }
308
309 /**
310  * Show an info message to user.
311  *
312  * This function save text in session, to be shown to the user at next page load
313  *
314  * @param string $s - Text of notice
315  */
316 function info($s)
317 {
318         $a = DI::app();
319
320         if (empty($_SESSION['sysmsg_info'])) {
321                 $_SESSION['sysmsg_info'] = [];
322         }
323         if ($a->interactive) {
324                 $_SESSION['sysmsg_info'][] = $s;
325         }
326 }
327
328 function feed_birthday($uid, $tz)
329 {
330         /**
331          * Determine the next birthday, but only if the birthday is published
332          * in the default profile. We _could_ also look for a private profile that the
333          * recipient can see, but somebody could get mad at us if they start getting
334          * public birthday greetings when they haven't made this info public.
335          *
336          * Assuming we are able to publish this info, we are then going to convert
337          * the start time from the owner's timezone to UTC.
338          *
339          * This will potentially solve the problem found with some social networks
340          * where birthdays are converted to the viewer's timezone and salutations from
341          * elsewhere in the world show up on the wrong day. We will convert it to the
342          * viewer's timezone also, but first we are going to convert it from the birthday
343          * person's timezone to GMT - so the viewer may find the birthday starting at
344          * 6:00PM the day before, but that will correspond to midnight to the birthday person.
345          */
346         $birthday = '';
347
348         if (!strlen($tz)) {
349                 $tz = 'UTC';
350         }
351
352         $profile = DBA::selectFirst('profile', ['dob'], ['uid' => $uid]);
353         if (DBA::isResult($profile)) {
354                 $tmp_dob = substr($profile['dob'], 5);
355                 if (intval($tmp_dob)) {
356                         $y = DateTimeFormat::timezoneNow($tz, 'Y');
357                         $bd = $y . '-' . $tmp_dob . ' 00:00';
358                         $t_dob = strtotime($bd);
359                         $now = strtotime(DateTimeFormat::timezoneNow($tz));
360                         if ($t_dob < $now) {
361                                 $bd = $y + 1 . '-' . $tmp_dob . ' 00:00';
362                         }
363                         $birthday = DateTimeFormat::convert($bd, 'UTC', $tz, DateTimeFormat::ATOM);
364                 }
365         }
366
367         return $birthday;
368 }
369
370 /**
371  * Check if current user has admin role.
372  *
373  * @return bool true if user is an admin
374  */
375 function is_site_admin()
376 {
377         $a = DI::app();
378
379         $admin_email = DI::config()->get('config', 'admin_email');
380
381         $adminlist = explode(',', str_replace(' ', '', $admin_email));
382
383         return local_user() && $admin_email && in_array($a->user['email'] ?? '', $adminlist);
384 }
385
386 function explode_querystring($query)
387 {
388         $arg_st = strpos($query, '?');
389         if ($arg_st !== false) {
390                 $base = substr($query, 0, $arg_st);
391                 $arg_st += 1;
392         } else {
393                 $base = '';
394                 $arg_st = 0;
395         }
396
397         $args = explode('&', substr($query, $arg_st));
398         foreach ($args as $k => $arg) {
399                 /// @TODO really compare type-safe here?
400                 if ($arg === '') {
401                         unset($args[$k]);
402                 }
403         }
404         $args = array_values($args);
405
406         if (!$base) {
407                 $base = $args[0];
408                 unset($args[0]);
409                 $args = array_values($args);
410         }
411
412         return [
413                 'base' => $base,
414                 'args' => $args,
415         ];
416 }
417
418 /**
419  * Returns the complete URL of the current page, e.g.: http(s)://something.com/network
420  *
421  * Taken from http://webcheatsheet.com/php/get_current_page_url.php
422  */
423 function curPageURL()
424 {
425         $pageURL = 'http';
426         if (!empty($_SERVER["HTTPS"]) && ($_SERVER["HTTPS"] == "on")) {
427                 $pageURL .= "s";
428         }
429
430         $pageURL .= "://";
431
432         if ($_SERVER["SERVER_PORT"] != "80" && $_SERVER["SERVER_PORT"] != "443") {
433                 $pageURL .= $_SERVER["SERVER_NAME"] . ":" . $_SERVER["SERVER_PORT"] . $_SERVER["REQUEST_URI"];
434         } else {
435                 $pageURL .= $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"];
436         }
437         return $pageURL;
438 }
439
440 function get_temppath()
441 {
442         $temppath = DI::config()->get("system", "temppath");
443
444         if (($temppath != "") && System::isDirectoryUsable($temppath)) {
445                 // We have a temp path and it is usable
446                 return BasePath::getRealPath($temppath);
447         }
448
449         // We don't have a working preconfigured temp path, so we take the system path.
450         $temppath = sys_get_temp_dir();
451
452         // Check if it is usable
453         if (($temppath != "") && System::isDirectoryUsable($temppath)) {
454                 // Always store the real path, not the path through symlinks
455                 $temppath = BasePath::getRealPath($temppath);
456
457                 // To avoid any interferences with other systems we create our own directory
458                 $new_temppath = $temppath . "/" . DI::baseUrl()->getHostname();
459                 if (!is_dir($new_temppath)) {
460                         /// @TODO There is a mkdir()+chmod() upwards, maybe generalize this (+ configurable) into a function/method?
461                         mkdir($new_temppath);
462                 }
463
464                 if (System::isDirectoryUsable($new_temppath)) {
465                         // The new path is usable, we are happy
466                         DI::config()->set("system", "temppath", $new_temppath);
467                         return $new_temppath;
468                 } else {
469                         // We can't create a subdirectory, strange.
470                         // But the directory seems to work, so we use it but don't store it.
471                         return $temppath;
472                 }
473         }
474
475         // Reaching this point means that the operating system is configured badly.
476         return '';
477 }
478
479 function get_cachefile($file, $writemode = true)
480 {
481         $cache = get_itemcachepath();
482
483         if ((!$cache) || (!is_dir($cache))) {
484                 return "";
485         }
486
487         $subfolder = $cache . "/" . substr($file, 0, 2);
488
489         $cachepath = $subfolder . "/" . $file;
490
491         if ($writemode) {
492                 if (!is_dir($subfolder)) {
493                         mkdir($subfolder);
494                         chmod($subfolder, 0777);
495                 }
496         }
497
498         return $cachepath;
499 }
500
501 function clear_cache($basepath = "", $path = "")
502 {
503         if ($path == "") {
504                 $basepath = get_itemcachepath();
505                 $path = $basepath;
506         }
507
508         if (($path == "") || (!is_dir($path))) {
509                 return;
510         }
511
512         if (substr(realpath($path), 0, strlen($basepath)) != $basepath) {
513                 return;
514         }
515
516         $cachetime = (int) DI::config()->get('system', 'itemcache_duration');
517         if ($cachetime == 0) {
518                 $cachetime = 86400;
519         }
520
521         if (is_writable($path)) {
522                 if ($dh = opendir($path)) {
523                         while (($file = readdir($dh)) !== false) {
524                                 $fullpath = $path . "/" . $file;
525                                 if ((filetype($fullpath) == "dir") && ($file != ".") && ($file != "..")) {
526                                         clear_cache($basepath, $fullpath);
527                                 }
528                                 if ((filetype($fullpath) == "file") && (filectime($fullpath) < (time() - $cachetime))) {
529                                         unlink($fullpath);
530                                 }
531                         }
532                         closedir($dh);
533                 }
534         }
535 }
536
537 function get_itemcachepath()
538 {
539         // Checking, if the cache is deactivated
540         $cachetime = (int) DI::config()->get('system', 'itemcache_duration');
541         if ($cachetime < 0) {
542                 return "";
543         }
544
545         $itemcache = DI::config()->get('system', 'itemcache');
546         if (($itemcache != "") && System::isDirectoryUsable($itemcache)) {
547                 return BasePath::getRealPath($itemcache);
548         }
549
550         $temppath = get_temppath();
551
552         if ($temppath != "") {
553                 $itemcache = $temppath . "/itemcache";
554                 if (!file_exists($itemcache) && !is_dir($itemcache)) {
555                         mkdir($itemcache);
556                 }
557
558                 if (System::isDirectoryUsable($itemcache)) {
559                         DI::config()->set("system", "itemcache", $itemcache);
560                         return $itemcache;
561                 }
562         }
563         return "";
564 }
565
566 /**
567  * Returns the path where spool files are stored
568  *
569  * @return string Spool path
570  */
571 function get_spoolpath()
572 {
573         $spoolpath = DI::config()->get('system', 'spoolpath');
574         if (($spoolpath != "") && System::isDirectoryUsable($spoolpath)) {
575                 // We have a spool path and it is usable
576                 return $spoolpath;
577         }
578
579         // We don't have a working preconfigured spool path, so we take the temp path.
580         $temppath = get_temppath();
581
582         if ($temppath != "") {
583                 // To avoid any interferences with other systems we create our own directory
584                 $spoolpath = $temppath . "/spool";
585                 if (!is_dir($spoolpath)) {
586                         mkdir($spoolpath);
587                 }
588
589                 if (System::isDirectoryUsable($spoolpath)) {
590                         // The new path is usable, we are happy
591                         DI::config()->set("system", "spoolpath", $spoolpath);
592                         return $spoolpath;
593                 } else {
594                         // We can't create a subdirectory, strange.
595                         // But the directory seems to work, so we use it but don't store it.
596                         return $temppath;
597                 }
598         }
599
600         // Reaching this point means that the operating system is configured badly.
601         return "";
602 }
603
604 if (!function_exists('exif_imagetype')) {
605         function exif_imagetype($file)
606         {
607                 $size = getimagesize($file);
608                 return $size[2];
609         }
610 }
611
612 function validate_include(&$file)
613 {
614         $orig_file = $file;
615
616         $file = realpath($file);
617
618         if (strpos($file, getcwd()) !== 0) {
619                 return false;
620         }
621
622         $file = str_replace(getcwd() . "/", "", $file, $count);
623         if ($count != 1) {
624                 return false;
625         }
626
627         if ($orig_file !== $file) {
628                 return false;
629         }
630
631         $valid = false;
632         if (strpos($file, "include/") === 0) {
633                 $valid = true;
634         }
635
636         if (strpos($file, "addon/") === 0) {
637                 $valid = true;
638         }
639
640         // Simply return flag
641         return $valid;
642 }