4 * This file defines some global constants and includes the central App class.
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.
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.
20 require_once __DIR__ . DIRECTORY_SEPARATOR . 'vendor' . DIRECTORY_SEPARATOR . 'autoload.php';
23 use Friendica\BaseObject;
24 use Friendica\Core\Addon;
25 use Friendica\Core\Cache;
26 use Friendica\Core\Config;
27 use Friendica\Core\L10n;
28 use Friendica\Core\PConfig;
29 use Friendica\Core\Protocol;
30 use Friendica\Core\System;
31 use Friendica\Core\Update;
32 use Friendica\Core\Worker;
33 use Friendica\Database\DBA;
34 use Friendica\Model\Contact;
35 use Friendica\Model\Conversation;
36 use Friendica\Util\DateTimeFormat;
38 require_once 'include/text.php';
40 define('FRIENDICA_PLATFORM', 'Friendica');
41 define('FRIENDICA_CODENAME', 'The Tazmans Flax-lily');
42 define('FRIENDICA_VERSION', '2018.12-dev');
43 define('DFRN_PROTOCOL_VERSION', '2.23');
44 define('NEW_UPDATE_ROUTINE_VERSION', 1170);
47 * @brief Constant with a HTML line break.
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.
53 define('EOL', "<br />\r\n");
56 * @brief Image storage quality.
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.ini.php,
60 * where n is between 1 and 100, and with very poor results below about 50
62 define('JPEG_QUALITY', 100);
65 * [system] png_quality = n where is between 0 (uncompressed) to 9
67 define('PNG_QUALITY', 8);
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
77 * max_image_length = n;
79 * in config/local.ini.php
81 * If you don't want to set a maximum length, set to -1. The default value is
82 * defined by 'MAX_IMAGE_LENGTH' below.
84 define('MAX_IMAGE_LENGTH', -1);
89 define('DEFAULT_DB_ENGINE', 'InnoDB');
94 * SSL redirection policies
97 define('SSL_POLICY_NONE', 0);
98 define('SSL_POLICY_FULL', 1);
99 define('SSL_POLICY_SELFSIGN', 2);
105 * Registration policies
108 define('REGISTER_CLOSED', 0);
109 define('REGISTER_APPROVE', 1);
110 define('REGISTER_OPEN', 2);
118 * Type of the community page
121 define('CP_NO_INTERNAL_COMMUNITY', -2);
122 define('CP_NO_COMMUNITY_PAGE', -1);
123 define('CP_USERS_ON_SERVER', 0);
124 define('CP_GLOBAL_COMMUNITY', 1);
125 define('CP_USERS_AND_GLOBAL', 2);
131 * These numbers are used in stored permissions
132 * and existing allocations MUST NEVER BE CHANGED
133 * OR RE-ASSIGNED! You may only add to them.
136 Protocol::DFRN => (-1),
137 Protocol::ZOT => (-2),
138 Protocol::OSTATUS => (-3),
139 Protocol::FEED => (-4),
140 Protocol::DIASPORA => (-5),
141 Protocol::MAIL => (-6),
142 Protocol::FACEBOOK => (-8),
143 Protocol::LINKEDIN => (-9),
144 Protocol::XMPP => (-10),
145 Protocol::MYSPACE => (-11),
146 Protocol::GPLUS => (-12),
147 Protocol::PUMPIO => (-13),
148 Protocol::TWITTER => (-14),
149 Protocol::DIASPORA2 => (-15),
150 Protocol::STATUSNET => (-16),
151 Protocol::NEWS => (-18),
152 Protocol::ICALENDAR => (-19),
153 Protocol::PNUT => (-20),
155 Protocol::PHANTOM => (-127),
159 * Maximum number of "people who like (or don't like) this" that we will list by name
161 define('MAX_LIKERS', 75);
166 * Email notification options
169 define('NOTIFY_INTRO', 0x0001);
170 define('NOTIFY_CONFIRM', 0x0002);
171 define('NOTIFY_WALL', 0x0004);
172 define('NOTIFY_COMMENT', 0x0008);
173 define('NOTIFY_MAIL', 0x0010);
174 define('NOTIFY_SUGGEST', 0x0020);
175 define('NOTIFY_PROFILE', 0x0040);
176 define('NOTIFY_TAGSELF', 0x0080);
177 define('NOTIFY_TAGSHARE', 0x0100);
178 define('NOTIFY_POKE', 0x0200);
179 define('NOTIFY_SHARE', 0x0400);
181 define('SYSTEM_EMAIL', 0x4000);
183 define('NOTIFY_SYSTEM', 0x8000);
193 define('TERM_UNKNOWN', 0);
194 define('TERM_HASHTAG', 1);
195 define('TERM_MENTION', 2);
196 define('TERM_CATEGORY', 3);
197 define('TERM_PCATEGORY', 4);
198 define('TERM_FILE', 5);
199 define('TERM_SAVEDSEARCH', 6);
200 define('TERM_CONVERSATION', 7);
202 define('TERM_OBJ_POST', 1);
203 define('TERM_OBJ_PHOTO', 2);
208 * Various namespaces we may need to parse
211 define('NAMESPACE_ZOT', 'http://purl.org/zot');
212 define('NAMESPACE_DFRN', 'http://purl.org/macgirvin/dfrn/1.0');
213 define('NAMESPACE_THREAD', 'http://purl.org/syndication/thread/1.0');
214 define('NAMESPACE_TOMB', 'http://purl.org/atompub/tombstones/1.0');
215 define('NAMESPACE_ACTIVITY', 'http://activitystrea.ms/spec/1.0/');
216 define('NAMESPACE_ACTIVITY_SCHEMA', 'http://activitystrea.ms/schema/1.0/');
217 define('NAMESPACE_MEDIA', 'http://purl.org/syndication/atommedia');
218 define('NAMESPACE_SALMON_ME', 'http://salmon-protocol.org/ns/magic-env');
219 define('NAMESPACE_OSTATUSSUB', 'http://ostatus.org/schema/1.0/subscribe');
220 define('NAMESPACE_GEORSS', 'http://www.georss.org/georss');
221 define('NAMESPACE_POCO', 'http://portablecontacts.net/spec/1.0');
222 define('NAMESPACE_FEED', 'http://schemas.google.com/g/2010#updates-from');
223 define('NAMESPACE_OSTATUS', 'http://ostatus.org/schema/1.0');
224 define('NAMESPACE_STATUSNET', 'http://status.net/schema/api/1/');
225 define('NAMESPACE_ATOM1', 'http://www.w3.org/2005/Atom');
226 define('NAMESPACE_MASTODON', 'http://mastodon.social/schema/1.0');
232 * Activity stream defines
235 define('ACTIVITY_LIKE', NAMESPACE_ACTIVITY_SCHEMA . 'like');
236 define('ACTIVITY_DISLIKE', NAMESPACE_DFRN . '/dislike');
237 define('ACTIVITY_ATTEND', NAMESPACE_ZOT . '/activity/attendyes');
238 define('ACTIVITY_ATTENDNO', NAMESPACE_ZOT . '/activity/attendno');
239 define('ACTIVITY_ATTENDMAYBE', NAMESPACE_ZOT . '/activity/attendmaybe');
241 define('ACTIVITY_OBJ_HEART', NAMESPACE_DFRN . '/heart');
243 define('ACTIVITY_FRIEND', NAMESPACE_ACTIVITY_SCHEMA . 'make-friend');
244 define('ACTIVITY_REQ_FRIEND', NAMESPACE_ACTIVITY_SCHEMA . 'request-friend');
245 define('ACTIVITY_UNFRIEND', NAMESPACE_ACTIVITY_SCHEMA . 'remove-friend');
246 define('ACTIVITY_FOLLOW', NAMESPACE_ACTIVITY_SCHEMA . 'follow');
247 define('ACTIVITY_UNFOLLOW', NAMESPACE_ACTIVITY_SCHEMA . 'stop-following');
248 define('ACTIVITY_JOIN', NAMESPACE_ACTIVITY_SCHEMA . 'join');
250 define('ACTIVITY_POST', NAMESPACE_ACTIVITY_SCHEMA . 'post');
251 define('ACTIVITY_UPDATE', NAMESPACE_ACTIVITY_SCHEMA . 'update');
252 define('ACTIVITY_TAG', NAMESPACE_ACTIVITY_SCHEMA . 'tag');
253 define('ACTIVITY_FAVORITE', NAMESPACE_ACTIVITY_SCHEMA . 'favorite');
254 define('ACTIVITY_UNFAVORITE', NAMESPACE_ACTIVITY_SCHEMA . 'unfavorite');
255 define('ACTIVITY_SHARE', NAMESPACE_ACTIVITY_SCHEMA . 'share');
256 define('ACTIVITY_DELETE', NAMESPACE_ACTIVITY_SCHEMA . 'delete');
258 define('ACTIVITY_POKE', NAMESPACE_ZOT . '/activity/poke');
260 define('ACTIVITY_OBJ_BOOKMARK', NAMESPACE_ACTIVITY_SCHEMA . 'bookmark');
261 define('ACTIVITY_OBJ_COMMENT', NAMESPACE_ACTIVITY_SCHEMA . 'comment');
262 define('ACTIVITY_OBJ_NOTE', NAMESPACE_ACTIVITY_SCHEMA . 'note');
263 define('ACTIVITY_OBJ_PERSON', NAMESPACE_ACTIVITY_SCHEMA . 'person');
264 define('ACTIVITY_OBJ_IMAGE', NAMESPACE_ACTIVITY_SCHEMA . 'image');
265 define('ACTIVITY_OBJ_PHOTO', NAMESPACE_ACTIVITY_SCHEMA . 'photo');
266 define('ACTIVITY_OBJ_VIDEO', NAMESPACE_ACTIVITY_SCHEMA . 'video');
267 define('ACTIVITY_OBJ_P_PHOTO', NAMESPACE_ACTIVITY_SCHEMA . 'profile-photo');
268 define('ACTIVITY_OBJ_ALBUM', NAMESPACE_ACTIVITY_SCHEMA . 'photo-album');
269 define('ACTIVITY_OBJ_EVENT', NAMESPACE_ACTIVITY_SCHEMA . 'event');
270 define('ACTIVITY_OBJ_GROUP', NAMESPACE_ACTIVITY_SCHEMA . 'group');
271 define('ACTIVITY_OBJ_TAGTERM', NAMESPACE_DFRN . '/tagterm');
272 define('ACTIVITY_OBJ_PROFILE', NAMESPACE_DFRN . '/profile');
273 define('ACTIVITY_OBJ_QUESTION', 'http://activityschema.org/object/question');
279 * Item weight for query ordering
282 define('GRAVITY_PARENT', 0);
283 define('GRAVITY_ACTIVITY', 3);
284 define('GRAVITY_COMMENT', 6);
285 define('GRAVITY_UNKNOWN', 9);
291 * Process priority for the worker
294 define('PRIORITY_UNDEFINED', 0);
295 define('PRIORITY_CRITICAL', 10);
296 define('PRIORITY_HIGH', 20);
297 define('PRIORITY_MEDIUM', 30);
298 define('PRIORITY_LOW', 40);
299 define('PRIORITY_NEGLIGIBLE', 50);
303 * @name Social Relay settings
305 * See here: https://github.com/jaywink/social-relay
306 * and here: https://wiki.diasporafoundation.org/Relay_servers_for_public_posts
309 define('SR_SCOPE_NONE', '');
310 define('SR_SCOPE_ALL', 'all');
311 define('SR_SCOPE_TAGS', 'tags');
314 // Normally this constant is defined - but not if "pcntl" isn't installed
315 if (!defined("SIGTERM")) {
316 define("SIGTERM", 15);
320 * Depending on the PHP version this constant does exist - or not.
321 * See here: http://php.net/manual/en/curl.constants.php#117928
323 if (!defined('CURLE_OPERATION_TIMEDOUT')) {
324 define('CURLE_OPERATION_TIMEDOUT', CURLE_OPERATION_TIMEOUTED);
328 * @brief Retrieve the App structure
330 * Useful in functions which require it but don't get it passed to them
336 return BaseObject::getApp();
340 * @brief Multi-purpose function to check variable state.
342 * Usage: x($var) or $x($array, 'key')
344 * returns false if variable/key is not set
345 * if variable is set, returns 1 if has 'non-zero' value, otherwise returns 0.
346 * e.g. x('') or x(0) returns 0;
348 * @param string|array $s variable to check
349 * @param string $k key inside the array to check
353 function x($s, $k = null)
356 if ((is_array($s)) && (array_key_exists($k, $s))) {
375 * Return the provided variable value if it exists and is truthy or the provided
376 * default value instead.
378 * Works with initialized variables and potentially uninitialized array keys
381 * - defaults($var, $default)
382 * - defaults($array, 'key', $default)
384 * @brief Returns a defaut value if the provided variable or array key is falsy
388 function defaults() {
389 $args = func_get_args();
391 if (count($args) < 2) {
392 throw new BadFunctionCallException('defaults() requires at least 2 parameters');
394 if (count($args) > 3) {
395 throw new BadFunctionCallException('defaults() cannot use more than 3 parameters');
397 if (count($args) === 3 && is_null($args[1])) {
398 throw new BadFunctionCallException('defaults($arr, $key, $def) $key is null');
401 $default = array_pop($args);
403 if (call_user_func_array('x', $args)) {
404 if (count($args) === 1) {
407 $return = $args[0][$args[1]];
417 * @brief Used to end the current process, after saving session state.
426 * @brief Returns the user id of locally logged in user or false.
428 * @return int|bool user id or false
430 function local_user()
432 if (!empty($_SESSION['authenticated']) && !empty($_SESSION['uid'])) {
433 return intval($_SESSION['uid']);
439 * @brief Returns the public contact id of logged in user or false.
441 * @return int|bool public contact id or false
443 function public_contact()
445 static $public_contact_id = false;
447 if (!$public_contact_id && x($_SESSION, 'authenticated')) {
448 if (x($_SESSION, 'my_address')) {
450 $public_contact_id = intval(Contact::getIdForURL($_SESSION['my_address'], 0, true));
451 } elseif (x($_SESSION, 'visitor_home')) {
453 $public_contact_id = intval(Contact::getIdForURL($_SESSION['visitor_home'], 0, true));
455 } elseif (!x($_SESSION, 'authenticated')) {
456 $public_contact_id = false;
459 return $public_contact_id;
463 * @brief Returns contact id of authenticated site visitor or false
465 * @return int|bool visitor_id or false
467 function remote_user()
469 // You cannot be both local and remote.
470 // Unncommented by rabuzarus because remote authentication to local
471 // profiles wasn't possible anymore (2018-04-12).
472 // if (local_user()) {
476 if (empty($_SESSION)) {
480 if (x($_SESSION, 'authenticated') && x($_SESSION, 'visitor_id')) {
481 return intval($_SESSION['visitor_id']);
487 * @brief Show an error message to user.
489 * This function save text in session, to be shown to the user at next page load
491 * @param string $s - Text of notice
495 if (empty($_SESSION)) {
500 if (!x($_SESSION, 'sysmsg')) {
501 $_SESSION['sysmsg'] = [];
503 if ($a->interactive) {
504 $_SESSION['sysmsg'][] = $s;
509 * @brief Show an info message to user.
511 * This function save text in session, to be shown to the user at next page load
513 * @param string $s - Text of notice
519 if (local_user() && PConfig::get(local_user(), 'system', 'ignore_info')) {
523 if (!x($_SESSION, 'sysmsg_info')) {
524 $_SESSION['sysmsg_info'] = [];
526 if ($a->interactive) {
527 $_SESSION['sysmsg_info'][] = $s;
531 function feed_birthday($uid, $tz)
534 * Determine the next birthday, but only if the birthday is published
535 * in the default profile. We _could_ also look for a private profile that the
536 * recipient can see, but somebody could get mad at us if they start getting
537 * public birthday greetings when they haven't made this info public.
539 * Assuming we are able to publish this info, we are then going to convert
540 * the start time from the owner's timezone to UTC.
542 * This will potentially solve the problem found with some social networks
543 * where birthdays are converted to the viewer's timezone and salutations from
544 * elsewhere in the world show up on the wrong day. We will convert it to the
545 * viewer's timezone also, but first we are going to convert it from the birthday
546 * person's timezone to GMT - so the viewer may find the birthday starting at
547 * 6:00PM the day before, but that will correspond to midnight to the birthday person.
555 $profile = DBA::selectFirst('profile', ['dob'], ['is-default' => true, 'uid' => $uid]);
556 if (DBA::isResult($profile)) {
557 $tmp_dob = substr($profile['dob'], 5);
558 if (intval($tmp_dob)) {
559 $y = DateTimeFormat::timezoneNow($tz, 'Y');
560 $bd = $y . '-' . $tmp_dob . ' 00:00';
561 $t_dob = strtotime($bd);
562 $now = strtotime(DateTimeFormat::timezoneNow($tz));
564 $bd = $y + 1 . '-' . $tmp_dob . ' 00:00';
566 $birthday = DateTimeFormat::convert($bd, 'UTC', $tz, DateTimeFormat::ATOM);
574 * @brief Check if current user has admin role.
576 * @return bool true if user is an admin
578 function is_site_admin()
582 $admin_email = Config::get('config', 'admin_email');
584 $adminlist = explode(',', str_replace(' ', '', $admin_email));
586 return local_user() && $admin_email && in_array(defaults($a->user, 'email', ''), $adminlist);
590 * @brief Returns querystring as string from a mapped array.
592 * @param array $params mapped array with query parameters
593 * @param string $name of parameter, default null
597 function build_querystring($params, $name = null)
600 foreach ($params as $key => $val) {
601 if (is_array($val)) {
602 /// @TODO maybe not compare against null, use is_null()
604 $ret .= build_querystring($val, $key);
606 $ret .= build_querystring($val, $name . "[$key]");
609 $val = urlencode($val);
610 /// @TODO maybe not compare against null, use is_null()
612 /// @TODO two string concated, can be merged to one
613 $ret .= $name . "[$key]" . "=$val&";
615 $ret .= "$key=$val&";
622 function explode_querystring($query)
624 $arg_st = strpos($query, '?');
625 if ($arg_st !== false) {
626 $base = substr($query, 0, $arg_st);
633 $args = explode('&', substr($query, $arg_st));
634 foreach ($args as $k => $arg) {
635 /// @TODO really compare type-safe here?
640 $args = array_values($args);
645 $args = array_values($args);
655 * Returns the complete URL of the current page, e.g.: http(s)://something.com/network
657 * Taken from http://webcheatsheet.com/php/get_current_page_url.php
659 function curPageURL()
662 if (!empty($_SERVER["HTTPS"]) && ($_SERVER["HTTPS"] == "on")) {
668 if ($_SERVER["SERVER_PORT"] != "80" && $_SERVER["SERVER_PORT"] != "443") {
669 $pageURL .= $_SERVER["SERVER_NAME"] . ":" . $_SERVER["SERVER_PORT"] . $_SERVER["REQUEST_URI"];
671 $pageURL .= $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"];
676 function get_server()
678 $server = Config::get("system", "directory");
681 $server = "https://dir.friendica.social";
687 function get_temppath()
691 $temppath = Config::get("system", "temppath");
693 if (($temppath != "") && App::isDirectoryUsable($temppath)) {
694 // We have a temp path and it is usable
695 return App::getRealPath($temppath);
698 // We don't have a working preconfigured temp path, so we take the system path.
699 $temppath = sys_get_temp_dir();
701 // Check if it is usable
702 if (($temppath != "") && App::isDirectoryUsable($temppath)) {
703 // Always store the real path, not the path through symlinks
704 $temppath = App::getRealPath($temppath);
706 // To avoid any interferences with other systems we create our own directory
707 $new_temppath = $temppath . "/" . $a->getHostName();
708 if (!is_dir($new_temppath)) {
709 /// @TODO There is a mkdir()+chmod() upwards, maybe generalize this (+ configurable) into a function/method?
710 mkdir($new_temppath);
713 if (App::isDirectoryUsable($new_temppath)) {
714 // The new path is usable, we are happy
715 Config::set("system", "temppath", $new_temppath);
716 return $new_temppath;
718 // We can't create a subdirectory, strange.
719 // But the directory seems to work, so we use it but don't store it.
724 // Reaching this point means that the operating system is configured badly.
728 function get_cachefile($file, $writemode = true)
730 $cache = get_itemcachepath();
732 if ((!$cache) || (!is_dir($cache))) {
736 $subfolder = $cache . "/" . substr($file, 0, 2);
738 $cachepath = $subfolder . "/" . $file;
741 if (!is_dir($subfolder)) {
743 chmod($subfolder, 0777);
750 function clear_cache($basepath = "", $path = "")
753 $basepath = get_itemcachepath();
757 if (($path == "") || (!is_dir($path))) {
761 if (substr(realpath($path), 0, strlen($basepath)) != $basepath) {
765 $cachetime = (int) Config::get('system', 'itemcache_duration');
766 if ($cachetime == 0) {
770 if (is_writable($path)) {
771 if ($dh = opendir($path)) {
772 while (($file = readdir($dh)) !== false) {
773 $fullpath = $path . "/" . $file;
774 if ((filetype($fullpath) == "dir") && ($file != ".") && ($file != "..")) {
775 clear_cache($basepath, $fullpath);
777 if ((filetype($fullpath) == "file") && (filectime($fullpath) < (time() - $cachetime))) {
786 function get_itemcachepath()
788 // Checking, if the cache is deactivated
789 $cachetime = (int) Config::get('system', 'itemcache_duration');
790 if ($cachetime < 0) {
794 $itemcache = Config::get('system', 'itemcache');
795 if (($itemcache != "") && App::isDirectoryUsable($itemcache)) {
796 return App::getRealPath($itemcache);
799 $temppath = get_temppath();
801 if ($temppath != "") {
802 $itemcache = $temppath . "/itemcache";
803 if (!file_exists($itemcache) && !is_dir($itemcache)) {
807 if (App::isDirectoryUsable($itemcache)) {
808 Config::set("system", "itemcache", $itemcache);
816 * @brief Returns the path where spool files are stored
818 * @return string Spool path
820 function get_spoolpath()
822 $spoolpath = Config::get('system', 'spoolpath');
823 if (($spoolpath != "") && App::isDirectoryUsable($spoolpath)) {
824 // We have a spool path and it is usable
828 // We don't have a working preconfigured spool path, so we take the temp path.
829 $temppath = get_temppath();
831 if ($temppath != "") {
832 // To avoid any interferences with other systems we create our own directory
833 $spoolpath = $temppath . "/spool";
834 if (!is_dir($spoolpath)) {
838 if (App::isDirectoryUsable($spoolpath)) {
839 // The new path is usable, we are happy
840 Config::set("system", "spoolpath", $spoolpath);
843 // We can't create a subdirectory, strange.
844 // But the directory seems to work, so we use it but don't store it.
849 // Reaching this point means that the operating system is configured badly.
853 if (!function_exists('exif_imagetype')) {
854 function exif_imagetype($file)
856 $size = getimagesize($file);
861 function validate_include(&$file)
865 $file = realpath($file);
867 if (strpos($file, getcwd()) !== 0) {
871 $file = str_replace(getcwd() . "/", "", $file, $count);
876 if ($orig_file !== $file) {
881 if (strpos($file, "include/") === 0) {
885 if (strpos($file, "addon/") === 0) {
889 // Simply return flag