7 use Friendica\Core\Config;
8 use Friendica\Core\L10n;
9 use Friendica\Core\PConfig;
10 use Friendica\Core\System;
11 use Friendica\Database\DBM;
14 use Detection\MobileDetect;
18 require_once 'boot.php';
19 require_once 'include/dba.php';
20 require_once 'include/text.php';
26 * @brief Our main application structure for the life of this page.
28 * Primarily deals with the URL that got us here
29 * and tries to make some sense of it, and
30 * stores our page contents and config storage
31 * and anything else that might need to be passed around
32 * before we spit the page out.
37 const MODE_LOCALCONFIGPRESENT = 1;
38 const MODE_DBAVAILABLE = 2;
39 const MODE_DBCONFIGAVAILABLE = 4;
40 const MODE_MAINTENANCEDISABLED = 8;
43 * @deprecated since version 2008.08 Use App->isInstallMode() instead to check for install mode.
45 const MODE_INSTALL = 0;
48 * @deprecated since version 2008.08 Use the precise mode constant to check for a specific capability instead.
50 const MODE_NORMAL = App::MODE_LOCALCONFIGPRESENT | App::MODE_DBAVAILABLE | App::MODE_DBCONFIGAVAILABLE | App::MODE_MAINTENANCEDISABLED;
52 public $module_loaded = false;
53 public $module_class = null;
54 public $query_string = '';
68 public $error = false;
73 public $mode = App::MODE_INSTALL;
79 public $interactive = true;
81 public $addons_admin = [];
84 public $is_mobile = false;
85 public $is_tablet = false;
86 public $is_friendica_app;
87 public $performance = [];
88 public $callstack = [];
89 public $theme_info = [];
90 public $backend = true;
93 // Allow themes to control internal parameters
94 // by changing App values in theme.php
96 public $sourcename = '';
97 public $videowidth = 425;
98 public $videoheight = 350;
99 public $force_max_items = 0;
100 public $theme_events_in_profile = true;
103 * @brief An array for all theme-controllable parameters
105 * Mostly unimplemented yet. Only options 'template_engine' and
111 'videoheight' => 350,
112 'force_max_items' => 0,
114 'template_engine' => 'smarty3',
118 * @brief An array of registered template engines ('name'=>'class name')
120 public $template_engines = [];
123 * @brief An array of instanced template engines ('name'=>'instance')
125 public $template_engine_instance = [];
139 private $curl_content_type;
140 private $curl_headers;
143 * @brief App constructor.
145 * @param string $basepath Path to the app base folder
147 public function __construct($basepath)
149 if (!static::directory_usable($basepath, false)) {
150 throw new Exception('Basepath ' . $basepath . ' isn\'t usable.');
153 BaseObject::setApp($this);
155 $this->basepath = rtrim($basepath, DIRECTORY_SEPARATOR);
157 // The order of the following calls is important to ensure proper initialization
158 $this->loadConfigFiles();
160 $this->loadDatabase();
162 $this->determineMode();
164 $this->determineUrlPath();
168 if ($this->mode & self::MODE_DBAVAILABLE) {
169 Core\Addon::loadHooks();
171 $this->loadAddonConfig();
174 $this->loadDefaultTimezone();
176 $this->performance['start'] = microtime(true);
177 $this->performance['database'] = 0;
178 $this->performance['database_write'] = 0;
179 $this->performance['cache'] = 0;
180 $this->performance['cache_write'] = 0;
181 $this->performance['network'] = 0;
182 $this->performance['file'] = 0;
183 $this->performance['rendering'] = 0;
184 $this->performance['parser'] = 0;
185 $this->performance['marktime'] = 0;
186 $this->performance['markstart'] = microtime(true);
188 $this->callstack['database'] = [];
189 $this->callstack['database_write'] = [];
190 $this->callstack['cache'] = [];
191 $this->callstack['cache_write'] = [];
192 $this->callstack['network'] = [];
193 $this->callstack['file'] = [];
194 $this->callstack['rendering'] = [];
195 $this->callstack['parser'] = [];
211 $this->process_id = System::processID('log');
215 // This has to be quite large to deal with embedded private photos
216 ini_set('pcre.backtrack_limit', 500000);
218 $this->scheme = 'http';
220 if ((x($_SERVER, 'HTTPS') && $_SERVER['HTTPS']) ||
221 (x($_SERVER, 'HTTP_FORWARDED') && preg_match('/proto=https/', $_SERVER['HTTP_FORWARDED'])) ||
222 (x($_SERVER, 'HTTP_X_FORWARDED_PROTO') && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') ||
223 (x($_SERVER, 'HTTP_X_FORWARDED_SSL') && $_SERVER['HTTP_X_FORWARDED_SSL'] == 'on') ||
224 (x($_SERVER, 'FRONT_END_HTTPS') && $_SERVER['FRONT_END_HTTPS'] == 'on') ||
225 (x($_SERVER, 'SERVER_PORT') && (intval($_SERVER['SERVER_PORT']) == 443)) // XXX: reasonable assumption, but isn't this hardcoding too much?
227 $this->scheme = 'https';
230 if (x($_SERVER, 'SERVER_NAME')) {
231 $this->hostname = $_SERVER['SERVER_NAME'];
233 if (x($_SERVER, 'SERVER_PORT') && $_SERVER['SERVER_PORT'] != 80 && $_SERVER['SERVER_PORT'] != 443) {
234 $this->hostname .= ':' . $_SERVER['SERVER_PORT'];
239 get_include_path() . PATH_SEPARATOR
240 . $this->basepath . DIRECTORY_SEPARATOR . 'include' . PATH_SEPARATOR
241 . $this->basepath . DIRECTORY_SEPARATOR . 'library' . PATH_SEPARATOR
244 if ((x($_SERVER, 'QUERY_STRING')) && substr($_SERVER['QUERY_STRING'], 0, 9) === 'pagename=') {
245 $this->query_string = substr($_SERVER['QUERY_STRING'], 9);
246 } elseif ((x($_SERVER, 'QUERY_STRING')) && substr($_SERVER['QUERY_STRING'], 0, 2) === 'q=') {
247 $this->query_string = substr($_SERVER['QUERY_STRING'], 2);
250 // removing trailing / - maybe a nginx problem
251 $this->query_string = ltrim($this->query_string, '/');
253 if (!empty($_GET['pagename'])) {
254 $this->cmd = trim($_GET['pagename'], '/\\');
255 } elseif (!empty($_GET['q'])) {
256 $this->cmd = trim($_GET['q'], '/\\');
260 $this->query_string = str_replace($this->cmd . '&', $this->cmd . '?', $this->query_string);
262 // unix style "homedir"
263 if (substr($this->cmd, 0, 1) === '~') {
264 $this->cmd = 'profile/' . substr($this->cmd, 1);
267 // Diaspora style profile url
268 if (substr($this->cmd, 0, 2) === 'u/') {
269 $this->cmd = 'profile/' . substr($this->cmd, 2);
273 * Break the URL path into C style argc/argv style arguments for our
274 * modules. Given "http://example.com/module/arg1/arg2", $this->argc
275 * will be 3 (integer) and $this->argv will contain:
281 * There will always be one argument. If provided a naked domain
282 * URL, $this->argv[0] is set to "home".
285 $this->argv = explode('/', $this->cmd);
286 $this->argc = count($this->argv);
287 if ((array_key_exists('0', $this->argv)) && strlen($this->argv[0])) {
288 $this->module = str_replace('.', '_', $this->argv[0]);
289 $this->module = str_replace('-', '_', $this->module);
292 $this->argv = ['home'];
293 $this->module = 'home';
296 // See if there is any page number information, and initialise pagination
297 $this->pager['page'] = ((x($_GET, 'page') && intval($_GET['page']) > 0) ? intval($_GET['page']) : 1);
298 $this->pager['itemspage'] = 50;
299 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
301 if ($this->pager['start'] < 0) {
302 $this->pager['start'] = 0;
304 $this->pager['total'] = 0;
306 // Detect mobile devices
307 $mobile_detect = new MobileDetect();
308 $this->is_mobile = $mobile_detect->isMobile();
309 $this->is_tablet = $mobile_detect->isTablet();
312 $this->is_friendica_app = isset($_SERVER['HTTP_USER_AGENT']) && $_SERVER['HTTP_USER_AGENT'] == 'Apache-HttpClient/UNAVAILABLE (java 1.4)';
314 // Register template engines
315 $this->register_template_engine('Friendica\Render\FriendicaSmartyEngine');
319 * Load the configuration files
321 * First loads the default value for all the configuration keys, then the legacy configuration files, then the
322 * expected local.ini.php
324 private function loadConfigFiles()
326 $this->loadConfigFile($this->basepath . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'config.ini.php');
327 $this->loadConfigFile($this->basepath . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'settings.ini.php');
329 // Legacy .htconfig.php support
330 if (file_exists($this->basepath . DIRECTORY_SEPARATOR . '.htpreconfig.php')) {
332 include $this->basepath . DIRECTORY_SEPARATOR . '.htpreconfig.php';
335 // Legacy .htconfig.php support
336 if (file_exists($this->basepath . DIRECTORY_SEPARATOR . '.htconfig.php')) {
339 include $this->basepath . DIRECTORY_SEPARATOR . '.htconfig.php';
341 $this->setConfigValue('database', 'hostname', $db_host);
342 $this->setConfigValue('database', 'username', $db_user);
343 $this->setConfigValue('database', 'password', $db_pass);
344 $this->setConfigValue('database', 'database', $db_data);
345 if (isset($a->config['system']['db_charset'])) {
346 $this->setConfigValue('database', 'charset', $a->config['system']['db_charset']);
349 unset($db_host, $db_user, $db_pass, $db_data);
351 if (isset($default_timezone)) {
352 $this->setConfigValue('system', 'default_timezone', $default_timezone);
353 unset($default_timezone);
356 if (isset($pidfile)) {
357 $this->setConfigValue('system', 'pidfile', $pidfile);
362 if (file_exists($this->basepath . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'local.ini.php')) {
363 $this->loadConfigFile($this->basepath . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'local.ini.php');
368 * Tries to load the specified configuration file into the App->config array.
369 * Overwrites previously set values.
371 * The config format is INI and the template for configuration files is the following:
373 * <?php return <<<INI
381 * @param type $filepath
384 public function loadConfigFile($filepath)
386 if (!file_exists($filepath)) {
387 throw new Exception('Error parsing non-existent config file ' . $filepath);
390 $contents = include($filepath);
392 $config = parse_ini_string($contents, true, INI_SCANNER_TYPED);
394 if ($config === false) {
395 throw new Exception('Error parsing config file ' . $filepath);
398 foreach ($config as $category => $values) {
399 foreach ($values as $key => $value) {
400 $this->setConfigValue($category, $key, $value);
406 * Loads addons configuration files
408 * First loads all activated addons default configuration throught the load_config hook, then load the local.ini.php
409 * again to overwrite potential local addon configuration.
411 private function loadAddonConfig()
413 // Loads addons default config
414 Core\Addon::callHooks('load_config');
416 // Load the local addon config file to overwritten default addon config values
417 if (file_exists($this->basepath . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'addon.ini.php')) {
418 $this->loadConfigFile($this->basepath . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'addon.ini.php');
423 * Loads the default timezone
425 * Include support for legacy $default_timezone
427 * @global string $default_timezone
429 private function loadDefaultTimezone()
431 if ($this->getConfigValue('system', 'default_timezone')) {
432 $this->timezone = $this->getConfigValue('system', 'default_timezone');
434 global $default_timezone;
435 $this->timezone = !empty($default_timezone) ? $default_timezone : 'UTC';
438 if ($this->timezone) {
439 date_default_timezone_set($this->timezone);
444 * Figure out if we are running at the top of a domain or in a sub-directory and adjust accordingly
446 private function determineUrlPath()
448 $this->urlpath = $this->getConfigValue('system', 'urlpath');
450 /* SCRIPT_URL gives /path/to/friendica/module/parameter
451 * QUERY_STRING gives pagename=module/parameter
453 * To get /path/to/friendica we perform dirname() for as many levels as there are slashes in the QUERY_STRING
455 if (!empty($_SERVER['SCRIPT_URL'])) {
457 if (!empty($_SERVER['QUERY_STRING'])) {
458 $path = trim(dirname($_SERVER['SCRIPT_URL'], substr_count(trim($_SERVER['QUERY_STRING'], '/'), '/') + 1), '/');
461 $path = trim($_SERVER['SCRIPT_URL'], '/');
464 if ($path && $path != $this->urlpath) {
465 $this->urlpath = $path;
473 * - App::MODE_INSTALL : Either the database connection can't be established or the config table doesn't exist
474 * - App::MODE_MAINTENANCE: The maintenance mode has been set
475 * - App::MODE_NORMAL : Normal run with all features enabled
479 private function determineMode()
483 if (!file_exists($this->basepath . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'local.ini.php')
484 && !file_exists($this->basepath . DIRECTORY_SEPARATOR . '.htconfig.php')) {
488 $this->mode |= App::MODE_LOCALCONFIGPRESENT;
490 if (!\dba::connected()) {
494 $this->mode |= App::MODE_DBAVAILABLE;
496 if (\dba::fetch_first("SHOW TABLES LIKE 'config'") === false) {
500 $this->mode |= App::MODE_DBCONFIGAVAILABLE;
502 if (Config::get('system', 'maintenance')) {
506 $this->mode |= App::MODE_MAINTENANCEDISABLED;
509 public function loadDatabase()
511 if (\dba::connected()) {
515 $db_host = $this->getConfigValue('database', 'hostname');
516 $db_user = $this->getConfigValue('database', 'username');
517 $db_pass = $this->getConfigValue('database', 'password');
518 $db_data = $this->getConfigValue('database', 'database');
519 $charset = $this->getConfigValue('database', 'charset');
521 // Use environment variables for mysql if they are set beforehand
522 if (!empty(getenv('MYSQL_HOST'))
523 && (!empty(getenv('MYSQL_USERNAME')) || !empty(getenv('MYSQL_USER')))
524 && getenv('MYSQL_PASSWORD') !== false
525 && !empty(getenv('MYSQL_DATABASE')))
527 $db_host = getenv('MYSQL_HOST');
528 if (!empty(getenv('MYSQL_PORT'))) {
529 $db_host .= ':' . getenv('MYSQL_PORT');
531 if (!empty(getenv('MYSQL_USERNAME'))) {
532 $db_user = getenv('MYSQL_USERNAME');
534 $db_user = getenv('MYSQL_USER');
536 $db_pass = (string) getenv('MYSQL_PASSWORD');
537 $db_data = getenv('MYSQL_DATABASE');
540 $stamp1 = microtime(true);
542 \dba::connect($db_host, $db_user, $db_pass, $db_data, $charset);
543 unset($db_host, $db_user, $db_pass, $db_data, $charset);
545 $this->save_timestamp($stamp1, 'network');
549 * Install mode is when the local config file is missing or the DB schema hasn't been installed yet.
553 public function isInstallMode()
555 return !($this->mode & App::MODE_LOCALCONFIGPRESENT) || !($this->mode & App::MODE_DBCONFIGAVAILABLE);
559 * @brief Returns the base filesystem path of the App
561 * It first checks for the internal variable, then for DOCUMENT_ROOT and
566 public function get_basepath()
568 $basepath = $this->basepath;
571 $basepath = Config::get('system', 'basepath');
574 if (!$basepath && x($_SERVER, 'DOCUMENT_ROOT')) {
575 $basepath = $_SERVER['DOCUMENT_ROOT'];
578 if (!$basepath && x($_SERVER, 'PWD')) {
579 $basepath = $_SERVER['PWD'];
582 return self::realpath($basepath);
586 * @brief Returns a normalized file path
588 * This is a wrapper for the "realpath" function.
589 * That function cannot detect the real path when some folders aren't readable.
590 * Since this could happen with some hosters we need to handle this.
592 * @param string $path The path that is about to be normalized
593 * @return string normalized path - when possible
595 public static function realpath($path)
597 $normalized = realpath($path);
599 if (!is_bool($normalized)) {
606 public function get_scheme()
608 return $this->scheme;
612 * @brief Retrieves the Friendica instance base URL
614 * This function assembles the base URL from multiple parts:
615 * - Protocol is determined either by the request or a combination of
616 * system.ssl_policy and the $ssl parameter.
617 * - Host name is determined either by system.hostname or inferred from request
618 * - Path is inferred from SCRIPT_NAME
620 * Note: $ssl parameter value doesn't directly correlate with the resulting protocol
622 * @param bool $ssl Whether to append http or https under SSL_POLICY_SELFSIGN
623 * @return string Friendica server base URL
625 public function get_baseurl($ssl = false)
627 $scheme = $this->scheme;
629 if (Config::get('system', 'ssl_policy') == SSL_POLICY_FULL) {
633 // Basically, we have $ssl = true on any links which can only be seen by a logged in user
634 // (and also the login link). Anything seen by an outsider will have it turned off.
636 if (Config::get('system', 'ssl_policy') == SSL_POLICY_SELFSIGN) {
644 if (Config::get('config', 'hostname') != '') {
645 $this->hostname = Config::get('config', 'hostname');
648 return $scheme . '://' . $this->hostname . (!empty($this->urlpath) ? '/' . $this->urlpath : '' );
652 * @brief Initializes the baseurl components
654 * Clears the baseurl cache to prevent inconsistencies
658 public function set_baseurl($url)
660 $parsed = @parse_url($url);
664 if (!empty($parsed['scheme'])) {
665 $this->scheme = $parsed['scheme'];
668 if (!empty($parsed['host'])) {
669 $hostname = $parsed['host'];
672 if (x($parsed, 'port')) {
673 $hostname .= ':' . $parsed['port'];
675 if (x($parsed, 'path')) {
676 $this->urlpath = trim($parsed['path'], '\\/');
679 if (file_exists($this->basepath . DIRECTORY_SEPARATOR . '.htpreconfig.php')) {
680 include $this->basepath . DIRECTORY_SEPARATOR . '.htpreconfig.php';
683 if (Config::get('config', 'hostname') != '') {
684 $this->hostname = Config::get('config', 'hostname');
687 if (!isset($this->hostname) || ($this->hostname == '')) {
688 $this->hostname = $hostname;
693 public function get_hostname()
695 if (Config::get('config', 'hostname') != '') {
696 $this->hostname = Config::get('config', 'hostname');
699 return $this->hostname;
702 public function get_path()
704 return $this->urlpath;
707 public function set_pager_total($n)
709 $this->pager['total'] = intval($n);
712 public function set_pager_itemspage($n)
714 $this->pager['itemspage'] = ((intval($n) > 0) ? intval($n) : 0);
715 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
718 public function set_pager_page($n)
720 $this->pager['page'] = $n;
721 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
724 public function init_pagehead()
726 $interval = ((local_user()) ? PConfig::get(local_user(), 'system', 'update_interval') : 40000);
728 // If the update is 'deactivated' set it to the highest integer number (~24 days)
730 $interval = 2147483647;
733 if ($interval < 10000) {
737 // compose the page title from the sitename and the
738 // current module called
739 if (!$this->module == '') {
740 $this->page['title'] = $this->config['sitename'] . ' (' . $this->module . ')';
742 $this->page['title'] = $this->config['sitename'];
745 /* put the head template at the beginning of page['htmlhead']
746 * since the code added by the modules frequently depends on it
749 if (!isset($this->page['htmlhead'])) {
750 $this->page['htmlhead'] = '';
753 // If we're using Smarty, then doing replace_macros() will replace
754 // any unrecognized variables with a blank string. Since we delay
755 // replacing $stylesheet until later, we need to replace it now
756 // with another variable name
757 if ($this->theme['template_engine'] === 'smarty3') {
758 $stylesheet = $this->get_template_ldelim('smarty3') . '$stylesheet' . $this->get_template_rdelim('smarty3');
760 $stylesheet = '$stylesheet';
763 $shortcut_icon = Config::get('system', 'shortcut_icon');
764 if ($shortcut_icon == '') {
765 $shortcut_icon = 'images/friendica-32.png';
768 $touch_icon = Config::get('system', 'touch_icon');
769 if ($touch_icon == '') {
770 $touch_icon = 'images/friendica-128.png';
773 // get data wich is needed for infinite scroll on the network page
774 $invinite_scroll = infinite_scroll_data($this->module);
776 $tpl = get_markup_template('head.tpl');
777 $this->page['htmlhead'] = replace_macros($tpl, [
778 '$baseurl' => $this->get_baseurl(),
779 '$local_user' => local_user(),
780 '$generator' => 'Friendica' . ' ' . FRIENDICA_VERSION,
781 '$delitem' => L10n::t('Delete this item?'),
782 '$showmore' => L10n::t('show more'),
783 '$showfewer' => L10n::t('show fewer'),
784 '$update_interval' => $interval,
785 '$shortcut_icon' => $shortcut_icon,
786 '$touch_icon' => $touch_icon,
787 '$stylesheet' => $stylesheet,
788 '$infinite_scroll' => $invinite_scroll,
789 '$block_public' => intval(Config::get('system', 'block_public')),
790 ]) . $this->page['htmlhead'];
793 public function init_page_end()
795 if (!isset($this->page['end'])) {
796 $this->page['end'] = '';
798 $tpl = get_markup_template('end.tpl');
799 $this->page['end'] = replace_macros($tpl, [
800 '$baseurl' => $this->get_baseurl()
801 ]) . $this->page['end'];
804 public function set_curl_code($code)
806 $this->curl_code = $code;
809 public function get_curl_code()
811 return $this->curl_code;
814 public function set_curl_content_type($content_type)
816 $this->curl_content_type = $content_type;
819 public function get_curl_content_type()
821 return $this->curl_content_type;
824 public function set_curl_headers($headers)
826 $this->curl_headers = $headers;
829 public function get_curl_headers()
831 return $this->curl_headers;
835 * @brief Removes the base url from an url. This avoids some mixed content problems.
837 * @param string $orig_url
839 * @return string The cleaned url
841 public function remove_baseurl($orig_url)
843 // Remove the hostname from the url if it is an internal link
844 $nurl = normalise_link($orig_url);
845 $base = normalise_link($this->get_baseurl());
846 $url = str_replace($base . '/', '', $nurl);
848 // if it is an external link return the orignal value
849 if ($url == normalise_link($orig_url)) {
857 * @brief Register template engine class
859 * @param string $class
861 private function register_template_engine($class)
863 $v = get_class_vars($class);
866 $this->template_engines[$name] = $class;
868 echo "template engine <tt>$class</tt> cannot be registered without a name.\n";
874 * @brief Return template engine instance.
876 * If $name is not defined, return engine defined by theme,
879 * @return object Template Engine instance
881 public function template_engine()
883 $template_engine = 'smarty3';
884 if (x($this->theme, 'template_engine')) {
885 $template_engine = $this->theme['template_engine'];
888 if (isset($this->template_engines[$template_engine])) {
889 if (isset($this->template_engine_instance[$template_engine])) {
890 return $this->template_engine_instance[$template_engine];
892 $class = $this->template_engines[$template_engine];
894 $this->template_engine_instance[$template_engine] = $obj;
899 echo "template engine <tt>$template_engine</tt> is not registered!\n";
904 * @brief Returns the active template engine.
908 public function get_template_engine()
910 return $this->theme['template_engine'];
913 public function set_template_engine($engine = 'smarty3')
915 $this->theme['template_engine'] = $engine;
918 public function get_template_ldelim($engine = 'smarty3')
920 return $this->ldelim[$engine];
923 public function get_template_rdelim($engine = 'smarty3')
925 return $this->rdelim[$engine];
928 public function save_timestamp($stamp, $value)
930 if (!isset($this->config['system']['profiler']) || !$this->config['system']['profiler']) {
934 $duration = (float) (microtime(true) - $stamp);
936 if (!isset($this->performance[$value])) {
937 // Prevent ugly E_NOTICE
938 $this->performance[$value] = 0;
941 $this->performance[$value] += (float) $duration;
942 $this->performance['marktime'] += (float) $duration;
944 $callstack = System::callstack();
946 if (!isset($this->callstack[$value][$callstack])) {
947 // Prevent ugly E_NOTICE
948 $this->callstack[$value][$callstack] = 0;
951 $this->callstack[$value][$callstack] += (float) $duration;
954 public function get_useragent()
957 FRIENDICA_PLATFORM . " '" .
958 FRIENDICA_CODENAME . "' " .
959 FRIENDICA_VERSION . '-' .
960 DB_UPDATE_VERSION . '; ' .
961 $this->get_baseurl();
964 public function is_friendica_app()
966 return $this->is_friendica_app;
970 * @brief Checks if the site is called via a backend process
972 * This isn't a perfect solution. But we need this check very early.
973 * So we cannot wait until the modules are loaded.
975 * @return bool Is it a known backend?
977 public function is_backend()
1001 // Check if current module is in backend or backend flag is set
1002 return (in_array($this->module, $backends) || $this->backend);
1006 * @brief Checks if the maximum number of database processes is reached
1008 * @return bool Is the limit reached?
1010 public function isMaxProcessesReached()
1012 // Deactivated, needs more investigating if this check really makes sense
1016 * Commented out to suppress static analyzer issues
1018 if ($this->is_backend()) {
1019 $process = 'backend';
1020 $max_processes = Config::get('system', 'max_processes_backend');
1021 if (intval($max_processes) == 0) {
1025 $process = 'frontend';
1026 $max_processes = Config::get('system', 'max_processes_frontend');
1027 if (intval($max_processes) == 0) {
1028 $max_processes = 20;
1032 $processlist = DBM::processlist();
1033 if ($processlist['list'] != '') {
1034 logger('Processcheck: Processes: ' . $processlist['amount'] . ' - Processlist: ' . $processlist['list'], LOGGER_DEBUG);
1036 if ($processlist['amount'] > $max_processes) {
1037 logger('Processcheck: Maximum number of processes for ' . $process . ' tasks (' . $max_processes . ') reached.', LOGGER_DEBUG);
1046 * @brief Checks if the minimal memory is reached
1048 * @return bool Is the memory limit reached?
1050 public function min_memory_reached()
1052 $min_memory = Config::get('system', 'min_memory', 0);
1053 if ($min_memory == 0) {
1057 if (!is_readable('/proc/meminfo')) {
1061 $memdata = explode("\n", file_get_contents('/proc/meminfo'));
1064 foreach ($memdata as $line) {
1065 list($key, $val) = explode(':', $line);
1066 $meminfo[$key] = (int) trim(str_replace('kB', '', $val));
1067 $meminfo[$key] = (int) ($meminfo[$key] / 1024);
1070 if (!isset($meminfo['MemAvailable']) || !isset($meminfo['MemFree'])) {
1074 $free = $meminfo['MemAvailable'] + $meminfo['MemFree'];
1076 $reached = ($free < $min_memory);
1079 logger('Minimal memory reached: ' . $free . '/' . $meminfo['MemTotal'] . ' - limit ' . $min_memory, LOGGER_DEBUG);
1086 * @brief Checks if the maximum load is reached
1088 * @return bool Is the load reached?
1090 public function isMaxLoadReached()
1092 if ($this->is_backend()) {
1093 $process = 'backend';
1094 $maxsysload = intval(Config::get('system', 'maxloadavg'));
1095 if ($maxsysload < 1) {
1099 $process = 'frontend';
1100 $maxsysload = intval(Config::get('system', 'maxloadavg_frontend'));
1101 if ($maxsysload < 1) {
1106 $load = current_load();
1108 if (intval($load) > $maxsysload) {
1109 logger('system: load ' . $load . ' for ' . $process . ' tasks (' . $maxsysload . ') too high.');
1116 public function proc_run($args)
1118 if (!function_exists('proc_open')) {
1122 array_unshift($args, $this->getConfigValue('config', 'php_path', 'php'));
1124 for ($x = 0; $x < count($args); $x ++) {
1125 $args[$x] = escapeshellarg($args[$x]);
1128 $cmdline = implode(' ', $args);
1130 if ($this->min_memory_reached()) {
1134 if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
1135 $resource = proc_open('cmd /c start /b ' . $cmdline, [], $foo, $this->get_basepath());
1137 $resource = proc_open($cmdline . ' &', [], $foo, $this->get_basepath());
1139 if (!is_resource($resource)) {
1140 logger('We got no resource for command ' . $cmdline, LOGGER_DEBUG);
1143 proc_close($resource);
1147 * @brief Returns the system user that is executing the script
1149 * This mostly returns something like "www-data".
1151 * @return string system username
1153 private static function systemuser()
1155 if (!function_exists('posix_getpwuid') || !function_exists('posix_geteuid')) {
1159 $processUser = posix_getpwuid(posix_geteuid());
1160 return $processUser['name'];
1164 * @brief Checks if a given directory is usable for the system
1166 * @return boolean the directory is usable
1168 public static function directory_usable($directory, $check_writable = true)
1170 if ($directory == '') {
1171 logger('Directory is empty. This shouldn\'t happen.', LOGGER_DEBUG);
1175 if (!file_exists($directory)) {
1176 logger('Path "' . $directory . '" does not exist for user ' . self::systemuser(), LOGGER_DEBUG);
1180 if (is_file($directory)) {
1181 logger('Path "' . $directory . '" is a file for user ' . self::systemuser(), LOGGER_DEBUG);
1185 if (!is_dir($directory)) {
1186 logger('Path "' . $directory . '" is not a directory for user ' . self::systemuser(), LOGGER_DEBUG);
1190 if ($check_writable && !is_writable($directory)) {
1191 logger('Path "' . $directory . '" is not writable for user ' . self::systemuser(), LOGGER_DEBUG);
1199 * @param string $cat Config category
1200 * @param string $k Config key
1201 * @param mixed $default Default value if it isn't set
1203 public function getConfigValue($cat, $k, $default = null)
1207 if ($cat === 'config') {
1208 if (isset($this->config[$k])) {
1209 $return = $this->config[$k];
1212 if (isset($this->config[$cat][$k])) {
1213 $return = $this->config[$cat][$k];
1221 * Sets a value in the config cache. Accepts raw output from the config table
1223 * @param string $cat Config category
1224 * @param string $k Config key
1225 * @param mixed $v Value to set
1227 public function setConfigValue($cat, $k, $v)
1229 // Only arrays are serialized in database, so we have to unserialize sparingly
1230 $value = is_string($v) && preg_match("|^a:[0-9]+:{.*}$|s", $v) ? unserialize($v) : $v;
1232 if ($cat === 'config') {
1233 $this->config[$k] = $value;
1235 if (!isset($this->config[$cat])) {
1236 $this->config[$cat] = [];
1239 $this->config[$cat][$k] = $value;
1244 * Deletes a value from the config cache
1246 * @param string $cat Config category
1247 * @param string $k Config key
1249 public function deleteConfigValue($cat, $k)
1251 if ($cat === 'config') {
1252 if (isset($this->config[$k])) {
1253 unset($this->config[$k]);
1256 if (isset($this->config[$cat][$k])) {
1257 unset($this->config[$cat][$k]);
1264 * Retrieves a value from the user config cache
1266 * @param int $uid User Id
1267 * @param string $cat Config category
1268 * @param string $k Config key
1269 * @param mixed $default Default value if key isn't set
1271 public function getPConfigValue($uid, $cat, $k, $default = null)
1275 if (isset($this->config[$uid][$cat][$k])) {
1276 $return = $this->config[$uid][$cat][$k];
1283 * Sets a value in the user config cache
1285 * Accepts raw output from the pconfig table
1287 * @param int $uid User Id
1288 * @param string $cat Config category
1289 * @param string $k Config key
1290 * @param mixed $v Value to set
1292 public function setPConfigValue($uid, $cat, $k, $v)
1294 // Only arrays are serialized in database, so we have to unserialize sparingly
1295 $value = is_string($v) && preg_match("|^a:[0-9]+:{.*}$|s", $v) ? unserialize($v) : $v;
1297 if (!isset($this->config[$uid])) {
1298 $this->config[$uid] = [];
1301 if (!isset($this->config[$uid][$cat])) {
1302 $this->config[$uid][$cat] = [];
1305 $this->config[$uid][$cat][$k] = $value;
1309 * Deletes a value from the user config cache
1311 * @param int $uid User Id
1312 * @param string $cat Config category
1313 * @param string $k Config key
1315 public function deletePConfigValue($uid, $cat, $k)
1317 if (isset($this->config[$uid][$cat][$k])) {
1318 unset($this->config[$uid][$cat][$k]);
1323 * Generates the site's default sender email address
1327 public function getSenderEmailAddress()
1329 $sender_email = Config::get('config', 'sender_email');
1330 if (empty($sender_email)) {
1331 $hostname = $this->get_hostname();
1332 if (strpos($hostname, ':')) {
1333 $hostname = substr($hostname, 0, strpos($hostname, ':'));
1336 $sender_email = 'noreply@' . $hostname;
1339 return $sender_email;
1343 * Returns the current theme name.
1347 public function getCurrentTheme()
1349 if ($this->isInstallMode()) {
1353 //// @TODO Compute the current theme only once (this behavior has
1354 /// already been implemented, but it didn't work well -
1355 /// https://github.com/friendica/friendica/issues/5092)
1356 $this->computeCurrentTheme();
1358 return $this->current_theme;
1362 * Computes the current theme name based on the node settings, the user settings and the device type
1366 private function computeCurrentTheme()
1368 $system_theme = Config::get('system', 'theme');
1369 if (!$system_theme) {
1370 throw new Exception(L10n::t('No system theme config value set.'));
1374 $this->current_theme = $system_theme;
1376 $allowed_themes = explode(',', Config::get('system', 'allowed_themes', $system_theme));
1379 // Find the theme that belongs to the user whose stuff we are looking at
1380 if ($this->profile_uid && ($this->profile_uid != local_user())) {
1381 // Allow folks to override user themes and always use their own on their own site.
1382 // This works only if the user is on the same server
1383 $user = dba::selectFirst('user', ['theme'], ['uid' => $this->profile_uid]);
1384 if (DBM::is_result($user) && !PConfig::get(local_user(), 'system', 'always_my_theme')) {
1385 $page_theme = $user['theme'];
1389 if (!empty($_SESSION)) {
1390 $user_theme = defaults($_SESSION, 'theme', $system_theme);
1392 $user_theme = $system_theme;
1395 // Specific mobile theme override
1396 if (($this->is_mobile || $this->is_tablet) && defaults($_SESSION, 'show-mobile', true)) {
1397 $system_mobile_theme = Config::get('system', 'mobile-theme');
1398 $user_mobile_theme = defaults($_SESSION, 'mobile-theme', $system_mobile_theme);
1400 // --- means same mobile theme as desktop
1401 if (!empty($user_mobile_theme) && $user_mobile_theme !== '---') {
1402 $user_theme = $user_mobile_theme;
1407 $theme_name = $page_theme;
1409 $theme_name = $user_theme;
1413 && in_array($theme_name, $allowed_themes)
1414 && (file_exists('view/theme/' . $theme_name . '/style.css')
1415 || file_exists('view/theme/' . $theme_name . '/style.php'))
1417 $this->current_theme = $theme_name;
1422 * @brief Return full URL to theme which is currently in effect.
1424 * Provide a sane default if nothing is chosen or the specified theme does not exist.
1428 public function getCurrentThemeStylesheetPath()
1430 return Core\Theme::getStylesheetPath($this->getCurrentTheme());