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;
99 public $stylesheets = [];
100 public $footerScripts = [];
102 public function registerStylesheet($path)
104 $url = str_replace($this->get_basepath() . DIRECTORY_SEPARATOR, '', $path);
106 $this->stylesheets[] = trim($url, '/');
109 public function registerFooterScript($path)
111 $url = str_replace($this->get_basepath() . DIRECTORY_SEPARATOR, '', $path);
113 $this->footerScripts[] = trim($url, '/');
117 * @brief An array for all theme-controllable parameters
119 * Mostly unimplemented yet. Only options 'template_engine' and
125 'videoheight' => 350,
126 'force_max_items' => 0,
128 'template_engine' => 'smarty3',
132 * @brief An array of registered template engines ('name'=>'class name')
134 public $template_engines = [];
137 * @brief An array of instanced template engines ('name'=>'instance')
139 public $template_engine_instance = [];
153 private $curl_content_type;
154 private $curl_headers;
157 * @brief App constructor.
159 * @param string $basepath Path to the app base folder
161 * @throws Exception if the Basepath is not usable
163 public function __construct($basepath)
165 if (!static::directory_usable($basepath, false)) {
166 throw new Exception('Basepath ' . $basepath . ' isn\'t usable.');
169 BaseObject::setApp($this);
171 $this->basepath = rtrim($basepath, DIRECTORY_SEPARATOR);
173 $this->performance['start'] = microtime(true);
174 $this->performance['database'] = 0;
175 $this->performance['database_write'] = 0;
176 $this->performance['cache'] = 0;
177 $this->performance['cache_write'] = 0;
178 $this->performance['network'] = 0;
179 $this->performance['file'] = 0;
180 $this->performance['rendering'] = 0;
181 $this->performance['parser'] = 0;
182 $this->performance['marktime'] = 0;
183 $this->performance['markstart'] = microtime(true);
185 $this->callstack['database'] = [];
186 $this->callstack['database_write'] = [];
187 $this->callstack['cache'] = [];
188 $this->callstack['cache_write'] = [];
189 $this->callstack['network'] = [];
190 $this->callstack['file'] = [];
191 $this->callstack['rendering'] = [];
192 $this->callstack['parser'] = [];
198 // This has to be quite large to deal with embedded private photos
199 ini_set('pcre.backtrack_limit', 500000);
201 $this->scheme = 'http';
203 if ((x($_SERVER, 'HTTPS') && $_SERVER['HTTPS']) ||
204 (x($_SERVER, 'HTTP_FORWARDED') && preg_match('/proto=https/', $_SERVER['HTTP_FORWARDED'])) ||
205 (x($_SERVER, 'HTTP_X_FORWARDED_PROTO') && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') ||
206 (x($_SERVER, 'HTTP_X_FORWARDED_SSL') && $_SERVER['HTTP_X_FORWARDED_SSL'] == 'on') ||
207 (x($_SERVER, 'FRONT_END_HTTPS') && $_SERVER['FRONT_END_HTTPS'] == 'on') ||
208 (x($_SERVER, 'SERVER_PORT') && (intval($_SERVER['SERVER_PORT']) == 443)) // XXX: reasonable assumption, but isn't this hardcoding too much?
210 $this->scheme = 'https';
213 if (x($_SERVER, 'SERVER_NAME')) {
214 $this->hostname = $_SERVER['SERVER_NAME'];
216 if (x($_SERVER, 'SERVER_PORT') && $_SERVER['SERVER_PORT'] != 80 && $_SERVER['SERVER_PORT'] != 443) {
217 $this->hostname .= ':' . $_SERVER['SERVER_PORT'];
222 get_include_path() . PATH_SEPARATOR
223 . $this->basepath . DIRECTORY_SEPARATOR . 'include' . PATH_SEPARATOR
224 . $this->basepath . DIRECTORY_SEPARATOR . 'library' . PATH_SEPARATOR
227 if ((x($_SERVER, 'QUERY_STRING')) && substr($_SERVER['QUERY_STRING'], 0, 9) === 'pagename=') {
228 $this->query_string = substr($_SERVER['QUERY_STRING'], 9);
229 } elseif ((x($_SERVER, 'QUERY_STRING')) && substr($_SERVER['QUERY_STRING'], 0, 2) === 'q=') {
230 $this->query_string = substr($_SERVER['QUERY_STRING'], 2);
233 // removing trailing / - maybe a nginx problem
234 $this->query_string = ltrim($this->query_string, '/');
236 if (!empty($_GET['pagename'])) {
237 $this->cmd = trim($_GET['pagename'], '/\\');
238 } elseif (!empty($_GET['q'])) {
239 $this->cmd = trim($_GET['q'], '/\\');
243 $this->query_string = str_replace($this->cmd . '&', $this->cmd . '?', $this->query_string);
245 // unix style "homedir"
246 if (substr($this->cmd, 0, 1) === '~') {
247 $this->cmd = 'profile/' . substr($this->cmd, 1);
250 // Diaspora style profile url
251 if (substr($this->cmd, 0, 2) === 'u/') {
252 $this->cmd = 'profile/' . substr($this->cmd, 2);
256 * Break the URL path into C style argc/argv style arguments for our
257 * modules. Given "http://example.com/module/arg1/arg2", $this->argc
258 * will be 3 (integer) and $this->argv will contain:
264 * There will always be one argument. If provided a naked domain
265 * URL, $this->argv[0] is set to "home".
268 $this->argv = explode('/', $this->cmd);
269 $this->argc = count($this->argv);
270 if ((array_key_exists('0', $this->argv)) && strlen($this->argv[0])) {
271 $this->module = str_replace('.', '_', $this->argv[0]);
272 $this->module = str_replace('-', '_', $this->module);
275 $this->argv = ['home'];
276 $this->module = 'home';
279 // See if there is any page number information, and initialise pagination
280 $this->pager['page'] = ((x($_GET, 'page') && intval($_GET['page']) > 0) ? intval($_GET['page']) : 1);
281 $this->pager['itemspage'] = 50;
282 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
284 if ($this->pager['start'] < 0) {
285 $this->pager['start'] = 0;
287 $this->pager['total'] = 0;
289 // Detect mobile devices
290 $mobile_detect = new MobileDetect();
291 $this->is_mobile = $mobile_detect->isMobile();
292 $this->is_tablet = $mobile_detect->isTablet();
295 $this->is_friendica_app = isset($_SERVER['HTTP_USER_AGENT']) && $_SERVER['HTTP_USER_AGENT'] == 'Apache-HttpClient/UNAVAILABLE (java 1.4)';
297 // Register template engines
298 $this->register_template_engine('Friendica\Render\FriendicaSmartyEngine');
302 * Reloads the whole app instance
304 public function reload()
306 // The order of the following calls is important to ensure proper initialization
307 $this->loadConfigFiles();
309 $this->loadDatabase();
311 $this->determineMode();
313 $this->determineUrlPath();
317 if ($this->mode & self::MODE_DBAVAILABLE) {
318 Core\Addon::loadHooks();
320 $this->loadAddonConfig();
323 $this->loadDefaultTimezone();
338 $this->process_id = System::processID('log');
342 * Load the configuration files
344 * First loads the default value for all the configuration keys, then the legacy configuration files, then the
345 * expected local.ini.php
347 private function loadConfigFiles()
349 $this->loadConfigFile($this->basepath . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'config.ini.php');
350 $this->loadConfigFile($this->basepath . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'settings.ini.php');
352 // Legacy .htconfig.php support
353 if (file_exists($this->basepath . DIRECTORY_SEPARATOR . '.htpreconfig.php')) {
355 include $this->basepath . DIRECTORY_SEPARATOR . '.htpreconfig.php';
358 // Legacy .htconfig.php support
359 if (file_exists($this->basepath . DIRECTORY_SEPARATOR . '.htconfig.php')) {
362 include $this->basepath . DIRECTORY_SEPARATOR . '.htconfig.php';
364 $this->setConfigValue('database', 'hostname', $db_host);
365 $this->setConfigValue('database', 'username', $db_user);
366 $this->setConfigValue('database', 'password', $db_pass);
367 $this->setConfigValue('database', 'database', $db_data);
368 if (isset($a->config['system']['db_charset'])) {
369 $this->setConfigValue('database', 'charset', $a->config['system']['db_charset']);
372 unset($db_host, $db_user, $db_pass, $db_data);
374 if (isset($default_timezone)) {
375 $this->setConfigValue('system', 'default_timezone', $default_timezone);
376 unset($default_timezone);
379 if (isset($pidfile)) {
380 $this->setConfigValue('system', 'pidfile', $pidfile);
385 $this->setConfigValue('system', 'language', $lang);
390 if (file_exists($this->basepath . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'local.ini.php')) {
391 $this->loadConfigFile($this->basepath . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'local.ini.php');
396 * Tries to load the specified configuration file into the App->config array.
397 * Overwrites previously set values.
399 * The config format is INI and the template for configuration files is the following:
401 * <?php return <<<INI
409 * @param type $filepath
412 public function loadConfigFile($filepath)
414 if (!file_exists($filepath)) {
415 throw new Exception('Error parsing non-existent config file ' . $filepath);
418 $contents = include($filepath);
420 $config = parse_ini_string($contents, true, INI_SCANNER_TYPED);
422 if ($config === false) {
423 throw new Exception('Error parsing config file ' . $filepath);
426 foreach ($config as $category => $values) {
427 foreach ($values as $key => $value) {
428 $this->setConfigValue($category, $key, $value);
434 * Loads addons configuration files
436 * First loads all activated addons default configuration throught the load_config hook, then load the local.ini.php
437 * again to overwrite potential local addon configuration.
439 private function loadAddonConfig()
441 // Loads addons default config
442 Core\Addon::callHooks('load_config');
444 // Load the local addon config file to overwritten default addon config values
445 if (file_exists($this->basepath . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'addon.ini.php')) {
446 $this->loadConfigFile($this->basepath . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'addon.ini.php');
451 * Loads the default timezone
453 * Include support for legacy $default_timezone
455 * @global string $default_timezone
457 private function loadDefaultTimezone()
459 if ($this->getConfigValue('system', 'default_timezone')) {
460 $this->timezone = $this->getConfigValue('system', 'default_timezone');
462 global $default_timezone;
463 $this->timezone = !empty($default_timezone) ? $default_timezone : 'UTC';
466 if ($this->timezone) {
467 date_default_timezone_set($this->timezone);
472 * Figure out if we are running at the top of a domain or in a sub-directory and adjust accordingly
474 private function determineUrlPath()
476 $this->urlpath = $this->getConfigValue('system', 'urlpath');
478 /* SCRIPT_URL gives /path/to/friendica/module/parameter
479 * QUERY_STRING gives pagename=module/parameter
481 * To get /path/to/friendica we perform dirname() for as many levels as there are slashes in the QUERY_STRING
483 if (!empty($_SERVER['SCRIPT_URL'])) {
485 if (!empty($_SERVER['QUERY_STRING'])) {
486 $path = trim(dirname($_SERVER['SCRIPT_URL'], substr_count(trim($_SERVER['QUERY_STRING'], '/'), '/') + 1), '/');
489 $path = trim($_SERVER['SCRIPT_URL'], '/');
492 if ($path && $path != $this->urlpath) {
493 $this->urlpath = $path;
501 * - App::MODE_INSTALL : Either the database connection can't be established or the config table doesn't exist
502 * - App::MODE_MAINTENANCE: The maintenance mode has been set
503 * - App::MODE_NORMAL : Normal run with all features enabled
507 private function determineMode()
511 if (!file_exists($this->basepath . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'local.ini.php')
512 && !file_exists($this->basepath . DIRECTORY_SEPARATOR . '.htconfig.php')) {
516 $this->mode |= App::MODE_LOCALCONFIGPRESENT;
518 if (!DBA::connected()) {
522 $this->mode |= App::MODE_DBAVAILABLE;
524 if (DBA::fetchFirst("SHOW TABLES LIKE 'config'") === false) {
528 $this->mode |= App::MODE_DBCONFIGAVAILABLE;
530 if (Config::get('system', 'maintenance')) {
534 $this->mode |= App::MODE_MAINTENANCEDISABLED;
537 public function loadDatabase()
539 if (DBA::connected()) {
543 $db_host = $this->getConfigValue('database', 'hostname');
544 $db_user = $this->getConfigValue('database', 'username');
545 $db_pass = $this->getConfigValue('database', 'password');
546 $db_data = $this->getConfigValue('database', 'database');
547 $charset = $this->getConfigValue('database', 'charset');
549 // Use environment variables for mysql if they are set beforehand
550 if (!empty(getenv('MYSQL_HOST'))
551 && (!empty(getenv('MYSQL_USERNAME')) || !empty(getenv('MYSQL_USER')))
552 && getenv('MYSQL_PASSWORD') !== false
553 && !empty(getenv('MYSQL_DATABASE')))
555 $db_host = getenv('MYSQL_HOST');
556 if (!empty(getenv('MYSQL_PORT'))) {
557 $db_host .= ':' . getenv('MYSQL_PORT');
559 if (!empty(getenv('MYSQL_USERNAME'))) {
560 $db_user = getenv('MYSQL_USERNAME');
562 $db_user = getenv('MYSQL_USER');
564 $db_pass = (string) getenv('MYSQL_PASSWORD');
565 $db_data = getenv('MYSQL_DATABASE');
568 $stamp1 = microtime(true);
570 DBA::connect($db_host, $db_user, $db_pass, $db_data, $charset);
571 unset($db_host, $db_user, $db_pass, $db_data, $charset);
573 $this->save_timestamp($stamp1, 'network');
577 * Install mode is when the local config file is missing or the DB schema hasn't been installed yet.
581 public function isInstallMode()
583 return !($this->mode & App::MODE_LOCALCONFIGPRESENT) || !($this->mode & App::MODE_DBCONFIGAVAILABLE);
587 * @brief Returns the base filesystem path of the App
589 * It first checks for the internal variable, then for DOCUMENT_ROOT and
594 public function get_basepath()
596 $basepath = $this->basepath;
599 $basepath = Config::get('system', 'basepath');
602 if (!$basepath && x($_SERVER, 'DOCUMENT_ROOT')) {
603 $basepath = $_SERVER['DOCUMENT_ROOT'];
606 if (!$basepath && x($_SERVER, 'PWD')) {
607 $basepath = $_SERVER['PWD'];
610 return self::realpath($basepath);
614 * @brief Returns a normalized file path
616 * This is a wrapper for the "realpath" function.
617 * That function cannot detect the real path when some folders aren't readable.
618 * Since this could happen with some hosters we need to handle this.
620 * @param string $path The path that is about to be normalized
621 * @return string normalized path - when possible
623 public static function realpath($path)
625 $normalized = realpath($path);
627 if (!is_bool($normalized)) {
634 public function get_scheme()
636 return $this->scheme;
640 * @brief Retrieves the Friendica instance base URL
642 * This function assembles the base URL from multiple parts:
643 * - Protocol is determined either by the request or a combination of
644 * system.ssl_policy and the $ssl parameter.
645 * - Host name is determined either by system.hostname or inferred from request
646 * - Path is inferred from SCRIPT_NAME
648 * Note: $ssl parameter value doesn't directly correlate with the resulting protocol
650 * @param bool $ssl Whether to append http or https under SSL_POLICY_SELFSIGN
651 * @return string Friendica server base URL
653 public function get_baseurl($ssl = false)
655 $scheme = $this->scheme;
657 if (Config::get('system', 'ssl_policy') == SSL_POLICY_FULL) {
661 // Basically, we have $ssl = true on any links which can only be seen by a logged in user
662 // (and also the login link). Anything seen by an outsider will have it turned off.
664 if (Config::get('system', 'ssl_policy') == SSL_POLICY_SELFSIGN) {
672 if (Config::get('config', 'hostname') != '') {
673 $this->hostname = Config::get('config', 'hostname');
676 return $scheme . '://' . $this->hostname . (!empty($this->urlpath) ? '/' . $this->urlpath : '' );
680 * @brief Initializes the baseurl components
682 * Clears the baseurl cache to prevent inconsistencies
686 public function set_baseurl($url)
688 $parsed = @parse_url($url);
692 if (!empty($parsed['scheme'])) {
693 $this->scheme = $parsed['scheme'];
696 if (!empty($parsed['host'])) {
697 $hostname = $parsed['host'];
700 if (x($parsed, 'port')) {
701 $hostname .= ':' . $parsed['port'];
703 if (x($parsed, 'path')) {
704 $this->urlpath = trim($parsed['path'], '\\/');
707 if (file_exists($this->basepath . DIRECTORY_SEPARATOR . '.htpreconfig.php')) {
708 include $this->basepath . DIRECTORY_SEPARATOR . '.htpreconfig.php';
711 if (Config::get('config', 'hostname') != '') {
712 $this->hostname = Config::get('config', 'hostname');
715 if (!isset($this->hostname) || ($this->hostname == '')) {
716 $this->hostname = $hostname;
721 public function get_hostname()
723 if (Config::get('config', 'hostname') != '') {
724 $this->hostname = Config::get('config', 'hostname');
727 return $this->hostname;
730 public function get_path()
732 return $this->urlpath;
735 public function set_pager_total($n)
737 $this->pager['total'] = intval($n);
740 public function set_pager_itemspage($n)
742 $this->pager['itemspage'] = ((intval($n) > 0) ? intval($n) : 0);
743 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
746 public function set_pager_page($n)
748 $this->pager['page'] = $n;
749 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
752 public function initHead()
754 $interval = ((local_user()) ? PConfig::get(local_user(), 'system', 'update_interval') : 40000);
756 // If the update is 'deactivated' set it to the highest integer number (~24 days)
758 $interval = 2147483647;
761 if ($interval < 10000) {
765 // compose the page title from the sitename and the
766 // current module called
767 if (!$this->module == '') {
768 $this->page['title'] = $this->config['sitename'] . ' (' . $this->module . ')';
770 $this->page['title'] = $this->config['sitename'];
773 /* put the head template at the beginning of page['htmlhead']
774 * since the code added by the modules frequently depends on it
778 // If we're using Smarty, then doing replace_macros() will replace
779 // any unrecognized variables with a blank string. Since we delay
780 // replacing $stylesheet until later, we need to replace it now
781 // with another variable name
782 if ($this->theme['template_engine'] === 'smarty3') {
783 $stylesheet = $this->get_template_ldelim('smarty3') . '$stylesheet' . $this->get_template_rdelim('smarty3');
785 $stylesheet = '$stylesheet';
788 $shortcut_icon = Config::get('system', 'shortcut_icon');
789 if ($shortcut_icon == '') {
790 $shortcut_icon = 'images/friendica-32.png';
793 $touch_icon = Config::get('system', 'touch_icon');
794 if ($touch_icon == '') {
795 $touch_icon = 'images/friendica-128.png';
798 // get data wich is needed for infinite scroll on the network page
799 $infinite_scroll = infinite_scroll_data($this->module);
801 Core\Addon::callHooks('head', $this->page['htmlhead']);
803 $tpl = get_markup_template('head.tpl');
804 $this->page['htmlhead'] = replace_macros($tpl, [
805 '$baseurl' => $this->get_baseurl(),
806 '$local_user' => local_user(),
807 '$generator' => 'Friendica' . ' ' . FRIENDICA_VERSION,
808 '$delitem' => L10n::t('Delete this item?'),
809 '$showmore' => L10n::t('show more'),
810 '$showfewer' => L10n::t('show fewer'),
811 '$update_interval' => $interval,
812 '$shortcut_icon' => $shortcut_icon,
813 '$touch_icon' => $touch_icon,
814 '$stylesheet' => $stylesheet,
815 '$infinite_scroll' => $infinite_scroll,
816 '$block_public' => intval(Config::get('system', 'block_public')),
817 '$stylesheets' => $this->stylesheets,
818 ]) . $this->page['htmlhead'];
821 public function initFooter()
823 if (!isset($this->page['footer'])) {
824 $this->page['footer'] = '';
827 // If you're just visiting, let javascript take you home
828 if (!empty($_SESSION['visitor_home'])) {
829 $homebase = $_SESSION['visitor_home'];
830 } elseif (local_user()) {
831 $homebase = 'profile/' . $a->user['nickname'];
834 if (isset($homebase)) {
835 $this->page['footer'] .= '<script>var homebase="' . $homebase . '";</script>' . "\n";
839 * Add a "toggle mobile" link if we're using a mobile device
841 if ($this->is_mobile || $this->is_tablet) {
842 if (isset($_SESSION['show-mobile']) && !$_SESSION['show-mobile']) {
843 $link = 'toggle_mobile?address=' . curPageURL();
845 $link = 'toggle_mobile?off=1&address=' . curPageURL();
847 $this->page['footer'] .= replace_macros(get_markup_template("toggle_mobile_footer.tpl"), [
848 '$toggle_link' => $link,
849 '$toggle_text' => Core\L10n::t('toggle mobile')
853 Core\Addon::callHooks('footer', $this->page['footer']);
855 $tpl = get_markup_template('footer.tpl');
856 $this->page['footer'] = replace_macros($tpl, [
857 '$baseurl' => $this->get_baseurl(),
858 '$footerScripts' => $this->footerScripts,
859 ]) . $this->page['footer'];
862 public function set_curl_code($code)
864 $this->curl_code = $code;
867 public function get_curl_code()
869 return $this->curl_code;
872 public function set_curl_content_type($content_type)
874 $this->curl_content_type = $content_type;
877 public function get_curl_content_type()
879 return $this->curl_content_type;
882 public function set_curl_headers($headers)
884 $this->curl_headers = $headers;
887 public function get_curl_headers()
889 return $this->curl_headers;
893 * @brief Removes the base url from an url. This avoids some mixed content problems.
895 * @param string $orig_url
897 * @return string The cleaned url
899 public function remove_baseurl($orig_url)
901 // Remove the hostname from the url if it is an internal link
902 $nurl = normalise_link($orig_url);
903 $base = normalise_link($this->get_baseurl());
904 $url = str_replace($base . '/', '', $nurl);
906 // if it is an external link return the orignal value
907 if ($url == normalise_link($orig_url)) {
915 * @brief Register template engine class
917 * @param string $class
919 private function register_template_engine($class)
921 $v = get_class_vars($class);
924 $this->template_engines[$name] = $class;
926 echo "template engine <tt>$class</tt> cannot be registered without a name.\n";
932 * @brief Return template engine instance.
934 * If $name is not defined, return engine defined by theme,
937 * @return object Template Engine instance
939 public function template_engine()
941 $template_engine = 'smarty3';
942 if (x($this->theme, 'template_engine')) {
943 $template_engine = $this->theme['template_engine'];
946 if (isset($this->template_engines[$template_engine])) {
947 if (isset($this->template_engine_instance[$template_engine])) {
948 return $this->template_engine_instance[$template_engine];
950 $class = $this->template_engines[$template_engine];
952 $this->template_engine_instance[$template_engine] = $obj;
957 echo "template engine <tt>$template_engine</tt> is not registered!\n";
962 * @brief Returns the active template engine.
966 public function get_template_engine()
968 return $this->theme['template_engine'];
971 public function set_template_engine($engine = 'smarty3')
973 $this->theme['template_engine'] = $engine;
976 public function get_template_ldelim($engine = 'smarty3')
978 return $this->ldelim[$engine];
981 public function get_template_rdelim($engine = 'smarty3')
983 return $this->rdelim[$engine];
986 public function save_timestamp($stamp, $value)
988 if (!isset($this->config['system']['profiler']) || !$this->config['system']['profiler']) {
992 $duration = (float) (microtime(true) - $stamp);
994 if (!isset($this->performance[$value])) {
995 // Prevent ugly E_NOTICE
996 $this->performance[$value] = 0;
999 $this->performance[$value] += (float) $duration;
1000 $this->performance['marktime'] += (float) $duration;
1002 $callstack = System::callstack();
1004 if (!isset($this->callstack[$value][$callstack])) {
1005 // Prevent ugly E_NOTICE
1006 $this->callstack[$value][$callstack] = 0;
1009 $this->callstack[$value][$callstack] += (float) $duration;
1012 public function get_useragent()
1015 FRIENDICA_PLATFORM . " '" .
1016 FRIENDICA_CODENAME . "' " .
1017 FRIENDICA_VERSION . '-' .
1018 DB_UPDATE_VERSION . '; ' .
1019 $this->get_baseurl();
1022 public function is_friendica_app()
1024 return $this->is_friendica_app;
1028 * @brief Checks if the site is called via a backend process
1030 * This isn't a perfect solution. But we need this check very early.
1031 * So we cannot wait until the modules are loaded.
1033 * @return bool Is it a known backend?
1035 public function is_backend()
1037 static $backends = [
1059 // Check if current module is in backend or backend flag is set
1060 return (in_array($this->module, $backends) || $this->backend);
1064 * @brief Checks if the maximum number of database processes is reached
1066 * @return bool Is the limit reached?
1068 public function isMaxProcessesReached()
1070 // Deactivated, needs more investigating if this check really makes sense
1074 * Commented out to suppress static analyzer issues
1076 if ($this->is_backend()) {
1077 $process = 'backend';
1078 $max_processes = Config::get('system', 'max_processes_backend');
1079 if (intval($max_processes) == 0) {
1083 $process = 'frontend';
1084 $max_processes = Config::get('system', 'max_processes_frontend');
1085 if (intval($max_processes) == 0) {
1086 $max_processes = 20;
1090 $processlist = DBA::processlist();
1091 if ($processlist['list'] != '') {
1092 logger('Processcheck: Processes: ' . $processlist['amount'] . ' - Processlist: ' . $processlist['list'], LOGGER_DEBUG);
1094 if ($processlist['amount'] > $max_processes) {
1095 logger('Processcheck: Maximum number of processes for ' . $process . ' tasks (' . $max_processes . ') reached.', LOGGER_DEBUG);
1104 * @brief Checks if the minimal memory is reached
1106 * @return bool Is the memory limit reached?
1108 public function min_memory_reached()
1110 $min_memory = Config::get('system', 'min_memory', 0);
1111 if ($min_memory == 0) {
1115 if (!is_readable('/proc/meminfo')) {
1119 $memdata = explode("\n", file_get_contents('/proc/meminfo'));
1122 foreach ($memdata as $line) {
1123 list($key, $val) = explode(':', $line);
1124 $meminfo[$key] = (int) trim(str_replace('kB', '', $val));
1125 $meminfo[$key] = (int) ($meminfo[$key] / 1024);
1128 if (!isset($meminfo['MemAvailable']) || !isset($meminfo['MemFree'])) {
1132 $free = $meminfo['MemAvailable'] + $meminfo['MemFree'];
1134 $reached = ($free < $min_memory);
1137 logger('Minimal memory reached: ' . $free . '/' . $meminfo['MemTotal'] . ' - limit ' . $min_memory, LOGGER_DEBUG);
1144 * @brief Checks if the maximum load is reached
1146 * @return bool Is the load reached?
1148 public function isMaxLoadReached()
1150 if ($this->is_backend()) {
1151 $process = 'backend';
1152 $maxsysload = intval(Config::get('system', 'maxloadavg'));
1153 if ($maxsysload < 1) {
1157 $process = 'frontend';
1158 $maxsysload = intval(Config::get('system', 'maxloadavg_frontend'));
1159 if ($maxsysload < 1) {
1164 $load = current_load();
1166 if (intval($load) > $maxsysload) {
1167 logger('system: load ' . $load . ' for ' . $process . ' tasks (' . $maxsysload . ') too high.');
1175 * Executes a child process with 'proc_open'
1177 * @param string $command The command to execute
1178 * @param array $args Arguments to pass to the command ( [ 'key' => value, 'key2' => value2, ... ]
1180 public function proc_run($command, $args)
1182 if (!function_exists('proc_open')) {
1186 $cmdline = $this->getConfigValue('config', 'php_path', 'php') . ' ' . escapeshellarg($command);
1188 foreach ($args as $key => $value) {
1189 if (!is_null($value) && is_bool($value) && !$value) {
1193 $cmdline .= ' --' . $key;
1194 if (!is_null($value) && !is_bool($value)) {
1195 $cmdline .= ' ' . $value;
1199 if ($this->min_memory_reached()) {
1203 if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
1204 $resource = proc_open('cmd /c start /b ' . $cmdline, [], $foo, $this->get_basepath());
1206 $resource = proc_open($cmdline . ' &', [], $foo, $this->get_basepath());
1208 if (!is_resource($resource)) {
1209 logger('We got no resource for command ' . $cmdline, LOGGER_DEBUG);
1212 proc_close($resource);
1216 * @brief Returns the system user that is executing the script
1218 * This mostly returns something like "www-data".
1220 * @return string system username
1222 private static function systemuser()
1224 if (!function_exists('posix_getpwuid') || !function_exists('posix_geteuid')) {
1228 $processUser = posix_getpwuid(posix_geteuid());
1229 return $processUser['name'];
1233 * @brief Checks if a given directory is usable for the system
1235 * @return boolean the directory is usable
1237 public static function directory_usable($directory, $check_writable = true)
1239 if ($directory == '') {
1240 logger('Directory is empty. This shouldn\'t happen.', LOGGER_DEBUG);
1244 if (!file_exists($directory)) {
1245 logger('Path "' . $directory . '" does not exist for user ' . self::systemuser(), LOGGER_DEBUG);
1249 if (is_file($directory)) {
1250 logger('Path "' . $directory . '" is a file for user ' . self::systemuser(), LOGGER_DEBUG);
1254 if (!is_dir($directory)) {
1255 logger('Path "' . $directory . '" is not a directory for user ' . self::systemuser(), LOGGER_DEBUG);
1259 if ($check_writable && !is_writable($directory)) {
1260 logger('Path "' . $directory . '" is not writable for user ' . self::systemuser(), LOGGER_DEBUG);
1268 * @param string $cat Config category
1269 * @param string $k Config key
1270 * @param mixed $default Default value if it isn't set
1272 public function getConfigValue($cat, $k, $default = null)
1276 if ($cat === 'config') {
1277 if (isset($this->config[$k])) {
1278 $return = $this->config[$k];
1281 if (isset($this->config[$cat][$k])) {
1282 $return = $this->config[$cat][$k];
1290 * Sets a value in the config cache. Accepts raw output from the config table
1292 * @param string $cat Config category
1293 * @param string $k Config key
1294 * @param mixed $v Value to set
1296 public function setConfigValue($cat, $k, $v)
1298 // Only arrays are serialized in database, so we have to unserialize sparingly
1299 $value = is_string($v) && preg_match("|^a:[0-9]+:{.*}$|s", $v) ? unserialize($v) : $v;
1301 if ($cat === 'config') {
1302 $this->config[$k] = $value;
1304 if (!isset($this->config[$cat])) {
1305 $this->config[$cat] = [];
1308 $this->config[$cat][$k] = $value;
1313 * Deletes a value from the config cache
1315 * @param string $cat Config category
1316 * @param string $k Config key
1318 public function deleteConfigValue($cat, $k)
1320 if ($cat === 'config') {
1321 if (isset($this->config[$k])) {
1322 unset($this->config[$k]);
1325 if (isset($this->config[$cat][$k])) {
1326 unset($this->config[$cat][$k]);
1333 * Retrieves a value from the user config cache
1335 * @param int $uid User Id
1336 * @param string $cat Config category
1337 * @param string $k Config key
1338 * @param mixed $default Default value if key isn't set
1340 public function getPConfigValue($uid, $cat, $k, $default = null)
1344 if (isset($this->config[$uid][$cat][$k])) {
1345 $return = $this->config[$uid][$cat][$k];
1352 * Sets a value in the user config cache
1354 * Accepts raw output from the pconfig table
1356 * @param int $uid User Id
1357 * @param string $cat Config category
1358 * @param string $k Config key
1359 * @param mixed $v Value to set
1361 public function setPConfigValue($uid, $cat, $k, $v)
1363 // Only arrays are serialized in database, so we have to unserialize sparingly
1364 $value = is_string($v) && preg_match("|^a:[0-9]+:{.*}$|s", $v) ? unserialize($v) : $v;
1366 if (!isset($this->config[$uid]) || !is_array($this->config[$uid])) {
1367 $this->config[$uid] = [];
1370 if (!isset($this->config[$uid][$cat]) || !is_array($this->config[$uid][$cat])) {
1371 $this->config[$uid][$cat] = [];
1374 $this->config[$uid][$cat][$k] = $value;
1378 * Deletes a value from the user config cache
1380 * @param int $uid User Id
1381 * @param string $cat Config category
1382 * @param string $k Config key
1384 public function deletePConfigValue($uid, $cat, $k)
1386 if (isset($this->config[$uid][$cat][$k])) {
1387 unset($this->config[$uid][$cat][$k]);
1392 * Generates the site's default sender email address
1396 public function getSenderEmailAddress()
1398 $sender_email = Config::get('config', 'sender_email');
1399 if (empty($sender_email)) {
1400 $hostname = $this->get_hostname();
1401 if (strpos($hostname, ':')) {
1402 $hostname = substr($hostname, 0, strpos($hostname, ':'));
1405 $sender_email = 'noreply@' . $hostname;
1408 return $sender_email;
1412 * Returns the current theme name.
1416 public function getCurrentTheme()
1418 if ($this->isInstallMode()) {
1422 //// @TODO Compute the current theme only once (this behavior has
1423 /// already been implemented, but it didn't work well -
1424 /// https://github.com/friendica/friendica/issues/5092)
1425 $this->computeCurrentTheme();
1427 return $this->current_theme;
1431 * Computes the current theme name based on the node settings, the user settings and the device type
1435 private function computeCurrentTheme()
1437 $system_theme = Config::get('system', 'theme');
1438 if (!$system_theme) {
1439 throw new Exception(L10n::t('No system theme config value set.'));
1443 $this->current_theme = $system_theme;
1445 $allowed_themes = explode(',', Config::get('system', 'allowed_themes', $system_theme));
1448 // Find the theme that belongs to the user whose stuff we are looking at
1449 if ($this->profile_uid && ($this->profile_uid != local_user())) {
1450 // Allow folks to override user themes and always use their own on their own site.
1451 // This works only if the user is on the same server
1452 $user = DBA::selectFirst('user', ['theme'], ['uid' => $this->profile_uid]);
1453 if (DBA::isResult($user) && !PConfig::get(local_user(), 'system', 'always_my_theme')) {
1454 $page_theme = $user['theme'];
1458 $user_theme = Core\Session::get('theme', $system_theme);
1460 // Specific mobile theme override
1461 if (($this->is_mobile || $this->is_tablet) && Core\Session::get('show-mobile', true)) {
1462 $system_mobile_theme = Config::get('system', 'mobile-theme');
1463 $user_mobile_theme = Core\Session::get('mobile-theme', $system_mobile_theme);
1465 // --- means same mobile theme as desktop
1466 if (!empty($user_mobile_theme) && $user_mobile_theme !== '---') {
1467 $user_theme = $user_mobile_theme;
1472 $theme_name = $page_theme;
1474 $theme_name = $user_theme;
1478 && in_array($theme_name, $allowed_themes)
1479 && (file_exists('view/theme/' . $theme_name . '/style.css')
1480 || file_exists('view/theme/' . $theme_name . '/style.php'))
1482 $this->current_theme = $theme_name;
1487 * @brief Return full URL to theme which is currently in effect.
1489 * Provide a sane default if nothing is chosen or the specified theme does not exist.
1493 public function getCurrentThemeStylesheetPath()
1495 return Core\Theme::getStylesheetPath($this->getCurrentTheme());