7 use Detection\MobileDetect;
11 use Friendica\Database\DBA;
12 use Friendica\Network\HTTPException\InternalServerErrorException;
18 * @brief Our main application structure for the life of this page.
20 * Primarily deals with the URL that got us here
21 * and tries to make some sense of it, and
22 * stores our page contents and config storage
23 * and anything else that might need to be passed around
24 * before we spit the page out.
29 public $module_loaded = false;
30 public $module_class = null;
31 public $query_string = '';
43 public $error = false;
49 public $interactive = true;
51 public $is_mobile = false;
52 public $is_tablet = false;
53 public $performance = [];
54 public $callstack = [];
55 public $theme_info = [];
57 // Allow themes to control internal parameters
58 // by changing App values in theme.php
60 public $sourcename = '';
61 public $videowidth = 425;
62 public $videoheight = 350;
63 public $force_max_items = 0;
64 public $theme_events_in_profile = true;
66 public $stylesheets = [];
67 public $footerScripts = [];
70 * @var App\Mode The Mode of the Application
75 * @var string The App base path
80 * @var string The App URL path
85 * @var bool true, if the call is from the Friendica APP, otherwise false
87 private $isFriendicaApp;
90 * @var bool true, if the call is from an backend node (f.e. worker)
95 * @var string The name of the current theme
97 private $currentTheme;
100 * @var bool check if request was an AJAX (xmlhttprequest) request
107 public $mobileDetect;
110 * Register a stylesheet file path to be included in the <head> tag of every page.
111 * Inclusion is done in App->initHead().
112 * The path can be absolute or relative to the Friendica installation base folder.
116 * @param string $path
118 public function registerStylesheet($path)
120 $url = str_replace($this->getBasePath() . DIRECTORY_SEPARATOR, '', $path);
122 $this->stylesheets[] = trim($url, '/');
126 * Register a javascript file path to be included in the <footer> tag of every page.
127 * Inclusion is done in App->initFooter().
128 * The path can be absolute or relative to the Friendica installation base folder.
132 * @param string $path
134 public function registerFooterScript($path)
136 $url = str_replace($this->getBasePath() . DIRECTORY_SEPARATOR, '', $path);
138 $this->footerScripts[] = trim($url, '/');
147 * @brief App constructor.
149 * @param string $basePath Path to the app base folder
150 * @param bool $isBackend Whether it is used for backend or frontend (Default true=backend)
152 * @throws Exception if the Basepath is not usable
154 public function __construct($basePath, $isBackend = true)
156 if (!static::isDirectoryUsable($basePath, false)) {
157 throw new Exception('Basepath ' . $basePath . ' isn\'t usable.');
160 BaseObject::setApp($this);
162 $this->basePath = rtrim($basePath, DIRECTORY_SEPARATOR);
163 $this->checkBackend($isBackend);
164 $this->checkFriendicaApp();
166 $this->performance['start'] = microtime(true);
167 $this->performance['database'] = 0;
168 $this->performance['database_write'] = 0;
169 $this->performance['cache'] = 0;
170 $this->performance['cache_write'] = 0;
171 $this->performance['network'] = 0;
172 $this->performance['file'] = 0;
173 $this->performance['rendering'] = 0;
174 $this->performance['parser'] = 0;
175 $this->performance['marktime'] = 0;
176 $this->performance['markstart'] = microtime(true);
178 $this->callstack['database'] = [];
179 $this->callstack['database_write'] = [];
180 $this->callstack['cache'] = [];
181 $this->callstack['cache_write'] = [];
182 $this->callstack['network'] = [];
183 $this->callstack['file'] = [];
184 $this->callstack['rendering'] = [];
185 $this->callstack['parser'] = [];
187 $this->mode = new App\Mode($basePath);
193 // This has to be quite large to deal with embedded private photos
194 ini_set('pcre.backtrack_limit', 500000);
196 $this->scheme = 'http';
198 if (!empty($_SERVER['HTTPS']) ||
199 !empty($_SERVER['HTTP_FORWARDED']) && preg_match('/proto=https/', $_SERVER['HTTP_FORWARDED']) ||
200 !empty($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https' ||
201 !empty($_SERVER['HTTP_X_FORWARDED_SSL']) && $_SERVER['HTTP_X_FORWARDED_SSL'] == 'on' ||
202 !empty($_SERVER['FRONT_END_HTTPS']) && $_SERVER['FRONT_END_HTTPS'] == 'on' ||
203 !empty($_SERVER['SERVER_PORT']) && (intval($_SERVER['SERVER_PORT']) == 443) // XXX: reasonable assumption, but isn't this hardcoding too much?
205 $this->scheme = 'https';
208 if (!empty($_SERVER['SERVER_NAME'])) {
209 $this->hostname = $_SERVER['SERVER_NAME'];
211 if (!empty($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] != 80 && $_SERVER['SERVER_PORT'] != 443) {
212 $this->hostname .= ':' . $_SERVER['SERVER_PORT'];
217 get_include_path() . PATH_SEPARATOR
218 . $this->getBasePath() . DIRECTORY_SEPARATOR . 'include' . PATH_SEPARATOR
219 . $this->getBasePath() . DIRECTORY_SEPARATOR . 'library' . PATH_SEPARATOR
220 . $this->getBasePath());
222 if (!empty($_SERVER['QUERY_STRING']) && strpos($_SERVER['QUERY_STRING'], 'pagename=') === 0) {
223 $this->query_string = substr($_SERVER['QUERY_STRING'], 9);
224 } elseif (!empty($_SERVER['QUERY_STRING']) && strpos($_SERVER['QUERY_STRING'], 'q=') === 0) {
225 $this->query_string = substr($_SERVER['QUERY_STRING'], 2);
228 // removing trailing / - maybe a nginx problem
229 $this->query_string = ltrim($this->query_string, '/');
231 if (!empty($_GET['pagename'])) {
232 $this->cmd = trim($_GET['pagename'], '/\\');
233 } elseif (!empty($_GET['q'])) {
234 $this->cmd = trim($_GET['q'], '/\\');
238 $this->query_string = str_replace($this->cmd . '&', $this->cmd . '?', $this->query_string);
240 // unix style "homedir"
241 if (substr($this->cmd, 0, 1) === '~') {
242 $this->cmd = 'profile/' . substr($this->cmd, 1);
245 // Diaspora style profile url
246 if (substr($this->cmd, 0, 2) === 'u/') {
247 $this->cmd = 'profile/' . substr($this->cmd, 2);
251 * Break the URL path into C style argc/argv style arguments for our
252 * modules. Given "http://example.com/module/arg1/arg2", $this->argc
253 * will be 3 (integer) and $this->argv will contain:
259 * There will always be one argument. If provided a naked domain
260 * URL, $this->argv[0] is set to "home".
263 $this->argv = explode('/', $this->cmd);
264 $this->argc = count($this->argv);
265 if ((array_key_exists('0', $this->argv)) && strlen($this->argv[0])) {
266 $this->module = str_replace('.', '_', $this->argv[0]);
267 $this->module = str_replace('-', '_', $this->module);
270 $this->argv = ['home'];
271 $this->module = 'home';
274 // Detect mobile devices
275 $mobile_detect = new MobileDetect();
277 $this->mobileDetect = $mobile_detect;
279 $this->is_mobile = $mobile_detect->isMobile();
280 $this->is_tablet = $mobile_detect->isTablet();
282 $this->isAjax = strtolower(defaults($_SERVER, 'HTTP_X_REQUESTED_WITH', '')) == 'xmlhttprequest';
284 // Register template engines
285 Core\Renderer::registerTemplateEngine('Friendica\Render\FriendicaSmartyEngine');
289 * Returns the Mode of the Application
291 * @return App\Mode The Application Mode
293 * @throws InternalServerErrorException when the mode isn't created
295 public function getMode()
297 if (empty($this->mode)) {
298 throw new InternalServerErrorException('Mode of the Application is not defined');
305 * Reloads the whole app instance
307 public function reload()
309 // The order of the following calls is important to ensure proper initialization
310 $this->loadConfigFiles();
312 $this->loadDatabase();
314 $this->getMode()->determine($this->getBasePath());
316 $this->determineURLPath();
320 if ($this->getMode()->has(App\Mode::DBAVAILABLE)) {
321 Core\Hook::loadHooks();
323 $this->loadAddonConfig();
326 $this->loadDefaultTimezone();
330 $this->process_id = Core\System::processID('log');
334 * Load the configuration files
336 * First loads the default value for all the configuration keys, then the legacy configuration files, then the
337 * expected local.config.php
339 private function loadConfigFiles()
341 $this->loadConfigFile($this->getBasePath() . '/config/defaults.config.php');
342 $this->loadConfigFile($this->getBasePath() . '/config/settings.config.php');
344 // Legacy .htconfig.php support
345 if (file_exists($this->getBasePath() . '/.htpreconfig.php')) {
347 include $this->getBasePath() . '/.htpreconfig.php';
350 // Legacy .htconfig.php support
351 if (file_exists($this->getBasePath() . '/.htconfig.php')) {
354 include $this->getBasePath() . '/.htconfig.php';
356 $this->setConfigValue('database', 'hostname', $db_host);
357 $this->setConfigValue('database', 'username', $db_user);
358 $this->setConfigValue('database', 'password', $db_pass);
359 $this->setConfigValue('database', 'database', $db_data);
360 if (isset($a->config['system']['db_charset'])) {
361 $this->setConfigValue('database', 'charset', $a->config['system']['db_charset']);
364 unset($db_host, $db_user, $db_pass, $db_data);
366 if (isset($default_timezone)) {
367 $this->setConfigValue('system', 'default_timezone', $default_timezone);
368 unset($default_timezone);
371 if (isset($pidfile)) {
372 $this->setConfigValue('system', 'pidfile', $pidfile);
377 $this->setConfigValue('system', 'language', $lang);
382 if (file_exists($this->getBasePath() . '/config/local.config.php')) {
383 $this->loadConfigFile($this->getBasePath() . '/config/local.config.php', true);
384 } elseif (file_exists($this->getBasePath() . '/config/local.ini.php')) {
385 $this->loadINIConfigFile($this->getBasePath() . '/config/local.ini.php', true);
390 * Tries to load the specified legacy configuration file into the App->config array.
391 * Doesn't overwrite previously set values by default to prevent default config files to supersede DB Config.
393 * @deprecated since version 2018.12
394 * @param string $filepath
395 * @param bool $overwrite Force value overwrite if the config key already exists
398 public function loadINIConfigFile($filepath, $overwrite = false)
400 if (!file_exists($filepath)) {
401 throw new Exception('Error parsing non-existent INI config file ' . $filepath);
404 $contents = include($filepath);
406 $config = parse_ini_string($contents, true, INI_SCANNER_TYPED);
408 if ($config === false) {
409 throw new Exception('Error parsing INI config file ' . $filepath);
412 $this->loadConfigArray($config, $overwrite);
416 * Tries to load the specified configuration file into the App->config array.
417 * Doesn't overwrite previously set values by default to prevent default config files to supersede DB Config.
419 * The config format is PHP array and the template for configuration files is the following:
427 * @param string $filepath
428 * @param bool $overwrite Force value overwrite if the config key already exists
431 public function loadConfigFile($filepath, $overwrite = false)
433 if (!file_exists($filepath)) {
434 throw new Exception('Error loading non-existent config file ' . $filepath);
437 $config = include($filepath);
439 if (!is_array($config)) {
440 throw new Exception('Error loading config file ' . $filepath);
443 $this->loadConfigArray($config, $overwrite);
447 * Loads addons configuration files
449 * First loads all activated addons default configuration through the load_config hook, then load the local.config.php
450 * again to overwrite potential local addon configuration.
452 private function loadAddonConfig()
454 // Loads addons default config
455 Core\Hook::callAll('load_config');
457 // Load the local addon config file to overwritten default addon config values
458 if (file_exists($this->getBasePath() . '/config/addon.config.php')) {
459 $this->loadConfigFile($this->getBasePath() . '/config/addon.config.php', true);
460 } elseif (file_exists($this->getBasePath() . '/config/addon.ini.php')) {
461 $this->loadINIConfigFile($this->getBasePath() . '/config/addon.ini.php', true);
466 * Tries to load the specified configuration array into the App->config array.
467 * Doesn't overwrite previously set values by default to prevent default config files to supersede DB Config.
469 * @param array $config
470 * @param bool $overwrite Force value overwrite if the config key already exists
472 private function loadConfigArray(array $config, $overwrite = false)
474 foreach ($config as $category => $values) {
475 foreach ($values as $key => $value) {
477 $this->setConfigValue($category, $key, $value);
479 $this->setDefaultConfigValue($category, $key, $value);
486 * Loads the default timezone
488 * Include support for legacy $default_timezone
490 * @global string $default_timezone
492 private function loadDefaultTimezone()
494 if ($this->getConfigValue('system', 'default_timezone')) {
495 $this->timezone = $this->getConfigValue('system', 'default_timezone');
497 global $default_timezone;
498 $this->timezone = !empty($default_timezone) ? $default_timezone : 'UTC';
501 if ($this->timezone) {
502 date_default_timezone_set($this->timezone);
507 * Figure out if we are running at the top of a domain or in a sub-directory and adjust accordingly
509 private function determineURLPath()
511 /* Relative script path to the web server root
512 * Not all of those $_SERVER properties can be present, so we do by inverse priority order
514 $relative_script_path = '';
515 $relative_script_path = defaults($_SERVER, 'REDIRECT_URL' , $relative_script_path);
516 $relative_script_path = defaults($_SERVER, 'REDIRECT_URI' , $relative_script_path);
517 $relative_script_path = defaults($_SERVER, 'REDIRECT_SCRIPT_URL', $relative_script_path);
518 $relative_script_path = defaults($_SERVER, 'SCRIPT_URL' , $relative_script_path);
519 $relative_script_path = defaults($_SERVER, 'REQUEST_URI' , $relative_script_path);
521 $this->urlPath = $this->getConfigValue('system', 'urlpath');
523 /* $relative_script_path gives /relative/path/to/friendica/module/parameter
524 * QUERY_STRING gives pagename=module/parameter
526 * To get /relative/path/to/friendica we perform dirname() for as many levels as there are slashes in the QUERY_STRING
528 if (!empty($relative_script_path)) {
530 if (!empty($_SERVER['QUERY_STRING'])) {
531 $path = trim(rdirname($relative_script_path, substr_count(trim($_SERVER['QUERY_STRING'], '/'), '/') + 1), '/');
534 $path = trim($relative_script_path, '/');
537 if ($path && $path != $this->urlPath) {
538 $this->urlPath = $path;
543 public function loadDatabase()
545 if (DBA::connected()) {
549 $db_host = $this->getConfigValue('database', 'hostname');
550 $db_user = $this->getConfigValue('database', 'username');
551 $db_pass = $this->getConfigValue('database', 'password');
552 $db_data = $this->getConfigValue('database', 'database');
553 $charset = $this->getConfigValue('database', 'charset');
555 // Use environment variables for mysql if they are set beforehand
556 if (!empty(getenv('MYSQL_HOST'))
557 && !empty(getenv('MYSQL_USERNAME') || !empty(getenv('MYSQL_USER')))
558 && getenv('MYSQL_PASSWORD') !== false
559 && !empty(getenv('MYSQL_DATABASE')))
561 $db_host = getenv('MYSQL_HOST');
562 if (!empty(getenv('MYSQL_PORT'))) {
563 $db_host .= ':' . getenv('MYSQL_PORT');
565 if (!empty(getenv('MYSQL_USERNAME'))) {
566 $db_user = getenv('MYSQL_USERNAME');
568 $db_user = getenv('MYSQL_USER');
570 $db_pass = (string) getenv('MYSQL_PASSWORD');
571 $db_data = getenv('MYSQL_DATABASE');
574 $stamp1 = microtime(true);
576 if (DBA::connect($db_host, $db_user, $db_pass, $db_data, $charset)) {
577 // Loads DB_UPDATE_VERSION constant
578 Database\DBStructure::definition(false);
581 unset($db_host, $db_user, $db_pass, $db_data, $charset);
583 $this->saveTimestamp($stamp1, 'network');
587 * @brief Returns the base filesystem path of the App
589 * It first checks for the internal variable, then for DOCUMENT_ROOT and
594 public function getBasePath()
596 $basepath = $this->basePath;
599 $basepath = Core\Config::get('system', 'basepath');
602 if (!$basepath && !empty($_SERVER['DOCUMENT_ROOT'])) {
603 $basepath = $_SERVER['DOCUMENT_ROOT'];
606 if (!$basepath && !empty($_SERVER['PWD'])) {
607 $basepath = $_SERVER['PWD'];
610 return self::getRealPath($basepath);
614 * @brief Returns a normalized file path
616 * This is a wrapper for the "realpath" function.
617 * That function cannot detect the real path when some folders aren't readable.
618 * Since this could happen with some hosters we need to handle this.
620 * @param string $path The path that is about to be normalized
621 * @return string normalized path - when possible
623 public static function getRealPath($path)
625 $normalized = realpath($path);
627 if (!is_bool($normalized)) {
634 public function getScheme()
636 return $this->scheme;
640 * @brief Retrieves the Friendica instance base URL
642 * This function assembles the base URL from multiple parts:
643 * - Protocol is determined either by the request or a combination of
644 * system.ssl_policy and the $ssl parameter.
645 * - Host name is determined either by system.hostname or inferred from request
646 * - Path is inferred from SCRIPT_NAME
648 * Note: $ssl parameter value doesn't directly correlate with the resulting protocol
650 * @param bool $ssl Whether to append http or https under SSL_POLICY_SELFSIGN
651 * @return string Friendica server base URL
653 public function getBaseURL($ssl = false)
655 $scheme = $this->scheme;
657 if (Core\Config::get('system', 'ssl_policy') == SSL_POLICY_FULL) {
661 // Basically, we have $ssl = true on any links which can only be seen by a logged in user
662 // (and also the login link). Anything seen by an outsider will have it turned off.
664 if (Core\Config::get('system', 'ssl_policy') == SSL_POLICY_SELFSIGN) {
672 if (Core\Config::get('config', 'hostname') != '') {
673 $this->hostname = Core\Config::get('config', 'hostname');
676 return $scheme . '://' . $this->hostname . !empty($this->getURLPath() ? '/' . $this->getURLPath() : '' );
680 * @brief Initializes the baseurl components
682 * Clears the baseurl cache to prevent inconsistencies
686 public function setBaseURL($url)
688 $parsed = @parse_url($url);
691 if (!empty($parsed)) {
692 if (!empty($parsed['scheme'])) {
693 $this->scheme = $parsed['scheme'];
696 if (!empty($parsed['host'])) {
697 $hostname = $parsed['host'];
700 if (!empty($parsed['port'])) {
701 $hostname .= ':' . $parsed['port'];
703 if (!empty($parsed['path'])) {
704 $this->urlPath = trim($parsed['path'], '\\/');
707 if (file_exists($this->getBasePath() . '/.htpreconfig.php')) {
708 include $this->getBasePath() . '/.htpreconfig.php';
711 if (Core\Config::get('config', 'hostname') != '') {
712 $this->hostname = Core\Config::get('config', 'hostname');
715 if (!isset($this->hostname) || ($this->hostname == '')) {
716 $this->hostname = $hostname;
721 public function getHostName()
723 if (Core\Config::get('config', 'hostname') != '') {
724 $this->hostname = Core\Config::get('config', 'hostname');
727 return $this->hostname;
730 public function getURLPath()
732 return $this->urlPath;
736 * Initializes App->page['htmlhead'].
741 * - Registered stylesheets (through App->registerStylesheet())
742 * - Infinite scroll data
743 * - head.tpl template
745 public function initHead()
747 $interval = ((local_user()) ? Core\PConfig::get(local_user(), 'system', 'update_interval') : 40000);
749 // If the update is 'deactivated' set it to the highest integer number (~24 days)
751 $interval = 2147483647;
754 if ($interval < 10000) {
758 // compose the page title from the sitename and the
759 // current module called
760 if (!$this->module == '') {
761 $this->page['title'] = $this->config['sitename'] . ' (' . $this->module . ')';
763 $this->page['title'] = $this->config['sitename'];
766 if (!empty(Core\Renderer::$theme['stylesheet'])) {
767 $stylesheet = Core\Renderer::$theme['stylesheet'];
769 $stylesheet = $this->getCurrentThemeStylesheetPath();
772 $this->registerStylesheet($stylesheet);
774 $shortcut_icon = Core\Config::get('system', 'shortcut_icon');
775 if ($shortcut_icon == '') {
776 $shortcut_icon = 'images/friendica-32.png';
779 $touch_icon = Core\Config::get('system', 'touch_icon');
780 if ($touch_icon == '') {
781 $touch_icon = 'images/friendica-128.png';
784 Core\Hook::callAll('head', $this->page['htmlhead']);
786 $tpl = Core\Renderer::getMarkupTemplate('head.tpl');
787 /* put the head template at the beginning of page['htmlhead']
788 * since the code added by the modules frequently depends on it
791 $this->page['htmlhead'] = Core\Renderer::replaceMacros($tpl, [
792 '$baseurl' => $this->getBaseURL(),
793 '$local_user' => local_user(),
794 '$generator' => 'Friendica' . ' ' . FRIENDICA_VERSION,
795 '$delitem' => Core\L10n::t('Delete this item?'),
796 '$showmore' => Core\L10n::t('show more'),
797 '$showfewer' => Core\L10n::t('show fewer'),
798 '$update_interval' => $interval,
799 '$shortcut_icon' => $shortcut_icon,
800 '$touch_icon' => $touch_icon,
801 '$block_public' => intval(Core\Config::get('system', 'block_public')),
802 '$stylesheets' => $this->stylesheets,
803 ]) . $this->page['htmlhead'];
807 * Initializes App->page['footer'].
810 * - Javascript homebase
811 * - Mobile toggle link
812 * - Registered footer scripts (through App->registerFooterScript())
813 * - footer.tpl template
815 public function initFooter()
817 // If you're just visiting, let javascript take you home
818 if (!empty($_SESSION['visitor_home'])) {
819 $homebase = $_SESSION['visitor_home'];
820 } elseif (local_user()) {
821 $homebase = 'profile/' . $this->user['nickname'];
824 if (isset($homebase)) {
825 $this->page['footer'] .= '<script>var homebase="' . $homebase . '";</script>' . "\n";
829 * Add a "toggle mobile" link if we're using a mobile device
831 if ($this->is_mobile || $this->is_tablet) {
832 if (isset($_SESSION['show-mobile']) && !$_SESSION['show-mobile']) {
833 $link = 'toggle_mobile?address=' . urlencode(curPageURL());
835 $link = 'toggle_mobile?off=1&address=' . urlencode(curPageURL());
837 $this->page['footer'] .= Core\Renderer::replaceMacros(Core\Renderer::getMarkupTemplate("toggle_mobile_footer.tpl"), [
838 '$toggle_link' => $link,
839 '$toggle_text' => Core\L10n::t('toggle mobile')
843 Core\Hook::callAll('footer', $this->page['footer']);
845 $tpl = Core\Renderer::getMarkupTemplate('footer.tpl');
846 $this->page['footer'] = Core\Renderer::replaceMacros($tpl, [
847 '$baseurl' => $this->getBaseURL(),
848 '$footerScripts' => $this->footerScripts,
849 ]) . $this->page['footer'];
853 * @brief Removes the base url from an url. This avoids some mixed content problems.
855 * @param string $origURL
857 * @return string The cleaned url
859 public function removeBaseURL($origURL)
861 // Remove the hostname from the url if it is an internal link
862 $nurl = Util\Strings::normaliseLink($origURL);
863 $base = Util\Strings::normaliseLink($this->getBaseURL());
864 $url = str_replace($base . '/', '', $nurl);
866 // if it is an external link return the orignal value
867 if ($url == Util\Strings::normaliseLink($origURL)) {
875 * Saves a timestamp for a value - f.e. a call
876 * Necessary for profiling Friendica
878 * @param int $timestamp the Timestamp
879 * @param string $value A value to profile
881 public function saveTimestamp($timestamp, $value)
883 if (!isset($this->config['system']['profiler']) || !$this->config['system']['profiler']) {
887 $duration = (float) (microtime(true) - $timestamp);
889 if (!isset($this->performance[$value])) {
890 // Prevent ugly E_NOTICE
891 $this->performance[$value] = 0;
894 $this->performance[$value] += (float) $duration;
895 $this->performance['marktime'] += (float) $duration;
897 $callstack = Core\System::callstack();
899 if (!isset($this->callstack[$value][$callstack])) {
900 // Prevent ugly E_NOTICE
901 $this->callstack[$value][$callstack] = 0;
904 $this->callstack[$value][$callstack] += (float) $duration;
908 * Returns the current UserAgent as a String
910 * @return string the UserAgent as a String
912 public function getUserAgent()
915 FRIENDICA_PLATFORM . " '" .
916 FRIENDICA_CODENAME . "' " .
917 FRIENDICA_VERSION . '-' .
918 DB_UPDATE_VERSION . '; ' .
923 * Checks, if the call is from the Friendica App
926 * The friendica client has problems with the GUID in the notify. this is some workaround
928 private function checkFriendicaApp()
931 $this->isFriendicaApp = isset($_SERVER['HTTP_USER_AGENT']) && $_SERVER['HTTP_USER_AGENT'] == 'Apache-HttpClient/UNAVAILABLE (java 1.4)';
935 * Is the call via the Friendica app? (not a "normale" call)
937 * @return bool true if it's from the Friendica app
939 public function isFriendicaApp()
941 return $this->isFriendicaApp;
945 * @brief Checks if the site is called via a backend process
947 * This isn't a perfect solution. But we need this check very early.
948 * So we cannot wait until the modules are loaded.
950 * @param string $backend true, if the backend flag was set during App initialization
953 private function checkBackend($backend) {
976 // Check if current module is in backend or backend flag is set
977 $this->isBackend = (in_array($this->module, $backends) || $backend || $this->isBackend);
981 * Returns true, if the call is from a backend node (f.e. from a worker)
983 * @return bool Is it a known backend?
985 public function isBackend()
987 return $this->isBackend;
991 * @brief Checks if the maximum number of database processes is reached
993 * @return bool Is the limit reached?
995 public function isMaxProcessesReached()
997 // Deactivated, needs more investigating if this check really makes sense
1001 * Commented out to suppress static analyzer issues
1003 if ($this->is_backend()) {
1004 $process = 'backend';
1005 $max_processes = Core\Config::get('system', 'max_processes_backend');
1006 if (intval($max_processes) == 0) {
1010 $process = 'frontend';
1011 $max_processes = Core\Config::get('system', 'max_processes_frontend');
1012 if (intval($max_processes) == 0) {
1013 $max_processes = 20;
1017 $processlist = DBA::processlist();
1018 if ($processlist['list'] != '') {
1019 Core\Logger::log('Processcheck: Processes: ' . $processlist['amount'] . ' - Processlist: ' . $processlist['list'], Core\Logger::DEBUG);
1021 if ($processlist['amount'] > $max_processes) {
1022 Core\Logger::log('Processcheck: Maximum number of processes for ' . $process . ' tasks (' . $max_processes . ') reached.', Core\Logger::DEBUG);
1031 * @brief Checks if the minimal memory is reached
1033 * @return bool Is the memory limit reached?
1035 public function isMinMemoryReached()
1037 $min_memory = Core\Config::get('system', 'min_memory', 0);
1038 if ($min_memory == 0) {
1042 if (!is_readable('/proc/meminfo')) {
1046 $memdata = explode("\n", file_get_contents('/proc/meminfo'));
1049 foreach ($memdata as $line) {
1050 $data = explode(':', $line);
1051 if (count($data) != 2) {
1054 list($key, $val) = $data;
1055 $meminfo[$key] = (int) trim(str_replace('kB', '', $val));
1056 $meminfo[$key] = (int) ($meminfo[$key] / 1024);
1059 if (!isset($meminfo['MemFree'])) {
1063 $free = $meminfo['MemFree'];
1065 $reached = ($free < $min_memory);
1068 Core\Logger::log('Minimal memory reached: ' . $free . '/' . $meminfo['MemTotal'] . ' - limit ' . $min_memory, Core\Logger::DEBUG);
1075 * @brief Checks if the maximum load is reached
1077 * @return bool Is the load reached?
1079 public function isMaxLoadReached()
1081 if ($this->isBackend()) {
1082 $process = 'backend';
1083 $maxsysload = intval(Core\Config::get('system', 'maxloadavg'));
1084 if ($maxsysload < 1) {
1088 $process = 'frontend';
1089 $maxsysload = intval(Core\Config::get('system', 'maxloadavg_frontend'));
1090 if ($maxsysload < 1) {
1095 $load = Core\System::currentLoad();
1097 if (intval($load) > $maxsysload) {
1098 Core\Logger::log('system: load ' . $load . ' for ' . $process . ' tasks (' . $maxsysload . ') too high.');
1106 * Executes a child process with 'proc_open'
1108 * @param string $command The command to execute
1109 * @param array $args Arguments to pass to the command ( [ 'key' => value, 'key2' => value2, ... ]
1111 public function proc_run($command, $args)
1113 if (!function_exists('proc_open')) {
1117 $cmdline = $this->getConfigValue('config', 'php_path', 'php') . ' ' . escapeshellarg($command);
1119 foreach ($args as $key => $value) {
1120 if (!is_null($value) && is_bool($value) && !$value) {
1124 $cmdline .= ' --' . $key;
1125 if (!is_null($value) && !is_bool($value)) {
1126 $cmdline .= ' ' . $value;
1130 if ($this->isMinMemoryReached()) {
1134 if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
1135 $resource = proc_open('cmd /c start /b ' . $cmdline, [], $foo, $this->getBasePath());
1137 $resource = proc_open($cmdline . ' &', [], $foo, $this->getBasePath());
1139 if (!is_resource($resource)) {
1140 Core\Logger::log('We got no resource for command ' . $cmdline, Core\Logger::DEBUG);
1143 proc_close($resource);
1147 * @brief Returns the system user that is executing the script
1149 * This mostly returns something like "www-data".
1151 * @return string system username
1153 private static function getSystemUser()
1155 if (!function_exists('posix_getpwuid') || !function_exists('posix_geteuid')) {
1159 $processUser = posix_getpwuid(posix_geteuid());
1160 return $processUser['name'];
1164 * @brief Checks if a given directory is usable for the system
1166 * @return boolean the directory is usable
1168 public static function isDirectoryUsable($directory, $check_writable = true)
1170 if ($directory == '') {
1171 Core\Logger::log('Directory is empty. This shouldn\'t happen.', Core\Logger::DEBUG);
1175 if (!file_exists($directory)) {
1176 Core\Logger::log('Path "' . $directory . '" does not exist for user ' . self::getSystemUser(), Core\Logger::DEBUG);
1180 if (is_file($directory)) {
1181 Core\Logger::log('Path "' . $directory . '" is a file for user ' . self::getSystemUser(), Core\Logger::DEBUG);
1185 if (!is_dir($directory)) {
1186 Core\Logger::log('Path "' . $directory . '" is not a directory for user ' . self::getSystemUser(), Core\Logger::DEBUG);
1190 if ($check_writable && !is_writable($directory)) {
1191 Core\Logger::log('Path "' . $directory . '" is not writable for user ' . self::getSystemUser(), Core\Logger::DEBUG);
1199 * @param string $cat Config category
1200 * @param string $k Config key
1201 * @param mixed $default Default value if it isn't set
1203 * @return string Returns the value of the Config entry
1205 public function getConfigValue($cat, $k, $default = null)
1209 if ($cat === 'config') {
1210 if (isset($this->config[$k])) {
1211 $return = $this->config[$k];
1214 if (isset($this->config[$cat][$k])) {
1215 $return = $this->config[$cat][$k];
1223 * Sets a default value in the config cache. Ignores already existing keys.
1225 * @param string $cat Config category
1226 * @param string $k Config key
1227 * @param mixed $v Default value to set
1229 private function setDefaultConfigValue($cat, $k, $v)
1231 if (!isset($this->config[$cat][$k])) {
1232 $this->setConfigValue($cat, $k, $v);
1237 * Sets a value in the config cache. Accepts raw output from the config table
1239 * @param string $cat Config category
1240 * @param string $k Config key
1241 * @param mixed $v Value to set
1243 public function setConfigValue($cat, $k, $v)
1245 // Only arrays are serialized in database, so we have to unserialize sparingly
1246 $value = is_string($v) && preg_match("|^a:[0-9]+:{.*}$|s", $v) ? unserialize($v) : $v;
1248 if ($cat === 'config') {
1249 $this->config[$k] = $value;
1251 if (!isset($this->config[$cat])) {
1252 $this->config[$cat] = [];
1255 $this->config[$cat][$k] = $value;
1260 * Deletes a value from the config cache
1262 * @param string $cat Config category
1263 * @param string $k Config key
1265 public function deleteConfigValue($cat, $k)
1267 if ($cat === 'config') {
1268 if (isset($this->config[$k])) {
1269 unset($this->config[$k]);
1272 if (isset($this->config[$cat][$k])) {
1273 unset($this->config[$cat][$k]);
1280 * Retrieves a value from the user config cache
1282 * @param int $uid User Id
1283 * @param string $cat Config category
1284 * @param string $k Config key
1285 * @param mixed $default Default value if key isn't set
1287 * @return string The value of the config entry
1289 public function getPConfigValue($uid, $cat, $k, $default = null)
1293 if (isset($this->config[$uid][$cat][$k])) {
1294 $return = $this->config[$uid][$cat][$k];
1301 * Sets a value in the user config cache
1303 * Accepts raw output from the pconfig table
1305 * @param int $uid User Id
1306 * @param string $cat Config category
1307 * @param string $k Config key
1308 * @param mixed $v Value to set
1310 public function setPConfigValue($uid, $cat, $k, $v)
1312 // Only arrays are serialized in database, so we have to unserialize sparingly
1313 $value = is_string($v) && preg_match("|^a:[0-9]+:{.*}$|s", $v) ? unserialize($v) : $v;
1315 if (!isset($this->config[$uid]) || !is_array($this->config[$uid])) {
1316 $this->config[$uid] = [];
1319 if (!isset($this->config[$uid][$cat]) || !is_array($this->config[$uid][$cat])) {
1320 $this->config[$uid][$cat] = [];
1323 $this->config[$uid][$cat][$k] = $value;
1327 * Deletes a value from the user config cache
1329 * @param int $uid User Id
1330 * @param string $cat Config category
1331 * @param string $k Config key
1333 public function deletePConfigValue($uid, $cat, $k)
1335 if (isset($this->config[$uid][$cat][$k])) {
1336 unset($this->config[$uid][$cat][$k]);
1341 * Generates the site's default sender email address
1345 public function getSenderEmailAddress()
1347 $sender_email = Core\Config::get('config', 'sender_email');
1348 if (empty($sender_email)) {
1349 $hostname = $this->getHostName();
1350 if (strpos($hostname, ':')) {
1351 $hostname = substr($hostname, 0, strpos($hostname, ':'));
1354 $sender_email = 'noreply@' . $hostname;
1357 return $sender_email;
1361 * Returns the current theme name.
1363 * @return string the name of the current theme
1365 public function getCurrentTheme()
1367 if ($this->getMode()->isInstall()) {
1371 if (!$this->currentTheme) {
1372 $this->computeCurrentTheme();
1375 return $this->currentTheme;
1378 public function setCurrentTheme($theme)
1380 $this->currentTheme = $theme;
1384 * Computes the current theme name based on the node settings, the user settings and the device type
1388 private function computeCurrentTheme()
1390 $system_theme = Core\Config::get('system', 'theme');
1391 if (!$system_theme) {
1392 throw new Exception(Core\L10n::t('No system theme config value set.'));
1396 $this->currentTheme = $system_theme;
1398 $allowed_themes = explode(',', Core\Config::get('system', 'allowed_themes', $system_theme));
1401 // Find the theme that belongs to the user whose stuff we are looking at
1402 if ($this->profile_uid && ($this->profile_uid != local_user())) {
1403 // Allow folks to override user themes and always use their own on their own site.
1404 // This works only if the user is on the same server
1405 $user = DBA::selectFirst('user', ['theme'], ['uid' => $this->profile_uid]);
1406 if (DBA::isResult($user) && !Core\PConfig::get(local_user(), 'system', 'always_my_theme')) {
1407 $page_theme = $user['theme'];
1411 $user_theme = Core\Session::get('theme', $system_theme);
1413 // Specific mobile theme override
1414 if (($this->is_mobile || $this->is_tablet) && Core\Session::get('show-mobile', true)) {
1415 $system_mobile_theme = Core\Config::get('system', 'mobile-theme');
1416 $user_mobile_theme = Core\Session::get('mobile-theme', $system_mobile_theme);
1418 // --- means same mobile theme as desktop
1419 if (!empty($user_mobile_theme) && $user_mobile_theme !== '---') {
1420 $user_theme = $user_mobile_theme;
1425 $theme_name = $page_theme;
1427 $theme_name = $user_theme;
1431 && in_array($theme_name, $allowed_themes)
1432 && (file_exists('view/theme/' . $theme_name . '/style.css')
1433 || file_exists('view/theme/' . $theme_name . '/style.php'))
1435 $this->currentTheme = $theme_name;
1440 * @brief Return full URL to theme which is currently in effect.
1442 * Provide a sane default if nothing is chosen or the specified theme does not exist.
1446 public function getCurrentThemeStylesheetPath()
1448 return Core\Theme::getStylesheetPath($this->getCurrentTheme());
1452 * Check if request was an AJAX (xmlhttprequest) request.
1454 * @return boolean true if it was an AJAX request
1456 public function isAjax()
1458 return $this->isAjax;
1462 * Returns the value of a argv key
1463 * TODO there are a lot of $a->argv usages in combination with defaults() which can be replaced with this method
1465 * @param int $position the position of the argument
1466 * @param mixed $default the default value if not found
1468 * @return mixed returns the value of the argument
1470 public function getArgumentValue($position, $default = '')
1472 if (array_key_exists($position, $this->argv)) {
1473 return $this->argv[$position];
1480 * Sets the base url for use in cmdline programs which don't have
1481 * $_SERVER variables
1483 public function checkURL()
1485 $url = Core\Config::get('system', 'url');
1487 // if the url isn't set or the stored url is radically different
1488 // than the currently visited url, store the current value accordingly.
1489 // "Radically different" ignores common variations such as http vs https
1490 // and www.example.com vs example.com.
1491 // We will only change the url to an ip address if there is no existing setting
1493 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()))) {
1494 Core\Config::set('system', 'url', $this->getBaseURL());
1499 * Frontend App script
1501 * The App object behaves like a container and a dispatcher at the same time, including a representation of the
1502 * request and a representation of the response.
1504 * This probably should change to limit the size of this monster method.
1506 public function runFrontend()
1508 // Missing DB connection: ERROR
1509 if ($this->getMode()->has(App\Mode::LOCALCONFIGPRESENT) && !$this->getMode()->has(App\Mode::DBAVAILABLE)) {
1510 Core\System::httpExit(500, ['title' => 'Error 500 - Internal Server Error', 'description' => 'Apologies but the website is unavailable at the moment.']);
1513 // Max Load Average reached: ERROR
1514 if ($this->isMaxProcessesReached() || $this->isMaxLoadReached()) {
1515 header('Retry-After: 120');
1516 header('Refresh: 120; url=' . $this->getBaseURL() . "/" . $this->query_string);
1518 Core\System::httpExit(503, ['title' => 'Error 503 - Service Temporarily Unavailable', 'description' => 'Core\System is currently overloaded. Please try again later.']);
1521 if (strstr($this->query_string, '.well-known/host-meta') && ($this->query_string != '.well-known/host-meta')) {
1522 Core\System::httpExit(404);
1525 if (!$this->getMode()->isInstall()) {
1526 // Force SSL redirection
1527 if (Core\Config::get('system', 'force_ssl') && ($this->getScheme() == "http")
1528 && intval(Core\Config::get('system', 'ssl_policy')) == SSL_POLICY_FULL
1529 && strpos($this->getBaseURL(), 'https://') === 0
1530 && $_SERVER['REQUEST_METHOD'] == 'GET') {
1531 header('HTTP/1.1 302 Moved Temporarily');
1532 header('Location: ' . $this->getBaseURL() . '/' . $this->query_string);
1536 Core\Session::init();
1537 Core\Hook::callAll('init_1');
1540 // Exclude the backend processes from the session management
1541 if (!$this->isBackend()) {
1542 $stamp1 = microtime(true);
1544 $this->saveTimestamp($stamp1, 'parser');
1545 Core\L10n::setSessionVariable();
1546 Core\L10n::setLangFromSession();
1549 Core\Worker::executeIfIdle();
1553 if (!empty($_GET['zrl']) && $this->getMode()->isNormal()) {
1554 $this->query_string = Model\Profile::stripZrls($this->query_string);
1555 if (!local_user()) {
1556 // Only continue when the given profile link seems valid
1557 // Valid profile links contain a path with "/profile/" and no query parameters
1558 if ((parse_url($_GET['zrl'], PHP_URL_QUERY) == "") &&
1559 strstr(parse_url($_GET['zrl'], PHP_URL_PATH), "/profile/")) {
1560 if (defaults($_SESSION, "visitor_home", "") != $_GET["zrl"]) {
1561 $_SESSION['my_url'] = $_GET['zrl'];
1562 $_SESSION['authenticated'] = 0;
1564 Model\Profile::zrlInit($this);
1566 // Someone came with an invalid parameter, maybe as a DDoS attempt
1567 // We simply stop processing here
1568 Core\Logger::log("Invalid ZRL parameter " . $_GET['zrl'], Core\Logger::DEBUG);
1569 Core\System::httpExit(403, ['title' => '403 Forbidden']);
1574 if (!empty($_GET['owt']) && $this->getMode()->isNormal()) {
1575 $token = $_GET['owt'];
1576 $this->query_string = Model\Profile::stripQueryParam($this->query_string, 'owt');
1577 Model\Profile::openWebAuthInit($token);
1580 Module\Login::sessionAuth();
1582 if (empty($_SESSION['authenticated'])) {
1583 header('X-Account-Management-Status: none');
1586 $_SESSION['sysmsg'] = defaults($_SESSION, 'sysmsg' , []);
1587 $_SESSION['sysmsg_info'] = defaults($_SESSION, 'sysmsg_info' , []);
1588 $_SESSION['last_updated'] = defaults($_SESSION, 'last_updated', []);
1591 * check_config() is responsible for running update scripts. These automatically
1592 * update the DB schema whenever we push a new one out. It also checks to see if
1593 * any addons have been added or removed and reacts accordingly.
1596 // in install mode, any url loads install module
1597 // but we need "view" module for stylesheet
1598 if ($this->getMode()->isInstall() && $this->module != 'view') {
1599 $this->module = 'install';
1600 } elseif (!$this->getMode()->has(App\Mode::MAINTENANCEDISABLED) && $this->module != 'view') {
1601 $this->module = 'maintenance';
1604 Core\Update::check(false);
1605 Core\Addon::loadAddons();
1606 Core\Hook::loadHooks();
1617 'right_aside' => '',
1622 if (strlen($this->module)) {
1623 // Compatibility with the Android Diaspora client
1624 if ($this->module == 'stream') {
1625 $this->internalRedirect('network?f=&order=post');
1628 if ($this->module == 'conversations') {
1629 $this->internalRedirect('message');
1632 if ($this->module == 'commented') {
1633 $this->internalRedirect('network?f=&order=comment');
1636 if ($this->module == 'liked') {
1637 $this->internalRedirect('network?f=&order=comment');
1640 if ($this->module == 'activity') {
1641 $this->internalRedirect('network/?f=&conv=1');
1644 if (($this->module == 'status_messages') && ($this->cmd == 'status_messages/new')) {
1645 $this->internalRedirect('bookmarklet');
1648 if (($this->module == 'user') && ($this->cmd == 'user/edit')) {
1649 $this->internalRedirect('settings');
1652 if (($this->module == 'tag_followings') && ($this->cmd == 'tag_followings/manage')) {
1653 $this->internalRedirect('search');
1656 // Compatibility with the Firefox App
1657 if (($this->module == "users") && ($this->cmd == "users/sign_in")) {
1658 $this->module = "login";
1661 $privateapps = Core\Config::get('config', 'private_addons', false);
1662 if (Core\Addon::isEnabled($this->module) && file_exists("addon/{$this->module}/{$this->module}.php")) {
1663 //Check if module is an app and if public access to apps is allowed or not
1664 if ((!local_user()) && Core\Hook::isAddonApp($this->module) && $privateapps) {
1665 info(Core\L10n::t("You must be logged in to use addons. "));
1667 include_once "addon/{$this->module}/{$this->module}.php";
1668 if (function_exists($this->module . '_module')) {
1669 LegacyModule::setModuleFile("addon/{$this->module}/{$this->module}.php");
1670 $this->module_class = 'Friendica\\LegacyModule';
1671 $this->module_loaded = true;
1676 // Controller class routing
1677 if (! $this->module_loaded && class_exists('Friendica\\Module\\' . ucfirst($this->module))) {
1678 $this->module_class = 'Friendica\\Module\\' . ucfirst($this->module);
1679 $this->module_loaded = true;
1682 /* If not, next look for a 'standard' program module in the 'mod' directory
1683 * We emulate a Module class through the LegacyModule class
1685 if (! $this->module_loaded && file_exists("mod/{$this->module}.php")) {
1686 LegacyModule::setModuleFile("mod/{$this->module}.php");
1687 $this->module_class = 'Friendica\\LegacyModule';
1688 $this->module_loaded = true;
1691 /* The URL provided does not resolve to a valid module.
1693 * On Dreamhost sites, quite often things go wrong for no apparent reason and they send us to '/internal_error.html'.
1694 * We don't like doing this, but as it occasionally accounts for 10-20% or more of all site traffic -
1695 * 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
1696 * this will often succeed and eventually do the right thing.
1698 * Otherwise we are going to emit a 404 not found.
1700 if (! $this->module_loaded) {
1701 // Stupid browser tried to pre-fetch our Javascript img template. Don't log the event or return anything - just quietly exit.
1702 if (!empty($_SERVER['QUERY_STRING']) && preg_match('/{[0-9]}/', $_SERVER['QUERY_STRING']) !== 0) {
1706 if (!empty($_SERVER['QUERY_STRING']) && ($_SERVER['QUERY_STRING'] === 'q=internal_error.html') && isset($dreamhost_error_hack)) {
1707 Core\Logger::log('index.php: dreamhost_error_hack invoked. Original URI =' . $_SERVER['REQUEST_URI']);
1708 $this->internalRedirect($_SERVER['REQUEST_URI']);
1711 Core\Logger::log('index.php: page not found: ' . $_SERVER['REQUEST_URI'] . ' ADDRESS: ' . $_SERVER['REMOTE_ADDR'] . ' QUERY: ' . $_SERVER['QUERY_STRING'], Core\Logger::DEBUG);
1713 header($_SERVER["SERVER_PROTOCOL"] . ' 404 ' . Core\L10n::t('Not Found'));
1714 $tpl = Core\Renderer::getMarkupTemplate("404.tpl");
1715 $this->page['content'] = Core\Renderer::replaceMacros($tpl, [
1716 '$message' => Core\L10n::t('Page not found.')
1723 // Initialize module that can set the current theme in the init() method, either directly or via App->profile_uid
1724 if ($this->module_loaded) {
1725 $this->page['page_title'] = $this->module;
1728 Core\Hook::callAll($this->module . '_mod_init', $placeholder);
1730 call_user_func([$this->module_class, 'init']);
1732 // "rawContent" is especially meant for technical endpoints.
1733 // This endpoint doesn't need any theme initialization or other comparable stuff.
1734 if (!$this->error) {
1735 call_user_func([$this->module_class, 'rawContent']);
1739 // Load current theme info after module has been initialized as theme could have been set in module
1740 $theme_info_file = 'view/theme/' . $this->getCurrentTheme() . '/theme.php';
1741 if (file_exists($theme_info_file)) {
1742 require_once $theme_info_file;
1745 if (function_exists(str_replace('-', '_', $this->getCurrentTheme()) . '_init')) {
1746 $func = str_replace('-', '_', $this->getCurrentTheme()) . '_init';
1750 if ($this->module_loaded) {
1751 if (! $this->error && $_SERVER['REQUEST_METHOD'] === 'POST') {
1752 Core\Hook::callAll($this->module . '_mod_post', $_POST);
1753 call_user_func([$this->module_class, 'post']);
1756 if (! $this->error) {
1757 Core\Hook::callAll($this->module . '_mod_afterpost', $placeholder);
1758 call_user_func([$this->module_class, 'afterpost']);
1761 if (! $this->error) {
1762 $arr = ['content' => $content];
1763 Core\Hook::callAll($this->module . '_mod_content', $arr);
1764 $content = $arr['content'];
1765 $arr = ['content' => call_user_func([$this->module_class, 'content'])];
1766 Core\Hook::callAll($this->module . '_mod_aftercontent', $arr);
1767 $content .= $arr['content'];
1771 // initialise content region
1772 if ($this->getMode()->isNormal()) {
1773 Core\Hook::callAll('page_content_top', $this->page['content']);
1776 $this->page['content'] .= $content;
1778 /* Create the page head after setting the language
1779 * and getting any auth credentials.
1781 * Moved initHead() and initFooter() to after
1782 * all the module functions have executed so that all
1783 * theme choices made by the modules can take effect.
1787 /* Build the page ending -- this is stuff that goes right before
1788 * the closing </body> tag
1790 $this->initFooter();
1792 /* now that we've been through the module content, see if the page reported
1793 * a permission problem and if so, a 403 response would seem to be in order.
1795 if (stristr(implode("", $_SESSION['sysmsg']), Core\L10n::t('Permission denied'))) {
1796 header($_SERVER["SERVER_PROTOCOL"] . ' 403 ' . Core\L10n::t('Permission denied.'));
1799 // Report anything which needs to be communicated in the notification area (before the main body)
1800 Core\Hook::callAll('page_end', $this->page['content']);
1802 // Add the navigation (menu) template
1803 if ($this->module != 'install' && $this->module != 'maintenance') {
1804 $this->page['htmlhead'] .= Core\Renderer::replaceMacros(Core\Renderer::getMarkupTemplate('nav_head.tpl'), []);
1805 $this->page['nav'] = Content\Nav::build($this);
1808 // Build the page - now that we have all the components
1809 if (isset($_GET["mode"]) && (($_GET["mode"] == "raw") || ($_GET["mode"] == "minimal"))) {
1810 $doc = new DOMDocument();
1812 $target = new DOMDocument();
1813 $target->loadXML("<root></root>");
1815 $content = mb_convert_encoding($this->page["content"], 'HTML-ENTITIES', "UTF-8");
1817 /// @TODO one day, kill those error-surpressing @ stuff, or PHP should ban it
1818 @$doc->loadHTML($content);
1820 $xpath = new DOMXPath($doc);
1822 $list = $xpath->query("//*[contains(@id,'tread-wrapper-')]"); /* */
1824 foreach ($list as $item) {
1825 $item = $target->importNode($item, true);
1827 // And then append it to the target
1828 $target->documentElement->appendChild($item);
1832 if (isset($_GET["mode"]) && ($_GET["mode"] == "raw")) {
1833 header("Content-type: text/html; charset=utf-8");
1835 echo substr($target->saveHTML(), 6, -8);
1840 $page = $this->page;
1841 $profile = $this->profile;
1843 header("X-Friendica-Version: " . FRIENDICA_VERSION);
1844 header("Content-type: text/html; charset=utf-8");
1846 if (Core\Config::get('system', 'hsts') && (Core\Config::get('system', 'ssl_policy') == SSL_POLICY_FULL)) {
1847 header("Strict-Transport-Security: max-age=31536000");
1850 // Some security stuff
1851 header('X-Content-Type-Options: nosniff');
1852 header('X-XSS-Protection: 1; mode=block');
1853 header('X-Permitted-Cross-Domain-Policies: none');
1854 header('X-Frame-Options: sameorigin');
1856 // Things like embedded OSM maps don't work, when this is enabled
1857 // 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'");
1859 /* We use $_GET["mode"] for special page templates. So we will check if we have
1860 * to load another page template than the default one.
1861 * The page templates are located in /view/php/ or in the theme directory.
1863 if (isset($_GET["mode"])) {
1864 $template = Core\Theme::getPathForFile($_GET["mode"] . '.php');
1867 // If there is no page template use the default page template
1868 if (empty($template)) {
1869 $template = Core\Theme::getPathForFile("default.php");
1872 // Theme templates expect $a as an App instance
1875 // Used as is in view/php/default.php
1876 $lang = Core\L10n::getCurrentLang();
1878 /// @TODO Looks unsafe (remote-inclusion), is maybe not but Core\Theme::getPathForFile() uses file_exists() but does not escape anything
1879 require_once $template;
1883 * Redirects to another module relative to the current Friendica base.
1884 * If you want to redirect to a external URL, use System::externalRedirectTo()
1886 * @param string $toUrl The destination URL (Default is empty, which is the default page of the Friendica node)
1887 * @param bool $ssl if true, base URL will try to get called with https:// (works just for relative paths)
1889 * @throws InternalServerErrorException In Case the given URL is not relative to the Friendica node
1891 public function internalRedirect($toUrl = '', $ssl = false)
1893 if (!empty(parse_url($toUrl, PHP_URL_SCHEME))) {
1894 throw new InternalServerErrorException("'$toUrl is not a relative path, please use System::externalRedirectTo");
1897 $redirectTo = $this->getBaseURL($ssl) . '/' . ltrim($toUrl, '/');
1898 Core\System::externalRedirect($redirectTo);
1902 * Automatically redirects to relative or absolute URL
1903 * Should only be used if it isn't clear if the URL is either internal or external
1905 * @param string $toUrl The target URL
1908 public function redirect($toUrl)
1910 if (!empty(parse_url($toUrl, PHP_URL_SCHEME))) {
1911 Core\System::externalRedirect($toUrl);
1913 $this->internalRedirect($toUrl);