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;
59 public $interactive = true;
61 public $addons_admin = [];
64 public $is_mobile = false;
65 public $is_tablet = false;
66 public $performance = [];
67 public $callstack = [];
68 public $theme_info = [];
71 // Allow themes to control internal parameters
72 // by changing App values in theme.php
74 public $sourcename = '';
75 public $videowidth = 425;
76 public $videoheight = 350;
77 public $force_max_items = 0;
78 public $theme_events_in_profile = true;
80 public $stylesheets = [];
81 public $footerScripts = [];
84 * @var App\Mode The Mode of the Application
89 * @var string The App base path
94 * @var string The App URL path
99 * @var bool true, if the call is from the Friendica APP, otherwise false
101 private $isFriendicaApp;
104 * @var bool true, if the call is from an backend node (f.e. worker)
109 * @var string The name of the current theme
111 private $currentTheme;
114 * Register a stylesheet file path to be included in the <head> tag of every page.
115 * Inclusion is done in App->initHead().
116 * The path can be absolute or relative to the Friendica installation base folder.
118 * @see App->initHead()
120 * @param string $path
122 public function registerStylesheet($path)
124 $url = str_replace($this->getBasePath() . DIRECTORY_SEPARATOR, '', $path);
126 $this->stylesheets[] = trim($url, '/');
130 * Register a javascript file path to be included in the <footer> tag of every page.
131 * Inclusion is done in App->initFooter().
132 * The path can be absolute or relative to the Friendica installation base folder.
134 * @see App->initFooter()
136 * @param string $path
138 public function registerFooterScript($path)
140 $url = str_replace($this->getBasePath() . DIRECTORY_SEPARATOR, '', $path);
142 $this->footerScripts[] = trim($url, '/');
146 * @brief An array for all theme-controllable parameters
148 * Mostly unimplemented yet. Only options 'template_engine' and
154 'videoheight' => 350,
155 'force_max_items' => 0,
157 'template_engine' => 'smarty3',
161 * @brief An array of registered template engines ('name'=>'class name')
163 public $template_engines = [];
166 * @brief An array of instanced template engines ('name'=>'instance')
168 public $template_engine_instance = [];
183 * @brief App constructor.
185 * @param string $basePath Path to the app base folder
186 * @param bool $backend true, if the call is from backend, otherwise set to true (Default true)
188 * @throws Exception if the Basepath is not usable
190 public function __construct($basePath, $backend = true)
192 if (!static::isDirectoryUsable($basePath, false)) {
193 throw new Exception('Basepath ' . $basePath . ' isn\'t usable.');
196 BaseObject::setApp($this);
198 $this->basePath = rtrim($basePath, DIRECTORY_SEPARATOR);
199 $this->checkBackend($backend);
200 $this->checkFriendicaApp();
202 $this->performance['start'] = microtime(true);
203 $this->performance['database'] = 0;
204 $this->performance['database_write'] = 0;
205 $this->performance['cache'] = 0;
206 $this->performance['cache_write'] = 0;
207 $this->performance['network'] = 0;
208 $this->performance['file'] = 0;
209 $this->performance['rendering'] = 0;
210 $this->performance['parser'] = 0;
211 $this->performance['marktime'] = 0;
212 $this->performance['markstart'] = microtime(true);
214 $this->callstack['database'] = [];
215 $this->callstack['database_write'] = [];
216 $this->callstack['cache'] = [];
217 $this->callstack['cache_write'] = [];
218 $this->callstack['network'] = [];
219 $this->callstack['file'] = [];
220 $this->callstack['rendering'] = [];
221 $this->callstack['parser'] = [];
223 $this->mode = new App\Mode($basePath);
229 // This has to be quite large to deal with embedded private photos
230 ini_set('pcre.backtrack_limit', 500000);
232 $this->scheme = 'http';
234 if ((x($_SERVER, 'HTTPS') && $_SERVER['HTTPS']) ||
235 (x($_SERVER, 'HTTP_FORWARDED') && preg_match('/proto=https/', $_SERVER['HTTP_FORWARDED'])) ||
236 (x($_SERVER, 'HTTP_X_FORWARDED_PROTO') && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') ||
237 (x($_SERVER, 'HTTP_X_FORWARDED_SSL') && $_SERVER['HTTP_X_FORWARDED_SSL'] == 'on') ||
238 (x($_SERVER, 'FRONT_END_HTTPS') && $_SERVER['FRONT_END_HTTPS'] == 'on') ||
239 (x($_SERVER, 'SERVER_PORT') && (intval($_SERVER['SERVER_PORT']) == 443)) // XXX: reasonable assumption, but isn't this hardcoding too much?
241 $this->scheme = 'https';
244 if (x($_SERVER, 'SERVER_NAME')) {
245 $this->hostname = $_SERVER['SERVER_NAME'];
247 if (x($_SERVER, 'SERVER_PORT') && $_SERVER['SERVER_PORT'] != 80 && $_SERVER['SERVER_PORT'] != 443) {
248 $this->hostname .= ':' . $_SERVER['SERVER_PORT'];
253 get_include_path() . PATH_SEPARATOR
254 . $this->getBasePath() . DIRECTORY_SEPARATOR . 'include' . PATH_SEPARATOR
255 . $this->getBasePath(). DIRECTORY_SEPARATOR . 'library' . PATH_SEPARATOR
256 . $this->getBasePath());
258 if ((x($_SERVER, 'QUERY_STRING')) && substr($_SERVER['QUERY_STRING'], 0, 9) === 'pagename=') {
259 $this->query_string = substr($_SERVER['QUERY_STRING'], 9);
260 } elseif ((x($_SERVER, 'QUERY_STRING')) && substr($_SERVER['QUERY_STRING'], 0, 2) === 'q=') {
261 $this->query_string = substr($_SERVER['QUERY_STRING'], 2);
264 // removing trailing / - maybe a nginx problem
265 $this->query_string = ltrim($this->query_string, '/');
267 if (!empty($_GET['pagename'])) {
268 $this->cmd = trim($_GET['pagename'], '/\\');
269 } elseif (!empty($_GET['q'])) {
270 $this->cmd = trim($_GET['q'], '/\\');
274 $this->query_string = str_replace($this->cmd . '&', $this->cmd . '?', $this->query_string);
276 // unix style "homedir"
277 if (substr($this->cmd, 0, 1) === '~') {
278 $this->cmd = 'profile/' . substr($this->cmd, 1);
281 // Diaspora style profile url
282 if (substr($this->cmd, 0, 2) === 'u/') {
283 $this->cmd = 'profile/' . substr($this->cmd, 2);
287 * Break the URL path into C style argc/argv style arguments for our
288 * modules. Given "http://example.com/module/arg1/arg2", $this->argc
289 * will be 3 (integer) and $this->argv will contain:
295 * There will always be one argument. If provided a naked domain
296 * URL, $this->argv[0] is set to "home".
299 $this->argv = explode('/', $this->cmd);
300 $this->argc = count($this->argv);
301 if ((array_key_exists('0', $this->argv)) && strlen($this->argv[0])) {
302 $this->module = str_replace('.', '_', $this->argv[0]);
303 $this->module = str_replace('-', '_', $this->module);
306 $this->argv = ['home'];
307 $this->module = 'home';
310 // See if there is any page number information, and initialise pagination
311 $this->pager['page'] = ((x($_GET, 'page') && intval($_GET['page']) > 0) ? intval($_GET['page']) : 1);
312 $this->pager['itemspage'] = 50;
313 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
315 if ($this->pager['start'] < 0) {
316 $this->pager['start'] = 0;
318 $this->pager['total'] = 0;
320 // Detect mobile devices
321 $mobile_detect = new MobileDetect();
322 $this->is_mobile = $mobile_detect->isMobile();
323 $this->is_tablet = $mobile_detect->isTablet();
325 // Register template engines
326 $this->registerTemplateEngine('Friendica\Render\FriendicaSmartyEngine');
330 * Returns the Mode of the Application
332 * @return App\Mode The Application Mode
334 * @throws InternalServerErrorException when the mode isn't created
336 public function getMode()
338 if (empty($this->mode)) {
339 throw new InternalServerErrorException('Mode of the Application is not defined');
346 * Reloads the whole app instance
348 public function reload()
350 // The order of the following calls is important to ensure proper initialization
351 $this->loadConfigFiles();
353 $this->loadDatabase();
355 $this->getMode()->determine($this->getBasePath());
357 $this->determineURLPath();
361 if ($this->getMode()->has(App\Mode::DBAVAILABLE)) {
362 Core\Addon::loadHooks();
364 $this->loadAddonConfig();
367 $this->loadDefaultTimezone();
382 $this->process_id = System::processID('log');
386 * Load the configuration files
388 * First loads the default value for all the configuration keys, then the legacy configuration files, then the
389 * expected local.ini.php
391 private function loadConfigFiles()
393 $this->loadConfigFile($this->getBasePath() . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'config.ini.php');
394 $this->loadConfigFile($this->getBasePath() . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'settings.ini.php');
396 // Legacy .htconfig.php support
397 if (file_exists($this->getBasePath() . DIRECTORY_SEPARATOR . '.htpreconfig.php')) {
399 include $this->getBasePath() . DIRECTORY_SEPARATOR . '.htpreconfig.php';
402 // Legacy .htconfig.php support
403 if (file_exists($this->getBasePath() . DIRECTORY_SEPARATOR . '.htconfig.php')) {
406 include $this->getBasePath() . DIRECTORY_SEPARATOR . '.htconfig.php';
408 $this->setConfigValue('database', 'hostname', $db_host);
409 $this->setConfigValue('database', 'username', $db_user);
410 $this->setConfigValue('database', 'password', $db_pass);
411 $this->setConfigValue('database', 'database', $db_data);
412 if (isset($a->config['system']['db_charset'])) {
413 $this->setConfigValue('database', 'charset', $a->config['system']['db_charset']);
416 unset($db_host, $db_user, $db_pass, $db_data);
418 if (isset($default_timezone)) {
419 $this->setConfigValue('system', 'default_timezone', $default_timezone);
420 unset($default_timezone);
423 if (isset($pidfile)) {
424 $this->setConfigValue('system', 'pidfile', $pidfile);
429 $this->setConfigValue('system', 'language', $lang);
434 if (file_exists($this->getBasePath() . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'local.ini.php')) {
435 $this->loadConfigFile($this->getBasePath() . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'local.ini.php', true);
440 * Tries to load the specified configuration file into the App->config array.
441 * Doesn't overwrite previously set values by default to prevent default config files to supersede DB Config.
443 * The config format is INI and the template for configuration files is the following:
445 * <?php return <<<INI
453 * @param string $filepath
454 * @param bool $overwrite Force value overwrite if the config key already exists
457 public function loadConfigFile($filepath, $overwrite = false)
459 if (!file_exists($filepath)) {
460 throw new Exception('Error parsing non-existent config file ' . $filepath);
463 $contents = include($filepath);
465 $config = parse_ini_string($contents, true, INI_SCANNER_TYPED);
467 if ($config === false) {
468 throw new Exception('Error parsing config file ' . $filepath);
471 foreach ($config as $category => $values) {
472 foreach ($values as $key => $value) {
474 $this->setConfigValue($category, $key, $value);
476 $this->setDefaultConfigValue($category, $key, $value);
483 * Loads addons configuration files
485 * First loads all activated addons default configuration throught the load_config hook, then load the local.ini.php
486 * again to overwrite potential local addon configuration.
488 private function loadAddonConfig()
490 // Loads addons default config
491 Core\Addon::callHooks('load_config');
493 // Load the local addon config file to overwritten default addon config values
494 if (file_exists($this->getBasePath() . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'addon.ini.php')) {
495 $this->loadConfigFile($this->getBasePath() . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'addon.ini.php', true);
500 * Loads the default timezone
502 * Include support for legacy $default_timezone
504 * @global string $default_timezone
506 private function loadDefaultTimezone()
508 if ($this->getConfigValue('system', 'default_timezone')) {
509 $this->timezone = $this->getConfigValue('system', 'default_timezone');
511 global $default_timezone;
512 $this->timezone = !empty($default_timezone) ? $default_timezone : 'UTC';
515 if ($this->timezone) {
516 date_default_timezone_set($this->timezone);
521 * Figure out if we are running at the top of a domain or in a sub-directory and adjust accordingly
523 private function determineURLPath()
525 /* Relative script path to the web server root
526 * Not all of those $_SERVER properties can be present, so we do by inverse priority order
528 $relative_script_path = '';
529 $relative_script_path = defaults($_SERVER, 'REDIRECT_URL' , $relative_script_path);
530 $relative_script_path = defaults($_SERVER, 'REDIRECT_URI' , $relative_script_path);
531 $relative_script_path = defaults($_SERVER, 'REDIRECT_SCRIPT_URL', $relative_script_path);
532 $relative_script_path = defaults($_SERVER, 'SCRIPT_URL' , $relative_script_path);
534 $this->urlPath = $this->getConfigValue('system', 'urlpath');
536 /* $relative_script_path gives /relative/path/to/friendica/module/parameter
537 * QUERY_STRING gives pagename=module/parameter
539 * To get /relative/path/to/friendica we perform dirname() for as many levels as there are slashes in the QUERY_STRING
541 if (!empty($relative_script_path)) {
543 if (!empty($_SERVER['QUERY_STRING'])) {
544 $path = trim(dirname($relative_script_path, substr_count(trim($_SERVER['QUERY_STRING'], '/'), '/') + 1), '/');
547 $path = trim($relative_script_path, '/');
550 if ($path && $path != $this->urlPath) {
551 $this->urlPath = $path;
556 public function loadDatabase()
558 if (DBA::connected()) {
562 $db_host = $this->getConfigValue('database', 'hostname');
563 $db_user = $this->getConfigValue('database', 'username');
564 $db_pass = $this->getConfigValue('database', 'password');
565 $db_data = $this->getConfigValue('database', 'database');
566 $charset = $this->getConfigValue('database', 'charset');
568 // Use environment variables for mysql if they are set beforehand
569 if (!empty(getenv('MYSQL_HOST'))
570 && (!empty(getenv('MYSQL_USERNAME')) || !empty(getenv('MYSQL_USER')))
571 && getenv('MYSQL_PASSWORD') !== false
572 && !empty(getenv('MYSQL_DATABASE')))
574 $db_host = getenv('MYSQL_HOST');
575 if (!empty(getenv('MYSQL_PORT'))) {
576 $db_host .= ':' . getenv('MYSQL_PORT');
578 if (!empty(getenv('MYSQL_USERNAME'))) {
579 $db_user = getenv('MYSQL_USERNAME');
581 $db_user = getenv('MYSQL_USER');
583 $db_pass = (string) getenv('MYSQL_PASSWORD');
584 $db_data = getenv('MYSQL_DATABASE');
587 $stamp1 = microtime(true);
589 DBA::connect($db_host, $db_user, $db_pass, $db_data, $charset);
590 unset($db_host, $db_user, $db_pass, $db_data, $charset);
592 $this->saveTimestamp($stamp1, 'network');
596 * @brief Returns the base filesystem path of the App
598 * It first checks for the internal variable, then for DOCUMENT_ROOT and
603 public function getBasePath()
605 $basepath = $this->basePath;
608 $basepath = Config::get('system', 'basepath');
611 if (!$basepath && x($_SERVER, 'DOCUMENT_ROOT')) {
612 $basepath = $_SERVER['DOCUMENT_ROOT'];
615 if (!$basepath && x($_SERVER, 'PWD')) {
616 $basepath = $_SERVER['PWD'];
619 return self::getRealPath($basepath);
623 * @brief Returns a normalized file path
625 * This is a wrapper for the "realpath" function.
626 * That function cannot detect the real path when some folders aren't readable.
627 * Since this could happen with some hosters we need to handle this.
629 * @param string $path The path that is about to be normalized
630 * @return string normalized path - when possible
632 public static function getRealPath($path)
634 $normalized = realpath($path);
636 if (!is_bool($normalized)) {
643 public function getScheme()
645 return $this->scheme;
649 * @brief Retrieves the Friendica instance base URL
651 * This function assembles the base URL from multiple parts:
652 * - Protocol is determined either by the request or a combination of
653 * system.ssl_policy and the $ssl parameter.
654 * - Host name is determined either by system.hostname or inferred from request
655 * - Path is inferred from SCRIPT_NAME
657 * Note: $ssl parameter value doesn't directly correlate with the resulting protocol
659 * @param bool $ssl Whether to append http or https under SSL_POLICY_SELFSIGN
660 * @return string Friendica server base URL
662 public function getBaseURL($ssl = false)
664 $scheme = $this->scheme;
666 if (Config::get('system', 'ssl_policy') == SSL_POLICY_FULL) {
670 // Basically, we have $ssl = true on any links which can only be seen by a logged in user
671 // (and also the login link). Anything seen by an outsider will have it turned off.
673 if (Config::get('system', 'ssl_policy') == SSL_POLICY_SELFSIGN) {
681 if (Config::get('config', 'hostname') != '') {
682 $this->hostname = Config::get('config', 'hostname');
685 return $scheme . '://' . $this->hostname . (!empty($this->getURLPath()) ? '/' . $this->getURLPath() : '' );
689 * @brief Initializes the baseurl components
691 * Clears the baseurl cache to prevent inconsistencies
695 public function setBaseURL($url)
697 $parsed = @parse_url($url);
701 if (!empty($parsed['scheme'])) {
702 $this->scheme = $parsed['scheme'];
705 if (!empty($parsed['host'])) {
706 $hostname = $parsed['host'];
709 if (x($parsed, 'port')) {
710 $hostname .= ':' . $parsed['port'];
712 if (x($parsed, 'path')) {
713 $this->urlPath = trim($parsed['path'], '\\/');
716 if (file_exists($this->getBasePath() . DIRECTORY_SEPARATOR . '.htpreconfig.php')) {
717 include $this->getBasePath() . DIRECTORY_SEPARATOR . '.htpreconfig.php';
720 if (Config::get('config', 'hostname') != '') {
721 $this->hostname = Config::get('config', 'hostname');
724 if (!isset($this->hostname) || ($this->hostname == '')) {
725 $this->hostname = $hostname;
730 public function getHostName()
732 if (Config::get('config', 'hostname') != '') {
733 $this->hostname = Config::get('config', 'hostname');
736 return $this->hostname;
739 public function getURLPath()
741 return $this->urlPath;
744 public function setPagerTotal($n)
746 $this->pager['total'] = intval($n);
749 public function setPagerItemsPage($n)
751 $this->pager['itemspage'] = ((intval($n) > 0) ? intval($n) : 0);
752 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
755 public function setPagerPage($n)
757 $this->pager['page'] = $n;
758 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
762 * Initializes App->page['htmlhead'].
767 * - Registered stylesheets (through App->registerStylesheet())
768 * - Infinite scroll data
769 * - head.tpl template
771 public function initHead()
773 $interval = ((local_user()) ? PConfig::get(local_user(), 'system', 'update_interval') : 40000);
775 // If the update is 'deactivated' set it to the highest integer number (~24 days)
777 $interval = 2147483647;
780 if ($interval < 10000) {
784 // compose the page title from the sitename and the
785 // current module called
786 if (!$this->module == '') {
787 $this->page['title'] = $this->config['sitename'] . ' (' . $this->module . ')';
789 $this->page['title'] = $this->config['sitename'];
792 if (!empty($this->theme['stylesheet'])) {
793 $stylesheet = $this->theme['stylesheet'];
795 $stylesheet = $this->getCurrentThemeStylesheetPath();
798 $this->registerStylesheet($stylesheet);
800 $shortcut_icon = Config::get('system', 'shortcut_icon');
801 if ($shortcut_icon == '') {
802 $shortcut_icon = 'images/friendica-32.png';
805 $touch_icon = Config::get('system', 'touch_icon');
806 if ($touch_icon == '') {
807 $touch_icon = 'images/friendica-128.png';
810 // get data wich is needed for infinite scroll on the network page
811 $infinite_scroll = infinite_scroll_data($this->module);
813 Core\Addon::callHooks('head', $this->page['htmlhead']);
815 $tpl = get_markup_template('head.tpl');
816 /* put the head template at the beginning of page['htmlhead']
817 * since the code added by the modules frequently depends on it
820 $this->page['htmlhead'] = replace_macros($tpl, [
821 '$baseurl' => $this->getBaseURL(),
822 '$local_user' => local_user(),
823 '$generator' => 'Friendica' . ' ' . FRIENDICA_VERSION,
824 '$delitem' => L10n::t('Delete this item?'),
825 '$showmore' => L10n::t('show more'),
826 '$showfewer' => L10n::t('show fewer'),
827 '$update_interval' => $interval,
828 '$shortcut_icon' => $shortcut_icon,
829 '$touch_icon' => $touch_icon,
830 '$infinite_scroll' => $infinite_scroll,
831 '$block_public' => intval(Config::get('system', 'block_public')),
832 '$stylesheets' => $this->stylesheets,
833 ]) . $this->page['htmlhead'];
837 * Initializes App->page['footer'].
840 * - Javascript homebase
841 * - Mobile toggle link
842 * - Registered footer scripts (through App->registerFooterScript())
843 * - footer.tpl template
845 public function initFooter()
847 // If you're just visiting, let javascript take you home
848 if (!empty($_SESSION['visitor_home'])) {
849 $homebase = $_SESSION['visitor_home'];
850 } elseif (local_user()) {
851 $homebase = 'profile/' . $this->user['nickname'];
854 if (isset($homebase)) {
855 $this->page['footer'] .= '<script>var homebase="' . $homebase . '";</script>' . "\n";
859 * Add a "toggle mobile" link if we're using a mobile device
861 if ($this->is_mobile || $this->is_tablet) {
862 if (isset($_SESSION['show-mobile']) && !$_SESSION['show-mobile']) {
863 $link = 'toggle_mobile?address=' . curPageURL();
865 $link = 'toggle_mobile?off=1&address=' . curPageURL();
867 $this->page['footer'] .= replace_macros(get_markup_template("toggle_mobile_footer.tpl"), [
868 '$toggle_link' => $link,
869 '$toggle_text' => Core\L10n::t('toggle mobile')
873 Core\Addon::callHooks('footer', $this->page['footer']);
875 $tpl = get_markup_template('footer.tpl');
876 $this->page['footer'] = replace_macros($tpl, [
877 '$baseurl' => $this->getBaseURL(),
878 '$footerScripts' => $this->footerScripts,
879 ]) . $this->page['footer'];
883 * @brief Removes the base url from an url. This avoids some mixed content problems.
885 * @param string $origURL
887 * @return string The cleaned url
889 public function removeBaseURL($origURL)
891 // Remove the hostname from the url if it is an internal link
892 $nurl = normalise_link($origURL);
893 $base = normalise_link($this->getBaseURL());
894 $url = str_replace($base . '/', '', $nurl);
896 // if it is an external link return the orignal value
897 if ($url == normalise_link($origURL)) {
905 * @brief Register template engine class
907 * @param string $class
909 private function registerTemplateEngine($class)
911 $v = get_class_vars($class);
914 $this->template_engines[$name] = $class;
916 echo "template engine <tt>$class</tt> cannot be registered without a name.\n";
922 * @brief Return template engine instance.
924 * If $name is not defined, return engine defined by theme,
927 * @return object Template Engine instance
929 public function getTemplateEngine()
931 $template_engine = 'smarty3';
932 if (x($this->theme, 'template_engine')) {
933 $template_engine = $this->theme['template_engine'];
936 if (isset($this->template_engines[$template_engine])) {
937 if (isset($this->template_engine_instance[$template_engine])) {
938 return $this->template_engine_instance[$template_engine];
940 $class = $this->template_engines[$template_engine];
942 $this->template_engine_instance[$template_engine] = $obj;
947 echo "template engine <tt>$template_engine</tt> is not registered!\n";
952 * @brief Returns the active template engine.
954 * @return string the active template engine
956 public function getActiveTemplateEngine()
958 return $this->theme['template_engine'];
962 * sets the active template engine
964 * @param string $engine the template engine (default is Smarty3)
966 public function setActiveTemplateEngine($engine = 'smarty3')
968 $this->theme['template_engine'] = $engine;
972 * Gets the right delimiter for a template engine
978 * @param string $engine The template engine (default is Smarty3)
980 * @return string the right delimiter
982 public function getTemplateLeftDelimiter($engine = 'smarty3')
984 return $this->ldelim[$engine];
988 * Gets the left delimiter for a template engine
994 * @param string $engine The template engine (default is Smarty3)
996 * @return string the left delimiter
998 public function getTemplateRightDelimiter($engine = 'smarty3')
1000 return $this->rdelim[$engine];
1004 * Saves a timestamp for a value - f.e. a call
1005 * Necessary for profiling Friendica
1007 * @param int $timestamp the Timestamp
1008 * @param string $value A value to profile
1010 public function saveTimestamp($timestamp, $value)
1012 if (!isset($this->config['system']['profiler']) || !$this->config['system']['profiler']) {
1016 $duration = (float) (microtime(true) - $timestamp);
1018 if (!isset($this->performance[$value])) {
1019 // Prevent ugly E_NOTICE
1020 $this->performance[$value] = 0;
1023 $this->performance[$value] += (float) $duration;
1024 $this->performance['marktime'] += (float) $duration;
1026 $callstack = System::callstack();
1028 if (!isset($this->callstack[$value][$callstack])) {
1029 // Prevent ugly E_NOTICE
1030 $this->callstack[$value][$callstack] = 0;
1033 $this->callstack[$value][$callstack] += (float) $duration;
1037 * Returns the current UserAgent as a String
1039 * @return string the UserAgent as a String
1041 public function getUserAgent()
1044 FRIENDICA_PLATFORM . " '" .
1045 FRIENDICA_CODENAME . "' " .
1046 FRIENDICA_VERSION . '-' .
1047 DB_UPDATE_VERSION . '; ' .
1048 $this->getBaseURL();
1052 * Checks, if the call is from the Friendica App
1055 * The friendica client has problems with the GUID in the notify. this is some workaround
1057 private function checkFriendicaApp()
1060 $this->isFriendicaApp = isset($_SERVER['HTTP_USER_AGENT']) && $_SERVER['HTTP_USER_AGENT'] == 'Apache-HttpClient/UNAVAILABLE (java 1.4)';
1064 * Is the call via the Friendica app? (not a "normale" call)
1066 * @return bool true if it's from the Friendica app
1068 public function isFriendicaApp()
1070 return $this->isFriendicaApp;
1074 * @brief Checks if the site is called via a backend process
1076 * This isn't a perfect solution. But we need this check very early.
1077 * So we cannot wait until the modules are loaded.
1079 * @param string $backend true, if the backend flag was set during App initialization
1082 private function checkBackend($backend) {
1083 static $backends = [
1105 // Check if current module is in backend or backend flag is set
1106 $this->isBackend = (in_array($this->module, $backends) || $backend || $this->isBackend);
1110 * Returns true, if the call is from a backend node (f.e. from a worker)
1112 * @return bool Is it a known backend?
1114 public function isBackend()
1116 return $this->isBackend;
1120 * @brief Checks if the maximum number of database processes is reached
1122 * @return bool Is the limit reached?
1124 public function isMaxProcessesReached()
1126 // Deactivated, needs more investigating if this check really makes sense
1130 * Commented out to suppress static analyzer issues
1132 if ($this->is_backend()) {
1133 $process = 'backend';
1134 $max_processes = Config::get('system', 'max_processes_backend');
1135 if (intval($max_processes) == 0) {
1139 $process = 'frontend';
1140 $max_processes = Config::get('system', 'max_processes_frontend');
1141 if (intval($max_processes) == 0) {
1142 $max_processes = 20;
1146 $processlist = DBA::processlist();
1147 if ($processlist['list'] != '') {
1148 logger('Processcheck: Processes: ' . $processlist['amount'] . ' - Processlist: ' . $processlist['list'], LOGGER_DEBUG);
1150 if ($processlist['amount'] > $max_processes) {
1151 logger('Processcheck: Maximum number of processes for ' . $process . ' tasks (' . $max_processes . ') reached.', LOGGER_DEBUG);
1160 * @brief Checks if the minimal memory is reached
1162 * @return bool Is the memory limit reached?
1164 public function isMinMemoryReached()
1166 $min_memory = Config::get('system', 'min_memory', 0);
1167 if ($min_memory == 0) {
1171 if (!is_readable('/proc/meminfo')) {
1175 $memdata = explode("\n", file_get_contents('/proc/meminfo'));
1178 foreach ($memdata as $line) {
1179 $data = explode(':', $line);
1180 if (count($data) != 2) {
1183 list($key, $val) = $data;
1184 $meminfo[$key] = (int) trim(str_replace('kB', '', $val));
1185 $meminfo[$key] = (int) ($meminfo[$key] / 1024);
1188 if (!isset($meminfo['MemAvailable']) || !isset($meminfo['MemFree'])) {
1192 $free = $meminfo['MemAvailable'] + $meminfo['MemFree'];
1194 $reached = ($free < $min_memory);
1197 logger('Minimal memory reached: ' . $free . '/' . $meminfo['MemTotal'] . ' - limit ' . $min_memory, LOGGER_DEBUG);
1204 * @brief Checks if the maximum load is reached
1206 * @return bool Is the load reached?
1208 public function isMaxLoadReached()
1210 if ($this->isBackend()) {
1211 $process = 'backend';
1212 $maxsysload = intval(Config::get('system', 'maxloadavg'));
1213 if ($maxsysload < 1) {
1217 $process = 'frontend';
1218 $maxsysload = intval(Config::get('system', 'maxloadavg_frontend'));
1219 if ($maxsysload < 1) {
1224 $load = current_load();
1226 if (intval($load) > $maxsysload) {
1227 logger('system: load ' . $load . ' for ' . $process . ' tasks (' . $maxsysload . ') too high.');
1235 * Executes a child process with 'proc_open'
1237 * @param string $command The command to execute
1238 * @param array $args Arguments to pass to the command ( [ 'key' => value, 'key2' => value2, ... ]
1240 public function proc_run($command, $args)
1242 if (!function_exists('proc_open')) {
1246 $cmdline = $this->getConfigValue('config', 'php_path', 'php') . ' ' . escapeshellarg($command);
1248 foreach ($args as $key => $value) {
1249 if (!is_null($value) && is_bool($value) && !$value) {
1253 $cmdline .= ' --' . $key;
1254 if (!is_null($value) && !is_bool($value)) {
1255 $cmdline .= ' ' . $value;
1259 if ($this->isMinMemoryReached()) {
1263 if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
1264 $resource = proc_open('cmd /c start /b ' . $cmdline, [], $foo, $this->getBasePath());
1266 $resource = proc_open($cmdline . ' &', [], $foo, $this->getBasePath());
1268 if (!is_resource($resource)) {
1269 logger('We got no resource for command ' . $cmdline, LOGGER_DEBUG);
1272 proc_close($resource);
1276 * @brief Returns the system user that is executing the script
1278 * This mostly returns something like "www-data".
1280 * @return string system username
1282 private static function getSystemUser()
1284 if (!function_exists('posix_getpwuid') || !function_exists('posix_geteuid')) {
1288 $processUser = posix_getpwuid(posix_geteuid());
1289 return $processUser['name'];
1293 * @brief Checks if a given directory is usable for the system
1295 * @return boolean the directory is usable
1297 public static function isDirectoryUsable($directory, $check_writable = true)
1299 if ($directory == '') {
1300 logger('Directory is empty. This shouldn\'t happen.', LOGGER_DEBUG);
1304 if (!file_exists($directory)) {
1305 logger('Path "' . $directory . '" does not exist for user ' . self::getSystemUser(), LOGGER_DEBUG);
1309 if (is_file($directory)) {
1310 logger('Path "' . $directory . '" is a file for user ' . self::getSystemUser(), LOGGER_DEBUG);
1314 if (!is_dir($directory)) {
1315 logger('Path "' . $directory . '" is not a directory for user ' . self::getSystemUser(), LOGGER_DEBUG);
1319 if ($check_writable && !is_writable($directory)) {
1320 logger('Path "' . $directory . '" is not writable for user ' . self::getSystemUser(), LOGGER_DEBUG);
1328 * @param string $cat Config category
1329 * @param string $k Config key
1330 * @param mixed $default Default value if it isn't set
1332 * @return string Returns the value of the Config entry
1334 public function getConfigValue($cat, $k, $default = null)
1338 if ($cat === 'config') {
1339 if (isset($this->config[$k])) {
1340 $return = $this->config[$k];
1343 if (isset($this->config[$cat][$k])) {
1344 $return = $this->config[$cat][$k];
1352 * Sets a default value in the config cache. Ignores already existing keys.
1354 * @param string $cat Config category
1355 * @param string $k Config key
1356 * @param mixed $v Default value to set
1358 private function setDefaultConfigValue($cat, $k, $v)
1360 if (!isset($this->config[$cat][$k])) {
1361 $this->setConfigValue($cat, $k, $v);
1366 * Sets a value in the config cache. Accepts raw output from the config table
1368 * @param string $cat Config category
1369 * @param string $k Config key
1370 * @param mixed $v Value to set
1372 public function setConfigValue($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 ($cat === 'config') {
1378 $this->config[$k] = $value;
1380 if (!isset($this->config[$cat])) {
1381 $this->config[$cat] = [];
1384 $this->config[$cat][$k] = $value;
1389 * Deletes a value from the config cache
1391 * @param string $cat Config category
1392 * @param string $k Config key
1394 public function deleteConfigValue($cat, $k)
1396 if ($cat === 'config') {
1397 if (isset($this->config[$k])) {
1398 unset($this->config[$k]);
1401 if (isset($this->config[$cat][$k])) {
1402 unset($this->config[$cat][$k]);
1409 * Retrieves a value from the user config cache
1411 * @param int $uid User Id
1412 * @param string $cat Config category
1413 * @param string $k Config key
1414 * @param mixed $default Default value if key isn't set
1416 * @return string The value of the config entry
1418 public function getPConfigValue($uid, $cat, $k, $default = null)
1422 if (isset($this->config[$uid][$cat][$k])) {
1423 $return = $this->config[$uid][$cat][$k];
1430 * Sets a value in the user config cache
1432 * Accepts raw output from the pconfig table
1434 * @param int $uid User Id
1435 * @param string $cat Config category
1436 * @param string $k Config key
1437 * @param mixed $v Value to set
1439 public function setPConfigValue($uid, $cat, $k, $v)
1441 // Only arrays are serialized in database, so we have to unserialize sparingly
1442 $value = is_string($v) && preg_match("|^a:[0-9]+:{.*}$|s", $v) ? unserialize($v) : $v;
1444 if (!isset($this->config[$uid]) || !is_array($this->config[$uid])) {
1445 $this->config[$uid] = [];
1448 if (!isset($this->config[$uid][$cat]) || !is_array($this->config[$uid][$cat])) {
1449 $this->config[$uid][$cat] = [];
1452 $this->config[$uid][$cat][$k] = $value;
1456 * Deletes a value from the user config cache
1458 * @param int $uid User Id
1459 * @param string $cat Config category
1460 * @param string $k Config key
1462 public function deletePConfigValue($uid, $cat, $k)
1464 if (isset($this->config[$uid][$cat][$k])) {
1465 unset($this->config[$uid][$cat][$k]);
1470 * Generates the site's default sender email address
1474 public function getSenderEmailAddress()
1476 $sender_email = Config::get('config', 'sender_email');
1477 if (empty($sender_email)) {
1478 $hostname = $this->getHostName();
1479 if (strpos($hostname, ':')) {
1480 $hostname = substr($hostname, 0, strpos($hostname, ':'));
1483 $sender_email = 'noreply@' . $hostname;
1486 return $sender_email;
1490 * Returns the current theme name.
1492 * @return string the name of the current theme
1494 public function getCurrentTheme()
1496 if ($this->getMode()->isInstall()) {
1500 //// @TODO Compute the current theme only once (this behavior has
1501 /// already been implemented, but it didn't work well -
1502 /// https://github.com/friendica/friendica/issues/5092)
1503 $this->computeCurrentTheme();
1505 return $this->currentTheme;
1509 * Computes the current theme name based on the node settings, the user settings and the device type
1513 private function computeCurrentTheme()
1515 $system_theme = Config::get('system', 'theme');
1516 if (!$system_theme) {
1517 throw new Exception(L10n::t('No system theme config value set.'));
1521 $this->currentTheme = $system_theme;
1523 $allowed_themes = explode(',', Config::get('system', 'allowed_themes', $system_theme));
1526 // Find the theme that belongs to the user whose stuff we are looking at
1527 if ($this->profile_uid && ($this->profile_uid != local_user())) {
1528 // Allow folks to override user themes and always use their own on their own site.
1529 // This works only if the user is on the same server
1530 $user = DBA::selectFirst('user', ['theme'], ['uid' => $this->profile_uid]);
1531 if (DBA::isResult($user) && !PConfig::get(local_user(), 'system', 'always_my_theme')) {
1532 $page_theme = $user['theme'];
1536 $user_theme = Core\Session::get('theme', $system_theme);
1538 // Specific mobile theme override
1539 if (($this->is_mobile || $this->is_tablet) && Core\Session::get('show-mobile', true)) {
1540 $system_mobile_theme = Config::get('system', 'mobile-theme');
1541 $user_mobile_theme = Core\Session::get('mobile-theme', $system_mobile_theme);
1543 // --- means same mobile theme as desktop
1544 if (!empty($user_mobile_theme) && $user_mobile_theme !== '---') {
1545 $user_theme = $user_mobile_theme;
1550 $theme_name = $page_theme;
1552 $theme_name = $user_theme;
1556 && in_array($theme_name, $allowed_themes)
1557 && (file_exists('view/theme/' . $theme_name . '/style.css')
1558 || file_exists('view/theme/' . $theme_name . '/style.php'))
1560 $this->currentTheme = $theme_name;
1565 * @brief Return full URL to theme which is currently in effect.
1567 * Provide a sane default if nothing is chosen or the specified theme does not exist.
1571 public function getCurrentThemeStylesheetPath()
1573 return Core\Theme::getStylesheetPath($this->getCurrentTheme());