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 * @var bool check if request was an AJAX (xmlhttprequest) request
119 * Register a stylesheet file path to be included in the <head> tag of every page.
120 * Inclusion is done in App->initHead().
121 * The path can be absolute or relative to the Friendica installation base folder.
123 * @see App->initHead()
125 * @param string $path
127 public function registerStylesheet($path)
129 $url = str_replace($this->getBasePath() . DIRECTORY_SEPARATOR, '', $path);
131 $this->stylesheets[] = trim($url, '/');
135 * Register a javascript file path to be included in the <footer> tag of every page.
136 * Inclusion is done in App->initFooter().
137 * The path can be absolute or relative to the Friendica installation base folder.
139 * @see App->initFooter()
141 * @param string $path
143 public function registerFooterScript($path)
145 $url = str_replace($this->getBasePath() . DIRECTORY_SEPARATOR, '', $path);
147 $this->footerScripts[] = trim($url, '/');
151 * @brief An array for all theme-controllable parameters
153 * Mostly unimplemented yet. Only options 'template_engine' and
159 'videoheight' => 350,
160 'force_max_items' => 0,
162 'template_engine' => 'smarty3',
166 * @brief An array of registered template engines ('name'=>'class name')
168 public $template_engines = [];
171 * @brief An array of instanced template engines ('name'=>'instance')
173 public $template_engine_instance = [];
188 * @brief App constructor.
190 * @param string $basePath Path to the app base folder
191 * @param bool $backend true, if the call is from backend, otherwise set to true (Default true)
193 * @throws Exception if the Basepath is not usable
195 public function __construct($basePath, $backend = true)
197 if (!static::isDirectoryUsable($basePath, false)) {
198 throw new Exception('Basepath ' . $basePath . ' isn\'t usable.');
201 BaseObject::setApp($this);
203 $this->basePath = rtrim($basePath, DIRECTORY_SEPARATOR);
204 $this->checkBackend($backend);
205 $this->checkFriendicaApp();
207 $this->performance['start'] = microtime(true);
208 $this->performance['database'] = 0;
209 $this->performance['database_write'] = 0;
210 $this->performance['cache'] = 0;
211 $this->performance['cache_write'] = 0;
212 $this->performance['network'] = 0;
213 $this->performance['file'] = 0;
214 $this->performance['rendering'] = 0;
215 $this->performance['parser'] = 0;
216 $this->performance['marktime'] = 0;
217 $this->performance['markstart'] = microtime(true);
219 $this->callstack['database'] = [];
220 $this->callstack['database_write'] = [];
221 $this->callstack['cache'] = [];
222 $this->callstack['cache_write'] = [];
223 $this->callstack['network'] = [];
224 $this->callstack['file'] = [];
225 $this->callstack['rendering'] = [];
226 $this->callstack['parser'] = [];
228 $this->mode = new App\Mode($basePath);
234 // This has to be quite large to deal with embedded private photos
235 ini_set('pcre.backtrack_limit', 500000);
237 $this->scheme = 'http';
239 if ((x($_SERVER, 'HTTPS') && $_SERVER['HTTPS']) ||
240 (x($_SERVER, 'HTTP_FORWARDED') && preg_match('/proto=https/', $_SERVER['HTTP_FORWARDED'])) ||
241 (x($_SERVER, 'HTTP_X_FORWARDED_PROTO') && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') ||
242 (x($_SERVER, 'HTTP_X_FORWARDED_SSL') && $_SERVER['HTTP_X_FORWARDED_SSL'] == 'on') ||
243 (x($_SERVER, 'FRONT_END_HTTPS') && $_SERVER['FRONT_END_HTTPS'] == 'on') ||
244 (x($_SERVER, 'SERVER_PORT') && (intval($_SERVER['SERVER_PORT']) == 443)) // XXX: reasonable assumption, but isn't this hardcoding too much?
246 $this->scheme = 'https';
249 if (x($_SERVER, 'SERVER_NAME')) {
250 $this->hostname = $_SERVER['SERVER_NAME'];
252 if (x($_SERVER, 'SERVER_PORT') && $_SERVER['SERVER_PORT'] != 80 && $_SERVER['SERVER_PORT'] != 443) {
253 $this->hostname .= ':' . $_SERVER['SERVER_PORT'];
258 get_include_path() . PATH_SEPARATOR
259 . $this->getBasePath() . DIRECTORY_SEPARATOR . 'include' . PATH_SEPARATOR
260 . $this->getBasePath(). DIRECTORY_SEPARATOR . 'library' . PATH_SEPARATOR
261 . $this->getBasePath());
263 if ((x($_SERVER, 'QUERY_STRING')) && substr($_SERVER['QUERY_STRING'], 0, 9) === 'pagename=') {
264 $this->query_string = substr($_SERVER['QUERY_STRING'], 9);
265 } elseif ((x($_SERVER, 'QUERY_STRING')) && substr($_SERVER['QUERY_STRING'], 0, 2) === 'q=') {
266 $this->query_string = substr($_SERVER['QUERY_STRING'], 2);
269 // removing trailing / - maybe a nginx problem
270 $this->query_string = ltrim($this->query_string, '/');
272 if (!empty($_GET['pagename'])) {
273 $this->cmd = trim($_GET['pagename'], '/\\');
274 } elseif (!empty($_GET['q'])) {
275 $this->cmd = trim($_GET['q'], '/\\');
279 $this->query_string = str_replace($this->cmd . '&', $this->cmd . '?', $this->query_string);
281 // unix style "homedir"
282 if (substr($this->cmd, 0, 1) === '~') {
283 $this->cmd = 'profile/' . substr($this->cmd, 1);
286 // Diaspora style profile url
287 if (substr($this->cmd, 0, 2) === 'u/') {
288 $this->cmd = 'profile/' . substr($this->cmd, 2);
292 * Break the URL path into C style argc/argv style arguments for our
293 * modules. Given "http://example.com/module/arg1/arg2", $this->argc
294 * will be 3 (integer) and $this->argv will contain:
300 * There will always be one argument. If provided a naked domain
301 * URL, $this->argv[0] is set to "home".
304 $this->argv = explode('/', $this->cmd);
305 $this->argc = count($this->argv);
306 if ((array_key_exists('0', $this->argv)) && strlen($this->argv[0])) {
307 $this->module = str_replace('.', '_', $this->argv[0]);
308 $this->module = str_replace('-', '_', $this->module);
311 $this->argv = ['home'];
312 $this->module = 'home';
315 // See if there is any page number information, and initialise pagination
316 $this->pager['page'] = ((x($_GET, 'page') && intval($_GET['page']) > 0) ? intval($_GET['page']) : 1);
317 $this->pager['itemspage'] = 50;
318 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
320 if ($this->pager['start'] < 0) {
321 $this->pager['start'] = 0;
323 $this->pager['total'] = 0;
325 // Detect mobile devices
326 $mobile_detect = new MobileDetect();
327 $this->is_mobile = $mobile_detect->isMobile();
328 $this->is_tablet = $mobile_detect->isTablet();
330 $this->isAjax = strtolower(defaults($_SERVER, 'HTTP_X_REQUESTED_WITH', '')) == 'xmlhttprequest';
332 // Register template engines
333 $this->registerTemplateEngine('Friendica\Render\FriendicaSmartyEngine');
337 * Returns the Mode of the Application
339 * @return App\Mode The Application Mode
341 * @throws InternalServerErrorException when the mode isn't created
343 public function getMode()
345 if (empty($this->mode)) {
346 throw new InternalServerErrorException('Mode of the Application is not defined');
353 * Reloads the whole app instance
355 public function reload()
357 // The order of the following calls is important to ensure proper initialization
358 $this->loadConfigFiles();
360 $this->loadDatabase();
362 $this->getMode()->determine($this->getBasePath());
364 $this->determineURLPath();
368 if ($this->getMode()->has(App\Mode::DBAVAILABLE)) {
369 Core\Addon::loadHooks();
371 $this->loadAddonConfig();
374 $this->loadDefaultTimezone();
389 $this->process_id = System::processID('log');
393 * Load the configuration files
395 * First loads the default value for all the configuration keys, then the legacy configuration files, then the
396 * expected local.ini.php
398 private function loadConfigFiles()
400 $this->loadConfigFile($this->getBasePath() . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'config.ini.php');
401 $this->loadConfigFile($this->getBasePath() . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'settings.ini.php');
403 // Legacy .htconfig.php support
404 if (file_exists($this->getBasePath() . DIRECTORY_SEPARATOR . '.htpreconfig.php')) {
406 include $this->getBasePath() . DIRECTORY_SEPARATOR . '.htpreconfig.php';
409 // Legacy .htconfig.php support
410 if (file_exists($this->getBasePath() . DIRECTORY_SEPARATOR . '.htconfig.php')) {
413 include $this->getBasePath() . DIRECTORY_SEPARATOR . '.htconfig.php';
415 $this->setConfigValue('database', 'hostname', $db_host);
416 $this->setConfigValue('database', 'username', $db_user);
417 $this->setConfigValue('database', 'password', $db_pass);
418 $this->setConfigValue('database', 'database', $db_data);
419 if (isset($a->config['system']['db_charset'])) {
420 $this->setConfigValue('database', 'charset', $a->config['system']['db_charset']);
423 unset($db_host, $db_user, $db_pass, $db_data);
425 if (isset($default_timezone)) {
426 $this->setConfigValue('system', 'default_timezone', $default_timezone);
427 unset($default_timezone);
430 if (isset($pidfile)) {
431 $this->setConfigValue('system', 'pidfile', $pidfile);
436 $this->setConfigValue('system', 'language', $lang);
441 if (file_exists($this->getBasePath() . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'local.ini.php')) {
442 $this->loadConfigFile($this->getBasePath() . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'local.ini.php', true);
447 * Tries to load the specified configuration file into the App->config array.
448 * Doesn't overwrite previously set values by default to prevent default config files to supersede DB Config.
450 * The config format is INI and the template for configuration files is the following:
452 * <?php return <<<INI
460 * @param string $filepath
461 * @param bool $overwrite Force value overwrite if the config key already exists
464 public function loadConfigFile($filepath, $overwrite = false)
466 if (!file_exists($filepath)) {
467 throw new Exception('Error parsing non-existent config file ' . $filepath);
470 $contents = include($filepath);
472 $config = parse_ini_string($contents, true, INI_SCANNER_TYPED);
474 if ($config === false) {
475 throw new Exception('Error parsing config file ' . $filepath);
478 foreach ($config as $category => $values) {
479 foreach ($values as $key => $value) {
481 $this->setConfigValue($category, $key, $value);
483 $this->setDefaultConfigValue($category, $key, $value);
490 * Loads addons configuration files
492 * First loads all activated addons default configuration throught the load_config hook, then load the local.ini.php
493 * again to overwrite potential local addon configuration.
495 private function loadAddonConfig()
497 // Loads addons default config
498 Core\Addon::callHooks('load_config');
500 // Load the local addon config file to overwritten default addon config values
501 if (file_exists($this->getBasePath() . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'addon.ini.php')) {
502 $this->loadConfigFile($this->getBasePath() . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'addon.ini.php', true);
507 * Loads the default timezone
509 * Include support for legacy $default_timezone
511 * @global string $default_timezone
513 private function loadDefaultTimezone()
515 if ($this->getConfigValue('system', 'default_timezone')) {
516 $this->timezone = $this->getConfigValue('system', 'default_timezone');
518 global $default_timezone;
519 $this->timezone = !empty($default_timezone) ? $default_timezone : 'UTC';
522 if ($this->timezone) {
523 date_default_timezone_set($this->timezone);
528 * Figure out if we are running at the top of a domain or in a sub-directory and adjust accordingly
530 private function determineURLPath()
532 /* Relative script path to the web server root
533 * Not all of those $_SERVER properties can be present, so we do by inverse priority order
535 $relative_script_path = '';
536 $relative_script_path = defaults($_SERVER, 'REDIRECT_URL' , $relative_script_path);
537 $relative_script_path = defaults($_SERVER, 'REDIRECT_URI' , $relative_script_path);
538 $relative_script_path = defaults($_SERVER, 'REDIRECT_SCRIPT_URL', $relative_script_path);
539 $relative_script_path = defaults($_SERVER, 'SCRIPT_URL' , $relative_script_path);
541 $this->urlPath = $this->getConfigValue('system', 'urlpath');
543 /* $relative_script_path gives /relative/path/to/friendica/module/parameter
544 * QUERY_STRING gives pagename=module/parameter
546 * To get /relative/path/to/friendica we perform dirname() for as many levels as there are slashes in the QUERY_STRING
548 if (!empty($relative_script_path)) {
550 if (!empty($_SERVER['QUERY_STRING'])) {
551 $path = trim(dirname($relative_script_path, substr_count(trim($_SERVER['QUERY_STRING'], '/'), '/') + 1), '/');
554 $path = trim($relative_script_path, '/');
557 if ($path && $path != $this->urlPath) {
558 $this->urlPath = $path;
563 public function loadDatabase()
565 if (DBA::connected()) {
569 $db_host = $this->getConfigValue('database', 'hostname');
570 $db_user = $this->getConfigValue('database', 'username');
571 $db_pass = $this->getConfigValue('database', 'password');
572 $db_data = $this->getConfigValue('database', 'database');
573 $charset = $this->getConfigValue('database', 'charset');
575 // Use environment variables for mysql if they are set beforehand
576 if (!empty(getenv('MYSQL_HOST'))
577 && (!empty(getenv('MYSQL_USERNAME')) || !empty(getenv('MYSQL_USER')))
578 && getenv('MYSQL_PASSWORD') !== false
579 && !empty(getenv('MYSQL_DATABASE')))
581 $db_host = getenv('MYSQL_HOST');
582 if (!empty(getenv('MYSQL_PORT'))) {
583 $db_host .= ':' . getenv('MYSQL_PORT');
585 if (!empty(getenv('MYSQL_USERNAME'))) {
586 $db_user = getenv('MYSQL_USERNAME');
588 $db_user = getenv('MYSQL_USER');
590 $db_pass = (string) getenv('MYSQL_PASSWORD');
591 $db_data = getenv('MYSQL_DATABASE');
594 $stamp1 = microtime(true);
596 DBA::connect($db_host, $db_user, $db_pass, $db_data, $charset);
597 unset($db_host, $db_user, $db_pass, $db_data, $charset);
599 $this->saveTimestamp($stamp1, 'network');
603 * @brief Returns the base filesystem path of the App
605 * It first checks for the internal variable, then for DOCUMENT_ROOT and
610 public function getBasePath()
612 $basepath = $this->basePath;
615 $basepath = Config::get('system', 'basepath');
618 if (!$basepath && x($_SERVER, 'DOCUMENT_ROOT')) {
619 $basepath = $_SERVER['DOCUMENT_ROOT'];
622 if (!$basepath && x($_SERVER, 'PWD')) {
623 $basepath = $_SERVER['PWD'];
626 return self::getRealPath($basepath);
630 * @brief Returns a normalized file path
632 * This is a wrapper for the "realpath" function.
633 * That function cannot detect the real path when some folders aren't readable.
634 * Since this could happen with some hosters we need to handle this.
636 * @param string $path The path that is about to be normalized
637 * @return string normalized path - when possible
639 public static function getRealPath($path)
641 $normalized = realpath($path);
643 if (!is_bool($normalized)) {
650 public function getScheme()
652 return $this->scheme;
656 * @brief Retrieves the Friendica instance base URL
658 * This function assembles the base URL from multiple parts:
659 * - Protocol is determined either by the request or a combination of
660 * system.ssl_policy and the $ssl parameter.
661 * - Host name is determined either by system.hostname or inferred from request
662 * - Path is inferred from SCRIPT_NAME
664 * Note: $ssl parameter value doesn't directly correlate with the resulting protocol
666 * @param bool $ssl Whether to append http or https under SSL_POLICY_SELFSIGN
667 * @return string Friendica server base URL
669 public function getBaseURL($ssl = false)
671 $scheme = $this->scheme;
673 if (Config::get('system', 'ssl_policy') == SSL_POLICY_FULL) {
677 // Basically, we have $ssl = true on any links which can only be seen by a logged in user
678 // (and also the login link). Anything seen by an outsider will have it turned off.
680 if (Config::get('system', 'ssl_policy') == SSL_POLICY_SELFSIGN) {
688 if (Config::get('config', 'hostname') != '') {
689 $this->hostname = Config::get('config', 'hostname');
692 return $scheme . '://' . $this->hostname . (!empty($this->getURLPath()) ? '/' . $this->getURLPath() : '' );
696 * @brief Initializes the baseurl components
698 * Clears the baseurl cache to prevent inconsistencies
702 public function setBaseURL($url)
704 $parsed = @parse_url($url);
708 if (!empty($parsed['scheme'])) {
709 $this->scheme = $parsed['scheme'];
712 if (!empty($parsed['host'])) {
713 $hostname = $parsed['host'];
716 if (x($parsed, 'port')) {
717 $hostname .= ':' . $parsed['port'];
719 if (x($parsed, 'path')) {
720 $this->urlPath = trim($parsed['path'], '\\/');
723 if (file_exists($this->getBasePath() . DIRECTORY_SEPARATOR . '.htpreconfig.php')) {
724 include $this->getBasePath() . DIRECTORY_SEPARATOR . '.htpreconfig.php';
727 if (Config::get('config', 'hostname') != '') {
728 $this->hostname = Config::get('config', 'hostname');
731 if (!isset($this->hostname) || ($this->hostname == '')) {
732 $this->hostname = $hostname;
737 public function getHostName()
739 if (Config::get('config', 'hostname') != '') {
740 $this->hostname = Config::get('config', 'hostname');
743 return $this->hostname;
746 public function getURLPath()
748 return $this->urlPath;
751 public function setPagerTotal($n)
753 $this->pager['total'] = intval($n);
756 public function setPagerItemsPage($n)
758 $this->pager['itemspage'] = ((intval($n) > 0) ? intval($n) : 0);
759 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
762 public function setPagerPage($n)
764 $this->pager['page'] = $n;
765 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
769 * Initializes App->page['htmlhead'].
774 * - Registered stylesheets (through App->registerStylesheet())
775 * - Infinite scroll data
776 * - head.tpl template
778 public function initHead()
780 $interval = ((local_user()) ? PConfig::get(local_user(), 'system', 'update_interval') : 40000);
782 // If the update is 'deactivated' set it to the highest integer number (~24 days)
784 $interval = 2147483647;
787 if ($interval < 10000) {
791 // compose the page title from the sitename and the
792 // current module called
793 if (!$this->module == '') {
794 $this->page['title'] = $this->config['sitename'] . ' (' . $this->module . ')';
796 $this->page['title'] = $this->config['sitename'];
799 if (!empty($this->theme['stylesheet'])) {
800 $stylesheet = $this->theme['stylesheet'];
802 $stylesheet = $this->getCurrentThemeStylesheetPath();
805 $this->registerStylesheet($stylesheet);
807 $shortcut_icon = Config::get('system', 'shortcut_icon');
808 if ($shortcut_icon == '') {
809 $shortcut_icon = 'images/friendica-32.png';
812 $touch_icon = Config::get('system', 'touch_icon');
813 if ($touch_icon == '') {
814 $touch_icon = 'images/friendica-128.png';
817 // get data wich is needed for infinite scroll on the network page
818 $infinite_scroll = infinite_scroll_data($this->module);
820 Core\Addon::callHooks('head', $this->page['htmlhead']);
822 $tpl = get_markup_template('head.tpl');
823 /* put the head template at the beginning of page['htmlhead']
824 * since the code added by the modules frequently depends on it
827 $this->page['htmlhead'] = replace_macros($tpl, [
828 '$baseurl' => $this->getBaseURL(),
829 '$local_user' => local_user(),
830 '$generator' => 'Friendica' . ' ' . FRIENDICA_VERSION,
831 '$delitem' => L10n::t('Delete this item?'),
832 '$showmore' => L10n::t('show more'),
833 '$showfewer' => L10n::t('show fewer'),
834 '$update_interval' => $interval,
835 '$shortcut_icon' => $shortcut_icon,
836 '$touch_icon' => $touch_icon,
837 '$infinite_scroll' => $infinite_scroll,
838 '$block_public' => intval(Config::get('system', 'block_public')),
839 '$stylesheets' => $this->stylesheets,
840 ]) . $this->page['htmlhead'];
844 * Initializes App->page['footer'].
847 * - Javascript homebase
848 * - Mobile toggle link
849 * - Registered footer scripts (through App->registerFooterScript())
850 * - footer.tpl template
852 public function initFooter()
854 // If you're just visiting, let javascript take you home
855 if (!empty($_SESSION['visitor_home'])) {
856 $homebase = $_SESSION['visitor_home'];
857 } elseif (local_user()) {
858 $homebase = 'profile/' . $this->user['nickname'];
861 if (isset($homebase)) {
862 $this->page['footer'] .= '<script>var homebase="' . $homebase . '";</script>' . "\n";
866 * Add a "toggle mobile" link if we're using a mobile device
868 if ($this->is_mobile || $this->is_tablet) {
869 if (isset($_SESSION['show-mobile']) && !$_SESSION['show-mobile']) {
870 $link = 'toggle_mobile?address=' . curPageURL();
872 $link = 'toggle_mobile?off=1&address=' . curPageURL();
874 $this->page['footer'] .= replace_macros(get_markup_template("toggle_mobile_footer.tpl"), [
875 '$toggle_link' => $link,
876 '$toggle_text' => Core\L10n::t('toggle mobile')
880 Core\Addon::callHooks('footer', $this->page['footer']);
882 $tpl = get_markup_template('footer.tpl');
883 $this->page['footer'] = replace_macros($tpl, [
884 '$baseurl' => $this->getBaseURL(),
885 '$footerScripts' => $this->footerScripts,
886 ]) . $this->page['footer'];
890 * @brief Removes the base url from an url. This avoids some mixed content problems.
892 * @param string $origURL
894 * @return string The cleaned url
896 public function removeBaseURL($origURL)
898 // Remove the hostname from the url if it is an internal link
899 $nurl = normalise_link($origURL);
900 $base = normalise_link($this->getBaseURL());
901 $url = str_replace($base . '/', '', $nurl);
903 // if it is an external link return the orignal value
904 if ($url == normalise_link($origURL)) {
912 * @brief Register template engine class
914 * @param string $class
916 private function registerTemplateEngine($class)
918 $v = get_class_vars($class);
921 $this->template_engines[$name] = $class;
923 echo "template engine <tt>$class</tt> cannot be registered without a name.\n";
929 * @brief Return template engine instance.
931 * If $name is not defined, return engine defined by theme,
934 * @return object Template Engine instance
936 public function getTemplateEngine()
938 $template_engine = 'smarty3';
939 if (x($this->theme, 'template_engine')) {
940 $template_engine = $this->theme['template_engine'];
943 if (isset($this->template_engines[$template_engine])) {
944 if (isset($this->template_engine_instance[$template_engine])) {
945 return $this->template_engine_instance[$template_engine];
947 $class = $this->template_engines[$template_engine];
949 $this->template_engine_instance[$template_engine] = $obj;
954 echo "template engine <tt>$template_engine</tt> is not registered!\n";
959 * @brief Returns the active template engine.
961 * @return string the active template engine
963 public function getActiveTemplateEngine()
965 return $this->theme['template_engine'];
969 * sets the active template engine
971 * @param string $engine the template engine (default is Smarty3)
973 public function setActiveTemplateEngine($engine = 'smarty3')
975 $this->theme['template_engine'] = $engine;
979 * Gets the right delimiter for a template engine
985 * @param string $engine The template engine (default is Smarty3)
987 * @return string the right delimiter
989 public function getTemplateLeftDelimiter($engine = 'smarty3')
991 return $this->ldelim[$engine];
995 * Gets the left delimiter for a template engine
1001 * @param string $engine The template engine (default is Smarty3)
1003 * @return string the left delimiter
1005 public function getTemplateRightDelimiter($engine = 'smarty3')
1007 return $this->rdelim[$engine];
1011 * Saves a timestamp for a value - f.e. a call
1012 * Necessary for profiling Friendica
1014 * @param int $timestamp the Timestamp
1015 * @param string $value A value to profile
1017 public function saveTimestamp($timestamp, $value)
1019 if (!isset($this->config['system']['profiler']) || !$this->config['system']['profiler']) {
1023 $duration = (float) (microtime(true) - $timestamp);
1025 if (!isset($this->performance[$value])) {
1026 // Prevent ugly E_NOTICE
1027 $this->performance[$value] = 0;
1030 $this->performance[$value] += (float) $duration;
1031 $this->performance['marktime'] += (float) $duration;
1033 $callstack = System::callstack();
1035 if (!isset($this->callstack[$value][$callstack])) {
1036 // Prevent ugly E_NOTICE
1037 $this->callstack[$value][$callstack] = 0;
1040 $this->callstack[$value][$callstack] += (float) $duration;
1044 * Returns the current UserAgent as a String
1046 * @return string the UserAgent as a String
1048 public function getUserAgent()
1051 FRIENDICA_PLATFORM . " '" .
1052 FRIENDICA_CODENAME . "' " .
1053 FRIENDICA_VERSION . '-' .
1054 DB_UPDATE_VERSION . '; ' .
1055 $this->getBaseURL();
1059 * Checks, if the call is from the Friendica App
1062 * The friendica client has problems with the GUID in the notify. this is some workaround
1064 private function checkFriendicaApp()
1067 $this->isFriendicaApp = isset($_SERVER['HTTP_USER_AGENT']) && $_SERVER['HTTP_USER_AGENT'] == 'Apache-HttpClient/UNAVAILABLE (java 1.4)';
1071 * Is the call via the Friendica app? (not a "normale" call)
1073 * @return bool true if it's from the Friendica app
1075 public function isFriendicaApp()
1077 return $this->isFriendicaApp;
1081 * @brief Checks if the site is called via a backend process
1083 * This isn't a perfect solution. But we need this check very early.
1084 * So we cannot wait until the modules are loaded.
1086 * @param string $backend true, if the backend flag was set during App initialization
1089 private function checkBackend($backend) {
1090 static $backends = [
1112 // Check if current module is in backend or backend flag is set
1113 $this->isBackend = (in_array($this->module, $backends) || $backend || $this->isBackend);
1117 * Returns true, if the call is from a backend node (f.e. from a worker)
1119 * @return bool Is it a known backend?
1121 public function isBackend()
1123 return $this->isBackend;
1127 * @brief Checks if the maximum number of database processes is reached
1129 * @return bool Is the limit reached?
1131 public function isMaxProcessesReached()
1133 // Deactivated, needs more investigating if this check really makes sense
1137 * Commented out to suppress static analyzer issues
1139 if ($this->is_backend()) {
1140 $process = 'backend';
1141 $max_processes = Config::get('system', 'max_processes_backend');
1142 if (intval($max_processes) == 0) {
1146 $process = 'frontend';
1147 $max_processes = Config::get('system', 'max_processes_frontend');
1148 if (intval($max_processes) == 0) {
1149 $max_processes = 20;
1153 $processlist = DBA::processlist();
1154 if ($processlist['list'] != '') {
1155 logger('Processcheck: Processes: ' . $processlist['amount'] . ' - Processlist: ' . $processlist['list'], LOGGER_DEBUG);
1157 if ($processlist['amount'] > $max_processes) {
1158 logger('Processcheck: Maximum number of processes for ' . $process . ' tasks (' . $max_processes . ') reached.', LOGGER_DEBUG);
1167 * @brief Checks if the minimal memory is reached
1169 * @return bool Is the memory limit reached?
1171 public function isMinMemoryReached()
1173 $min_memory = Config::get('system', 'min_memory', 0);
1174 if ($min_memory == 0) {
1178 if (!is_readable('/proc/meminfo')) {
1182 $memdata = explode("\n", file_get_contents('/proc/meminfo'));
1185 foreach ($memdata as $line) {
1186 $data = explode(':', $line);
1187 if (count($data) != 2) {
1190 list($key, $val) = $data;
1191 $meminfo[$key] = (int) trim(str_replace('kB', '', $val));
1192 $meminfo[$key] = (int) ($meminfo[$key] / 1024);
1195 if (!isset($meminfo['MemAvailable']) || !isset($meminfo['MemFree'])) {
1199 $free = $meminfo['MemAvailable'] + $meminfo['MemFree'];
1201 $reached = ($free < $min_memory);
1204 logger('Minimal memory reached: ' . $free . '/' . $meminfo['MemTotal'] . ' - limit ' . $min_memory, LOGGER_DEBUG);
1211 * @brief Checks if the maximum load is reached
1213 * @return bool Is the load reached?
1215 public function isMaxLoadReached()
1217 if ($this->isBackend()) {
1218 $process = 'backend';
1219 $maxsysload = intval(Config::get('system', 'maxloadavg'));
1220 if ($maxsysload < 1) {
1224 $process = 'frontend';
1225 $maxsysload = intval(Config::get('system', 'maxloadavg_frontend'));
1226 if ($maxsysload < 1) {
1231 $load = System::currentLoad();
1233 if (intval($load) > $maxsysload) {
1234 logger('system: load ' . $load . ' for ' . $process . ' tasks (' . $maxsysload . ') too high.');
1242 * Executes a child process with 'proc_open'
1244 * @param string $command The command to execute
1245 * @param array $args Arguments to pass to the command ( [ 'key' => value, 'key2' => value2, ... ]
1247 public function proc_run($command, $args)
1249 if (!function_exists('proc_open')) {
1253 $cmdline = $this->getConfigValue('config', 'php_path', 'php') . ' ' . escapeshellarg($command);
1255 foreach ($args as $key => $value) {
1256 if (!is_null($value) && is_bool($value) && !$value) {
1260 $cmdline .= ' --' . $key;
1261 if (!is_null($value) && !is_bool($value)) {
1262 $cmdline .= ' ' . $value;
1266 if ($this->isMinMemoryReached()) {
1270 if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
1271 $resource = proc_open('cmd /c start /b ' . $cmdline, [], $foo, $this->getBasePath());
1273 $resource = proc_open($cmdline . ' &', [], $foo, $this->getBasePath());
1275 if (!is_resource($resource)) {
1276 logger('We got no resource for command ' . $cmdline, LOGGER_DEBUG);
1279 proc_close($resource);
1283 * @brief Returns the system user that is executing the script
1285 * This mostly returns something like "www-data".
1287 * @return string system username
1289 private static function getSystemUser()
1291 if (!function_exists('posix_getpwuid') || !function_exists('posix_geteuid')) {
1295 $processUser = posix_getpwuid(posix_geteuid());
1296 return $processUser['name'];
1300 * @brief Checks if a given directory is usable for the system
1302 * @return boolean the directory is usable
1304 public static function isDirectoryUsable($directory, $check_writable = true)
1306 if ($directory == '') {
1307 logger('Directory is empty. This shouldn\'t happen.', LOGGER_DEBUG);
1311 if (!file_exists($directory)) {
1312 logger('Path "' . $directory . '" does not exist for user ' . self::getSystemUser(), LOGGER_DEBUG);
1316 if (is_file($directory)) {
1317 logger('Path "' . $directory . '" is a file for user ' . self::getSystemUser(), LOGGER_DEBUG);
1321 if (!is_dir($directory)) {
1322 logger('Path "' . $directory . '" is not a directory for user ' . self::getSystemUser(), LOGGER_DEBUG);
1326 if ($check_writable && !is_writable($directory)) {
1327 logger('Path "' . $directory . '" is not writable for user ' . self::getSystemUser(), LOGGER_DEBUG);
1335 * @param string $cat Config category
1336 * @param string $k Config key
1337 * @param mixed $default Default value if it isn't set
1339 * @return string Returns the value of the Config entry
1341 public function getConfigValue($cat, $k, $default = null)
1345 if ($cat === 'config') {
1346 if (isset($this->config[$k])) {
1347 $return = $this->config[$k];
1350 if (isset($this->config[$cat][$k])) {
1351 $return = $this->config[$cat][$k];
1359 * Sets a default value in the config cache. Ignores already existing keys.
1361 * @param string $cat Config category
1362 * @param string $k Config key
1363 * @param mixed $v Default value to set
1365 private function setDefaultConfigValue($cat, $k, $v)
1367 if (!isset($this->config[$cat][$k])) {
1368 $this->setConfigValue($cat, $k, $v);
1373 * Sets a value in the config cache. Accepts raw output from the config table
1375 * @param string $cat Config category
1376 * @param string $k Config key
1377 * @param mixed $v Value to set
1379 public function setConfigValue($cat, $k, $v)
1381 // Only arrays are serialized in database, so we have to unserialize sparingly
1382 $value = is_string($v) && preg_match("|^a:[0-9]+:{.*}$|s", $v) ? unserialize($v) : $v;
1384 if ($cat === 'config') {
1385 $this->config[$k] = $value;
1387 if (!isset($this->config[$cat])) {
1388 $this->config[$cat] = [];
1391 $this->config[$cat][$k] = $value;
1396 * Deletes a value from the config cache
1398 * @param string $cat Config category
1399 * @param string $k Config key
1401 public function deleteConfigValue($cat, $k)
1403 if ($cat === 'config') {
1404 if (isset($this->config[$k])) {
1405 unset($this->config[$k]);
1408 if (isset($this->config[$cat][$k])) {
1409 unset($this->config[$cat][$k]);
1416 * Retrieves a value from the user config cache
1418 * @param int $uid User Id
1419 * @param string $cat Config category
1420 * @param string $k Config key
1421 * @param mixed $default Default value if key isn't set
1423 * @return string The value of the config entry
1425 public function getPConfigValue($uid, $cat, $k, $default = null)
1429 if (isset($this->config[$uid][$cat][$k])) {
1430 $return = $this->config[$uid][$cat][$k];
1437 * Sets a value in the user config cache
1439 * Accepts raw output from the pconfig table
1441 * @param int $uid User Id
1442 * @param string $cat Config category
1443 * @param string $k Config key
1444 * @param mixed $v Value to set
1446 public function setPConfigValue($uid, $cat, $k, $v)
1448 // Only arrays are serialized in database, so we have to unserialize sparingly
1449 $value = is_string($v) && preg_match("|^a:[0-9]+:{.*}$|s", $v) ? unserialize($v) : $v;
1451 if (!isset($this->config[$uid]) || !is_array($this->config[$uid])) {
1452 $this->config[$uid] = [];
1455 if (!isset($this->config[$uid][$cat]) || !is_array($this->config[$uid][$cat])) {
1456 $this->config[$uid][$cat] = [];
1459 $this->config[$uid][$cat][$k] = $value;
1463 * Deletes a value from the user config cache
1465 * @param int $uid User Id
1466 * @param string $cat Config category
1467 * @param string $k Config key
1469 public function deletePConfigValue($uid, $cat, $k)
1471 if (isset($this->config[$uid][$cat][$k])) {
1472 unset($this->config[$uid][$cat][$k]);
1477 * Generates the site's default sender email address
1481 public function getSenderEmailAddress()
1483 $sender_email = Config::get('config', 'sender_email');
1484 if (empty($sender_email)) {
1485 $hostname = $this->getHostName();
1486 if (strpos($hostname, ':')) {
1487 $hostname = substr($hostname, 0, strpos($hostname, ':'));
1490 $sender_email = 'noreply@' . $hostname;
1493 return $sender_email;
1497 * Returns the current theme name.
1499 * @return string the name of the current theme
1501 public function getCurrentTheme()
1503 if ($this->getMode()->isInstall()) {
1507 //// @TODO Compute the current theme only once (this behavior has
1508 /// already been implemented, but it didn't work well -
1509 /// https://github.com/friendica/friendica/issues/5092)
1510 $this->computeCurrentTheme();
1512 return $this->currentTheme;
1516 * Computes the current theme name based on the node settings, the user settings and the device type
1520 private function computeCurrentTheme()
1522 $system_theme = Config::get('system', 'theme');
1523 if (!$system_theme) {
1524 throw new Exception(L10n::t('No system theme config value set.'));
1528 $this->currentTheme = $system_theme;
1530 $allowed_themes = explode(',', Config::get('system', 'allowed_themes', $system_theme));
1533 // Find the theme that belongs to the user whose stuff we are looking at
1534 if ($this->profile_uid && ($this->profile_uid != local_user())) {
1535 // Allow folks to override user themes and always use their own on their own site.
1536 // This works only if the user is on the same server
1537 $user = DBA::selectFirst('user', ['theme'], ['uid' => $this->profile_uid]);
1538 if (DBA::isResult($user) && !PConfig::get(local_user(), 'system', 'always_my_theme')) {
1539 $page_theme = $user['theme'];
1543 $user_theme = Core\Session::get('theme', $system_theme);
1545 // Specific mobile theme override
1546 if (($this->is_mobile || $this->is_tablet) && Core\Session::get('show-mobile', true)) {
1547 $system_mobile_theme = Config::get('system', 'mobile-theme');
1548 $user_mobile_theme = Core\Session::get('mobile-theme', $system_mobile_theme);
1550 // --- means same mobile theme as desktop
1551 if (!empty($user_mobile_theme) && $user_mobile_theme !== '---') {
1552 $user_theme = $user_mobile_theme;
1557 $theme_name = $page_theme;
1559 $theme_name = $user_theme;
1563 && in_array($theme_name, $allowed_themes)
1564 && (file_exists('view/theme/' . $theme_name . '/style.css')
1565 || file_exists('view/theme/' . $theme_name . '/style.php'))
1567 $this->currentTheme = $theme_name;
1572 * @brief Return full URL to theme which is currently in effect.
1574 * Provide a sane default if nothing is chosen or the specified theme does not exist.
1578 public function getCurrentThemeStylesheetPath()
1580 return Core\Theme::getStylesheetPath($this->getCurrentTheme());
1584 * Check if request was an AJAX (xmlhttprequest) request.
1586 * @return boolean true if it was an AJAX request
1588 public function isAjax()
1590 return $this->isAjax;
1594 * Returns the value of a argv key
1595 * TODO there are a lot of $a->argv usages in combination with defaults() which can be replaced with this method
1597 * @param int $position the position of the argument
1598 * @param mixed $default the default value if not found
1600 * @return mixed returns the value of the argument
1602 public function getArgumentValue($position, $default = '')
1604 if (array_key_exists($position, $this->argv)) {
1605 return $this->argv[$position];