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;
14 use Friendica\Database\DBM;
16 require_once 'boot.php';
17 require_once 'include/dba.php';
18 require_once 'include/text.php';
24 * @brief Our main application structure for the life of this page.
26 * Primarily deals with the URL that got us here
27 * and tries to make some sense of it, and
28 * stores our page contents and config storage
29 * and anything else that might need to be passed around
30 * before we spit the page out.
35 const MODE_LOCALCONFIGPRESENT = 1;
36 const MODE_DBAVAILABLE = 2;
37 const MODE_DBCONFIGAVAILABLE = 4;
38 const MODE_MAINTENANCEDISABLED = 8;
41 * @deprecated since version 2008.08 Use App->isInstallMode() instead to check for install mode.
43 const MODE_INSTALL = 0;
46 * @deprecated since version 2008.08 Use the precise mode constant to check for a specific capability instead.
48 const MODE_NORMAL = App::MODE_LOCALCONFIGPRESENT | App::MODE_DBAVAILABLE | App::MODE_DBCONFIGAVAILABLE | App::MODE_MAINTENANCEDISABLED;
50 public $module_loaded = false;
51 public $module_class = null;
52 public $query_string = '';
66 public $error = false;
71 public $mode = App::MODE_INSTALL;
77 public $interactive = true;
79 public $addons_admin = [];
82 public $is_mobile = false;
83 public $is_tablet = false;
84 public $is_friendica_app;
85 public $performance = [];
86 public $callstack = [];
87 public $theme_info = [];
88 public $backend = true;
91 // Allow themes to control internal parameters
92 // by changing App values in theme.php
94 public $sourcename = '';
95 public $videowidth = 425;
96 public $videoheight = 350;
97 public $force_max_items = 0;
98 public $theme_events_in_profile = true;
101 * @brief An array for all theme-controllable parameters
103 * Mostly unimplemented yet. Only options 'template_engine' and
109 'videoheight' => 350,
110 'force_max_items' => 0,
112 'template_engine' => 'smarty3',
116 * @brief An array of registered template engines ('name'=>'class name')
118 public $template_engines = [];
121 * @brief An array of instanced template engines ('name'=>'instance')
123 public $template_engine_instance = [];
137 private $curl_content_type;
138 private $curl_headers;
141 * @brief App constructor.
143 * @param string $basepath Path to the app base folder
145 public function __construct($basepath)
147 if (!static::directory_usable($basepath, false)) {
148 throw new Exception('Basepath ' . $basepath . ' isn\'t usable.');
151 BaseObject::setApp($this);
153 $this->basepath = rtrim($basepath, DIRECTORY_SEPARATOR);
155 $this->performance['start'] = microtime(true);
156 $this->performance['database'] = 0;
157 $this->performance['database_write'] = 0;
158 $this->performance['cache'] = 0;
159 $this->performance['cache_write'] = 0;
160 $this->performance['network'] = 0;
161 $this->performance['file'] = 0;
162 $this->performance['rendering'] = 0;
163 $this->performance['parser'] = 0;
164 $this->performance['marktime'] = 0;
165 $this->performance['markstart'] = microtime(true);
167 $this->callstack['database'] = [];
168 $this->callstack['database_write'] = [];
169 $this->callstack['cache'] = [];
170 $this->callstack['cache_write'] = [];
171 $this->callstack['network'] = [];
172 $this->callstack['file'] = [];
173 $this->callstack['rendering'] = [];
174 $this->callstack['parser'] = [];
176 // The order of the following calls is important to ensure proper initialization
177 $this->loadConfigFiles();
179 $this->loadDatabase();
181 $this->determineMode();
183 $this->determineUrlPath();
187 if ($this->mode & self::MODE_DBAVAILABLE) {
188 Core\Addon::loadHooks();
190 $this->loadAddonConfig();
193 $this->loadDefaultTimezone();
209 $this->process_id = System::processID('log');
213 // This has to be quite large to deal with embedded private photos
214 ini_set('pcre.backtrack_limit', 500000);
216 $this->scheme = 'http';
218 if ((x($_SERVER, 'HTTPS') && $_SERVER['HTTPS']) ||
219 (x($_SERVER, 'HTTP_FORWARDED') && preg_match('/proto=https/', $_SERVER['HTTP_FORWARDED'])) ||
220 (x($_SERVER, 'HTTP_X_FORWARDED_PROTO') && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') ||
221 (x($_SERVER, 'HTTP_X_FORWARDED_SSL') && $_SERVER['HTTP_X_FORWARDED_SSL'] == 'on') ||
222 (x($_SERVER, 'FRONT_END_HTTPS') && $_SERVER['FRONT_END_HTTPS'] == 'on') ||
223 (x($_SERVER, 'SERVER_PORT') && (intval($_SERVER['SERVER_PORT']) == 443)) // XXX: reasonable assumption, but isn't this hardcoding too much?
225 $this->scheme = 'https';
228 if (x($_SERVER, 'SERVER_NAME')) {
229 $this->hostname = $_SERVER['SERVER_NAME'];
231 if (x($_SERVER, 'SERVER_PORT') && $_SERVER['SERVER_PORT'] != 80 && $_SERVER['SERVER_PORT'] != 443) {
232 $this->hostname .= ':' . $_SERVER['SERVER_PORT'];
237 get_include_path() . PATH_SEPARATOR
238 . $this->basepath . DIRECTORY_SEPARATOR . 'include' . PATH_SEPARATOR
239 . $this->basepath . DIRECTORY_SEPARATOR . 'library' . PATH_SEPARATOR
242 if ((x($_SERVER, 'QUERY_STRING')) && substr($_SERVER['QUERY_STRING'], 0, 9) === 'pagename=') {
243 $this->query_string = substr($_SERVER['QUERY_STRING'], 9);
244 } elseif ((x($_SERVER, 'QUERY_STRING')) && substr($_SERVER['QUERY_STRING'], 0, 2) === 'q=') {
245 $this->query_string = substr($_SERVER['QUERY_STRING'], 2);
248 // removing trailing / - maybe a nginx problem
249 $this->query_string = ltrim($this->query_string, '/');
251 if (!empty($_GET['pagename'])) {
252 $this->cmd = trim($_GET['pagename'], '/\\');
253 } elseif (!empty($_GET['q'])) {
254 $this->cmd = trim($_GET['q'], '/\\');
258 $this->query_string = str_replace($this->cmd . '&', $this->cmd . '?', $this->query_string);
260 // unix style "homedir"
261 if (substr($this->cmd, 0, 1) === '~') {
262 $this->cmd = 'profile/' . substr($this->cmd, 1);
265 // Diaspora style profile url
266 if (substr($this->cmd, 0, 2) === 'u/') {
267 $this->cmd = 'profile/' . substr($this->cmd, 2);
271 * Break the URL path into C style argc/argv style arguments for our
272 * modules. Given "http://example.com/module/arg1/arg2", $this->argc
273 * will be 3 (integer) and $this->argv will contain:
279 * There will always be one argument. If provided a naked domain
280 * URL, $this->argv[0] is set to "home".
283 $this->argv = explode('/', $this->cmd);
284 $this->argc = count($this->argv);
285 if ((array_key_exists('0', $this->argv)) && strlen($this->argv[0])) {
286 $this->module = str_replace('.', '_', $this->argv[0]);
287 $this->module = str_replace('-', '_', $this->module);
290 $this->argv = ['home'];
291 $this->module = 'home';
294 // See if there is any page number information, and initialise pagination
295 $this->pager['page'] = ((x($_GET, 'page') && intval($_GET['page']) > 0) ? intval($_GET['page']) : 1);
296 $this->pager['itemspage'] = 50;
297 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
299 if ($this->pager['start'] < 0) {
300 $this->pager['start'] = 0;
302 $this->pager['total'] = 0;
304 // Detect mobile devices
305 $mobile_detect = new MobileDetect();
306 $this->is_mobile = $mobile_detect->isMobile();
307 $this->is_tablet = $mobile_detect->isTablet();
310 $this->is_friendica_app = isset($_SERVER['HTTP_USER_AGENT']) && $_SERVER['HTTP_USER_AGENT'] == 'Apache-HttpClient/UNAVAILABLE (java 1.4)';
312 // Register template engines
313 $this->register_template_engine('Friendica\Render\FriendicaSmartyEngine');
317 * Load the configuration files
319 * First loads the default value for all the configuration keys, then the legacy configuration files, then the
320 * expected local.ini.php
322 private function loadConfigFiles()
324 $this->loadConfigFile($this->basepath . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'config.ini.php');
325 $this->loadConfigFile($this->basepath . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'settings.ini.php');
327 // Legacy .htconfig.php support
328 if (file_exists($this->basepath . DIRECTORY_SEPARATOR . '.htpreconfig.php')) {
330 include $this->basepath . DIRECTORY_SEPARATOR . '.htpreconfig.php';
333 // Legacy .htconfig.php support
334 if (file_exists($this->basepath . DIRECTORY_SEPARATOR . '.htconfig.php')) {
337 include $this->basepath . DIRECTORY_SEPARATOR . '.htconfig.php';
339 $this->setConfigValue('database', 'hostname', $db_host);
340 $this->setConfigValue('database', 'username', $db_user);
341 $this->setConfigValue('database', 'password', $db_pass);
342 $this->setConfigValue('database', 'database', $db_data);
343 if (isset($a->config['system']['db_charset'])) {
344 $this->setConfigValue('database', 'charset', $a->config['system']['db_charset']);
347 unset($db_host, $db_user, $db_pass, $db_data);
349 if (isset($default_timezone)) {
350 $this->setConfigValue('system', 'default_timezone', $default_timezone);
351 unset($default_timezone);
354 if (isset($pidfile)) {
355 $this->setConfigValue('system', 'pidfile', $pidfile);
360 $this->setConfigValue('system', 'language', $lang);
365 if (file_exists($this->basepath . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'local.ini.php')) {
366 $this->loadConfigFile($this->basepath . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'local.ini.php');
371 * Tries to load the specified configuration file into the App->config array.
372 * Overwrites previously set values.
374 * The config format is INI and the template for configuration files is the following:
376 * <?php return <<<INI
384 * @param type $filepath
387 public function loadConfigFile($filepath)
389 if (!file_exists($filepath)) {
390 throw new Exception('Error parsing non-existent config file ' . $filepath);
393 $contents = include($filepath);
395 $config = parse_ini_string($contents, true, INI_SCANNER_TYPED);
397 if ($config === false) {
398 throw new Exception('Error parsing config file ' . $filepath);
401 foreach ($config as $category => $values) {
402 foreach ($values as $key => $value) {
403 $this->setConfigValue($category, $key, $value);
409 * Loads addons configuration files
411 * First loads all activated addons default configuration throught the load_config hook, then load the local.ini.php
412 * again to overwrite potential local addon configuration.
414 private function loadAddonConfig()
416 // Loads addons default config
417 Core\Addon::callHooks('load_config');
419 // Load the local addon config file to overwritten default addon config values
420 if (file_exists($this->basepath . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'addon.ini.php')) {
421 $this->loadConfigFile($this->basepath . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'addon.ini.php');
426 * Loads the default timezone
428 * Include support for legacy $default_timezone
430 * @global string $default_timezone
432 private function loadDefaultTimezone()
434 if ($this->getConfigValue('system', 'default_timezone')) {
435 $this->timezone = $this->getConfigValue('system', 'default_timezone');
437 global $default_timezone;
438 $this->timezone = !empty($default_timezone) ? $default_timezone : 'UTC';
441 if ($this->timezone) {
442 date_default_timezone_set($this->timezone);
447 * Figure out if we are running at the top of a domain or in a sub-directory and adjust accordingly
449 private function determineUrlPath()
451 $this->urlpath = $this->getConfigValue('system', 'urlpath');
453 /* SCRIPT_URL gives /path/to/friendica/module/parameter
454 * QUERY_STRING gives pagename=module/parameter
456 * To get /path/to/friendica we perform dirname() for as many levels as there are slashes in the QUERY_STRING
458 if (!empty($_SERVER['SCRIPT_URL'])) {
460 if (!empty($_SERVER['QUERY_STRING'])) {
461 $path = trim(dirname($_SERVER['SCRIPT_URL'], substr_count(trim($_SERVER['QUERY_STRING'], '/'), '/') + 1), '/');
464 $path = trim($_SERVER['SCRIPT_URL'], '/');
467 if ($path && $path != $this->urlpath) {
468 $this->urlpath = $path;
476 * - App::MODE_INSTALL : Either the database connection can't be established or the config table doesn't exist
477 * - App::MODE_MAINTENANCE: The maintenance mode has been set
478 * - App::MODE_NORMAL : Normal run with all features enabled
482 private function determineMode()
486 if (!file_exists($this->basepath . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'local.ini.php')
487 && !file_exists($this->basepath . DIRECTORY_SEPARATOR . '.htconfig.php')) {
491 $this->mode |= App::MODE_LOCALCONFIGPRESENT;
493 if (!DBA::connected()) {
497 $this->mode |= App::MODE_DBAVAILABLE;
499 if (DBA::fetch_first("SHOW TABLES LIKE 'config'") === false) {
503 $this->mode |= App::MODE_DBCONFIGAVAILABLE;
505 if (Config::get('system', 'maintenance')) {
509 $this->mode |= App::MODE_MAINTENANCEDISABLED;
512 public function loadDatabase()
514 if (DBA::connected()) {
518 $db_host = $this->getConfigValue('database', 'hostname');
519 $db_user = $this->getConfigValue('database', 'username');
520 $db_pass = $this->getConfigValue('database', 'password');
521 $db_data = $this->getConfigValue('database', 'database');
522 $charset = $this->getConfigValue('database', 'charset');
524 // Use environment variables for mysql if they are set beforehand
525 if (!empty(getenv('MYSQL_HOST'))
526 && (!empty(getenv('MYSQL_USERNAME')) || !empty(getenv('MYSQL_USER')))
527 && getenv('MYSQL_PASSWORD') !== false
528 && !empty(getenv('MYSQL_DATABASE')))
530 $db_host = getenv('MYSQL_HOST');
531 if (!empty(getenv('MYSQL_PORT'))) {
532 $db_host .= ':' . getenv('MYSQL_PORT');
534 if (!empty(getenv('MYSQL_USERNAME'))) {
535 $db_user = getenv('MYSQL_USERNAME');
537 $db_user = getenv('MYSQL_USER');
539 $db_pass = (string) getenv('MYSQL_PASSWORD');
540 $db_data = getenv('MYSQL_DATABASE');
543 $stamp1 = microtime(true);
545 DBA::connect($db_host, $db_user, $db_pass, $db_data, $charset);
546 unset($db_host, $db_user, $db_pass, $db_data, $charset);
548 $this->save_timestamp($stamp1, 'network');
552 * Install mode is when the local config file is missing or the DB schema hasn't been installed yet.
556 public function isInstallMode()
558 return !($this->mode & App::MODE_LOCALCONFIGPRESENT) || !($this->mode & App::MODE_DBCONFIGAVAILABLE);
562 * @brief Returns the base filesystem path of the App
564 * It first checks for the internal variable, then for DOCUMENT_ROOT and
569 public function get_basepath()
571 $basepath = $this->basepath;
574 $basepath = Config::get('system', 'basepath');
577 if (!$basepath && x($_SERVER, 'DOCUMENT_ROOT')) {
578 $basepath = $_SERVER['DOCUMENT_ROOT'];
581 if (!$basepath && x($_SERVER, 'PWD')) {
582 $basepath = $_SERVER['PWD'];
585 return self::realpath($basepath);
589 * @brief Returns a normalized file path
591 * This is a wrapper for the "realpath" function.
592 * That function cannot detect the real path when some folders aren't readable.
593 * Since this could happen with some hosters we need to handle this.
595 * @param string $path The path that is about to be normalized
596 * @return string normalized path - when possible
598 public static function realpath($path)
600 $normalized = realpath($path);
602 if (!is_bool($normalized)) {
609 public function get_scheme()
611 return $this->scheme;
615 * @brief Retrieves the Friendica instance base URL
617 * This function assembles the base URL from multiple parts:
618 * - Protocol is determined either by the request or a combination of
619 * system.ssl_policy and the $ssl parameter.
620 * - Host name is determined either by system.hostname or inferred from request
621 * - Path is inferred from SCRIPT_NAME
623 * Note: $ssl parameter value doesn't directly correlate with the resulting protocol
625 * @param bool $ssl Whether to append http or https under SSL_POLICY_SELFSIGN
626 * @return string Friendica server base URL
628 public function get_baseurl($ssl = false)
630 $scheme = $this->scheme;
632 if (Config::get('system', 'ssl_policy') == SSL_POLICY_FULL) {
636 // Basically, we have $ssl = true on any links which can only be seen by a logged in user
637 // (and also the login link). Anything seen by an outsider will have it turned off.
639 if (Config::get('system', 'ssl_policy') == SSL_POLICY_SELFSIGN) {
647 if (Config::get('config', 'hostname') != '') {
648 $this->hostname = Config::get('config', 'hostname');
651 return $scheme . '://' . $this->hostname . (!empty($this->urlpath) ? '/' . $this->urlpath : '' );
655 * @brief Initializes the baseurl components
657 * Clears the baseurl cache to prevent inconsistencies
661 public function set_baseurl($url)
663 $parsed = @parse_url($url);
667 if (!empty($parsed['scheme'])) {
668 $this->scheme = $parsed['scheme'];
671 if (!empty($parsed['host'])) {
672 $hostname = $parsed['host'];
675 if (x($parsed, 'port')) {
676 $hostname .= ':' . $parsed['port'];
678 if (x($parsed, 'path')) {
679 $this->urlpath = trim($parsed['path'], '\\/');
682 if (file_exists($this->basepath . DIRECTORY_SEPARATOR . '.htpreconfig.php')) {
683 include $this->basepath . DIRECTORY_SEPARATOR . '.htpreconfig.php';
686 if (Config::get('config', 'hostname') != '') {
687 $this->hostname = Config::get('config', 'hostname');
690 if (!isset($this->hostname) || ($this->hostname == '')) {
691 $this->hostname = $hostname;
696 public function get_hostname()
698 if (Config::get('config', 'hostname') != '') {
699 $this->hostname = Config::get('config', 'hostname');
702 return $this->hostname;
705 public function get_path()
707 return $this->urlpath;
710 public function set_pager_total($n)
712 $this->pager['total'] = intval($n);
715 public function set_pager_itemspage($n)
717 $this->pager['itemspage'] = ((intval($n) > 0) ? intval($n) : 0);
718 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
721 public function set_pager_page($n)
723 $this->pager['page'] = $n;
724 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
727 public function init_pagehead()
729 $interval = ((local_user()) ? PConfig::get(local_user(), 'system', 'update_interval') : 40000);
731 // If the update is 'deactivated' set it to the highest integer number (~24 days)
733 $interval = 2147483647;
736 if ($interval < 10000) {
740 // compose the page title from the sitename and the
741 // current module called
742 if (!$this->module == '') {
743 $this->page['title'] = $this->config['sitename'] . ' (' . $this->module . ')';
745 $this->page['title'] = $this->config['sitename'];
748 /* put the head template at the beginning of page['htmlhead']
749 * since the code added by the modules frequently depends on it
752 if (!isset($this->page['htmlhead'])) {
753 $this->page['htmlhead'] = '';
756 // If we're using Smarty, then doing replace_macros() will replace
757 // any unrecognized variables with a blank string. Since we delay
758 // replacing $stylesheet until later, we need to replace it now
759 // with another variable name
760 if ($this->theme['template_engine'] === 'smarty3') {
761 $stylesheet = $this->get_template_ldelim('smarty3') . '$stylesheet' . $this->get_template_rdelim('smarty3');
763 $stylesheet = '$stylesheet';
766 $shortcut_icon = Config::get('system', 'shortcut_icon');
767 if ($shortcut_icon == '') {
768 $shortcut_icon = 'images/friendica-32.png';
771 $touch_icon = Config::get('system', 'touch_icon');
772 if ($touch_icon == '') {
773 $touch_icon = 'images/friendica-128.png';
776 // get data wich is needed for infinite scroll on the network page
777 $invinite_scroll = infinite_scroll_data($this->module);
779 $tpl = get_markup_template('head.tpl');
780 $this->page['htmlhead'] = replace_macros($tpl, [
781 '$baseurl' => $this->get_baseurl(),
782 '$local_user' => local_user(),
783 '$generator' => 'Friendica' . ' ' . FRIENDICA_VERSION,
784 '$delitem' => L10n::t('Delete this item?'),
785 '$showmore' => L10n::t('show more'),
786 '$showfewer' => L10n::t('show fewer'),
787 '$update_interval' => $interval,
788 '$shortcut_icon' => $shortcut_icon,
789 '$touch_icon' => $touch_icon,
790 '$stylesheet' => $stylesheet,
791 '$infinite_scroll' => $invinite_scroll,
792 '$block_public' => intval(Config::get('system', 'block_public')),
793 ]) . $this->page['htmlhead'];
796 public function init_page_end()
798 if (!isset($this->page['end'])) {
799 $this->page['end'] = '';
801 $tpl = get_markup_template('end.tpl');
802 $this->page['end'] = replace_macros($tpl, [
803 '$baseurl' => $this->get_baseurl()
804 ]) . $this->page['end'];
807 public function set_curl_code($code)
809 $this->curl_code = $code;
812 public function get_curl_code()
814 return $this->curl_code;
817 public function set_curl_content_type($content_type)
819 $this->curl_content_type = $content_type;
822 public function get_curl_content_type()
824 return $this->curl_content_type;
827 public function set_curl_headers($headers)
829 $this->curl_headers = $headers;
832 public function get_curl_headers()
834 return $this->curl_headers;
838 * @brief Removes the base url from an url. This avoids some mixed content problems.
840 * @param string $orig_url
842 * @return string The cleaned url
844 public function remove_baseurl($orig_url)
846 // Remove the hostname from the url if it is an internal link
847 $nurl = normalise_link($orig_url);
848 $base = normalise_link($this->get_baseurl());
849 $url = str_replace($base . '/', '', $nurl);
851 // if it is an external link return the orignal value
852 if ($url == normalise_link($orig_url)) {
860 * @brief Register template engine class
862 * @param string $class
864 private function register_template_engine($class)
866 $v = get_class_vars($class);
869 $this->template_engines[$name] = $class;
871 echo "template engine <tt>$class</tt> cannot be registered without a name.\n";
877 * @brief Return template engine instance.
879 * If $name is not defined, return engine defined by theme,
882 * @return object Template Engine instance
884 public function template_engine()
886 $template_engine = 'smarty3';
887 if (x($this->theme, 'template_engine')) {
888 $template_engine = $this->theme['template_engine'];
891 if (isset($this->template_engines[$template_engine])) {
892 if (isset($this->template_engine_instance[$template_engine])) {
893 return $this->template_engine_instance[$template_engine];
895 $class = $this->template_engines[$template_engine];
897 $this->template_engine_instance[$template_engine] = $obj;
902 echo "template engine <tt>$template_engine</tt> is not registered!\n";
907 * @brief Returns the active template engine.
911 public function get_template_engine()
913 return $this->theme['template_engine'];
916 public function set_template_engine($engine = 'smarty3')
918 $this->theme['template_engine'] = $engine;
921 public function get_template_ldelim($engine = 'smarty3')
923 return $this->ldelim[$engine];
926 public function get_template_rdelim($engine = 'smarty3')
928 return $this->rdelim[$engine];
931 public function save_timestamp($stamp, $value)
933 if (!isset($this->config['system']['profiler']) || !$this->config['system']['profiler']) {
937 $duration = (float) (microtime(true) - $stamp);
939 if (!isset($this->performance[$value])) {
940 // Prevent ugly E_NOTICE
941 $this->performance[$value] = 0;
944 $this->performance[$value] += (float) $duration;
945 $this->performance['marktime'] += (float) $duration;
947 $callstack = System::callstack();
949 if (!isset($this->callstack[$value][$callstack])) {
950 // Prevent ugly E_NOTICE
951 $this->callstack[$value][$callstack] = 0;
954 $this->callstack[$value][$callstack] += (float) $duration;
957 public function get_useragent()
960 FRIENDICA_PLATFORM . " '" .
961 FRIENDICA_CODENAME . "' " .
962 FRIENDICA_VERSION . '-' .
963 DB_UPDATE_VERSION . '; ' .
964 $this->get_baseurl();
967 public function is_friendica_app()
969 return $this->is_friendica_app;
973 * @brief Checks if the site is called via a backend process
975 * This isn't a perfect solution. But we need this check very early.
976 * So we cannot wait until the modules are loaded.
978 * @return bool Is it a known backend?
980 public function is_backend()
1004 // Check if current module is in backend or backend flag is set
1005 return (in_array($this->module, $backends) || $this->backend);
1009 * @brief Checks if the maximum number of database processes is reached
1011 * @return bool Is the limit reached?
1013 public function isMaxProcessesReached()
1015 // Deactivated, needs more investigating if this check really makes sense
1019 * Commented out to suppress static analyzer issues
1021 if ($this->is_backend()) {
1022 $process = 'backend';
1023 $max_processes = Config::get('system', 'max_processes_backend');
1024 if (intval($max_processes) == 0) {
1028 $process = 'frontend';
1029 $max_processes = Config::get('system', 'max_processes_frontend');
1030 if (intval($max_processes) == 0) {
1031 $max_processes = 20;
1035 $processlist = DBM::processlist();
1036 if ($processlist['list'] != '') {
1037 logger('Processcheck: Processes: ' . $processlist['amount'] . ' - Processlist: ' . $processlist['list'], LOGGER_DEBUG);
1039 if ($processlist['amount'] > $max_processes) {
1040 logger('Processcheck: Maximum number of processes for ' . $process . ' tasks (' . $max_processes . ') reached.', LOGGER_DEBUG);
1049 * @brief Checks if the minimal memory is reached
1051 * @return bool Is the memory limit reached?
1053 public function min_memory_reached()
1055 $min_memory = Config::get('system', 'min_memory', 0);
1056 if ($min_memory == 0) {
1060 if (!is_readable('/proc/meminfo')) {
1064 $memdata = explode("\n", file_get_contents('/proc/meminfo'));
1067 foreach ($memdata as $line) {
1068 list($key, $val) = explode(':', $line);
1069 $meminfo[$key] = (int) trim(str_replace('kB', '', $val));
1070 $meminfo[$key] = (int) ($meminfo[$key] / 1024);
1073 if (!isset($meminfo['MemAvailable']) || !isset($meminfo['MemFree'])) {
1077 $free = $meminfo['MemAvailable'] + $meminfo['MemFree'];
1079 $reached = ($free < $min_memory);
1082 logger('Minimal memory reached: ' . $free . '/' . $meminfo['MemTotal'] . ' - limit ' . $min_memory, LOGGER_DEBUG);
1089 * @brief Checks if the maximum load is reached
1091 * @return bool Is the load reached?
1093 public function isMaxLoadReached()
1095 if ($this->is_backend()) {
1096 $process = 'backend';
1097 $maxsysload = intval(Config::get('system', 'maxloadavg'));
1098 if ($maxsysload < 1) {
1102 $process = 'frontend';
1103 $maxsysload = intval(Config::get('system', 'maxloadavg_frontend'));
1104 if ($maxsysload < 1) {
1109 $load = current_load();
1111 if (intval($load) > $maxsysload) {
1112 logger('system: load ' . $load . ' for ' . $process . ' tasks (' . $maxsysload . ') too high.');
1120 * Executes a child process with 'proc_open'
1122 * @param string $command The command to execute
1123 * @param array $args Arguments to pass to the command ( [ 'key' => value, 'key2' => value2, ... ]
1125 public function proc_run($command, $args)
1127 if (!function_exists('proc_open')) {
1131 $cmdline = $this->getConfigValue('config', 'php_path', 'php') . $command;
1133 foreach ($args as $key => $value) {
1134 if (!is_null($value) && is_bool($value) && !$value) {
1138 $cmdline .= ' --' . $key;
1139 if (!is_null($value) && !is_bool($value)) {
1140 $cmdline .= ' ' . $value;
1144 $cmdline = escapeshellarg($cmdline);
1146 if ($this->min_memory_reached()) {
1150 if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
1151 $resource = proc_open('cmd /c start /b ' . $cmdline, [], $foo, $this->get_basepath());
1153 $resource = proc_open($cmdline . ' &', [], $foo, $this->get_basepath());
1155 if (!is_resource($resource)) {
1156 logger('We got no resource for command ' . $cmdline, LOGGER_DEBUG);
1159 proc_close($resource);
1163 * @brief Returns the system user that is executing the script
1165 * This mostly returns something like "www-data".
1167 * @return string system username
1169 private static function systemuser()
1171 if (!function_exists('posix_getpwuid') || !function_exists('posix_geteuid')) {
1175 $processUser = posix_getpwuid(posix_geteuid());
1176 return $processUser['name'];
1180 * @brief Checks if a given directory is usable for the system
1182 * @return boolean the directory is usable
1184 public static function directory_usable($directory, $check_writable = true)
1186 if ($directory == '') {
1187 logger('Directory is empty. This shouldn\'t happen.', LOGGER_DEBUG);
1191 if (!file_exists($directory)) {
1192 logger('Path "' . $directory . '" does not exist for user ' . self::systemuser(), LOGGER_DEBUG);
1196 if (is_file($directory)) {
1197 logger('Path "' . $directory . '" is a file for user ' . self::systemuser(), LOGGER_DEBUG);
1201 if (!is_dir($directory)) {
1202 logger('Path "' . $directory . '" is not a directory for user ' . self::systemuser(), LOGGER_DEBUG);
1206 if ($check_writable && !is_writable($directory)) {
1207 logger('Path "' . $directory . '" is not writable for user ' . self::systemuser(), LOGGER_DEBUG);
1215 * @param string $cat Config category
1216 * @param string $k Config key
1217 * @param mixed $default Default value if it isn't set
1219 public function getConfigValue($cat, $k, $default = null)
1223 if ($cat === 'config') {
1224 if (isset($this->config[$k])) {
1225 $return = $this->config[$k];
1228 if (isset($this->config[$cat][$k])) {
1229 $return = $this->config[$cat][$k];
1237 * Sets a value in the config cache. Accepts raw output from the config table
1239 * @param string $cat Config category
1240 * @param string $k Config key
1241 * @param mixed $v Value to set
1243 public function setConfigValue($cat, $k, $v)
1245 // Only arrays are serialized in database, so we have to unserialize sparingly
1246 $value = is_string($v) && preg_match("|^a:[0-9]+:{.*}$|s", $v) ? unserialize($v) : $v;
1248 if ($cat === 'config') {
1249 $this->config[$k] = $value;
1251 if (!isset($this->config[$cat])) {
1252 $this->config[$cat] = [];
1255 $this->config[$cat][$k] = $value;
1260 * Deletes a value from the config cache
1262 * @param string $cat Config category
1263 * @param string $k Config key
1265 public function deleteConfigValue($cat, $k)
1267 if ($cat === 'config') {
1268 if (isset($this->config[$k])) {
1269 unset($this->config[$k]);
1272 if (isset($this->config[$cat][$k])) {
1273 unset($this->config[$cat][$k]);
1280 * Retrieves a value from the user config cache
1282 * @param int $uid User Id
1283 * @param string $cat Config category
1284 * @param string $k Config key
1285 * @param mixed $default Default value if key isn't set
1287 public function getPConfigValue($uid, $cat, $k, $default = null)
1291 if (isset($this->config[$uid][$cat][$k])) {
1292 $return = $this->config[$uid][$cat][$k];
1299 * Sets a value in the user config cache
1301 * Accepts raw output from the pconfig table
1303 * @param int $uid User Id
1304 * @param string $cat Config category
1305 * @param string $k Config key
1306 * @param mixed $v Value to set
1308 public function setPConfigValue($uid, $cat, $k, $v)
1310 // Only arrays are serialized in database, so we have to unserialize sparingly
1311 $value = is_string($v) && preg_match("|^a:[0-9]+:{.*}$|s", $v) ? unserialize($v) : $v;
1313 if (!isset($this->config[$uid])) {
1314 $this->config[$uid] = [];
1317 if (!isset($this->config[$uid][$cat])) {
1318 $this->config[$uid][$cat] = [];
1321 $this->config[$uid][$cat][$k] = $value;
1325 * Deletes a value from the user config cache
1327 * @param int $uid User Id
1328 * @param string $cat Config category
1329 * @param string $k Config key
1331 public function deletePConfigValue($uid, $cat, $k)
1333 if (isset($this->config[$uid][$cat][$k])) {
1334 unset($this->config[$uid][$cat][$k]);
1339 * Generates the site's default sender email address
1343 public function getSenderEmailAddress()
1345 $sender_email = Config::get('config', 'sender_email');
1346 if (empty($sender_email)) {
1347 $hostname = $this->get_hostname();
1348 if (strpos($hostname, ':')) {
1349 $hostname = substr($hostname, 0, strpos($hostname, ':'));
1352 $sender_email = 'noreply@' . $hostname;
1355 return $sender_email;
1359 * Returns the current theme name.
1363 public function getCurrentTheme()
1365 if ($this->isInstallMode()) {
1369 //// @TODO Compute the current theme only once (this behavior has
1370 /// already been implemented, but it didn't work well -
1371 /// https://github.com/friendica/friendica/issues/5092)
1372 $this->computeCurrentTheme();
1374 return $this->current_theme;
1378 * Computes the current theme name based on the node settings, the user settings and the device type
1382 private function computeCurrentTheme()
1384 $system_theme = Config::get('system', 'theme');
1385 if (!$system_theme) {
1386 throw new Exception(L10n::t('No system theme config value set.'));
1390 $this->current_theme = $system_theme;
1392 $allowed_themes = explode(',', Config::get('system', 'allowed_themes', $system_theme));
1395 // Find the theme that belongs to the user whose stuff we are looking at
1396 if ($this->profile_uid && ($this->profile_uid != local_user())) {
1397 // Allow folks to override user themes and always use their own on their own site.
1398 // This works only if the user is on the same server
1399 $user = DBA::selectFirst('user', ['theme'], ['uid' => $this->profile_uid]);
1400 if (DBM::is_result($user) && !PConfig::get(local_user(), 'system', 'always_my_theme')) {
1401 $page_theme = $user['theme'];
1405 if (!empty($_SESSION)) {
1406 $user_theme = defaults($_SESSION, 'theme', $system_theme);
1408 $user_theme = $system_theme;
1411 // Specific mobile theme override
1412 if (($this->is_mobile || $this->is_tablet) && defaults($_SESSION, 'show-mobile', true)) {
1413 $system_mobile_theme = Config::get('system', 'mobile-theme');
1414 $user_mobile_theme = defaults($_SESSION, 'mobile-theme', $system_mobile_theme);
1416 // --- means same mobile theme as desktop
1417 if (!empty($user_mobile_theme) && $user_mobile_theme !== '---') {
1418 $user_theme = $user_mobile_theme;
1423 $theme_name = $page_theme;
1425 $theme_name = $user_theme;
1429 && in_array($theme_name, $allowed_themes)
1430 && (file_exists('view/theme/' . $theme_name . '/style.css')
1431 || file_exists('view/theme/' . $theme_name . '/style.php'))
1433 $this->current_theme = $theme_name;
1438 * @brief Return full URL to theme which is currently in effect.
1440 * Provide a sane default if nothing is chosen or the specified theme does not exist.
1444 public function getCurrentThemeStylesheetPath()
1446 return Core\Theme::getStylesheetPath($this->getCurrentTheme());