7 use Detection\MobileDetect;
11 use Friendica\Database\DBA;
12 use Friendica\Network\HTTPException\InternalServerErrorException;
14 require_once 'boot.php';
15 require_once 'include/text.php';
21 * @brief Our main application structure for the life of this page.
23 * Primarily deals with the URL that got us here
24 * and tries to make some sense of it, and
25 * stores our page contents and config storage
26 * and anything else that might need to be passed around
27 * before we spit the page out.
32 public $module_loaded = false;
33 public $module_class = null;
34 public $query_string = '';
48 public $error = false;
56 public $interactive = true;
58 public $addons_admin = [];
61 public $is_mobile = false;
62 public $is_tablet = false;
63 public $performance = [];
64 public $callstack = [];
65 public $theme_info = [];
68 // Allow themes to control internal parameters
69 // by changing App values in theme.php
71 public $sourcename = '';
72 public $videowidth = 425;
73 public $videoheight = 350;
74 public $force_max_items = 0;
75 public $theme_events_in_profile = true;
77 public $stylesheets = [];
78 public $footerScripts = [];
81 * @var App\Mode The Mode of the Application
86 * @var string The App base path
91 * @var string The App URL path
96 * @var bool true, if the call is from the Friendica APP, otherwise false
98 private $isFriendicaApp;
101 * @var bool true, if the call is from an backend node (f.e. worker)
106 * @var string The name of the current theme
108 private $currentTheme;
111 * @var bool check if request was an AJAX (xmlhttprequest) request
116 * Register a stylesheet file path to be included in the <head> tag of every page.
117 * Inclusion is done in App->initHead().
118 * The path can be absolute or relative to the Friendica installation base folder.
122 * @param string $path
124 public function registerStylesheet($path)
126 $url = str_replace($this->getBasePath() . DIRECTORY_SEPARATOR, '', $path);
128 $this->stylesheets[] = trim($url, '/');
132 * Register a javascript file path to be included in the <footer> tag of every page.
133 * Inclusion is done in App->initFooter().
134 * The path can be absolute or relative to the Friendica installation base folder.
138 * @param string $path
140 public function registerFooterScript($path)
142 $url = str_replace($this->getBasePath() . DIRECTORY_SEPARATOR, '', $path);
144 $this->footerScripts[] = trim($url, '/');
148 * @brief An array for all theme-controllable parameters
150 * Mostly unimplemented yet. Only options 'template_engine' and
156 'videoheight' => 350,
157 'force_max_items' => 0,
159 'template_engine' => 'smarty3',
163 * @brief An array of registered template engines ('name'=>'class name')
165 public $template_engines = [];
168 * @brief An array of instanced template engines ('name'=>'instance')
170 public $template_engine_instance = [];
185 * @brief App constructor.
187 * @param string $basePath Path to the app base folder
188 * @param bool $isBackend Whether it is used for backend or frontend (Default true=backend)
190 * @throws Exception if the Basepath is not usable
192 public function __construct($basePath, $isBackend = true)
194 if (!static::isDirectoryUsable($basePath, false)) {
195 throw new Exception('Basepath ' . $basePath . ' isn\'t usable.');
198 BaseObject::setApp($this);
200 $this->basePath = rtrim($basePath, DIRECTORY_SEPARATOR);
201 $this->checkBackend($isBackend);
202 $this->checkFriendicaApp();
204 $this->performance['start'] = microtime(true);
205 $this->performance['database'] = 0;
206 $this->performance['database_write'] = 0;
207 $this->performance['cache'] = 0;
208 $this->performance['cache_write'] = 0;
209 $this->performance['network'] = 0;
210 $this->performance['file'] = 0;
211 $this->performance['rendering'] = 0;
212 $this->performance['parser'] = 0;
213 $this->performance['marktime'] = 0;
214 $this->performance['markstart'] = microtime(true);
216 $this->callstack['database'] = [];
217 $this->callstack['database_write'] = [];
218 $this->callstack['cache'] = [];
219 $this->callstack['cache_write'] = [];
220 $this->callstack['network'] = [];
221 $this->callstack['file'] = [];
222 $this->callstack['rendering'] = [];
223 $this->callstack['parser'] = [];
225 $this->mode = new App\Mode($basePath);
231 // This has to be quite large to deal with embedded private photos
232 ini_set('pcre.backtrack_limit', 500000);
234 $this->scheme = 'http';
236 if (!empty($_SERVER['HTTPS']) ||
237 !empty($_SERVER['HTTP_FORWARDED']) && preg_match('/proto=https/', $_SERVER['HTTP_FORWARDED']) ||
238 !empty($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https' ||
239 !empty($_SERVER['HTTP_X_FORWARDED_SSL']) && $_SERVER['HTTP_X_FORWARDED_SSL'] == 'on' ||
240 !empty($_SERVER['FRONT_END_HTTPS']) && $_SERVER['FRONT_END_HTTPS'] == 'on' ||
241 !empty($_SERVER['SERVER_PORT']) && (intval($_SERVER['SERVER_PORT']) == 443) // XXX: reasonable assumption, but isn't this hardcoding too much?
243 $this->scheme = 'https';
246 if (!empty($_SERVER['SERVER_NAME'])) {
247 $this->hostname = $_SERVER['SERVER_NAME'];
249 if (!empty($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] != 80 && $_SERVER['SERVER_PORT'] != 443) {
250 $this->hostname .= ':' . $_SERVER['SERVER_PORT'];
255 get_include_path() . PATH_SEPARATOR
256 . $this->getBasePath() . DIRECTORY_SEPARATOR . 'include' . PATH_SEPARATOR
257 . $this->getBasePath(). DIRECTORY_SEPARATOR . 'library' . PATH_SEPARATOR
258 . $this->getBasePath());
260 if (!empty($_SERVER['QUERY_STRING']) && strpos($_SERVER['QUERY_STRING'], 'pagename=') === 0) {
261 $this->query_string = substr($_SERVER['QUERY_STRING'], 9);
262 } elseif (!empty($_SERVER['QUERY_STRING']) && strpos($_SERVER['QUERY_STRING'], 'q=') === 0) {
263 $this->query_string = substr($_SERVER['QUERY_STRING'], 2);
266 // removing trailing / - maybe a nginx problem
267 $this->query_string = ltrim($this->query_string, '/');
269 if (!empty($_GET['pagename'])) {
270 $this->cmd = trim($_GET['pagename'], '/\\');
271 } elseif (!empty($_GET['q'])) {
272 $this->cmd = trim($_GET['q'], '/\\');
276 $this->query_string = str_replace($this->cmd . '&', $this->cmd . '?', $this->query_string);
278 // unix style "homedir"
279 if (substr($this->cmd, 0, 1) === '~') {
280 $this->cmd = 'profile/' . substr($this->cmd, 1);
283 // Diaspora style profile url
284 if (substr($this->cmd, 0, 2) === 'u/') {
285 $this->cmd = 'profile/' . substr($this->cmd, 2);
289 * Break the URL path into C style argc/argv style arguments for our
290 * modules. Given "http://example.com/module/arg1/arg2", $this->argc
291 * will be 3 (integer) and $this->argv will contain:
297 * There will always be one argument. If provided a naked domain
298 * URL, $this->argv[0] is set to "home".
301 $this->argv = explode('/', $this->cmd);
302 $this->argc = count($this->argv);
303 if ((array_key_exists('0', $this->argv)) && strlen($this->argv[0])) {
304 $this->module = str_replace('.', '_', $this->argv[0]);
305 $this->module = str_replace('-', '_', $this->module);
308 $this->argv = ['home'];
309 $this->module = 'home';
312 // See if there is any page number information, and initialise pagination
313 $this->pager['page'] = !empty($_GET['page']) && intval($_GET['page']) > 0 ? intval($_GET['page']) : 1;
314 $this->pager['itemspage'] = 50;
315 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
317 if ($this->pager['start'] < 0) {
318 $this->pager['start'] = 0;
320 $this->pager['total'] = 0;
322 // Detect mobile devices
323 $mobile_detect = new MobileDetect();
324 $this->is_mobile = $mobile_detect->isMobile();
325 $this->is_tablet = $mobile_detect->isTablet();
327 $this->isAjax = strtolower(defaults($_SERVER, 'HTTP_X_REQUESTED_WITH', '')) == 'xmlhttprequest';
329 // Register template engines
330 $this->registerTemplateEngine('Friendica\Render\FriendicaSmartyEngine');
334 * Returns the Mode of the Application
336 * @return App\Mode The Application Mode
338 * @throws InternalServerErrorException when the mode isn't created
340 public function getMode()
342 if (empty($this->mode)) {
343 throw new InternalServerErrorException('Mode of the Application is not defined');
350 * Reloads the whole app instance
352 public function reload()
354 // The order of the following calls is important to ensure proper initialization
355 $this->loadConfigFiles();
357 $this->loadDatabase();
359 $this->getMode()->determine($this->getBasePath());
361 $this->determineURLPath();
365 if ($this->getMode()->has(App\Mode::DBAVAILABLE)) {
366 Core\Addon::loadHooks();
368 $this->loadAddonConfig();
371 $this->loadDefaultTimezone();
386 $this->process_id = Core\System::processID('log');
390 * Load the configuration files
392 * First loads the default value for all the configuration keys, then the legacy configuration files, then the
393 * expected local.ini.php
395 private function loadConfigFiles()
397 $this->loadConfigFile($this->getBasePath() . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'config.ini.php');
398 $this->loadConfigFile($this->getBasePath() . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'settings.ini.php');
400 // Legacy .htconfig.php support
401 if (file_exists($this->getBasePath() . DIRECTORY_SEPARATOR . '.htpreconfig.php')) {
403 include $this->getBasePath() . DIRECTORY_SEPARATOR . '.htpreconfig.php';
406 // Legacy .htconfig.php support
407 if (file_exists($this->getBasePath() . DIRECTORY_SEPARATOR . '.htconfig.php')) {
410 include $this->getBasePath() . DIRECTORY_SEPARATOR . '.htconfig.php';
412 $this->setConfigValue('database', 'hostname', $db_host);
413 $this->setConfigValue('database', 'username', $db_user);
414 $this->setConfigValue('database', 'password', $db_pass);
415 $this->setConfigValue('database', 'database', $db_data);
416 if (isset($a->config['system']['db_charset'])) {
417 $this->setConfigValue('database', 'charset', $a->config['system']['db_charset']);
420 unset($db_host, $db_user, $db_pass, $db_data);
422 if (isset($default_timezone)) {
423 $this->setConfigValue('system', 'default_timezone', $default_timezone);
424 unset($default_timezone);
427 if (isset($pidfile)) {
428 $this->setConfigValue('system', 'pidfile', $pidfile);
433 $this->setConfigValue('system', 'language', $lang);
438 if (file_exists($this->getBasePath() . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'local.ini.php')) {
439 $this->loadConfigFile($this->getBasePath() . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'local.ini.php', true);
444 * Tries to load the specified configuration file into the App->config array.
445 * Doesn't overwrite previously set values by default to prevent default config files to supersede DB Config.
447 * The config format is INI and the template for configuration files is the following:
449 * <?php return <<<INI
457 * @param string $filepath
458 * @param bool $overwrite Force value overwrite if the config key already exists
461 public function loadConfigFile($filepath, $overwrite = false)
463 if (!file_exists($filepath)) {
464 throw new Exception('Error parsing non-existent config file ' . $filepath);
467 $contents = include($filepath);
469 $config = parse_ini_string($contents, true, INI_SCANNER_TYPED);
471 if ($config === false) {
472 throw new Exception('Error parsing config file ' . $filepath);
475 foreach ($config as $category => $values) {
476 foreach ($values as $key => $value) {
478 $this->setConfigValue($category, $key, $value);
480 $this->setDefaultConfigValue($category, $key, $value);
487 * Loads addons configuration files
489 * First loads all activated addons default configuration throught the load_config hook, then load the local.ini.php
490 * again to overwrite potential local addon configuration.
492 private function loadAddonConfig()
494 // Loads addons default config
495 Core\Addon::callHooks('load_config');
497 // Load the local addon config file to overwritten default addon config values
498 if (file_exists($this->getBasePath() . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'addon.ini.php')) {
499 $this->loadConfigFile($this->getBasePath() . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'addon.ini.php', true);
504 * Loads the default timezone
506 * Include support for legacy $default_timezone
508 * @global string $default_timezone
510 private function loadDefaultTimezone()
512 if ($this->getConfigValue('system', 'default_timezone')) {
513 $this->timezone = $this->getConfigValue('system', 'default_timezone');
515 global $default_timezone;
516 $this->timezone = !empty($default_timezone) ? $default_timezone : 'UTC';
519 if ($this->timezone) {
520 date_default_timezone_set($this->timezone);
525 * Figure out if we are running at the top of a domain or in a sub-directory and adjust accordingly
527 private function determineURLPath()
529 /* Relative script path to the web server root
530 * Not all of those $_SERVER properties can be present, so we do by inverse priority order
532 $relative_script_path = '';
533 $relative_script_path = defaults($_SERVER, 'REDIRECT_URL' , $relative_script_path);
534 $relative_script_path = defaults($_SERVER, 'REDIRECT_URI' , $relative_script_path);
535 $relative_script_path = defaults($_SERVER, 'REDIRECT_SCRIPT_URL', $relative_script_path);
536 $relative_script_path = defaults($_SERVER, 'SCRIPT_URL' , $relative_script_path);
538 $this->urlPath = $this->getConfigValue('system', 'urlpath');
540 /* $relative_script_path gives /relative/path/to/friendica/module/parameter
541 * QUERY_STRING gives pagename=module/parameter
543 * To get /relative/path/to/friendica we perform dirname() for as many levels as there are slashes in the QUERY_STRING
545 if (!empty($relative_script_path)) {
547 if (!empty($_SERVER['QUERY_STRING'])) {
548 $path = trim(dirname($relative_script_path, substr_count(trim($_SERVER['QUERY_STRING'], '/'), '/') + 1), '/');
551 $path = trim($relative_script_path, '/');
554 if ($path && $path != $this->urlPath) {
555 $this->urlPath = $path;
560 public function loadDatabase()
562 if (DBA::connected()) {
566 $db_host = $this->getConfigValue('database', 'hostname');
567 $db_user = $this->getConfigValue('database', 'username');
568 $db_pass = $this->getConfigValue('database', 'password');
569 $db_data = $this->getConfigValue('database', 'database');
570 $charset = $this->getConfigValue('database', 'charset');
572 // Use environment variables for mysql if they are set beforehand
573 if (!empty(getenv('MYSQL_HOST'))
574 && (!empty(getenv('MYSQL_USERNAME')) || !empty(getenv('MYSQL_USER')))
575 && getenv('MYSQL_PASSWORD') !== false
576 && !empty(getenv('MYSQL_DATABASE')))
578 $db_host = getenv('MYSQL_HOST');
579 if (!empty(getenv('MYSQL_PORT'))) {
580 $db_host .= ':' . getenv('MYSQL_PORT');
582 if (!empty(getenv('MYSQL_USERNAME'))) {
583 $db_user = getenv('MYSQL_USERNAME');
585 $db_user = getenv('MYSQL_USER');
587 $db_pass = (string) getenv('MYSQL_PASSWORD');
588 $db_data = getenv('MYSQL_DATABASE');
591 $stamp1 = microtime(true);
593 DBA::connect($db_host, $db_user, $db_pass, $db_data, $charset);
594 unset($db_host, $db_user, $db_pass, $db_data, $charset);
596 $this->saveTimestamp($stamp1, 'network');
600 * @brief Returns the base filesystem path of the App
602 * It first checks for the internal variable, then for DOCUMENT_ROOT and
607 public function getBasePath()
609 $basepath = $this->basePath;
612 $basepath = Core\Config::get('system', 'basepath');
615 if (!$basepath && !empty($_SERVER['DOCUMENT_ROOT'])) {
616 $basepath = $_SERVER['DOCUMENT_ROOT'];
619 if (!$basepath && !empty($_SERVER['PWD'])) {
620 $basepath = $_SERVER['PWD'];
623 return self::getRealPath($basepath);
627 * @brief Returns a normalized file path
629 * This is a wrapper for the "realpath" function.
630 * That function cannot detect the real path when some folders aren't readable.
631 * Since this could happen with some hosters we need to handle this.
633 * @param string $path The path that is about to be normalized
634 * @return string normalized path - when possible
636 public static function getRealPath($path)
638 $normalized = realpath($path);
640 if (!is_bool($normalized)) {
647 public function getScheme()
649 return $this->scheme;
653 * @brief Retrieves the Friendica instance base URL
655 * This function assembles the base URL from multiple parts:
656 * - Protocol is determined either by the request or a combination of
657 * system.ssl_policy and the $ssl parameter.
658 * - Host name is determined either by system.hostname or inferred from request
659 * - Path is inferred from SCRIPT_NAME
661 * Note: $ssl parameter value doesn't directly correlate with the resulting protocol
663 * @param bool $ssl Whether to append http or https under SSL_POLICY_SELFSIGN
664 * @return string Friendica server base URL
666 public function getBaseURL($ssl = false)
668 $scheme = $this->scheme;
670 if (Core\Config::get('system', 'ssl_policy') == SSL_POLICY_FULL) {
674 // Basically, we have $ssl = true on any links which can only be seen by a logged in user
675 // (and also the login link). Anything seen by an outsider will have it turned off.
677 if (Core\Config::get('system', 'ssl_policy') == SSL_POLICY_SELFSIGN) {
685 if (Core\Config::get('config', 'hostname') != '') {
686 $this->hostname = Core\Config::get('config', 'hostname');
689 return $scheme . '://' . $this->hostname . (!empty($this->getURLPath()) ? '/' . $this->getURLPath() : '' );
693 * @brief Initializes the baseurl components
695 * Clears the baseurl cache to prevent inconsistencies
699 public function setBaseURL($url)
701 $parsed = @parse_url($url);
704 if (!empty($parsed)) {
705 if (!empty($parsed['scheme'])) {
706 $this->scheme = $parsed['scheme'];
709 if (!empty($parsed['host'])) {
710 $hostname = $parsed['host'];
713 if (!empty($parsed['port'])) {
714 $hostname .= ':' . $parsed['port'];
716 if (!empty($parsed['path'])) {
717 $this->urlPath = trim($parsed['path'], '\\/');
720 if (file_exists($this->getBasePath() . DIRECTORY_SEPARATOR . '.htpreconfig.php')) {
721 include $this->getBasePath() . DIRECTORY_SEPARATOR . '.htpreconfig.php';
724 if (Core\Config::get('config', 'hostname') != '') {
725 $this->hostname = Core\Config::get('config', 'hostname');
728 if (!isset($this->hostname) || ($this->hostname == '')) {
729 $this->hostname = $hostname;
734 public function getHostName()
736 if (Core\Config::get('config', 'hostname') != '') {
737 $this->hostname = Core\Config::get('config', 'hostname');
740 return $this->hostname;
743 public function getURLPath()
745 return $this->urlPath;
748 public function setPagerTotal($n)
750 $this->pager['total'] = intval($n);
753 public function setPagerItemsPage($n)
755 $this->pager['itemspage'] = ((intval($n) > 0) ? intval($n) : 0);
756 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
759 public function setPagerPage($n)
761 $this->pager['page'] = $n;
762 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
766 * Initializes App->page['htmlhead'].
771 * - Registered stylesheets (through App->registerStylesheet())
772 * - Infinite scroll data
773 * - head.tpl template
775 public function initHead()
777 $interval = ((local_user()) ? Core\PConfig::get(local_user(), 'system', 'update_interval') : 40000);
779 // If the update is 'deactivated' set it to the highest integer number (~24 days)
781 $interval = 2147483647;
784 if ($interval < 10000) {
788 // compose the page title from the sitename and the
789 // current module called
790 if (!$this->module == '') {
791 $this->page['title'] = $this->config['sitename'] . ' (' . $this->module . ')';
793 $this->page['title'] = $this->config['sitename'];
796 if (!empty($this->theme['stylesheet'])) {
797 $stylesheet = $this->theme['stylesheet'];
799 $stylesheet = $this->getCurrentThemeStylesheetPath();
802 $this->registerStylesheet($stylesheet);
804 $shortcut_icon = Core\Config::get('system', 'shortcut_icon');
805 if ($shortcut_icon == '') {
806 $shortcut_icon = 'images/friendica-32.png';
809 $touch_icon = Core\Config::get('system', 'touch_icon');
810 if ($touch_icon == '') {
811 $touch_icon = 'images/friendica-128.png';
814 // get data wich is needed for infinite scroll on the network page
815 $infinite_scroll = infinite_scroll_data($this->module);
817 Core\Addon::callHooks('head', $this->page['htmlhead']);
819 $tpl = get_markup_template('head.tpl');
820 /* put the head template at the beginning of page['htmlhead']
821 * since the code added by the modules frequently depends on it
824 $this->page['htmlhead'] = replace_macros($tpl, [
825 '$baseurl' => $this->getBaseURL(),
826 '$local_user' => local_user(),
827 '$generator' => 'Friendica' . ' ' . FRIENDICA_VERSION,
828 '$delitem' => Core\L10n::t('Delete this item?'),
829 '$showmore' => Core\L10n::t('show more'),
830 '$showfewer' => Core\L10n::t('show fewer'),
831 '$update_interval' => $interval,
832 '$shortcut_icon' => $shortcut_icon,
833 '$touch_icon' => $touch_icon,
834 '$infinite_scroll' => $infinite_scroll,
835 '$block_public' => intval(Core\Config::get('system', 'block_public')),
836 '$stylesheets' => $this->stylesheets,
837 ]) . $this->page['htmlhead'];
841 * Initializes App->page['footer'].
844 * - Javascript homebase
845 * - Mobile toggle link
846 * - Registered footer scripts (through App->registerFooterScript())
847 * - footer.tpl template
849 public function initFooter()
851 // If you're just visiting, let javascript take you home
852 if (!empty($_SESSION['visitor_home'])) {
853 $homebase = $_SESSION['visitor_home'];
854 } elseif (local_user()) {
855 $homebase = 'profile/' . $this->user['nickname'];
858 if (isset($homebase)) {
859 $this->page['footer'] .= '<script>var homebase="' . $homebase . '";</script>' . "\n";
863 * Add a "toggle mobile" link if we're using a mobile device
865 if ($this->is_mobile || $this->is_tablet) {
866 if (isset($_SESSION['show-mobile']) && !$_SESSION['show-mobile']) {
867 $link = 'toggle_mobile?address=' . curPageURL();
869 $link = 'toggle_mobile?off=1&address=' . curPageURL();
871 $this->page['footer'] .= replace_macros(get_markup_template("toggle_mobile_footer.tpl"), [
872 '$toggle_link' => $link,
873 '$toggle_text' => Core\L10n::t('toggle mobile')
877 Core\Addon::callHooks('footer', $this->page['footer']);
879 $tpl = get_markup_template('footer.tpl');
880 $this->page['footer'] = replace_macros($tpl, [
881 '$baseurl' => $this->getBaseURL(),
882 '$footerScripts' => $this->footerScripts,
883 ]) . $this->page['footer'];
887 * @brief Removes the base url from an url. This avoids some mixed content problems.
889 * @param string $origURL
891 * @return string The cleaned url
893 public function removeBaseURL($origURL)
895 // Remove the hostname from the url if it is an internal link
896 $nurl = normalise_link($origURL);
897 $base = normalise_link($this->getBaseURL());
898 $url = str_replace($base . '/', '', $nurl);
900 // if it is an external link return the orignal value
901 if ($url == normalise_link($origURL)) {
909 * @brief Register template engine class
911 * @param string $class
913 private function registerTemplateEngine($class)
915 $v = get_class_vars($class);
916 if (!empty($v['name'])) {
918 $this->template_engines[$name] = $class;
920 echo "template engine <tt>$class</tt> cannot be registered without a name.\n";
926 * @brief Return template engine instance.
928 * If $name is not defined, return engine defined by theme,
931 * @return object Template Engine instance
933 public function getTemplateEngine()
935 $template_engine = defaults($this->theme, 'template_engine', 'smarty3');
937 if (isset($this->template_engines[$template_engine])) {
938 if (isset($this->template_engine_instance[$template_engine])) {
939 return $this->template_engine_instance[$template_engine];
941 $class = $this->template_engines[$template_engine];
943 $this->template_engine_instance[$template_engine] = $obj;
948 echo "template engine <tt>$template_engine</tt> is not registered!\n";
953 * @brief Returns the active template engine.
955 * @return string the active template engine
957 public function getActiveTemplateEngine()
959 return $this->theme['template_engine'];
963 * sets the active template engine
965 * @param string $engine the template engine (default is Smarty3)
967 public function setActiveTemplateEngine($engine = 'smarty3')
969 $this->theme['template_engine'] = $engine;
973 * Gets the right delimiter for a template engine
979 * @param string $engine The template engine (default is Smarty3)
981 * @return string the right delimiter
983 public function getTemplateLeftDelimiter($engine = 'smarty3')
985 return $this->ldelim[$engine];
989 * Gets the left delimiter for a template engine
995 * @param string $engine The template engine (default is Smarty3)
997 * @return string the left delimiter
999 public function getTemplateRightDelimiter($engine = 'smarty3')
1001 return $this->rdelim[$engine];
1005 * Saves a timestamp for a value - f.e. a call
1006 * Necessary for profiling Friendica
1008 * @param int $timestamp the Timestamp
1009 * @param string $value A value to profile
1011 public function saveTimestamp($timestamp, $value)
1013 if (!isset($this->config['system']['profiler']) || !$this->config['system']['profiler']) {
1017 $duration = (float) (microtime(true) - $timestamp);
1019 if (!isset($this->performance[$value])) {
1020 // Prevent ugly E_NOTICE
1021 $this->performance[$value] = 0;
1024 $this->performance[$value] += (float) $duration;
1025 $this->performance['marktime'] += (float) $duration;
1027 $callstack = Core\System::callstack();
1029 if (!isset($this->callstack[$value][$callstack])) {
1030 // Prevent ugly E_NOTICE
1031 $this->callstack[$value][$callstack] = 0;
1034 $this->callstack[$value][$callstack] += (float) $duration;
1038 * Returns the current UserAgent as a String
1040 * @return string the UserAgent as a String
1042 public function getUserAgent()
1045 FRIENDICA_PLATFORM . " '" .
1046 FRIENDICA_CODENAME . "' " .
1047 FRIENDICA_VERSION . '-' .
1048 DB_UPDATE_VERSION . '; ' .
1049 $this->getBaseURL();
1053 * Checks, if the call is from the Friendica App
1056 * The friendica client has problems with the GUID in the notify. this is some workaround
1058 private function checkFriendicaApp()
1061 $this->isFriendicaApp = isset($_SERVER['HTTP_USER_AGENT']) && $_SERVER['HTTP_USER_AGENT'] == 'Apache-HttpClient/UNAVAILABLE (java 1.4)';
1065 * Is the call via the Friendica app? (not a "normale" call)
1067 * @return bool true if it's from the Friendica app
1069 public function isFriendicaApp()
1071 return $this->isFriendicaApp;
1075 * @brief Checks if the site is called via a backend process
1077 * This isn't a perfect solution. But we need this check very early.
1078 * So we cannot wait until the modules are loaded.
1080 * @param string $backend true, if the backend flag was set during App initialization
1083 private function checkBackend($backend) {
1084 static $backends = [
1106 // Check if current module is in backend or backend flag is set
1107 $this->isBackend = (in_array($this->module, $backends) || $backend || $this->isBackend);
1111 * Returns true, if the call is from a backend node (f.e. from a worker)
1113 * @return bool Is it a known backend?
1115 public function isBackend()
1117 return $this->isBackend;
1121 * @brief Checks if the maximum number of database processes is reached
1123 * @return bool Is the limit reached?
1125 public function isMaxProcessesReached()
1127 // Deactivated, needs more investigating if this check really makes sense
1131 * Commented out to suppress static analyzer issues
1133 if ($this->is_backend()) {
1134 $process = 'backend';
1135 $max_processes = Core\Config::get('system', 'max_processes_backend');
1136 if (intval($max_processes) == 0) {
1140 $process = 'frontend';
1141 $max_processes = Core\Config::get('system', 'max_processes_frontend');
1142 if (intval($max_processes) == 0) {
1143 $max_processes = 20;
1147 $processlist = DBA::processlist();
1148 if ($processlist['list'] != '') {
1149 logger('Processcheck: Processes: ' . $processlist['amount'] . ' - Processlist: ' . $processlist['list'], LOGGER_DEBUG);
1151 if ($processlist['amount'] > $max_processes) {
1152 logger('Processcheck: Maximum number of processes for ' . $process . ' tasks (' . $max_processes . ') reached.', LOGGER_DEBUG);
1161 * @brief Checks if the minimal memory is reached
1163 * @return bool Is the memory limit reached?
1165 public function isMinMemoryReached()
1167 $min_memory = Core\Config::get('system', 'min_memory', 0);
1168 if ($min_memory == 0) {
1172 if (!is_readable('/proc/meminfo')) {
1176 $memdata = explode("\n", file_get_contents('/proc/meminfo'));
1179 foreach ($memdata as $line) {
1180 $data = explode(':', $line);
1181 if (count($data) != 2) {
1184 list($key, $val) = $data;
1185 $meminfo[$key] = (int) trim(str_replace('kB', '', $val));
1186 $meminfo[$key] = (int) ($meminfo[$key] / 1024);
1189 if (!isset($meminfo['MemAvailable']) || !isset($meminfo['MemFree'])) {
1193 $free = $meminfo['MemAvailable'] + $meminfo['MemFree'];
1195 $reached = ($free < $min_memory);
1198 logger('Minimal memory reached: ' . $free . '/' . $meminfo['MemTotal'] . ' - limit ' . $min_memory, LOGGER_DEBUG);
1205 * @brief Checks if the maximum load is reached
1207 * @return bool Is the load reached?
1209 public function isMaxLoadReached()
1211 if ($this->isBackend()) {
1212 $process = 'backend';
1213 $maxsysload = intval(Core\Config::get('system', 'maxloadavg'));
1214 if ($maxsysload < 1) {
1218 $process = 'frontend';
1219 $maxsysload = intval(Core\Config::get('system', 'maxloadavg_frontend'));
1220 if ($maxsysload < 1) {
1225 $load = Core\System::currentLoad();
1227 if (intval($load) > $maxsysload) {
1228 logger('system: load ' . $load . ' for ' . $process . ' tasks (' . $maxsysload . ') too high.');
1236 * Executes a child process with 'proc_open'
1238 * @param string $command The command to execute
1239 * @param array $args Arguments to pass to the command ( [ 'key' => value, 'key2' => value2, ... ]
1241 public function proc_run($command, $args)
1243 if (!function_exists('proc_open')) {
1247 $cmdline = $this->getConfigValue('config', 'php_path', 'php') . ' ' . escapeshellarg($command);
1249 foreach ($args as $key => $value) {
1250 if (!is_null($value) && is_bool($value) && !$value) {
1254 $cmdline .= ' --' . $key;
1255 if (!is_null($value) && !is_bool($value)) {
1256 $cmdline .= ' ' . $value;
1260 if ($this->isMinMemoryReached()) {
1264 if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
1265 $resource = proc_open('cmd /c start /b ' . $cmdline, [], $foo, $this->getBasePath());
1267 $resource = proc_open($cmdline . ' &', [], $foo, $this->getBasePath());
1269 if (!is_resource($resource)) {
1270 logger('We got no resource for command ' . $cmdline, LOGGER_DEBUG);
1273 proc_close($resource);
1277 * @brief Returns the system user that is executing the script
1279 * This mostly returns something like "www-data".
1281 * @return string system username
1283 private static function getSystemUser()
1285 if (!function_exists('posix_getpwuid') || !function_exists('posix_geteuid')) {
1289 $processUser = posix_getpwuid(posix_geteuid());
1290 return $processUser['name'];
1294 * @brief Checks if a given directory is usable for the system
1296 * @return boolean the directory is usable
1298 public static function isDirectoryUsable($directory, $check_writable = true)
1300 if ($directory == '') {
1301 logger('Directory is empty. This shouldn\'t happen.', LOGGER_DEBUG);
1305 if (!file_exists($directory)) {
1306 logger('Path "' . $directory . '" does not exist for user ' . self::getSystemUser(), LOGGER_DEBUG);
1310 if (is_file($directory)) {
1311 logger('Path "' . $directory . '" is a file for user ' . self::getSystemUser(), LOGGER_DEBUG);
1315 if (!is_dir($directory)) {
1316 logger('Path "' . $directory . '" is not a directory for user ' . self::getSystemUser(), LOGGER_DEBUG);
1320 if ($check_writable && !is_writable($directory)) {
1321 logger('Path "' . $directory . '" is not writable for user ' . self::getSystemUser(), LOGGER_DEBUG);
1329 * @param string $cat Config category
1330 * @param string $k Config key
1331 * @param mixed $default Default value if it isn't set
1333 * @return string Returns the value of the Config entry
1335 public function getConfigValue($cat, $k, $default = null)
1339 if ($cat === 'config') {
1340 if (isset($this->config[$k])) {
1341 $return = $this->config[$k];
1344 if (isset($this->config[$cat][$k])) {
1345 $return = $this->config[$cat][$k];
1353 * Sets a default value in the config cache. Ignores already existing keys.
1355 * @param string $cat Config category
1356 * @param string $k Config key
1357 * @param mixed $v Default value to set
1359 private function setDefaultConfigValue($cat, $k, $v)
1361 if (!isset($this->config[$cat][$k])) {
1362 $this->setConfigValue($cat, $k, $v);
1367 * Sets a value in the config cache. Accepts raw output from the config table
1369 * @param string $cat Config category
1370 * @param string $k Config key
1371 * @param mixed $v Value to set
1373 public function setConfigValue($cat, $k, $v)
1375 // Only arrays are serialized in database, so we have to unserialize sparingly
1376 $value = is_string($v) && preg_match("|^a:[0-9]+:{.*}$|s", $v) ? unserialize($v) : $v;
1378 if ($cat === 'config') {
1379 $this->config[$k] = $value;
1381 if (!isset($this->config[$cat])) {
1382 $this->config[$cat] = [];
1385 $this->config[$cat][$k] = $value;
1390 * Deletes a value from the config cache
1392 * @param string $cat Config category
1393 * @param string $k Config key
1395 public function deleteConfigValue($cat, $k)
1397 if ($cat === 'config') {
1398 if (isset($this->config[$k])) {
1399 unset($this->config[$k]);
1402 if (isset($this->config[$cat][$k])) {
1403 unset($this->config[$cat][$k]);
1410 * Retrieves a value from the user config cache
1412 * @param int $uid User Id
1413 * @param string $cat Config category
1414 * @param string $k Config key
1415 * @param mixed $default Default value if key isn't set
1417 * @return string The value of the config entry
1419 public function getPConfigValue($uid, $cat, $k, $default = null)
1423 if (isset($this->config[$uid][$cat][$k])) {
1424 $return = $this->config[$uid][$cat][$k];
1431 * Sets a value in the user config cache
1433 * Accepts raw output from the pconfig table
1435 * @param int $uid User Id
1436 * @param string $cat Config category
1437 * @param string $k Config key
1438 * @param mixed $v Value to set
1440 public function setPConfigValue($uid, $cat, $k, $v)
1442 // Only arrays are serialized in database, so we have to unserialize sparingly
1443 $value = is_string($v) && preg_match("|^a:[0-9]+:{.*}$|s", $v) ? unserialize($v) : $v;
1445 if (!isset($this->config[$uid]) || !is_array($this->config[$uid])) {
1446 $this->config[$uid] = [];
1449 if (!isset($this->config[$uid][$cat]) || !is_array($this->config[$uid][$cat])) {
1450 $this->config[$uid][$cat] = [];
1453 $this->config[$uid][$cat][$k] = $value;
1457 * Deletes a value from the user config cache
1459 * @param int $uid User Id
1460 * @param string $cat Config category
1461 * @param string $k Config key
1463 public function deletePConfigValue($uid, $cat, $k)
1465 if (isset($this->config[$uid][$cat][$k])) {
1466 unset($this->config[$uid][$cat][$k]);
1471 * Generates the site's default sender email address
1475 public function getSenderEmailAddress()
1477 $sender_email = Core\Config::get('config', 'sender_email');
1478 if (empty($sender_email)) {
1479 $hostname = $this->getHostName();
1480 if (strpos($hostname, ':')) {
1481 $hostname = substr($hostname, 0, strpos($hostname, ':'));
1484 $sender_email = 'noreply@' . $hostname;
1487 return $sender_email;
1491 * Returns the current theme name.
1493 * @return string the name of the current theme
1495 public function getCurrentTheme()
1497 if ($this->getMode()->isInstall()) {
1501 //// @TODO Compute the current theme only once (this behavior has
1502 /// already been implemented, but it didn't work well -
1503 /// https://github.com/friendica/friendica/issues/5092)
1504 $this->computeCurrentTheme();
1506 return $this->currentTheme;
1510 * Computes the current theme name based on the node settings, the user settings and the device type
1514 private function computeCurrentTheme()
1516 $system_theme = Core\Config::get('system', 'theme');
1517 if (!$system_theme) {
1518 throw new Exception(Core\L10n::t('No system theme config value set.'));
1522 $this->currentTheme = $system_theme;
1524 $allowed_themes = explode(',', Core\Config::get('system', 'allowed_themes', $system_theme));
1527 // Find the theme that belongs to the user whose stuff we are looking at
1528 if ($this->profile_uid && ($this->profile_uid != local_user())) {
1529 // Allow folks to override user themes and always use their own on their own site.
1530 // This works only if the user is on the same server
1531 $user = DBA::selectFirst('user', ['theme'], ['uid' => $this->profile_uid]);
1532 if (DBA::isResult($user) && !Core\PConfig::get(local_user(), 'system', 'always_my_theme')) {
1533 $page_theme = $user['theme'];
1537 $user_theme = Core\Session::get('theme', $system_theme);
1539 // Specific mobile theme override
1540 if (($this->is_mobile || $this->is_tablet) && Core\Session::get('show-mobile', true)) {
1541 $system_mobile_theme = Core\Config::get('system', 'mobile-theme');
1542 $user_mobile_theme = Core\Session::get('mobile-theme', $system_mobile_theme);
1544 // --- means same mobile theme as desktop
1545 if (!empty($user_mobile_theme) && $user_mobile_theme !== '---') {
1546 $user_theme = $user_mobile_theme;
1551 $theme_name = $page_theme;
1553 $theme_name = $user_theme;
1557 && in_array($theme_name, $allowed_themes)
1558 && (file_exists('view/theme/' . $theme_name . '/style.css')
1559 || file_exists('view/theme/' . $theme_name . '/style.php'))
1561 $this->currentTheme = $theme_name;
1566 * @brief Return full URL to theme which is currently in effect.
1568 * Provide a sane default if nothing is chosen or the specified theme does not exist.
1572 public function getCurrentThemeStylesheetPath()
1574 return Core\Theme::getStylesheetPath($this->getCurrentTheme());
1578 * Check if request was an AJAX (xmlhttprequest) request.
1580 * @return boolean true if it was an AJAX request
1582 public function isAjax()
1584 return $this->isAjax;
1588 * Returns the value of a argv key
1589 * TODO there are a lot of $a->argv usages in combination with defaults() which can be replaced with this method
1591 * @param int $position the position of the argument
1592 * @param mixed $default the default value if not found
1594 * @return mixed returns the value of the argument
1596 public function getArgumentValue($position, $default = '')
1598 if (array_key_exists($position, $this->argv)) {
1599 return $this->argv[$position];
1606 * Sets the base url for use in cmdline programs which don't have
1607 * $_SERVER variables
1609 public function checkURL()
1611 $url = Core\Config::get('system', 'url');
1613 // if the url isn't set or the stored url is radically different
1614 // than the currently visited url, store the current value accordingly.
1615 // "Radically different" ignores common variations such as http vs https
1616 // and www.example.com vs example.com.
1617 // We will only change the url to an ip address if there is no existing setting
1619 if (empty($url) || (!link_compare($url, $this->getBaseURL())) && (!preg_match("/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/", $this->getHostName()))) {
1620 Core\Config::set('system', 'url', $this->getBaseURL());
1625 * Frontend App script
1627 * The App object behaves like a container and a dispatcher at the same time, including a representation of the
1628 * request and a representation of the response.
1630 * This probably should change to limit the size of this monster method.
1632 public function runFrontend()
1634 // Missing DB connection: ERROR
1635 if ($this->getMode()->has(App\Mode::LOCALCONFIGPRESENT) && !$this->getMode()->has(App\Mode::DBAVAILABLE)) {
1636 Core\System::httpExit(500, ['title' => 'Error 500 - Internal Server Error', 'description' => 'Apologies but the website is unavailable at the moment.']);
1639 // Max Load Average reached: ERROR
1640 if ($this->isMaxProcessesReached() || $this->isMaxLoadReached()) {
1641 header('Retry-After: 120');
1642 header('Refresh: 120; url=' . $this->getBaseURL() . "/" . $this->query_string);
1644 Core\System::httpExit(503, ['title' => 'Error 503 - Service Temporarily Unavailable', 'description' => 'Core\System is currently overloaded. Please try again later.']);
1647 if (strstr($this->query_string, '.well-known/host-meta') && ($this->query_string != '.well-known/host-meta')) {
1648 Core\System::httpExit(404);
1651 if (!$this->getMode()->isInstall()) {
1652 // Force SSL redirection
1653 if (Core\Config::get('system', 'force_ssl') && ($this->getScheme() == "http")
1654 && intval(Core\Config::get('system', 'ssl_policy')) == SSL_POLICY_FULL
1655 && strpos($this->getBaseURL(), 'https://') === 0
1656 && $_SERVER['REQUEST_METHOD'] == 'GET') {
1657 header('HTTP/1.1 302 Moved Temporarily');
1658 header('Location: ' . $this->getBaseURL() . '/' . $this->query_string);
1662 Core\Session::init();
1663 Core\Addon::callHooks('init_1');
1666 $lang = Core\L10n::getBrowserLanguage();
1668 Core\L10n::loadTranslationTable($lang);
1671 // Exclude the backend processes from the session management
1672 if (!$this->isBackend()) {
1673 $stamp1 = microtime(true);
1675 $this->saveTimestamp($stamp1, "parser");
1678 Core\Worker::executeIfIdle();
1681 /* Language was set earlier, but we can over-ride it in the session.
1682 * We have to do it here because the session was just now opened.
1684 if (!empty($_SESSION['authenticated']) && empty($_SESSION['language'])) {
1685 $_SESSION['language'] = $lang;
1686 // we haven't loaded user data yet, but we need user language
1687 if (!empty($_SESSION['uid'])) {
1688 $user = DBA::selectFirst('user', ['language'], ['uid' => $_SESSION['uid']]);
1689 if (DBA::isResult($user)) {
1690 $_SESSION['language'] = $user['language'];
1695 if (!empty($_SESSION['language']) && $_SESSION['language'] !== $lang) {
1696 $lang = $_SESSION['language'];
1697 Core\L10n::loadTranslationTable($lang);
1701 if (!empty($_GET['zrl']) && $this->getMode()->isNormal()) {
1702 $this->query_string = Model\Profile::stripZrls($this->query_string);
1703 if (!local_user()) {
1704 // Only continue when the given profile link seems valid
1705 // Valid profile links contain a path with "/profile/" and no query parameters
1706 if ((parse_url($_GET['zrl'], PHP_URL_QUERY) == "") &&
1707 strstr(parse_url($_GET['zrl'], PHP_URL_PATH), "/profile/")) {
1708 if (defaults($_SESSION, "visitor_home", "") != $_GET["zrl"]) {
1709 $_SESSION['my_url'] = $_GET['zrl'];
1710 $_SESSION['authenticated'] = 0;
1712 Model\Profile::zrlInit($this);
1714 // Someone came with an invalid parameter, maybe as a DDoS attempt
1715 // We simply stop processing here
1716 logger("Invalid ZRL parameter " . $_GET['zrl'], LOGGER_DEBUG);
1717 Core\System::httpExit(403, ['title' => '403 Forbidden']);
1722 if (!empty($_GET['owt']) && $this->getMode()->isNormal()) {
1723 $token = $_GET['owt'];
1724 $this->query_string = Model\Profile::stripQueryParam($this->query_string, 'owt');
1725 Model\Profile::openWebAuthInit($token);
1728 Module\Login::sessionAuth();
1730 if (empty($_SESSION['authenticated'])) {
1731 header('X-Account-Management-Status: none');
1734 $_SESSION['sysmsg'] = defaults($_SESSION, 'sysmsg' , []);
1735 $_SESSION['sysmsg_info'] = defaults($_SESSION, 'sysmsg_info' , []);
1736 $_SESSION['last_updated'] = defaults($_SESSION, 'last_updated', []);
1739 * check_config() is responsible for running update scripts. These automatically
1740 * update the DB schema whenever we push a new one out. It also checks to see if
1741 * any addons have been added or removed and reacts accordingly.
1744 // in install mode, any url loads install module
1745 // but we need "view" module for stylesheet
1746 if ($this->getMode()->isInstall() && $this->module != 'view') {
1747 $this->module = 'install';
1748 } elseif (!$this->getMode()->has(App\Mode::MAINTENANCEDISABLED) && $this->module != 'view') {
1749 $this->module = 'maintenance';
1753 Core\Addon::check();
1756 Content\Nav::setSelected('nothing');
1758 //Don't populate apps_menu if apps are private
1759 $privateapps = Core\Config::get('config', 'private_addons');
1760 if ((local_user()) || (! $privateapps === "1")) {
1761 $arr = ['app_menu' => $this->apps];
1763 Core\Addon::callHooks('app_menu', $arr);
1765 $this->apps = $arr['app_menu'];
1768 if (strlen($this->module)) {
1769 // Compatibility with the Android Diaspora client
1770 if ($this->module == 'stream') {
1771 goaway('network?f=&order=post');
1774 if ($this->module == 'conversations') {
1778 if ($this->module == 'commented') {
1779 goaway('network?f=&order=comment');
1782 if ($this->module == 'liked') {
1783 goaway('network?f=&order=comment');
1786 if ($this->module == 'activity') {
1787 goaway('network/?f=&conv=1');
1790 if (($this->module == 'status_messages') && ($this->cmd == 'status_messages/new')) {
1791 goaway('bookmarklet');
1794 if (($this->module == 'user') && ($this->cmd == 'user/edit')) {
1798 if (($this->module == 'tag_followings') && ($this->cmd == 'tag_followings/manage')) {
1802 // Compatibility with the Firefox App
1803 if (($this->module == "users") && ($this->cmd == "users/sign_in")) {
1804 $this->module = "login";
1807 $privateapps = Core\Config::get('config', 'private_addons', false);
1808 if (is_array($this->addons) && in_array($this->module, $this->addons) && file_exists("addon/{$this->module}/{$this->module}.php")) {
1809 //Check if module is an app and if public access to apps is allowed or not
1810 if ((!local_user()) && Core\Addon::isApp($this->module) && $privateapps) {
1811 info(Core\L10n::t("You must be logged in to use addons. "));
1813 include_once "addon/{$this->module}/{$this->module}.php";
1814 if (function_exists($this->module . '_module')) {
1815 LegacyModule::setModuleFile("addon/{$this->module}/{$this->module}.php");
1816 $this->module_class = 'Friendica\\LegacyModule';
1817 $this->module_loaded = true;
1822 // Controller class routing
1823 if (! $this->module_loaded && class_exists('Friendica\\Module\\' . ucfirst($this->module))) {
1824 $this->module_class = 'Friendica\\Module\\' . ucfirst($this->module);
1825 $this->module_loaded = true;
1828 /* If not, next look for a 'standard' program module in the 'mod' directory
1829 * We emulate a Module class through the LegacyModule class
1831 if (! $this->module_loaded && file_exists("mod/{$this->module}.php")) {
1832 LegacyModule::setModuleFile("mod/{$this->module}.php");
1833 $this->module_class = 'Friendica\\LegacyModule';
1834 $this->module_loaded = true;
1837 /* The URL provided does not resolve to a valid module.
1839 * On Dreamhost sites, quite often things go wrong for no apparent reason and they send us to '/internal_error.html'.
1840 * We don't like doing this, but as it occasionally accounts for 10-20% or more of all site traffic -
1841 * we are going to trap this and redirect back to the requested page. As long as you don't have a critical error on your page
1842 * this will often succeed and eventually do the right thing.
1844 * Otherwise we are going to emit a 404 not found.
1846 if (! $this->module_loaded) {
1847 // Stupid browser tried to pre-fetch our Javascript img template. Don't log the event or return anything - just quietly exit.
1848 if (!empty($_SERVER['QUERY_STRING']) && preg_match('/{[0-9]}/', $_SERVER['QUERY_STRING']) !== 0) {
1852 if (!empty($_SERVER['QUERY_STRING']) && ($_SERVER['QUERY_STRING'] === 'q=internal_error.html') && isset($dreamhost_error_hack)) {
1853 logger('index.php: dreamhost_error_hack invoked. Original URI =' . $_SERVER['REQUEST_URI']);
1854 goaway($this->getBaseURL() . $_SERVER['REQUEST_URI']);
1857 logger('index.php: page not found: ' . $_SERVER['REQUEST_URI'] . ' ADDRESS: ' . $_SERVER['REMOTE_ADDR'] . ' QUERY: ' . $_SERVER['QUERY_STRING'], LOGGER_DEBUG);
1859 header($_SERVER["SERVER_PROTOCOL"] . ' 404 ' . Core\L10n::t('Not Found'));
1860 $tpl = get_markup_template("404.tpl");
1861 $this->page['content'] = replace_macros($tpl, [
1862 '$message' => Core\L10n::t('Page not found.')
1867 // Load current theme info
1868 $theme_info_file = 'view/theme/' . $this->getCurrentTheme() . '/theme.php';
1869 if (file_exists($theme_info_file)) {
1870 require_once $theme_info_file;
1874 // initialise content region
1875 if ($this->getMode()->isNormal()) {
1876 Core\Addon::callHooks('page_content_top', $this->page['content']);
1879 // Call module functions
1880 if ($this->module_loaded) {
1881 $this->page['page_title'] = $this->module;
1884 Core\Addon::callHooks($this->module . '_mod_init', $placeholder);
1886 call_user_func([$this->module_class, 'init']);
1888 // "rawContent" is especially meant for technical endpoints.
1889 // This endpoint doesn't need any theme initialization or other comparable stuff.
1890 if (!$this->error) {
1891 call_user_func([$this->module_class, 'rawContent']);
1894 if (function_exists(str_replace('-', '_', $this->getCurrentTheme()) . '_init')) {
1895 $func = str_replace('-', '_', $this->getCurrentTheme()) . '_init';
1899 if (! $this->error && $_SERVER['REQUEST_METHOD'] === 'POST') {
1900 Core\Addon::callHooks($this->module . '_mod_post', $_POST);
1901 call_user_func([$this->module_class, 'post']);
1904 if (! $this->error) {
1905 Core\Addon::callHooks($this->module . '_mod_afterpost', $placeholder);
1906 call_user_func([$this->module_class, 'afterpost']);
1909 if (! $this->error) {
1910 $arr = ['content' => $this->page['content']];
1911 Core\Addon::callHooks($this->module . '_mod_content', $arr);
1912 $this->page['content'] = $arr['content'];
1913 $arr = ['content' => call_user_func([$this->module_class, 'content'])];
1914 Core\Addon::callHooks($this->module . '_mod_aftercontent', $arr);
1915 $this->page['content'] .= $arr['content'];
1918 if (function_exists(str_replace('-', '_', $this->getCurrentTheme()) . '_content_loaded')) {
1919 $func = str_replace('-', '_', $this->getCurrentTheme()) . '_content_loaded';
1924 /* Create the page head after setting the language
1925 * and getting any auth credentials.
1927 * Moved initHead() and initFooter() to after
1928 * all the module functions have executed so that all
1929 * theme choices made by the modules can take effect.
1933 /* Build the page ending -- this is stuff that goes right before
1934 * the closing </body> tag
1936 $this->initFooter();
1938 /* now that we've been through the module content, see if the page reported
1939 * a permission problem and if so, a 403 response would seem to be in order.
1941 if (stristr(implode("", $_SESSION['sysmsg']), Core\L10n::t('Permission denied'))) {
1942 header($_SERVER["SERVER_PROTOCOL"] . ' 403 ' . Core\L10n::t('Permission denied.'));
1945 // Report anything which needs to be communicated in the notification area (before the main body)
1946 Core\Addon::callHooks('page_end', $this->page['content']);
1948 // Add the navigation (menu) template
1949 if ($this->module != 'install' && $this->module != 'maintenance') {
1950 Content\Nav::build($this);
1953 // Build the page - now that we have all the components
1954 if (isset($_GET["mode"]) && (($_GET["mode"] == "raw") || ($_GET["mode"] == "minimal"))) {
1955 $doc = new DOMDocument();
1957 $target = new DOMDocument();
1958 $target->loadXML("<root></root>");
1960 $content = mb_convert_encoding($this->page["content"], 'HTML-ENTITIES', "UTF-8");
1962 /// @TODO one day, kill those error-surpressing @ stuff, or PHP should ban it
1963 @$doc->loadHTML($content);
1965 $xpath = new DOMXPath($doc);
1967 $list = $xpath->query("//*[contains(@id,'tread-wrapper-')]"); /* */
1969 foreach ($list as $item) {
1970 $item = $target->importNode($item, true);
1972 // And then append it to the target
1973 $target->documentElement->appendChild($item);
1977 if (isset($_GET["mode"]) && ($_GET["mode"] == "raw")) {
1978 header("Content-type: text/html; charset=utf-8");
1980 echo substr($target->saveHTML(), 6, -8);
1985 $page = $this->page;
1986 $profile = $this->profile;
1988 header("X-Friendica-Version: " . FRIENDICA_VERSION);
1989 header("Content-type: text/html; charset=utf-8");
1991 if (Core\Config::get('system', 'hsts') && (Core\Config::get('system', 'ssl_policy') == SSL_POLICY_FULL)) {
1992 header("Strict-Transport-Security: max-age=31536000");
1995 // Some security stuff
1996 header('X-Content-Type-Options: nosniff');
1997 header('X-XSS-Protection: 1; mode=block');
1998 header('X-Permitted-Cross-Domain-Policies: none');
1999 header('X-Frame-Options: sameorigin');
2001 // Things like embedded OSM maps don't work, when this is enabled
2002 // header("Content-Security-Policy: default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; connect-src 'self'; style-src 'self' 'unsafe-inline'; font-src 'self'; img-src 'self' https: data:; media-src 'self' https:; child-src 'self' https:; object-src 'none'");
2004 /* We use $_GET["mode"] for special page templates. So we will check if we have
2005 * to load another page template than the default one.
2006 * The page templates are located in /view/php/ or in the theme directory.
2008 if (isset($_GET["mode"])) {
2009 $template = Core\Theme::getPathForFile($_GET["mode"] . '.php');
2012 // If there is no page template use the default page template
2013 if (empty($template)) {
2014 $template = Core\Theme::getPathForFile("default.php");
2017 // Theme templates expect $a as an App instance
2020 /// @TODO Looks unsafe (remote-inclusion), is maybe not but Core\Theme::getPathForFile() uses file_exists() but does not escape anything
2021 require_once $template;