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'] = [];
177 // The order of the following calls is important to ensure proper initialization
178 $this->loadConfigFiles();
180 $this->loadDatabase();
182 $this->determineMode();
184 $this->determineUrlPath();
188 if ($this->mode & self::MODE_DBAVAILABLE) {
189 Core\Addon::loadHooks();
191 $this->loadAddonConfig();
194 $this->loadDefaultTimezone();
210 $this->process_id = System::processID('log');
214 // This has to be quite large to deal with embedded private photos
215 ini_set('pcre.backtrack_limit', 500000);
217 $this->scheme = 'http';
219 if ((x($_SERVER, 'HTTPS') && $_SERVER['HTTPS']) ||
220 (x($_SERVER, 'HTTP_FORWARDED') && preg_match('/proto=https/', $_SERVER['HTTP_FORWARDED'])) ||
221 (x($_SERVER, 'HTTP_X_FORWARDED_PROTO') && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') ||
222 (x($_SERVER, 'HTTP_X_FORWARDED_SSL') && $_SERVER['HTTP_X_FORWARDED_SSL'] == 'on') ||
223 (x($_SERVER, 'FRONT_END_HTTPS') && $_SERVER['FRONT_END_HTTPS'] == 'on') ||
224 (x($_SERVER, 'SERVER_PORT') && (intval($_SERVER['SERVER_PORT']) == 443)) // XXX: reasonable assumption, but isn't this hardcoding too much?
226 $this->scheme = 'https';
229 if (x($_SERVER, 'SERVER_NAME')) {
230 $this->hostname = $_SERVER['SERVER_NAME'];
232 if (x($_SERVER, 'SERVER_PORT') && $_SERVER['SERVER_PORT'] != 80 && $_SERVER['SERVER_PORT'] != 443) {
233 $this->hostname .= ':' . $_SERVER['SERVER_PORT'];
238 get_include_path() . PATH_SEPARATOR
239 . $this->basepath . DIRECTORY_SEPARATOR . 'include' . PATH_SEPARATOR
240 . $this->basepath . DIRECTORY_SEPARATOR . 'library' . PATH_SEPARATOR
243 if ((x($_SERVER, 'QUERY_STRING')) && substr($_SERVER['QUERY_STRING'], 0, 9) === 'pagename=') {
244 $this->query_string = substr($_SERVER['QUERY_STRING'], 9);
245 } elseif ((x($_SERVER, 'QUERY_STRING')) && substr($_SERVER['QUERY_STRING'], 0, 2) === 'q=') {
246 $this->query_string = substr($_SERVER['QUERY_STRING'], 2);
249 // removing trailing / - maybe a nginx problem
250 $this->query_string = ltrim($this->query_string, '/');
252 if (!empty($_GET['pagename'])) {
253 $this->cmd = trim($_GET['pagename'], '/\\');
254 } elseif (!empty($_GET['q'])) {
255 $this->cmd = trim($_GET['q'], '/\\');
259 $this->query_string = str_replace($this->cmd . '&', $this->cmd . '?', $this->query_string);
261 // unix style "homedir"
262 if (substr($this->cmd, 0, 1) === '~') {
263 $this->cmd = 'profile/' . substr($this->cmd, 1);
266 // Diaspora style profile url
267 if (substr($this->cmd, 0, 2) === 'u/') {
268 $this->cmd = 'profile/' . substr($this->cmd, 2);
272 * Break the URL path into C style argc/argv style arguments for our
273 * modules. Given "http://example.com/module/arg1/arg2", $this->argc
274 * will be 3 (integer) and $this->argv will contain:
280 * There will always be one argument. If provided a naked domain
281 * URL, $this->argv[0] is set to "home".
284 $this->argv = explode('/', $this->cmd);
285 $this->argc = count($this->argv);
286 if ((array_key_exists('0', $this->argv)) && strlen($this->argv[0])) {
287 $this->module = str_replace('.', '_', $this->argv[0]);
288 $this->module = str_replace('-', '_', $this->module);
291 $this->argv = ['home'];
292 $this->module = 'home';
295 // See if there is any page number information, and initialise pagination
296 $this->pager['page'] = ((x($_GET, 'page') && intval($_GET['page']) > 0) ? intval($_GET['page']) : 1);
297 $this->pager['itemspage'] = 50;
298 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
300 if ($this->pager['start'] < 0) {
301 $this->pager['start'] = 0;
303 $this->pager['total'] = 0;
305 // Detect mobile devices
306 $mobile_detect = new MobileDetect();
307 $this->is_mobile = $mobile_detect->isMobile();
308 $this->is_tablet = $mobile_detect->isTablet();
311 $this->is_friendica_app = isset($_SERVER['HTTP_USER_AGENT']) && $_SERVER['HTTP_USER_AGENT'] == 'Apache-HttpClient/UNAVAILABLE (java 1.4)';
313 // Register template engines
314 $this->register_template_engine('Friendica\Render\FriendicaSmartyEngine');
318 * Load the configuration files
320 * First loads the default value for all the configuration keys, then the legacy configuration files, then the
321 * expected local.ini.php
323 private function loadConfigFiles()
325 $this->loadConfigFile($this->basepath . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'config.ini.php');
326 $this->loadConfigFile($this->basepath . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'settings.ini.php');
328 // Legacy .htconfig.php support
329 if (file_exists($this->basepath . DIRECTORY_SEPARATOR . '.htpreconfig.php')) {
331 include $this->basepath . DIRECTORY_SEPARATOR . '.htpreconfig.php';
334 // Legacy .htconfig.php support
335 if (file_exists($this->basepath . DIRECTORY_SEPARATOR . '.htconfig.php')) {
338 include $this->basepath . DIRECTORY_SEPARATOR . '.htconfig.php';
340 $this->setConfigValue('database', 'hostname', $db_host);
341 $this->setConfigValue('database', 'username', $db_user);
342 $this->setConfigValue('database', 'password', $db_pass);
343 $this->setConfigValue('database', 'database', $db_data);
344 if (isset($a->config['system']['db_charset'])) {
345 $this->setConfigValue('database', 'charset', $a->config['system']['db_charset']);
348 unset($db_host, $db_user, $db_pass, $db_data);
350 if (isset($default_timezone)) {
351 $this->setConfigValue('system', 'default_timezone', $default_timezone);
352 unset($default_timezone);
355 if (isset($pidfile)) {
356 $this->setConfigValue('system', 'pidfile', $pidfile);
361 $this->setConfigValue('system', 'language', $lang);
366 if (file_exists($this->basepath . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'local.ini.php')) {
367 $this->loadConfigFile($this->basepath . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'local.ini.php');
372 * Tries to load the specified configuration file into the App->config array.
373 * Overwrites previously set values.
375 * The config format is INI and the template for configuration files is the following:
377 * <?php return <<<INI
385 * @param type $filepath
388 public function loadConfigFile($filepath)
390 if (!file_exists($filepath)) {
391 throw new Exception('Error parsing non-existent config file ' . $filepath);
394 $contents = include($filepath);
396 $config = parse_ini_string($contents, true, INI_SCANNER_TYPED);
398 if ($config === false) {
399 throw new Exception('Error parsing config file ' . $filepath);
402 foreach ($config as $category => $values) {
403 foreach ($values as $key => $value) {
404 $this->setConfigValue($category, $key, $value);
410 * Loads addons configuration files
412 * First loads all activated addons default configuration throught the load_config hook, then load the local.ini.php
413 * again to overwrite potential local addon configuration.
415 private function loadAddonConfig()
417 // Loads addons default config
418 Core\Addon::callHooks('load_config');
420 // Load the local addon config file to overwritten default addon config values
421 if (file_exists($this->basepath . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'addon.ini.php')) {
422 $this->loadConfigFile($this->basepath . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'addon.ini.php');
427 * Loads the default timezone
429 * Include support for legacy $default_timezone
431 * @global string $default_timezone
433 private function loadDefaultTimezone()
435 if ($this->getConfigValue('system', 'default_timezone')) {
436 $this->timezone = $this->getConfigValue('system', 'default_timezone');
438 global $default_timezone;
439 $this->timezone = !empty($default_timezone) ? $default_timezone : 'UTC';
442 if ($this->timezone) {
443 date_default_timezone_set($this->timezone);
448 * Figure out if we are running at the top of a domain or in a sub-directory and adjust accordingly
450 private function determineUrlPath()
452 $this->urlpath = $this->getConfigValue('system', 'urlpath');
454 /* SCRIPT_URL gives /path/to/friendica/module/parameter
455 * QUERY_STRING gives pagename=module/parameter
457 * To get /path/to/friendica we perform dirname() for as many levels as there are slashes in the QUERY_STRING
459 if (!empty($_SERVER['SCRIPT_URL'])) {
461 if (!empty($_SERVER['QUERY_STRING'])) {
462 $path = trim(dirname($_SERVER['SCRIPT_URL'], substr_count(trim($_SERVER['QUERY_STRING'], '/'), '/') + 1), '/');
465 $path = trim($_SERVER['SCRIPT_URL'], '/');
468 if ($path && $path != $this->urlpath) {
469 $this->urlpath = $path;
477 * - App::MODE_INSTALL : Either the database connection can't be established or the config table doesn't exist
478 * - App::MODE_MAINTENANCE: The maintenance mode has been set
479 * - App::MODE_NORMAL : Normal run with all features enabled
483 private function determineMode()
487 if (!file_exists($this->basepath . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'local.ini.php')
488 && !file_exists($this->basepath . DIRECTORY_SEPARATOR . '.htconfig.php')) {
492 $this->mode |= App::MODE_LOCALCONFIGPRESENT;
494 if (!DBA::connected()) {
498 $this->mode |= App::MODE_DBAVAILABLE;
500 if (DBA::fetchFirst("SHOW TABLES LIKE 'config'") === false) {
504 $this->mode |= App::MODE_DBCONFIGAVAILABLE;
506 if (Config::get('system', 'maintenance')) {
510 $this->mode |= App::MODE_MAINTENANCEDISABLED;
513 public function loadDatabase()
515 if (DBA::connected()) {
519 $db_host = $this->getConfigValue('database', 'hostname');
520 $db_user = $this->getConfigValue('database', 'username');
521 $db_pass = $this->getConfigValue('database', 'password');
522 $db_data = $this->getConfigValue('database', 'database');
523 $charset = $this->getConfigValue('database', 'charset');
525 // Use environment variables for mysql if they are set beforehand
526 if (!empty(getenv('MYSQL_HOST'))
527 && (!empty(getenv('MYSQL_USERNAME')) || !empty(getenv('MYSQL_USER')))
528 && getenv('MYSQL_PASSWORD') !== false
529 && !empty(getenv('MYSQL_DATABASE')))
531 $db_host = getenv('MYSQL_HOST');
532 if (!empty(getenv('MYSQL_PORT'))) {
533 $db_host .= ':' . getenv('MYSQL_PORT');
535 if (!empty(getenv('MYSQL_USERNAME'))) {
536 $db_user = getenv('MYSQL_USERNAME');
538 $db_user = getenv('MYSQL_USER');
540 $db_pass = (string) getenv('MYSQL_PASSWORD');
541 $db_data = getenv('MYSQL_DATABASE');
544 $stamp1 = microtime(true);
546 DBA::connect($db_host, $db_user, $db_pass, $db_data, $charset);
547 unset($db_host, $db_user, $db_pass, $db_data, $charset);
549 $this->save_timestamp($stamp1, 'network');
553 * Install mode is when the local config file is missing or the DB schema hasn't been installed yet.
557 public function isInstallMode()
559 return !($this->mode & App::MODE_LOCALCONFIGPRESENT) || !($this->mode & App::MODE_DBCONFIGAVAILABLE);
563 * @brief Returns the base filesystem path of the App
565 * It first checks for the internal variable, then for DOCUMENT_ROOT and
570 public function get_basepath()
572 $basepath = $this->basepath;
575 $basepath = Config::get('system', 'basepath');
578 if (!$basepath && x($_SERVER, 'DOCUMENT_ROOT')) {
579 $basepath = $_SERVER['DOCUMENT_ROOT'];
582 if (!$basepath && x($_SERVER, 'PWD')) {
583 $basepath = $_SERVER['PWD'];
586 return self::realpath($basepath);
590 * @brief Returns a normalized file path
592 * This is a wrapper for the "realpath" function.
593 * That function cannot detect the real path when some folders aren't readable.
594 * Since this could happen with some hosters we need to handle this.
596 * @param string $path The path that is about to be normalized
597 * @return string normalized path - when possible
599 public static function realpath($path)
601 $normalized = realpath($path);
603 if (!is_bool($normalized)) {
610 public function get_scheme()
612 return $this->scheme;
616 * @brief Retrieves the Friendica instance base URL
618 * This function assembles the base URL from multiple parts:
619 * - Protocol is determined either by the request or a combination of
620 * system.ssl_policy and the $ssl parameter.
621 * - Host name is determined either by system.hostname or inferred from request
622 * - Path is inferred from SCRIPT_NAME
624 * Note: $ssl parameter value doesn't directly correlate with the resulting protocol
626 * @param bool $ssl Whether to append http or https under SSL_POLICY_SELFSIGN
627 * @return string Friendica server base URL
629 public function get_baseurl($ssl = false)
631 $scheme = $this->scheme;
633 if (Config::get('system', 'ssl_policy') == SSL_POLICY_FULL) {
637 // Basically, we have $ssl = true on any links which can only be seen by a logged in user
638 // (and also the login link). Anything seen by an outsider will have it turned off.
640 if (Config::get('system', 'ssl_policy') == SSL_POLICY_SELFSIGN) {
648 if (Config::get('config', 'hostname') != '') {
649 $this->hostname = Config::get('config', 'hostname');
652 return $scheme . '://' . $this->hostname . (!empty($this->urlpath) ? '/' . $this->urlpath : '' );
656 * @brief Initializes the baseurl components
658 * Clears the baseurl cache to prevent inconsistencies
662 public function set_baseurl($url)
664 $parsed = @parse_url($url);
668 if (!empty($parsed['scheme'])) {
669 $this->scheme = $parsed['scheme'];
672 if (!empty($parsed['host'])) {
673 $hostname = $parsed['host'];
676 if (x($parsed, 'port')) {
677 $hostname .= ':' . $parsed['port'];
679 if (x($parsed, 'path')) {
680 $this->urlpath = trim($parsed['path'], '\\/');
683 if (file_exists($this->basepath . DIRECTORY_SEPARATOR . '.htpreconfig.php')) {
684 include $this->basepath . DIRECTORY_SEPARATOR . '.htpreconfig.php';
687 if (Config::get('config', 'hostname') != '') {
688 $this->hostname = Config::get('config', 'hostname');
691 if (!isset($this->hostname) || ($this->hostname == '')) {
692 $this->hostname = $hostname;
697 public function get_hostname()
699 if (Config::get('config', 'hostname') != '') {
700 $this->hostname = Config::get('config', 'hostname');
703 return $this->hostname;
706 public function get_path()
708 return $this->urlpath;
711 public function set_pager_total($n)
713 $this->pager['total'] = intval($n);
716 public function set_pager_itemspage($n)
718 $this->pager['itemspage'] = ((intval($n) > 0) ? intval($n) : 0);
719 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
722 public function set_pager_page($n)
724 $this->pager['page'] = $n;
725 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
728 public function init_pagehead()
730 $interval = ((local_user()) ? PConfig::get(local_user(), 'system', 'update_interval') : 40000);
732 // If the update is 'deactivated' set it to the highest integer number (~24 days)
734 $interval = 2147483647;
737 if ($interval < 10000) {
741 // compose the page title from the sitename and the
742 // current module called
743 if (!$this->module == '') {
744 $this->page['title'] = $this->config['sitename'] . ' (' . $this->module . ')';
746 $this->page['title'] = $this->config['sitename'];
749 /* put the head template at the beginning of page['htmlhead']
750 * since the code added by the modules frequently depends on it
753 if (!isset($this->page['htmlhead'])) {
754 $this->page['htmlhead'] = '';
757 // If we're using Smarty, then doing replace_macros() will replace
758 // any unrecognized variables with a blank string. Since we delay
759 // replacing $stylesheet until later, we need to replace it now
760 // with another variable name
761 if ($this->theme['template_engine'] === 'smarty3') {
762 $stylesheet = $this->get_template_ldelim('smarty3') . '$stylesheet' . $this->get_template_rdelim('smarty3');
764 $stylesheet = '$stylesheet';
767 $shortcut_icon = Config::get('system', 'shortcut_icon');
768 if ($shortcut_icon == '') {
769 $shortcut_icon = 'images/friendica-32.png';
772 $touch_icon = Config::get('system', 'touch_icon');
773 if ($touch_icon == '') {
774 $touch_icon = 'images/friendica-128.png';
777 // get data wich is needed for infinite scroll on the network page
778 $invinite_scroll = infinite_scroll_data($this->module);
780 $tpl = get_markup_template('head.tpl');
781 $this->page['htmlhead'] = replace_macros($tpl, [
782 '$baseurl' => $this->get_baseurl(),
783 '$local_user' => local_user(),
784 '$generator' => 'Friendica' . ' ' . FRIENDICA_VERSION,
785 '$delitem' => L10n::t('Delete this item?'),
786 '$showmore' => L10n::t('show more'),
787 '$showfewer' => L10n::t('show fewer'),
788 '$update_interval' => $interval,
789 '$shortcut_icon' => $shortcut_icon,
790 '$touch_icon' => $touch_icon,
791 '$stylesheet' => $stylesheet,
792 '$infinite_scroll' => $invinite_scroll,
793 '$block_public' => intval(Config::get('system', 'block_public')),
794 ]) . $this->page['htmlhead'];
797 public function init_page_end()
799 if (!isset($this->page['end'])) {
800 $this->page['end'] = '';
802 $tpl = get_markup_template('end.tpl');
803 $this->page['end'] = replace_macros($tpl, [
804 '$baseurl' => $this->get_baseurl()
805 ]) . $this->page['end'];
808 public function set_curl_code($code)
810 $this->curl_code = $code;
813 public function get_curl_code()
815 return $this->curl_code;
818 public function set_curl_content_type($content_type)
820 $this->curl_content_type = $content_type;
823 public function get_curl_content_type()
825 return $this->curl_content_type;
828 public function set_curl_headers($headers)
830 $this->curl_headers = $headers;
833 public function get_curl_headers()
835 return $this->curl_headers;
839 * @brief Removes the base url from an url. This avoids some mixed content problems.
841 * @param string $orig_url
843 * @return string The cleaned url
845 public function remove_baseurl($orig_url)
847 // Remove the hostname from the url if it is an internal link
848 $nurl = normalise_link($orig_url);
849 $base = normalise_link($this->get_baseurl());
850 $url = str_replace($base . '/', '', $nurl);
852 // if it is an external link return the orignal value
853 if ($url == normalise_link($orig_url)) {
861 * @brief Register template engine class
863 * @param string $class
865 private function register_template_engine($class)
867 $v = get_class_vars($class);
870 $this->template_engines[$name] = $class;
872 echo "template engine <tt>$class</tt> cannot be registered without a name.\n";
878 * @brief Return template engine instance.
880 * If $name is not defined, return engine defined by theme,
883 * @return object Template Engine instance
885 public function template_engine()
887 $template_engine = 'smarty3';
888 if (x($this->theme, 'template_engine')) {
889 $template_engine = $this->theme['template_engine'];
892 if (isset($this->template_engines[$template_engine])) {
893 if (isset($this->template_engine_instance[$template_engine])) {
894 return $this->template_engine_instance[$template_engine];
896 $class = $this->template_engines[$template_engine];
898 $this->template_engine_instance[$template_engine] = $obj;
903 echo "template engine <tt>$template_engine</tt> is not registered!\n";
908 * @brief Returns the active template engine.
912 public function get_template_engine()
914 return $this->theme['template_engine'];
917 public function set_template_engine($engine = 'smarty3')
919 $this->theme['template_engine'] = $engine;
922 public function get_template_ldelim($engine = 'smarty3')
924 return $this->ldelim[$engine];
927 public function get_template_rdelim($engine = 'smarty3')
929 return $this->rdelim[$engine];
932 public function save_timestamp($stamp, $value)
934 if (!isset($this->config['system']['profiler']) || !$this->config['system']['profiler']) {
938 $duration = (float) (microtime(true) - $stamp);
940 if (!isset($this->performance[$value])) {
941 // Prevent ugly E_NOTICE
942 $this->performance[$value] = 0;
945 $this->performance[$value] += (float) $duration;
946 $this->performance['marktime'] += (float) $duration;
948 $callstack = System::callstack();
950 if (!isset($this->callstack[$value][$callstack])) {
951 // Prevent ugly E_NOTICE
952 $this->callstack[$value][$callstack] = 0;
955 $this->callstack[$value][$callstack] += (float) $duration;
958 public function get_useragent()
961 FRIENDICA_PLATFORM . " '" .
962 FRIENDICA_CODENAME . "' " .
963 FRIENDICA_VERSION . '-' .
964 DB_UPDATE_VERSION . '; ' .
965 $this->get_baseurl();
968 public function is_friendica_app()
970 return $this->is_friendica_app;
974 * @brief Checks if the site is called via a backend process
976 * This isn't a perfect solution. But we need this check very early.
977 * So we cannot wait until the modules are loaded.
979 * @return bool Is it a known backend?
981 public function is_backend()
1005 // Check if current module is in backend or backend flag is set
1006 return (in_array($this->module, $backends) || $this->backend);
1010 * @brief Checks if the maximum number of database processes is reached
1012 * @return bool Is the limit reached?
1014 public function isMaxProcessesReached()
1016 // Deactivated, needs more investigating if this check really makes sense
1020 * Commented out to suppress static analyzer issues
1022 if ($this->is_backend()) {
1023 $process = 'backend';
1024 $max_processes = Config::get('system', 'max_processes_backend');
1025 if (intval($max_processes) == 0) {
1029 $process = 'frontend';
1030 $max_processes = Config::get('system', 'max_processes_frontend');
1031 if (intval($max_processes) == 0) {
1032 $max_processes = 20;
1036 $processlist = DBA::processlist();
1037 if ($processlist['list'] != '') {
1038 logger('Processcheck: Processes: ' . $processlist['amount'] . ' - Processlist: ' . $processlist['list'], LOGGER_DEBUG);
1040 if ($processlist['amount'] > $max_processes) {
1041 logger('Processcheck: Maximum number of processes for ' . $process . ' tasks (' . $max_processes . ') reached.', LOGGER_DEBUG);
1050 * @brief Checks if the minimal memory is reached
1052 * @return bool Is the memory limit reached?
1054 public function min_memory_reached()
1056 $min_memory = Config::get('system', 'min_memory', 0);
1057 if ($min_memory == 0) {
1061 if (!is_readable('/proc/meminfo')) {
1065 $memdata = explode("\n", file_get_contents('/proc/meminfo'));
1068 foreach ($memdata as $line) {
1069 list($key, $val) = explode(':', $line);
1070 $meminfo[$key] = (int) trim(str_replace('kB', '', $val));
1071 $meminfo[$key] = (int) ($meminfo[$key] / 1024);
1074 if (!isset($meminfo['MemAvailable']) || !isset($meminfo['MemFree'])) {
1078 $free = $meminfo['MemAvailable'] + $meminfo['MemFree'];
1080 $reached = ($free < $min_memory);
1083 logger('Minimal memory reached: ' . $free . '/' . $meminfo['MemTotal'] . ' - limit ' . $min_memory, LOGGER_DEBUG);
1090 * @brief Checks if the maximum load is reached
1092 * @return bool Is the load reached?
1094 public function isMaxLoadReached()
1096 if ($this->is_backend()) {
1097 $process = 'backend';
1098 $maxsysload = intval(Config::get('system', 'maxloadavg'));
1099 if ($maxsysload < 1) {
1103 $process = 'frontend';
1104 $maxsysload = intval(Config::get('system', 'maxloadavg_frontend'));
1105 if ($maxsysload < 1) {
1110 $load = current_load();
1112 if (intval($load) > $maxsysload) {
1113 logger('system: load ' . $load . ' for ' . $process . ' tasks (' . $maxsysload . ') too high.');
1121 * Executes a child process with 'proc_open'
1123 * @param string $command The command to execute
1124 * @param array $args Arguments to pass to the command ( [ 'key' => value, 'key2' => value2, ... ]
1126 public function proc_run($command, $args)
1128 if (!function_exists('proc_open')) {
1132 $cmdline = $this->getConfigValue('config', 'php_path', 'php') . ' ' . escapeshellarg($command);
1134 foreach ($args as $key => $value) {
1135 if (!is_null($value) && is_bool($value) && !$value) {
1139 $cmdline .= ' --' . $key;
1140 if (!is_null($value) && !is_bool($value)) {
1141 $cmdline .= ' ' . $value;
1145 if ($this->min_memory_reached()) {
1149 if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
1150 $resource = proc_open('cmd /c start /b ' . $cmdline, [], $foo, $this->get_basepath());
1152 $resource = proc_open($cmdline . ' &', [], $foo, $this->get_basepath());
1154 if (!is_resource($resource)) {
1155 logger('We got no resource for command ' . $cmdline, LOGGER_DEBUG);
1158 proc_close($resource);
1162 * @brief Returns the system user that is executing the script
1164 * This mostly returns something like "www-data".
1166 * @return string system username
1168 private static function systemuser()
1170 if (!function_exists('posix_getpwuid') || !function_exists('posix_geteuid')) {
1174 $processUser = posix_getpwuid(posix_geteuid());
1175 return $processUser['name'];
1179 * @brief Checks if a given directory is usable for the system
1181 * @return boolean the directory is usable
1183 public static function directory_usable($directory, $check_writable = true)
1185 if ($directory == '') {
1186 logger('Directory is empty. This shouldn\'t happen.', LOGGER_DEBUG);
1190 if (!file_exists($directory)) {
1191 logger('Path "' . $directory . '" does not exist for user ' . self::systemuser(), LOGGER_DEBUG);
1195 if (is_file($directory)) {
1196 logger('Path "' . $directory . '" is a file for user ' . self::systemuser(), LOGGER_DEBUG);
1200 if (!is_dir($directory)) {
1201 logger('Path "' . $directory . '" is not a directory for user ' . self::systemuser(), LOGGER_DEBUG);
1205 if ($check_writable && !is_writable($directory)) {
1206 logger('Path "' . $directory . '" is not writable for user ' . self::systemuser(), LOGGER_DEBUG);
1214 * @param string $cat Config category
1215 * @param string $k Config key
1216 * @param mixed $default Default value if it isn't set
1218 public function getConfigValue($cat, $k, $default = null)
1222 if ($cat === 'config') {
1223 if (isset($this->config[$k])) {
1224 $return = $this->config[$k];
1227 if (isset($this->config[$cat][$k])) {
1228 $return = $this->config[$cat][$k];
1236 * Sets a value in the config cache. Accepts raw output from the config table
1238 * @param string $cat Config category
1239 * @param string $k Config key
1240 * @param mixed $v Value to set
1242 public function setConfigValue($cat, $k, $v)
1244 // Only arrays are serialized in database, so we have to unserialize sparingly
1245 $value = is_string($v) && preg_match("|^a:[0-9]+:{.*}$|s", $v) ? unserialize($v) : $v;
1247 if ($cat === 'config') {
1248 $this->config[$k] = $value;
1250 if (!isset($this->config[$cat])) {
1251 $this->config[$cat] = [];
1254 $this->config[$cat][$k] = $value;
1259 * Deletes a value from the config cache
1261 * @param string $cat Config category
1262 * @param string $k Config key
1264 public function deleteConfigValue($cat, $k)
1266 if ($cat === 'config') {
1267 if (isset($this->config[$k])) {
1268 unset($this->config[$k]);
1271 if (isset($this->config[$cat][$k])) {
1272 unset($this->config[$cat][$k]);
1279 * Retrieves a value from the user config cache
1281 * @param int $uid User Id
1282 * @param string $cat Config category
1283 * @param string $k Config key
1284 * @param mixed $default Default value if key isn't set
1286 public function getPConfigValue($uid, $cat, $k, $default = null)
1290 if (isset($this->config[$uid][$cat][$k])) {
1291 $return = $this->config[$uid][$cat][$k];
1298 * Sets a value in the user config cache
1300 * Accepts raw output from the pconfig table
1302 * @param int $uid User Id
1303 * @param string $cat Config category
1304 * @param string $k Config key
1305 * @param mixed $v Value to set
1307 public function setPConfigValue($uid, $cat, $k, $v)
1309 // Only arrays are serialized in database, so we have to unserialize sparingly
1310 $value = is_string($v) && preg_match("|^a:[0-9]+:{.*}$|s", $v) ? unserialize($v) : $v;
1312 if (!isset($this->config[$uid]) || !is_array($this->config[$uid])) {
1313 $this->config[$uid] = [];
1316 if (!isset($this->config[$uid][$cat]) || !is_array($this->config[$uid][$cat])) {
1317 $this->config[$uid][$cat] = [];
1320 $this->config[$uid][$cat][$k] = $value;
1324 * Deletes a value from the user config cache
1326 * @param int $uid User Id
1327 * @param string $cat Config category
1328 * @param string $k Config key
1330 public function deletePConfigValue($uid, $cat, $k)
1332 if (isset($this->config[$uid][$cat][$k])) {
1333 unset($this->config[$uid][$cat][$k]);
1338 * Generates the site's default sender email address
1342 public function getSenderEmailAddress()
1344 $sender_email = Config::get('config', 'sender_email');
1345 if (empty($sender_email)) {
1346 $hostname = $this->get_hostname();
1347 if (strpos($hostname, ':')) {
1348 $hostname = substr($hostname, 0, strpos($hostname, ':'));
1351 $sender_email = 'noreply@' . $hostname;
1354 return $sender_email;
1358 * Returns the current theme name.
1362 public function getCurrentTheme()
1364 if ($this->isInstallMode()) {
1368 //// @TODO Compute the current theme only once (this behavior has
1369 /// already been implemented, but it didn't work well -
1370 /// https://github.com/friendica/friendica/issues/5092)
1371 $this->computeCurrentTheme();
1373 return $this->current_theme;
1377 * Computes the current theme name based on the node settings, the user settings and the device type
1381 private function computeCurrentTheme()
1383 $system_theme = Config::get('system', 'theme');
1384 if (!$system_theme) {
1385 throw new Exception(L10n::t('No system theme config value set.'));
1389 $this->current_theme = $system_theme;
1391 $allowed_themes = explode(',', Config::get('system', 'allowed_themes', $system_theme));
1394 // Find the theme that belongs to the user whose stuff we are looking at
1395 if ($this->profile_uid && ($this->profile_uid != local_user())) {
1396 // Allow folks to override user themes and always use their own on their own site.
1397 // This works only if the user is on the same server
1398 $user = DBA::selectFirst('user', ['theme'], ['uid' => $this->profile_uid]);
1399 if (DBA::isResult($user) && !PConfig::get(local_user(), 'system', 'always_my_theme')) {
1400 $page_theme = $user['theme'];
1404 $user_theme = Core\Session::get('theme', $system_theme);
1406 // Specific mobile theme override
1407 if (($this->is_mobile || $this->is_tablet) && Core\Session::get('show-mobile', true)) {
1408 $system_mobile_theme = Config::get('system', 'mobile-theme');
1409 $user_mobile_theme = Core\Session::get('mobile-theme', $system_mobile_theme);
1411 // --- means same mobile theme as desktop
1412 if (!empty($user_mobile_theme) && $user_mobile_theme !== '---') {
1413 $user_theme = $user_mobile_theme;
1418 $theme_name = $page_theme;
1420 $theme_name = $user_theme;
1424 && in_array($theme_name, $allowed_themes)
1425 && (file_exists('view/theme/' . $theme_name . '/style.css')
1426 || file_exists('view/theme/' . $theme_name . '/style.php'))
1428 $this->current_theme = $theme_name;
1433 * @brief Return full URL to theme which is currently in effect.
1435 * Provide a sane default if nothing is chosen or the specified theme does not exist.
1439 public function getCurrentThemeStylesheetPath()
1441 return Core\Theme::getStylesheetPath($this->getCurrentTheme());