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 public function __construct($basepath)
146 if (!static::directory_usable($basepath, false)) {
147 throw new Exception('Basepath ' . $basepath . ' isn\'t usable.');
150 BaseObject::setApp($this);
152 $this->basepath = rtrim($basepath, DIRECTORY_SEPARATOR);
154 $this->performance['start'] = microtime(true);
155 $this->performance['database'] = 0;
156 $this->performance['database_write'] = 0;
157 $this->performance['cache'] = 0;
158 $this->performance['cache_write'] = 0;
159 $this->performance['network'] = 0;
160 $this->performance['file'] = 0;
161 $this->performance['rendering'] = 0;
162 $this->performance['parser'] = 0;
163 $this->performance['marktime'] = 0;
164 $this->performance['markstart'] = microtime(true);
166 $this->callstack['database'] = [];
167 $this->callstack['database_write'] = [];
168 $this->callstack['cache'] = [];
169 $this->callstack['cache_write'] = [];
170 $this->callstack['network'] = [];
171 $this->callstack['file'] = [];
172 $this->callstack['rendering'] = [];
173 $this->callstack['parser'] = [];
175 // The order of the following calls is important to ensure proper initialization
176 $this->loadConfigFiles();
178 $this->loadDatabase();
180 $this->determineMode();
182 $this->determineUrlPath();
186 if ($this->mode & self::MODE_DBAVAILABLE) {
187 Core\Addon::loadHooks();
189 $this->loadAddonConfig();
192 $this->loadDefaultTimezone();
208 $this->process_id = System::processID('log');
212 // This has to be quite large to deal with embedded private photos
213 ini_set('pcre.backtrack_limit', 500000);
215 $this->scheme = 'http';
217 if ((x($_SERVER, 'HTTPS') && $_SERVER['HTTPS']) ||
218 (x($_SERVER, 'HTTP_FORWARDED') && preg_match('/proto=https/', $_SERVER['HTTP_FORWARDED'])) ||
219 (x($_SERVER, 'HTTP_X_FORWARDED_PROTO') && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') ||
220 (x($_SERVER, 'HTTP_X_FORWARDED_SSL') && $_SERVER['HTTP_X_FORWARDED_SSL'] == 'on') ||
221 (x($_SERVER, 'FRONT_END_HTTPS') && $_SERVER['FRONT_END_HTTPS'] == 'on') ||
222 (x($_SERVER, 'SERVER_PORT') && (intval($_SERVER['SERVER_PORT']) == 443)) // XXX: reasonable assumption, but isn't this hardcoding too much?
224 $this->scheme = 'https';
227 if (x($_SERVER, 'SERVER_NAME')) {
228 $this->hostname = $_SERVER['SERVER_NAME'];
230 if (x($_SERVER, 'SERVER_PORT') && $_SERVER['SERVER_PORT'] != 80 && $_SERVER['SERVER_PORT'] != 443) {
231 $this->hostname .= ':' . $_SERVER['SERVER_PORT'];
236 get_include_path() . PATH_SEPARATOR
237 . $this->basepath . DIRECTORY_SEPARATOR . 'include' . PATH_SEPARATOR
238 . $this->basepath . DIRECTORY_SEPARATOR . 'library' . PATH_SEPARATOR
241 if ((x($_SERVER, 'QUERY_STRING')) && substr($_SERVER['QUERY_STRING'], 0, 9) === 'pagename=') {
242 $this->query_string = substr($_SERVER['QUERY_STRING'], 9);
243 } elseif ((x($_SERVER, 'QUERY_STRING')) && substr($_SERVER['QUERY_STRING'], 0, 2) === 'q=') {
244 $this->query_string = substr($_SERVER['QUERY_STRING'], 2);
247 // removing trailing / - maybe a nginx problem
248 $this->query_string = ltrim($this->query_string, '/');
250 if (!empty($_GET['pagename'])) {
251 $this->cmd = trim($_GET['pagename'], '/\\');
252 } elseif (!empty($_GET['q'])) {
253 $this->cmd = trim($_GET['q'], '/\\');
257 $this->query_string = str_replace($this->cmd . '&', $this->cmd . '?', $this->query_string);
259 // unix style "homedir"
260 if (substr($this->cmd, 0, 1) === '~') {
261 $this->cmd = 'profile/' . substr($this->cmd, 1);
264 // Diaspora style profile url
265 if (substr($this->cmd, 0, 2) === 'u/') {
266 $this->cmd = 'profile/' . substr($this->cmd, 2);
270 * Break the URL path into C style argc/argv style arguments for our
271 * modules. Given "http://example.com/module/arg1/arg2", $this->argc
272 * will be 3 (integer) and $this->argv will contain:
278 * There will always be one argument. If provided a naked domain
279 * URL, $this->argv[0] is set to "home".
282 $this->argv = explode('/', $this->cmd);
283 $this->argc = count($this->argv);
284 if ((array_key_exists('0', $this->argv)) && strlen($this->argv[0])) {
285 $this->module = str_replace('.', '_', $this->argv[0]);
286 $this->module = str_replace('-', '_', $this->module);
289 $this->argv = ['home'];
290 $this->module = 'home';
293 // See if there is any page number information, and initialise pagination
294 $this->pager['page'] = ((x($_GET, 'page') && intval($_GET['page']) > 0) ? intval($_GET['page']) : 1);
295 $this->pager['itemspage'] = 50;
296 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
298 if ($this->pager['start'] < 0) {
299 $this->pager['start'] = 0;
301 $this->pager['total'] = 0;
303 // Detect mobile devices
304 $mobile_detect = new MobileDetect();
305 $this->is_mobile = $mobile_detect->isMobile();
306 $this->is_tablet = $mobile_detect->isTablet();
309 $this->is_friendica_app = isset($_SERVER['HTTP_USER_AGENT']) && $_SERVER['HTTP_USER_AGENT'] == 'Apache-HttpClient/UNAVAILABLE (java 1.4)';
311 // Register template engines
312 $this->register_template_engine('Friendica\Render\FriendicaSmartyEngine');
316 * Load the configuration files
318 * First loads the default value for all the configuration keys, then the legacy configuration files, then the
319 * expected local.ini.php
321 private function loadConfigFiles()
323 $this->loadConfigFile($this->basepath . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'config.ini.php');
324 $this->loadConfigFile($this->basepath . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'settings.ini.php');
326 // Legacy .htconfig.php support
327 if (file_exists($this->basepath . DIRECTORY_SEPARATOR . '.htpreconfig.php')) {
329 include $this->basepath . DIRECTORY_SEPARATOR . '.htpreconfig.php';
332 // Legacy .htconfig.php support
333 if (file_exists($this->basepath . DIRECTORY_SEPARATOR . '.htconfig.php')) {
336 include $this->basepath . DIRECTORY_SEPARATOR . '.htconfig.php';
338 $this->setConfigValue('database', 'hostname', $db_host);
339 $this->setConfigValue('database', 'username', $db_user);
340 $this->setConfigValue('database', 'password', $db_pass);
341 $this->setConfigValue('database', 'database', $db_data);
342 if (isset($a->config['system']['db_charset'])) {
343 $this->setConfigValue('database', 'charset', $a->config['system']['db_charset']);
346 unset($db_host, $db_user, $db_pass, $db_data);
348 if (isset($default_timezone)) {
349 $this->setConfigValue('system', 'default_timezone', $default_timezone);
350 unset($default_timezone);
353 if (isset($pidfile)) {
354 $this->setConfigValue('system', 'pidfile', $pidfile);
359 $this->setConfigValue('system', 'language', $lang);
364 if (file_exists($this->basepath . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'local.ini.php')) {
365 $this->loadConfigFile($this->basepath . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'local.ini.php');
370 * Tries to load the specified configuration file into the App->config array.
371 * Overwrites previously set values.
373 * The config format is INI and the template for configuration files is the following:
375 * <?php return <<<INI
383 * @param type $filepath
386 public function loadConfigFile($filepath)
388 if (!file_exists($filepath)) {
389 throw new Exception('Error parsing non-existent config file ' . $filepath);
392 $contents = include($filepath);
394 $config = parse_ini_string($contents, true, INI_SCANNER_TYPED);
396 if ($config === false) {
397 throw new Exception('Error parsing config file ' . $filepath);
400 foreach ($config as $category => $values) {
401 foreach ($values as $key => $value) {
402 $this->setConfigValue($category, $key, $value);
408 * Loads addons configuration files
410 * First loads all activated addons default configuration throught the load_config hook, then load the local.ini.php
411 * again to overwrite potential local addon configuration.
413 private function loadAddonConfig()
415 // Loads addons default config
416 Core\Addon::callHooks('load_config');
418 // Load the local addon config file to overwritten default addon config values
419 if (file_exists($this->basepath . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'addon.ini.php')) {
420 $this->loadConfigFile($this->basepath . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'addon.ini.php');
425 * Loads the default timezone
427 * Include support for legacy $default_timezone
429 * @global string $default_timezone
431 private function loadDefaultTimezone()
433 if ($this->getConfigValue('system', 'default_timezone')) {
434 $this->timezone = $this->getConfigValue('system', 'default_timezone');
436 global $default_timezone;
437 $this->timezone = !empty($default_timezone) ? $default_timezone : 'UTC';
440 if ($this->timezone) {
441 date_default_timezone_set($this->timezone);
446 * Figure out if we are running at the top of a domain or in a sub-directory and adjust accordingly
448 private function determineUrlPath()
450 $this->urlpath = $this->getConfigValue('system', 'urlpath');
452 /* SCRIPT_URL gives /path/to/friendica/module/parameter
453 * QUERY_STRING gives pagename=module/parameter
455 * To get /path/to/friendica we perform dirname() for as many levels as there are slashes in the QUERY_STRING
457 if (!empty($_SERVER['SCRIPT_URL'])) {
459 if (!empty($_SERVER['QUERY_STRING'])) {
460 $path = trim(dirname($_SERVER['SCRIPT_URL'], substr_count(trim($_SERVER['QUERY_STRING'], '/'), '/') + 1), '/');
463 $path = trim($_SERVER['SCRIPT_URL'], '/');
466 if ($path && $path != $this->urlpath) {
467 $this->urlpath = $path;
475 * - App::MODE_INSTALL : Either the database connection can't be established or the config table doesn't exist
476 * - App::MODE_MAINTENANCE: The maintenance mode has been set
477 * - App::MODE_NORMAL : Normal run with all features enabled
481 private function determineMode()
485 if (!file_exists($this->basepath . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'local.ini.php')
486 && !file_exists($this->basepath . DIRECTORY_SEPARATOR . '.htconfig.php')) {
490 $this->mode |= App::MODE_LOCALCONFIGPRESENT;
492 if (!DBA::connected()) {
496 $this->mode |= App::MODE_DBAVAILABLE;
498 if (DBA::fetchFirst("SHOW TABLES LIKE 'config'") === false) {
502 $this->mode |= App::MODE_DBCONFIGAVAILABLE;
504 if (Config::get('system', 'maintenance')) {
508 $this->mode |= App::MODE_MAINTENANCEDISABLED;
511 public function loadDatabase()
513 if (DBA::connected()) {
517 $db_host = $this->getConfigValue('database', 'hostname');
518 $db_user = $this->getConfigValue('database', 'username');
519 $db_pass = $this->getConfigValue('database', 'password');
520 $db_data = $this->getConfigValue('database', 'database');
521 $charset = $this->getConfigValue('database', 'charset');
523 // Use environment variables for mysql if they are set beforehand
524 if (!empty(getenv('MYSQL_HOST'))
525 && (!empty(getenv('MYSQL_USERNAME')) || !empty(getenv('MYSQL_USER')))
526 && getenv('MYSQL_PASSWORD') !== false
527 && !empty(getenv('MYSQL_DATABASE')))
529 $db_host = getenv('MYSQL_HOST');
530 if (!empty(getenv('MYSQL_PORT'))) {
531 $db_host .= ':' . getenv('MYSQL_PORT');
533 if (!empty(getenv('MYSQL_USERNAME'))) {
534 $db_user = getenv('MYSQL_USERNAME');
536 $db_user = getenv('MYSQL_USER');
538 $db_pass = (string) getenv('MYSQL_PASSWORD');
539 $db_data = getenv('MYSQL_DATABASE');
542 $stamp1 = microtime(true);
544 DBA::connect($db_host, $db_user, $db_pass, $db_data, $charset);
545 unset($db_host, $db_user, $db_pass, $db_data, $charset);
547 $this->save_timestamp($stamp1, 'network');
551 * Install mode is when the local config file is missing or the DB schema hasn't been installed yet.
555 public function isInstallMode()
557 return !($this->mode & App::MODE_LOCALCONFIGPRESENT) || !($this->mode & App::MODE_DBCONFIGAVAILABLE);
561 * @brief Returns the base filesystem path of the App
563 * It first checks for the internal variable, then for DOCUMENT_ROOT and
568 public function get_basepath()
570 $basepath = $this->basepath;
573 $basepath = Config::get('system', 'basepath');
576 if (!$basepath && x($_SERVER, 'DOCUMENT_ROOT')) {
577 $basepath = $_SERVER['DOCUMENT_ROOT'];
580 if (!$basepath && x($_SERVER, 'PWD')) {
581 $basepath = $_SERVER['PWD'];
584 return self::realpath($basepath);
588 * @brief Returns a normalized file path
590 * This is a wrapper for the "realpath" function.
591 * That function cannot detect the real path when some folders aren't readable.
592 * Since this could happen with some hosters we need to handle this.
594 * @param string $path The path that is about to be normalized
595 * @return string normalized path - when possible
597 public static function realpath($path)
599 $normalized = realpath($path);
601 if (!is_bool($normalized)) {
608 public function get_scheme()
610 return $this->scheme;
614 * @brief Retrieves the Friendica instance base URL
616 * This function assembles the base URL from multiple parts:
617 * - Protocol is determined either by the request or a combination of
618 * system.ssl_policy and the $ssl parameter.
619 * - Host name is determined either by system.hostname or inferred from request
620 * - Path is inferred from SCRIPT_NAME
622 * Note: $ssl parameter value doesn't directly correlate with the resulting protocol
624 * @param bool $ssl Whether to append http or https under SSL_POLICY_SELFSIGN
625 * @return string Friendica server base URL
627 public function get_baseurl($ssl = false)
629 $scheme = $this->scheme;
631 if (Config::get('system', 'ssl_policy') == SSL_POLICY_FULL) {
635 // Basically, we have $ssl = true on any links which can only be seen by a logged in user
636 // (and also the login link). Anything seen by an outsider will have it turned off.
638 if (Config::get('system', 'ssl_policy') == SSL_POLICY_SELFSIGN) {
646 if (Config::get('config', 'hostname') != '') {
647 $this->hostname = Config::get('config', 'hostname');
650 return $scheme . '://' . $this->hostname . (!empty($this->urlpath) ? '/' . $this->urlpath : '' );
654 * @brief Initializes the baseurl components
656 * Clears the baseurl cache to prevent inconsistencies
660 public function set_baseurl($url)
662 $parsed = @parse_url($url);
666 if (!empty($parsed['scheme'])) {
667 $this->scheme = $parsed['scheme'];
670 if (!empty($parsed['host'])) {
671 $hostname = $parsed['host'];
674 if (x($parsed, 'port')) {
675 $hostname .= ':' . $parsed['port'];
677 if (x($parsed, 'path')) {
678 $this->urlpath = trim($parsed['path'], '\\/');
681 if (file_exists($this->basepath . DIRECTORY_SEPARATOR . '.htpreconfig.php')) {
682 include $this->basepath . DIRECTORY_SEPARATOR . '.htpreconfig.php';
685 if (Config::get('config', 'hostname') != '') {
686 $this->hostname = Config::get('config', 'hostname');
689 if (!isset($this->hostname) || ($this->hostname == '')) {
690 $this->hostname = $hostname;
695 public function get_hostname()
697 if (Config::get('config', 'hostname') != '') {
698 $this->hostname = Config::get('config', 'hostname');
701 return $this->hostname;
704 public function get_path()
706 return $this->urlpath;
709 public function set_pager_total($n)
711 $this->pager['total'] = intval($n);
714 public function set_pager_itemspage($n)
716 $this->pager['itemspage'] = ((intval($n) > 0) ? intval($n) : 0);
717 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
720 public function set_pager_page($n)
722 $this->pager['page'] = $n;
723 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
726 public function init_pagehead()
728 $interval = ((local_user()) ? PConfig::get(local_user(), 'system', 'update_interval') : 40000);
730 // If the update is 'deactivated' set it to the highest integer number (~24 days)
732 $interval = 2147483647;
735 if ($interval < 10000) {
739 // compose the page title from the sitename and the
740 // current module called
741 if (!$this->module == '') {
742 $this->page['title'] = $this->config['sitename'] . ' (' . $this->module . ')';
744 $this->page['title'] = $this->config['sitename'];
747 /* put the head template at the beginning of page['htmlhead']
748 * since the code added by the modules frequently depends on it
751 if (!isset($this->page['htmlhead'])) {
752 $this->page['htmlhead'] = '';
755 // If we're using Smarty, then doing replace_macros() will replace
756 // any unrecognized variables with a blank string. Since we delay
757 // replacing $stylesheet until later, we need to replace it now
758 // with another variable name
759 if ($this->theme['template_engine'] === 'smarty3') {
760 $stylesheet = $this->get_template_ldelim('smarty3') . '$stylesheet' . $this->get_template_rdelim('smarty3');
762 $stylesheet = '$stylesheet';
765 $shortcut_icon = Config::get('system', 'shortcut_icon');
766 if ($shortcut_icon == '') {
767 $shortcut_icon = 'images/friendica-32.png';
770 $touch_icon = Config::get('system', 'touch_icon');
771 if ($touch_icon == '') {
772 $touch_icon = 'images/friendica-128.png';
775 // get data wich is needed for infinite scroll on the network page
776 $invinite_scroll = infinite_scroll_data($this->module);
778 $tpl = get_markup_template('head.tpl');
779 $this->page['htmlhead'] = replace_macros($tpl, [
780 '$baseurl' => $this->get_baseurl(),
781 '$local_user' => local_user(),
782 '$generator' => 'Friendica' . ' ' . FRIENDICA_VERSION,
783 '$delitem' => L10n::t('Delete this item?'),
784 '$showmore' => L10n::t('show more'),
785 '$showfewer' => L10n::t('show fewer'),
786 '$update_interval' => $interval,
787 '$shortcut_icon' => $shortcut_icon,
788 '$touch_icon' => $touch_icon,
789 '$stylesheet' => $stylesheet,
790 '$infinite_scroll' => $invinite_scroll,
791 '$block_public' => intval(Config::get('system', 'block_public')),
792 ]) . $this->page['htmlhead'];
795 public function init_page_end()
797 if (!isset($this->page['end'])) {
798 $this->page['end'] = '';
800 $tpl = get_markup_template('end.tpl');
801 $this->page['end'] = replace_macros($tpl, [
802 '$baseurl' => $this->get_baseurl()
803 ]) . $this->page['end'];
806 public function set_curl_code($code)
808 $this->curl_code = $code;
811 public function get_curl_code()
813 return $this->curl_code;
816 public function set_curl_content_type($content_type)
818 $this->curl_content_type = $content_type;
821 public function get_curl_content_type()
823 return $this->curl_content_type;
826 public function set_curl_headers($headers)
828 $this->curl_headers = $headers;
831 public function get_curl_headers()
833 return $this->curl_headers;
837 * @brief Removes the base url from an url. This avoids some mixed content problems.
839 * @param string $orig_url
841 * @return string The cleaned url
843 public function remove_baseurl($orig_url)
845 // Remove the hostname from the url if it is an internal link
846 $nurl = normalise_link($orig_url);
847 $base = normalise_link($this->get_baseurl());
848 $url = str_replace($base . '/', '', $nurl);
850 // if it is an external link return the orignal value
851 if ($url == normalise_link($orig_url)) {
859 * @brief Register template engine class
861 * @param string $class
863 private function register_template_engine($class)
865 $v = get_class_vars($class);
868 $this->template_engines[$name] = $class;
870 echo "template engine <tt>$class</tt> cannot be registered without a name.\n";
876 * @brief Return template engine instance.
878 * If $name is not defined, return engine defined by theme,
881 * @return object Template Engine instance
883 public function template_engine()
885 $template_engine = 'smarty3';
886 if (x($this->theme, 'template_engine')) {
887 $template_engine = $this->theme['template_engine'];
890 if (isset($this->template_engines[$template_engine])) {
891 if (isset($this->template_engine_instance[$template_engine])) {
892 return $this->template_engine_instance[$template_engine];
894 $class = $this->template_engines[$template_engine];
896 $this->template_engine_instance[$template_engine] = $obj;
901 echo "template engine <tt>$template_engine</tt> is not registered!\n";
906 * @brief Returns the active template engine.
910 public function get_template_engine()
912 return $this->theme['template_engine'];
915 public function set_template_engine($engine = 'smarty3')
917 $this->theme['template_engine'] = $engine;
920 public function get_template_ldelim($engine = 'smarty3')
922 return $this->ldelim[$engine];
925 public function get_template_rdelim($engine = 'smarty3')
927 return $this->rdelim[$engine];
930 public function save_timestamp($stamp, $value)
932 if (!isset($this->config['system']['profiler']) || !$this->config['system']['profiler']) {
936 $duration = (float) (microtime(true) - $stamp);
938 if (!isset($this->performance[$value])) {
939 // Prevent ugly E_NOTICE
940 $this->performance[$value] = 0;
943 $this->performance[$value] += (float) $duration;
944 $this->performance['marktime'] += (float) $duration;
946 $callstack = System::callstack();
948 if (!isset($this->callstack[$value][$callstack])) {
949 // Prevent ugly E_NOTICE
950 $this->callstack[$value][$callstack] = 0;
953 $this->callstack[$value][$callstack] += (float) $duration;
956 public function get_useragent()
959 FRIENDICA_PLATFORM . " '" .
960 FRIENDICA_CODENAME . "' " .
961 FRIENDICA_VERSION . '-' .
962 DB_UPDATE_VERSION . '; ' .
963 $this->get_baseurl();
966 public function is_friendica_app()
968 return $this->is_friendica_app;
972 * @brief Checks if the site is called via a backend process
974 * This isn't a perfect solution. But we need this check very early.
975 * So we cannot wait until the modules are loaded.
977 * @return bool Is it a known backend?
979 public function is_backend()
1003 // Check if current module is in backend or backend flag is set
1004 return (in_array($this->module, $backends) || $this->backend);
1008 * @brief Checks if the maximum number of database processes is reached
1010 * @return bool Is the limit reached?
1012 public function isMaxProcessesReached()
1014 // Deactivated, needs more investigating if this check really makes sense
1018 * Commented out to suppress static analyzer issues
1020 if ($this->is_backend()) {
1021 $process = 'backend';
1022 $max_processes = Config::get('system', 'max_processes_backend');
1023 if (intval($max_processes) == 0) {
1027 $process = 'frontend';
1028 $max_processes = Config::get('system', 'max_processes_frontend');
1029 if (intval($max_processes) == 0) {
1030 $max_processes = 20;
1034 $processlist = DBA::processlist();
1035 if ($processlist['list'] != '') {
1036 logger('Processcheck: Processes: ' . $processlist['amount'] . ' - Processlist: ' . $processlist['list'], LOGGER_DEBUG);
1038 if ($processlist['amount'] > $max_processes) {
1039 logger('Processcheck: Maximum number of processes for ' . $process . ' tasks (' . $max_processes . ') reached.', LOGGER_DEBUG);
1048 * @brief Checks if the minimal memory is reached
1050 * @return bool Is the memory limit reached?
1052 public function min_memory_reached()
1054 $min_memory = Config::get('system', 'min_memory', 0);
1055 if ($min_memory == 0) {
1059 if (!is_readable('/proc/meminfo')) {
1063 $memdata = explode("\n", file_get_contents('/proc/meminfo'));
1066 foreach ($memdata as $line) {
1067 list($key, $val) = explode(':', $line);
1068 $meminfo[$key] = (int) trim(str_replace('kB', '', $val));
1069 $meminfo[$key] = (int) ($meminfo[$key] / 1024);
1072 if (!isset($meminfo['MemAvailable']) || !isset($meminfo['MemFree'])) {
1076 $free = $meminfo['MemAvailable'] + $meminfo['MemFree'];
1078 $reached = ($free < $min_memory);
1081 logger('Minimal memory reached: ' . $free . '/' . $meminfo['MemTotal'] . ' - limit ' . $min_memory, LOGGER_DEBUG);
1088 * @brief Checks if the maximum load is reached
1090 * @return bool Is the load reached?
1092 public function isMaxLoadReached()
1094 if ($this->is_backend()) {
1095 $process = 'backend';
1096 $maxsysload = intval(Config::get('system', 'maxloadavg'));
1097 if ($maxsysload < 1) {
1101 $process = 'frontend';
1102 $maxsysload = intval(Config::get('system', 'maxloadavg_frontend'));
1103 if ($maxsysload < 1) {
1108 $load = current_load();
1110 if (intval($load) > $maxsysload) {
1111 logger('system: load ' . $load . ' for ' . $process . ' tasks (' . $maxsysload . ') too high.');
1119 * Executes a child process with 'proc_open'
1121 * @param string $command The command to execute
1122 * @param array $args Arguments to pass to the command ( [ 'key' => value, 'key2' => value2, ... ]
1124 public function proc_run($command, $args)
1126 if (!function_exists('proc_open')) {
1130 $cmdline = $this->getConfigValue('config', 'php_path', 'php') . ' ' . escapeshellarg($command);
1132 foreach ($args as $key => $value) {
1133 if (!is_null($value) && is_bool($value) && !$value) {
1137 $cmdline .= ' --' . $key;
1138 if (!is_null($value) && !is_bool($value)) {
1139 $cmdline .= ' ' . $value;
1143 if ($this->min_memory_reached()) {
1147 if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
1148 $resource = proc_open('cmd /c start /b ' . $cmdline, [], $foo, $this->get_basepath());
1150 $resource = proc_open($cmdline . ' &', [], $foo, $this->get_basepath());
1152 if (!is_resource($resource)) {
1153 logger('We got no resource for command ' . $cmdline, LOGGER_DEBUG);
1156 proc_close($resource);
1160 * @brief Returns the system user that is executing the script
1162 * This mostly returns something like "www-data".
1164 * @return string system username
1166 private static function systemuser()
1168 if (!function_exists('posix_getpwuid') || !function_exists('posix_geteuid')) {
1172 $processUser = posix_getpwuid(posix_geteuid());
1173 return $processUser['name'];
1177 * @brief Checks if a given directory is usable for the system
1179 * @return boolean the directory is usable
1181 public static function directory_usable($directory, $check_writable = true)
1183 if ($directory == '') {
1184 logger('Directory is empty. This shouldn\'t happen.', LOGGER_DEBUG);
1188 if (!file_exists($directory)) {
1189 logger('Path "' . $directory . '" does not exist for user ' . self::systemuser(), LOGGER_DEBUG);
1193 if (is_file($directory)) {
1194 logger('Path "' . $directory . '" is a file for user ' . self::systemuser(), LOGGER_DEBUG);
1198 if (!is_dir($directory)) {
1199 logger('Path "' . $directory . '" is not a directory for user ' . self::systemuser(), LOGGER_DEBUG);
1203 if ($check_writable && !is_writable($directory)) {
1204 logger('Path "' . $directory . '" is not writable for user ' . self::systemuser(), LOGGER_DEBUG);
1212 * @param string $cat Config category
1213 * @param string $k Config key
1214 * @param mixed $default Default value if it isn't set
1216 public function getConfigValue($cat, $k, $default = null)
1220 if ($cat === 'config') {
1221 if (isset($this->config[$k])) {
1222 $return = $this->config[$k];
1225 if (isset($this->config[$cat][$k])) {
1226 $return = $this->config[$cat][$k];
1234 * Sets a value in the config cache. Accepts raw output from the config table
1236 * @param string $cat Config category
1237 * @param string $k Config key
1238 * @param mixed $v Value to set
1240 public function setConfigValue($cat, $k, $v)
1242 // Only arrays are serialized in database, so we have to unserialize sparingly
1243 $value = is_string($v) && preg_match("|^a:[0-9]+:{.*}$|s", $v) ? unserialize($v) : $v;
1245 if ($cat === 'config') {
1246 $this->config[$k] = $value;
1248 if (!isset($this->config[$cat])) {
1249 $this->config[$cat] = [];
1252 $this->config[$cat][$k] = $value;
1257 * Deletes a value from the config cache
1259 * @param string $cat Config category
1260 * @param string $k Config key
1262 public function deleteConfigValue($cat, $k)
1264 if ($cat === 'config') {
1265 if (isset($this->config[$k])) {
1266 unset($this->config[$k]);
1269 if (isset($this->config[$cat][$k])) {
1270 unset($this->config[$cat][$k]);
1277 * Retrieves a value from the user config cache
1279 * @param int $uid User Id
1280 * @param string $cat Config category
1281 * @param string $k Config key
1282 * @param mixed $default Default value if key isn't set
1284 public function getPConfigValue($uid, $cat, $k, $default = null)
1288 if (isset($this->config[$uid][$cat][$k])) {
1289 $return = $this->config[$uid][$cat][$k];
1296 * Sets a value in the user config cache
1298 * Accepts raw output from the pconfig table
1300 * @param int $uid User Id
1301 * @param string $cat Config category
1302 * @param string $k Config key
1303 * @param mixed $v Value to set
1305 public function setPConfigValue($uid, $cat, $k, $v)
1307 // Only arrays are serialized in database, so we have to unserialize sparingly
1308 $value = is_string($v) && preg_match("|^a:[0-9]+:{.*}$|s", $v) ? unserialize($v) : $v;
1310 if (!isset($this->config[$uid]) || !is_array($this->config[$uid])) {
1311 $this->config[$uid] = [];
1314 if (!isset($this->config[$uid][$cat]) || !is_array($this->config[$uid][$cat])) {
1315 $this->config[$uid][$cat] = [];
1318 $this->config[$uid][$cat][$k] = $value;
1322 * Deletes a value from the user config cache
1324 * @param int $uid User Id
1325 * @param string $cat Config category
1326 * @param string $k Config key
1328 public function deletePConfigValue($uid, $cat, $k)
1330 if (isset($this->config[$uid][$cat][$k])) {
1331 unset($this->config[$uid][$cat][$k]);
1336 * Generates the site's default sender email address
1340 public function getSenderEmailAddress()
1342 $sender_email = Config::get('config', 'sender_email');
1343 if (empty($sender_email)) {
1344 $hostname = $this->get_hostname();
1345 if (strpos($hostname, ':')) {
1346 $hostname = substr($hostname, 0, strpos($hostname, ':'));
1349 $sender_email = 'noreply@' . $hostname;
1352 return $sender_email;
1356 * Returns the current theme name.
1360 public function getCurrentTheme()
1362 if ($this->isInstallMode()) {
1366 //// @TODO Compute the current theme only once (this behavior has
1367 /// already been implemented, but it didn't work well -
1368 /// https://github.com/friendica/friendica/issues/5092)
1369 $this->computeCurrentTheme();
1371 return $this->current_theme;
1375 * Computes the current theme name based on the node settings, the user settings and the device type
1379 private function computeCurrentTheme()
1381 $system_theme = Config::get('system', 'theme');
1382 if (!$system_theme) {
1383 throw new Exception(L10n::t('No system theme config value set.'));
1387 $this->current_theme = $system_theme;
1389 $allowed_themes = explode(',', Config::get('system', 'allowed_themes', $system_theme));
1392 // Find the theme that belongs to the user whose stuff we are looking at
1393 if ($this->profile_uid && ($this->profile_uid != local_user())) {
1394 // Allow folks to override user themes and always use their own on their own site.
1395 // This works only if the user is on the same server
1396 $user = DBA::selectFirst('user', ['theme'], ['uid' => $this->profile_uid]);
1397 if (DBA::isResult($user) && !PConfig::get(local_user(), 'system', 'always_my_theme')) {
1398 $page_theme = $user['theme'];
1402 if (!empty($_SESSION)) {
1403 $user_theme = defaults($_SESSION, 'theme', $system_theme);
1405 $user_theme = $system_theme;
1408 // Specific mobile theme override
1409 if (($this->is_mobile || $this->is_tablet) && defaults($_SESSION, 'show-mobile', true)) {
1410 $system_mobile_theme = Config::get('system', 'mobile-theme');
1411 $user_mobile_theme = defaults($_SESSION, 'mobile-theme', $system_mobile_theme);
1413 // --- means same mobile theme as desktop
1414 if (!empty($user_mobile_theme) && $user_mobile_theme !== '---') {
1415 $user_theme = $user_mobile_theme;
1420 $theme_name = $page_theme;
1422 $theme_name = $user_theme;
1426 && in_array($theme_name, $allowed_themes)
1427 && (file_exists('view/theme/' . $theme_name . '/style.css')
1428 || file_exists('view/theme/' . $theme_name . '/style.php'))
1430 $this->current_theme = $theme_name;
1435 * @brief Return full URL to theme which is currently in effect.
1437 * Provide a sane default if nothing is chosen or the specified theme does not exist.
1441 public function getCurrentThemeStylesheetPath()
1443 return Core\Theme::getStylesheetPath($this->getCurrentTheme());