7 use Detection\MobileDetect;
11 use Friendica\Database\DBA;
12 use Friendica\Network\HTTPException\InternalServerErrorException;
13 use Psr\Log\LoggerInterface;
19 * @brief Our main application structure for the life of this page.
21 * Primarily deals with the URL that got us here
22 * and tries to make some sense of it, and
23 * stores our page contents and config storage
24 * and anything else that might need to be passed around
25 * before we spit the page out.
30 public $module_loaded = false;
31 public $module_class = null;
32 public $query_string = '';
44 public $error = false;
50 public $interactive = true;
52 public $is_mobile = false;
53 public $is_tablet = false;
54 public $performance = [];
55 public $callstack = [];
56 public $theme_info = [];
58 // Allow themes to control internal parameters
59 // by changing App values in theme.php
61 public $sourcename = '';
62 public $videowidth = 425;
63 public $videoheight = 350;
64 public $force_max_items = 0;
65 public $theme_events_in_profile = true;
67 public $stylesheets = [];
68 public $footerScripts = [];
71 * @var App\Mode The Mode of the Application
76 * @var string The App base path
81 * @var string The App URL path
86 * @var bool true, if the call is from the Friendica APP, otherwise false
88 private $isFriendicaApp;
91 * @var bool true, if the call is from an backend node (f.e. worker)
96 * @var string The name of the current theme
98 private $currentTheme;
101 * @var bool check if request was an AJAX (xmlhttprequest) request
108 public $mobileDetect;
111 * @var LoggerInterface The current logger of this App
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
123 * @throws InternalServerErrorException
125 public function registerStylesheet($path)
127 $url = str_replace($this->getBasePath() . DIRECTORY_SEPARATOR, '', $path);
129 $this->stylesheets[] = trim($url, '/');
133 * Register a javascript file path to be included in the <footer> tag of every page.
134 * Inclusion is done in App->initFooter().
135 * The path can be absolute or relative to the Friendica installation base folder.
139 * @param string $path
140 * @throws InternalServerErrorException
142 public function registerFooterScript($path)
144 $url = str_replace($this->getBasePath() . DIRECTORY_SEPARATOR, '', $path);
146 $this->footerScripts[] = trim($url, '/');
155 * @brief App constructor.
157 * @param string $basePath Path to the app base folder
158 * @param LoggerInterface $logger Logger of this application
159 * @param bool $isBackend Whether it is used for backend or frontend (Default true=backend)
161 * @throws Exception if the Basepath is not usable
163 public function __construct($basePath, LoggerInterface $logger, $isBackend = true)
165 $this->logger = $logger;
167 if (!static::isDirectoryUsable($basePath, false)) {
168 throw new Exception('Basepath ' . $basePath . ' isn\'t usable.');
171 BaseObject::setApp($this);
173 $this->basePath = rtrim($basePath, DIRECTORY_SEPARATOR);
174 $this->checkBackend($isBackend);
175 $this->checkFriendicaApp();
177 $this->performance['start'] = microtime(true);
178 $this->performance['database'] = 0;
179 $this->performance['database_write'] = 0;
180 $this->performance['cache'] = 0;
181 $this->performance['cache_write'] = 0;
182 $this->performance['network'] = 0;
183 $this->performance['file'] = 0;
184 $this->performance['rendering'] = 0;
185 $this->performance['parser'] = 0;
186 $this->performance['marktime'] = 0;
187 $this->performance['markstart'] = microtime(true);
189 $this->callstack['database'] = [];
190 $this->callstack['database_write'] = [];
191 $this->callstack['cache'] = [];
192 $this->callstack['cache_write'] = [];
193 $this->callstack['network'] = [];
194 $this->callstack['file'] = [];
195 $this->callstack['rendering'] = [];
196 $this->callstack['parser'] = [];
198 $this->mode = new App\Mode($basePath);
204 // This has to be quite large to deal with embedded private photos
205 ini_set('pcre.backtrack_limit', 500000);
207 $this->scheme = 'http';
209 if (!empty($_SERVER['HTTPS']) ||
210 !empty($_SERVER['HTTP_FORWARDED']) && preg_match('/proto=https/', $_SERVER['HTTP_FORWARDED']) ||
211 !empty($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https' ||
212 !empty($_SERVER['HTTP_X_FORWARDED_SSL']) && $_SERVER['HTTP_X_FORWARDED_SSL'] == 'on' ||
213 !empty($_SERVER['FRONT_END_HTTPS']) && $_SERVER['FRONT_END_HTTPS'] == 'on' ||
214 !empty($_SERVER['SERVER_PORT']) && (intval($_SERVER['SERVER_PORT']) == 443) // XXX: reasonable assumption, but isn't this hardcoding too much?
216 $this->scheme = 'https';
219 if (!empty($_SERVER['SERVER_NAME'])) {
220 $this->hostname = $_SERVER['SERVER_NAME'];
222 if (!empty($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] != 80 && $_SERVER['SERVER_PORT'] != 443) {
223 $this->hostname .= ':' . $_SERVER['SERVER_PORT'];
228 get_include_path() . PATH_SEPARATOR
229 . $this->getBasePath() . DIRECTORY_SEPARATOR . 'include' . PATH_SEPARATOR
230 . $this->getBasePath() . DIRECTORY_SEPARATOR . 'library' . PATH_SEPARATOR
231 . $this->getBasePath());
233 if (!empty($_SERVER['QUERY_STRING']) && strpos($_SERVER['QUERY_STRING'], 'pagename=') === 0) {
234 $this->query_string = substr($_SERVER['QUERY_STRING'], 9);
235 } elseif (!empty($_SERVER['QUERY_STRING']) && strpos($_SERVER['QUERY_STRING'], 'q=') === 0) {
236 $this->query_string = substr($_SERVER['QUERY_STRING'], 2);
239 // removing trailing / - maybe a nginx problem
240 $this->query_string = ltrim($this->query_string, '/');
242 if (!empty($_GET['pagename'])) {
243 $this->cmd = trim($_GET['pagename'], '/\\');
244 } elseif (!empty($_GET['q'])) {
245 $this->cmd = trim($_GET['q'], '/\\');
249 $this->query_string = str_replace($this->cmd . '&', $this->cmd . '?', $this->query_string);
251 // unix style "homedir"
252 if (substr($this->cmd, 0, 1) === '~') {
253 $this->cmd = 'profile/' . substr($this->cmd, 1);
256 // Diaspora style profile url
257 if (substr($this->cmd, 0, 2) === 'u/') {
258 $this->cmd = 'profile/' . substr($this->cmd, 2);
262 * Break the URL path into C style argc/argv style arguments for our
263 * modules. Given "http://example.com/module/arg1/arg2", $this->argc
264 * will be 3 (integer) and $this->argv will contain:
270 * There will always be one argument. If provided a naked domain
271 * URL, $this->argv[0] is set to "home".
274 $this->argv = explode('/', $this->cmd);
275 $this->argc = count($this->argv);
276 if ((array_key_exists('0', $this->argv)) && strlen($this->argv[0])) {
277 $this->module = str_replace('.', '_', $this->argv[0]);
278 $this->module = str_replace('-', '_', $this->module);
281 $this->argv = ['home'];
282 $this->module = 'home';
285 // Detect mobile devices
286 $mobile_detect = new MobileDetect();
288 $this->mobileDetect = $mobile_detect;
290 $this->is_mobile = $mobile_detect->isMobile();
291 $this->is_tablet = $mobile_detect->isTablet();
293 $this->isAjax = strtolower(defaults($_SERVER, 'HTTP_X_REQUESTED_WITH', '')) == 'xmlhttprequest';
295 // Register template engines
296 Core\Renderer::registerTemplateEngine('Friendica\Render\FriendicaSmartyEngine');
300 * Returns the Mode of the Application
302 * @return App\Mode The Application Mode
304 * @throws InternalServerErrorException when the mode isn't created
306 public function getMode()
308 if (empty($this->mode)) {
309 throw new InternalServerErrorException('Mode of the Application is not defined');
316 * Returns the Logger of the Application
318 * @return LoggerInterface The Logger
319 * @throws InternalServerErrorException when the logger isn't created
321 public function getLogger()
323 if (empty($this->logger)) {
324 throw new InternalServerErrorException('Logger of the Application is not defined');
327 return $this->logger;
331 * Reloads the whole app instance
333 public function reload()
335 // The order of the following calls is important to ensure proper initialization
336 $this->loadConfigFiles();
338 $this->loadDatabase();
340 $this->getMode()->determine($this->getBasePath());
342 $this->determineURLPath();
346 if ($this->getMode()->has(App\Mode::DBAVAILABLE)) {
347 Core\Hook::loadHooks();
349 $this->loadAddonConfig();
352 $this->loadDefaultTimezone();
356 $this->process_id = Core\System::processID('log');
358 Core\Logger::setLogger($this->logger);
362 * Load the configuration files
364 * First loads the default value for all the configuration keys, then the legacy configuration files, then the
365 * expected local.config.php
367 private function loadConfigFiles()
369 $this->loadConfigFile($this->getBasePath() . '/config/defaults.config.php');
370 $this->loadConfigFile($this->getBasePath() . '/config/settings.config.php');
372 // Legacy .htconfig.php support
373 if (file_exists($this->getBasePath() . '/.htpreconfig.php')) {
375 include $this->getBasePath() . '/.htpreconfig.php';
378 // Legacy .htconfig.php support
379 if (file_exists($this->getBasePath() . '/.htconfig.php')) {
382 include $this->getBasePath() . '/.htconfig.php';
384 Core\Config::setConfigValue('database', 'hostname', $db_host);
385 Core\Config::setConfigValue('database', 'username', $db_user);
386 Core\Config::setConfigValue('database', 'password', $db_pass);
387 Core\Config::setConfigValue('database', 'database', $db_data);
388 $charset = Core\Config::getConfigValue('system', 'db_charset');
389 if (isset($charset)) {
390 Core\Config::setConfigValue('database', 'charset', $charset);
393 unset($db_host, $db_user, $db_pass, $db_data);
395 if (isset($default_timezone)) {
396 Core\Config::setConfigValue('system', 'default_timezone', $default_timezone);
397 unset($default_timezone);
400 if (isset($pidfile)) {
401 Core\Config::setConfigValue('system', 'pidfile', $pidfile);
406 Core\Config::setConfigValue('system', 'language', $lang);
411 if (file_exists($this->getBasePath() . '/config/local.config.php')) {
412 $this->loadConfigFile($this->getBasePath() . '/config/local.config.php', true);
413 } elseif (file_exists($this->getBasePath() . '/config/local.ini.php')) {
414 $this->loadINIConfigFile($this->getBasePath() . '/config/local.ini.php', true);
419 * Tries to load the specified legacy configuration file into the App->config array.
420 * Doesn't overwrite previously set values by default to prevent default config files to supersede DB Config.
422 * @deprecated since version 2018.12
423 * @param string $filepath
424 * @param bool $overwrite Force value overwrite if the config key already exists
427 public function loadINIConfigFile($filepath, $overwrite = false)
429 if (!file_exists($filepath)) {
430 throw new Exception('Error parsing non-existent INI config file ' . $filepath);
433 $contents = include($filepath);
435 $config = parse_ini_string($contents, true, INI_SCANNER_TYPED);
437 if ($config === false) {
438 throw new Exception('Error parsing INI config file ' . $filepath);
441 Core\Config::loadConfigArray($config, $overwrite);
445 * Tries to load the specified configuration file into the App->config array.
446 * Doesn't overwrite previously set values by default to prevent default config files to supersede DB Config.
448 * The config format is PHP array and the template for configuration files is the following:
456 * @param string $filepath
457 * @param bool $overwrite Force value overwrite if the config key already exists
460 public function loadConfigFile($filepath, $overwrite = false)
462 if (!file_exists($filepath)) {
463 throw new Exception('Error loading non-existent config file ' . $filepath);
466 $config = include($filepath);
468 if (!is_array($config)) {
469 throw new Exception('Error loading config file ' . $filepath);
472 Core\Config::loadConfigArray($config, $overwrite);
476 * Loads addons configuration files
478 * First loads all activated addons default configuration through the load_config hook, then load the local.config.php
479 * again to overwrite potential local addon configuration.
481 private function loadAddonConfig()
483 // Loads addons default config
484 Core\Hook::callAll('load_config');
486 // Load the local addon config file to overwritten default addon config values
487 if (file_exists($this->getBasePath() . '/config/addon.config.php')) {
488 $this->loadConfigFile($this->getBasePath() . '/config/addon.config.php', true);
489 } elseif (file_exists($this->getBasePath() . '/config/addon.ini.php')) {
490 $this->loadINIConfigFile($this->getBasePath() . '/config/addon.ini.php', true);
495 * Loads the default timezone
497 * Include support for legacy $default_timezone
499 * @global string $default_timezone
501 private function loadDefaultTimezone()
503 if (Core\Config::getConfigValue('system', 'default_timezone')) {
504 $this->timezone = Core\Config::getConfigValue('system', 'default_timezone');
506 global $default_timezone;
507 $this->timezone = !empty($default_timezone) ? $default_timezone : 'UTC';
510 if ($this->timezone) {
511 date_default_timezone_set($this->timezone);
516 * Figure out if we are running at the top of a domain or in a sub-directory and adjust accordingly
518 private function determineURLPath()
520 /* Relative script path to the web server root
521 * Not all of those $_SERVER properties can be present, so we do by inverse priority order
523 $relative_script_path = '';
524 $relative_script_path = defaults($_SERVER, 'REDIRECT_URL' , $relative_script_path);
525 $relative_script_path = defaults($_SERVER, 'REDIRECT_URI' , $relative_script_path);
526 $relative_script_path = defaults($_SERVER, 'REDIRECT_SCRIPT_URL', $relative_script_path);
527 $relative_script_path = defaults($_SERVER, 'SCRIPT_URL' , $relative_script_path);
528 $relative_script_path = defaults($_SERVER, 'REQUEST_URI' , $relative_script_path);
530 $this->urlPath = Core\Config::getConfigValue('system', 'urlpath');
532 /* $relative_script_path gives /relative/path/to/friendica/module/parameter
533 * QUERY_STRING gives pagename=module/parameter
535 * To get /relative/path/to/friendica we perform dirname() for as many levels as there are slashes in the QUERY_STRING
537 if (!empty($relative_script_path)) {
539 if (!empty($_SERVER['QUERY_STRING'])) {
540 $path = trim(rdirname($relative_script_path, substr_count(trim($_SERVER['QUERY_STRING'], '/'), '/') + 1), '/');
543 $path = trim($relative_script_path, '/');
546 if ($path && $path != $this->urlPath) {
547 $this->urlPath = $path;
552 public function loadDatabase()
554 if (DBA::connected()) {
558 $db_host = Core\Config::getConfigValue('database', 'hostname');
559 $db_user = Core\Config::getConfigValue('database', 'username');
560 $db_pass = Core\Config::getConfigValue('database', 'password');
561 $db_data = Core\Config::getConfigValue('database', 'database');
562 $charset = Core\Config::getConfigValue('database', 'charset');
564 // Use environment variables for mysql if they are set beforehand
565 if (!empty(getenv('MYSQL_HOST'))
566 && !empty(getenv('MYSQL_USERNAME') || !empty(getenv('MYSQL_USER')))
567 && getenv('MYSQL_PASSWORD') !== false
568 && !empty(getenv('MYSQL_DATABASE')))
570 $db_host = getenv('MYSQL_HOST');
571 if (!empty(getenv('MYSQL_PORT'))) {
572 $db_host .= ':' . getenv('MYSQL_PORT');
574 if (!empty(getenv('MYSQL_USERNAME'))) {
575 $db_user = getenv('MYSQL_USERNAME');
577 $db_user = getenv('MYSQL_USER');
579 $db_pass = (string) getenv('MYSQL_PASSWORD');
580 $db_data = getenv('MYSQL_DATABASE');
583 $stamp1 = microtime(true);
585 if (DBA::connect($db_host, $db_user, $db_pass, $db_data, $charset)) {
586 // Loads DB_UPDATE_VERSION constant
587 Database\DBStructure::definition(false);
590 unset($db_host, $db_user, $db_pass, $db_data, $charset);
592 $this->saveTimestamp($stamp1, 'network');
596 * @brief Returns the base filesystem path of the App
598 * It first checks for the internal variable, then for DOCUMENT_ROOT and
602 * @throws InternalServerErrorException
604 public function getBasePath()
606 $basepath = $this->basePath;
609 $basepath = Core\Config::get('system', 'basepath');
612 if (!$basepath && !empty($_SERVER['DOCUMENT_ROOT'])) {
613 $basepath = $_SERVER['DOCUMENT_ROOT'];
616 if (!$basepath && !empty($_SERVER['PWD'])) {
617 $basepath = $_SERVER['PWD'];
620 return self::getRealPath($basepath);
624 * @brief Returns a normalized file path
626 * This is a wrapper for the "realpath" function.
627 * That function cannot detect the real path when some folders aren't readable.
628 * Since this could happen with some hosters we need to handle this.
630 * @param string $path The path that is about to be normalized
631 * @return string normalized path - when possible
633 public static function getRealPath($path)
635 $normalized = realpath($path);
637 if (!is_bool($normalized)) {
644 public function getScheme()
646 return $this->scheme;
650 * @brief Retrieves the Friendica instance base URL
652 * This function assembles the base URL from multiple parts:
653 * - Protocol is determined either by the request or a combination of
654 * system.ssl_policy and the $ssl parameter.
655 * - Host name is determined either by system.hostname or inferred from request
656 * - Path is inferred from SCRIPT_NAME
658 * Note: $ssl parameter value doesn't directly correlate with the resulting protocol
660 * @param bool $ssl Whether to append http or https under SSL_POLICY_SELFSIGN
661 * @return string Friendica server base URL
662 * @throws InternalServerErrorException
664 public function getBaseURL($ssl = false)
666 $scheme = $this->scheme;
668 if (Core\Config::get('system', 'ssl_policy') == SSL_POLICY_FULL) {
672 // Basically, we have $ssl = true on any links which can only be seen by a logged in user
673 // (and also the login link). Anything seen by an outsider will have it turned off.
675 if (Core\Config::get('system', 'ssl_policy') == SSL_POLICY_SELFSIGN) {
683 if (Core\Config::get('config', 'hostname') != '') {
684 $this->hostname = Core\Config::get('config', 'hostname');
687 return $scheme . '://' . $this->hostname . (!empty($this->getURLPath()) ? '/' . $this->getURLPath() : '' );
691 * @brief Initializes the baseurl components
693 * Clears the baseurl cache to prevent inconsistencies
696 * @throws InternalServerErrorException
698 public function setBaseURL($url)
700 $parsed = @parse_url($url);
703 if (!empty($parsed)) {
704 if (!empty($parsed['scheme'])) {
705 $this->scheme = $parsed['scheme'];
708 if (!empty($parsed['host'])) {
709 $hostname = $parsed['host'];
712 if (!empty($parsed['port'])) {
713 $hostname .= ':' . $parsed['port'];
715 if (!empty($parsed['path'])) {
716 $this->urlPath = trim($parsed['path'], '\\/');
719 if (file_exists($this->getBasePath() . '/.htpreconfig.php')) {
720 include $this->getBasePath() . '/.htpreconfig.php';
723 if (Core\Config::get('config', 'hostname') != '') {
724 $this->hostname = Core\Config::get('config', 'hostname');
727 if (!isset($this->hostname) || ($this->hostname == '')) {
728 $this->hostname = $hostname;
733 public function getHostName()
735 if (Core\Config::get('config', 'hostname') != '') {
736 $this->hostname = Core\Config::get('config', 'hostname');
739 return $this->hostname;
742 public function getURLPath()
744 return $this->urlPath;
748 * Initializes App->page['htmlhead'].
753 * - Registered stylesheets (through App->registerStylesheet())
754 * - Infinite scroll data
755 * - head.tpl template
757 public function initHead()
759 $interval = ((local_user()) ? Core\PConfig::get(local_user(), 'system', 'update_interval') : 40000);
761 // If the update is 'deactivated' set it to the highest integer number (~24 days)
763 $interval = 2147483647;
766 if ($interval < 10000) {
770 // compose the page title from the sitename and the
771 // current module called
772 if (!$this->module == '') {
773 $this->page['title'] = Core\Config::getConfigValue('config', 'sitename') . ' (' . $this->module . ')';
775 $this->page['title'] = Core\Config::getConfigValue('config', 'sitename');
778 if (!empty(Core\Renderer::$theme['stylesheet'])) {
779 $stylesheet = Core\Renderer::$theme['stylesheet'];
781 $stylesheet = $this->getCurrentThemeStylesheetPath();
784 $this->registerStylesheet($stylesheet);
786 $shortcut_icon = Core\Config::get('system', 'shortcut_icon');
787 if ($shortcut_icon == '') {
788 $shortcut_icon = 'images/friendica-32.png';
791 $touch_icon = Core\Config::get('system', 'touch_icon');
792 if ($touch_icon == '') {
793 $touch_icon = 'images/friendica-128.png';
796 Core\Hook::callAll('head', $this->page['htmlhead']);
798 $tpl = Core\Renderer::getMarkupTemplate('head.tpl');
799 /* put the head template at the beginning of page['htmlhead']
800 * since the code added by the modules frequently depends on it
803 $this->page['htmlhead'] = Core\Renderer::replaceMacros($tpl, [
804 '$baseurl' => $this->getBaseURL(),
805 '$local_user' => local_user(),
806 '$generator' => 'Friendica' . ' ' . FRIENDICA_VERSION,
807 '$delitem' => Core\L10n::t('Delete this item?'),
808 '$showmore' => Core\L10n::t('show more'),
809 '$showfewer' => Core\L10n::t('show fewer'),
810 '$update_interval' => $interval,
811 '$shortcut_icon' => $shortcut_icon,
812 '$touch_icon' => $touch_icon,
813 '$block_public' => intval(Core\Config::get('system', 'block_public')),
814 '$stylesheets' => $this->stylesheets,
815 ]) . $this->page['htmlhead'];
819 * Initializes App->page['footer'].
822 * - Javascript homebase
823 * - Mobile toggle link
824 * - Registered footer scripts (through App->registerFooterScript())
825 * - footer.tpl template
827 public function initFooter()
829 // If you're just visiting, let javascript take you home
830 if (!empty($_SESSION['visitor_home'])) {
831 $homebase = $_SESSION['visitor_home'];
832 } elseif (local_user()) {
833 $homebase = 'profile/' . $this->user['nickname'];
836 if (isset($homebase)) {
837 $this->page['footer'] .= '<script>var homebase="' . $homebase . '";</script>' . "\n";
841 * Add a "toggle mobile" link if we're using a mobile device
843 if ($this->is_mobile || $this->is_tablet) {
844 if (isset($_SESSION['show-mobile']) && !$_SESSION['show-mobile']) {
845 $link = 'toggle_mobile?address=' . urlencode(curPageURL());
847 $link = 'toggle_mobile?off=1&address=' . urlencode(curPageURL());
849 $this->page['footer'] .= Core\Renderer::replaceMacros(Core\Renderer::getMarkupTemplate("toggle_mobile_footer.tpl"), [
850 '$toggle_link' => $link,
851 '$toggle_text' => Core\L10n::t('toggle mobile')
855 Core\Hook::callAll('footer', $this->page['footer']);
857 $tpl = Core\Renderer::getMarkupTemplate('footer.tpl');
858 $this->page['footer'] = Core\Renderer::replaceMacros($tpl, [
859 '$baseurl' => $this->getBaseURL(),
860 '$footerScripts' => $this->footerScripts,
861 ]) . $this->page['footer'];
865 * @brief Removes the base url from an url. This avoids some mixed content problems.
867 * @param string $origURL
869 * @return string The cleaned url
870 * @throws InternalServerErrorException
872 public function removeBaseURL($origURL)
874 // Remove the hostname from the url if it is an internal link
875 $nurl = Util\Strings::normaliseLink($origURL);
876 $base = Util\Strings::normaliseLink($this->getBaseURL());
877 $url = str_replace($base . '/', '', $nurl);
879 // if it is an external link return the orignal value
880 if ($url == Util\Strings::normaliseLink($origURL)) {
888 * Saves a timestamp for a value - f.e. a call
889 * Necessary for profiling Friendica
891 * @param int $timestamp the Timestamp
892 * @param string $value A value to profile
894 public function saveTimestamp($timestamp, $value)
896 $profiler = Core\Config::getConfigValue('system', 'profiler');
898 if (!isset($profiler) || !$profiler) {
902 $duration = (float) (microtime(true) - $timestamp);
904 if (!isset($this->performance[$value])) {
905 // Prevent ugly E_NOTICE
906 $this->performance[$value] = 0;
909 $this->performance[$value] += (float) $duration;
910 $this->performance['marktime'] += (float) $duration;
912 $callstack = Core\System::callstack();
914 if (!isset($this->callstack[$value][$callstack])) {
915 // Prevent ugly E_NOTICE
916 $this->callstack[$value][$callstack] = 0;
919 $this->callstack[$value][$callstack] += (float) $duration;
923 * Returns the current UserAgent as a String
925 * @return string the UserAgent as a String
926 * @throws InternalServerErrorException
928 public function getUserAgent()
931 FRIENDICA_PLATFORM . " '" .
932 FRIENDICA_CODENAME . "' " .
933 FRIENDICA_VERSION . '-' .
934 DB_UPDATE_VERSION . '; ' .
939 * Checks, if the call is from the Friendica App
942 * The friendica client has problems with the GUID in the notify. this is some workaround
944 private function checkFriendicaApp()
947 $this->isFriendicaApp = isset($_SERVER['HTTP_USER_AGENT']) && $_SERVER['HTTP_USER_AGENT'] == 'Apache-HttpClient/UNAVAILABLE (java 1.4)';
951 * Is the call via the Friendica app? (not a "normale" call)
953 * @return bool true if it's from the Friendica app
955 public function isFriendicaApp()
957 return $this->isFriendicaApp;
961 * @brief Checks if the site is called via a backend process
963 * This isn't a perfect solution. But we need this check very early.
964 * So we cannot wait until the modules are loaded.
966 * @param string $backend true, if the backend flag was set during App initialization
969 private function checkBackend($backend) {
992 // Check if current module is in backend or backend flag is set
993 $this->isBackend = (in_array($this->module, $backends) || $backend || $this->isBackend);
997 * Returns true, if the call is from a backend node (f.e. from a worker)
999 * @return bool Is it a known backend?
1001 public function isBackend()
1003 return $this->isBackend;
1007 * @brief Checks if the maximum number of database processes is reached
1009 * @return bool Is the limit reached?
1011 public function isMaxProcessesReached()
1013 // Deactivated, needs more investigating if this check really makes sense
1017 * Commented out to suppress static analyzer issues
1019 if ($this->is_backend()) {
1020 $process = 'backend';
1021 $max_processes = Core\Config::get('system', 'max_processes_backend');
1022 if (intval($max_processes) == 0) {
1026 $process = 'frontend';
1027 $max_processes = Core\Config::get('system', 'max_processes_frontend');
1028 if (intval($max_processes) == 0) {
1029 $max_processes = 20;
1033 $processlist = DBA::processlist();
1034 if ($processlist['list'] != '') {
1035 Core\Logger::log('Processcheck: Processes: ' . $processlist['amount'] . ' - Processlist: ' . $processlist['list'], Core\Logger::DEBUG);
1037 if ($processlist['amount'] > $max_processes) {
1038 Core\Logger::log('Processcheck: Maximum number of processes for ' . $process . ' tasks (' . $max_processes . ') reached.', Core\Logger::DEBUG);
1047 * @brief Checks if the minimal memory is reached
1049 * @return bool Is the memory limit reached?
1050 * @throws InternalServerErrorException
1052 public function isMinMemoryReached()
1054 $min_memory = Core\Config::get('system', 'min_memory', 0);
1055 if ($min_memory == 0) {
1059 if (!is_readable('/proc/meminfo')) {
1063 $memdata = explode("\n", file_get_contents('/proc/meminfo'));
1066 foreach ($memdata as $line) {
1067 $data = explode(':', $line);
1068 if (count($data) != 2) {
1071 list($key, $val) = $data;
1072 $meminfo[$key] = (int) trim(str_replace('kB', '', $val));
1073 $meminfo[$key] = (int) ($meminfo[$key] / 1024);
1076 if (!isset($meminfo['MemFree'])) {
1080 $free = $meminfo['MemFree'];
1082 $reached = ($free < $min_memory);
1085 Core\Logger::log('Minimal memory reached: ' . $free . '/' . $meminfo['MemTotal'] . ' - limit ' . $min_memory, Core\Logger::DEBUG);
1092 * @brief Checks if the maximum load is reached
1094 * @return bool Is the load reached?
1095 * @throws InternalServerErrorException
1097 public function isMaxLoadReached()
1099 if ($this->isBackend()) {
1100 $process = 'backend';
1101 $maxsysload = intval(Core\Config::get('system', 'maxloadavg'));
1102 if ($maxsysload < 1) {
1106 $process = 'frontend';
1107 $maxsysload = intval(Core\Config::get('system', 'maxloadavg_frontend'));
1108 if ($maxsysload < 1) {
1113 $load = Core\System::currentLoad();
1115 if (intval($load) > $maxsysload) {
1116 Core\Logger::log('system: load ' . $load . ' for ' . $process . ' tasks (' . $maxsysload . ') too high.');
1124 * Executes a child process with 'proc_open'
1126 * @param string $command The command to execute
1127 * @param array $args Arguments to pass to the command ( [ 'key' => value, 'key2' => value2, ... ]
1128 * @throws InternalServerErrorException
1130 public function proc_run($command, $args)
1132 if (!function_exists('proc_open')) {
1136 $cmdline = Core\Config::getConfigValue('config', 'php_path', 'php') . ' ' . escapeshellarg($command);
1138 foreach ($args as $key => $value) {
1139 if (!is_null($value) && is_bool($value) && !$value) {
1143 $cmdline .= ' --' . $key;
1144 if (!is_null($value) && !is_bool($value)) {
1145 $cmdline .= ' ' . $value;
1149 if ($this->isMinMemoryReached()) {
1153 if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
1154 $resource = proc_open('cmd /c start /b ' . $cmdline, [], $foo, $this->getBasePath());
1156 $resource = proc_open($cmdline . ' &', [], $foo, $this->getBasePath());
1158 if (!is_resource($resource)) {
1159 Core\Logger::log('We got no resource for command ' . $cmdline, Core\Logger::DEBUG);
1162 proc_close($resource);
1166 * @brief Returns the system user that is executing the script
1168 * This mostly returns something like "www-data".
1170 * @return string system username
1172 private static function getSystemUser()
1174 if (!function_exists('posix_getpwuid') || !function_exists('posix_geteuid')) {
1178 $processUser = posix_getpwuid(posix_geteuid());
1179 return $processUser['name'];
1183 * @brief Checks if a given directory is usable for the system
1186 * @param bool $check_writable
1187 * @return boolean the directory is usable
1190 public static function isDirectoryUsable($directory, $check_writable = true)
1192 if ($directory == '') {
1193 Core\Logger::log('Directory is empty. This shouldn\'t happen.', Core\Logger::DEBUG);
1197 if (!file_exists($directory)) {
1198 Core\Logger::log('Path "' . $directory . '" does not exist for user ' . self::getSystemUser(), Core\Logger::DEBUG);
1202 if (is_file($directory)) {
1203 Core\Logger::log('Path "' . $directory . '" is a file for user ' . self::getSystemUser(), Core\Logger::DEBUG);
1207 if (!is_dir($directory)) {
1208 Core\Logger::log('Path "' . $directory . '" is not a directory for user ' . self::getSystemUser(), Core\Logger::DEBUG);
1212 if ($check_writable && !is_writable($directory)) {
1213 Core\Logger::log('Path "' . $directory . '" is not writable for user ' . self::getSystemUser(), Core\Logger::DEBUG);
1221 * Retrieves a value from the user config cache
1223 * @param int $uid User Id
1224 * @param string $cat Config category
1225 * @param string $k Config key
1226 * @param mixed $default Default value if key isn't set
1228 * @return string The value of the config entry
1230 public function getPConfigValue($uid, $cat, $k, $default = null)
1234 if (isset($this->config[$uid][$cat][$k])) {
1235 $return = $this->config[$uid][$cat][$k];
1242 * Sets a value in the user config cache
1244 * Accepts raw output from the pconfig table
1246 * @param int $uid User Id
1247 * @param string $cat Config category
1248 * @param string $k Config key
1249 * @param mixed $v Value to set
1251 public function setPConfigValue($uid, $cat, $k, $v)
1253 // Only arrays are serialized in database, so we have to unserialize sparingly
1254 $value = is_string($v) && preg_match("|^a:[0-9]+:{.*}$|s", $v) ? unserialize($v) : $v;
1256 if (!isset($this->config[$uid]) || !is_array($this->config[$uid])) {
1257 $this->config[$uid] = [];
1260 if (!isset($this->config[$uid][$cat]) || !is_array($this->config[$uid][$cat])) {
1261 $this->config[$uid][$cat] = [];
1264 $this->config[$uid][$cat][$k] = $value;
1268 * Deletes a value from the user config cache
1270 * @param int $uid User Id
1271 * @param string $cat Config category
1272 * @param string $k Config key
1274 public function deletePConfigValue($uid, $cat, $k)
1276 if (isset($this->config[$uid][$cat][$k])) {
1277 unset($this->config[$uid][$cat][$k]);
1282 * Generates the site's default sender email address
1285 * @throws InternalServerErrorException
1287 public function getSenderEmailAddress()
1289 $sender_email = Core\Config::get('config', 'sender_email');
1290 if (empty($sender_email)) {
1291 $hostname = $this->getHostName();
1292 if (strpos($hostname, ':')) {
1293 $hostname = substr($hostname, 0, strpos($hostname, ':'));
1296 $sender_email = 'noreply@' . $hostname;
1299 return $sender_email;
1303 * Returns the current theme name.
1305 * @return string the name of the current theme
1306 * @throws InternalServerErrorException
1308 public function getCurrentTheme()
1310 if ($this->getMode()->isInstall()) {
1314 if (!$this->currentTheme) {
1315 $this->computeCurrentTheme();
1318 return $this->currentTheme;
1321 public function setCurrentTheme($theme)
1323 $this->currentTheme = $theme;
1327 * Computes the current theme name based on the node settings, the user settings and the device type
1331 private function computeCurrentTheme()
1333 $system_theme = Core\Config::get('system', 'theme');
1334 if (!$system_theme) {
1335 throw new Exception(Core\L10n::t('No system theme config value set.'));
1339 $this->currentTheme = $system_theme;
1341 $allowed_themes = explode(',', Core\Config::get('system', 'allowed_themes', $system_theme));
1344 // Find the theme that belongs to the user whose stuff we are looking at
1345 if ($this->profile_uid && ($this->profile_uid != local_user())) {
1346 // Allow folks to override user themes and always use their own on their own site.
1347 // This works only if the user is on the same server
1348 $user = DBA::selectFirst('user', ['theme'], ['uid' => $this->profile_uid]);
1349 if (DBA::isResult($user) && !Core\PConfig::get(local_user(), 'system', 'always_my_theme')) {
1350 $page_theme = $user['theme'];
1354 $user_theme = Core\Session::get('theme', $system_theme);
1356 // Specific mobile theme override
1357 if (($this->is_mobile || $this->is_tablet) && Core\Session::get('show-mobile', true)) {
1358 $system_mobile_theme = Core\Config::get('system', 'mobile-theme');
1359 $user_mobile_theme = Core\Session::get('mobile-theme', $system_mobile_theme);
1361 // --- means same mobile theme as desktop
1362 if (!empty($user_mobile_theme) && $user_mobile_theme !== '---') {
1363 $user_theme = $user_mobile_theme;
1368 $theme_name = $page_theme;
1370 $theme_name = $user_theme;
1374 && in_array($theme_name, $allowed_themes)
1375 && (file_exists('view/theme/' . $theme_name . '/style.css')
1376 || file_exists('view/theme/' . $theme_name . '/style.php'))
1378 $this->currentTheme = $theme_name;
1383 * @brief Return full URL to theme which is currently in effect.
1385 * Provide a sane default if nothing is chosen or the specified theme does not exist.
1388 * @throws InternalServerErrorException
1390 public function getCurrentThemeStylesheetPath()
1392 return Core\Theme::getStylesheetPath($this->getCurrentTheme());
1396 * Check if request was an AJAX (xmlhttprequest) request.
1398 * @return boolean true if it was an AJAX request
1400 public function isAjax()
1402 return $this->isAjax;
1406 * Returns the value of a argv key
1407 * TODO there are a lot of $a->argv usages in combination with defaults() which can be replaced with this method
1409 * @param int $position the position of the argument
1410 * @param mixed $default the default value if not found
1412 * @return mixed returns the value of the argument
1414 public function getArgumentValue($position, $default = '')
1416 if (array_key_exists($position, $this->argv)) {
1417 return $this->argv[$position];
1424 * Sets the base url for use in cmdline programs which don't have
1425 * $_SERVER variables
1427 public function checkURL()
1429 $url = Core\Config::get('system', 'url');
1431 // if the url isn't set or the stored url is radically different
1432 // than the currently visited url, store the current value accordingly.
1433 // "Radically different" ignores common variations such as http vs https
1434 // and www.example.com vs example.com.
1435 // We will only change the url to an ip address if there is no existing setting
1437 if (empty($url) || (!Util\Strings::compareLink($url, $this->getBaseURL())) && (!preg_match("/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/", $this->getHostName()))) {
1438 Core\Config::set('system', 'url', $this->getBaseURL());
1443 * Frontend App script
1445 * The App object behaves like a container and a dispatcher at the same time, including a representation of the
1446 * request and a representation of the response.
1448 * This probably should change to limit the size of this monster method.
1450 public function runFrontend()
1452 // Missing DB connection: ERROR
1453 if ($this->getMode()->has(App\Mode::LOCALCONFIGPRESENT) && !$this->getMode()->has(App\Mode::DBAVAILABLE)) {
1454 Core\System::httpExit(500, ['title' => 'Error 500 - Internal Server Error', 'description' => 'Apologies but the website is unavailable at the moment.']);
1457 // Max Load Average reached: ERROR
1458 if ($this->isMaxProcessesReached() || $this->isMaxLoadReached()) {
1459 header('Retry-After: 120');
1460 header('Refresh: 120; url=' . $this->getBaseURL() . "/" . $this->query_string);
1462 Core\System::httpExit(503, ['title' => 'Error 503 - Service Temporarily Unavailable', 'description' => 'Core\System is currently overloaded. Please try again later.']);
1465 if (strstr($this->query_string, '.well-known/host-meta') && ($this->query_string != '.well-known/host-meta')) {
1466 Core\System::httpExit(404);
1469 if (!$this->getMode()->isInstall()) {
1470 // Force SSL redirection
1471 if (Core\Config::get('system', 'force_ssl') && ($this->getScheme() == "http")
1472 && intval(Core\Config::get('system', 'ssl_policy')) == SSL_POLICY_FULL
1473 && strpos($this->getBaseURL(), 'https://') === 0
1474 && $_SERVER['REQUEST_METHOD'] == 'GET') {
1475 header('HTTP/1.1 302 Moved Temporarily');
1476 header('Location: ' . $this->getBaseURL() . '/' . $this->query_string);
1480 Core\Session::init();
1481 Core\Hook::callAll('init_1');
1484 // Exclude the backend processes from the session management
1485 if (!$this->isBackend()) {
1486 $stamp1 = microtime(true);
1488 $this->saveTimestamp($stamp1, 'parser');
1489 Core\L10n::setSessionVariable();
1490 Core\L10n::setLangFromSession();
1493 Core\Worker::executeIfIdle();
1497 if (!empty($_GET['zrl']) && $this->getMode()->isNormal()) {
1498 $this->query_string = Model\Profile::stripZrls($this->query_string);
1499 if (!local_user()) {
1500 // Only continue when the given profile link seems valid
1501 // Valid profile links contain a path with "/profile/" and no query parameters
1502 if ((parse_url($_GET['zrl'], PHP_URL_QUERY) == "") &&
1503 strstr(parse_url($_GET['zrl'], PHP_URL_PATH), "/profile/")) {
1504 if (defaults($_SESSION, "visitor_home", "") != $_GET["zrl"]) {
1505 $_SESSION['my_url'] = $_GET['zrl'];
1506 $_SESSION['authenticated'] = 0;
1508 Model\Profile::zrlInit($this);
1510 // Someone came with an invalid parameter, maybe as a DDoS attempt
1511 // We simply stop processing here
1512 Core\Logger::log("Invalid ZRL parameter " . $_GET['zrl'], Core\Logger::DEBUG);
1513 Core\System::httpExit(403, ['title' => '403 Forbidden']);
1518 if (!empty($_GET['owt']) && $this->getMode()->isNormal()) {
1519 $token = $_GET['owt'];
1520 $this->query_string = Model\Profile::stripQueryParam($this->query_string, 'owt');
1521 Model\Profile::openWebAuthInit($token);
1524 Module\Login::sessionAuth();
1526 if (empty($_SESSION['authenticated'])) {
1527 header('X-Account-Management-Status: none');
1530 $_SESSION['sysmsg'] = defaults($_SESSION, 'sysmsg' , []);
1531 $_SESSION['sysmsg_info'] = defaults($_SESSION, 'sysmsg_info' , []);
1532 $_SESSION['last_updated'] = defaults($_SESSION, 'last_updated', []);
1535 * check_config() is responsible for running update scripts. These automatically
1536 * update the DB schema whenever we push a new one out. It also checks to see if
1537 * any addons have been added or removed and reacts accordingly.
1540 // in install mode, any url loads install module
1541 // but we need "view" module for stylesheet
1542 if ($this->getMode()->isInstall() && $this->module != 'view') {
1543 $this->module = 'install';
1544 } elseif (!$this->getMode()->has(App\Mode::MAINTENANCEDISABLED) && $this->module != 'view') {
1545 $this->module = 'maintenance';
1548 Core\Update::check(false);
1549 Core\Addon::loadAddons();
1550 Core\Hook::loadHooks();
1561 'right_aside' => '',
1566 if (strlen($this->module)) {
1567 // Compatibility with the Android Diaspora client
1568 if ($this->module == 'stream') {
1569 $this->internalRedirect('network?f=&order=post');
1572 if ($this->module == 'conversations') {
1573 $this->internalRedirect('message');
1576 if ($this->module == 'commented') {
1577 $this->internalRedirect('network?f=&order=comment');
1580 if ($this->module == 'liked') {
1581 $this->internalRedirect('network?f=&order=comment');
1584 if ($this->module == 'activity') {
1585 $this->internalRedirect('network/?f=&conv=1');
1588 if (($this->module == 'status_messages') && ($this->cmd == 'status_messages/new')) {
1589 $this->internalRedirect('bookmarklet');
1592 if (($this->module == 'user') && ($this->cmd == 'user/edit')) {
1593 $this->internalRedirect('settings');
1596 if (($this->module == 'tag_followings') && ($this->cmd == 'tag_followings/manage')) {
1597 $this->internalRedirect('search');
1600 // Compatibility with the Firefox App
1601 if (($this->module == "users") && ($this->cmd == "users/sign_in")) {
1602 $this->module = "login";
1605 $privateapps = Core\Config::get('config', 'private_addons', false);
1606 if (Core\Addon::isEnabled($this->module) && file_exists("addon/{$this->module}/{$this->module}.php")) {
1607 //Check if module is an app and if public access to apps is allowed or not
1608 if ((!local_user()) && Core\Hook::isAddonApp($this->module) && $privateapps) {
1609 info(Core\L10n::t("You must be logged in to use addons. "));
1611 include_once "addon/{$this->module}/{$this->module}.php";
1612 if (function_exists($this->module . '_module')) {
1613 LegacyModule::setModuleFile("addon/{$this->module}/{$this->module}.php");
1614 $this->module_class = 'Friendica\\LegacyModule';
1615 $this->module_loaded = true;
1620 // Controller class routing
1621 if (! $this->module_loaded && class_exists('Friendica\\Module\\' . ucfirst($this->module))) {
1622 $this->module_class = 'Friendica\\Module\\' . ucfirst($this->module);
1623 $this->module_loaded = true;
1626 /* If not, next look for a 'standard' program module in the 'mod' directory
1627 * We emulate a Module class through the LegacyModule class
1629 if (! $this->module_loaded && file_exists("mod/{$this->module}.php")) {
1630 LegacyModule::setModuleFile("mod/{$this->module}.php");
1631 $this->module_class = 'Friendica\\LegacyModule';
1632 $this->module_loaded = true;
1635 /* The URL provided does not resolve to a valid module.
1637 * On Dreamhost sites, quite often things go wrong for no apparent reason and they send us to '/internal_error.html'.
1638 * We don't like doing this, but as it occasionally accounts for 10-20% or more of all site traffic -
1639 * 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
1640 * this will often succeed and eventually do the right thing.
1642 * Otherwise we are going to emit a 404 not found.
1644 if (! $this->module_loaded) {
1645 // Stupid browser tried to pre-fetch our Javascript img template. Don't log the event or return anything - just quietly exit.
1646 if (!empty($_SERVER['QUERY_STRING']) && preg_match('/{[0-9]}/', $_SERVER['QUERY_STRING']) !== 0) {
1650 if (!empty($_SERVER['QUERY_STRING']) && ($_SERVER['QUERY_STRING'] === 'q=internal_error.html') && isset($dreamhost_error_hack)) {
1651 Core\Logger::log('index.php: dreamhost_error_hack invoked. Original URI =' . $_SERVER['REQUEST_URI']);
1652 $this->internalRedirect($_SERVER['REQUEST_URI']);
1655 Core\Logger::log('index.php: page not found: ' . $_SERVER['REQUEST_URI'] . ' ADDRESS: ' . $_SERVER['REMOTE_ADDR'] . ' QUERY: ' . $_SERVER['QUERY_STRING'], Core\Logger::DEBUG);
1657 header($_SERVER["SERVER_PROTOCOL"] . ' 404 ' . Core\L10n::t('Not Found'));
1658 $tpl = Core\Renderer::getMarkupTemplate("404.tpl");
1659 $this->page['content'] = Core\Renderer::replaceMacros($tpl, [
1660 '$message' => Core\L10n::t('Page not found.')
1667 // Initialize module that can set the current theme in the init() method, either directly or via App->profile_uid
1668 if ($this->module_loaded) {
1669 $this->page['page_title'] = $this->module;
1672 Core\Hook::callAll($this->module . '_mod_init', $placeholder);
1674 call_user_func([$this->module_class, 'init']);
1676 // "rawContent" is especially meant for technical endpoints.
1677 // This endpoint doesn't need any theme initialization or other comparable stuff.
1678 if (!$this->error) {
1679 call_user_func([$this->module_class, 'rawContent']);
1683 // Load current theme info after module has been initialized as theme could have been set in module
1684 $theme_info_file = 'view/theme/' . $this->getCurrentTheme() . '/theme.php';
1685 if (file_exists($theme_info_file)) {
1686 require_once $theme_info_file;
1689 if (function_exists(str_replace('-', '_', $this->getCurrentTheme()) . '_init')) {
1690 $func = str_replace('-', '_', $this->getCurrentTheme()) . '_init';
1694 if ($this->module_loaded) {
1695 if (! $this->error && $_SERVER['REQUEST_METHOD'] === 'POST') {
1696 Core\Hook::callAll($this->module . '_mod_post', $_POST);
1697 call_user_func([$this->module_class, 'post']);
1700 if (! $this->error) {
1701 Core\Hook::callAll($this->module . '_mod_afterpost', $placeholder);
1702 call_user_func([$this->module_class, 'afterpost']);
1705 if (! $this->error) {
1706 $arr = ['content' => $content];
1707 Core\Hook::callAll($this->module . '_mod_content', $arr);
1708 $content = $arr['content'];
1709 $arr = ['content' => call_user_func([$this->module_class, 'content'])];
1710 Core\Hook::callAll($this->module . '_mod_aftercontent', $arr);
1711 $content .= $arr['content'];
1715 // initialise content region
1716 if ($this->getMode()->isNormal()) {
1717 Core\Hook::callAll('page_content_top', $this->page['content']);
1720 $this->page['content'] .= $content;
1722 /* Create the page head after setting the language
1723 * and getting any auth credentials.
1725 * Moved initHead() and initFooter() to after
1726 * all the module functions have executed so that all
1727 * theme choices made by the modules can take effect.
1731 /* Build the page ending -- this is stuff that goes right before
1732 * the closing </body> tag
1734 $this->initFooter();
1736 /* now that we've been through the module content, see if the page reported
1737 * a permission problem and if so, a 403 response would seem to be in order.
1739 if (stristr(implode("", $_SESSION['sysmsg']), Core\L10n::t('Permission denied'))) {
1740 header($_SERVER["SERVER_PROTOCOL"] . ' 403 ' . Core\L10n::t('Permission denied.'));
1743 // Report anything which needs to be communicated in the notification area (before the main body)
1744 Core\Hook::callAll('page_end', $this->page['content']);
1746 // Add the navigation (menu) template
1747 if ($this->module != 'install' && $this->module != 'maintenance') {
1748 $this->page['htmlhead'] .= Core\Renderer::replaceMacros(Core\Renderer::getMarkupTemplate('nav_head.tpl'), []);
1749 $this->page['nav'] = Content\Nav::build($this);
1752 // Build the page - now that we have all the components
1753 if (isset($_GET["mode"]) && (($_GET["mode"] == "raw") || ($_GET["mode"] == "minimal"))) {
1754 $doc = new DOMDocument();
1756 $target = new DOMDocument();
1757 $target->loadXML("<root></root>");
1759 $content = mb_convert_encoding($this->page["content"], 'HTML-ENTITIES', "UTF-8");
1761 /// @TODO one day, kill those error-surpressing @ stuff, or PHP should ban it
1762 @$doc->loadHTML($content);
1764 $xpath = new DOMXPath($doc);
1766 $list = $xpath->query("//*[contains(@id,'tread-wrapper-')]"); /* */
1768 foreach ($list as $item) {
1769 $item = $target->importNode($item, true);
1771 // And then append it to the target
1772 $target->documentElement->appendChild($item);
1775 if ($_GET["mode"] == "raw") {
1776 header("Content-type: text/html; charset=utf-8");
1778 echo substr($target->saveHTML(), 6, -8);
1784 $page = $this->page;
1785 $profile = $this->profile;
1787 header("X-Friendica-Version: " . FRIENDICA_VERSION);
1788 header("Content-type: text/html; charset=utf-8");
1790 if (Core\Config::get('system', 'hsts') && (Core\Config::get('system', 'ssl_policy') == SSL_POLICY_FULL)) {
1791 header("Strict-Transport-Security: max-age=31536000");
1794 // Some security stuff
1795 header('X-Content-Type-Options: nosniff');
1796 header('X-XSS-Protection: 1; mode=block');
1797 header('X-Permitted-Cross-Domain-Policies: none');
1798 header('X-Frame-Options: sameorigin');
1800 // Things like embedded OSM maps don't work, when this is enabled
1801 // 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'");
1803 /* We use $_GET["mode"] for special page templates. So we will check if we have
1804 * to load another page template than the default one.
1805 * The page templates are located in /view/php/ or in the theme directory.
1807 if (isset($_GET["mode"])) {
1808 $template = Core\Theme::getPathForFile($_GET["mode"] . '.php');
1811 // If there is no page template use the default page template
1812 if (empty($template)) {
1813 $template = Core\Theme::getPathForFile("default.php");
1816 // Theme templates expect $a as an App instance
1819 // Used as is in view/php/default.php
1820 $lang = Core\L10n::getCurrentLang();
1822 /// @TODO Looks unsafe (remote-inclusion), is maybe not but Core\Theme::getPathForFile() uses file_exists() but does not escape anything
1823 require_once $template;
1827 * Redirects to another module relative to the current Friendica base.
1828 * If you want to redirect to a external URL, use System::externalRedirectTo()
1830 * @param string $toUrl The destination URL (Default is empty, which is the default page of the Friendica node)
1831 * @param bool $ssl if true, base URL will try to get called with https:// (works just for relative paths)
1833 * @throws InternalServerErrorException In Case the given URL is not relative to the Friendica node
1835 public function internalRedirect($toUrl = '', $ssl = false)
1837 if (!empty(parse_url($toUrl, PHP_URL_SCHEME))) {
1838 throw new InternalServerErrorException("'$toUrl is not a relative path, please use System::externalRedirectTo");
1841 $redirectTo = $this->getBaseURL($ssl) . '/' . ltrim($toUrl, '/');
1842 Core\System::externalRedirect($redirectTo);
1846 * Automatically redirects to relative or absolute URL
1847 * Should only be used if it isn't clear if the URL is either internal or external
1849 * @param string $toUrl The target URL
1850 * @throws InternalServerErrorException
1852 public function redirect($toUrl)
1854 if (!empty(parse_url($toUrl, PHP_URL_SCHEME))) {
1855 Core\System::externalRedirect($toUrl);
1857 $this->internalRedirect($toUrl);