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 public $module_loaded = false;
35 public $module_class = null;
36 public $query_string = '';
50 public $error = false;
60 public $interactive = true;
62 public $addons_admin = [];
65 public $is_mobile = false;
66 public $is_tablet = false;
67 public $is_friendica_app;
68 public $performance = [];
69 public $callstack = [];
70 public $theme_info = [];
71 public $backend = true;
74 // Allow themes to control internal parameters
75 // by changing App values in theme.php
77 public $sourcename = '';
78 public $videowidth = 425;
79 public $videoheight = 350;
80 public $force_max_items = 0;
81 public $theme_events_in_profile = true;
83 public $stylesheets = [];
84 public $footerScripts = [];
87 * Register a stylesheet file path to be included in the <head> tag of every page.
88 * Inclusion is done in App->initHead().
89 * The path can be absolute or relative to the Friendica installation base folder.
91 * @see App->initHead()
95 public function registerStylesheet($path)
97 $url = str_replace($this->get_basepath() . DIRECTORY_SEPARATOR, '', $path);
99 $this->stylesheets[] = trim($url, '/');
103 * Register a javascript file path to be included in the <footer> tag of every page.
104 * Inclusion is done in App->initFooter().
105 * The path can be absolute or relative to the Friendica installation base folder.
107 * @see App->initFooter()
109 * @param string $path
111 public function registerFooterScript($path)
113 $url = str_replace($this->get_basepath() . DIRECTORY_SEPARATOR, '', $path);
115 $this->footerScripts[] = trim($url, '/');
119 * @brief An array for all theme-controllable parameters
121 * Mostly unimplemented yet. Only options 'template_engine' and
127 'videoheight' => 350,
128 'force_max_items' => 0,
130 'template_engine' => 'smarty3',
134 * @brief An array of registered template engines ('name'=>'class name')
136 public $template_engines = [];
139 * @brief An array of instanced template engines ('name'=>'instance')
141 public $template_engine_instance = [];
155 private $curl_content_type;
156 private $curl_headers;
159 * @brief App constructor.
161 * @param string $basepath Path to the app base folder
163 * @throws Exception if the Basepath is not usable
165 public function __construct($basepath)
167 if (!static::directory_usable($basepath, false)) {
168 throw new Exception('Basepath ' . $basepath . ' isn\'t usable.');
171 BaseObject::setApp($this);
173 $this->basepath = rtrim($basepath, DIRECTORY_SEPARATOR);
175 $this->performance['start'] = microtime(true);
176 $this->performance['database'] = 0;
177 $this->performance['database_write'] = 0;
178 $this->performance['cache'] = 0;
179 $this->performance['cache_write'] = 0;
180 $this->performance['network'] = 0;
181 $this->performance['file'] = 0;
182 $this->performance['rendering'] = 0;
183 $this->performance['parser'] = 0;
184 $this->performance['marktime'] = 0;
185 $this->performance['markstart'] = microtime(true);
187 $this->callstack['database'] = [];
188 $this->callstack['database_write'] = [];
189 $this->callstack['cache'] = [];
190 $this->callstack['cache_write'] = [];
191 $this->callstack['network'] = [];
192 $this->callstack['file'] = [];
193 $this->callstack['rendering'] = [];
194 $this->callstack['parser'] = [];
200 // This has to be quite large to deal with embedded private photos
201 ini_set('pcre.backtrack_limit', 500000);
203 $this->scheme = 'http';
205 if ((x($_SERVER, 'HTTPS') && $_SERVER['HTTPS']) ||
206 (x($_SERVER, 'HTTP_FORWARDED') && preg_match('/proto=https/', $_SERVER['HTTP_FORWARDED'])) ||
207 (x($_SERVER, 'HTTP_X_FORWARDED_PROTO') && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') ||
208 (x($_SERVER, 'HTTP_X_FORWARDED_SSL') && $_SERVER['HTTP_X_FORWARDED_SSL'] == 'on') ||
209 (x($_SERVER, 'FRONT_END_HTTPS') && $_SERVER['FRONT_END_HTTPS'] == 'on') ||
210 (x($_SERVER, 'SERVER_PORT') && (intval($_SERVER['SERVER_PORT']) == 443)) // XXX: reasonable assumption, but isn't this hardcoding too much?
212 $this->scheme = 'https';
215 if (x($_SERVER, 'SERVER_NAME')) {
216 $this->hostname = $_SERVER['SERVER_NAME'];
218 if (x($_SERVER, 'SERVER_PORT') && $_SERVER['SERVER_PORT'] != 80 && $_SERVER['SERVER_PORT'] != 443) {
219 $this->hostname .= ':' . $_SERVER['SERVER_PORT'];
224 get_include_path() . PATH_SEPARATOR
225 . $this->basepath . DIRECTORY_SEPARATOR . 'include' . PATH_SEPARATOR
226 . $this->basepath . DIRECTORY_SEPARATOR . 'library' . PATH_SEPARATOR
229 if ((x($_SERVER, 'QUERY_STRING')) && substr($_SERVER['QUERY_STRING'], 0, 9) === 'pagename=') {
230 $this->query_string = substr($_SERVER['QUERY_STRING'], 9);
231 } elseif ((x($_SERVER, 'QUERY_STRING')) && substr($_SERVER['QUERY_STRING'], 0, 2) === 'q=') {
232 $this->query_string = substr($_SERVER['QUERY_STRING'], 2);
235 // removing trailing / - maybe a nginx problem
236 $this->query_string = ltrim($this->query_string, '/');
238 if (!empty($_GET['pagename'])) {
239 $this->cmd = trim($_GET['pagename'], '/\\');
240 } elseif (!empty($_GET['q'])) {
241 $this->cmd = trim($_GET['q'], '/\\');
245 $this->query_string = str_replace($this->cmd . '&', $this->cmd . '?', $this->query_string);
247 // unix style "homedir"
248 if (substr($this->cmd, 0, 1) === '~') {
249 $this->cmd = 'profile/' . substr($this->cmd, 1);
252 // Diaspora style profile url
253 if (substr($this->cmd, 0, 2) === 'u/') {
254 $this->cmd = 'profile/' . substr($this->cmd, 2);
258 * Break the URL path into C style argc/argv style arguments for our
259 * modules. Given "http://example.com/module/arg1/arg2", $this->argc
260 * will be 3 (integer) and $this->argv will contain:
266 * There will always be one argument. If provided a naked domain
267 * URL, $this->argv[0] is set to "home".
270 $this->argv = explode('/', $this->cmd);
271 $this->argc = count($this->argv);
272 if ((array_key_exists('0', $this->argv)) && strlen($this->argv[0])) {
273 $this->module = str_replace('.', '_', $this->argv[0]);
274 $this->module = str_replace('-', '_', $this->module);
277 $this->argv = ['home'];
278 $this->module = 'home';
281 // See if there is any page number information, and initialise pagination
282 $this->pager['page'] = ((x($_GET, 'page') && intval($_GET['page']) > 0) ? intval($_GET['page']) : 1);
283 $this->pager['itemspage'] = 50;
284 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
286 if ($this->pager['start'] < 0) {
287 $this->pager['start'] = 0;
289 $this->pager['total'] = 0;
291 // Detect mobile devices
292 $mobile_detect = new MobileDetect();
293 $this->is_mobile = $mobile_detect->isMobile();
294 $this->is_tablet = $mobile_detect->isTablet();
297 $this->is_friendica_app = isset($_SERVER['HTTP_USER_AGENT']) && $_SERVER['HTTP_USER_AGENT'] == 'Apache-HttpClient/UNAVAILABLE (java 1.4)';
299 // Register template engines
300 $this->register_template_engine('Friendica\Render\FriendicaSmartyEngine');
304 * Reloads the whole app instance
306 public function reload()
308 // The order of the following calls is important to ensure proper initialization
309 $this->loadConfigFiles();
311 $this->loadDatabase();
313 App\Mode::determine($this->basepath);
315 $this->determineUrlPath();
319 if (App\Mode::has(App\Mode::DBAVAILABLE)) {
320 Core\Addon::loadHooks();
322 $this->loadAddonConfig();
325 $this->loadDefaultTimezone();
340 $this->process_id = System::processID('log');
344 * Load the configuration files
346 * First loads the default value for all the configuration keys, then the legacy configuration files, then the
347 * expected local.ini.php
349 private function loadConfigFiles()
351 $this->loadConfigFile($this->basepath . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'config.ini.php');
352 $this->loadConfigFile($this->basepath . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'settings.ini.php');
354 // Legacy .htconfig.php support
355 if (file_exists($this->basepath . DIRECTORY_SEPARATOR . '.htpreconfig.php')) {
357 include $this->basepath . DIRECTORY_SEPARATOR . '.htpreconfig.php';
360 // Legacy .htconfig.php support
361 if (file_exists($this->basepath . DIRECTORY_SEPARATOR . '.htconfig.php')) {
364 include $this->basepath . DIRECTORY_SEPARATOR . '.htconfig.php';
366 $this->setConfigValue('database', 'hostname', $db_host);
367 $this->setConfigValue('database', 'username', $db_user);
368 $this->setConfigValue('database', 'password', $db_pass);
369 $this->setConfigValue('database', 'database', $db_data);
370 if (isset($a->config['system']['db_charset'])) {
371 $this->setConfigValue('database', 'charset', $a->config['system']['db_charset']);
374 unset($db_host, $db_user, $db_pass, $db_data);
376 if (isset($default_timezone)) {
377 $this->setConfigValue('system', 'default_timezone', $default_timezone);
378 unset($default_timezone);
381 if (isset($pidfile)) {
382 $this->setConfigValue('system', 'pidfile', $pidfile);
387 $this->setConfigValue('system', 'language', $lang);
392 if (file_exists($this->basepath . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'local.ini.php')) {
393 $this->loadConfigFile($this->basepath . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'local.ini.php', true);
398 * Tries to load the specified configuration file into the App->config array.
399 * Doesn't overwrite previously set values by default to prevent default config files to supersede DB Config.
401 * The config format is INI and the template for configuration files is the following:
403 * <?php return <<<INI
411 * @param type $filepath
412 * @param bool $overwrite Force value overwrite if the config key already exists
415 public function loadConfigFile($filepath, $overwrite = false)
417 if (!file_exists($filepath)) {
418 throw new Exception('Error parsing non-existent config file ' . $filepath);
421 $contents = include($filepath);
423 $config = parse_ini_string($contents, true, INI_SCANNER_TYPED);
425 if ($config === false) {
426 throw new Exception('Error parsing config file ' . $filepath);
429 foreach ($config as $category => $values) {
430 foreach ($values as $key => $value) {
432 $this->setConfigValue($category, $key, $value);
434 $this->setDefaultConfigValue($category, $key, $value);
441 * Loads addons configuration files
443 * First loads all activated addons default configuration throught the load_config hook, then load the local.ini.php
444 * again to overwrite potential local addon configuration.
446 private function loadAddonConfig()
448 // Loads addons default config
449 Core\Addon::callHooks('load_config');
451 // Load the local addon config file to overwritten default addon config values
452 if (file_exists($this->basepath . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'addon.ini.php')) {
453 $this->loadConfigFile($this->basepath . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'addon.ini.php', true);
458 * Loads the default timezone
460 * Include support for legacy $default_timezone
462 * @global string $default_timezone
464 private function loadDefaultTimezone()
466 if ($this->getConfigValue('system', 'default_timezone')) {
467 $this->timezone = $this->getConfigValue('system', 'default_timezone');
469 global $default_timezone;
470 $this->timezone = !empty($default_timezone) ? $default_timezone : 'UTC';
473 if ($this->timezone) {
474 date_default_timezone_set($this->timezone);
479 * Figure out if we are running at the top of a domain or in a sub-directory and adjust accordingly
481 private function determineUrlPath()
483 $this->urlpath = $this->getConfigValue('system', 'urlpath');
485 /* SCRIPT_URL gives /path/to/friendica/module/parameter
486 * QUERY_STRING gives pagename=module/parameter
488 * To get /path/to/friendica we perform dirname() for as many levels as there are slashes in the QUERY_STRING
490 if (!empty($_SERVER['SCRIPT_URL'])) {
492 if (!empty($_SERVER['QUERY_STRING'])) {
493 $path = trim(dirname($_SERVER['SCRIPT_URL'], substr_count(trim($_SERVER['QUERY_STRING'], '/'), '/') + 1), '/');
496 $path = trim($_SERVER['SCRIPT_URL'], '/');
499 if ($path && $path != $this->urlpath) {
500 $this->urlpath = $path;
505 public function loadDatabase()
507 if (DBA::connected()) {
511 $db_host = $this->getConfigValue('database', 'hostname');
512 $db_user = $this->getConfigValue('database', 'username');
513 $db_pass = $this->getConfigValue('database', 'password');
514 $db_data = $this->getConfigValue('database', 'database');
515 $charset = $this->getConfigValue('database', 'charset');
517 // Use environment variables for mysql if they are set beforehand
518 if (!empty(getenv('MYSQL_HOST'))
519 && (!empty(getenv('MYSQL_USERNAME')) || !empty(getenv('MYSQL_USER')))
520 && getenv('MYSQL_PASSWORD') !== false
521 && !empty(getenv('MYSQL_DATABASE')))
523 $db_host = getenv('MYSQL_HOST');
524 if (!empty(getenv('MYSQL_PORT'))) {
525 $db_host .= ':' . getenv('MYSQL_PORT');
527 if (!empty(getenv('MYSQL_USERNAME'))) {
528 $db_user = getenv('MYSQL_USERNAME');
530 $db_user = getenv('MYSQL_USER');
532 $db_pass = (string) getenv('MYSQL_PASSWORD');
533 $db_data = getenv('MYSQL_DATABASE');
536 $stamp1 = microtime(true);
538 DBA::connect($db_host, $db_user, $db_pass, $db_data, $charset);
539 unset($db_host, $db_user, $db_pass, $db_data, $charset);
541 $this->save_timestamp($stamp1, 'network');
545 * @brief Returns the base filesystem path of the App
547 * It first checks for the internal variable, then for DOCUMENT_ROOT and
552 public function get_basepath()
554 $basepath = $this->basepath;
557 $basepath = Config::get('system', 'basepath');
560 if (!$basepath && x($_SERVER, 'DOCUMENT_ROOT')) {
561 $basepath = $_SERVER['DOCUMENT_ROOT'];
564 if (!$basepath && x($_SERVER, 'PWD')) {
565 $basepath = $_SERVER['PWD'];
568 return self::realpath($basepath);
572 * @brief Returns a normalized file path
574 * This is a wrapper for the "realpath" function.
575 * That function cannot detect the real path when some folders aren't readable.
576 * Since this could happen with some hosters we need to handle this.
578 * @param string $path The path that is about to be normalized
579 * @return string normalized path - when possible
581 public static function realpath($path)
583 $normalized = realpath($path);
585 if (!is_bool($normalized)) {
592 public function get_scheme()
594 return $this->scheme;
598 * @brief Retrieves the Friendica instance base URL
600 * This function assembles the base URL from multiple parts:
601 * - Protocol is determined either by the request or a combination of
602 * system.ssl_policy and the $ssl parameter.
603 * - Host name is determined either by system.hostname or inferred from request
604 * - Path is inferred from SCRIPT_NAME
606 * Note: $ssl parameter value doesn't directly correlate with the resulting protocol
608 * @param bool $ssl Whether to append http or https under SSL_POLICY_SELFSIGN
609 * @return string Friendica server base URL
611 public function get_baseurl($ssl = false)
613 $scheme = $this->scheme;
615 if (Config::get('system', 'ssl_policy') == SSL_POLICY_FULL) {
619 // Basically, we have $ssl = true on any links which can only be seen by a logged in user
620 // (and also the login link). Anything seen by an outsider will have it turned off.
622 if (Config::get('system', 'ssl_policy') == SSL_POLICY_SELFSIGN) {
630 if (Config::get('config', 'hostname') != '') {
631 $this->hostname = Config::get('config', 'hostname');
634 return $scheme . '://' . $this->hostname . (!empty($this->urlpath) ? '/' . $this->urlpath : '' );
638 * @brief Initializes the baseurl components
640 * Clears the baseurl cache to prevent inconsistencies
644 public function set_baseurl($url)
646 $parsed = @parse_url($url);
650 if (!empty($parsed['scheme'])) {
651 $this->scheme = $parsed['scheme'];
654 if (!empty($parsed['host'])) {
655 $hostname = $parsed['host'];
658 if (x($parsed, 'port')) {
659 $hostname .= ':' . $parsed['port'];
661 if (x($parsed, 'path')) {
662 $this->urlpath = trim($parsed['path'], '\\/');
665 if (file_exists($this->basepath . DIRECTORY_SEPARATOR . '.htpreconfig.php')) {
666 include $this->basepath . DIRECTORY_SEPARATOR . '.htpreconfig.php';
669 if (Config::get('config', 'hostname') != '') {
670 $this->hostname = Config::get('config', 'hostname');
673 if (!isset($this->hostname) || ($this->hostname == '')) {
674 $this->hostname = $hostname;
679 public function get_hostname()
681 if (Config::get('config', 'hostname') != '') {
682 $this->hostname = Config::get('config', 'hostname');
685 return $this->hostname;
688 public function get_path()
690 return $this->urlpath;
693 public function set_pager_total($n)
695 $this->pager['total'] = intval($n);
698 public function set_pager_itemspage($n)
700 $this->pager['itemspage'] = ((intval($n) > 0) ? intval($n) : 0);
701 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
704 public function set_pager_page($n)
706 $this->pager['page'] = $n;
707 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
711 * Initializes App->page['htmlhead'].
716 * - Registered stylesheets (through App->registerStylesheet())
717 * - Infinite scroll data
718 * - head.tpl template
720 public function initHead()
722 $interval = ((local_user()) ? PConfig::get(local_user(), 'system', 'update_interval') : 40000);
724 // If the update is 'deactivated' set it to the highest integer number (~24 days)
726 $interval = 2147483647;
729 if ($interval < 10000) {
733 // compose the page title from the sitename and the
734 // current module called
735 if (!$this->module == '') {
736 $this->page['title'] = $this->config['sitename'] . ' (' . $this->module . ')';
738 $this->page['title'] = $this->config['sitename'];
741 if (!empty($this->theme['stylesheet'])) {
742 $stylesheet = $this->theme['stylesheet'];
744 $stylesheet = $this->getCurrentThemeStylesheetPath();
747 $this->registerStylesheet($stylesheet);
749 $shortcut_icon = Config::get('system', 'shortcut_icon');
750 if ($shortcut_icon == '') {
751 $shortcut_icon = 'images/friendica-32.png';
754 $touch_icon = Config::get('system', 'touch_icon');
755 if ($touch_icon == '') {
756 $touch_icon = 'images/friendica-128.png';
759 // get data wich is needed for infinite scroll on the network page
760 $infinite_scroll = infinite_scroll_data($this->module);
762 Core\Addon::callHooks('head', $this->page['htmlhead']);
764 $tpl = get_markup_template('head.tpl');
765 /* put the head template at the beginning of page['htmlhead']
766 * since the code added by the modules frequently depends on it
769 $this->page['htmlhead'] = replace_macros($tpl, [
770 '$baseurl' => $this->get_baseurl(),
771 '$local_user' => local_user(),
772 '$generator' => 'Friendica' . ' ' . FRIENDICA_VERSION,
773 '$delitem' => L10n::t('Delete this item?'),
774 '$showmore' => L10n::t('show more'),
775 '$showfewer' => L10n::t('show fewer'),
776 '$update_interval' => $interval,
777 '$shortcut_icon' => $shortcut_icon,
778 '$touch_icon' => $touch_icon,
779 '$infinite_scroll' => $infinite_scroll,
780 '$block_public' => intval(Config::get('system', 'block_public')),
781 '$stylesheets' => $this->stylesheets,
782 ]) . $this->page['htmlhead'];
786 * Initializes App->page['footer'].
789 * - Javascript homebase
790 * - Mobile toggle link
791 * - Registered footer scripts (through App->registerFooterScript())
792 * - footer.tpl template
794 public function initFooter()
796 // If you're just visiting, let javascript take you home
797 if (!empty($_SESSION['visitor_home'])) {
798 $homebase = $_SESSION['visitor_home'];
799 } elseif (local_user()) {
800 $homebase = 'profile/' . $this->user['nickname'];
803 if (isset($homebase)) {
804 $this->page['footer'] .= '<script>var homebase="' . $homebase . '";</script>' . "\n";
808 * Add a "toggle mobile" link if we're using a mobile device
810 if ($this->is_mobile || $this->is_tablet) {
811 if (isset($_SESSION['show-mobile']) && !$_SESSION['show-mobile']) {
812 $link = 'toggle_mobile?address=' . curPageURL();
814 $link = 'toggle_mobile?off=1&address=' . curPageURL();
816 $this->page['footer'] .= replace_macros(get_markup_template("toggle_mobile_footer.tpl"), [
817 '$toggle_link' => $link,
818 '$toggle_text' => Core\L10n::t('toggle mobile')
822 Core\Addon::callHooks('footer', $this->page['footer']);
824 $tpl = get_markup_template('footer.tpl');
825 $this->page['footer'] = replace_macros($tpl, [
826 '$baseurl' => $this->get_baseurl(),
827 '$footerScripts' => $this->footerScripts,
828 ]) . $this->page['footer'];
831 public function set_curl_code($code)
833 $this->curl_code = $code;
836 public function get_curl_code()
838 return $this->curl_code;
841 public function set_curl_content_type($content_type)
843 $this->curl_content_type = $content_type;
846 public function get_curl_content_type()
848 return $this->curl_content_type;
851 public function set_curl_headers($headers)
853 $this->curl_headers = $headers;
856 public function get_curl_headers()
858 return $this->curl_headers;
862 * @brief Removes the base url from an url. This avoids some mixed content problems.
864 * @param string $orig_url
866 * @return string The cleaned url
868 public function remove_baseurl($orig_url)
870 // Remove the hostname from the url if it is an internal link
871 $nurl = normalise_link($orig_url);
872 $base = normalise_link($this->get_baseurl());
873 $url = str_replace($base . '/', '', $nurl);
875 // if it is an external link return the orignal value
876 if ($url == normalise_link($orig_url)) {
884 * @brief Register template engine class
886 * @param string $class
888 private function register_template_engine($class)
890 $v = get_class_vars($class);
893 $this->template_engines[$name] = $class;
895 echo "template engine <tt>$class</tt> cannot be registered without a name.\n";
901 * @brief Return template engine instance.
903 * If $name is not defined, return engine defined by theme,
906 * @return object Template Engine instance
908 public function template_engine()
910 $template_engine = 'smarty3';
911 if (x($this->theme, 'template_engine')) {
912 $template_engine = $this->theme['template_engine'];
915 if (isset($this->template_engines[$template_engine])) {
916 if (isset($this->template_engine_instance[$template_engine])) {
917 return $this->template_engine_instance[$template_engine];
919 $class = $this->template_engines[$template_engine];
921 $this->template_engine_instance[$template_engine] = $obj;
926 echo "template engine <tt>$template_engine</tt> is not registered!\n";
931 * @brief Returns the active template engine.
935 public function get_template_engine()
937 return $this->theme['template_engine'];
940 public function set_template_engine($engine = 'smarty3')
942 $this->theme['template_engine'] = $engine;
945 public function get_template_ldelim($engine = 'smarty3')
947 return $this->ldelim[$engine];
950 public function get_template_rdelim($engine = 'smarty3')
952 return $this->rdelim[$engine];
955 public function save_timestamp($stamp, $value)
957 if (!isset($this->config['system']['profiler']) || !$this->config['system']['profiler']) {
961 $duration = (float) (microtime(true) - $stamp);
963 if (!isset($this->performance[$value])) {
964 // Prevent ugly E_NOTICE
965 $this->performance[$value] = 0;
968 $this->performance[$value] += (float) $duration;
969 $this->performance['marktime'] += (float) $duration;
971 $callstack = System::callstack();
973 if (!isset($this->callstack[$value][$callstack])) {
974 // Prevent ugly E_NOTICE
975 $this->callstack[$value][$callstack] = 0;
978 $this->callstack[$value][$callstack] += (float) $duration;
981 public function get_useragent()
984 FRIENDICA_PLATFORM . " '" .
985 FRIENDICA_CODENAME . "' " .
986 FRIENDICA_VERSION . '-' .
987 DB_UPDATE_VERSION . '; ' .
988 $this->get_baseurl();
991 public function is_friendica_app()
993 return $this->is_friendica_app;
997 * @brief Checks if the site is called via a backend process
999 * This isn't a perfect solution. But we need this check very early.
1000 * So we cannot wait until the modules are loaded.
1002 * @return bool Is it a known backend?
1004 public function is_backend()
1006 static $backends = [
1028 // Check if current module is in backend or backend flag is set
1029 return (in_array($this->module, $backends) || $this->backend);
1033 * @brief Checks if the maximum number of database processes is reached
1035 * @return bool Is the limit reached?
1037 public function isMaxProcessesReached()
1039 // Deactivated, needs more investigating if this check really makes sense
1043 * Commented out to suppress static analyzer issues
1045 if ($this->is_backend()) {
1046 $process = 'backend';
1047 $max_processes = Config::get('system', 'max_processes_backend');
1048 if (intval($max_processes) == 0) {
1052 $process = 'frontend';
1053 $max_processes = Config::get('system', 'max_processes_frontend');
1054 if (intval($max_processes) == 0) {
1055 $max_processes = 20;
1059 $processlist = DBA::processlist();
1060 if ($processlist['list'] != '') {
1061 logger('Processcheck: Processes: ' . $processlist['amount'] . ' - Processlist: ' . $processlist['list'], LOGGER_DEBUG);
1063 if ($processlist['amount'] > $max_processes) {
1064 logger('Processcheck: Maximum number of processes for ' . $process . ' tasks (' . $max_processes . ') reached.', LOGGER_DEBUG);
1073 * @brief Checks if the minimal memory is reached
1075 * @return bool Is the memory limit reached?
1077 public function min_memory_reached()
1079 $min_memory = Config::get('system', 'min_memory', 0);
1080 if ($min_memory == 0) {
1084 if (!is_readable('/proc/meminfo')) {
1088 $memdata = explode("\n", file_get_contents('/proc/meminfo'));
1091 foreach ($memdata as $line) {
1092 $data = explode(':', $line);
1093 if (count($data) != 2) {
1096 list($key, $val) = $data;
1097 $meminfo[$key] = (int) trim(str_replace('kB', '', $val));
1098 $meminfo[$key] = (int) ($meminfo[$key] / 1024);
1101 if (!isset($meminfo['MemAvailable']) || !isset($meminfo['MemFree'])) {
1105 $free = $meminfo['MemAvailable'] + $meminfo['MemFree'];
1107 $reached = ($free < $min_memory);
1110 logger('Minimal memory reached: ' . $free . '/' . $meminfo['MemTotal'] . ' - limit ' . $min_memory, LOGGER_DEBUG);
1117 * @brief Checks if the maximum load is reached
1119 * @return bool Is the load reached?
1121 public function isMaxLoadReached()
1123 if ($this->is_backend()) {
1124 $process = 'backend';
1125 $maxsysload = intval(Config::get('system', 'maxloadavg'));
1126 if ($maxsysload < 1) {
1130 $process = 'frontend';
1131 $maxsysload = intval(Config::get('system', 'maxloadavg_frontend'));
1132 if ($maxsysload < 1) {
1137 $load = current_load();
1139 if (intval($load) > $maxsysload) {
1140 logger('system: load ' . $load . ' for ' . $process . ' tasks (' . $maxsysload . ') too high.');
1148 * Executes a child process with 'proc_open'
1150 * @param string $command The command to execute
1151 * @param array $args Arguments to pass to the command ( [ 'key' => value, 'key2' => value2, ... ]
1153 public function proc_run($command, $args)
1155 if (!function_exists('proc_open')) {
1159 $cmdline = $this->getConfigValue('config', 'php_path', 'php') . ' ' . escapeshellarg($command);
1161 foreach ($args as $key => $value) {
1162 if (!is_null($value) && is_bool($value) && !$value) {
1166 $cmdline .= ' --' . $key;
1167 if (!is_null($value) && !is_bool($value)) {
1168 $cmdline .= ' ' . $value;
1172 if ($this->min_memory_reached()) {
1176 if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
1177 $resource = proc_open('cmd /c start /b ' . $cmdline, [], $foo, $this->get_basepath());
1179 $resource = proc_open($cmdline . ' &', [], $foo, $this->get_basepath());
1181 if (!is_resource($resource)) {
1182 logger('We got no resource for command ' . $cmdline, LOGGER_DEBUG);
1185 proc_close($resource);
1189 * @brief Returns the system user that is executing the script
1191 * This mostly returns something like "www-data".
1193 * @return string system username
1195 private static function systemuser()
1197 if (!function_exists('posix_getpwuid') || !function_exists('posix_geteuid')) {
1201 $processUser = posix_getpwuid(posix_geteuid());
1202 return $processUser['name'];
1206 * @brief Checks if a given directory is usable for the system
1208 * @return boolean the directory is usable
1210 public static function directory_usable($directory, $check_writable = true)
1212 if ($directory == '') {
1213 logger('Directory is empty. This shouldn\'t happen.', LOGGER_DEBUG);
1217 if (!file_exists($directory)) {
1218 logger('Path "' . $directory . '" does not exist for user ' . self::systemuser(), LOGGER_DEBUG);
1222 if (is_file($directory)) {
1223 logger('Path "' . $directory . '" is a file for user ' . self::systemuser(), LOGGER_DEBUG);
1227 if (!is_dir($directory)) {
1228 logger('Path "' . $directory . '" is not a directory for user ' . self::systemuser(), LOGGER_DEBUG);
1232 if ($check_writable && !is_writable($directory)) {
1233 logger('Path "' . $directory . '" is not writable for user ' . self::systemuser(), LOGGER_DEBUG);
1241 * @param string $cat Config category
1242 * @param string $k Config key
1243 * @param mixed $default Default value if it isn't set
1245 public function getConfigValue($cat, $k, $default = null)
1249 if ($cat === 'config') {
1250 if (isset($this->config[$k])) {
1251 $return = $this->config[$k];
1254 if (isset($this->config[$cat][$k])) {
1255 $return = $this->config[$cat][$k];
1263 * Sets a default value in the config cache. Ignores already existing keys.
1265 * @param string $cat Config category
1266 * @param string $k Config key
1267 * @param mixed $v Default value to set
1269 private function setDefaultConfigValue($cat, $k, $v)
1271 if (!isset($this->config[$cat][$k])) {
1272 $this->setConfigValue($cat, $k, $v);
1277 * Sets a value in the config cache. Accepts raw output from the config table
1279 * @param string $cat Config category
1280 * @param string $k Config key
1281 * @param mixed $v Value to set
1283 public function setConfigValue($cat, $k, $v)
1285 // Only arrays are serialized in database, so we have to unserialize sparingly
1286 $value = is_string($v) && preg_match("|^a:[0-9]+:{.*}$|s", $v) ? unserialize($v) : $v;
1288 if ($cat === 'config') {
1289 $this->config[$k] = $value;
1291 if (!isset($this->config[$cat])) {
1292 $this->config[$cat] = [];
1295 $this->config[$cat][$k] = $value;
1300 * Deletes a value from the config cache
1302 * @param string $cat Config category
1303 * @param string $k Config key
1305 public function deleteConfigValue($cat, $k)
1307 if ($cat === 'config') {
1308 if (isset($this->config[$k])) {
1309 unset($this->config[$k]);
1312 if (isset($this->config[$cat][$k])) {
1313 unset($this->config[$cat][$k]);
1320 * Retrieves a value from the user config cache
1322 * @param int $uid User Id
1323 * @param string $cat Config category
1324 * @param string $k Config key
1325 * @param mixed $default Default value if key isn't set
1327 public function getPConfigValue($uid, $cat, $k, $default = null)
1331 if (isset($this->config[$uid][$cat][$k])) {
1332 $return = $this->config[$uid][$cat][$k];
1339 * Sets a value in the user config cache
1341 * Accepts raw output from the pconfig table
1343 * @param int $uid User Id
1344 * @param string $cat Config category
1345 * @param string $k Config key
1346 * @param mixed $v Value to set
1348 public function setPConfigValue($uid, $cat, $k, $v)
1350 // Only arrays are serialized in database, so we have to unserialize sparingly
1351 $value = is_string($v) && preg_match("|^a:[0-9]+:{.*}$|s", $v) ? unserialize($v) : $v;
1353 if (!isset($this->config[$uid]) || !is_array($this->config[$uid])) {
1354 $this->config[$uid] = [];
1357 if (!isset($this->config[$uid][$cat]) || !is_array($this->config[$uid][$cat])) {
1358 $this->config[$uid][$cat] = [];
1361 $this->config[$uid][$cat][$k] = $value;
1365 * Deletes a value from the user config cache
1367 * @param int $uid User Id
1368 * @param string $cat Config category
1369 * @param string $k Config key
1371 public function deletePConfigValue($uid, $cat, $k)
1373 if (isset($this->config[$uid][$cat][$k])) {
1374 unset($this->config[$uid][$cat][$k]);
1379 * Generates the site's default sender email address
1383 public function getSenderEmailAddress()
1385 $sender_email = Config::get('config', 'sender_email');
1386 if (empty($sender_email)) {
1387 $hostname = $this->get_hostname();
1388 if (strpos($hostname, ':')) {
1389 $hostname = substr($hostname, 0, strpos($hostname, ':'));
1392 $sender_email = 'noreply@' . $hostname;
1395 return $sender_email;
1399 * Returns the current theme name.
1403 public function getCurrentTheme()
1405 if (App\Mode::isInstall()) {
1409 //// @TODO Compute the current theme only once (this behavior has
1410 /// already been implemented, but it didn't work well -
1411 /// https://github.com/friendica/friendica/issues/5092)
1412 $this->computeCurrentTheme();
1414 return $this->current_theme;
1418 * Computes the current theme name based on the node settings, the user settings and the device type
1422 private function computeCurrentTheme()
1424 $system_theme = Config::get('system', 'theme');
1425 if (!$system_theme) {
1426 throw new Exception(L10n::t('No system theme config value set.'));
1430 $this->current_theme = $system_theme;
1432 $allowed_themes = explode(',', Config::get('system', 'allowed_themes', $system_theme));
1435 // Find the theme that belongs to the user whose stuff we are looking at
1436 if ($this->profile_uid && ($this->profile_uid != local_user())) {
1437 // Allow folks to override user themes and always use their own on their own site.
1438 // This works only if the user is on the same server
1439 $user = DBA::selectFirst('user', ['theme'], ['uid' => $this->profile_uid]);
1440 if (DBA::isResult($user) && !PConfig::get(local_user(), 'system', 'always_my_theme')) {
1441 $page_theme = $user['theme'];
1445 $user_theme = Core\Session::get('theme', $system_theme);
1447 // Specific mobile theme override
1448 if (($this->is_mobile || $this->is_tablet) && Core\Session::get('show-mobile', true)) {
1449 $system_mobile_theme = Config::get('system', 'mobile-theme');
1450 $user_mobile_theme = Core\Session::get('mobile-theme', $system_mobile_theme);
1452 // --- means same mobile theme as desktop
1453 if (!empty($user_mobile_theme) && $user_mobile_theme !== '---') {
1454 $user_theme = $user_mobile_theme;
1459 $theme_name = $page_theme;
1461 $theme_name = $user_theme;
1465 && in_array($theme_name, $allowed_themes)
1466 && (file_exists('view/theme/' . $theme_name . '/style.css')
1467 || file_exists('view/theme/' . $theme_name . '/style.php'))
1469 $this->current_theme = $theme_name;
1474 * @brief Return full URL to theme which is currently in effect.
1476 * Provide a sane default if nothing is chosen or the specified theme does not exist.
1480 public function getCurrentThemeStylesheetPath()
1482 return Core\Theme::getStylesheetPath($this->getCurrentTheme());