7 use Detection\MobileDetect;
9 use Friendica\Core\Config;
10 use Friendica\Core\L10n;
11 use Friendica\Core\PConfig;
12 use Friendica\Core\System;
13 use Friendica\Database\DBA;
15 require_once 'boot.php';
16 require_once 'include/dba.php';
17 require_once 'include/text.php';
23 * @brief Our main application structure for the life of this page.
25 * Primarily deals with the URL that got us here
26 * and tries to make some sense of it, and
27 * stores our page contents and config storage
28 * and anything else that might need to be passed around
29 * before we spit the page out.
34 const MODE_LOCALCONFIGPRESENT = 1;
35 const MODE_DBAVAILABLE = 2;
36 const MODE_DBCONFIGAVAILABLE = 4;
37 const MODE_MAINTENANCEDISABLED = 8;
40 * @deprecated since version 2008.08 Use App->isInstallMode() instead to check for install mode.
42 const MODE_INSTALL = 0;
45 * @deprecated since version 2008.08 Use the precise mode constant to check for a specific capability instead.
47 const MODE_NORMAL = App::MODE_LOCALCONFIGPRESENT | App::MODE_DBAVAILABLE | App::MODE_DBCONFIGAVAILABLE | App::MODE_MAINTENANCEDISABLED;
49 public $module_loaded = false;
50 public $module_class = null;
51 public $query_string = '';
65 public $error = false;
70 public $mode = App::MODE_INSTALL;
76 public $interactive = true;
78 public $addons_admin = [];
81 public $is_mobile = false;
82 public $is_tablet = false;
83 public $is_friendica_app;
84 public $performance = [];
85 public $callstack = [];
86 public $theme_info = [];
87 public $backend = true;
90 // Allow themes to control internal parameters
91 // by changing App values in theme.php
93 public $sourcename = '';
94 public $videowidth = 425;
95 public $videoheight = 350;
96 public $force_max_items = 0;
97 public $theme_events_in_profile = true;
100 * @brief An array for all theme-controllable parameters
102 * Mostly unimplemented yet. Only options 'template_engine' and
108 'videoheight' => 350,
109 'force_max_items' => 0,
111 'template_engine' => 'smarty3',
115 * @brief An array of registered template engines ('name'=>'class name')
117 public $template_engines = [];
120 * @brief An array of instanced template engines ('name'=>'instance')
122 public $template_engine_instance = [];
136 private $curl_content_type;
137 private $curl_headers;
140 * @brief App constructor.
142 * @param string $basepath Path to the app base folder
144 * @throws Exception if the Basepath is not usable
146 public function __construct($basepath)
148 if (!static::directory_usable($basepath, false)) {
149 throw new Exception('Basepath ' . $basepath . ' isn\'t usable.');
152 BaseObject::setApp($this);
154 $this->basepath = rtrim($basepath, DIRECTORY_SEPARATOR);
156 $this->performance['start'] = microtime(true);
157 $this->performance['database'] = 0;
158 $this->performance['database_write'] = 0;
159 $this->performance['cache'] = 0;
160 $this->performance['cache_write'] = 0;
161 $this->performance['network'] = 0;
162 $this->performance['file'] = 0;
163 $this->performance['rendering'] = 0;
164 $this->performance['parser'] = 0;
165 $this->performance['marktime'] = 0;
166 $this->performance['markstart'] = microtime(true);
168 $this->callstack['database'] = [];
169 $this->callstack['database_write'] = [];
170 $this->callstack['cache'] = [];
171 $this->callstack['cache_write'] = [];
172 $this->callstack['network'] = [];
173 $this->callstack['file'] = [];
174 $this->callstack['rendering'] = [];
175 $this->callstack['parser'] = [];
181 // This has to be quite large to deal with embedded private photos
182 ini_set('pcre.backtrack_limit', 500000);
184 $this->scheme = 'http';
186 if ((x($_SERVER, 'HTTPS') && $_SERVER['HTTPS']) ||
187 (x($_SERVER, 'HTTP_FORWARDED') && preg_match('/proto=https/', $_SERVER['HTTP_FORWARDED'])) ||
188 (x($_SERVER, 'HTTP_X_FORWARDED_PROTO') && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') ||
189 (x($_SERVER, 'HTTP_X_FORWARDED_SSL') && $_SERVER['HTTP_X_FORWARDED_SSL'] == 'on') ||
190 (x($_SERVER, 'FRONT_END_HTTPS') && $_SERVER['FRONT_END_HTTPS'] == 'on') ||
191 (x($_SERVER, 'SERVER_PORT') && (intval($_SERVER['SERVER_PORT']) == 443)) // XXX: reasonable assumption, but isn't this hardcoding too much?
193 $this->scheme = 'https';
196 if (x($_SERVER, 'SERVER_NAME')) {
197 $this->hostname = $_SERVER['SERVER_NAME'];
199 if (x($_SERVER, 'SERVER_PORT') && $_SERVER['SERVER_PORT'] != 80 && $_SERVER['SERVER_PORT'] != 443) {
200 $this->hostname .= ':' . $_SERVER['SERVER_PORT'];
205 get_include_path() . PATH_SEPARATOR
206 . $this->basepath . DIRECTORY_SEPARATOR . 'include' . PATH_SEPARATOR
207 . $this->basepath . DIRECTORY_SEPARATOR . 'library' . PATH_SEPARATOR
210 if ((x($_SERVER, 'QUERY_STRING')) && substr($_SERVER['QUERY_STRING'], 0, 9) === 'pagename=') {
211 $this->query_string = substr($_SERVER['QUERY_STRING'], 9);
212 } elseif ((x($_SERVER, 'QUERY_STRING')) && substr($_SERVER['QUERY_STRING'], 0, 2) === 'q=') {
213 $this->query_string = substr($_SERVER['QUERY_STRING'], 2);
216 // removing trailing / - maybe a nginx problem
217 $this->query_string = ltrim($this->query_string, '/');
219 if (!empty($_GET['pagename'])) {
220 $this->cmd = trim($_GET['pagename'], '/\\');
221 } elseif (!empty($_GET['q'])) {
222 $this->cmd = trim($_GET['q'], '/\\');
226 $this->query_string = str_replace($this->cmd . '&', $this->cmd . '?', $this->query_string);
228 // unix style "homedir"
229 if (substr($this->cmd, 0, 1) === '~') {
230 $this->cmd = 'profile/' . substr($this->cmd, 1);
233 // Diaspora style profile url
234 if (substr($this->cmd, 0, 2) === 'u/') {
235 $this->cmd = 'profile/' . substr($this->cmd, 2);
239 * Break the URL path into C style argc/argv style arguments for our
240 * modules. Given "http://example.com/module/arg1/arg2", $this->argc
241 * will be 3 (integer) and $this->argv will contain:
247 * There will always be one argument. If provided a naked domain
248 * URL, $this->argv[0] is set to "home".
251 $this->argv = explode('/', $this->cmd);
252 $this->argc = count($this->argv);
253 if ((array_key_exists('0', $this->argv)) && strlen($this->argv[0])) {
254 $this->module = str_replace('.', '_', $this->argv[0]);
255 $this->module = str_replace('-', '_', $this->module);
258 $this->argv = ['home'];
259 $this->module = 'home';
262 // See if there is any page number information, and initialise pagination
263 $this->pager['page'] = ((x($_GET, 'page') && intval($_GET['page']) > 0) ? intval($_GET['page']) : 1);
264 $this->pager['itemspage'] = 50;
265 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
267 if ($this->pager['start'] < 0) {
268 $this->pager['start'] = 0;
270 $this->pager['total'] = 0;
272 // Detect mobile devices
273 $mobile_detect = new MobileDetect();
274 $this->is_mobile = $mobile_detect->isMobile();
275 $this->is_tablet = $mobile_detect->isTablet();
278 $this->is_friendica_app = isset($_SERVER['HTTP_USER_AGENT']) && $_SERVER['HTTP_USER_AGENT'] == 'Apache-HttpClient/UNAVAILABLE (java 1.4)';
280 // Register template engines
281 $this->register_template_engine('Friendica\Render\FriendicaSmartyEngine');
285 * Reloads the whole app instance
287 public function reload()
289 // The order of the following calls is important to ensure proper initialization
290 $this->loadConfigFiles();
292 $this->loadDatabase();
294 $this->determineMode();
296 $this->determineUrlPath();
300 if ($this->mode & self::MODE_DBAVAILABLE) {
301 Core\Addon::loadHooks();
303 $this->loadAddonConfig();
306 $this->loadDefaultTimezone();
322 $this->process_id = System::processID('log');
326 * Load the configuration files
328 * First loads the default value for all the configuration keys, then the legacy configuration files, then the
329 * expected local.ini.php
331 private function loadConfigFiles()
333 $this->loadConfigFile($this->basepath . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'config.ini.php');
334 $this->loadConfigFile($this->basepath . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'settings.ini.php');
336 // Legacy .htconfig.php support
337 if (file_exists($this->basepath . DIRECTORY_SEPARATOR . '.htpreconfig.php')) {
339 include $this->basepath . DIRECTORY_SEPARATOR . '.htpreconfig.php';
342 // Legacy .htconfig.php support
343 if (file_exists($this->basepath . DIRECTORY_SEPARATOR . '.htconfig.php')) {
346 include $this->basepath . DIRECTORY_SEPARATOR . '.htconfig.php';
348 $this->setConfigValue('database', 'hostname', $db_host);
349 $this->setConfigValue('database', 'username', $db_user);
350 $this->setConfigValue('database', 'password', $db_pass);
351 $this->setConfigValue('database', 'database', $db_data);
352 if (isset($a->config['system']['db_charset'])) {
353 $this->setConfigValue('database', 'charset', $a->config['system']['db_charset']);
356 unset($db_host, $db_user, $db_pass, $db_data);
358 if (isset($default_timezone)) {
359 $this->setConfigValue('system', 'default_timezone', $default_timezone);
360 unset($default_timezone);
363 if (isset($pidfile)) {
364 $this->setConfigValue('system', 'pidfile', $pidfile);
369 $this->setConfigValue('system', 'language', $lang);
374 if (file_exists($this->basepath . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'local.ini.php')) {
375 $this->loadConfigFile($this->basepath . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'local.ini.php', true);
380 * Tries to load the specified configuration file into the App->config array.
381 * Doesn't overwrite previously set values by default to prevent default config files to supersede DB Config.
383 * The config format is INI and the template for configuration files is the following:
385 * <?php return <<<INI
393 * @param type $filepath
394 * @param bool $overwrite Force value overwrite if the config key already exists
397 public function loadConfigFile($filepath, $overwrite = false)
399 if (!file_exists($filepath)) {
400 throw new Exception('Error parsing non-existent config file ' . $filepath);
403 $contents = include($filepath);
405 $config = parse_ini_string($contents, true, INI_SCANNER_TYPED);
407 if ($config === false) {
408 throw new Exception('Error parsing config file ' . $filepath);
411 foreach ($config as $category => $values) {
412 foreach ($values as $key => $value) {
414 $this->setConfigValue($category, $key, $value);
416 $this->setDefaultConfigValue($category, $key, $value);
423 * Loads addons configuration files
425 * First loads all activated addons default configuration throught the load_config hook, then load the local.ini.php
426 * again to overwrite potential local addon configuration.
428 private function loadAddonConfig()
430 // Loads addons default config
431 Core\Addon::callHooks('load_config');
433 // Load the local addon config file to overwritten default addon config values
434 if (file_exists($this->basepath . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'addon.ini.php')) {
435 $this->loadConfigFile($this->basepath . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'addon.ini.php', true);
440 * Loads the default timezone
442 * Include support for legacy $default_timezone
444 * @global string $default_timezone
446 private function loadDefaultTimezone()
448 if ($this->getConfigValue('system', 'default_timezone')) {
449 $this->timezone = $this->getConfigValue('system', 'default_timezone');
451 global $default_timezone;
452 $this->timezone = !empty($default_timezone) ? $default_timezone : 'UTC';
455 if ($this->timezone) {
456 date_default_timezone_set($this->timezone);
461 * Figure out if we are running at the top of a domain or in a sub-directory and adjust accordingly
463 private function determineUrlPath()
465 $this->urlpath = $this->getConfigValue('system', 'urlpath');
467 /* SCRIPT_URL gives /path/to/friendica/module/parameter
468 * QUERY_STRING gives pagename=module/parameter
470 * To get /path/to/friendica we perform dirname() for as many levels as there are slashes in the QUERY_STRING
472 if (!empty($_SERVER['SCRIPT_URL'])) {
474 if (!empty($_SERVER['QUERY_STRING'])) {
475 $path = trim(dirname($_SERVER['SCRIPT_URL'], substr_count(trim($_SERVER['QUERY_STRING'], '/'), '/') + 1), '/');
478 $path = trim($_SERVER['SCRIPT_URL'], '/');
481 if ($path && $path != $this->urlpath) {
482 $this->urlpath = $path;
490 * - App::MODE_INSTALL : Either the database connection can't be established or the config table doesn't exist
491 * - App::MODE_MAINTENANCE: The maintenance mode has been set
492 * - App::MODE_NORMAL : Normal run with all features enabled
496 private function determineMode()
500 if (!file_exists($this->basepath . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'local.ini.php')
501 && !file_exists($this->basepath . DIRECTORY_SEPARATOR . '.htconfig.php')) {
505 $this->mode |= App::MODE_LOCALCONFIGPRESENT;
507 if (!DBA::connected()) {
511 $this->mode |= App::MODE_DBAVAILABLE;
513 if (DBA::fetchFirst("SHOW TABLES LIKE 'config'") === false) {
517 $this->mode |= App::MODE_DBCONFIGAVAILABLE;
519 if (Config::get('system', 'maintenance')) {
523 $this->mode |= App::MODE_MAINTENANCEDISABLED;
526 public function loadDatabase()
528 if (DBA::connected()) {
532 $db_host = $this->getConfigValue('database', 'hostname');
533 $db_user = $this->getConfigValue('database', 'username');
534 $db_pass = $this->getConfigValue('database', 'password');
535 $db_data = $this->getConfigValue('database', 'database');
536 $charset = $this->getConfigValue('database', 'charset');
538 // Use environment variables for mysql if they are set beforehand
539 if (!empty(getenv('MYSQL_HOST'))
540 && (!empty(getenv('MYSQL_USERNAME')) || !empty(getenv('MYSQL_USER')))
541 && getenv('MYSQL_PASSWORD') !== false
542 && !empty(getenv('MYSQL_DATABASE')))
544 $db_host = getenv('MYSQL_HOST');
545 if (!empty(getenv('MYSQL_PORT'))) {
546 $db_host .= ':' . getenv('MYSQL_PORT');
548 if (!empty(getenv('MYSQL_USERNAME'))) {
549 $db_user = getenv('MYSQL_USERNAME');
551 $db_user = getenv('MYSQL_USER');
553 $db_pass = (string) getenv('MYSQL_PASSWORD');
554 $db_data = getenv('MYSQL_DATABASE');
557 $stamp1 = microtime(true);
559 DBA::connect($db_host, $db_user, $db_pass, $db_data, $charset);
560 unset($db_host, $db_user, $db_pass, $db_data, $charset);
562 $this->save_timestamp($stamp1, 'network');
566 * Install mode is when the local config file is missing or the DB schema hasn't been installed yet.
570 public function isInstallMode()
572 return !($this->mode & App::MODE_LOCALCONFIGPRESENT) || !($this->mode & App::MODE_DBCONFIGAVAILABLE);
576 * @brief Returns the base filesystem path of the App
578 * It first checks for the internal variable, then for DOCUMENT_ROOT and
583 public function get_basepath()
585 $basepath = $this->basepath;
588 $basepath = Config::get('system', 'basepath');
591 if (!$basepath && x($_SERVER, 'DOCUMENT_ROOT')) {
592 $basepath = $_SERVER['DOCUMENT_ROOT'];
595 if (!$basepath && x($_SERVER, 'PWD')) {
596 $basepath = $_SERVER['PWD'];
599 return self::realpath($basepath);
603 * @brief Returns a normalized file path
605 * This is a wrapper for the "realpath" function.
606 * That function cannot detect the real path when some folders aren't readable.
607 * Since this could happen with some hosters we need to handle this.
609 * @param string $path The path that is about to be normalized
610 * @return string normalized path - when possible
612 public static function realpath($path)
614 $normalized = realpath($path);
616 if (!is_bool($normalized)) {
623 public function get_scheme()
625 return $this->scheme;
629 * @brief Retrieves the Friendica instance base URL
631 * This function assembles the base URL from multiple parts:
632 * - Protocol is determined either by the request or a combination of
633 * system.ssl_policy and the $ssl parameter.
634 * - Host name is determined either by system.hostname or inferred from request
635 * - Path is inferred from SCRIPT_NAME
637 * Note: $ssl parameter value doesn't directly correlate with the resulting protocol
639 * @param bool $ssl Whether to append http or https under SSL_POLICY_SELFSIGN
640 * @return string Friendica server base URL
642 public function get_baseurl($ssl = false)
644 $scheme = $this->scheme;
646 if (Config::get('system', 'ssl_policy') == SSL_POLICY_FULL) {
650 // Basically, we have $ssl = true on any links which can only be seen by a logged in user
651 // (and also the login link). Anything seen by an outsider will have it turned off.
653 if (Config::get('system', 'ssl_policy') == SSL_POLICY_SELFSIGN) {
661 if (Config::get('config', 'hostname') != '') {
662 $this->hostname = Config::get('config', 'hostname');
665 return $scheme . '://' . $this->hostname . (!empty($this->urlpath) ? '/' . $this->urlpath : '' );
669 * @brief Initializes the baseurl components
671 * Clears the baseurl cache to prevent inconsistencies
675 public function set_baseurl($url)
677 $parsed = @parse_url($url);
681 if (!empty($parsed['scheme'])) {
682 $this->scheme = $parsed['scheme'];
685 if (!empty($parsed['host'])) {
686 $hostname = $parsed['host'];
689 if (x($parsed, 'port')) {
690 $hostname .= ':' . $parsed['port'];
692 if (x($parsed, 'path')) {
693 $this->urlpath = trim($parsed['path'], '\\/');
696 if (file_exists($this->basepath . DIRECTORY_SEPARATOR . '.htpreconfig.php')) {
697 include $this->basepath . DIRECTORY_SEPARATOR . '.htpreconfig.php';
700 if (Config::get('config', 'hostname') != '') {
701 $this->hostname = Config::get('config', 'hostname');
704 if (!isset($this->hostname) || ($this->hostname == '')) {
705 $this->hostname = $hostname;
710 public function get_hostname()
712 if (Config::get('config', 'hostname') != '') {
713 $this->hostname = Config::get('config', 'hostname');
716 return $this->hostname;
719 public function get_path()
721 return $this->urlpath;
724 public function set_pager_total($n)
726 $this->pager['total'] = intval($n);
729 public function set_pager_itemspage($n)
731 $this->pager['itemspage'] = ((intval($n) > 0) ? intval($n) : 0);
732 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
735 public function set_pager_page($n)
737 $this->pager['page'] = $n;
738 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
741 public function init_pagehead()
743 $interval = ((local_user()) ? PConfig::get(local_user(), 'system', 'update_interval') : 40000);
745 // If the update is 'deactivated' set it to the highest integer number (~24 days)
747 $interval = 2147483647;
750 if ($interval < 10000) {
754 // compose the page title from the sitename and the
755 // current module called
756 if (!$this->module == '') {
757 $this->page['title'] = $this->config['sitename'] . ' (' . $this->module . ')';
759 $this->page['title'] = $this->config['sitename'];
762 /* put the head template at the beginning of page['htmlhead']
763 * since the code added by the modules frequently depends on it
766 if (!isset($this->page['htmlhead'])) {
767 $this->page['htmlhead'] = '';
770 // If we're using Smarty, then doing replace_macros() will replace
771 // any unrecognized variables with a blank string. Since we delay
772 // replacing $stylesheet until later, we need to replace it now
773 // with another variable name
774 if ($this->theme['template_engine'] === 'smarty3') {
775 $stylesheet = $this->get_template_ldelim('smarty3') . '$stylesheet' . $this->get_template_rdelim('smarty3');
777 $stylesheet = '$stylesheet';
780 $shortcut_icon = Config::get('system', 'shortcut_icon');
781 if ($shortcut_icon == '') {
782 $shortcut_icon = 'images/friendica-32.png';
785 $touch_icon = Config::get('system', 'touch_icon');
786 if ($touch_icon == '') {
787 $touch_icon = 'images/friendica-128.png';
790 // get data wich is needed for infinite scroll on the network page
791 $invinite_scroll = infinite_scroll_data($this->module);
793 $tpl = get_markup_template('head.tpl');
794 $this->page['htmlhead'] = replace_macros($tpl, [
795 '$baseurl' => $this->get_baseurl(),
796 '$local_user' => local_user(),
797 '$generator' => 'Friendica' . ' ' . FRIENDICA_VERSION,
798 '$delitem' => L10n::t('Delete this item?'),
799 '$showmore' => L10n::t('show more'),
800 '$showfewer' => L10n::t('show fewer'),
801 '$update_interval' => $interval,
802 '$shortcut_icon' => $shortcut_icon,
803 '$touch_icon' => $touch_icon,
804 '$stylesheet' => $stylesheet,
805 '$infinite_scroll' => $invinite_scroll,
806 '$block_public' => intval(Config::get('system', 'block_public')),
807 ]) . $this->page['htmlhead'];
810 public function init_page_end()
812 if (!isset($this->page['end'])) {
813 $this->page['end'] = '';
815 $tpl = get_markup_template('end.tpl');
816 $this->page['end'] = replace_macros($tpl, [
817 '$baseurl' => $this->get_baseurl()
818 ]) . $this->page['end'];
821 public function set_curl_code($code)
823 $this->curl_code = $code;
826 public function get_curl_code()
828 return $this->curl_code;
831 public function set_curl_content_type($content_type)
833 $this->curl_content_type = $content_type;
836 public function get_curl_content_type()
838 return $this->curl_content_type;
841 public function set_curl_headers($headers)
843 $this->curl_headers = $headers;
846 public function get_curl_headers()
848 return $this->curl_headers;
852 * @brief Removes the base url from an url. This avoids some mixed content problems.
854 * @param string $orig_url
856 * @return string The cleaned url
858 public function remove_baseurl($orig_url)
860 // Remove the hostname from the url if it is an internal link
861 $nurl = normalise_link($orig_url);
862 $base = normalise_link($this->get_baseurl());
863 $url = str_replace($base . '/', '', $nurl);
865 // if it is an external link return the orignal value
866 if ($url == normalise_link($orig_url)) {
874 * @brief Register template engine class
876 * @param string $class
878 private function register_template_engine($class)
880 $v = get_class_vars($class);
883 $this->template_engines[$name] = $class;
885 echo "template engine <tt>$class</tt> cannot be registered without a name.\n";
891 * @brief Return template engine instance.
893 * If $name is not defined, return engine defined by theme,
896 * @return object Template Engine instance
898 public function template_engine()
900 $template_engine = 'smarty3';
901 if (x($this->theme, 'template_engine')) {
902 $template_engine = $this->theme['template_engine'];
905 if (isset($this->template_engines[$template_engine])) {
906 if (isset($this->template_engine_instance[$template_engine])) {
907 return $this->template_engine_instance[$template_engine];
909 $class = $this->template_engines[$template_engine];
911 $this->template_engine_instance[$template_engine] = $obj;
916 echo "template engine <tt>$template_engine</tt> is not registered!\n";
921 * @brief Returns the active template engine.
925 public function get_template_engine()
927 return $this->theme['template_engine'];
930 public function set_template_engine($engine = 'smarty3')
932 $this->theme['template_engine'] = $engine;
935 public function get_template_ldelim($engine = 'smarty3')
937 return $this->ldelim[$engine];
940 public function get_template_rdelim($engine = 'smarty3')
942 return $this->rdelim[$engine];
945 public function save_timestamp($stamp, $value)
947 if (!isset($this->config['system']['profiler']) || !$this->config['system']['profiler']) {
951 $duration = (float) (microtime(true) - $stamp);
953 if (!isset($this->performance[$value])) {
954 // Prevent ugly E_NOTICE
955 $this->performance[$value] = 0;
958 $this->performance[$value] += (float) $duration;
959 $this->performance['marktime'] += (float) $duration;
961 $callstack = System::callstack();
963 if (!isset($this->callstack[$value][$callstack])) {
964 // Prevent ugly E_NOTICE
965 $this->callstack[$value][$callstack] = 0;
968 $this->callstack[$value][$callstack] += (float) $duration;
971 public function get_useragent()
974 FRIENDICA_PLATFORM . " '" .
975 FRIENDICA_CODENAME . "' " .
976 FRIENDICA_VERSION . '-' .
977 DB_UPDATE_VERSION . '; ' .
978 $this->get_baseurl();
981 public function is_friendica_app()
983 return $this->is_friendica_app;
987 * @brief Checks if the site is called via a backend process
989 * This isn't a perfect solution. But we need this check very early.
990 * So we cannot wait until the modules are loaded.
992 * @return bool Is it a known backend?
994 public function is_backend()
1018 // Check if current module is in backend or backend flag is set
1019 return (in_array($this->module, $backends) || $this->backend);
1023 * @brief Checks if the maximum number of database processes is reached
1025 * @return bool Is the limit reached?
1027 public function isMaxProcessesReached()
1029 // Deactivated, needs more investigating if this check really makes sense
1033 * Commented out to suppress static analyzer issues
1035 if ($this->is_backend()) {
1036 $process = 'backend';
1037 $max_processes = Config::get('system', 'max_processes_backend');
1038 if (intval($max_processes) == 0) {
1042 $process = 'frontend';
1043 $max_processes = Config::get('system', 'max_processes_frontend');
1044 if (intval($max_processes) == 0) {
1045 $max_processes = 20;
1049 $processlist = DBA::processlist();
1050 if ($processlist['list'] != '') {
1051 logger('Processcheck: Processes: ' . $processlist['amount'] . ' - Processlist: ' . $processlist['list'], LOGGER_DEBUG);
1053 if ($processlist['amount'] > $max_processes) {
1054 logger('Processcheck: Maximum number of processes for ' . $process . ' tasks (' . $max_processes . ') reached.', LOGGER_DEBUG);
1063 * @brief Checks if the minimal memory is reached
1065 * @return bool Is the memory limit reached?
1067 public function min_memory_reached()
1069 $min_memory = Config::get('system', 'min_memory', 0);
1070 if ($min_memory == 0) {
1074 if (!is_readable('/proc/meminfo')) {
1078 $memdata = explode("\n", file_get_contents('/proc/meminfo'));
1081 foreach ($memdata as $line) {
1082 $data = explode(':', $line);
1083 if (count($data) != 2) {
1086 list($key, $val) = $data;
1087 $meminfo[$key] = (int) trim(str_replace('kB', '', $val));
1088 $meminfo[$key] = (int) ($meminfo[$key] / 1024);
1091 if (!isset($meminfo['MemAvailable']) || !isset($meminfo['MemFree'])) {
1095 $free = $meminfo['MemAvailable'] + $meminfo['MemFree'];
1097 $reached = ($free < $min_memory);
1100 logger('Minimal memory reached: ' . $free . '/' . $meminfo['MemTotal'] . ' - limit ' . $min_memory, LOGGER_DEBUG);
1107 * @brief Checks if the maximum load is reached
1109 * @return bool Is the load reached?
1111 public function isMaxLoadReached()
1113 if ($this->is_backend()) {
1114 $process = 'backend';
1115 $maxsysload = intval(Config::get('system', 'maxloadavg'));
1116 if ($maxsysload < 1) {
1120 $process = 'frontend';
1121 $maxsysload = intval(Config::get('system', 'maxloadavg_frontend'));
1122 if ($maxsysload < 1) {
1127 $load = current_load();
1129 if (intval($load) > $maxsysload) {
1130 logger('system: load ' . $load . ' for ' . $process . ' tasks (' . $maxsysload . ') too high.');
1138 * Executes a child process with 'proc_open'
1140 * @param string $command The command to execute
1141 * @param array $args Arguments to pass to the command ( [ 'key' => value, 'key2' => value2, ... ]
1143 public function proc_run($command, $args)
1145 if (!function_exists('proc_open')) {
1149 $cmdline = $this->getConfigValue('config', 'php_path', 'php') . ' ' . escapeshellarg($command);
1151 foreach ($args as $key => $value) {
1152 if (!is_null($value) && is_bool($value) && !$value) {
1156 $cmdline .= ' --' . $key;
1157 if (!is_null($value) && !is_bool($value)) {
1158 $cmdline .= ' ' . $value;
1162 if ($this->min_memory_reached()) {
1166 if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
1167 $resource = proc_open('cmd /c start /b ' . $cmdline, [], $foo, $this->get_basepath());
1169 $resource = proc_open($cmdline . ' &', [], $foo, $this->get_basepath());
1171 if (!is_resource($resource)) {
1172 logger('We got no resource for command ' . $cmdline, LOGGER_DEBUG);
1175 proc_close($resource);
1179 * @brief Returns the system user that is executing the script
1181 * This mostly returns something like "www-data".
1183 * @return string system username
1185 private static function systemuser()
1187 if (!function_exists('posix_getpwuid') || !function_exists('posix_geteuid')) {
1191 $processUser = posix_getpwuid(posix_geteuid());
1192 return $processUser['name'];
1196 * @brief Checks if a given directory is usable for the system
1198 * @return boolean the directory is usable
1200 public static function directory_usable($directory, $check_writable = true)
1202 if ($directory == '') {
1203 logger('Directory is empty. This shouldn\'t happen.', LOGGER_DEBUG);
1207 if (!file_exists($directory)) {
1208 logger('Path "' . $directory . '" does not exist for user ' . self::systemuser(), LOGGER_DEBUG);
1212 if (is_file($directory)) {
1213 logger('Path "' . $directory . '" is a file for user ' . self::systemuser(), LOGGER_DEBUG);
1217 if (!is_dir($directory)) {
1218 logger('Path "' . $directory . '" is not a directory for user ' . self::systemuser(), LOGGER_DEBUG);
1222 if ($check_writable && !is_writable($directory)) {
1223 logger('Path "' . $directory . '" is not writable for user ' . self::systemuser(), LOGGER_DEBUG);
1231 * @param string $cat Config category
1232 * @param string $k Config key
1233 * @param mixed $default Default value if it isn't set
1235 public function getConfigValue($cat, $k, $default = null)
1239 if ($cat === 'config') {
1240 if (isset($this->config[$k])) {
1241 $return = $this->config[$k];
1244 if (isset($this->config[$cat][$k])) {
1245 $return = $this->config[$cat][$k];
1253 * Sets a default value in the config cache. Ignores already existing keys.
1255 * @param string $cat Config category
1256 * @param string $k Config key
1257 * @param mixed $v Default value to set
1259 private function setDefaultConfigValue($cat, $k, $v)
1261 if (!isset($this->config[$cat][$k])) {
1262 $this->setConfigValue($cat, $k, $v);
1267 * Sets a value in the config cache. Accepts raw output from the config table
1269 * @param string $cat Config category
1270 * @param string $k Config key
1271 * @param mixed $v Value to set
1273 public function setConfigValue($cat, $k, $v)
1275 // Only arrays are serialized in database, so we have to unserialize sparingly
1276 $value = is_string($v) && preg_match("|^a:[0-9]+:{.*}$|s", $v) ? unserialize($v) : $v;
1278 if ($cat === 'config') {
1279 $this->config[$k] = $value;
1281 if (!isset($this->config[$cat])) {
1282 $this->config[$cat] = [];
1285 $this->config[$cat][$k] = $value;
1290 * Deletes a value from the config cache
1292 * @param string $cat Config category
1293 * @param string $k Config key
1295 public function deleteConfigValue($cat, $k)
1297 if ($cat === 'config') {
1298 if (isset($this->config[$k])) {
1299 unset($this->config[$k]);
1302 if (isset($this->config[$cat][$k])) {
1303 unset($this->config[$cat][$k]);
1310 * Retrieves a value from the user config cache
1312 * @param int $uid User Id
1313 * @param string $cat Config category
1314 * @param string $k Config key
1315 * @param mixed $default Default value if key isn't set
1317 public function getPConfigValue($uid, $cat, $k, $default = null)
1321 if (isset($this->config[$uid][$cat][$k])) {
1322 $return = $this->config[$uid][$cat][$k];
1329 * Sets a value in the user config cache
1331 * Accepts raw output from the pconfig table
1333 * @param int $uid User Id
1334 * @param string $cat Config category
1335 * @param string $k Config key
1336 * @param mixed $v Value to set
1338 public function setPConfigValue($uid, $cat, $k, $v)
1340 // Only arrays are serialized in database, so we have to unserialize sparingly
1341 $value = is_string($v) && preg_match("|^a:[0-9]+:{.*}$|s", $v) ? unserialize($v) : $v;
1343 if (!isset($this->config[$uid]) || !is_array($this->config[$uid])) {
1344 $this->config[$uid] = [];
1347 if (!isset($this->config[$uid][$cat]) || !is_array($this->config[$uid][$cat])) {
1348 $this->config[$uid][$cat] = [];
1351 $this->config[$uid][$cat][$k] = $value;
1355 * Deletes a value from the user config cache
1357 * @param int $uid User Id
1358 * @param string $cat Config category
1359 * @param string $k Config key
1361 public function deletePConfigValue($uid, $cat, $k)
1363 if (isset($this->config[$uid][$cat][$k])) {
1364 unset($this->config[$uid][$cat][$k]);
1369 * Generates the site's default sender email address
1373 public function getSenderEmailAddress()
1375 $sender_email = Config::get('config', 'sender_email');
1376 if (empty($sender_email)) {
1377 $hostname = $this->get_hostname();
1378 if (strpos($hostname, ':')) {
1379 $hostname = substr($hostname, 0, strpos($hostname, ':'));
1382 $sender_email = 'noreply@' . $hostname;
1385 return $sender_email;
1389 * Returns the current theme name.
1393 public function getCurrentTheme()
1395 if ($this->isInstallMode()) {
1399 //// @TODO Compute the current theme only once (this behavior has
1400 /// already been implemented, but it didn't work well -
1401 /// https://github.com/friendica/friendica/issues/5092)
1402 $this->computeCurrentTheme();
1404 return $this->current_theme;
1408 * Computes the current theme name based on the node settings, the user settings and the device type
1412 private function computeCurrentTheme()
1414 $system_theme = Config::get('system', 'theme');
1415 if (!$system_theme) {
1416 throw new Exception(L10n::t('No system theme config value set.'));
1420 $this->current_theme = $system_theme;
1422 $allowed_themes = explode(',', Config::get('system', 'allowed_themes', $system_theme));
1425 // Find the theme that belongs to the user whose stuff we are looking at
1426 if ($this->profile_uid && ($this->profile_uid != local_user())) {
1427 // Allow folks to override user themes and always use their own on their own site.
1428 // This works only if the user is on the same server
1429 $user = DBA::selectFirst('user', ['theme'], ['uid' => $this->profile_uid]);
1430 if (DBA::isResult($user) && !PConfig::get(local_user(), 'system', 'always_my_theme')) {
1431 $page_theme = $user['theme'];
1435 $user_theme = Core\Session::get('theme', $system_theme);
1437 // Specific mobile theme override
1438 if (($this->is_mobile || $this->is_tablet) && Core\Session::get('show-mobile', true)) {
1439 $system_mobile_theme = Config::get('system', 'mobile-theme');
1440 $user_mobile_theme = Core\Session::get('mobile-theme', $system_mobile_theme);
1442 // --- means same mobile theme as desktop
1443 if (!empty($user_mobile_theme) && $user_mobile_theme !== '---') {
1444 $user_theme = $user_mobile_theme;
1449 $theme_name = $page_theme;
1451 $theme_name = $user_theme;
1455 && in_array($theme_name, $allowed_themes)
1456 && (file_exists('view/theme/' . $theme_name . '/style.css')
1457 || file_exists('view/theme/' . $theme_name . '/style.php'))
1459 $this->current_theme = $theme_name;
1464 * @brief Return full URL to theme which is currently in effect.
1466 * Provide a sane default if nothing is chosen or the specified theme does not exist.
1470 public function getCurrentThemeStylesheetPath()
1472 return Core\Theme::getStylesheetPath($this->getCurrentTheme());