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