7 use Detection\MobileDetect;
11 use Friendica\Database\DBA;
12 use Friendica\Network\HTTPException\InternalServerErrorException;
14 require_once 'boot.php';
15 require_once 'include/text.php';
21 * @brief Our main application structure for the life of this page.
23 * Primarily deals with the URL that got us here
24 * and tries to make some sense of it, and
25 * stores our page contents and config storage
26 * and anything else that might need to be passed around
27 * before we spit the page out.
32 public $module_loaded = false;
33 public $module_class = null;
34 public $query_string = '';
46 public $error = false;
52 public $interactive = true;
54 public $is_mobile = false;
55 public $is_tablet = false;
56 public $performance = [];
57 public $callstack = [];
58 public $theme_info = [];
60 // Allow themes to control internal parameters
61 // by changing App values in theme.php
63 public $sourcename = '';
64 public $videowidth = 425;
65 public $videoheight = 350;
66 public $force_max_items = 0;
67 public $theme_events_in_profile = true;
69 public $stylesheets = [];
70 public $footerScripts = [];
73 * @var App\Mode The Mode of the Application
78 * @var string The App base path
83 * @var string The App URL path
88 * @var bool true, if the call is from the Friendica APP, otherwise false
90 private $isFriendicaApp;
93 * @var bool true, if the call is from an backend node (f.e. worker)
98 * @var string The name of the current theme
100 private $currentTheme;
103 * @var bool check if request was an AJAX (xmlhttprequest) request
108 * Register a stylesheet file path to be included in the <head> tag of every page.
109 * Inclusion is done in App->initHead().
110 * The path can be absolute or relative to the Friendica installation base folder.
114 * @param string $path
116 public function registerStylesheet($path)
118 $url = str_replace($this->getBasePath() . DIRECTORY_SEPARATOR, '', $path);
120 $this->stylesheets[] = trim($url, '/');
124 * Register a javascript file path to be included in the <footer> tag of every page.
125 * Inclusion is done in App->initFooter().
126 * The path can be absolute or relative to the Friendica installation base folder.
130 * @param string $path
132 public function registerFooterScript($path)
134 $url = str_replace($this->getBasePath() . DIRECTORY_SEPARATOR, '', $path);
136 $this->footerScripts[] = trim($url, '/');
145 * @brief App constructor.
147 * @param string $basePath Path to the app base folder
148 * @param bool $isBackend Whether it is used for backend or frontend (Default true=backend)
150 * @throws Exception if the Basepath is not usable
152 public function __construct($basePath, $isBackend = true)
154 if (!static::isDirectoryUsable($basePath, false)) {
155 throw new Exception('Basepath ' . $basePath . ' isn\'t usable.');
158 BaseObject::setApp($this);
160 $this->basePath = rtrim($basePath, DIRECTORY_SEPARATOR);
161 $this->checkBackend($isBackend);
162 $this->checkFriendicaApp();
164 $this->performance['start'] = microtime(true);
165 $this->performance['database'] = 0;
166 $this->performance['database_write'] = 0;
167 $this->performance['cache'] = 0;
168 $this->performance['cache_write'] = 0;
169 $this->performance['network'] = 0;
170 $this->performance['file'] = 0;
171 $this->performance['rendering'] = 0;
172 $this->performance['parser'] = 0;
173 $this->performance['marktime'] = 0;
174 $this->performance['markstart'] = microtime(true);
176 $this->callstack['database'] = [];
177 $this->callstack['database_write'] = [];
178 $this->callstack['cache'] = [];
179 $this->callstack['cache_write'] = [];
180 $this->callstack['network'] = [];
181 $this->callstack['file'] = [];
182 $this->callstack['rendering'] = [];
183 $this->callstack['parser'] = [];
185 $this->mode = new App\Mode($basePath);
191 // This has to be quite large to deal with embedded private photos
192 ini_set('pcre.backtrack_limit', 500000);
194 $this->scheme = 'http';
196 if (!empty($_SERVER['HTTPS']) ||
197 !empty($_SERVER['HTTP_FORWARDED']) && preg_match('/proto=https/', $_SERVER['HTTP_FORWARDED']) ||
198 !empty($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https' ||
199 !empty($_SERVER['HTTP_X_FORWARDED_SSL']) && $_SERVER['HTTP_X_FORWARDED_SSL'] == 'on' ||
200 !empty($_SERVER['FRONT_END_HTTPS']) && $_SERVER['FRONT_END_HTTPS'] == 'on' ||
201 !empty($_SERVER['SERVER_PORT']) && (intval($_SERVER['SERVER_PORT']) == 443) // XXX: reasonable assumption, but isn't this hardcoding too much?
203 $this->scheme = 'https';
206 if (!empty($_SERVER['SERVER_NAME'])) {
207 $this->hostname = $_SERVER['SERVER_NAME'];
209 if (!empty($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] != 80 && $_SERVER['SERVER_PORT'] != 443) {
210 $this->hostname .= ':' . $_SERVER['SERVER_PORT'];
215 get_include_path() . PATH_SEPARATOR
216 . $this->getBasePath() . DIRECTORY_SEPARATOR . 'include' . PATH_SEPARATOR
217 . $this->getBasePath(). DIRECTORY_SEPARATOR . 'library' . PATH_SEPARATOR
218 . $this->getBasePath());
220 if (!empty($_SERVER['QUERY_STRING']) && strpos($_SERVER['QUERY_STRING'], 'pagename=') === 0) {
221 $this->query_string = substr($_SERVER['QUERY_STRING'], 9);
222 } elseif (!empty($_SERVER['QUERY_STRING']) && strpos($_SERVER['QUERY_STRING'], 'q=') === 0) {
223 $this->query_string = substr($_SERVER['QUERY_STRING'], 2);
226 // removing trailing / - maybe a nginx problem
227 $this->query_string = ltrim($this->query_string, '/');
229 if (!empty($_GET['pagename'])) {
230 $this->cmd = trim($_GET['pagename'], '/\\');
231 } elseif (!empty($_GET['q'])) {
232 $this->cmd = trim($_GET['q'], '/\\');
236 $this->query_string = str_replace($this->cmd . '&', $this->cmd . '?', $this->query_string);
238 // unix style "homedir"
239 if (substr($this->cmd, 0, 1) === '~') {
240 $this->cmd = 'profile/' . substr($this->cmd, 1);
243 // Diaspora style profile url
244 if (substr($this->cmd, 0, 2) === 'u/') {
245 $this->cmd = 'profile/' . substr($this->cmd, 2);
249 * Break the URL path into C style argc/argv style arguments for our
250 * modules. Given "http://example.com/module/arg1/arg2", $this->argc
251 * will be 3 (integer) and $this->argv will contain:
257 * There will always be one argument. If provided a naked domain
258 * URL, $this->argv[0] is set to "home".
261 $this->argv = explode('/', $this->cmd);
262 $this->argc = count($this->argv);
263 if ((array_key_exists('0', $this->argv)) && strlen($this->argv[0])) {
264 $this->module = str_replace('.', '_', $this->argv[0]);
265 $this->module = str_replace('-', '_', $this->module);
268 $this->argv = ['home'];
269 $this->module = 'home';
272 // Detect mobile devices
273 $mobile_detect = new MobileDetect();
274 $this->is_mobile = $mobile_detect->isMobile();
275 $this->is_tablet = $mobile_detect->isTablet();
277 $this->isAjax = strtolower(defaults($_SERVER, 'HTTP_X_REQUESTED_WITH', '')) == 'xmlhttprequest';
279 // Register template engines
280 Core\Renderer::registerTemplateEngine('Friendica\Render\FriendicaSmartyEngine');
284 * Returns the Mode of the Application
286 * @return App\Mode The Application Mode
288 * @throws InternalServerErrorException when the mode isn't created
290 public function getMode()
292 if (empty($this->mode)) {
293 throw new InternalServerErrorException('Mode of the Application is not defined');
300 * Reloads the whole app instance
302 public function reload()
304 // The order of the following calls is important to ensure proper initialization
305 $this->loadConfigFiles();
307 $this->loadDatabase();
309 $this->getMode()->determine($this->getBasePath());
311 $this->determineURLPath();
315 if ($this->getMode()->has(App\Mode::DBAVAILABLE)) {
316 Core\Hook::loadHooks();
318 $this->loadAddonConfig();
321 $this->loadDefaultTimezone();
325 $this->process_id = Core\System::processID('log');
329 * Load the configuration files
331 * First loads the default value for all the configuration keys, then the legacy configuration files, then the
332 * expected local.ini.php
334 private function loadConfigFiles()
336 $this->loadConfigFile($this->getBasePath() . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'config.ini.php');
337 $this->loadConfigFile($this->getBasePath() . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'settings.ini.php');
339 // Legacy .htconfig.php support
340 if (file_exists($this->getBasePath() . DIRECTORY_SEPARATOR . '.htpreconfig.php')) {
342 include $this->getBasePath() . DIRECTORY_SEPARATOR . '.htpreconfig.php';
345 // Legacy .htconfig.php support
346 if (file_exists($this->getBasePath() . DIRECTORY_SEPARATOR . '.htconfig.php')) {
349 include $this->getBasePath() . DIRECTORY_SEPARATOR . '.htconfig.php';
351 $this->setConfigValue('database', 'hostname', $db_host);
352 $this->setConfigValue('database', 'username', $db_user);
353 $this->setConfigValue('database', 'password', $db_pass);
354 $this->setConfigValue('database', 'database', $db_data);
355 if (isset($a->config['system']['db_charset'])) {
356 $this->setConfigValue('database', 'charset', $a->config['system']['db_charset']);
359 unset($db_host, $db_user, $db_pass, $db_data);
361 if (isset($default_timezone)) {
362 $this->setConfigValue('system', 'default_timezone', $default_timezone);
363 unset($default_timezone);
366 if (isset($pidfile)) {
367 $this->setConfigValue('system', 'pidfile', $pidfile);
372 $this->setConfigValue('system', 'language', $lang);
377 if (file_exists($this->getBasePath() . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'local.ini.php')) {
378 $this->loadConfigFile($this->getBasePath() . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'local.ini.php', true);
383 * Tries to load the specified configuration file into the App->config array.
384 * Doesn't overwrite previously set values by default to prevent default config files to supersede DB Config.
386 * The config format is INI and the template for configuration files is the following:
388 * <?php return <<<INI
396 * @param string $filepath
397 * @param bool $overwrite Force value overwrite if the config key already exists
400 public function loadConfigFile($filepath, $overwrite = false)
402 if (!file_exists($filepath)) {
403 throw new Exception('Error parsing non-existent config file ' . $filepath);
406 $contents = include($filepath);
408 $config = parse_ini_string($contents, true, INI_SCANNER_TYPED);
410 if ($config === false) {
411 throw new Exception('Error parsing config file ' . $filepath);
414 foreach ($config as $category => $values) {
415 foreach ($values as $key => $value) {
417 $this->setConfigValue($category, $key, $value);
419 $this->setDefaultConfigValue($category, $key, $value);
426 * Loads addons configuration files
428 * First loads all activated addons default configuration throught the load_config hook, then load the local.ini.php
429 * again to overwrite potential local addon configuration.
431 private function loadAddonConfig()
433 // Loads addons default config
434 Core\Addon::callHooks('load_config');
436 // Load the local addon config file to overwritten default addon config values
437 if (file_exists($this->getBasePath() . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'addon.ini.php')) {
438 $this->loadConfigFile($this->getBasePath() . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'addon.ini.php', true);
443 * Loads the default timezone
445 * Include support for legacy $default_timezone
447 * @global string $default_timezone
449 private function loadDefaultTimezone()
451 if ($this->getConfigValue('system', 'default_timezone')) {
452 $this->timezone = $this->getConfigValue('system', 'default_timezone');
454 global $default_timezone;
455 $this->timezone = !empty($default_timezone) ? $default_timezone : 'UTC';
458 if ($this->timezone) {
459 date_default_timezone_set($this->timezone);
464 * Figure out if we are running at the top of a domain or in a sub-directory and adjust accordingly
466 private function determineURLPath()
468 /* Relative script path to the web server root
469 * Not all of those $_SERVER properties can be present, so we do by inverse priority order
471 $relative_script_path = '';
472 $relative_script_path = defaults($_SERVER, 'REDIRECT_URL' , $relative_script_path);
473 $relative_script_path = defaults($_SERVER, 'REDIRECT_URI' , $relative_script_path);
474 $relative_script_path = defaults($_SERVER, 'REDIRECT_SCRIPT_URL', $relative_script_path);
475 $relative_script_path = defaults($_SERVER, 'SCRIPT_URL' , $relative_script_path);
476 $relative_script_path = defaults($_SERVER, 'REQUEST_URI' , $relative_script_path);
478 $this->urlPath = $this->getConfigValue('system', 'urlpath');
480 /* $relative_script_path gives /relative/path/to/friendica/module/parameter
481 * QUERY_STRING gives pagename=module/parameter
483 * To get /relative/path/to/friendica we perform dirname() for as many levels as there are slashes in the QUERY_STRING
485 if (!empty($relative_script_path)) {
487 if (!empty($_SERVER['QUERY_STRING'])) {
488 $path = trim(dirname($relative_script_path, substr_count(trim($_SERVER['QUERY_STRING'], '/'), '/') + 1), '/');
491 $path = trim($relative_script_path, '/');
494 if ($path && $path != $this->urlPath) {
495 $this->urlPath = $path;
500 public function loadDatabase()
502 if (DBA::connected()) {
506 $db_host = $this->getConfigValue('database', 'hostname');
507 $db_user = $this->getConfigValue('database', 'username');
508 $db_pass = $this->getConfigValue('database', 'password');
509 $db_data = $this->getConfigValue('database', 'database');
510 $charset = $this->getConfigValue('database', 'charset');
512 // Use environment variables for mysql if they are set beforehand
513 if (!empty(getenv('MYSQL_HOST'))
514 && (!empty(getenv('MYSQL_USERNAME')) || !empty(getenv('MYSQL_USER')))
515 && getenv('MYSQL_PASSWORD') !== false
516 && !empty(getenv('MYSQL_DATABASE')))
518 $db_host = getenv('MYSQL_HOST');
519 if (!empty(getenv('MYSQL_PORT'))) {
520 $db_host .= ':' . getenv('MYSQL_PORT');
522 if (!empty(getenv('MYSQL_USERNAME'))) {
523 $db_user = getenv('MYSQL_USERNAME');
525 $db_user = getenv('MYSQL_USER');
527 $db_pass = (string) getenv('MYSQL_PASSWORD');
528 $db_data = getenv('MYSQL_DATABASE');
531 $stamp1 = microtime(true);
533 if (DBA::connect($db_host, $db_user, $db_pass, $db_data, $charset)) {
534 // Loads DB_UPDATE_VERSION constant
535 Database\DBStructure::definition(false);
538 unset($db_host, $db_user, $db_pass, $db_data, $charset);
540 $this->saveTimestamp($stamp1, 'network');
544 * @brief Returns the base filesystem path of the App
546 * It first checks for the internal variable, then for DOCUMENT_ROOT and
551 public function getBasePath()
553 $basepath = $this->basePath;
556 $basepath = Core\Config::get('system', 'basepath');
559 if (!$basepath && !empty($_SERVER['DOCUMENT_ROOT'])) {
560 $basepath = $_SERVER['DOCUMENT_ROOT'];
563 if (!$basepath && !empty($_SERVER['PWD'])) {
564 $basepath = $_SERVER['PWD'];
567 return self::getRealPath($basepath);
571 * @brief Returns a normalized file path
573 * This is a wrapper for the "realpath" function.
574 * That function cannot detect the real path when some folders aren't readable.
575 * Since this could happen with some hosters we need to handle this.
577 * @param string $path The path that is about to be normalized
578 * @return string normalized path - when possible
580 public static function getRealPath($path)
582 $normalized = realpath($path);
584 if (!is_bool($normalized)) {
591 public function getScheme()
593 return $this->scheme;
597 * @brief Retrieves the Friendica instance base URL
599 * This function assembles the base URL from multiple parts:
600 * - Protocol is determined either by the request or a combination of
601 * system.ssl_policy and the $ssl parameter.
602 * - Host name is determined either by system.hostname or inferred from request
603 * - Path is inferred from SCRIPT_NAME
605 * Note: $ssl parameter value doesn't directly correlate with the resulting protocol
607 * @param bool $ssl Whether to append http or https under SSL_POLICY_SELFSIGN
608 * @return string Friendica server base URL
610 public function getBaseURL($ssl = false)
612 $scheme = $this->scheme;
614 if (Core\Config::get('system', 'ssl_policy') == SSL_POLICY_FULL) {
618 // Basically, we have $ssl = true on any links which can only be seen by a logged in user
619 // (and also the login link). Anything seen by an outsider will have it turned off.
621 if (Core\Config::get('system', 'ssl_policy') == SSL_POLICY_SELFSIGN) {
629 if (Core\Config::get('config', 'hostname') != '') {
630 $this->hostname = Core\Config::get('config', 'hostname');
633 return $scheme . '://' . $this->hostname . (!empty($this->getURLPath()) ? '/' . $this->getURLPath() : '' );
637 * @brief Initializes the baseurl components
639 * Clears the baseurl cache to prevent inconsistencies
643 public function setBaseURL($url)
645 $parsed = @parse_url($url);
648 if (!empty($parsed)) {
649 if (!empty($parsed['scheme'])) {
650 $this->scheme = $parsed['scheme'];
653 if (!empty($parsed['host'])) {
654 $hostname = $parsed['host'];
657 if (!empty($parsed['port'])) {
658 $hostname .= ':' . $parsed['port'];
660 if (!empty($parsed['path'])) {
661 $this->urlPath = trim($parsed['path'], '\\/');
664 if (file_exists($this->getBasePath() . DIRECTORY_SEPARATOR . '.htpreconfig.php')) {
665 include $this->getBasePath() . DIRECTORY_SEPARATOR . '.htpreconfig.php';
668 if (Core\Config::get('config', 'hostname') != '') {
669 $this->hostname = Core\Config::get('config', 'hostname');
672 if (!isset($this->hostname) || ($this->hostname == '')) {
673 $this->hostname = $hostname;
678 public function getHostName()
680 if (Core\Config::get('config', 'hostname') != '') {
681 $this->hostname = Core\Config::get('config', 'hostname');
684 return $this->hostname;
687 public function getURLPath()
689 return $this->urlPath;
693 * Initializes App->page['htmlhead'].
698 * - Registered stylesheets (through App->registerStylesheet())
699 * - Infinite scroll data
700 * - head.tpl template
702 public function initHead()
704 $interval = ((local_user()) ? Core\PConfig::get(local_user(), 'system', 'update_interval') : 40000);
706 // If the update is 'deactivated' set it to the highest integer number (~24 days)
708 $interval = 2147483647;
711 if ($interval < 10000) {
715 // compose the page title from the sitename and the
716 // current module called
717 if (!$this->module == '') {
718 $this->page['title'] = $this->config['sitename'] . ' (' . $this->module . ')';
720 $this->page['title'] = $this->config['sitename'];
723 if (!empty(Core\Renderer::$theme['stylesheet'])) {
724 $stylesheet = Core\Renderer::$theme['stylesheet'];
726 $stylesheet = $this->getCurrentThemeStylesheetPath();
729 $this->registerStylesheet($stylesheet);
731 $shortcut_icon = Core\Config::get('system', 'shortcut_icon');
732 if ($shortcut_icon == '') {
733 $shortcut_icon = 'images/friendica-32.png';
736 $touch_icon = Core\Config::get('system', 'touch_icon');
737 if ($touch_icon == '') {
738 $touch_icon = 'images/friendica-128.png';
741 Core\Addon::callHooks('head', $this->page['htmlhead']);
743 $tpl = Core\Renderer::getMarkupTemplate('head.tpl');
744 /* put the head template at the beginning of page['htmlhead']
745 * since the code added by the modules frequently depends on it
748 $this->page['htmlhead'] = Core\Renderer::replaceMacros($tpl, [
749 '$baseurl' => $this->getBaseURL(),
750 '$local_user' => local_user(),
751 '$generator' => 'Friendica' . ' ' . FRIENDICA_VERSION,
752 '$delitem' => Core\L10n::t('Delete this item?'),
753 '$showmore' => Core\L10n::t('show more'),
754 '$showfewer' => Core\L10n::t('show fewer'),
755 '$update_interval' => $interval,
756 '$shortcut_icon' => $shortcut_icon,
757 '$touch_icon' => $touch_icon,
758 '$block_public' => intval(Core\Config::get('system', 'block_public')),
759 '$stylesheets' => $this->stylesheets,
760 ]) . $this->page['htmlhead'];
764 * Initializes App->page['footer'].
767 * - Javascript homebase
768 * - Mobile toggle link
769 * - Registered footer scripts (through App->registerFooterScript())
770 * - footer.tpl template
772 public function initFooter()
774 // If you're just visiting, let javascript take you home
775 if (!empty($_SESSION['visitor_home'])) {
776 $homebase = $_SESSION['visitor_home'];
777 } elseif (local_user()) {
778 $homebase = 'profile/' . $this->user['nickname'];
781 if (isset($homebase)) {
782 $this->page['footer'] .= '<script>var homebase="' . $homebase . '";</script>' . "\n";
786 * Add a "toggle mobile" link if we're using a mobile device
788 if ($this->is_mobile || $this->is_tablet) {
789 if (isset($_SESSION['show-mobile']) && !$_SESSION['show-mobile']) {
790 $link = 'toggle_mobile?address=' . curPageURL();
792 $link = 'toggle_mobile?off=1&address=' . curPageURL();
794 $this->page['footer'] .= Core\Renderer::replaceMacros(Core\Renderer::getMarkupTemplate("toggle_mobile_footer.tpl"), [
795 '$toggle_link' => $link,
796 '$toggle_text' => Core\L10n::t('toggle mobile')
800 Core\Addon::callHooks('footer', $this->page['footer']);
802 $tpl = Core\Renderer::getMarkupTemplate('footer.tpl');
803 $this->page['footer'] = Core\Renderer::replaceMacros($tpl, [
804 '$baseurl' => $this->getBaseURL(),
805 '$footerScripts' => $this->footerScripts,
806 ]) . $this->page['footer'];
810 * @brief Removes the base url from an url. This avoids some mixed content problems.
812 * @param string $origURL
814 * @return string The cleaned url
816 public function removeBaseURL($origURL)
818 // Remove the hostname from the url if it is an internal link
819 $nurl = Util\Strings::normaliseLink($origURL);
820 $base = Util\Strings::normaliseLink($this->getBaseURL());
821 $url = str_replace($base . '/', '', $nurl);
823 // if it is an external link return the orignal value
824 if ($url == Util\Strings::normaliseLink($origURL)) {
832 * Saves a timestamp for a value - f.e. a call
833 * Necessary for profiling Friendica
835 * @param int $timestamp the Timestamp
836 * @param string $value A value to profile
838 public function saveTimestamp($timestamp, $value)
840 if (!isset($this->config['system']['profiler']) || !$this->config['system']['profiler']) {
844 $duration = (float) (microtime(true) - $timestamp);
846 if (!isset($this->performance[$value])) {
847 // Prevent ugly E_NOTICE
848 $this->performance[$value] = 0;
851 $this->performance[$value] += (float) $duration;
852 $this->performance['marktime'] += (float) $duration;
854 $callstack = Core\System::callstack();
856 if (!isset($this->callstack[$value][$callstack])) {
857 // Prevent ugly E_NOTICE
858 $this->callstack[$value][$callstack] = 0;
861 $this->callstack[$value][$callstack] += (float) $duration;
865 * Returns the current UserAgent as a String
867 * @return string the UserAgent as a String
869 public function getUserAgent()
872 FRIENDICA_PLATFORM . " '" .
873 FRIENDICA_CODENAME . "' " .
874 FRIENDICA_VERSION . '-' .
875 DB_UPDATE_VERSION . '; ' .
880 * Checks, if the call is from the Friendica App
883 * The friendica client has problems with the GUID in the notify. this is some workaround
885 private function checkFriendicaApp()
888 $this->isFriendicaApp = isset($_SERVER['HTTP_USER_AGENT']) && $_SERVER['HTTP_USER_AGENT'] == 'Apache-HttpClient/UNAVAILABLE (java 1.4)';
892 * Is the call via the Friendica app? (not a "normale" call)
894 * @return bool true if it's from the Friendica app
896 public function isFriendicaApp()
898 return $this->isFriendicaApp;
902 * @brief Checks if the site is called via a backend process
904 * This isn't a perfect solution. But we need this check very early.
905 * So we cannot wait until the modules are loaded.
907 * @param string $backend true, if the backend flag was set during App initialization
910 private function checkBackend($backend) {
933 // Check if current module is in backend or backend flag is set
934 $this->isBackend = (in_array($this->module, $backends) || $backend || $this->isBackend);
938 * Returns true, if the call is from a backend node (f.e. from a worker)
940 * @return bool Is it a known backend?
942 public function isBackend()
944 return $this->isBackend;
948 * @brief Checks if the maximum number of database processes is reached
950 * @return bool Is the limit reached?
952 public function isMaxProcessesReached()
954 // Deactivated, needs more investigating if this check really makes sense
958 * Commented out to suppress static analyzer issues
960 if ($this->is_backend()) {
961 $process = 'backend';
962 $max_processes = Core\Config::get('system', 'max_processes_backend');
963 if (intval($max_processes) == 0) {
967 $process = 'frontend';
968 $max_processes = Core\Config::get('system', 'max_processes_frontend');
969 if (intval($max_processes) == 0) {
974 $processlist = DBA::processlist();
975 if ($processlist['list'] != '') {
976 Core\Logger::log('Processcheck: Processes: ' . $processlist['amount'] . ' - Processlist: ' . $processlist['list'], Core\Logger::DEBUG);
978 if ($processlist['amount'] > $max_processes) {
979 Core\Logger::log('Processcheck: Maximum number of processes for ' . $process . ' tasks (' . $max_processes . ') reached.', Core\Logger::DEBUG);
988 * @brief Checks if the minimal memory is reached
990 * @return bool Is the memory limit reached?
992 public function isMinMemoryReached()
994 $min_memory = Core\Config::get('system', 'min_memory', 0);
995 if ($min_memory == 0) {
999 if (!is_readable('/proc/meminfo')) {
1003 $memdata = explode("\n", file_get_contents('/proc/meminfo'));
1006 foreach ($memdata as $line) {
1007 $data = explode(':', $line);
1008 if (count($data) != 2) {
1011 list($key, $val) = $data;
1012 $meminfo[$key] = (int) trim(str_replace('kB', '', $val));
1013 $meminfo[$key] = (int) ($meminfo[$key] / 1024);
1016 if (!isset($meminfo['MemAvailable']) || !isset($meminfo['MemFree'])) {
1020 $free = $meminfo['MemAvailable'] + $meminfo['MemFree'];
1022 $reached = ($free < $min_memory);
1025 Core\Logger::log('Minimal memory reached: ' . $free . '/' . $meminfo['MemTotal'] . ' - limit ' . $min_memory, Core\Logger::DEBUG);
1032 * @brief Checks if the maximum load is reached
1034 * @return bool Is the load reached?
1036 public function isMaxLoadReached()
1038 if ($this->isBackend()) {
1039 $process = 'backend';
1040 $maxsysload = intval(Core\Config::get('system', 'maxloadavg'));
1041 if ($maxsysload < 1) {
1045 $process = 'frontend';
1046 $maxsysload = intval(Core\Config::get('system', 'maxloadavg_frontend'));
1047 if ($maxsysload < 1) {
1052 $load = Core\System::currentLoad();
1054 if (intval($load) > $maxsysload) {
1055 Core\Logger::log('system: load ' . $load . ' for ' . $process . ' tasks (' . $maxsysload . ') too high.');
1063 * Executes a child process with 'proc_open'
1065 * @param string $command The command to execute
1066 * @param array $args Arguments to pass to the command ( [ 'key' => value, 'key2' => value2, ... ]
1068 public function proc_run($command, $args)
1070 if (!function_exists('proc_open')) {
1074 $cmdline = $this->getConfigValue('config', 'php_path', 'php') . ' ' . escapeshellarg($command);
1076 foreach ($args as $key => $value) {
1077 if (!is_null($value) && is_bool($value) && !$value) {
1081 $cmdline .= ' --' . $key;
1082 if (!is_null($value) && !is_bool($value)) {
1083 $cmdline .= ' ' . $value;
1087 if ($this->isMinMemoryReached()) {
1091 if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
1092 $resource = proc_open('cmd /c start /b ' . $cmdline, [], $foo, $this->getBasePath());
1094 $resource = proc_open($cmdline . ' &', [], $foo, $this->getBasePath());
1096 if (!is_resource($resource)) {
1097 Core\Logger::log('We got no resource for command ' . $cmdline, Core\Logger::DEBUG);
1100 proc_close($resource);
1104 * @brief Returns the system user that is executing the script
1106 * This mostly returns something like "www-data".
1108 * @return string system username
1110 private static function getSystemUser()
1112 if (!function_exists('posix_getpwuid') || !function_exists('posix_geteuid')) {
1116 $processUser = posix_getpwuid(posix_geteuid());
1117 return $processUser['name'];
1121 * @brief Checks if a given directory is usable for the system
1123 * @return boolean the directory is usable
1125 public static function isDirectoryUsable($directory, $check_writable = true)
1127 if ($directory == '') {
1128 Core\Logger::log('Directory is empty. This shouldn\'t happen.', Core\Logger::DEBUG);
1132 if (!file_exists($directory)) {
1133 Core\Logger::log('Path "' . $directory . '" does not exist for user ' . self::getSystemUser(), Core\Logger::DEBUG);
1137 if (is_file($directory)) {
1138 Core\Logger::log('Path "' . $directory . '" is a file for user ' . self::getSystemUser(), Core\Logger::DEBUG);
1142 if (!is_dir($directory)) {
1143 Core\Logger::log('Path "' . $directory . '" is not a directory for user ' . self::getSystemUser(), Core\Logger::DEBUG);
1147 if ($check_writable && !is_writable($directory)) {
1148 Core\Logger::log('Path "' . $directory . '" is not writable for user ' . self::getSystemUser(), Core\Logger::DEBUG);
1156 * @param string $cat Config category
1157 * @param string $k Config key
1158 * @param mixed $default Default value if it isn't set
1160 * @return string Returns the value of the Config entry
1162 public function getConfigValue($cat, $k, $default = null)
1166 if ($cat === 'config') {
1167 if (isset($this->config[$k])) {
1168 $return = $this->config[$k];
1171 if (isset($this->config[$cat][$k])) {
1172 $return = $this->config[$cat][$k];
1180 * Sets a default value in the config cache. Ignores already existing keys.
1182 * @param string $cat Config category
1183 * @param string $k Config key
1184 * @param mixed $v Default value to set
1186 private function setDefaultConfigValue($cat, $k, $v)
1188 if (!isset($this->config[$cat][$k])) {
1189 $this->setConfigValue($cat, $k, $v);
1194 * Sets a value in the config cache. Accepts raw output from the config table
1196 * @param string $cat Config category
1197 * @param string $k Config key
1198 * @param mixed $v Value to set
1200 public function setConfigValue($cat, $k, $v)
1202 // Only arrays are serialized in database, so we have to unserialize sparingly
1203 $value = is_string($v) && preg_match("|^a:[0-9]+:{.*}$|s", $v) ? unserialize($v) : $v;
1205 if ($cat === 'config') {
1206 $this->config[$k] = $value;
1208 if (!isset($this->config[$cat])) {
1209 $this->config[$cat] = [];
1212 $this->config[$cat][$k] = $value;
1217 * Deletes a value from the config cache
1219 * @param string $cat Config category
1220 * @param string $k Config key
1222 public function deleteConfigValue($cat, $k)
1224 if ($cat === 'config') {
1225 if (isset($this->config[$k])) {
1226 unset($this->config[$k]);
1229 if (isset($this->config[$cat][$k])) {
1230 unset($this->config[$cat][$k]);
1237 * Retrieves a value from the user config cache
1239 * @param int $uid User Id
1240 * @param string $cat Config category
1241 * @param string $k Config key
1242 * @param mixed $default Default value if key isn't set
1244 * @return string The value of the config entry
1246 public function getPConfigValue($uid, $cat, $k, $default = null)
1250 if (isset($this->config[$uid][$cat][$k])) {
1251 $return = $this->config[$uid][$cat][$k];
1258 * Sets a value in the user config cache
1260 * Accepts raw output from the pconfig table
1262 * @param int $uid User Id
1263 * @param string $cat Config category
1264 * @param string $k Config key
1265 * @param mixed $v Value to set
1267 public function setPConfigValue($uid, $cat, $k, $v)
1269 // Only arrays are serialized in database, so we have to unserialize sparingly
1270 $value = is_string($v) && preg_match("|^a:[0-9]+:{.*}$|s", $v) ? unserialize($v) : $v;
1272 if (!isset($this->config[$uid]) || !is_array($this->config[$uid])) {
1273 $this->config[$uid] = [];
1276 if (!isset($this->config[$uid][$cat]) || !is_array($this->config[$uid][$cat])) {
1277 $this->config[$uid][$cat] = [];
1280 $this->config[$uid][$cat][$k] = $value;
1284 * Deletes a value from the user config cache
1286 * @param int $uid User Id
1287 * @param string $cat Config category
1288 * @param string $k Config key
1290 public function deletePConfigValue($uid, $cat, $k)
1292 if (isset($this->config[$uid][$cat][$k])) {
1293 unset($this->config[$uid][$cat][$k]);
1298 * Generates the site's default sender email address
1302 public function getSenderEmailAddress()
1304 $sender_email = Core\Config::get('config', 'sender_email');
1305 if (empty($sender_email)) {
1306 $hostname = $this->getHostName();
1307 if (strpos($hostname, ':')) {
1308 $hostname = substr($hostname, 0, strpos($hostname, ':'));
1311 $sender_email = 'noreply@' . $hostname;
1314 return $sender_email;
1318 * Returns the current theme name.
1320 * @return string the name of the current theme
1322 public function getCurrentTheme()
1324 if ($this->getMode()->isInstall()) {
1328 //// @TODO Compute the current theme only once (this behavior has
1329 /// already been implemented, but it didn't work well -
1330 /// https://github.com/friendica/friendica/issues/5092)
1331 $this->computeCurrentTheme();
1333 return $this->currentTheme;
1337 * Computes the current theme name based on the node settings, the user settings and the device type
1341 private function computeCurrentTheme()
1343 $system_theme = Core\Config::get('system', 'theme');
1344 if (!$system_theme) {
1345 throw new Exception(Core\L10n::t('No system theme config value set.'));
1349 $this->currentTheme = $system_theme;
1351 $allowed_themes = explode(',', Core\Config::get('system', 'allowed_themes', $system_theme));
1354 // Find the theme that belongs to the user whose stuff we are looking at
1355 if ($this->profile_uid && ($this->profile_uid != local_user())) {
1356 // Allow folks to override user themes and always use their own on their own site.
1357 // This works only if the user is on the same server
1358 $user = DBA::selectFirst('user', ['theme'], ['uid' => $this->profile_uid]);
1359 if (DBA::isResult($user) && !Core\PConfig::get(local_user(), 'system', 'always_my_theme')) {
1360 $page_theme = $user['theme'];
1364 $user_theme = Core\Session::get('theme', $system_theme);
1366 // Specific mobile theme override
1367 if (($this->is_mobile || $this->is_tablet) && Core\Session::get('show-mobile', true)) {
1368 $system_mobile_theme = Core\Config::get('system', 'mobile-theme');
1369 $user_mobile_theme = Core\Session::get('mobile-theme', $system_mobile_theme);
1371 // --- means same mobile theme as desktop
1372 if (!empty($user_mobile_theme) && $user_mobile_theme !== '---') {
1373 $user_theme = $user_mobile_theme;
1378 $theme_name = $page_theme;
1380 $theme_name = $user_theme;
1384 && in_array($theme_name, $allowed_themes)
1385 && (file_exists('view/theme/' . $theme_name . '/style.css')
1386 || file_exists('view/theme/' . $theme_name . '/style.php'))
1388 $this->currentTheme = $theme_name;
1393 * @brief Return full URL to theme which is currently in effect.
1395 * Provide a sane default if nothing is chosen or the specified theme does not exist.
1399 public function getCurrentThemeStylesheetPath()
1401 return Core\Theme::getStylesheetPath($this->getCurrentTheme());
1405 * Check if request was an AJAX (xmlhttprequest) request.
1407 * @return boolean true if it was an AJAX request
1409 public function isAjax()
1411 return $this->isAjax;
1415 * Returns the value of a argv key
1416 * TODO there are a lot of $a->argv usages in combination with defaults() which can be replaced with this method
1418 * @param int $position the position of the argument
1419 * @param mixed $default the default value if not found
1421 * @return mixed returns the value of the argument
1423 public function getArgumentValue($position, $default = '')
1425 if (array_key_exists($position, $this->argv)) {
1426 return $this->argv[$position];
1433 * Sets the base url for use in cmdline programs which don't have
1434 * $_SERVER variables
1436 public function checkURL()
1438 $url = Core\Config::get('system', 'url');
1440 // if the url isn't set or the stored url is radically different
1441 // than the currently visited url, store the current value accordingly.
1442 // "Radically different" ignores common variations such as http vs https
1443 // and www.example.com vs example.com.
1444 // We will only change the url to an ip address if there is no existing setting
1446 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()))) {
1447 Core\Config::set('system', 'url', $this->getBaseURL());
1452 * Frontend App script
1454 * The App object behaves like a container and a dispatcher at the same time, including a representation of the
1455 * request and a representation of the response.
1457 * This probably should change to limit the size of this monster method.
1459 public function runFrontend()
1461 // Missing DB connection: ERROR
1462 if ($this->getMode()->has(App\Mode::LOCALCONFIGPRESENT) && !$this->getMode()->has(App\Mode::DBAVAILABLE)) {
1463 Core\System::httpExit(500, ['title' => 'Error 500 - Internal Server Error', 'description' => 'Apologies but the website is unavailable at the moment.']);
1466 // Max Load Average reached: ERROR
1467 if ($this->isMaxProcessesReached() || $this->isMaxLoadReached()) {
1468 header('Retry-After: 120');
1469 header('Refresh: 120; url=' . $this->getBaseURL() . "/" . $this->query_string);
1471 Core\System::httpExit(503, ['title' => 'Error 503 - Service Temporarily Unavailable', 'description' => 'Core\System is currently overloaded. Please try again later.']);
1474 if (strstr($this->query_string, '.well-known/host-meta') && ($this->query_string != '.well-known/host-meta')) {
1475 Core\System::httpExit(404);
1478 if (!$this->getMode()->isInstall()) {
1479 // Force SSL redirection
1480 if (Core\Config::get('system', 'force_ssl') && ($this->getScheme() == "http")
1481 && intval(Core\Config::get('system', 'ssl_policy')) == SSL_POLICY_FULL
1482 && strpos($this->getBaseURL(), 'https://') === 0
1483 && $_SERVER['REQUEST_METHOD'] == 'GET') {
1484 header('HTTP/1.1 302 Moved Temporarily');
1485 header('Location: ' . $this->getBaseURL() . '/' . $this->query_string);
1489 Core\Session::init();
1490 Core\Addon::callHooks('init_1');
1493 // Exclude the backend processes from the session management
1494 if (!$this->isBackend()) {
1495 $stamp1 = microtime(true);
1497 $this->saveTimestamp($stamp1, 'parser');
1498 Core\L10n::setSessionVariable();
1499 Core\L10n::setLangFromSession();
1502 Core\Worker::executeIfIdle();
1506 if (!empty($_GET['zrl']) && $this->getMode()->isNormal()) {
1507 $this->query_string = Model\Profile::stripZrls($this->query_string);
1508 if (!local_user()) {
1509 // Only continue when the given profile link seems valid
1510 // Valid profile links contain a path with "/profile/" and no query parameters
1511 if ((parse_url($_GET['zrl'], PHP_URL_QUERY) == "") &&
1512 strstr(parse_url($_GET['zrl'], PHP_URL_PATH), "/profile/")) {
1513 if (defaults($_SESSION, "visitor_home", "") != $_GET["zrl"]) {
1514 $_SESSION['my_url'] = $_GET['zrl'];
1515 $_SESSION['authenticated'] = 0;
1517 Model\Profile::zrlInit($this);
1519 // Someone came with an invalid parameter, maybe as a DDoS attempt
1520 // We simply stop processing here
1521 Core\Logger::log("Invalid ZRL parameter " . $_GET['zrl'], Core\Logger::DEBUG);
1522 Core\System::httpExit(403, ['title' => '403 Forbidden']);
1527 if (!empty($_GET['owt']) && $this->getMode()->isNormal()) {
1528 $token = $_GET['owt'];
1529 $this->query_string = Model\Profile::stripQueryParam($this->query_string, 'owt');
1530 Model\Profile::openWebAuthInit($token);
1533 Module\Login::sessionAuth();
1535 if (empty($_SESSION['authenticated'])) {
1536 header('X-Account-Management-Status: none');
1539 $_SESSION['sysmsg'] = defaults($_SESSION, 'sysmsg' , []);
1540 $_SESSION['sysmsg_info'] = defaults($_SESSION, 'sysmsg_info' , []);
1541 $_SESSION['last_updated'] = defaults($_SESSION, 'last_updated', []);
1544 * check_config() is responsible for running update scripts. These automatically
1545 * update the DB schema whenever we push a new one out. It also checks to see if
1546 * any addons have been added or removed and reacts accordingly.
1549 // in install mode, any url loads install module
1550 // but we need "view" module for stylesheet
1551 if ($this->getMode()->isInstall() && $this->module != 'view') {
1552 $this->module = 'install';
1553 } elseif (!$this->getMode()->has(App\Mode::MAINTENANCEDISABLED) && $this->module != 'view') {
1554 $this->module = 'maintenance';
1557 Core\Update::check(false);
1558 Core\Addon::loadAddons();
1559 Core\Hook::loadHooks();
1570 'right_aside' => '',
1575 if (strlen($this->module)) {
1576 // Compatibility with the Android Diaspora client
1577 if ($this->module == 'stream') {
1578 $this->internalRedirect('network?f=&order=post');
1581 if ($this->module == 'conversations') {
1582 $this->internalRedirect('message');
1585 if ($this->module == 'commented') {
1586 $this->internalRedirect('network?f=&order=comment');
1589 if ($this->module == 'liked') {
1590 $this->internalRedirect('network?f=&order=comment');
1593 if ($this->module == 'activity') {
1594 $this->internalRedirect('network/?f=&conv=1');
1597 if (($this->module == 'status_messages') && ($this->cmd == 'status_messages/new')) {
1598 $this->internalRedirect('bookmarklet');
1601 if (($this->module == 'user') && ($this->cmd == 'user/edit')) {
1602 $this->internalRedirect('settings');
1605 if (($this->module == 'tag_followings') && ($this->cmd == 'tag_followings/manage')) {
1606 $this->internalRedirect('search');
1609 // Compatibility with the Firefox App
1610 if (($this->module == "users") && ($this->cmd == "users/sign_in")) {
1611 $this->module = "login";
1614 $privateapps = Core\Config::get('config', 'private_addons', false);
1615 if (Core\Addon::isEnabled($this->module) && file_exists("addon/{$this->module}/{$this->module}.php")) {
1616 //Check if module is an app and if public access to apps is allowed or not
1617 if ((!local_user()) && Core\Hook::isAddonApp($this->module) && $privateapps) {
1618 info(Core\L10n::t("You must be logged in to use addons. "));
1620 include_once "addon/{$this->module}/{$this->module}.php";
1621 if (function_exists($this->module . '_module')) {
1622 LegacyModule::setModuleFile("addon/{$this->module}/{$this->module}.php");
1623 $this->module_class = 'Friendica\\LegacyModule';
1624 $this->module_loaded = true;
1629 // Controller class routing
1630 if (! $this->module_loaded && class_exists('Friendica\\Module\\' . ucfirst($this->module))) {
1631 $this->module_class = 'Friendica\\Module\\' . ucfirst($this->module);
1632 $this->module_loaded = true;
1635 /* If not, next look for a 'standard' program module in the 'mod' directory
1636 * We emulate a Module class through the LegacyModule class
1638 if (! $this->module_loaded && file_exists("mod/{$this->module}.php")) {
1639 LegacyModule::setModuleFile("mod/{$this->module}.php");
1640 $this->module_class = 'Friendica\\LegacyModule';
1641 $this->module_loaded = true;
1644 /* The URL provided does not resolve to a valid module.
1646 * On Dreamhost sites, quite often things go wrong for no apparent reason and they send us to '/internal_error.html'.
1647 * We don't like doing this, but as it occasionally accounts for 10-20% or more of all site traffic -
1648 * 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
1649 * this will often succeed and eventually do the right thing.
1651 * Otherwise we are going to emit a 404 not found.
1653 if (! $this->module_loaded) {
1654 // Stupid browser tried to pre-fetch our Javascript img template. Don't log the event or return anything - just quietly exit.
1655 if (!empty($_SERVER['QUERY_STRING']) && preg_match('/{[0-9]}/', $_SERVER['QUERY_STRING']) !== 0) {
1659 if (!empty($_SERVER['QUERY_STRING']) && ($_SERVER['QUERY_STRING'] === 'q=internal_error.html') && isset($dreamhost_error_hack)) {
1660 Core\Logger::log('index.php: dreamhost_error_hack invoked. Original URI =' . $_SERVER['REQUEST_URI']);
1661 $this->internalRedirect($_SERVER['REQUEST_URI']);
1664 Core\Logger::log('index.php: page not found: ' . $_SERVER['REQUEST_URI'] . ' ADDRESS: ' . $_SERVER['REMOTE_ADDR'] . ' QUERY: ' . $_SERVER['QUERY_STRING'], Core\Logger::DEBUG);
1666 header($_SERVER["SERVER_PROTOCOL"] . ' 404 ' . Core\L10n::t('Not Found'));
1667 $tpl = Core\Renderer::getMarkupTemplate("404.tpl");
1668 $this->page['content'] = Core\Renderer::replaceMacros($tpl, [
1669 '$message' => Core\L10n::t('Page not found.')
1674 // Load current theme info
1675 $theme_info_file = 'view/theme/' . $this->getCurrentTheme() . '/theme.php';
1676 if (file_exists($theme_info_file)) {
1677 require_once $theme_info_file;
1680 // initialise content region
1681 if ($this->getMode()->isNormal()) {
1682 Core\Addon::callHooks('page_content_top', $this->page['content']);
1685 // Call module functions
1686 if ($this->module_loaded) {
1687 $this->page['page_title'] = $this->module;
1690 Core\Addon::callHooks($this->module . '_mod_init', $placeholder);
1692 call_user_func([$this->module_class, 'init']);
1694 // "rawContent" is especially meant for technical endpoints.
1695 // This endpoint doesn't need any theme initialization or other comparable stuff.
1696 if (!$this->error) {
1697 call_user_func([$this->module_class, 'rawContent']);
1700 if (function_exists(str_replace('-', '_', $this->getCurrentTheme()) . '_init')) {
1701 $func = str_replace('-', '_', $this->getCurrentTheme()) . '_init';
1705 if (! $this->error && $_SERVER['REQUEST_METHOD'] === 'POST') {
1706 Core\Addon::callHooks($this->module . '_mod_post', $_POST);
1707 call_user_func([$this->module_class, 'post']);
1710 if (! $this->error) {
1711 Core\Addon::callHooks($this->module . '_mod_afterpost', $placeholder);
1712 call_user_func([$this->module_class, 'afterpost']);
1715 if (! $this->error) {
1716 $arr = ['content' => $this->page['content']];
1717 Core\Addon::callHooks($this->module . '_mod_content', $arr);
1718 $this->page['content'] = $arr['content'];
1719 $arr = ['content' => call_user_func([$this->module_class, 'content'])];
1720 Core\Addon::callHooks($this->module . '_mod_aftercontent', $arr);
1721 $this->page['content'] .= $arr['content'];
1724 if (function_exists(str_replace('-', '_', $this->getCurrentTheme()) . '_content_loaded')) {
1725 $func = str_replace('-', '_', $this->getCurrentTheme()) . '_content_loaded';
1730 /* Create the page head after setting the language
1731 * and getting any auth credentials.
1733 * Moved initHead() and initFooter() to after
1734 * all the module functions have executed so that all
1735 * theme choices made by the modules can take effect.
1739 /* Build the page ending -- this is stuff that goes right before
1740 * the closing </body> tag
1742 $this->initFooter();
1744 /* now that we've been through the module content, see if the page reported
1745 * a permission problem and if so, a 403 response would seem to be in order.
1747 if (stristr(implode("", $_SESSION['sysmsg']), Core\L10n::t('Permission denied'))) {
1748 header($_SERVER["SERVER_PROTOCOL"] . ' 403 ' . Core\L10n::t('Permission denied.'));
1751 // Report anything which needs to be communicated in the notification area (before the main body)
1752 Core\Addon::callHooks('page_end', $this->page['content']);
1754 // Add the navigation (menu) template
1755 if ($this->module != 'install' && $this->module != 'maintenance') {
1756 $this->page['htmlhead'] .= Core\Renderer::replaceMacros(Core\Renderer::getMarkupTemplate('nav_head.tpl'), []);
1757 $this->page['nav'] = Content\Nav::build($this);
1760 // Build the page - now that we have all the components
1761 if (isset($_GET["mode"]) && (($_GET["mode"] == "raw") || ($_GET["mode"] == "minimal"))) {
1762 $doc = new DOMDocument();
1764 $target = new DOMDocument();
1765 $target->loadXML("<root></root>");
1767 $content = mb_convert_encoding($this->page["content"], 'HTML-ENTITIES', "UTF-8");
1769 /// @TODO one day, kill those error-surpressing @ stuff, or PHP should ban it
1770 @$doc->loadHTML($content);
1772 $xpath = new DOMXPath($doc);
1774 $list = $xpath->query("//*[contains(@id,'tread-wrapper-')]"); /* */
1776 foreach ($list as $item) {
1777 $item = $target->importNode($item, true);
1779 // And then append it to the target
1780 $target->documentElement->appendChild($item);
1784 if (isset($_GET["mode"]) && ($_GET["mode"] == "raw")) {
1785 header("Content-type: text/html; charset=utf-8");
1787 echo substr($target->saveHTML(), 6, -8);
1792 $page = $this->page;
1793 $profile = $this->profile;
1795 header("X-Friendica-Version: " . FRIENDICA_VERSION);
1796 header("Content-type: text/html; charset=utf-8");
1798 if (Core\Config::get('system', 'hsts') && (Core\Config::get('system', 'ssl_policy') == SSL_POLICY_FULL)) {
1799 header("Strict-Transport-Security: max-age=31536000");
1802 // Some security stuff
1803 header('X-Content-Type-Options: nosniff');
1804 header('X-XSS-Protection: 1; mode=block');
1805 header('X-Permitted-Cross-Domain-Policies: none');
1806 header('X-Frame-Options: sameorigin');
1808 // Things like embedded OSM maps don't work, when this is enabled
1809 // 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'");
1811 /* We use $_GET["mode"] for special page templates. So we will check if we have
1812 * to load another page template than the default one.
1813 * The page templates are located in /view/php/ or in the theme directory.
1815 if (isset($_GET["mode"])) {
1816 $template = Core\Theme::getPathForFile($_GET["mode"] . '.php');
1819 // If there is no page template use the default page template
1820 if (empty($template)) {
1821 $template = Core\Theme::getPathForFile("default.php");
1824 // Theme templates expect $a as an App instance
1827 // Used as is in view/php/default.php
1828 $lang = Core\L10n::getCurrentLang();
1830 /// @TODO Looks unsafe (remote-inclusion), is maybe not but Core\Theme::getPathForFile() uses file_exists() but does not escape anything
1831 require_once $template;
1835 * Redirects to another module relative to the current Friendica base.
1836 * If you want to redirect to a external URL, use System::externalRedirectTo()
1838 * @param string $toUrl The destination URL (Default is empty, which is the default page of the Friendica node)
1839 * @param bool $ssl if true, base URL will try to get called with https:// (works just for relative paths)
1841 * @throws InternalServerErrorException In Case the given URL is not relative to the Friendica node
1843 public function internalRedirect($toUrl = '', $ssl = false)
1845 if (filter_var($toUrl, FILTER_VALIDATE_URL)) {
1846 throw new InternalServerErrorException("'$toUrl is not a relative path, please use System::externalRedirectTo");
1849 $redirectTo = $this->getBaseURL($ssl) . '/' . ltrim($toUrl, '/');
1850 Core\System::externalRedirect($redirectTo);
1854 * Automatically redirects to relative or absolute URL
1855 * Should only be used if it isn't clear if the URL is either internal or external
1857 * @param string $toUrl The target URL
1860 public function redirect($toUrl)
1862 if (filter_var($toUrl, FILTER_VALIDATE_URL)) {
1863 Core\System::externalRedirect($toUrl);
1865 $this->internalRedirect($toUrl);