Merge pull request #8215 from nupplaphil/task/extract_email
[friendica.git/.git] / boot.php
1 <?php
2 /**
3  * @file boot.php
4  * This file defines some global constants and includes the central App class.
5  */
6
7 /**
8  * Friendica
9  *
10  * Friendica is a communications platform for integrated social communications
11  * utilising decentralised communications and linkage to several indie social
12  * projects - as well as popular mainstream providers.
13  *
14  * Our mission is to free our friends and families from the clutches of
15  * data-harvesting corporations, and pave the way to a future where social
16  * communications are free and open and flow between alternate providers as
17  * easily as email does today.
18  */
19
20 use Friendica\Core\Protocol;
21 use Friendica\Core\System;
22 use Friendica\Database\DBA;
23 use Friendica\DI;
24 use Friendica\Model\Contact;
25 use Friendica\Model\Term;
26 use Friendica\Util\BasePath;
27 use Friendica\Util\DateTimeFormat;
28
29 define('FRIENDICA_PLATFORM',     'Friendica');
30 define('FRIENDICA_CODENAME',     'Dalmatian Bellflower');
31 define('FRIENDICA_VERSION',      '2020.03-dev');
32 define('DFRN_PROTOCOL_VERSION',  '2.23');
33 define('NEW_UPDATE_ROUTINE_VERSION', 1170);
34
35 /**
36  * Constant with a HTML line break.
37  *
38  * Contains a HTML line break (br) element and a real carriage return with line
39  * feed for the source.
40  * This can be used in HTML and JavaScript where needed a line break.
41  */
42 define('EOL',                    "<br />\r\n");
43
44 /**
45  * Image storage quality.
46  *
47  * Lower numbers save space at cost of image detail.
48  * For ease of upgrade, please do not change here. Set system.jpegquality = n in config/local.config.php,
49  * where n is between 1 and 100, and with very poor results below about 50
50  */
51 define('JPEG_QUALITY',            100);
52
53 /**
54  * system.png_quality = n where is between 0 (uncompressed) to 9
55  */
56 define('PNG_QUALITY',             8);
57
58 /**
59  * An alternate way of limiting picture upload sizes. Specify the maximum pixel
60  * length that pictures are allowed to be (for non-square pictures, it will apply
61  * to the longest side). Pictures longer than this length will be resized to be
62  * this length (on the longest side, the other side will be scaled appropriately).
63  * Modify this value using
64  *
65  * 'system' => [
66  *      'max_image_length' => 'n',
67  *      ...
68  * ],
69  *
70  * in config/local.config.php
71  *
72  * If you don't want to set a maximum length, set to -1. The default value is
73  * defined by 'MAX_IMAGE_LENGTH' below.
74  */
75 define('MAX_IMAGE_LENGTH',        -1);
76
77 /**
78  * Not yet used
79  */
80 define('DEFAULT_DB_ENGINE',  'InnoDB');
81
82 /** @deprecated since version 2019.03, please use \Friendica\Module\Register::CLOSED instead */
83 define('REGISTER_CLOSED',        \Friendica\Module\Register::CLOSED);
84 /** @deprecated since version 2019.03, please use \Friendica\Module\Register::APPROVE instead */
85 define('REGISTER_APPROVE',       \Friendica\Module\Register::APPROVE);
86 /** @deprecated since version 2019.03, please use \Friendica\Module\Register::OPEN instead */
87 define('REGISTER_OPEN',          \Friendica\Module\Register::OPEN);
88
89 /**
90  * @name CP
91  *
92  * Type of the community page
93  * @{
94  */
95 define('CP_NO_INTERNAL_COMMUNITY', -2);
96 define('CP_NO_COMMUNITY_PAGE',     -1);
97 define('CP_USERS_ON_SERVER',        0);
98 define('CP_GLOBAL_COMMUNITY',       1);
99 define('CP_USERS_AND_GLOBAL',       2);
100 /**
101  * @}
102  */
103
104 /**
105  * These numbers are used in stored permissions
106  * and existing allocations MUST NEVER BE CHANGED
107  * OR RE-ASSIGNED! You may only add to them.
108  */
109 $netgroup_ids = [
110         Protocol::DFRN     => (-1),
111         Protocol::ZOT      => (-2),
112         Protocol::OSTATUS  => (-3),
113         Protocol::FEED     => (-4),
114         Protocol::DIASPORA => (-5),
115         Protocol::MAIL     => (-6),
116         Protocol::FACEBOOK => (-8),
117         Protocol::LINKEDIN => (-9),
118         Protocol::XMPP     => (-10),
119         Protocol::MYSPACE  => (-11),
120         Protocol::GPLUS    => (-12),
121         Protocol::PUMPIO   => (-13),
122         Protocol::TWITTER  => (-14),
123         Protocol::DIASPORA2 => (-15),
124         Protocol::STATUSNET => (-16),
125         Protocol::NEWS      => (-18),
126         Protocol::ICALENDAR => (-19),
127         Protocol::PNUT      => (-20),
128
129         Protocol::PHANTOM  => (-127),
130 ];
131
132 /**
133  * Maximum number of "people who like (or don't like) this"  that we will list by name
134  */
135 define('MAX_LIKERS',    75);
136
137 /**
138  * @name Notify
139  *
140  * Email notification options
141  * @{
142  */
143 define('NOTIFY_INTRO',        1);
144 define('NOTIFY_CONFIRM',      2);
145 define('NOTIFY_WALL',         4);
146 define('NOTIFY_COMMENT',      8);
147 define('NOTIFY_MAIL',        16);
148 define('NOTIFY_SUGGEST',     32);
149 define('NOTIFY_PROFILE',     64);
150 define('NOTIFY_TAGSELF',    128);
151 define('NOTIFY_TAGSHARE',   256);
152 define('NOTIFY_POKE',       512);
153 define('NOTIFY_SHARE',     1024);
154
155 define('NOTIFY_SYSTEM',   32768);
156 /* @}*/
157
158
159 /** @deprecated since 2019.03, use Term::UNKNOWN instead */
160 define('TERM_UNKNOWN',   Term::UNKNOWN);
161 /** @deprecated since 2019.03, use Term::HASHTAG instead */
162 define('TERM_HASHTAG',   Term::HASHTAG);
163 /** @deprecated since 2019.03, use Term::MENTION instead */
164 define('TERM_MENTION',   Term::MENTION);
165 /** @deprecated since 2019.03, use Term::CATEGORY instead */
166 define('TERM_CATEGORY',  Term::CATEGORY);
167 /** @deprecated since 2019.03, use Term::PCATEGORY instead */
168 define('TERM_PCATEGORY', Term::PCATEGORY);
169 /** @deprecated since 2019.03, use Term::FILE instead */
170 define('TERM_FILE',      Term::FILE);
171 /** @deprecated since 2019.03, use Term::SAVEDSEARCH instead */
172 define('TERM_SAVEDSEARCH', Term::SAVEDSEARCH);
173 /** @deprecated since 2019.03, use Term::CONVERSATION instead */
174 define('TERM_CONVERSATION', Term::CONVERSATION);
175
176 /** @deprecated since 2019.03, use Term::OBJECT_TYPE_POST instead */
177 define('TERM_OBJ_POST',  Term::OBJECT_TYPE_POST);
178 /** @deprecated since 2019.03, use Term::OBJECT_TYPE_PHOTO instead */
179 define('TERM_OBJ_PHOTO', Term::OBJECT_TYPE_PHOTO);
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 (local_user() && DI::pConfig()->get(local_user(), 'system', 'ignore_info')) {
321                 return;
322         }
323
324         if (empty($_SESSION['sysmsg_info'])) {
325                 $_SESSION['sysmsg_info'] = [];
326         }
327         if ($a->interactive) {
328                 $_SESSION['sysmsg_info'][] = $s;
329         }
330 }
331
332 function feed_birthday($uid, $tz)
333 {
334         /**
335          * Determine the next birthday, but only if the birthday is published
336          * in the default profile. We _could_ also look for a private profile that the
337          * recipient can see, but somebody could get mad at us if they start getting
338          * public birthday greetings when they haven't made this info public.
339          *
340          * Assuming we are able to publish this info, we are then going to convert
341          * the start time from the owner's timezone to UTC.
342          *
343          * This will potentially solve the problem found with some social networks
344          * where birthdays are converted to the viewer's timezone and salutations from
345          * elsewhere in the world show up on the wrong day. We will convert it to the
346          * viewer's timezone also, but first we are going to convert it from the birthday
347          * person's timezone to GMT - so the viewer may find the birthday starting at
348          * 6:00PM the day before, but that will correspond to midnight to the birthday person.
349          */
350         $birthday = '';
351
352         if (!strlen($tz)) {
353                 $tz = 'UTC';
354         }
355
356         $profile = DBA::selectFirst('profile', ['dob'], ['uid' => $uid]);
357         if (DBA::isResult($profile)) {
358                 $tmp_dob = substr($profile['dob'], 5);
359                 if (intval($tmp_dob)) {
360                         $y = DateTimeFormat::timezoneNow($tz, 'Y');
361                         $bd = $y . '-' . $tmp_dob . ' 00:00';
362                         $t_dob = strtotime($bd);
363                         $now = strtotime(DateTimeFormat::timezoneNow($tz));
364                         if ($t_dob < $now) {
365                                 $bd = $y + 1 . '-' . $tmp_dob . ' 00:00';
366                         }
367                         $birthday = DateTimeFormat::convert($bd, 'UTC', $tz, DateTimeFormat::ATOM);
368                 }
369         }
370
371         return $birthday;
372 }
373
374 /**
375  * Check if current user has admin role.
376  *
377  * @return bool true if user is an admin
378  */
379 function is_site_admin()
380 {
381         $a = DI::app();
382
383         $admin_email = DI::config()->get('config', 'admin_email');
384
385         $adminlist = explode(',', str_replace(' ', '', $admin_email));
386
387         return local_user() && $admin_email && in_array($a->user['email'] ?? '', $adminlist);
388 }
389
390 function explode_querystring($query)
391 {
392         $arg_st = strpos($query, '?');
393         if ($arg_st !== false) {
394                 $base = substr($query, 0, $arg_st);
395                 $arg_st += 1;
396         } else {
397                 $base = '';
398                 $arg_st = 0;
399         }
400
401         $args = explode('&', substr($query, $arg_st));
402         foreach ($args as $k => $arg) {
403                 /// @TODO really compare type-safe here?
404                 if ($arg === '') {
405                         unset($args[$k]);
406                 }
407         }
408         $args = array_values($args);
409
410         if (!$base) {
411                 $base = $args[0];
412                 unset($args[0]);
413                 $args = array_values($args);
414         }
415
416         return [
417                 'base' => $base,
418                 'args' => $args,
419         ];
420 }
421
422 /**
423  * Returns the complete URL of the current page, e.g.: http(s)://something.com/network
424  *
425  * Taken from http://webcheatsheet.com/php/get_current_page_url.php
426  */
427 function curPageURL()
428 {
429         $pageURL = 'http';
430         if (!empty($_SERVER["HTTPS"]) && ($_SERVER["HTTPS"] == "on")) {
431                 $pageURL .= "s";
432         }
433
434         $pageURL .= "://";
435
436         if ($_SERVER["SERVER_PORT"] != "80" && $_SERVER["SERVER_PORT"] != "443") {
437                 $pageURL .= $_SERVER["SERVER_NAME"] . ":" . $_SERVER["SERVER_PORT"] . $_SERVER["REQUEST_URI"];
438         } else {
439                 $pageURL .= $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"];
440         }
441         return $pageURL;
442 }
443
444 function get_temppath()
445 {
446         $temppath = DI::config()->get("system", "temppath");
447
448         if (($temppath != "") && System::isDirectoryUsable($temppath)) {
449                 // We have a temp path and it is usable
450                 return BasePath::getRealPath($temppath);
451         }
452
453         // We don't have a working preconfigured temp path, so we take the system path.
454         $temppath = sys_get_temp_dir();
455
456         // Check if it is usable
457         if (($temppath != "") && System::isDirectoryUsable($temppath)) {
458                 // Always store the real path, not the path through symlinks
459                 $temppath = BasePath::getRealPath($temppath);
460
461                 // To avoid any interferences with other systems we create our own directory
462                 $new_temppath = $temppath . "/" . DI::baseUrl()->getHostname();
463                 if (!is_dir($new_temppath)) {
464                         /// @TODO There is a mkdir()+chmod() upwards, maybe generalize this (+ configurable) into a function/method?
465                         mkdir($new_temppath);
466                 }
467
468                 if (System::isDirectoryUsable($new_temppath)) {
469                         // The new path is usable, we are happy
470                         DI::config()->set("system", "temppath", $new_temppath);
471                         return $new_temppath;
472                 } else {
473                         // We can't create a subdirectory, strange.
474                         // But the directory seems to work, so we use it but don't store it.
475                         return $temppath;
476                 }
477         }
478
479         // Reaching this point means that the operating system is configured badly.
480         return '';
481 }
482
483 function get_cachefile($file, $writemode = true)
484 {
485         $cache = get_itemcachepath();
486
487         if ((!$cache) || (!is_dir($cache))) {
488                 return "";
489         }
490
491         $subfolder = $cache . "/" . substr($file, 0, 2);
492
493         $cachepath = $subfolder . "/" . $file;
494
495         if ($writemode) {
496                 if (!is_dir($subfolder)) {
497                         mkdir($subfolder);
498                         chmod($subfolder, 0777);
499                 }
500         }
501
502         return $cachepath;
503 }
504
505 function clear_cache($basepath = "", $path = "")
506 {
507         if ($path == "") {
508                 $basepath = get_itemcachepath();
509                 $path = $basepath;
510         }
511
512         if (($path == "") || (!is_dir($path))) {
513                 return;
514         }
515
516         if (substr(realpath($path), 0, strlen($basepath)) != $basepath) {
517                 return;
518         }
519
520         $cachetime = (int) DI::config()->get('system', 'itemcache_duration');
521         if ($cachetime == 0) {
522                 $cachetime = 86400;
523         }
524
525         if (is_writable($path)) {
526                 if ($dh = opendir($path)) {
527                         while (($file = readdir($dh)) !== false) {
528                                 $fullpath = $path . "/" . $file;
529                                 if ((filetype($fullpath) == "dir") && ($file != ".") && ($file != "..")) {
530                                         clear_cache($basepath, $fullpath);
531                                 }
532                                 if ((filetype($fullpath) == "file") && (filectime($fullpath) < (time() - $cachetime))) {
533                                         unlink($fullpath);
534                                 }
535                         }
536                         closedir($dh);
537                 }
538         }
539 }
540
541 function get_itemcachepath()
542 {
543         // Checking, if the cache is deactivated
544         $cachetime = (int) DI::config()->get('system', 'itemcache_duration');
545         if ($cachetime < 0) {
546                 return "";
547         }
548
549         $itemcache = DI::config()->get('system', 'itemcache');
550         if (($itemcache != "") && System::isDirectoryUsable($itemcache)) {
551                 return BasePath::getRealPath($itemcache);
552         }
553
554         $temppath = get_temppath();
555
556         if ($temppath != "") {
557                 $itemcache = $temppath . "/itemcache";
558                 if (!file_exists($itemcache) && !is_dir($itemcache)) {
559                         mkdir($itemcache);
560                 }
561
562                 if (System::isDirectoryUsable($itemcache)) {
563                         DI::config()->set("system", "itemcache", $itemcache);
564                         return $itemcache;
565                 }
566         }
567         return "";
568 }
569
570 /**
571  * Returns the path where spool files are stored
572  *
573  * @return string Spool path
574  */
575 function get_spoolpath()
576 {
577         $spoolpath = DI::config()->get('system', 'spoolpath');
578         if (($spoolpath != "") && System::isDirectoryUsable($spoolpath)) {
579                 // We have a spool path and it is usable
580                 return $spoolpath;
581         }
582
583         // We don't have a working preconfigured spool path, so we take the temp path.
584         $temppath = get_temppath();
585
586         if ($temppath != "") {
587                 // To avoid any interferences with other systems we create our own directory
588                 $spoolpath = $temppath . "/spool";
589                 if (!is_dir($spoolpath)) {
590                         mkdir($spoolpath);
591                 }
592
593                 if (System::isDirectoryUsable($spoolpath)) {
594                         // The new path is usable, we are happy
595                         DI::config()->set("system", "spoolpath", $spoolpath);
596                         return $spoolpath;
597                 } else {
598                         // We can't create a subdirectory, strange.
599                         // But the directory seems to work, so we use it but don't store it.
600                         return $temppath;
601                 }
602         }
603
604         // Reaching this point means that the operating system is configured badly.
605         return "";
606 }
607
608 if (!function_exists('exif_imagetype')) {
609         function exif_imagetype($file)
610         {
611                 $size = getimagesize($file);
612                 return $size[2];
613         }
614 }
615
616 function validate_include(&$file)
617 {
618         $orig_file = $file;
619
620         $file = realpath($file);
621
622         if (strpos($file, getcwd()) !== 0) {
623                 return false;
624         }
625
626         $file = str_replace(getcwd() . "/", "", $file, $count);
627         if ($count != 1) {
628                 return false;
629         }
630
631         if ($orig_file !== $file) {
632                 return false;
633         }
634
635         $valid = false;
636         if (strpos($file, "include/") === 0) {
637                 $valid = true;
638         }
639
640         if (strpos($file, "addon/") === 0) {
641                 $valid = true;
642         }
643
644         // Simply return flag
645         return $valid;
646 }