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