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\Network\HTTPException\InternalServerErrorException;
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 public $module_loaded = false;
36 public $module_class = null;
37 public $query_string = '';
51 public $error = false;
61 public $interactive = true;
63 public $addons_admin = [];
66 public $is_mobile = false;
67 public $is_tablet = false;
68 public $is_friendica_app;
69 public $performance = [];
70 public $callstack = [];
71 public $theme_info = [];
72 public $backend = true;
75 // Allow themes to control internal parameters
76 // by changing App values in theme.php
78 public $sourcename = '';
79 public $videowidth = 425;
80 public $videoheight = 350;
81 public $force_max_items = 0;
82 public $theme_events_in_profile = true;
84 public $stylesheets = [];
85 public $footerScripts = [];
88 * @var App\Mode The Mode of the Application
93 * Register a stylesheet file path to be included in the <head> tag of every page.
94 * Inclusion is done in App->initHead().
95 * The path can be absolute or relative to the Friendica installation base folder.
97 * @see App->initHead()
101 public function registerStylesheet($path)
103 $url = str_replace($this->get_basepath() . DIRECTORY_SEPARATOR, '', $path);
105 $this->stylesheets[] = trim($url, '/');
109 * Register a javascript file path to be included in the <footer> tag of every page.
110 * Inclusion is done in App->initFooter().
111 * The path can be absolute or relative to the Friendica installation base folder.
113 * @see App->initFooter()
115 * @param string $path
117 public function registerFooterScript($path)
119 $url = str_replace($this->get_basepath() . DIRECTORY_SEPARATOR, '', $path);
121 $this->footerScripts[] = trim($url, '/');
125 * @brief An array for all theme-controllable parameters
127 * Mostly unimplemented yet. Only options 'template_engine' and
133 'videoheight' => 350,
134 'force_max_items' => 0,
136 'template_engine' => 'smarty3',
140 * @brief An array of registered template engines ('name'=>'class name')
142 public $template_engines = [];
145 * @brief An array of instanced template engines ('name'=>'instance')
147 public $template_engine_instance = [];
161 private $curl_content_type;
162 private $curl_headers;
165 * @brief App constructor.
167 * @param string $basepath Path to the app base folder
169 * @throws Exception if the Basepath is not usable
171 public function __construct($basepath)
173 if (!static::directory_usable($basepath, false)) {
174 throw new Exception('Basepath ' . $basepath . ' isn\'t usable.');
177 BaseObject::setApp($this);
179 $this->basepath = rtrim($basepath, DIRECTORY_SEPARATOR);
181 $this->performance['start'] = microtime(true);
182 $this->performance['database'] = 0;
183 $this->performance['database_write'] = 0;
184 $this->performance['cache'] = 0;
185 $this->performance['cache_write'] = 0;
186 $this->performance['network'] = 0;
187 $this->performance['file'] = 0;
188 $this->performance['rendering'] = 0;
189 $this->performance['parser'] = 0;
190 $this->performance['marktime'] = 0;
191 $this->performance['markstart'] = microtime(true);
193 $this->callstack['database'] = [];
194 $this->callstack['database_write'] = [];
195 $this->callstack['cache'] = [];
196 $this->callstack['cache_write'] = [];
197 $this->callstack['network'] = [];
198 $this->callstack['file'] = [];
199 $this->callstack['rendering'] = [];
200 $this->callstack['parser'] = [];
202 $this->mode = new App\Mode($basepath);
208 // This has to be quite large to deal with embedded private photos
209 ini_set('pcre.backtrack_limit', 500000);
211 $this->scheme = 'http';
213 if ((x($_SERVER, 'HTTPS') && $_SERVER['HTTPS']) ||
214 (x($_SERVER, 'HTTP_FORWARDED') && preg_match('/proto=https/', $_SERVER['HTTP_FORWARDED'])) ||
215 (x($_SERVER, 'HTTP_X_FORWARDED_PROTO') && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') ||
216 (x($_SERVER, 'HTTP_X_FORWARDED_SSL') && $_SERVER['HTTP_X_FORWARDED_SSL'] == 'on') ||
217 (x($_SERVER, 'FRONT_END_HTTPS') && $_SERVER['FRONT_END_HTTPS'] == 'on') ||
218 (x($_SERVER, 'SERVER_PORT') && (intval($_SERVER['SERVER_PORT']) == 443)) // XXX: reasonable assumption, but isn't this hardcoding too much?
220 $this->scheme = 'https';
223 if (x($_SERVER, 'SERVER_NAME')) {
224 $this->hostname = $_SERVER['SERVER_NAME'];
226 if (x($_SERVER, 'SERVER_PORT') && $_SERVER['SERVER_PORT'] != 80 && $_SERVER['SERVER_PORT'] != 443) {
227 $this->hostname .= ':' . $_SERVER['SERVER_PORT'];
232 get_include_path() . PATH_SEPARATOR
233 . $this->basepath . DIRECTORY_SEPARATOR . 'include' . PATH_SEPARATOR
234 . $this->basepath . DIRECTORY_SEPARATOR . 'library' . PATH_SEPARATOR
237 if ((x($_SERVER, 'QUERY_STRING')) && substr($_SERVER['QUERY_STRING'], 0, 9) === 'pagename=') {
238 $this->query_string = substr($_SERVER['QUERY_STRING'], 9);
239 } elseif ((x($_SERVER, 'QUERY_STRING')) && substr($_SERVER['QUERY_STRING'], 0, 2) === 'q=') {
240 $this->query_string = substr($_SERVER['QUERY_STRING'], 2);
243 // removing trailing / - maybe a nginx problem
244 $this->query_string = ltrim($this->query_string, '/');
246 if (!empty($_GET['pagename'])) {
247 $this->cmd = trim($_GET['pagename'], '/\\');
248 } elseif (!empty($_GET['q'])) {
249 $this->cmd = trim($_GET['q'], '/\\');
253 $this->query_string = str_replace($this->cmd . '&', $this->cmd . '?', $this->query_string);
255 // unix style "homedir"
256 if (substr($this->cmd, 0, 1) === '~') {
257 $this->cmd = 'profile/' . substr($this->cmd, 1);
260 // Diaspora style profile url
261 if (substr($this->cmd, 0, 2) === 'u/') {
262 $this->cmd = 'profile/' . substr($this->cmd, 2);
266 * Break the URL path into C style argc/argv style arguments for our
267 * modules. Given "http://example.com/module/arg1/arg2", $this->argc
268 * will be 3 (integer) and $this->argv will contain:
274 * There will always be one argument. If provided a naked domain
275 * URL, $this->argv[0] is set to "home".
278 $this->argv = explode('/', $this->cmd);
279 $this->argc = count($this->argv);
280 if ((array_key_exists('0', $this->argv)) && strlen($this->argv[0])) {
281 $this->module = str_replace('.', '_', $this->argv[0]);
282 $this->module = str_replace('-', '_', $this->module);
285 $this->argv = ['home'];
286 $this->module = 'home';
289 // See if there is any page number information, and initialise pagination
290 $this->pager['page'] = ((x($_GET, 'page') && intval($_GET['page']) > 0) ? intval($_GET['page']) : 1);
291 $this->pager['itemspage'] = 50;
292 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
294 if ($this->pager['start'] < 0) {
295 $this->pager['start'] = 0;
297 $this->pager['total'] = 0;
299 // Detect mobile devices
300 $mobile_detect = new MobileDetect();
301 $this->is_mobile = $mobile_detect->isMobile();
302 $this->is_tablet = $mobile_detect->isTablet();
305 $this->is_friendica_app = isset($_SERVER['HTTP_USER_AGENT']) && $_SERVER['HTTP_USER_AGENT'] == 'Apache-HttpClient/UNAVAILABLE (java 1.4)';
307 // Register template engines
308 $this->register_template_engine('Friendica\Render\FriendicaSmartyEngine');
312 * Returns the Mode of the Application
314 * @return App\Mode The Application Mode
316 * @throws InternalServerErrorException when the mode isn't created
318 public function getMode()
320 if (empty($this->mode)) {
321 throw new InternalServerErrorException('Mode of the Application is not defined');
328 * Reloads the whole app instance
330 public function reload()
332 // The order of the following calls is important to ensure proper initialization
333 $this->loadConfigFiles();
335 $this->loadDatabase();
337 $this->getMode()->determine($this->basepath);
339 $this->determineUrlPath();
343 if ($this->getMode()->has(App\Mode::DBAVAILABLE)) {
344 Core\Addon::loadHooks();
346 $this->loadAddonConfig();
349 $this->loadDefaultTimezone();
364 $this->process_id = System::processID('log');
368 * Load the configuration files
370 * First loads the default value for all the configuration keys, then the legacy configuration files, then the
371 * expected local.ini.php
373 private function loadConfigFiles()
375 $this->loadConfigFile($this->basepath . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'config.ini.php');
376 $this->loadConfigFile($this->basepath . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'settings.ini.php');
378 // Legacy .htconfig.php support
379 if (file_exists($this->basepath . DIRECTORY_SEPARATOR . '.htpreconfig.php')) {
381 include $this->basepath . DIRECTORY_SEPARATOR . '.htpreconfig.php';
384 // Legacy .htconfig.php support
385 if (file_exists($this->basepath . DIRECTORY_SEPARATOR . '.htconfig.php')) {
388 include $this->basepath . DIRECTORY_SEPARATOR . '.htconfig.php';
390 $this->setConfigValue('database', 'hostname', $db_host);
391 $this->setConfigValue('database', 'username', $db_user);
392 $this->setConfigValue('database', 'password', $db_pass);
393 $this->setConfigValue('database', 'database', $db_data);
394 if (isset($a->config['system']['db_charset'])) {
395 $this->setConfigValue('database', 'charset', $a->config['system']['db_charset']);
398 unset($db_host, $db_user, $db_pass, $db_data);
400 if (isset($default_timezone)) {
401 $this->setConfigValue('system', 'default_timezone', $default_timezone);
402 unset($default_timezone);
405 if (isset($pidfile)) {
406 $this->setConfigValue('system', 'pidfile', $pidfile);
411 $this->setConfigValue('system', 'language', $lang);
416 if (file_exists($this->basepath . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'local.ini.php')) {
417 $this->loadConfigFile($this->basepath . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'local.ini.php', true);
422 * Tries to load the specified configuration file into the App->config array.
423 * Doesn't overwrite previously set values by default to prevent default config files to supersede DB Config.
425 * The config format is INI and the template for configuration files is the following:
427 * <?php return <<<INI
435 * @param type $filepath
436 * @param bool $overwrite Force value overwrite if the config key already exists
439 public function loadConfigFile($filepath, $overwrite = false)
441 if (!file_exists($filepath)) {
442 throw new Exception('Error parsing non-existent config file ' . $filepath);
445 $contents = include($filepath);
447 $config = parse_ini_string($contents, true, INI_SCANNER_TYPED);
449 if ($config === false) {
450 throw new Exception('Error parsing config file ' . $filepath);
453 foreach ($config as $category => $values) {
454 foreach ($values as $key => $value) {
456 $this->setConfigValue($category, $key, $value);
458 $this->setDefaultConfigValue($category, $key, $value);
465 * Loads addons configuration files
467 * First loads all activated addons default configuration throught the load_config hook, then load the local.ini.php
468 * again to overwrite potential local addon configuration.
470 private function loadAddonConfig()
472 // Loads addons default config
473 Core\Addon::callHooks('load_config');
475 // Load the local addon config file to overwritten default addon config values
476 if (file_exists($this->basepath . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'addon.ini.php')) {
477 $this->loadConfigFile($this->basepath . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'addon.ini.php', true);
482 * Loads the default timezone
484 * Include support for legacy $default_timezone
486 * @global string $default_timezone
488 private function loadDefaultTimezone()
490 if ($this->getConfigValue('system', 'default_timezone')) {
491 $this->timezone = $this->getConfigValue('system', 'default_timezone');
493 global $default_timezone;
494 $this->timezone = !empty($default_timezone) ? $default_timezone : 'UTC';
497 if ($this->timezone) {
498 date_default_timezone_set($this->timezone);
503 * Figure out if we are running at the top of a domain or in a sub-directory and adjust accordingly
505 private function determineUrlPath()
507 $this->urlpath = $this->getConfigValue('system', 'urlpath');
509 /* SCRIPT_URL gives /path/to/friendica/module/parameter
510 * QUERY_STRING gives pagename=module/parameter
512 * To get /path/to/friendica we perform dirname() for as many levels as there are slashes in the QUERY_STRING
514 if (!empty($_SERVER['SCRIPT_URL'])) {
516 if (!empty($_SERVER['QUERY_STRING'])) {
517 $path = trim(dirname($_SERVER['SCRIPT_URL'], substr_count(trim($_SERVER['QUERY_STRING'], '/'), '/') + 1), '/');
520 $path = trim($_SERVER['SCRIPT_URL'], '/');
523 if ($path && $path != $this->urlpath) {
524 $this->urlpath = $path;
529 public function loadDatabase()
531 if (DBA::connected()) {
535 $db_host = $this->getConfigValue('database', 'hostname');
536 $db_user = $this->getConfigValue('database', 'username');
537 $db_pass = $this->getConfigValue('database', 'password');
538 $db_data = $this->getConfigValue('database', 'database');
539 $charset = $this->getConfigValue('database', 'charset');
541 // Use environment variables for mysql if they are set beforehand
542 if (!empty(getenv('MYSQL_HOST'))
543 && (!empty(getenv('MYSQL_USERNAME')) || !empty(getenv('MYSQL_USER')))
544 && getenv('MYSQL_PASSWORD') !== false
545 && !empty(getenv('MYSQL_DATABASE')))
547 $db_host = getenv('MYSQL_HOST');
548 if (!empty(getenv('MYSQL_PORT'))) {
549 $db_host .= ':' . getenv('MYSQL_PORT');
551 if (!empty(getenv('MYSQL_USERNAME'))) {
552 $db_user = getenv('MYSQL_USERNAME');
554 $db_user = getenv('MYSQL_USER');
556 $db_pass = (string) getenv('MYSQL_PASSWORD');
557 $db_data = getenv('MYSQL_DATABASE');
560 $stamp1 = microtime(true);
562 DBA::connect($db_host, $db_user, $db_pass, $db_data, $charset);
563 unset($db_host, $db_user, $db_pass, $db_data, $charset);
565 $this->save_timestamp($stamp1, 'network');
569 * @brief Returns the base filesystem path of the App
571 * It first checks for the internal variable, then for DOCUMENT_ROOT and
576 public function get_basepath()
578 $basepath = $this->basepath;
581 $basepath = Config::get('system', 'basepath');
584 if (!$basepath && x($_SERVER, 'DOCUMENT_ROOT')) {
585 $basepath = $_SERVER['DOCUMENT_ROOT'];
588 if (!$basepath && x($_SERVER, 'PWD')) {
589 $basepath = $_SERVER['PWD'];
592 return self::realpath($basepath);
596 * @brief Returns a normalized file path
598 * This is a wrapper for the "realpath" function.
599 * That function cannot detect the real path when some folders aren't readable.
600 * Since this could happen with some hosters we need to handle this.
602 * @param string $path The path that is about to be normalized
603 * @return string normalized path - when possible
605 public static function realpath($path)
607 $normalized = realpath($path);
609 if (!is_bool($normalized)) {
616 public function get_scheme()
618 return $this->scheme;
622 * @brief Retrieves the Friendica instance base URL
624 * This function assembles the base URL from multiple parts:
625 * - Protocol is determined either by the request or a combination of
626 * system.ssl_policy and the $ssl parameter.
627 * - Host name is determined either by system.hostname or inferred from request
628 * - Path is inferred from SCRIPT_NAME
630 * Note: $ssl parameter value doesn't directly correlate with the resulting protocol
632 * @param bool $ssl Whether to append http or https under SSL_POLICY_SELFSIGN
633 * @return string Friendica server base URL
635 public function get_baseurl($ssl = false)
637 $scheme = $this->scheme;
639 if (Config::get('system', 'ssl_policy') == SSL_POLICY_FULL) {
643 // Basically, we have $ssl = true on any links which can only be seen by a logged in user
644 // (and also the login link). Anything seen by an outsider will have it turned off.
646 if (Config::get('system', 'ssl_policy') == SSL_POLICY_SELFSIGN) {
654 if (Config::get('config', 'hostname') != '') {
655 $this->hostname = Config::get('config', 'hostname');
658 return $scheme . '://' . $this->hostname . (!empty($this->urlpath) ? '/' . $this->urlpath : '' );
662 * @brief Initializes the baseurl components
664 * Clears the baseurl cache to prevent inconsistencies
668 public function set_baseurl($url)
670 $parsed = @parse_url($url);
674 if (!empty($parsed['scheme'])) {
675 $this->scheme = $parsed['scheme'];
678 if (!empty($parsed['host'])) {
679 $hostname = $parsed['host'];
682 if (x($parsed, 'port')) {
683 $hostname .= ':' . $parsed['port'];
685 if (x($parsed, 'path')) {
686 $this->urlpath = trim($parsed['path'], '\\/');
689 if (file_exists($this->basepath . DIRECTORY_SEPARATOR . '.htpreconfig.php')) {
690 include $this->basepath . DIRECTORY_SEPARATOR . '.htpreconfig.php';
693 if (Config::get('config', 'hostname') != '') {
694 $this->hostname = Config::get('config', 'hostname');
697 if (!isset($this->hostname) || ($this->hostname == '')) {
698 $this->hostname = $hostname;
703 public function get_hostname()
705 if (Config::get('config', 'hostname') != '') {
706 $this->hostname = Config::get('config', 'hostname');
709 return $this->hostname;
712 public function get_path()
714 return $this->urlpath;
717 public function set_pager_total($n)
719 $this->pager['total'] = intval($n);
722 public function set_pager_itemspage($n)
724 $this->pager['itemspage'] = ((intval($n) > 0) ? intval($n) : 0);
725 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
728 public function set_pager_page($n)
730 $this->pager['page'] = $n;
731 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
735 * Initializes App->page['htmlhead'].
740 * - Registered stylesheets (through App->registerStylesheet())
741 * - Infinite scroll data
742 * - head.tpl template
744 public function initHead()
746 $interval = ((local_user()) ? PConfig::get(local_user(), 'system', 'update_interval') : 40000);
748 // If the update is 'deactivated' set it to the highest integer number (~24 days)
750 $interval = 2147483647;
753 if ($interval < 10000) {
757 // compose the page title from the sitename and the
758 // current module called
759 if (!$this->module == '') {
760 $this->page['title'] = $this->config['sitename'] . ' (' . $this->module . ')';
762 $this->page['title'] = $this->config['sitename'];
765 if (!empty($this->theme['stylesheet'])) {
766 $stylesheet = $this->theme['stylesheet'];
768 $stylesheet = $this->getCurrentThemeStylesheetPath();
771 $this->registerStylesheet($stylesheet);
773 $shortcut_icon = Config::get('system', 'shortcut_icon');
774 if ($shortcut_icon == '') {
775 $shortcut_icon = 'images/friendica-32.png';
778 $touch_icon = Config::get('system', 'touch_icon');
779 if ($touch_icon == '') {
780 $touch_icon = 'images/friendica-128.png';
783 // get data wich is needed for infinite scroll on the network page
784 $infinite_scroll = infinite_scroll_data($this->module);
786 Core\Addon::callHooks('head', $this->page['htmlhead']);
788 $tpl = get_markup_template('head.tpl');
789 /* put the head template at the beginning of page['htmlhead']
790 * since the code added by the modules frequently depends on it
793 $this->page['htmlhead'] = replace_macros($tpl, [
794 '$baseurl' => $this->get_baseurl(),
795 '$local_user' => local_user(),
796 '$generator' => 'Friendica' . ' ' . FRIENDICA_VERSION,
797 '$delitem' => L10n::t('Delete this item?'),
798 '$showmore' => L10n::t('show more'),
799 '$showfewer' => L10n::t('show fewer'),
800 '$update_interval' => $interval,
801 '$shortcut_icon' => $shortcut_icon,
802 '$touch_icon' => $touch_icon,
803 '$infinite_scroll' => $infinite_scroll,
804 '$block_public' => intval(Config::get('system', 'block_public')),
805 '$stylesheets' => $this->stylesheets,
806 ]) . $this->page['htmlhead'];
810 * Initializes App->page['footer'].
813 * - Javascript homebase
814 * - Mobile toggle link
815 * - Registered footer scripts (through App->registerFooterScript())
816 * - footer.tpl template
818 public function initFooter()
820 // If you're just visiting, let javascript take you home
821 if (!empty($_SESSION['visitor_home'])) {
822 $homebase = $_SESSION['visitor_home'];
823 } elseif (local_user()) {
824 $homebase = 'profile/' . $this->user['nickname'];
827 if (isset($homebase)) {
828 $this->page['footer'] .= '<script>var homebase="' . $homebase . '";</script>' . "\n";
832 * Add a "toggle mobile" link if we're using a mobile device
834 if ($this->is_mobile || $this->is_tablet) {
835 if (isset($_SESSION['show-mobile']) && !$_SESSION['show-mobile']) {
836 $link = 'toggle_mobile?address=' . curPageURL();
838 $link = 'toggle_mobile?off=1&address=' . curPageURL();
840 $this->page['footer'] .= replace_macros(get_markup_template("toggle_mobile_footer.tpl"), [
841 '$toggle_link' => $link,
842 '$toggle_text' => Core\L10n::t('toggle mobile')
846 Core\Addon::callHooks('footer', $this->page['footer']);
848 $tpl = get_markup_template('footer.tpl');
849 $this->page['footer'] = replace_macros($tpl, [
850 '$baseurl' => $this->get_baseurl(),
851 '$footerScripts' => $this->footerScripts,
852 ]) . $this->page['footer'];
855 public function set_curl_code($code)
857 $this->curl_code = $code;
860 public function get_curl_code()
862 return $this->curl_code;
865 public function set_curl_content_type($content_type)
867 $this->curl_content_type = $content_type;
870 public function get_curl_content_type()
872 return $this->curl_content_type;
875 public function set_curl_headers($headers)
877 $this->curl_headers = $headers;
880 public function get_curl_headers()
882 return $this->curl_headers;
886 * @brief Removes the base url from an url. This avoids some mixed content problems.
888 * @param string $orig_url
890 * @return string The cleaned url
892 public function remove_baseurl($orig_url)
894 // Remove the hostname from the url if it is an internal link
895 $nurl = normalise_link($orig_url);
896 $base = normalise_link($this->get_baseurl());
897 $url = str_replace($base . '/', '', $nurl);
899 // if it is an external link return the orignal value
900 if ($url == normalise_link($orig_url)) {
908 * @brief Register template engine class
910 * @param string $class
912 private function register_template_engine($class)
914 $v = get_class_vars($class);
917 $this->template_engines[$name] = $class;
919 echo "template engine <tt>$class</tt> cannot be registered without a name.\n";
925 * @brief Return template engine instance.
927 * If $name is not defined, return engine defined by theme,
930 * @return object Template Engine instance
932 public function template_engine()
934 $template_engine = 'smarty3';
935 if (x($this->theme, 'template_engine')) {
936 $template_engine = $this->theme['template_engine'];
939 if (isset($this->template_engines[$template_engine])) {
940 if (isset($this->template_engine_instance[$template_engine])) {
941 return $this->template_engine_instance[$template_engine];
943 $class = $this->template_engines[$template_engine];
945 $this->template_engine_instance[$template_engine] = $obj;
950 echo "template engine <tt>$template_engine</tt> is not registered!\n";
955 * @brief Returns the active template engine.
959 public function get_template_engine()
961 return $this->theme['template_engine'];
964 public function set_template_engine($engine = 'smarty3')
966 $this->theme['template_engine'] = $engine;
969 public function get_template_ldelim($engine = 'smarty3')
971 return $this->ldelim[$engine];
974 public function get_template_rdelim($engine = 'smarty3')
976 return $this->rdelim[$engine];
979 public function save_timestamp($stamp, $value)
981 if (!isset($this->config['system']['profiler']) || !$this->config['system']['profiler']) {
985 $duration = (float) (microtime(true) - $stamp);
987 if (!isset($this->performance[$value])) {
988 // Prevent ugly E_NOTICE
989 $this->performance[$value] = 0;
992 $this->performance[$value] += (float) $duration;
993 $this->performance['marktime'] += (float) $duration;
995 $callstack = System::callstack();
997 if (!isset($this->callstack[$value][$callstack])) {
998 // Prevent ugly E_NOTICE
999 $this->callstack[$value][$callstack] = 0;
1002 $this->callstack[$value][$callstack] += (float) $duration;
1005 public function get_useragent()
1008 FRIENDICA_PLATFORM . " '" .
1009 FRIENDICA_CODENAME . "' " .
1010 FRIENDICA_VERSION . '-' .
1011 DB_UPDATE_VERSION . '; ' .
1012 $this->get_baseurl();
1015 public function is_friendica_app()
1017 return $this->is_friendica_app;
1021 * @brief Checks if the site is called via a backend process
1023 * This isn't a perfect solution. But we need this check very early.
1024 * So we cannot wait until the modules are loaded.
1026 * @return bool Is it a known backend?
1028 public function is_backend()
1030 static $backends = [
1052 // Check if current module is in backend or backend flag is set
1053 return (in_array($this->module, $backends) || $this->backend);
1057 * @brief Checks if the maximum number of database processes is reached
1059 * @return bool Is the limit reached?
1061 public function isMaxProcessesReached()
1063 // Deactivated, needs more investigating if this check really makes sense
1067 * Commented out to suppress static analyzer issues
1069 if ($this->is_backend()) {
1070 $process = 'backend';
1071 $max_processes = Config::get('system', 'max_processes_backend');
1072 if (intval($max_processes) == 0) {
1076 $process = 'frontend';
1077 $max_processes = Config::get('system', 'max_processes_frontend');
1078 if (intval($max_processes) == 0) {
1079 $max_processes = 20;
1083 $processlist = DBA::processlist();
1084 if ($processlist['list'] != '') {
1085 logger('Processcheck: Processes: ' . $processlist['amount'] . ' - Processlist: ' . $processlist['list'], LOGGER_DEBUG);
1087 if ($processlist['amount'] > $max_processes) {
1088 logger('Processcheck: Maximum number of processes for ' . $process . ' tasks (' . $max_processes . ') reached.', LOGGER_DEBUG);
1097 * @brief Checks if the minimal memory is reached
1099 * @return bool Is the memory limit reached?
1101 public function min_memory_reached()
1103 $min_memory = Config::get('system', 'min_memory', 0);
1104 if ($min_memory == 0) {
1108 if (!is_readable('/proc/meminfo')) {
1112 $memdata = explode("\n", file_get_contents('/proc/meminfo'));
1115 foreach ($memdata as $line) {
1116 $data = explode(':', $line);
1117 if (count($data) != 2) {
1120 list($key, $val) = $data;
1121 $meminfo[$key] = (int) trim(str_replace('kB', '', $val));
1122 $meminfo[$key] = (int) ($meminfo[$key] / 1024);
1125 if (!isset($meminfo['MemAvailable']) || !isset($meminfo['MemFree'])) {
1129 $free = $meminfo['MemAvailable'] + $meminfo['MemFree'];
1131 $reached = ($free < $min_memory);
1134 logger('Minimal memory reached: ' . $free . '/' . $meminfo['MemTotal'] . ' - limit ' . $min_memory, LOGGER_DEBUG);
1141 * @brief Checks if the maximum load is reached
1143 * @return bool Is the load reached?
1145 public function isMaxLoadReached()
1147 if ($this->is_backend()) {
1148 $process = 'backend';
1149 $maxsysload = intval(Config::get('system', 'maxloadavg'));
1150 if ($maxsysload < 1) {
1154 $process = 'frontend';
1155 $maxsysload = intval(Config::get('system', 'maxloadavg_frontend'));
1156 if ($maxsysload < 1) {
1161 $load = current_load();
1163 if (intval($load) > $maxsysload) {
1164 logger('system: load ' . $load . ' for ' . $process . ' tasks (' . $maxsysload . ') too high.');
1172 * Executes a child process with 'proc_open'
1174 * @param string $command The command to execute
1175 * @param array $args Arguments to pass to the command ( [ 'key' => value, 'key2' => value2, ... ]
1177 public function proc_run($command, $args)
1179 if (!function_exists('proc_open')) {
1183 $cmdline = $this->getConfigValue('config', 'php_path', 'php') . ' ' . escapeshellarg($command);
1185 foreach ($args as $key => $value) {
1186 if (!is_null($value) && is_bool($value) && !$value) {
1190 $cmdline .= ' --' . $key;
1191 if (!is_null($value) && !is_bool($value)) {
1192 $cmdline .= ' ' . $value;
1196 if ($this->min_memory_reached()) {
1200 if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
1201 $resource = proc_open('cmd /c start /b ' . $cmdline, [], $foo, $this->get_basepath());
1203 $resource = proc_open($cmdline . ' &', [], $foo, $this->get_basepath());
1205 if (!is_resource($resource)) {
1206 logger('We got no resource for command ' . $cmdline, LOGGER_DEBUG);
1209 proc_close($resource);
1213 * @brief Returns the system user that is executing the script
1215 * This mostly returns something like "www-data".
1217 * @return string system username
1219 private static function systemuser()
1221 if (!function_exists('posix_getpwuid') || !function_exists('posix_geteuid')) {
1225 $processUser = posix_getpwuid(posix_geteuid());
1226 return $processUser['name'];
1230 * @brief Checks if a given directory is usable for the system
1232 * @return boolean the directory is usable
1234 public static function directory_usable($directory, $check_writable = true)
1236 if ($directory == '') {
1237 logger('Directory is empty. This shouldn\'t happen.', LOGGER_DEBUG);
1241 if (!file_exists($directory)) {
1242 logger('Path "' . $directory . '" does not exist for user ' . self::systemuser(), LOGGER_DEBUG);
1246 if (is_file($directory)) {
1247 logger('Path "' . $directory . '" is a file for user ' . self::systemuser(), LOGGER_DEBUG);
1251 if (!is_dir($directory)) {
1252 logger('Path "' . $directory . '" is not a directory for user ' . self::systemuser(), LOGGER_DEBUG);
1256 if ($check_writable && !is_writable($directory)) {
1257 logger('Path "' . $directory . '" is not writable for user ' . self::systemuser(), LOGGER_DEBUG);
1265 * @param string $cat Config category
1266 * @param string $k Config key
1267 * @param mixed $default Default value if it isn't set
1269 public function getConfigValue($cat, $k, $default = null)
1273 if ($cat === 'config') {
1274 if (isset($this->config[$k])) {
1275 $return = $this->config[$k];
1278 if (isset($this->config[$cat][$k])) {
1279 $return = $this->config[$cat][$k];
1287 * Sets a default value in the config cache. Ignores already existing keys.
1289 * @param string $cat Config category
1290 * @param string $k Config key
1291 * @param mixed $v Default value to set
1293 private function setDefaultConfigValue($cat, $k, $v)
1295 if (!isset($this->config[$cat][$k])) {
1296 $this->setConfigValue($cat, $k, $v);
1301 * Sets a value in the config cache. Accepts raw output from the config table
1303 * @param string $cat Config category
1304 * @param string $k Config key
1305 * @param mixed $v Value to set
1307 public function setConfigValue($cat, $k, $v)
1309 // Only arrays are serialized in database, so we have to unserialize sparingly
1310 $value = is_string($v) && preg_match("|^a:[0-9]+:{.*}$|s", $v) ? unserialize($v) : $v;
1312 if ($cat === 'config') {
1313 $this->config[$k] = $value;
1315 if (!isset($this->config[$cat])) {
1316 $this->config[$cat] = [];
1319 $this->config[$cat][$k] = $value;
1324 * Deletes a value from the config cache
1326 * @param string $cat Config category
1327 * @param string $k Config key
1329 public function deleteConfigValue($cat, $k)
1331 if ($cat === 'config') {
1332 if (isset($this->config[$k])) {
1333 unset($this->config[$k]);
1336 if (isset($this->config[$cat][$k])) {
1337 unset($this->config[$cat][$k]);
1344 * Retrieves a value from the user config cache
1346 * @param int $uid User Id
1347 * @param string $cat Config category
1348 * @param string $k Config key
1349 * @param mixed $default Default value if key isn't set
1351 public function getPConfigValue($uid, $cat, $k, $default = null)
1355 if (isset($this->config[$uid][$cat][$k])) {
1356 $return = $this->config[$uid][$cat][$k];
1363 * Sets a value in the user config cache
1365 * Accepts raw output from the pconfig table
1367 * @param int $uid User Id
1368 * @param string $cat Config category
1369 * @param string $k Config key
1370 * @param mixed $v Value to set
1372 public function setPConfigValue($uid, $cat, $k, $v)
1374 // Only arrays are serialized in database, so we have to unserialize sparingly
1375 $value = is_string($v) && preg_match("|^a:[0-9]+:{.*}$|s", $v) ? unserialize($v) : $v;
1377 if (!isset($this->config[$uid]) || !is_array($this->config[$uid])) {
1378 $this->config[$uid] = [];
1381 if (!isset($this->config[$uid][$cat]) || !is_array($this->config[$uid][$cat])) {
1382 $this->config[$uid][$cat] = [];
1385 $this->config[$uid][$cat][$k] = $value;
1389 * Deletes a value from the user config cache
1391 * @param int $uid User Id
1392 * @param string $cat Config category
1393 * @param string $k Config key
1395 public function deletePConfigValue($uid, $cat, $k)
1397 if (isset($this->config[$uid][$cat][$k])) {
1398 unset($this->config[$uid][$cat][$k]);
1403 * Generates the site's default sender email address
1407 public function getSenderEmailAddress()
1409 $sender_email = Config::get('config', 'sender_email');
1410 if (empty($sender_email)) {
1411 $hostname = $this->get_hostname();
1412 if (strpos($hostname, ':')) {
1413 $hostname = substr($hostname, 0, strpos($hostname, ':'));
1416 $sender_email = 'noreply@' . $hostname;
1419 return $sender_email;
1423 * Returns the current theme name.
1427 public function getCurrentTheme()
1429 if ($this->getMode()->isInstall()) {
1433 //// @TODO Compute the current theme only once (this behavior has
1434 /// already been implemented, but it didn't work well -
1435 /// https://github.com/friendica/friendica/issues/5092)
1436 $this->computeCurrentTheme();
1438 return $this->current_theme;
1442 * Computes the current theme name based on the node settings, the user settings and the device type
1446 private function computeCurrentTheme()
1448 $system_theme = Config::get('system', 'theme');
1449 if (!$system_theme) {
1450 throw new Exception(L10n::t('No system theme config value set.'));
1454 $this->current_theme = $system_theme;
1456 $allowed_themes = explode(',', Config::get('system', 'allowed_themes', $system_theme));
1459 // Find the theme that belongs to the user whose stuff we are looking at
1460 if ($this->profile_uid && ($this->profile_uid != local_user())) {
1461 // Allow folks to override user themes and always use their own on their own site.
1462 // This works only if the user is on the same server
1463 $user = DBA::selectFirst('user', ['theme'], ['uid' => $this->profile_uid]);
1464 if (DBA::isResult($user) && !PConfig::get(local_user(), 'system', 'always_my_theme')) {
1465 $page_theme = $user['theme'];
1469 $user_theme = Core\Session::get('theme', $system_theme);
1471 // Specific mobile theme override
1472 if (($this->is_mobile || $this->is_tablet) && Core\Session::get('show-mobile', true)) {
1473 $system_mobile_theme = Config::get('system', 'mobile-theme');
1474 $user_mobile_theme = Core\Session::get('mobile-theme', $system_mobile_theme);
1476 // --- means same mobile theme as desktop
1477 if (!empty($user_mobile_theme) && $user_mobile_theme !== '---') {
1478 $user_theme = $user_mobile_theme;
1483 $theme_name = $page_theme;
1485 $theme_name = $user_theme;
1489 && in_array($theme_name, $allowed_themes)
1490 && (file_exists('view/theme/' . $theme_name . '/style.css')
1491 || file_exists('view/theme/' . $theme_name . '/style.php'))
1493 $this->current_theme = $theme_name;
1498 * @brief Return full URL to theme which is currently in effect.
1500 * Provide a sane default if nothing is chosen or the specified theme does not exist.
1504 public function getCurrentThemeStylesheetPath()
1506 return Core\Theme::getStylesheetPath($this->getCurrentTheme());