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');
380 * Tries to load the specified configuration file into the App->config array.
381 * Overwrites previously set values.
383 * The config format is INI and the template for configuration files is the following:
385 * <?php return <<<INI
393 * @param type $filepath
396 public function loadConfigFile($filepath)
398 if (!file_exists($filepath)) {
399 throw new Exception('Error parsing non-existent config file ' . $filepath);
402 $contents = include($filepath);
404 $config = parse_ini_string($contents, true, INI_SCANNER_TYPED);
406 if ($config === false) {
407 throw new Exception('Error parsing config file ' . $filepath);
410 foreach ($config as $category => $values) {
411 foreach ($values as $key => $value) {
412 $this->setConfigValue($category, $key, $value);
418 * Loads addons configuration files
420 * First loads all activated addons default configuration throught the load_config hook, then load the local.ini.php
421 * again to overwrite potential local addon configuration.
423 private function loadAddonConfig()
425 // Loads addons default config
426 Core\Addon::callHooks('load_config');
428 // Load the local addon config file to overwritten default addon config values
429 if (file_exists($this->basepath . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'addon.ini.php')) {
430 $this->loadConfigFile($this->basepath . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'addon.ini.php');
435 * Loads the default timezone
437 * Include support for legacy $default_timezone
439 * @global string $default_timezone
441 private function loadDefaultTimezone()
443 if ($this->getConfigValue('system', 'default_timezone')) {
444 $this->timezone = $this->getConfigValue('system', 'default_timezone');
446 global $default_timezone;
447 $this->timezone = !empty($default_timezone) ? $default_timezone : 'UTC';
450 if ($this->timezone) {
451 date_default_timezone_set($this->timezone);
456 * Figure out if we are running at the top of a domain or in a sub-directory and adjust accordingly
458 private function determineUrlPath()
460 $this->urlpath = $this->getConfigValue('system', 'urlpath');
462 /* SCRIPT_URL gives /path/to/friendica/module/parameter
463 * QUERY_STRING gives pagename=module/parameter
465 * To get /path/to/friendica we perform dirname() for as many levels as there are slashes in the QUERY_STRING
467 if (!empty($_SERVER['SCRIPT_URL'])) {
469 if (!empty($_SERVER['QUERY_STRING'])) {
470 $path = trim(dirname($_SERVER['SCRIPT_URL'], substr_count(trim($_SERVER['QUERY_STRING'], '/'), '/') + 1), '/');
473 $path = trim($_SERVER['SCRIPT_URL'], '/');
476 if ($path && $path != $this->urlpath) {
477 $this->urlpath = $path;
485 * - App::MODE_INSTALL : Either the database connection can't be established or the config table doesn't exist
486 * - App::MODE_MAINTENANCE: The maintenance mode has been set
487 * - App::MODE_NORMAL : Normal run with all features enabled
491 private function determineMode()
495 if (!file_exists($this->basepath . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'local.ini.php')
496 && !file_exists($this->basepath . DIRECTORY_SEPARATOR . '.htconfig.php')) {
500 $this->mode |= App::MODE_LOCALCONFIGPRESENT;
502 if (!DBA::connected()) {
506 $this->mode |= App::MODE_DBAVAILABLE;
508 if (DBA::fetchFirst("SHOW TABLES LIKE 'config'") === false) {
512 $this->mode |= App::MODE_DBCONFIGAVAILABLE;
514 if (Config::get('system', 'maintenance')) {
518 $this->mode |= App::MODE_MAINTENANCEDISABLED;
521 public function loadDatabase()
523 if (DBA::connected()) {
527 $db_host = $this->getConfigValue('database', 'hostname');
528 $db_user = $this->getConfigValue('database', 'username');
529 $db_pass = $this->getConfigValue('database', 'password');
530 $db_data = $this->getConfigValue('database', 'database');
531 $charset = $this->getConfigValue('database', 'charset');
533 // Use environment variables for mysql if they are set beforehand
534 if (!empty(getenv('MYSQL_HOST'))
535 && (!empty(getenv('MYSQL_USERNAME')) || !empty(getenv('MYSQL_USER')))
536 && getenv('MYSQL_PASSWORD') !== false
537 && !empty(getenv('MYSQL_DATABASE')))
539 $db_host = getenv('MYSQL_HOST');
540 if (!empty(getenv('MYSQL_PORT'))) {
541 $db_host .= ':' . getenv('MYSQL_PORT');
543 if (!empty(getenv('MYSQL_USERNAME'))) {
544 $db_user = getenv('MYSQL_USERNAME');
546 $db_user = getenv('MYSQL_USER');
548 $db_pass = (string) getenv('MYSQL_PASSWORD');
549 $db_data = getenv('MYSQL_DATABASE');
552 $stamp1 = microtime(true);
554 DBA::connect($db_host, $db_user, $db_pass, $db_data, $charset);
555 unset($db_host, $db_user, $db_pass, $db_data, $charset);
557 $this->save_timestamp($stamp1, 'network');
561 * Install mode is when the local config file is missing or the DB schema hasn't been installed yet.
565 public function isInstallMode()
567 return !($this->mode & App::MODE_LOCALCONFIGPRESENT) || !($this->mode & App::MODE_DBCONFIGAVAILABLE);
571 * @brief Returns the base filesystem path of the App
573 * It first checks for the internal variable, then for DOCUMENT_ROOT and
578 public function get_basepath()
580 $basepath = $this->basepath;
583 $basepath = Config::get('system', 'basepath');
586 if (!$basepath && x($_SERVER, 'DOCUMENT_ROOT')) {
587 $basepath = $_SERVER['DOCUMENT_ROOT'];
590 if (!$basepath && x($_SERVER, 'PWD')) {
591 $basepath = $_SERVER['PWD'];
594 return self::realpath($basepath);
598 * @brief Returns a normalized file path
600 * This is a wrapper for the "realpath" function.
601 * That function cannot detect the real path when some folders aren't readable.
602 * Since this could happen with some hosters we need to handle this.
604 * @param string $path The path that is about to be normalized
605 * @return string normalized path - when possible
607 public static function realpath($path)
609 $normalized = realpath($path);
611 if (!is_bool($normalized)) {
618 public function get_scheme()
620 return $this->scheme;
624 * @brief Retrieves the Friendica instance base URL
626 * This function assembles the base URL from multiple parts:
627 * - Protocol is determined either by the request or a combination of
628 * system.ssl_policy and the $ssl parameter.
629 * - Host name is determined either by system.hostname or inferred from request
630 * - Path is inferred from SCRIPT_NAME
632 * Note: $ssl parameter value doesn't directly correlate with the resulting protocol
634 * @param bool $ssl Whether to append http or https under SSL_POLICY_SELFSIGN
635 * @return string Friendica server base URL
637 public function get_baseurl($ssl = false)
639 $scheme = $this->scheme;
641 if (Config::get('system', 'ssl_policy') == SSL_POLICY_FULL) {
645 // Basically, we have $ssl = true on any links which can only be seen by a logged in user
646 // (and also the login link). Anything seen by an outsider will have it turned off.
648 if (Config::get('system', 'ssl_policy') == SSL_POLICY_SELFSIGN) {
656 if (Config::get('config', 'hostname') != '') {
657 $this->hostname = Config::get('config', 'hostname');
660 return $scheme . '://' . $this->hostname . (!empty($this->urlpath) ? '/' . $this->urlpath : '' );
664 * @brief Initializes the baseurl components
666 * Clears the baseurl cache to prevent inconsistencies
670 public function set_baseurl($url)
672 $parsed = @parse_url($url);
676 if (!empty($parsed['scheme'])) {
677 $this->scheme = $parsed['scheme'];
680 if (!empty($parsed['host'])) {
681 $hostname = $parsed['host'];
684 if (x($parsed, 'port')) {
685 $hostname .= ':' . $parsed['port'];
687 if (x($parsed, 'path')) {
688 $this->urlpath = trim($parsed['path'], '\\/');
691 if (file_exists($this->basepath . DIRECTORY_SEPARATOR . '.htpreconfig.php')) {
692 include $this->basepath . DIRECTORY_SEPARATOR . '.htpreconfig.php';
695 if (Config::get('config', 'hostname') != '') {
696 $this->hostname = Config::get('config', 'hostname');
699 if (!isset($this->hostname) || ($this->hostname == '')) {
700 $this->hostname = $hostname;
705 public function get_hostname()
707 if (Config::get('config', 'hostname') != '') {
708 $this->hostname = Config::get('config', 'hostname');
711 return $this->hostname;
714 public function get_path()
716 return $this->urlpath;
719 public function set_pager_total($n)
721 $this->pager['total'] = intval($n);
724 public function set_pager_itemspage($n)
726 $this->pager['itemspage'] = ((intval($n) > 0) ? intval($n) : 0);
727 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
730 public function set_pager_page($n)
732 $this->pager['page'] = $n;
733 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
736 public function init_pagehead()
738 $interval = ((local_user()) ? PConfig::get(local_user(), 'system', 'update_interval') : 40000);
740 // If the update is 'deactivated' set it to the highest integer number (~24 days)
742 $interval = 2147483647;
745 if ($interval < 10000) {
749 // compose the page title from the sitename and the
750 // current module called
751 if (!$this->module == '') {
752 $this->page['title'] = $this->config['sitename'] . ' (' . $this->module . ')';
754 $this->page['title'] = $this->config['sitename'];
757 /* put the head template at the beginning of page['htmlhead']
758 * since the code added by the modules frequently depends on it
761 if (!isset($this->page['htmlhead'])) {
762 $this->page['htmlhead'] = '';
765 // If we're using Smarty, then doing replace_macros() will replace
766 // any unrecognized variables with a blank string. Since we delay
767 // replacing $stylesheet until later, we need to replace it now
768 // with another variable name
769 if ($this->theme['template_engine'] === 'smarty3') {
770 $stylesheet = $this->get_template_ldelim('smarty3') . '$stylesheet' . $this->get_template_rdelim('smarty3');
772 $stylesheet = '$stylesheet';
775 $shortcut_icon = Config::get('system', 'shortcut_icon');
776 if ($shortcut_icon == '') {
777 $shortcut_icon = 'images/friendica-32.png';
780 $touch_icon = Config::get('system', 'touch_icon');
781 if ($touch_icon == '') {
782 $touch_icon = 'images/friendica-128.png';
785 // get data wich is needed for infinite scroll on the network page
786 $invinite_scroll = infinite_scroll_data($this->module);
788 $tpl = get_markup_template('head.tpl');
789 $this->page['htmlhead'] = replace_macros($tpl, [
790 '$baseurl' => $this->get_baseurl(),
791 '$local_user' => local_user(),
792 '$generator' => 'Friendica' . ' ' . FRIENDICA_VERSION,
793 '$delitem' => L10n::t('Delete this item?'),
794 '$showmore' => L10n::t('show more'),
795 '$showfewer' => L10n::t('show fewer'),
796 '$update_interval' => $interval,
797 '$shortcut_icon' => $shortcut_icon,
798 '$touch_icon' => $touch_icon,
799 '$stylesheet' => $stylesheet,
800 '$infinite_scroll' => $invinite_scroll,
801 '$block_public' => intval(Config::get('system', 'block_public')),
802 ]) . $this->page['htmlhead'];
805 public function init_page_end()
807 if (!isset($this->page['end'])) {
808 $this->page['end'] = '';
810 $tpl = get_markup_template('end.tpl');
811 $this->page['end'] = replace_macros($tpl, [
812 '$baseurl' => $this->get_baseurl()
813 ]) . $this->page['end'];
816 public function set_curl_code($code)
818 $this->curl_code = $code;
821 public function get_curl_code()
823 return $this->curl_code;
826 public function set_curl_content_type($content_type)
828 $this->curl_content_type = $content_type;
831 public function get_curl_content_type()
833 return $this->curl_content_type;
836 public function set_curl_headers($headers)
838 $this->curl_headers = $headers;
841 public function get_curl_headers()
843 return $this->curl_headers;
847 * @brief Removes the base url from an url. This avoids some mixed content problems.
849 * @param string $orig_url
851 * @return string The cleaned url
853 public function remove_baseurl($orig_url)
855 // Remove the hostname from the url if it is an internal link
856 $nurl = normalise_link($orig_url);
857 $base = normalise_link($this->get_baseurl());
858 $url = str_replace($base . '/', '', $nurl);
860 // if it is an external link return the orignal value
861 if ($url == normalise_link($orig_url)) {
869 * @brief Register template engine class
871 * @param string $class
873 private function register_template_engine($class)
875 $v = get_class_vars($class);
878 $this->template_engines[$name] = $class;
880 echo "template engine <tt>$class</tt> cannot be registered without a name.\n";
886 * @brief Return template engine instance.
888 * If $name is not defined, return engine defined by theme,
891 * @return object Template Engine instance
893 public function template_engine()
895 $template_engine = 'smarty3';
896 if (x($this->theme, 'template_engine')) {
897 $template_engine = $this->theme['template_engine'];
900 if (isset($this->template_engines[$template_engine])) {
901 if (isset($this->template_engine_instance[$template_engine])) {
902 return $this->template_engine_instance[$template_engine];
904 $class = $this->template_engines[$template_engine];
906 $this->template_engine_instance[$template_engine] = $obj;
911 echo "template engine <tt>$template_engine</tt> is not registered!\n";
916 * @brief Returns the active template engine.
920 public function get_template_engine()
922 return $this->theme['template_engine'];
925 public function set_template_engine($engine = 'smarty3')
927 $this->theme['template_engine'] = $engine;
930 public function get_template_ldelim($engine = 'smarty3')
932 return $this->ldelim[$engine];
935 public function get_template_rdelim($engine = 'smarty3')
937 return $this->rdelim[$engine];
940 public function save_timestamp($stamp, $value)
942 if (!isset($this->config['system']['profiler']) || !$this->config['system']['profiler']) {
946 $duration = (float) (microtime(true) - $stamp);
948 if (!isset($this->performance[$value])) {
949 // Prevent ugly E_NOTICE
950 $this->performance[$value] = 0;
953 $this->performance[$value] += (float) $duration;
954 $this->performance['marktime'] += (float) $duration;
956 $callstack = System::callstack();
958 if (!isset($this->callstack[$value][$callstack])) {
959 // Prevent ugly E_NOTICE
960 $this->callstack[$value][$callstack] = 0;
963 $this->callstack[$value][$callstack] += (float) $duration;
966 public function get_useragent()
969 FRIENDICA_PLATFORM . " '" .
970 FRIENDICA_CODENAME . "' " .
971 FRIENDICA_VERSION . '-' .
972 DB_UPDATE_VERSION . '; ' .
973 $this->get_baseurl();
976 public function is_friendica_app()
978 return $this->is_friendica_app;
982 * @brief Checks if the site is called via a backend process
984 * This isn't a perfect solution. But we need this check very early.
985 * So we cannot wait until the modules are loaded.
987 * @return bool Is it a known backend?
989 public function is_backend()
1013 // Check if current module is in backend or backend flag is set
1014 return (in_array($this->module, $backends) || $this->backend);
1018 * @brief Checks if the maximum number of database processes is reached
1020 * @return bool Is the limit reached?
1022 public function isMaxProcessesReached()
1024 // Deactivated, needs more investigating if this check really makes sense
1028 * Commented out to suppress static analyzer issues
1030 if ($this->is_backend()) {
1031 $process = 'backend';
1032 $max_processes = Config::get('system', 'max_processes_backend');
1033 if (intval($max_processes) == 0) {
1037 $process = 'frontend';
1038 $max_processes = Config::get('system', 'max_processes_frontend');
1039 if (intval($max_processes) == 0) {
1040 $max_processes = 20;
1044 $processlist = DBA::processlist();
1045 if ($processlist['list'] != '') {
1046 logger('Processcheck: Processes: ' . $processlist['amount'] . ' - Processlist: ' . $processlist['list'], LOGGER_DEBUG);
1048 if ($processlist['amount'] > $max_processes) {
1049 logger('Processcheck: Maximum number of processes for ' . $process . ' tasks (' . $max_processes . ') reached.', LOGGER_DEBUG);
1058 * @brief Checks if the minimal memory is reached
1060 * @return bool Is the memory limit reached?
1062 public function min_memory_reached()
1064 $min_memory = Config::get('system', 'min_memory', 0);
1065 if ($min_memory == 0) {
1069 if (!is_readable('/proc/meminfo')) {
1073 $memdata = explode("\n", file_get_contents('/proc/meminfo'));
1076 foreach ($memdata as $line) {
1077 list($key, $val) = explode(':', $line);
1078 $meminfo[$key] = (int) trim(str_replace('kB', '', $val));
1079 $meminfo[$key] = (int) ($meminfo[$key] / 1024);
1082 if (!isset($meminfo['MemAvailable']) || !isset($meminfo['MemFree'])) {
1086 $free = $meminfo['MemAvailable'] + $meminfo['MemFree'];
1088 $reached = ($free < $min_memory);
1091 logger('Minimal memory reached: ' . $free . '/' . $meminfo['MemTotal'] . ' - limit ' . $min_memory, LOGGER_DEBUG);
1098 * @brief Checks if the maximum load is reached
1100 * @return bool Is the load reached?
1102 public function isMaxLoadReached()
1104 if ($this->is_backend()) {
1105 $process = 'backend';
1106 $maxsysload = intval(Config::get('system', 'maxloadavg'));
1107 if ($maxsysload < 1) {
1111 $process = 'frontend';
1112 $maxsysload = intval(Config::get('system', 'maxloadavg_frontend'));
1113 if ($maxsysload < 1) {
1118 $load = current_load();
1120 if (intval($load) > $maxsysload) {
1121 logger('system: load ' . $load . ' for ' . $process . ' tasks (' . $maxsysload . ') too high.');
1129 * Executes a child process with 'proc_open'
1131 * @param string $command The command to execute
1132 * @param array $args Arguments to pass to the command ( [ 'key' => value, 'key2' => value2, ... ]
1134 public function proc_run($command, $args)
1136 if (!function_exists('proc_open')) {
1140 $cmdline = $this->getConfigValue('config', 'php_path', 'php') . ' ' . escapeshellarg($command);
1142 foreach ($args as $key => $value) {
1143 if (!is_null($value) && is_bool($value) && !$value) {
1147 $cmdline .= ' --' . $key;
1148 if (!is_null($value) && !is_bool($value)) {
1149 $cmdline .= ' ' . $value;
1153 if ($this->min_memory_reached()) {
1157 if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
1158 $resource = proc_open('cmd /c start /b ' . $cmdline, [], $foo, $this->get_basepath());
1160 $resource = proc_open($cmdline . ' &', [], $foo, $this->get_basepath());
1162 if (!is_resource($resource)) {
1163 logger('We got no resource for command ' . $cmdline, LOGGER_DEBUG);
1166 proc_close($resource);
1170 * @brief Returns the system user that is executing the script
1172 * This mostly returns something like "www-data".
1174 * @return string system username
1176 private static function systemuser()
1178 if (!function_exists('posix_getpwuid') || !function_exists('posix_geteuid')) {
1182 $processUser = posix_getpwuid(posix_geteuid());
1183 return $processUser['name'];
1187 * @brief Checks if a given directory is usable for the system
1189 * @return boolean the directory is usable
1191 public static function directory_usable($directory, $check_writable = true)
1193 if ($directory == '') {
1194 logger('Directory is empty. This shouldn\'t happen.', LOGGER_DEBUG);
1198 if (!file_exists($directory)) {
1199 logger('Path "' . $directory . '" does not exist for user ' . self::systemuser(), LOGGER_DEBUG);
1203 if (is_file($directory)) {
1204 logger('Path "' . $directory . '" is a file for user ' . self::systemuser(), LOGGER_DEBUG);
1208 if (!is_dir($directory)) {
1209 logger('Path "' . $directory . '" is not a directory for user ' . self::systemuser(), LOGGER_DEBUG);
1213 if ($check_writable && !is_writable($directory)) {
1214 logger('Path "' . $directory . '" is not writable for user ' . self::systemuser(), LOGGER_DEBUG);
1222 * @param string $cat Config category
1223 * @param string $k Config key
1224 * @param mixed $default Default value if it isn't set
1226 public function getConfigValue($cat, $k, $default = null)
1230 if ($cat === 'config') {
1231 if (isset($this->config[$k])) {
1232 $return = $this->config[$k];
1235 if (isset($this->config[$cat][$k])) {
1236 $return = $this->config[$cat][$k];
1244 * Sets a value in the config cache. Accepts raw output from the config table
1246 * @param string $cat Config category
1247 * @param string $k Config key
1248 * @param mixed $v Value to set
1250 public function setConfigValue($cat, $k, $v)
1252 // Only arrays are serialized in database, so we have to unserialize sparingly
1253 $value = is_string($v) && preg_match("|^a:[0-9]+:{.*}$|s", $v) ? unserialize($v) : $v;
1255 if ($cat === 'config') {
1256 $this->config[$k] = $value;
1258 if (!isset($this->config[$cat])) {
1259 $this->config[$cat] = [];
1262 $this->config[$cat][$k] = $value;
1267 * Deletes a value from the config cache
1269 * @param string $cat Config category
1270 * @param string $k Config key
1272 public function deleteConfigValue($cat, $k)
1274 if ($cat === 'config') {
1275 if (isset($this->config[$k])) {
1276 unset($this->config[$k]);
1279 if (isset($this->config[$cat][$k])) {
1280 unset($this->config[$cat][$k]);
1287 * Retrieves a value from the user config cache
1289 * @param int $uid User Id
1290 * @param string $cat Config category
1291 * @param string $k Config key
1292 * @param mixed $default Default value if key isn't set
1294 public function getPConfigValue($uid, $cat, $k, $default = null)
1298 if (isset($this->config[$uid][$cat][$k])) {
1299 $return = $this->config[$uid][$cat][$k];
1306 * Sets a value in the user config cache
1308 * Accepts raw output from the pconfig table
1310 * @param int $uid User Id
1311 * @param string $cat Config category
1312 * @param string $k Config key
1313 * @param mixed $v Value to set
1315 public function setPConfigValue($uid, $cat, $k, $v)
1317 // Only arrays are serialized in database, so we have to unserialize sparingly
1318 $value = is_string($v) && preg_match("|^a:[0-9]+:{.*}$|s", $v) ? unserialize($v) : $v;
1320 if (!isset($this->config[$uid]) || !is_array($this->config[$uid])) {
1321 $this->config[$uid] = [];
1324 if (!isset($this->config[$uid][$cat]) || !is_array($this->config[$uid][$cat])) {
1325 $this->config[$uid][$cat] = [];
1328 $this->config[$uid][$cat][$k] = $value;
1332 * Deletes a value from the user config cache
1334 * @param int $uid User Id
1335 * @param string $cat Config category
1336 * @param string $k Config key
1338 public function deletePConfigValue($uid, $cat, $k)
1340 if (isset($this->config[$uid][$cat][$k])) {
1341 unset($this->config[$uid][$cat][$k]);
1346 * Generates the site's default sender email address
1350 public function getSenderEmailAddress()
1352 $sender_email = Config::get('config', 'sender_email');
1353 if (empty($sender_email)) {
1354 $hostname = $this->get_hostname();
1355 if (strpos($hostname, ':')) {
1356 $hostname = substr($hostname, 0, strpos($hostname, ':'));
1359 $sender_email = 'noreply@' . $hostname;
1362 return $sender_email;
1366 * Returns the current theme name.
1370 public function getCurrentTheme()
1372 if ($this->isInstallMode()) {
1376 //// @TODO Compute the current theme only once (this behavior has
1377 /// already been implemented, but it didn't work well -
1378 /// https://github.com/friendica/friendica/issues/5092)
1379 $this->computeCurrentTheme();
1381 return $this->current_theme;
1385 * Computes the current theme name based on the node settings, the user settings and the device type
1389 private function computeCurrentTheme()
1391 $system_theme = Config::get('system', 'theme');
1392 if (!$system_theme) {
1393 throw new Exception(L10n::t('No system theme config value set.'));
1397 $this->current_theme = $system_theme;
1399 $allowed_themes = explode(',', Config::get('system', 'allowed_themes', $system_theme));
1402 // Find the theme that belongs to the user whose stuff we are looking at
1403 if ($this->profile_uid && ($this->profile_uid != local_user())) {
1404 // Allow folks to override user themes and always use their own on their own site.
1405 // This works only if the user is on the same server
1406 $user = DBA::selectFirst('user', ['theme'], ['uid' => $this->profile_uid]);
1407 if (DBA::isResult($user) && !PConfig::get(local_user(), 'system', 'always_my_theme')) {
1408 $page_theme = $user['theme'];
1412 $user_theme = Core\Session::get('theme', $system_theme);
1414 // Specific mobile theme override
1415 if (($this->is_mobile || $this->is_tablet) && Core\Session::get('show-mobile', true)) {
1416 $system_mobile_theme = Config::get('system', 'mobile-theme');
1417 $user_mobile_theme = Core\Session::get('mobile-theme', $system_mobile_theme);
1419 // --- means same mobile theme as desktop
1420 if (!empty($user_mobile_theme) && $user_mobile_theme !== '---') {
1421 $user_theme = $user_mobile_theme;
1426 $theme_name = $page_theme;
1428 $theme_name = $user_theme;
1432 && in_array($theme_name, $allowed_themes)
1433 && (file_exists('view/theme/' . $theme_name . '/style.css')
1434 || file_exists('view/theme/' . $theme_name . '/style.php'))
1436 $this->current_theme = $theme_name;
1441 * @brief Return full URL to theme which is currently in effect.
1443 * Provide a sane default if nothing is chosen or the specified theme does not exist.
1447 public function getCurrentThemeStylesheetPath()
1449 return Core\Theme::getStylesheetPath($this->getCurrentTheme());