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 basepath
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 type $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 $this->urlpath = $this->getConfigValue('system', 'urlpath');
527 /* SCRIPT_URL gives /path/to/friendica/module/parameter
528 * QUERY_STRING gives pagename=module/parameter
530 * To get /path/to/friendica we perform dirname() for as many levels as there are slashes in the QUERY_STRING
532 if (!empty($_SERVER['SCRIPT_URL'])) {
534 if (!empty($_SERVER['QUERY_STRING'])) {
535 $path = trim(dirname($_SERVER['SCRIPT_URL'], substr_count(trim($_SERVER['QUERY_STRING'], '/'), '/') + 1), '/');
538 $path = trim($_SERVER['SCRIPT_URL'], '/');
541 if ($path && $path != $this->urlpath) {
542 $this->urlpath = $path;
547 public function loadDatabase()
549 if (DBA::connected()) {
553 $db_host = $this->getConfigValue('database', 'hostname');
554 $db_user = $this->getConfigValue('database', 'username');
555 $db_pass = $this->getConfigValue('database', 'password');
556 $db_data = $this->getConfigValue('database', 'database');
557 $charset = $this->getConfigValue('database', 'charset');
559 // Use environment variables for mysql if they are set beforehand
560 if (!empty(getenv('MYSQL_HOST'))
561 && (!empty(getenv('MYSQL_USERNAME')) || !empty(getenv('MYSQL_USER')))
562 && getenv('MYSQL_PASSWORD') !== false
563 && !empty(getenv('MYSQL_DATABASE')))
565 $db_host = getenv('MYSQL_HOST');
566 if (!empty(getenv('MYSQL_PORT'))) {
567 $db_host .= ':' . getenv('MYSQL_PORT');
569 if (!empty(getenv('MYSQL_USERNAME'))) {
570 $db_user = getenv('MYSQL_USERNAME');
572 $db_user = getenv('MYSQL_USER');
574 $db_pass = (string) getenv('MYSQL_PASSWORD');
575 $db_data = getenv('MYSQL_DATABASE');
578 $stamp1 = microtime(true);
580 DBA::connect($db_host, $db_user, $db_pass, $db_data, $charset);
581 unset($db_host, $db_user, $db_pass, $db_data, $charset);
583 $this->saveTimestamp($stamp1, 'network');
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 getBasePath()
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::getRealPath($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 getRealPath($path)
625 $normalized = realpath($path);
627 if (!is_bool($normalized)) {
634 public function getScheme()
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 getBaseURL($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->getURLpath()) ? '/' . $this->getURLpath() : '' );
680 * @brief Initializes the baseurl components
682 * Clears the baseurl cache to prevent inconsistencies
686 public function setBaseURL($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->getBasePath() . DIRECTORY_SEPARATOR . '.htpreconfig.php')) {
708 include $this->getBasePath() . 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 getHostName()
723 if (Config::get('config', 'hostname') != '') {
724 $this->hostname = Config::get('config', 'hostname');
727 return $this->hostname;
730 public function getURLpath()
732 return $this->urlpath;
735 public function setPagerTotal($n)
737 $this->pager['total'] = intval($n);
740 public function setPagerItemsPage($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 setPagerPage($n)
748 $this->pager['page'] = $n;
749 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
753 * Initializes App->page['htmlhead'].
758 * - Registered stylesheets (through App->registerStylesheet())
759 * - Infinite scroll data
760 * - head.tpl template
762 public function initHead()
764 $interval = ((local_user()) ? PConfig::get(local_user(), 'system', 'update_interval') : 40000);
766 // If the update is 'deactivated' set it to the highest integer number (~24 days)
768 $interval = 2147483647;
771 if ($interval < 10000) {
775 // compose the page title from the sitename and the
776 // current module called
777 if (!$this->module == '') {
778 $this->page['title'] = $this->config['sitename'] . ' (' . $this->module . ')';
780 $this->page['title'] = $this->config['sitename'];
783 if (!empty($this->theme['stylesheet'])) {
784 $stylesheet = $this->theme['stylesheet'];
786 $stylesheet = $this->getCurrentThemeStylesheetPath();
789 $this->registerStylesheet($stylesheet);
791 $shortcut_icon = Config::get('system', 'shortcut_icon');
792 if ($shortcut_icon == '') {
793 $shortcut_icon = 'images/friendica-32.png';
796 $touch_icon = Config::get('system', 'touch_icon');
797 if ($touch_icon == '') {
798 $touch_icon = 'images/friendica-128.png';
801 // get data wich is needed for infinite scroll on the network page
802 $infinite_scroll = infinite_scroll_data($this->module);
804 Core\Addon::callHooks('head', $this->page['htmlhead']);
806 $tpl = get_markup_template('head.tpl');
807 /* put the head template at the beginning of page['htmlhead']
808 * since the code added by the modules frequently depends on it
811 $this->page['htmlhead'] = replace_macros($tpl, [
812 '$baseurl' => $this->getBaseURL(),
813 '$local_user' => local_user(),
814 '$generator' => 'Friendica' . ' ' . FRIENDICA_VERSION,
815 '$delitem' => L10n::t('Delete this item?'),
816 '$showmore' => L10n::t('show more'),
817 '$showfewer' => L10n::t('show fewer'),
818 '$update_interval' => $interval,
819 '$shortcut_icon' => $shortcut_icon,
820 '$touch_icon' => $touch_icon,
821 '$infinite_scroll' => $infinite_scroll,
822 '$block_public' => intval(Config::get('system', 'block_public')),
823 '$stylesheets' => $this->stylesheets,
824 ]) . $this->page['htmlhead'];
828 * Initializes App->page['footer'].
831 * - Javascript homebase
832 * - Mobile toggle link
833 * - Registered footer scripts (through App->registerFooterScript())
834 * - footer.tpl template
836 public function initFooter()
838 // If you're just visiting, let javascript take you home
839 if (!empty($_SESSION['visitor_home'])) {
840 $homebase = $_SESSION['visitor_home'];
841 } elseif (local_user()) {
842 $homebase = 'profile/' . $this->user['nickname'];
845 if (isset($homebase)) {
846 $this->page['footer'] .= '<script>var homebase="' . $homebase . '";</script>' . "\n";
850 * Add a "toggle mobile" link if we're using a mobile device
852 if ($this->is_mobile || $this->is_tablet) {
853 if (isset($_SESSION['show-mobile']) && !$_SESSION['show-mobile']) {
854 $link = 'toggle_mobile?address=' . curPageURL();
856 $link = 'toggle_mobile?off=1&address=' . curPageURL();
858 $this->page['footer'] .= replace_macros(get_markup_template("toggle_mobile_footer.tpl"), [
859 '$toggle_link' => $link,
860 '$toggle_text' => Core\L10n::t('toggle mobile')
864 Core\Addon::callHooks('footer', $this->page['footer']);
866 $tpl = get_markup_template('footer.tpl');
867 $this->page['footer'] = replace_macros($tpl, [
868 '$baseurl' => $this->getBaseURL(),
869 '$footerScripts' => $this->footerScripts,
870 ]) . $this->page['footer'];
874 * @brief Removes the base url from an url. This avoids some mixed content problems.
876 * @param string $orig_url
878 * @return string The cleaned url
880 public function removeBaseURL($orig_url)
882 // Remove the hostname from the url if it is an internal link
883 $nurl = normalise_link($orig_url);
884 $base = normalise_link($this->getBaseURL());
885 $url = str_replace($base . '/', '', $nurl);
887 // if it is an external link return the orignal value
888 if ($url == normalise_link($orig_url)) {
896 * @brief Register template engine class
898 * @param string $class
900 private function registerTemplateEngine($class)
902 $v = get_class_vars($class);
905 $this->template_engines[$name] = $class;
907 echo "template engine <tt>$class</tt> cannot be registered without a name.\n";
913 * @brief Return template engine instance.
915 * If $name is not defined, return engine defined by theme,
918 * @return object Template Engine instance
920 public function getTemplateEngine()
922 $template_engine = 'smarty3';
923 if (x($this->theme, 'template_engine')) {
924 $template_engine = $this->theme['template_engine'];
927 if (isset($this->template_engines[$template_engine])) {
928 if (isset($this->template_engine_instance[$template_engine])) {
929 return $this->template_engine_instance[$template_engine];
931 $class = $this->template_engines[$template_engine];
933 $this->template_engine_instance[$template_engine] = $obj;
938 echo "template engine <tt>$template_engine</tt> is not registered!\n";
943 * @brief Returns the active template engine.
947 public function getActiveTemplateEngine()
949 return $this->theme['template_engine'];
952 public function setActiveTemplateEngine($engine = 'smarty3')
954 $this->theme['template_engine'] = $engine;
957 public function getTemplateLdelim($engine = 'smarty3')
959 return $this->ldelim[$engine];
962 public function getTemplateRdelim($engine = 'smarty3')
964 return $this->rdelim[$engine];
968 * Saves a timestamp for a value - f.e. a call
969 * Necessary for profiling Friendica
971 * @param int $timestamp the Timestamp
972 * @param string $value A value to profile
974 public function saveTimestamp($timestamp, $value)
976 if (!isset($this->config['system']['profiler']) || !$this->config['system']['profiler']) {
980 $duration = (float) (microtime(true) - $timestamp);
982 if (!isset($this->performance[$value])) {
983 // Prevent ugly E_NOTICE
984 $this->performance[$value] = 0;
987 $this->performance[$value] += (float) $duration;
988 $this->performance['marktime'] += (float) $duration;
990 $callstack = System::callstack();
992 if (!isset($this->callstack[$value][$callstack])) {
993 // Prevent ugly E_NOTICE
994 $this->callstack[$value][$callstack] = 0;
997 $this->callstack[$value][$callstack] += (float) $duration;
1001 * Returns the current UserAgent as a String
1003 * @return string the UserAgent as a String
1005 public function getUserAgent()
1008 FRIENDICA_PLATFORM . " '" .
1009 FRIENDICA_CODENAME . "' " .
1010 FRIENDICA_VERSION . '-' .
1011 DB_UPDATE_VERSION . '; ' .
1012 $this->getBaseURL();
1016 * Checks, if the call is from the Friendica App
1019 * The friendica client has problems with the GUID in the notify. this is some workaround
1021 private function checkFriendicaApp()
1024 $this->isFriendicaApp = isset($_SERVER['HTTP_USER_AGENT']) && $_SERVER['HTTP_USER_AGENT'] == 'Apache-HttpClient/UNAVAILABLE (java 1.4)';
1028 * Is the call via the Friendica app? (not a "normale" call)
1030 * @return bool true if it's from the Friendica app
1032 public function isFriendicaApp()
1034 return $this->isFriendicaApp;
1038 * @brief Checks if the site is called via a backend process
1040 * This isn't a perfect solution. But we need this check very early.
1041 * So we cannot wait until the modules are loaded.
1044 private function checkBackend($backend) {
1045 static $backends = [
1067 // Check if current module is in backend or backend flag is set
1068 $this->isBackend = (in_array($this->module, $backends) || $this->isBackend);
1072 * Returns true, if the call is from a backend node (f.e. from a worker)
1074 * @return bool Is it a known backend?
1076 public function isBackend()
1078 return $this->isBackend;
1082 * @brief Checks if the maximum number of database processes is reached
1084 * @return bool Is the limit reached?
1086 public function isMaxProcessesReached()
1088 // Deactivated, needs more investigating if this check really makes sense
1092 * Commented out to suppress static analyzer issues
1094 if ($this->is_backend()) {
1095 $process = 'backend';
1096 $max_processes = Config::get('system', 'max_processes_backend');
1097 if (intval($max_processes) == 0) {
1101 $process = 'frontend';
1102 $max_processes = Config::get('system', 'max_processes_frontend');
1103 if (intval($max_processes) == 0) {
1104 $max_processes = 20;
1108 $processlist = DBA::processlist();
1109 if ($processlist['list'] != '') {
1110 logger('Processcheck: Processes: ' . $processlist['amount'] . ' - Processlist: ' . $processlist['list'], LOGGER_DEBUG);
1112 if ($processlist['amount'] > $max_processes) {
1113 logger('Processcheck: Maximum number of processes for ' . $process . ' tasks (' . $max_processes . ') reached.', LOGGER_DEBUG);
1122 * @brief Checks if the minimal memory is reached
1124 * @return bool Is the memory limit reached?
1126 public function isMinMemoryReached()
1128 $min_memory = Config::get('system', 'min_memory', 0);
1129 if ($min_memory == 0) {
1133 if (!is_readable('/proc/meminfo')) {
1137 $memdata = explode("\n", file_get_contents('/proc/meminfo'));
1140 foreach ($memdata as $line) {
1141 $data = explode(':', $line);
1142 if (count($data) != 2) {
1145 list($key, $val) = $data;
1146 $meminfo[$key] = (int) trim(str_replace('kB', '', $val));
1147 $meminfo[$key] = (int) ($meminfo[$key] / 1024);
1150 if (!isset($meminfo['MemAvailable']) || !isset($meminfo['MemFree'])) {
1154 $free = $meminfo['MemAvailable'] + $meminfo['MemFree'];
1156 $reached = ($free < $min_memory);
1159 logger('Minimal memory reached: ' . $free . '/' . $meminfo['MemTotal'] . ' - limit ' . $min_memory, LOGGER_DEBUG);
1166 * @brief Checks if the maximum load is reached
1168 * @return bool Is the load reached?
1170 public function isMaxLoadReached()
1172 if ($this->isBackend()) {
1173 $process = 'backend';
1174 $maxsysload = intval(Config::get('system', 'maxloadavg'));
1175 if ($maxsysload < 1) {
1179 $process = 'frontend';
1180 $maxsysload = intval(Config::get('system', 'maxloadavg_frontend'));
1181 if ($maxsysload < 1) {
1186 $load = current_load();
1188 if (intval($load) > $maxsysload) {
1189 logger('system: load ' . $load . ' for ' . $process . ' tasks (' . $maxsysload . ') too high.');
1197 * Executes a child process with 'proc_open'
1199 * @param string $command The command to execute
1200 * @param array $args Arguments to pass to the command ( [ 'key' => value, 'key2' => value2, ... ]
1202 public function proc_run($command, $args)
1204 if (!function_exists('proc_open')) {
1208 $cmdline = $this->getConfigValue('config', 'php_path', 'php') . ' ' . escapeshellarg($command);
1210 foreach ($args as $key => $value) {
1211 if (!is_null($value) && is_bool($value) && !$value) {
1215 $cmdline .= ' --' . $key;
1216 if (!is_null($value) && !is_bool($value)) {
1217 $cmdline .= ' ' . $value;
1221 if ($this->isMinMemoryReached()) {
1225 if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
1226 $resource = proc_open('cmd /c start /b ' . $cmdline, [], $foo, $this->getBasePath());
1228 $resource = proc_open($cmdline . ' &', [], $foo, $this->getBasePath());
1230 if (!is_resource($resource)) {
1231 logger('We got no resource for command ' . $cmdline, LOGGER_DEBUG);
1234 proc_close($resource);
1238 * @brief Returns the system user that is executing the script
1240 * This mostly returns something like "www-data".
1242 * @return string system username
1244 private static function getSystemUser()
1246 if (!function_exists('posix_getpwuid') || !function_exists('posix_geteuid')) {
1250 $processUser = posix_getpwuid(posix_geteuid());
1251 return $processUser['name'];
1255 * @brief Checks if a given directory is usable for the system
1257 * @return boolean the directory is usable
1259 public static function isDirectoryUsable($directory, $check_writable = true)
1261 if ($directory == '') {
1262 logger('Directory is empty. This shouldn\'t happen.', LOGGER_DEBUG);
1266 if (!file_exists($directory)) {
1267 logger('Path "' . $directory . '" does not exist for user ' . self::getSystemUser(), LOGGER_DEBUG);
1271 if (is_file($directory)) {
1272 logger('Path "' . $directory . '" is a file for user ' . self::getSystemUser(), LOGGER_DEBUG);
1276 if (!is_dir($directory)) {
1277 logger('Path "' . $directory . '" is not a directory for user ' . self::getSystemUser(), LOGGER_DEBUG);
1281 if ($check_writable && !is_writable($directory)) {
1282 logger('Path "' . $directory . '" is not writable for user ' . self::getSystemUser(), LOGGER_DEBUG);
1290 * @param string $cat Config category
1291 * @param string $k Config key
1292 * @param mixed $default Default value if it isn't set
1294 * @return string Returns the value of the Config entry
1296 public function getConfigValue($cat, $k, $default = null)
1300 if ($cat === 'config') {
1301 if (isset($this->config[$k])) {
1302 $return = $this->config[$k];
1305 if (isset($this->config[$cat][$k])) {
1306 $return = $this->config[$cat][$k];
1314 * Sets a default value in the config cache. Ignores already existing keys.
1316 * @param string $cat Config category
1317 * @param string $k Config key
1318 * @param mixed $v Default value to set
1320 private function setDefaultConfigValue($cat, $k, $v)
1322 if (!isset($this->config[$cat][$k])) {
1323 $this->setConfigValue($cat, $k, $v);
1328 * Sets a value in the config cache. Accepts raw output from the config table
1330 * @param string $cat Config category
1331 * @param string $k Config key
1332 * @param mixed $v Value to set
1334 public function setConfigValue($cat, $k, $v)
1336 // Only arrays are serialized in database, so we have to unserialize sparingly
1337 $value = is_string($v) && preg_match("|^a:[0-9]+:{.*}$|s", $v) ? unserialize($v) : $v;
1339 if ($cat === 'config') {
1340 $this->config[$k] = $value;
1342 if (!isset($this->config[$cat])) {
1343 $this->config[$cat] = [];
1346 $this->config[$cat][$k] = $value;
1351 * Deletes a value from the config cache
1353 * @param string $cat Config category
1354 * @param string $k Config key
1356 public function deleteConfigValue($cat, $k)
1358 if ($cat === 'config') {
1359 if (isset($this->config[$k])) {
1360 unset($this->config[$k]);
1363 if (isset($this->config[$cat][$k])) {
1364 unset($this->config[$cat][$k]);
1371 * Retrieves a value from the user config cache
1373 * @param int $uid User Id
1374 * @param string $cat Config category
1375 * @param string $k Config key
1376 * @param mixed $default Default value if key isn't set
1378 * @return string The value of the config entry
1380 public function getPConfigValue($uid, $cat, $k, $default = null)
1384 if (isset($this->config[$uid][$cat][$k])) {
1385 $return = $this->config[$uid][$cat][$k];
1392 * Sets a value in the user config cache
1394 * Accepts raw output from the pconfig table
1396 * @param int $uid User Id
1397 * @param string $cat Config category
1398 * @param string $k Config key
1399 * @param mixed $v Value to set
1401 public function setPConfigValue($uid, $cat, $k, $v)
1403 // Only arrays are serialized in database, so we have to unserialize sparingly
1404 $value = is_string($v) && preg_match("|^a:[0-9]+:{.*}$|s", $v) ? unserialize($v) : $v;
1406 if (!isset($this->config[$uid]) || !is_array($this->config[$uid])) {
1407 $this->config[$uid] = [];
1410 if (!isset($this->config[$uid][$cat]) || !is_array($this->config[$uid][$cat])) {
1411 $this->config[$uid][$cat] = [];
1414 $this->config[$uid][$cat][$k] = $value;
1418 * Deletes a value from the user config cache
1420 * @param int $uid User Id
1421 * @param string $cat Config category
1422 * @param string $k Config key
1424 public function deletePConfigValue($uid, $cat, $k)
1426 if (isset($this->config[$uid][$cat][$k])) {
1427 unset($this->config[$uid][$cat][$k]);
1432 * Generates the site's default sender email address
1436 public function getSenderEmailAddress()
1438 $sender_email = Config::get('config', 'sender_email');
1439 if (empty($sender_email)) {
1440 $hostname = $this->getHostName();
1441 if (strpos($hostname, ':')) {
1442 $hostname = substr($hostname, 0, strpos($hostname, ':'));
1445 $sender_email = 'noreply@' . $hostname;
1448 return $sender_email;
1452 * Returns the current theme name.
1454 * @return string the name of the current theme
1456 public function getCurrentTheme()
1458 if ($this->getMode()->isInstall()) {
1462 //// @TODO Compute the current theme only once (this behavior has
1463 /// already been implemented, but it didn't work well -
1464 /// https://github.com/friendica/friendica/issues/5092)
1465 $this->computeCurrentTheme();
1467 return $this->currentTheme;
1471 * Computes the current theme name based on the node settings, the user settings and the device type
1475 private function computeCurrentTheme()
1477 $system_theme = Config::get('system', 'theme');
1478 if (!$system_theme) {
1479 throw new Exception(L10n::t('No system theme config value set.'));
1483 $this->currentTheme = $system_theme;
1485 $allowed_themes = explode(',', Config::get('system', 'allowed_themes', $system_theme));
1488 // Find the theme that belongs to the user whose stuff we are looking at
1489 if ($this->profile_uid && ($this->profile_uid != local_user())) {
1490 // Allow folks to override user themes and always use their own on their own site.
1491 // This works only if the user is on the same server
1492 $user = DBA::selectFirst('user', ['theme'], ['uid' => $this->profile_uid]);
1493 if (DBA::isResult($user) && !PConfig::get(local_user(), 'system', 'always_my_theme')) {
1494 $page_theme = $user['theme'];
1498 $user_theme = Core\Session::get('theme', $system_theme);
1500 // Specific mobile theme override
1501 if (($this->is_mobile || $this->is_tablet) && Core\Session::get('show-mobile', true)) {
1502 $system_mobile_theme = Config::get('system', 'mobile-theme');
1503 $user_mobile_theme = Core\Session::get('mobile-theme', $system_mobile_theme);
1505 // --- means same mobile theme as desktop
1506 if (!empty($user_mobile_theme) && $user_mobile_theme !== '---') {
1507 $user_theme = $user_mobile_theme;
1512 $theme_name = $page_theme;
1514 $theme_name = $user_theme;
1518 && in_array($theme_name, $allowed_themes)
1519 && (file_exists('view/theme/' . $theme_name . '/style.css')
1520 || file_exists('view/theme/' . $theme_name . '/style.php'))
1522 $this->currentTheme = $theme_name;
1527 * @brief Return full URL to theme which is currently in effect.
1529 * Provide a sane default if nothing is chosen or the specified theme does not exist.
1533 public function getCurrentThemeStylesheetPath()
1535 return Core\Theme::getStylesheetPath($this->getCurrentTheme());