Fix empty needle after trimming at PageInfo
[friendica.git/.git] / boot.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2021, the Friendica project
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\Notification;
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',      '2021.03-rc');
42 define('DFRN_PROTOCOL_VERSION',  '2.23');
43 define('NEW_TABLE_STRUCTURE_VERSION', 1288);
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 Notification
149  *
150  * Email notification options
151  * @{
152  */
153 /** @deprecated since 2020.03, use Notification\Type::INTRO instead */
154 define('NOTIFY_INTRO',        Notification\Type::INTRO);
155 /** @deprecated since 2020.03, use Notification\Type::CONFIRM instead */
156 define('NOTIFY_CONFIRM',      Notification\Type::CONFIRM);
157 /** @deprecated since 2020.03, use Notification\Type::WALL instead */
158 define('NOTIFY_WALL',         Notification\Type::WALL);
159 /** @deprecated since 2020.03, use Notification\Type::COMMENT instead */
160 define('NOTIFY_COMMENT',      Notification\Type::COMMENT);
161 /** @deprecated since 2020.03, use Notification\Type::MAIL instead */
162 define('NOTIFY_MAIL',        Notification\Type::MAIL);
163 /** @deprecated since 2020.03, use Notification\Type::SUGGEST instead */
164 define('NOTIFY_SUGGEST',     Notification\Type::SUGGEST);
165 /** @deprecated since 2020.03, use Notification\Type::PROFILE instead */
166 define('NOTIFY_PROFILE',     Notification\Type::PROFILE);
167 /** @deprecated since 2020.03, use Notification\Type::TAG_SELF instead */
168 define('NOTIFY_TAGSELF',     Notification\Type::TAG_SELF);
169 /** @deprecated since 2020.03, use Notification\Type::TAG_SHARE instead */
170 define('NOTIFY_TAGSHARE',    Notification\Type::TAG_SHARE);
171 /** @deprecated since 2020.03, use Notification\Type::POKE instead */
172 define('NOTIFY_POKE',        Notification\Type::POKE);
173 /** @deprecated since 2020.03, use Notification\Type::SHARE instead */
174 define('NOTIFY_SHARE',       Notification\Type::SHARE);
175
176 /** @deprecated since 2020.12, use Notification\Type::SYSTEM instead */
177 define('NOTIFY_SYSTEM',      Notification\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 define('PRIORITIES', [PRIORITY_CRITICAL, PRIORITY_HIGH, PRIORITY_MEDIUM, PRIORITY_LOW, PRIORITY_NEGLIGIBLE]);
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, false));
258                 } elseif (!empty($_SESSION['visitor_home'])) {
259                         // Remote user
260                         $public_contact_id = intval(Contact::getIdForURL($_SESSION['visitor_home'], 0, false));
261                 }
262         } elseif (empty($_SESSION['authenticated'])) {
263                 $public_contact_id = false;
264         }
265
266         return $public_contact_id;
267 }
268
269 /**
270  * Returns public 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 /**
387  * Returns the complete URL of the current page, e.g.: http(s)://something.com/network
388  *
389  * Taken from http://webcheatsheet.com/php/get_current_page_url.php
390  */
391 function curPageURL()
392 {
393         $pageURL = 'http';
394         if (!empty($_SERVER["HTTPS"]) && ($_SERVER["HTTPS"] == "on")) {
395                 $pageURL .= "s";
396         }
397
398         $pageURL .= "://";
399
400         if ($_SERVER["SERVER_PORT"] != "80" && $_SERVER["SERVER_PORT"] != "443") {
401                 $pageURL .= $_SERVER["SERVER_NAME"] . ":" . $_SERVER["SERVER_PORT"] . $_SERVER["REQUEST_URI"];
402         } else {
403                 $pageURL .= $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"];
404         }
405         return $pageURL;
406 }
407
408 function get_temppath()
409 {
410         $temppath = DI::config()->get("system", "temppath");
411
412         if (($temppath != "") && System::isDirectoryUsable($temppath)) {
413                 // We have a temp path and it is usable
414                 return BasePath::getRealPath($temppath);
415         }
416
417         // We don't have a working preconfigured temp path, so we take the system path.
418         $temppath = sys_get_temp_dir();
419
420         // Check if it is usable
421         if (($temppath != "") && System::isDirectoryUsable($temppath)) {
422                 // Always store the real path, not the path through symlinks
423                 $temppath = BasePath::getRealPath($temppath);
424
425                 // To avoid any interferences with other systems we create our own directory
426                 $new_temppath = $temppath . "/" . DI::baseUrl()->getHostname();
427                 if (!is_dir($new_temppath)) {
428                         /// @TODO There is a mkdir()+chmod() upwards, maybe generalize this (+ configurable) into a function/method?
429                         mkdir($new_temppath);
430                 }
431
432                 if (System::isDirectoryUsable($new_temppath)) {
433                         // The new path is usable, we are happy
434                         DI::config()->set("system", "temppath", $new_temppath);
435                         return $new_temppath;
436                 } else {
437                         // We can't create a subdirectory, strange.
438                         // But the directory seems to work, so we use it but don't store it.
439                         return $temppath;
440                 }
441         }
442
443         // Reaching this point means that the operating system is configured badly.
444         return '';
445 }
446
447 function get_cachefile($file, $writemode = true)
448 {
449         $cache = get_itemcachepath();
450
451         if ((!$cache) || (!is_dir($cache))) {
452                 return "";
453         }
454
455         $subfolder = $cache . "/" . substr($file, 0, 2);
456
457         $cachepath = $subfolder . "/" . $file;
458
459         if ($writemode) {
460                 if (!is_dir($subfolder)) {
461                         mkdir($subfolder);
462                         chmod($subfolder, 0777);
463                 }
464         }
465
466         return $cachepath;
467 }
468
469 function clear_cache($basepath = "", $path = "")
470 {
471         if ($path == "") {
472                 $basepath = get_itemcachepath();
473                 $path = $basepath;
474         }
475
476         if (($path == "") || (!is_dir($path))) {
477                 return;
478         }
479
480         if (substr(realpath($path), 0, strlen($basepath)) != $basepath) {
481                 return;
482         }
483
484         $cachetime = (int) DI::config()->get('system', 'itemcache_duration');
485         if ($cachetime == 0) {
486                 $cachetime = 86400;
487         }
488
489         if (is_writable($path)) {
490                 if ($dh = opendir($path)) {
491                         while (($file = readdir($dh)) !== false) {
492                                 $fullpath = $path . "/" . $file;
493                                 if ((filetype($fullpath) == "dir") && ($file != ".") && ($file != "..")) {
494                                         clear_cache($basepath, $fullpath);
495                                 }
496                                 if ((filetype($fullpath) == "file") && (filectime($fullpath) < (time() - $cachetime))) {
497                                         unlink($fullpath);
498                                 }
499                         }
500                         closedir($dh);
501                 }
502         }
503 }
504
505 function get_itemcachepath()
506 {
507         // Checking, if the cache is deactivated
508         $cachetime = (int) DI::config()->get('system', 'itemcache_duration');
509         if ($cachetime < 0) {
510                 return "";
511         }
512
513         $itemcache = DI::config()->get('system', 'itemcache');
514         if (($itemcache != "") && System::isDirectoryUsable($itemcache)) {
515                 return BasePath::getRealPath($itemcache);
516         }
517
518         $temppath = get_temppath();
519
520         if ($temppath != "") {
521                 $itemcache = $temppath . "/itemcache";
522                 if (!file_exists($itemcache) && !is_dir($itemcache)) {
523                         mkdir($itemcache);
524                 }
525
526                 if (System::isDirectoryUsable($itemcache)) {
527                         DI::config()->set("system", "itemcache", $itemcache);
528                         return $itemcache;
529                 }
530         }
531         return "";
532 }
533
534 /**
535  * Returns the path where spool files are stored
536  *
537  * @return string Spool path
538  */
539 function get_spoolpath()
540 {
541         $spoolpath = DI::config()->get('system', 'spoolpath');
542         if (($spoolpath != "") && System::isDirectoryUsable($spoolpath)) {
543                 // We have a spool path and it is usable
544                 return $spoolpath;
545         }
546
547         // We don't have a working preconfigured spool path, so we take the temp path.
548         $temppath = get_temppath();
549
550         if ($temppath != "") {
551                 // To avoid any interferences with other systems we create our own directory
552                 $spoolpath = $temppath . "/spool";
553                 if (!is_dir($spoolpath)) {
554                         mkdir($spoolpath);
555                 }
556
557                 if (System::isDirectoryUsable($spoolpath)) {
558                         // The new path is usable, we are happy
559                         DI::config()->set("system", "spoolpath", $spoolpath);
560                         return $spoolpath;
561                 } else {
562                         // We can't create a subdirectory, strange.
563                         // But the directory seems to work, so we use it but don't store it.
564                         return $temppath;
565                 }
566         }
567
568         // Reaching this point means that the operating system is configured badly.
569         return "";
570 }
571
572 if (!function_exists('exif_imagetype')) {
573         function exif_imagetype($file)
574         {
575                 $size = getimagesize($file);
576                 return $size[2];
577         }
578 }
579
580 function validate_include(&$file)
581 {
582         $orig_file = $file;
583
584         $file = realpath($file);
585
586         if (strpos($file, getcwd()) !== 0) {
587                 return false;
588         }
589
590         $file = str_replace(getcwd() . "/", "", $file, $count);
591         if ($count != 1) {
592                 return false;
593         }
594
595         if ($orig_file !== $file) {
596                 return false;
597         }
598
599         $valid = false;
600         if (strpos($file, "include/") === 0) {
601                 $valid = true;
602         }
603
604         if (strpos($file, "addon/") === 0) {
605                 $valid = true;
606         }
607
608         // Simply return flag
609         return $valid;
610 }