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
105 * Register a stylesheet file path to be included in the <head> tag of every page.
106 * Inclusion is done in App->initHead().
107 * The path can be absolute or relative to the Friendica installation base folder.
111 * @param string $path
113 public function registerStylesheet($path)
115 $url = str_replace($this->getBasePath() . DIRECTORY_SEPARATOR, '', $path);
117 $this->stylesheets[] = trim($url, '/');
121 * Register a javascript file path to be included in the <footer> tag of every page.
122 * Inclusion is done in App->initFooter().
123 * The path can be absolute or relative to the Friendica installation base folder.
127 * @param string $path
129 public function registerFooterScript($path)
131 $url = str_replace($this->getBasePath() . DIRECTORY_SEPARATOR, '', $path);
133 $this->footerScripts[] = trim($url, '/');
142 * @brief App constructor.
144 * @param string $basePath Path to the app base folder
145 * @param bool $isBackend Whether it is used for backend or frontend (Default true=backend)
147 * @throws Exception if the Basepath is not usable
149 public function __construct($basePath, $isBackend = true)
151 if (!static::isDirectoryUsable($basePath, false)) {
152 throw new Exception('Basepath ' . $basePath . ' isn\'t usable.');
155 BaseObject::setApp($this);
157 $this->basePath = rtrim($basePath, DIRECTORY_SEPARATOR);
158 $this->checkBackend($isBackend);
159 $this->checkFriendicaApp();
161 $this->performance['start'] = microtime(true);
162 $this->performance['database'] = 0;
163 $this->performance['database_write'] = 0;
164 $this->performance['cache'] = 0;
165 $this->performance['cache_write'] = 0;
166 $this->performance['network'] = 0;
167 $this->performance['file'] = 0;
168 $this->performance['rendering'] = 0;
169 $this->performance['parser'] = 0;
170 $this->performance['marktime'] = 0;
171 $this->performance['markstart'] = microtime(true);
173 $this->callstack['database'] = [];
174 $this->callstack['database_write'] = [];
175 $this->callstack['cache'] = [];
176 $this->callstack['cache_write'] = [];
177 $this->callstack['network'] = [];
178 $this->callstack['file'] = [];
179 $this->callstack['rendering'] = [];
180 $this->callstack['parser'] = [];
182 $this->mode = new App\Mode($basePath);
188 // This has to be quite large to deal with embedded private photos
189 ini_set('pcre.backtrack_limit', 500000);
191 $this->scheme = 'http';
193 if (!empty($_SERVER['HTTPS']) ||
194 !empty($_SERVER['HTTP_FORWARDED']) && preg_match('/proto=https/', $_SERVER['HTTP_FORWARDED']) ||
195 !empty($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https' ||
196 !empty($_SERVER['HTTP_X_FORWARDED_SSL']) && $_SERVER['HTTP_X_FORWARDED_SSL'] == 'on' ||
197 !empty($_SERVER['FRONT_END_HTTPS']) && $_SERVER['FRONT_END_HTTPS'] == 'on' ||
198 !empty($_SERVER['SERVER_PORT']) && (intval($_SERVER['SERVER_PORT']) == 443) // XXX: reasonable assumption, but isn't this hardcoding too much?
200 $this->scheme = 'https';
203 if (!empty($_SERVER['SERVER_NAME'])) {
204 $this->hostname = $_SERVER['SERVER_NAME'];
206 if (!empty($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] != 80 && $_SERVER['SERVER_PORT'] != 443) {
207 $this->hostname .= ':' . $_SERVER['SERVER_PORT'];
212 get_include_path() . PATH_SEPARATOR
213 . $this->getBasePath() . DIRECTORY_SEPARATOR . 'include' . PATH_SEPARATOR
214 . $this->getBasePath() . DIRECTORY_SEPARATOR . 'library' . PATH_SEPARATOR
215 . $this->getBasePath());
217 if (!empty($_SERVER['QUERY_STRING']) && strpos($_SERVER['QUERY_STRING'], 'pagename=') === 0) {
218 $this->query_string = substr($_SERVER['QUERY_STRING'], 9);
219 } elseif (!empty($_SERVER['QUERY_STRING']) && strpos($_SERVER['QUERY_STRING'], 'q=') === 0) {
220 $this->query_string = substr($_SERVER['QUERY_STRING'], 2);
223 // removing trailing / - maybe a nginx problem
224 $this->query_string = ltrim($this->query_string, '/');
226 if (!empty($_GET['pagename'])) {
227 $this->cmd = trim($_GET['pagename'], '/\\');
228 } elseif (!empty($_GET['q'])) {
229 $this->cmd = trim($_GET['q'], '/\\');
233 $this->query_string = str_replace($this->cmd . '&', $this->cmd . '?', $this->query_string);
235 // unix style "homedir"
236 if (substr($this->cmd, 0, 1) === '~') {
237 $this->cmd = 'profile/' . substr($this->cmd, 1);
240 // Diaspora style profile url
241 if (substr($this->cmd, 0, 2) === 'u/') {
242 $this->cmd = 'profile/' . substr($this->cmd, 2);
246 * Break the URL path into C style argc/argv style arguments for our
247 * modules. Given "http://example.com/module/arg1/arg2", $this->argc
248 * will be 3 (integer) and $this->argv will contain:
254 * There will always be one argument. If provided a naked domain
255 * URL, $this->argv[0] is set to "home".
258 $this->argv = explode('/', $this->cmd);
259 $this->argc = count($this->argv);
260 if ((array_key_exists('0', $this->argv)) && strlen($this->argv[0])) {
261 $this->module = str_replace('.', '_', $this->argv[0]);
262 $this->module = str_replace('-', '_', $this->module);
265 $this->argv = ['home'];
266 $this->module = 'home';
269 // Detect mobile devices
270 $mobile_detect = new MobileDetect();
271 $this->is_mobile = $mobile_detect->isMobile();
272 $this->is_tablet = $mobile_detect->isTablet();
274 $this->isAjax = strtolower(defaults($_SERVER, 'HTTP_X_REQUESTED_WITH', '')) == 'xmlhttprequest';
276 // Register template engines
277 Core\Renderer::registerTemplateEngine('Friendica\Render\FriendicaSmartyEngine');
281 * Returns the Mode of the Application
283 * @return App\Mode The Application Mode
285 * @throws InternalServerErrorException when the mode isn't created
287 public function getMode()
289 if (empty($this->mode)) {
290 throw new InternalServerErrorException('Mode of the Application is not defined');
297 * Reloads the whole app instance
299 public function reload()
301 // The order of the following calls is important to ensure proper initialization
302 $this->loadConfigFiles();
304 $this->loadDatabase();
306 $this->getMode()->determine($this->getBasePath());
308 $this->determineURLPath();
312 if ($this->getMode()->has(App\Mode::DBAVAILABLE)) {
313 Core\Hook::loadHooks();
315 $this->loadAddonConfig();
318 $this->loadDefaultTimezone();
322 $this->process_id = Core\System::processID('log');
326 * Load the configuration files
328 * First loads the default value for all the configuration keys, then the legacy configuration files, then the
329 * expected local.config.php
331 private function loadConfigFiles()
333 $this->loadConfigFile($this->getBasePath() . '/config/defaults.config.php');
334 $this->loadConfigFile($this->getBasePath() . '/config/settings.config.php');
336 // Legacy .htconfig.php support
337 if (file_exists($this->getBasePath() . '/.htpreconfig.php')) {
339 include $this->getBasePath() . '/.htpreconfig.php';
342 // Legacy .htconfig.php support
343 if (file_exists($this->getBasePath() . '/.htconfig.php')) {
346 include $this->getBasePath() . '/.htconfig.php';
348 $this->setConfigValue('database', 'hostname', $db_host);
349 $this->setConfigValue('database', 'username', $db_user);
350 $this->setConfigValue('database', 'password', $db_pass);
351 $this->setConfigValue('database', 'database', $db_data);
352 if (isset($a->config['system']['db_charset'])) {
353 $this->setConfigValue('database', 'charset', $a->config['system']['db_charset']);
356 unset($db_host, $db_user, $db_pass, $db_data);
358 if (isset($default_timezone)) {
359 $this->setConfigValue('system', 'default_timezone', $default_timezone);
360 unset($default_timezone);
363 if (isset($pidfile)) {
364 $this->setConfigValue('system', 'pidfile', $pidfile);
369 $this->setConfigValue('system', 'language', $lang);
374 if (file_exists($this->getBasePath() . '/config/local.config.php')) {
375 $this->loadConfigFile($this->getBasePath() . '/config/local.config.php', true);
376 } elseif (file_exists($this->getBasePath() . '/config/local.ini.php')) {
377 $this->loadINIConfigFile($this->getBasePath() . '/config/local.ini.php', true);
382 * Tries to load the specified legacy configuration file into the App->config array.
383 * Doesn't overwrite previously set values by default to prevent default config files to supersede DB Config.
385 * @deprecated since version 2018.12
386 * @param string $filepath
387 * @param bool $overwrite Force value overwrite if the config key already exists
390 public function loadINIConfigFile($filepath, $overwrite = false)
392 if (!file_exists($filepath)) {
393 throw new Exception('Error parsing non-existent INI config file ' . $filepath);
396 $contents = include($filepath);
398 $config = parse_ini_string($contents, true, INI_SCANNER_TYPED);
400 if ($config === false) {
401 throw new Exception('Error parsing INI config file ' . $filepath);
404 $this->loadConfigArray($config, $overwrite);
408 * Tries to load the specified configuration file into the App->config array.
409 * Doesn't overwrite previously set values by default to prevent default config files to supersede DB Config.
411 * The config format is PHP array and the template for configuration files is the following:
419 * @param string $filepath
420 * @param bool $overwrite Force value overwrite if the config key already exists
423 public function loadConfigFile($filepath, $overwrite = false)
425 if (!file_exists($filepath)) {
426 throw new Exception('Error loading non-existent config file ' . $filepath);
429 $config = include($filepath);
431 if (!is_array($config)) {
432 throw new Exception('Error loading config file ' . $filepath);
435 $this->loadConfigArray($config, $overwrite);
439 * Loads addons configuration files
441 * First loads all activated addons default configuration through the load_config hook, then load the local.config.php
442 * again to overwrite potential local addon configuration.
444 private function loadAddonConfig()
446 // Loads addons default config
447 Core\Hook::callAll('load_config');
449 // Load the local addon config file to overwritten default addon config values
450 if (file_exists($this->getBasePath() . '/config/addon.config.php')) {
451 $this->loadConfigFile($this->getBasePath() . '/config/addon.config.php', true);
452 } elseif (file_exists($this->getBasePath() . '/config/addon.ini.php')) {
453 $this->loadINIConfigFile($this->getBasePath() . '/config/addon.ini.php', true);
458 * Tries to load the specified configuration array into the App->config array.
459 * Doesn't overwrite previously set values by default to prevent default config files to supersede DB Config.
461 * @param array $config
462 * @param bool $overwrite Force value overwrite if the config key already exists
464 private function loadConfigArray(array $config, $overwrite = false)
466 foreach ($config as $category => $values) {
467 foreach ($values as $key => $value) {
469 $this->setConfigValue($category, $key, $value);
471 $this->setDefaultConfigValue($category, $key, $value);
478 * Loads the default timezone
480 * Include support for legacy $default_timezone
482 * @global string $default_timezone
484 private function loadDefaultTimezone()
486 if ($this->getConfigValue('system', 'default_timezone')) {
487 $this->timezone = $this->getConfigValue('system', 'default_timezone');
489 global $default_timezone;
490 $this->timezone = !empty($default_timezone) ? $default_timezone : 'UTC';
493 if ($this->timezone) {
494 date_default_timezone_set($this->timezone);
499 * Figure out if we are running at the top of a domain or in a sub-directory and adjust accordingly
501 private function determineURLPath()
503 /* Relative script path to the web server root
504 * Not all of those $_SERVER properties can be present, so we do by inverse priority order
506 $relative_script_path = '';
507 $relative_script_path = defaults($_SERVER, 'REDIRECT_URL' , $relative_script_path);
508 $relative_script_path = defaults($_SERVER, 'REDIRECT_URI' , $relative_script_path);
509 $relative_script_path = defaults($_SERVER, 'REDIRECT_SCRIPT_URL', $relative_script_path);
510 $relative_script_path = defaults($_SERVER, 'SCRIPT_URL' , $relative_script_path);
511 $relative_script_path = defaults($_SERVER, 'REQUEST_URI' , $relative_script_path);
513 $this->urlPath = $this->getConfigValue('system', 'urlpath');
515 /* $relative_script_path gives /relative/path/to/friendica/module/parameter
516 * QUERY_STRING gives pagename=module/parameter
518 * To get /relative/path/to/friendica we perform dirname() for as many levels as there are slashes in the QUERY_STRING
520 if (!empty($relative_script_path)) {
522 if (!empty($_SERVER['QUERY_STRING'])) {
523 $path = trim(rdirname($relative_script_path, substr_count(trim($_SERVER['QUERY_STRING'], '/'), '/') + 1), '/');
526 $path = trim($relative_script_path, '/');
529 if ($path && $path != $this->urlPath) {
530 $this->urlPath = $path;
535 public function loadDatabase()
537 if (DBA::connected()) {
541 $db_host = $this->getConfigValue('database', 'hostname');
542 $db_user = $this->getConfigValue('database', 'username');
543 $db_pass = $this->getConfigValue('database', 'password');
544 $db_data = $this->getConfigValue('database', 'database');
545 $charset = $this->getConfigValue('database', 'charset');
547 // Use environment variables for mysql if they are set beforehand
548 if (!empty(getenv('MYSQL_HOST'))
549 && !empty(getenv('MYSQL_USERNAME') || !empty(getenv('MYSQL_USER')))
550 && getenv('MYSQL_PASSWORD') !== false
551 && !empty(getenv('MYSQL_DATABASE')))
553 $db_host = getenv('MYSQL_HOST');
554 if (!empty(getenv('MYSQL_PORT'))) {
555 $db_host .= ':' . getenv('MYSQL_PORT');
557 if (!empty(getenv('MYSQL_USERNAME'))) {
558 $db_user = getenv('MYSQL_USERNAME');
560 $db_user = getenv('MYSQL_USER');
562 $db_pass = (string) getenv('MYSQL_PASSWORD');
563 $db_data = getenv('MYSQL_DATABASE');
566 $stamp1 = microtime(true);
568 if (DBA::connect($db_host, $db_user, $db_pass, $db_data, $charset)) {
569 // Loads DB_UPDATE_VERSION constant
570 Database\DBStructure::definition(false);
573 unset($db_host, $db_user, $db_pass, $db_data, $charset);
575 $this->saveTimestamp($stamp1, 'network');
579 * @brief Returns the base filesystem path of the App
581 * It first checks for the internal variable, then for DOCUMENT_ROOT and
586 public function getBasePath()
588 $basepath = $this->basePath;
591 $basepath = Core\Config::get('system', 'basepath');
594 if (!$basepath && !empty($_SERVER['DOCUMENT_ROOT'])) {
595 $basepath = $_SERVER['DOCUMENT_ROOT'];
598 if (!$basepath && !empty($_SERVER['PWD'])) {
599 $basepath = $_SERVER['PWD'];
602 return self::getRealPath($basepath);
606 * @brief Returns a normalized file path
608 * This is a wrapper for the "realpath" function.
609 * That function cannot detect the real path when some folders aren't readable.
610 * Since this could happen with some hosters we need to handle this.
612 * @param string $path The path that is about to be normalized
613 * @return string normalized path - when possible
615 public static function getRealPath($path)
617 $normalized = realpath($path);
619 if (!is_bool($normalized)) {
626 public function getScheme()
628 return $this->scheme;
632 * @brief Retrieves the Friendica instance base URL
634 * This function assembles the base URL from multiple parts:
635 * - Protocol is determined either by the request or a combination of
636 * system.ssl_policy and the $ssl parameter.
637 * - Host name is determined either by system.hostname or inferred from request
638 * - Path is inferred from SCRIPT_NAME
640 * Note: $ssl parameter value doesn't directly correlate with the resulting protocol
642 * @param bool $ssl Whether to append http or https under SSL_POLICY_SELFSIGN
643 * @return string Friendica server base URL
645 public function getBaseURL($ssl = false)
647 $scheme = $this->scheme;
649 if (Core\Config::get('system', 'ssl_policy') == SSL_POLICY_FULL) {
653 // Basically, we have $ssl = true on any links which can only be seen by a logged in user
654 // (and also the login link). Anything seen by an outsider will have it turned off.
656 if (Core\Config::get('system', 'ssl_policy') == SSL_POLICY_SELFSIGN) {
664 if (Core\Config::get('config', 'hostname') != '') {
665 $this->hostname = Core\Config::get('config', 'hostname');
668 return $scheme . '://' . $this->hostname . !empty($this->getURLPath() ? '/' . $this->getURLPath() : '' );
672 * @brief Initializes the baseurl components
674 * Clears the baseurl cache to prevent inconsistencies
678 public function setBaseURL($url)
680 $parsed = @parse_url($url);
683 if (!empty($parsed)) {
684 if (!empty($parsed['scheme'])) {
685 $this->scheme = $parsed['scheme'];
688 if (!empty($parsed['host'])) {
689 $hostname = $parsed['host'];
692 if (!empty($parsed['port'])) {
693 $hostname .= ':' . $parsed['port'];
695 if (!empty($parsed['path'])) {
696 $this->urlPath = trim($parsed['path'], '\\/');
699 if (file_exists($this->getBasePath() . '/.htpreconfig.php')) {
700 include $this->getBasePath() . '/.htpreconfig.php';
703 if (Core\Config::get('config', 'hostname') != '') {
704 $this->hostname = Core\Config::get('config', 'hostname');
707 if (!isset($this->hostname) || ($this->hostname == '')) {
708 $this->hostname = $hostname;
713 public function getHostName()
715 if (Core\Config::get('config', 'hostname') != '') {
716 $this->hostname = Core\Config::get('config', 'hostname');
719 return $this->hostname;
722 public function getURLPath()
724 return $this->urlPath;
728 * Initializes App->page['htmlhead'].
733 * - Registered stylesheets (through App->registerStylesheet())
734 * - Infinite scroll data
735 * - head.tpl template
737 public function initHead()
739 $interval = ((local_user()) ? Core\PConfig::get(local_user(), 'system', 'update_interval') : 40000);
741 // If the update is 'deactivated' set it to the highest integer number (~24 days)
743 $interval = 2147483647;
746 if ($interval < 10000) {
750 // compose the page title from the sitename and the
751 // current module called
752 if (!$this->module == '') {
753 $this->page['title'] = $this->config['sitename'] . ' (' . $this->module . ')';
755 $this->page['title'] = $this->config['sitename'];
758 if (!empty(Core\Renderer::$theme['stylesheet'])) {
759 $stylesheet = Core\Renderer::$theme['stylesheet'];
761 $stylesheet = $this->getCurrentThemeStylesheetPath();
764 $this->registerStylesheet($stylesheet);
766 $shortcut_icon = Core\Config::get('system', 'shortcut_icon');
767 if ($shortcut_icon == '') {
768 $shortcut_icon = 'images/friendica-32.png';
771 $touch_icon = Core\Config::get('system', 'touch_icon');
772 if ($touch_icon == '') {
773 $touch_icon = 'images/friendica-128.png';
776 Core\Addon::callHooks('head', $this->page['htmlhead']);
778 $tpl = Core\Renderer::getMarkupTemplate('head.tpl');
779 /* put the head template at the beginning of page['htmlhead']
780 * since the code added by the modules frequently depends on it
783 $this->page['htmlhead'] = Core\Renderer::replaceMacros($tpl, [
784 '$baseurl' => $this->getBaseURL(),
785 '$local_user' => local_user(),
786 '$generator' => 'Friendica' . ' ' . FRIENDICA_VERSION,
787 '$delitem' => Core\L10n::t('Delete this item?'),
788 '$showmore' => Core\L10n::t('show more'),
789 '$showfewer' => Core\L10n::t('show fewer'),
790 '$update_interval' => $interval,
791 '$shortcut_icon' => $shortcut_icon,
792 '$touch_icon' => $touch_icon,
793 '$block_public' => intval(Core\Config::get('system', 'block_public')),
794 '$stylesheets' => $this->stylesheets,
795 ]) . $this->page['htmlhead'];
799 * Initializes App->page['footer'].
802 * - Javascript homebase
803 * - Mobile toggle link
804 * - Registered footer scripts (through App->registerFooterScript())
805 * - footer.tpl template
807 public function initFooter()
809 // If you're just visiting, let javascript take you home
810 if (!empty($_SESSION['visitor_home'])) {
811 $homebase = $_SESSION['visitor_home'];
812 } elseif (local_user()) {
813 $homebase = 'profile/' . $this->user['nickname'];
816 if (isset($homebase)) {
817 $this->page['footer'] .= '<script>var homebase="' . $homebase . '";</script>' . "\n";
821 * Add a "toggle mobile" link if we're using a mobile device
823 if ($this->is_mobile || $this->is_tablet) {
824 if (isset($_SESSION['show-mobile']) && !$_SESSION['show-mobile']) {
825 $link = 'toggle_mobile?address=' . urlencode(curPageURL());
827 $link = 'toggle_mobile?off=1&address=' . urlencode(curPageURL());
829 $this->page['footer'] .= Core\Renderer::replaceMacros(Core\Renderer::getMarkupTemplate("toggle_mobile_footer.tpl"), [
830 '$toggle_link' => $link,
831 '$toggle_text' => Core\L10n::t('toggle mobile')
835 Core\Addon::callHooks('footer', $this->page['footer']);
837 $tpl = Core\Renderer::getMarkupTemplate('footer.tpl');
838 $this->page['footer'] = Core\Renderer::replaceMacros($tpl, [
839 '$baseurl' => $this->getBaseURL(),
840 '$footerScripts' => $this->footerScripts,
841 ]) . $this->page['footer'];
845 * @brief Removes the base url from an url. This avoids some mixed content problems.
847 * @param string $origURL
849 * @return string The cleaned url
851 public function removeBaseURL($origURL)
853 // Remove the hostname from the url if it is an internal link
854 $nurl = Util\Strings::normaliseLink($origURL);
855 $base = Util\Strings::normaliseLink($this->getBaseURL());
856 $url = str_replace($base . '/', '', $nurl);
858 // if it is an external link return the orignal value
859 if ($url == Util\Strings::normaliseLink($origURL)) {
867 * Saves a timestamp for a value - f.e. a call
868 * Necessary for profiling Friendica
870 * @param int $timestamp the Timestamp
871 * @param string $value A value to profile
873 public function saveTimestamp($timestamp, $value)
875 if (!isset($this->config['system']['profiler']) || !$this->config['system']['profiler']) {
879 $duration = (float) (microtime(true) - $timestamp);
881 if (!isset($this->performance[$value])) {
882 // Prevent ugly E_NOTICE
883 $this->performance[$value] = 0;
886 $this->performance[$value] += (float) $duration;
887 $this->performance['marktime'] += (float) $duration;
889 $callstack = Core\System::callstack();
891 if (!isset($this->callstack[$value][$callstack])) {
892 // Prevent ugly E_NOTICE
893 $this->callstack[$value][$callstack] = 0;
896 $this->callstack[$value][$callstack] += (float) $duration;
900 * Returns the current UserAgent as a String
902 * @return string the UserAgent as a String
904 public function getUserAgent()
907 FRIENDICA_PLATFORM . " '" .
908 FRIENDICA_CODENAME . "' " .
909 FRIENDICA_VERSION . '-' .
910 DB_UPDATE_VERSION . '; ' .
915 * Checks, if the call is from the Friendica App
918 * The friendica client has problems with the GUID in the notify. this is some workaround
920 private function checkFriendicaApp()
923 $this->isFriendicaApp = isset($_SERVER['HTTP_USER_AGENT']) && $_SERVER['HTTP_USER_AGENT'] == 'Apache-HttpClient/UNAVAILABLE (java 1.4)';
927 * Is the call via the Friendica app? (not a "normale" call)
929 * @return bool true if it's from the Friendica app
931 public function isFriendicaApp()
933 return $this->isFriendicaApp;
937 * @brief Checks if the site is called via a backend process
939 * This isn't a perfect solution. But we need this check very early.
940 * So we cannot wait until the modules are loaded.
942 * @param string $backend true, if the backend flag was set during App initialization
945 private function checkBackend($backend) {
968 // Check if current module is in backend or backend flag is set
969 $this->isBackend = (in_array($this->module, $backends) || $backend || $this->isBackend);
973 * Returns true, if the call is from a backend node (f.e. from a worker)
975 * @return bool Is it a known backend?
977 public function isBackend()
979 return $this->isBackend;
983 * @brief Checks if the maximum number of database processes is reached
985 * @return bool Is the limit reached?
987 public function isMaxProcessesReached()
989 // Deactivated, needs more investigating if this check really makes sense
993 * Commented out to suppress static analyzer issues
995 if ($this->is_backend()) {
996 $process = 'backend';
997 $max_processes = Core\Config::get('system', 'max_processes_backend');
998 if (intval($max_processes) == 0) {
1002 $process = 'frontend';
1003 $max_processes = Core\Config::get('system', 'max_processes_frontend');
1004 if (intval($max_processes) == 0) {
1005 $max_processes = 20;
1009 $processlist = DBA::processlist();
1010 if ($processlist['list'] != '') {
1011 Core\Logger::log('Processcheck: Processes: ' . $processlist['amount'] . ' - Processlist: ' . $processlist['list'], Core\Logger::DEBUG);
1013 if ($processlist['amount'] > $max_processes) {
1014 Core\Logger::log('Processcheck: Maximum number of processes for ' . $process . ' tasks (' . $max_processes . ') reached.', Core\Logger::DEBUG);
1023 * @brief Checks if the minimal memory is reached
1025 * @return bool Is the memory limit reached?
1027 public function isMinMemoryReached()
1029 $min_memory = Core\Config::get('system', 'min_memory', 0);
1030 if ($min_memory == 0) {
1034 if (!is_readable('/proc/meminfo')) {
1038 $memdata = explode("\n", file_get_contents('/proc/meminfo'));
1041 foreach ($memdata as $line) {
1042 $data = explode(':', $line);
1043 if (count($data) != 2) {
1046 list($key, $val) = $data;
1047 $meminfo[$key] = (int) trim(str_replace('kB', '', $val));
1048 $meminfo[$key] = (int) ($meminfo[$key] / 1024);
1051 if (!isset($meminfo['MemFree'])) {
1055 $free = $meminfo['MemFree'];
1057 $reached = ($free < $min_memory);
1060 Core\Logger::log('Minimal memory reached: ' . $free . '/' . $meminfo['MemTotal'] . ' - limit ' . $min_memory, Core\Logger::DEBUG);
1067 * @brief Checks if the maximum load is reached
1069 * @return bool Is the load reached?
1071 public function isMaxLoadReached()
1073 if ($this->isBackend()) {
1074 $process = 'backend';
1075 $maxsysload = intval(Core\Config::get('system', 'maxloadavg'));
1076 if ($maxsysload < 1) {
1080 $process = 'frontend';
1081 $maxsysload = intval(Core\Config::get('system', 'maxloadavg_frontend'));
1082 if ($maxsysload < 1) {
1087 $load = Core\System::currentLoad();
1089 if (intval($load) > $maxsysload) {
1090 Core\Logger::log('system: load ' . $load . ' for ' . $process . ' tasks (' . $maxsysload . ') too high.');
1098 * Executes a child process with 'proc_open'
1100 * @param string $command The command to execute
1101 * @param array $args Arguments to pass to the command ( [ 'key' => value, 'key2' => value2, ... ]
1103 public function proc_run($command, $args)
1105 if (!function_exists('proc_open')) {
1109 $cmdline = $this->getConfigValue('config', 'php_path', 'php') . ' ' . escapeshellarg($command);
1111 foreach ($args as $key => $value) {
1112 if (!is_null($value) && is_bool($value) && !$value) {
1116 $cmdline .= ' --' . $key;
1117 if (!is_null($value) && !is_bool($value)) {
1118 $cmdline .= ' ' . $value;
1122 if ($this->isMinMemoryReached()) {
1126 if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
1127 $resource = proc_open('cmd /c start /b ' . $cmdline, [], $foo, $this->getBasePath());
1129 $resource = proc_open($cmdline . ' &', [], $foo, $this->getBasePath());
1131 if (!is_resource($resource)) {
1132 Core\Logger::log('We got no resource for command ' . $cmdline, Core\Logger::DEBUG);
1135 proc_close($resource);
1139 * @brief Returns the system user that is executing the script
1141 * This mostly returns something like "www-data".
1143 * @return string system username
1145 private static function getSystemUser()
1147 if (!function_exists('posix_getpwuid') || !function_exists('posix_geteuid')) {
1151 $processUser = posix_getpwuid(posix_geteuid());
1152 return $processUser['name'];
1156 * @brief Checks if a given directory is usable for the system
1158 * @return boolean the directory is usable
1160 public static function isDirectoryUsable($directory, $check_writable = true)
1162 if ($directory == '') {
1163 Core\Logger::log('Directory is empty. This shouldn\'t happen.', Core\Logger::DEBUG);
1167 if (!file_exists($directory)) {
1168 Core\Logger::log('Path "' . $directory . '" does not exist for user ' . self::getSystemUser(), Core\Logger::DEBUG);
1172 if (is_file($directory)) {
1173 Core\Logger::log('Path "' . $directory . '" is a file for user ' . self::getSystemUser(), Core\Logger::DEBUG);
1177 if (!is_dir($directory)) {
1178 Core\Logger::log('Path "' . $directory . '" is not a directory for user ' . self::getSystemUser(), Core\Logger::DEBUG);
1182 if ($check_writable && !is_writable($directory)) {
1183 Core\Logger::log('Path "' . $directory . '" is not writable for user ' . self::getSystemUser(), Core\Logger::DEBUG);
1191 * @param string $cat Config category
1192 * @param string $k Config key
1193 * @param mixed $default Default value if it isn't set
1195 * @return string Returns the value of the Config entry
1197 public function getConfigValue($cat, $k, $default = null)
1201 if ($cat === 'config') {
1202 if (isset($this->config[$k])) {
1203 $return = $this->config[$k];
1206 if (isset($this->config[$cat][$k])) {
1207 $return = $this->config[$cat][$k];
1215 * Sets a default value in the config cache. Ignores already existing keys.
1217 * @param string $cat Config category
1218 * @param string $k Config key
1219 * @param mixed $v Default value to set
1221 private function setDefaultConfigValue($cat, $k, $v)
1223 if (!isset($this->config[$cat][$k])) {
1224 $this->setConfigValue($cat, $k, $v);
1229 * Sets a value in the config cache. Accepts raw output from the config table
1231 * @param string $cat Config category
1232 * @param string $k Config key
1233 * @param mixed $v Value to set
1235 public function setConfigValue($cat, $k, $v)
1237 // Only arrays are serialized in database, so we have to unserialize sparingly
1238 $value = is_string($v) && preg_match("|^a:[0-9]+:{.*}$|s", $v) ? unserialize($v) : $v;
1240 if ($cat === 'config') {
1241 $this->config[$k] = $value;
1243 if (!isset($this->config[$cat])) {
1244 $this->config[$cat] = [];
1247 $this->config[$cat][$k] = $value;
1252 * Deletes a value from the config cache
1254 * @param string $cat Config category
1255 * @param string $k Config key
1257 public function deleteConfigValue($cat, $k)
1259 if ($cat === 'config') {
1260 if (isset($this->config[$k])) {
1261 unset($this->config[$k]);
1264 if (isset($this->config[$cat][$k])) {
1265 unset($this->config[$cat][$k]);
1272 * Retrieves a value from the user config cache
1274 * @param int $uid User Id
1275 * @param string $cat Config category
1276 * @param string $k Config key
1277 * @param mixed $default Default value if key isn't set
1279 * @return string The value of the config entry
1281 public function getPConfigValue($uid, $cat, $k, $default = null)
1285 if (isset($this->config[$uid][$cat][$k])) {
1286 $return = $this->config[$uid][$cat][$k];
1293 * Sets a value in the user config cache
1295 * Accepts raw output from the pconfig table
1297 * @param int $uid User Id
1298 * @param string $cat Config category
1299 * @param string $k Config key
1300 * @param mixed $v Value to set
1302 public function setPConfigValue($uid, $cat, $k, $v)
1304 // Only arrays are serialized in database, so we have to unserialize sparingly
1305 $value = is_string($v) && preg_match("|^a:[0-9]+:{.*}$|s", $v) ? unserialize($v) : $v;
1307 if (!isset($this->config[$uid]) || !is_array($this->config[$uid])) {
1308 $this->config[$uid] = [];
1311 if (!isset($this->config[$uid][$cat]) || !is_array($this->config[$uid][$cat])) {
1312 $this->config[$uid][$cat] = [];
1315 $this->config[$uid][$cat][$k] = $value;
1319 * Deletes a value from the user config cache
1321 * @param int $uid User Id
1322 * @param string $cat Config category
1323 * @param string $k Config key
1325 public function deletePConfigValue($uid, $cat, $k)
1327 if (isset($this->config[$uid][$cat][$k])) {
1328 unset($this->config[$uid][$cat][$k]);
1333 * Generates the site's default sender email address
1337 public function getSenderEmailAddress()
1339 $sender_email = Core\Config::get('config', 'sender_email');
1340 if (empty($sender_email)) {
1341 $hostname = $this->getHostName();
1342 if (strpos($hostname, ':')) {
1343 $hostname = substr($hostname, 0, strpos($hostname, ':'));
1346 $sender_email = 'noreply@' . $hostname;
1349 return $sender_email;
1353 * Returns the current theme name.
1355 * @return string the name of the current theme
1357 public function getCurrentTheme()
1359 if ($this->getMode()->isInstall()) {
1363 if (!$this->currentTheme) {
1364 $this->computeCurrentTheme();
1367 return $this->currentTheme;
1370 public function setCurrentTheme($theme)
1372 $this->currentTheme = $theme;
1376 * Computes the current theme name based on the node settings, the user settings and the device type
1380 private function computeCurrentTheme()
1382 $system_theme = Core\Config::get('system', 'theme');
1383 if (!$system_theme) {
1384 throw new Exception(Core\L10n::t('No system theme config value set.'));
1388 $this->currentTheme = $system_theme;
1390 $allowed_themes = explode(',', Core\Config::get('system', 'allowed_themes', $system_theme));
1393 // Find the theme that belongs to the user whose stuff we are looking at
1394 if ($this->profile_uid && ($this->profile_uid != local_user())) {
1395 // Allow folks to override user themes and always use their own on their own site.
1396 // This works only if the user is on the same server
1397 $user = DBA::selectFirst('user', ['theme'], ['uid' => $this->profile_uid]);
1398 if (DBA::isResult($user) && !Core\PConfig::get(local_user(), 'system', 'always_my_theme')) {
1399 $page_theme = $user['theme'];
1403 $user_theme = Core\Session::get('theme', $system_theme);
1405 // Specific mobile theme override
1406 if (($this->is_mobile || $this->is_tablet) && Core\Session::get('show-mobile', true)) {
1407 $system_mobile_theme = Core\Config::get('system', 'mobile-theme');
1408 $user_mobile_theme = Core\Session::get('mobile-theme', $system_mobile_theme);
1410 // --- means same mobile theme as desktop
1411 if (!empty($user_mobile_theme) && $user_mobile_theme !== '---') {
1412 $user_theme = $user_mobile_theme;
1417 $theme_name = $page_theme;
1419 $theme_name = $user_theme;
1423 && in_array($theme_name, $allowed_themes)
1424 && (file_exists('view/theme/' . $theme_name . '/style.css')
1425 || file_exists('view/theme/' . $theme_name . '/style.php'))
1427 $this->currentTheme = $theme_name;
1432 * @brief Return full URL to theme which is currently in effect.
1434 * Provide a sane default if nothing is chosen or the specified theme does not exist.
1438 public function getCurrentThemeStylesheetPath()
1440 return Core\Theme::getStylesheetPath($this->getCurrentTheme());
1444 * Check if request was an AJAX (xmlhttprequest) request.
1446 * @return boolean true if it was an AJAX request
1448 public function isAjax()
1450 return $this->isAjax;
1454 * Returns the value of a argv key
1455 * TODO there are a lot of $a->argv usages in combination with defaults() which can be replaced with this method
1457 * @param int $position the position of the argument
1458 * @param mixed $default the default value if not found
1460 * @return mixed returns the value of the argument
1462 public function getArgumentValue($position, $default = '')
1464 if (array_key_exists($position, $this->argv)) {
1465 return $this->argv[$position];
1472 * Sets the base url for use in cmdline programs which don't have
1473 * $_SERVER variables
1475 public function checkURL()
1477 $url = Core\Config::get('system', 'url');
1479 // if the url isn't set or the stored url is radically different
1480 // than the currently visited url, store the current value accordingly.
1481 // "Radically different" ignores common variations such as http vs https
1482 // and www.example.com vs example.com.
1483 // We will only change the url to an ip address if there is no existing setting
1485 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()))) {
1486 Core\Config::set('system', 'url', $this->getBaseURL());
1491 * Frontend App script
1493 * The App object behaves like a container and a dispatcher at the same time, including a representation of the
1494 * request and a representation of the response.
1496 * This probably should change to limit the size of this monster method.
1498 public function runFrontend()
1500 // Missing DB connection: ERROR
1501 if ($this->getMode()->has(App\Mode::LOCALCONFIGPRESENT) && !$this->getMode()->has(App\Mode::DBAVAILABLE)) {
1502 Core\System::httpExit(500, ['title' => 'Error 500 - Internal Server Error', 'description' => 'Apologies but the website is unavailable at the moment.']);
1505 // Max Load Average reached: ERROR
1506 if ($this->isMaxProcessesReached() || $this->isMaxLoadReached()) {
1507 header('Retry-After: 120');
1508 header('Refresh: 120; url=' . $this->getBaseURL() . "/" . $this->query_string);
1510 Core\System::httpExit(503, ['title' => 'Error 503 - Service Temporarily Unavailable', 'description' => 'Core\System is currently overloaded. Please try again later.']);
1513 if (strstr($this->query_string, '.well-known/host-meta') && ($this->query_string != '.well-known/host-meta')) {
1514 Core\System::httpExit(404);
1517 if (!$this->getMode()->isInstall()) {
1518 // Force SSL redirection
1519 if (Core\Config::get('system', 'force_ssl') && ($this->getScheme() == "http")
1520 && intval(Core\Config::get('system', 'ssl_policy')) == SSL_POLICY_FULL
1521 && strpos($this->getBaseURL(), 'https://') === 0
1522 && $_SERVER['REQUEST_METHOD'] == 'GET') {
1523 header('HTTP/1.1 302 Moved Temporarily');
1524 header('Location: ' . $this->getBaseURL() . '/' . $this->query_string);
1528 Core\Session::init();
1529 Core\Addon::callHooks('init_1');
1532 // Exclude the backend processes from the session management
1533 if (!$this->isBackend()) {
1534 $stamp1 = microtime(true);
1536 $this->saveTimestamp($stamp1, 'parser');
1537 Core\L10n::setSessionVariable();
1538 Core\L10n::setLangFromSession();
1541 Core\Worker::executeIfIdle();
1545 if (!empty($_GET['zrl']) && $this->getMode()->isNormal()) {
1546 $this->query_string = Model\Profile::stripZrls($this->query_string);
1547 if (!local_user()) {
1548 // Only continue when the given profile link seems valid
1549 // Valid profile links contain a path with "/profile/" and no query parameters
1550 if ((parse_url($_GET['zrl'], PHP_URL_QUERY) == "") &&
1551 strstr(parse_url($_GET['zrl'], PHP_URL_PATH), "/profile/")) {
1552 if (defaults($_SESSION, "visitor_home", "") != $_GET["zrl"]) {
1553 $_SESSION['my_url'] = $_GET['zrl'];
1554 $_SESSION['authenticated'] = 0;
1556 Model\Profile::zrlInit($this);
1558 // Someone came with an invalid parameter, maybe as a DDoS attempt
1559 // We simply stop processing here
1560 Core\Logger::log("Invalid ZRL parameter " . $_GET['zrl'], Core\Logger::DEBUG);
1561 Core\System::httpExit(403, ['title' => '403 Forbidden']);
1566 if (!empty($_GET['owt']) && $this->getMode()->isNormal()) {
1567 $token = $_GET['owt'];
1568 $this->query_string = Model\Profile::stripQueryParam($this->query_string, 'owt');
1569 Model\Profile::openWebAuthInit($token);
1572 Module\Login::sessionAuth();
1574 if (empty($_SESSION['authenticated'])) {
1575 header('X-Account-Management-Status: none');
1578 $_SESSION['sysmsg'] = defaults($_SESSION, 'sysmsg' , []);
1579 $_SESSION['sysmsg_info'] = defaults($_SESSION, 'sysmsg_info' , []);
1580 $_SESSION['last_updated'] = defaults($_SESSION, 'last_updated', []);
1583 * check_config() is responsible for running update scripts. These automatically
1584 * update the DB schema whenever we push a new one out. It also checks to see if
1585 * any addons have been added or removed and reacts accordingly.
1588 // in install mode, any url loads install module
1589 // but we need "view" module for stylesheet
1590 if ($this->getMode()->isInstall() && $this->module != 'view') {
1591 $this->module = 'install';
1592 } elseif (!$this->getMode()->has(App\Mode::MAINTENANCEDISABLED) && $this->module != 'view') {
1593 $this->module = 'maintenance';
1596 Core\Update::check(false);
1597 Core\Addon::loadAddons();
1598 Core\Hook::loadHooks();
1609 'right_aside' => '',
1614 if (strlen($this->module)) {
1615 // Compatibility with the Android Diaspora client
1616 if ($this->module == 'stream') {
1617 $this->internalRedirect('network?f=&order=post');
1620 if ($this->module == 'conversations') {
1621 $this->internalRedirect('message');
1624 if ($this->module == 'commented') {
1625 $this->internalRedirect('network?f=&order=comment');
1628 if ($this->module == 'liked') {
1629 $this->internalRedirect('network?f=&order=comment');
1632 if ($this->module == 'activity') {
1633 $this->internalRedirect('network/?f=&conv=1');
1636 if (($this->module == 'status_messages') && ($this->cmd == 'status_messages/new')) {
1637 $this->internalRedirect('bookmarklet');
1640 if (($this->module == 'user') && ($this->cmd == 'user/edit')) {
1641 $this->internalRedirect('settings');
1644 if (($this->module == 'tag_followings') && ($this->cmd == 'tag_followings/manage')) {
1645 $this->internalRedirect('search');
1648 // Compatibility with the Firefox App
1649 if (($this->module == "users") && ($this->cmd == "users/sign_in")) {
1650 $this->module = "login";
1653 $privateapps = Core\Config::get('config', 'private_addons', false);
1654 if (Core\Addon::isEnabled($this->module) && file_exists("addon/{$this->module}/{$this->module}.php")) {
1655 //Check if module is an app and if public access to apps is allowed or not
1656 if ((!local_user()) && Core\Hook::isAddonApp($this->module) && $privateapps) {
1657 info(Core\L10n::t("You must be logged in to use addons. "));
1659 include_once "addon/{$this->module}/{$this->module}.php";
1660 if (function_exists($this->module . '_module')) {
1661 LegacyModule::setModuleFile("addon/{$this->module}/{$this->module}.php");
1662 $this->module_class = 'Friendica\\LegacyModule';
1663 $this->module_loaded = true;
1668 // Controller class routing
1669 if (! $this->module_loaded && class_exists('Friendica\\Module\\' . ucfirst($this->module))) {
1670 $this->module_class = 'Friendica\\Module\\' . ucfirst($this->module);
1671 $this->module_loaded = true;
1674 /* If not, next look for a 'standard' program module in the 'mod' directory
1675 * We emulate a Module class through the LegacyModule class
1677 if (! $this->module_loaded && file_exists("mod/{$this->module}.php")) {
1678 LegacyModule::setModuleFile("mod/{$this->module}.php");
1679 $this->module_class = 'Friendica\\LegacyModule';
1680 $this->module_loaded = true;
1683 /* The URL provided does not resolve to a valid module.
1685 * On Dreamhost sites, quite often things go wrong for no apparent reason and they send us to '/internal_error.html'.
1686 * We don't like doing this, but as it occasionally accounts for 10-20% or more of all site traffic -
1687 * 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
1688 * this will often succeed and eventually do the right thing.
1690 * Otherwise we are going to emit a 404 not found.
1692 if (! $this->module_loaded) {
1693 // Stupid browser tried to pre-fetch our Javascript img template. Don't log the event or return anything - just quietly exit.
1694 if (!empty($_SERVER['QUERY_STRING']) && preg_match('/{[0-9]}/', $_SERVER['QUERY_STRING']) !== 0) {
1698 if (!empty($_SERVER['QUERY_STRING']) && ($_SERVER['QUERY_STRING'] === 'q=internal_error.html') && isset($dreamhost_error_hack)) {
1699 Core\Logger::log('index.php: dreamhost_error_hack invoked. Original URI =' . $_SERVER['REQUEST_URI']);
1700 $this->internalRedirect($_SERVER['REQUEST_URI']);
1703 Core\Logger::log('index.php: page not found: ' . $_SERVER['REQUEST_URI'] . ' ADDRESS: ' . $_SERVER['REMOTE_ADDR'] . ' QUERY: ' . $_SERVER['QUERY_STRING'], Core\Logger::DEBUG);
1705 header($_SERVER["SERVER_PROTOCOL"] . ' 404 ' . Core\L10n::t('Not Found'));
1706 $tpl = Core\Renderer::getMarkupTemplate("404.tpl");
1707 $this->page['content'] = Core\Renderer::replaceMacros($tpl, [
1708 '$message' => Core\L10n::t('Page not found.')
1715 // Call module functions
1716 if ($this->module_loaded) {
1717 $this->page['page_title'] = $this->module;
1720 Core\Addon::callHooks($this->module . '_mod_init', $placeholder);
1722 call_user_func([$this->module_class, 'init']);
1724 // "rawContent" is especially meant for technical endpoints.
1725 // This endpoint doesn't need any theme initialization or other comparable stuff.
1726 if (!$this->error) {
1727 call_user_func([$this->module_class, 'rawContent']);
1730 if (function_exists(str_replace('-', '_', $this->getCurrentTheme()) . '_init')) {
1731 $func = str_replace('-', '_', $this->getCurrentTheme()) . '_init';
1735 if (! $this->error && $_SERVER['REQUEST_METHOD'] === 'POST') {
1736 Core\Addon::callHooks($this->module . '_mod_post', $_POST);
1737 call_user_func([$this->module_class, 'post']);
1740 if (! $this->error) {
1741 Core\Addon::callHooks($this->module . '_mod_afterpost', $placeholder);
1742 call_user_func([$this->module_class, 'afterpost']);
1745 if (! $this->error) {
1746 $arr = ['content' => $content];
1747 Core\Addon::callHooks($this->module . '_mod_content', $arr);
1748 $content = $arr['content'];
1749 $arr = ['content' => call_user_func([$this->module_class, 'content'])];
1750 Core\Addon::callHooks($this->module . '_mod_aftercontent', $arr);
1751 $content .= $arr['content'];
1755 // Load current theme info after module has been executed as theme could have been set in module
1756 $theme_info_file = 'view/theme/' . $this->getCurrentTheme() . '/theme.php';
1757 if (file_exists($theme_info_file)) {
1758 require_once $theme_info_file;
1761 // initialise content region
1762 if ($this->getMode()->isNormal()) {
1763 Core\Addon::callHooks('page_content_top', $this->page['content']);
1766 $this->page['content'] .= $content;
1768 /* Create the page head after setting the language
1769 * and getting any auth credentials.
1771 * Moved initHead() and initFooter() to after
1772 * all the module functions have executed so that all
1773 * theme choices made by the modules can take effect.
1777 /* Build the page ending -- this is stuff that goes right before
1778 * the closing </body> tag
1780 $this->initFooter();
1782 /* now that we've been through the module content, see if the page reported
1783 * a permission problem and if so, a 403 response would seem to be in order.
1785 if (stristr(implode("", $_SESSION['sysmsg']), Core\L10n::t('Permission denied'))) {
1786 header($_SERVER["SERVER_PROTOCOL"] . ' 403 ' . Core\L10n::t('Permission denied.'));
1789 // Report anything which needs to be communicated in the notification area (before the main body)
1790 Core\Addon::callHooks('page_end', $this->page['content']);
1792 // Add the navigation (menu) template
1793 if ($this->module != 'install' && $this->module != 'maintenance') {
1794 $this->page['htmlhead'] .= Core\Renderer::replaceMacros(Core\Renderer::getMarkupTemplate('nav_head.tpl'), []);
1795 $this->page['nav'] = Content\Nav::build($this);
1798 // Build the page - now that we have all the components
1799 if (isset($_GET["mode"]) && (($_GET["mode"] == "raw") || ($_GET["mode"] == "minimal"))) {
1800 $doc = new DOMDocument();
1802 $target = new DOMDocument();
1803 $target->loadXML("<root></root>");
1805 $content = mb_convert_encoding($this->page["content"], 'HTML-ENTITIES', "UTF-8");
1807 /// @TODO one day, kill those error-surpressing @ stuff, or PHP should ban it
1808 @$doc->loadHTML($content);
1810 $xpath = new DOMXPath($doc);
1812 $list = $xpath->query("//*[contains(@id,'tread-wrapper-')]"); /* */
1814 foreach ($list as $item) {
1815 $item = $target->importNode($item, true);
1817 // And then append it to the target
1818 $target->documentElement->appendChild($item);
1822 if (isset($_GET["mode"]) && ($_GET["mode"] == "raw")) {
1823 header("Content-type: text/html; charset=utf-8");
1825 echo substr($target->saveHTML(), 6, -8);
1830 $page = $this->page;
1831 $profile = $this->profile;
1833 header("X-Friendica-Version: " . FRIENDICA_VERSION);
1834 header("Content-type: text/html; charset=utf-8");
1836 if (Core\Config::get('system', 'hsts') && (Core\Config::get('system', 'ssl_policy') == SSL_POLICY_FULL)) {
1837 header("Strict-Transport-Security: max-age=31536000");
1840 // Some security stuff
1841 header('X-Content-Type-Options: nosniff');
1842 header('X-XSS-Protection: 1; mode=block');
1843 header('X-Permitted-Cross-Domain-Policies: none');
1844 header('X-Frame-Options: sameorigin');
1846 // Things like embedded OSM maps don't work, when this is enabled
1847 // 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'");
1849 /* We use $_GET["mode"] for special page templates. So we will check if we have
1850 * to load another page template than the default one.
1851 * The page templates are located in /view/php/ or in the theme directory.
1853 if (isset($_GET["mode"])) {
1854 $template = Core\Theme::getPathForFile($_GET["mode"] . '.php');
1857 // If there is no page template use the default page template
1858 if (empty($template)) {
1859 $template = Core\Theme::getPathForFile("default.php");
1862 // Theme templates expect $a as an App instance
1865 // Used as is in view/php/default.php
1866 $lang = Core\L10n::getCurrentLang();
1868 /// @TODO Looks unsafe (remote-inclusion), is maybe not but Core\Theme::getPathForFile() uses file_exists() but does not escape anything
1869 require_once $template;
1873 * Redirects to another module relative to the current Friendica base.
1874 * If you want to redirect to a external URL, use System::externalRedirectTo()
1876 * @param string $toUrl The destination URL (Default is empty, which is the default page of the Friendica node)
1877 * @param bool $ssl if true, base URL will try to get called with https:// (works just for relative paths)
1879 * @throws InternalServerErrorException In Case the given URL is not relative to the Friendica node
1881 public function internalRedirect($toUrl = '', $ssl = false)
1883 if (!empty(parse_url($toUrl, PHP_URL_SCHEME))) {
1884 throw new InternalServerErrorException("'$toUrl is not a relative path, please use System::externalRedirectTo");
1887 $redirectTo = $this->getBaseURL($ssl) . '/' . ltrim($toUrl, '/');
1888 Core\System::externalRedirect($redirectTo);
1892 * Automatically redirects to relative or absolute URL
1893 * Should only be used if it isn't clear if the URL is either internal or external
1895 * @param string $toUrl The target URL
1898 public function redirect($toUrl)
1900 if (!empty(parse_url($toUrl, PHP_URL_SCHEME))) {
1901 Core\System::externalRedirect($toUrl);
1903 $this->internalRedirect($toUrl);