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.config.php
334 private function loadConfigFiles()
336 $this->loadConfigFile($this->getBasePath() . '/config/defaults.config.php');
337 $this->loadConfigFile($this->getBasePath() . '/config/settings.config.php');
339 // Legacy .htconfig.php support
340 if (file_exists($this->getBasePath() . '/.htpreconfig.php')) {
342 include $this->getBasePath() . '/.htpreconfig.php';
345 // Legacy .htconfig.php support
346 if (file_exists($this->getBasePath() . '/.htconfig.php')) {
349 include $this->getBasePath() . '/.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() . '/config/local.config.php')) {
378 $this->loadConfigFile($this->getBasePath() . '/config/local.config.php', true);
379 } elseif (file_exists($this->getBasePath() . '/config/local.ini.php')) {
380 $this->loadINIConfigFile($this->getBasePath() . '/config/local.ini.php', true);
385 * Tries to load the specified legacy configuration file into the App->config array.
386 * Doesn't overwrite previously set values by default to prevent default config files to supersede DB Config.
388 * @deprecated since version 2018.12
389 * @param string $filepath
390 * @param bool $overwrite Force value overwrite if the config key already exists
393 public function loadINIConfigFile($filepath, $overwrite = false)
395 if (!file_exists($filepath)) {
396 throw new Exception('Error parsing non-existent INI config file ' . $filepath);
399 $contents = include($filepath);
401 $config = parse_ini_string($contents, true, INI_SCANNER_TYPED);
403 if ($config === false) {
404 throw new Exception('Error parsing INI config file ' . $filepath);
407 $this->loadConfigArray($config, $overwrite);
411 * Tries to load the specified configuration file into the App->config array.
412 * Doesn't overwrite previously set values by default to prevent default config files to supersede DB Config.
414 * The config format is PHP array and the template for configuration files is the following:
422 * @param string $filepath
423 * @param bool $overwrite Force value overwrite if the config key already exists
426 public function loadConfigFile($filepath, $overwrite = false)
428 if (!file_exists($filepath)) {
429 throw new Exception('Error loading non-existent config file ' . $filepath);
432 $config = include($filepath);
434 if (!is_array($config)) {
435 throw new Exception('Error loading config file ' . $filepath);
438 $this->loadConfigArray($config, $overwrite);
442 * Loads addons configuration files
444 * First loads all activated addons default configuration through the load_config hook, then load the local.config.php
445 * again to overwrite potential local addon configuration.
447 private function loadAddonConfig()
449 // Loads addons default config
450 Core\Hook::callAll('load_config');
452 // Load the local addon config file to overwritten default addon config values
453 if (file_exists($this->getBasePath() . '/config/addon.config.php')) {
454 $this->loadConfigFile($this->getBasePath() . '/config/addon.config.php', true);
455 } elseif (file_exists($this->getBasePath() . '/config/addon.ini.php')) {
456 $this->loadINIConfigFile($this->getBasePath() . '/config/addon.ini.php', true);
461 * Tries to load the specified configuration array into the App->config array.
462 * Doesn't overwrite previously set values by default to prevent default config files to supersede DB Config.
464 * @param array $config
465 * @param bool $overwrite Force value overwrite if the config key already exists
467 private function loadConfigArray(array $config, $overwrite = false)
469 foreach ($config as $category => $values) {
470 foreach ($values as $key => $value) {
472 $this->setConfigValue($category, $key, $value);
474 $this->setDefaultConfigValue($category, $key, $value);
481 * Loads the default timezone
483 * Include support for legacy $default_timezone
485 * @global string $default_timezone
487 private function loadDefaultTimezone()
489 if ($this->getConfigValue('system', 'default_timezone')) {
490 $this->timezone = $this->getConfigValue('system', 'default_timezone');
492 global $default_timezone;
493 $this->timezone = !empty($default_timezone) ? $default_timezone : 'UTC';
496 if ($this->timezone) {
497 date_default_timezone_set($this->timezone);
502 * Figure out if we are running at the top of a domain or in a sub-directory and adjust accordingly
504 private function determineURLPath()
506 /* Relative script path to the web server root
507 * Not all of those $_SERVER properties can be present, so we do by inverse priority order
509 $relative_script_path = '';
510 $relative_script_path = defaults($_SERVER, 'REDIRECT_URL' , $relative_script_path);
511 $relative_script_path = defaults($_SERVER, 'REDIRECT_URI' , $relative_script_path);
512 $relative_script_path = defaults($_SERVER, 'REDIRECT_SCRIPT_URL', $relative_script_path);
513 $relative_script_path = defaults($_SERVER, 'SCRIPT_URL' , $relative_script_path);
514 $relative_script_path = defaults($_SERVER, 'REQUEST_URI' , $relative_script_path);
516 $this->urlPath = $this->getConfigValue('system', 'urlpath');
518 /* $relative_script_path gives /relative/path/to/friendica/module/parameter
519 * QUERY_STRING gives pagename=module/parameter
521 * To get /relative/path/to/friendica we perform dirname() for as many levels as there are slashes in the QUERY_STRING
523 if (!empty($relative_script_path)) {
525 if (!empty($_SERVER['QUERY_STRING'])) {
526 $path = trim(dirname($relative_script_path, substr_count(trim($_SERVER['QUERY_STRING'], '/'), '/') + 1), '/');
529 $path = trim($relative_script_path, '/');
532 if ($path && $path != $this->urlPath) {
533 $this->urlPath = $path;
538 public function loadDatabase()
540 if (DBA::connected()) {
544 $db_host = $this->getConfigValue('database', 'hostname');
545 $db_user = $this->getConfigValue('database', 'username');
546 $db_pass = $this->getConfigValue('database', 'password');
547 $db_data = $this->getConfigValue('database', 'database');
548 $charset = $this->getConfigValue('database', 'charset');
550 // Use environment variables for mysql if they are set beforehand
551 if (!empty(getenv('MYSQL_HOST'))
552 && (!empty(getenv('MYSQL_USERNAME')) || !empty(getenv('MYSQL_USER')))
553 && getenv('MYSQL_PASSWORD') !== false
554 && !empty(getenv('MYSQL_DATABASE')))
556 $db_host = getenv('MYSQL_HOST');
557 if (!empty(getenv('MYSQL_PORT'))) {
558 $db_host .= ':' . getenv('MYSQL_PORT');
560 if (!empty(getenv('MYSQL_USERNAME'))) {
561 $db_user = getenv('MYSQL_USERNAME');
563 $db_user = getenv('MYSQL_USER');
565 $db_pass = (string) getenv('MYSQL_PASSWORD');
566 $db_data = getenv('MYSQL_DATABASE');
569 $stamp1 = microtime(true);
571 if (DBA::connect($db_host, $db_user, $db_pass, $db_data, $charset)) {
572 // Loads DB_UPDATE_VERSION constant
573 Database\DBStructure::definition(false);
576 unset($db_host, $db_user, $db_pass, $db_data, $charset);
578 $this->saveTimestamp($stamp1, 'network');
582 * @brief Returns the base filesystem path of the App
584 * It first checks for the internal variable, then for DOCUMENT_ROOT and
589 public function getBasePath()
591 $basepath = $this->basePath;
594 $basepath = Core\Config::get('system', 'basepath');
597 if (!$basepath && !empty($_SERVER['DOCUMENT_ROOT'])) {
598 $basepath = $_SERVER['DOCUMENT_ROOT'];
601 if (!$basepath && !empty($_SERVER['PWD'])) {
602 $basepath = $_SERVER['PWD'];
605 return self::getRealPath($basepath);
609 * @brief Returns a normalized file path
611 * This is a wrapper for the "realpath" function.
612 * That function cannot detect the real path when some folders aren't readable.
613 * Since this could happen with some hosters we need to handle this.
615 * @param string $path The path that is about to be normalized
616 * @return string normalized path - when possible
618 public static function getRealPath($path)
620 $normalized = realpath($path);
622 if (!is_bool($normalized)) {
629 public function getScheme()
631 return $this->scheme;
635 * @brief Retrieves the Friendica instance base URL
637 * This function assembles the base URL from multiple parts:
638 * - Protocol is determined either by the request or a combination of
639 * system.ssl_policy and the $ssl parameter.
640 * - Host name is determined either by system.hostname or inferred from request
641 * - Path is inferred from SCRIPT_NAME
643 * Note: $ssl parameter value doesn't directly correlate with the resulting protocol
645 * @param bool $ssl Whether to append http or https under SSL_POLICY_SELFSIGN
646 * @return string Friendica server base URL
648 public function getBaseURL($ssl = false)
650 $scheme = $this->scheme;
652 if (Core\Config::get('system', 'ssl_policy') == SSL_POLICY_FULL) {
656 // Basically, we have $ssl = true on any links which can only be seen by a logged in user
657 // (and also the login link). Anything seen by an outsider will have it turned off.
659 if (Core\Config::get('system', 'ssl_policy') == SSL_POLICY_SELFSIGN) {
667 if (Core\Config::get('config', 'hostname') != '') {
668 $this->hostname = Core\Config::get('config', 'hostname');
671 return $scheme . '://' . $this->hostname . (!empty($this->getURLPath()) ? '/' . $this->getURLPath() : '' );
675 * @brief Initializes the baseurl components
677 * Clears the baseurl cache to prevent inconsistencies
681 public function setBaseURL($url)
683 $parsed = @parse_url($url);
686 if (!empty($parsed)) {
687 if (!empty($parsed['scheme'])) {
688 $this->scheme = $parsed['scheme'];
691 if (!empty($parsed['host'])) {
692 $hostname = $parsed['host'];
695 if (!empty($parsed['port'])) {
696 $hostname .= ':' . $parsed['port'];
698 if (!empty($parsed['path'])) {
699 $this->urlPath = trim($parsed['path'], '\\/');
702 if (file_exists($this->getBasePath() . '/.htpreconfig.php')) {
703 include $this->getBasePath() . '/.htpreconfig.php';
706 if (Core\Config::get('config', 'hostname') != '') {
707 $this->hostname = Core\Config::get('config', 'hostname');
710 if (!isset($this->hostname) || ($this->hostname == '')) {
711 $this->hostname = $hostname;
716 public function getHostName()
718 if (Core\Config::get('config', 'hostname') != '') {
719 $this->hostname = Core\Config::get('config', 'hostname');
722 return $this->hostname;
725 public function getURLPath()
727 return $this->urlPath;
731 * Initializes App->page['htmlhead'].
736 * - Registered stylesheets (through App->registerStylesheet())
737 * - Infinite scroll data
738 * - head.tpl template
740 public function initHead()
742 $interval = ((local_user()) ? Core\PConfig::get(local_user(), 'system', 'update_interval') : 40000);
744 // If the update is 'deactivated' set it to the highest integer number (~24 days)
746 $interval = 2147483647;
749 if ($interval < 10000) {
753 // compose the page title from the sitename and the
754 // current module called
755 if (!$this->module == '') {
756 $this->page['title'] = $this->config['sitename'] . ' (' . $this->module . ')';
758 $this->page['title'] = $this->config['sitename'];
761 if (!empty(Core\Renderer::$theme['stylesheet'])) {
762 $stylesheet = Core\Renderer::$theme['stylesheet'];
764 $stylesheet = $this->getCurrentThemeStylesheetPath();
767 $this->registerStylesheet($stylesheet);
769 $shortcut_icon = Core\Config::get('system', 'shortcut_icon');
770 if ($shortcut_icon == '') {
771 $shortcut_icon = 'images/friendica-32.png';
774 $touch_icon = Core\Config::get('system', 'touch_icon');
775 if ($touch_icon == '') {
776 $touch_icon = 'images/friendica-128.png';
779 Core\Addon::callHooks('head', $this->page['htmlhead']);
781 $tpl = Core\Renderer::getMarkupTemplate('head.tpl');
782 /* put the head template at the beginning of page['htmlhead']
783 * since the code added by the modules frequently depends on it
786 $this->page['htmlhead'] = Core\Renderer::replaceMacros($tpl, [
787 '$baseurl' => $this->getBaseURL(),
788 '$local_user' => local_user(),
789 '$generator' => 'Friendica' . ' ' . FRIENDICA_VERSION,
790 '$delitem' => Core\L10n::t('Delete this item?'),
791 '$showmore' => Core\L10n::t('show more'),
792 '$showfewer' => Core\L10n::t('show fewer'),
793 '$update_interval' => $interval,
794 '$shortcut_icon' => $shortcut_icon,
795 '$touch_icon' => $touch_icon,
796 '$block_public' => intval(Core\Config::get('system', 'block_public')),
797 '$stylesheets' => $this->stylesheets,
798 ]) . $this->page['htmlhead'];
802 * Initializes App->page['footer'].
805 * - Javascript homebase
806 * - Mobile toggle link
807 * - Registered footer scripts (through App->registerFooterScript())
808 * - footer.tpl template
810 public function initFooter()
812 // If you're just visiting, let javascript take you home
813 if (!empty($_SESSION['visitor_home'])) {
814 $homebase = $_SESSION['visitor_home'];
815 } elseif (local_user()) {
816 $homebase = 'profile/' . $this->user['nickname'];
819 if (isset($homebase)) {
820 $this->page['footer'] .= '<script>var homebase="' . $homebase . '";</script>' . "\n";
824 * Add a "toggle mobile" link if we're using a mobile device
826 if ($this->is_mobile || $this->is_tablet) {
827 if (isset($_SESSION['show-mobile']) && !$_SESSION['show-mobile']) {
828 $link = 'toggle_mobile?address=' . urlencode(curPageURL());
830 $link = 'toggle_mobile?off=1&address=' . urlencode(curPageURL());
832 $this->page['footer'] .= Core\Renderer::replaceMacros(Core\Renderer::getMarkupTemplate("toggle_mobile_footer.tpl"), [
833 '$toggle_link' => $link,
834 '$toggle_text' => Core\L10n::t('toggle mobile')
838 Core\Addon::callHooks('footer', $this->page['footer']);
840 $tpl = Core\Renderer::getMarkupTemplate('footer.tpl');
841 $this->page['footer'] = Core\Renderer::replaceMacros($tpl, [
842 '$baseurl' => $this->getBaseURL(),
843 '$footerScripts' => $this->footerScripts,
844 ]) . $this->page['footer'];
848 * @brief Removes the base url from an url. This avoids some mixed content problems.
850 * @param string $origURL
852 * @return string The cleaned url
854 public function removeBaseURL($origURL)
856 // Remove the hostname from the url if it is an internal link
857 $nurl = Util\Strings::normaliseLink($origURL);
858 $base = Util\Strings::normaliseLink($this->getBaseURL());
859 $url = str_replace($base . '/', '', $nurl);
861 // if it is an external link return the orignal value
862 if ($url == Util\Strings::normaliseLink($origURL)) {
870 * Saves a timestamp for a value - f.e. a call
871 * Necessary for profiling Friendica
873 * @param int $timestamp the Timestamp
874 * @param string $value A value to profile
876 public function saveTimestamp($timestamp, $value)
878 if (!isset($this->config['system']['profiler']) || !$this->config['system']['profiler']) {
882 $duration = (float) (microtime(true) - $timestamp);
884 if (!isset($this->performance[$value])) {
885 // Prevent ugly E_NOTICE
886 $this->performance[$value] = 0;
889 $this->performance[$value] += (float) $duration;
890 $this->performance['marktime'] += (float) $duration;
892 $callstack = Core\System::callstack();
894 if (!isset($this->callstack[$value][$callstack])) {
895 // Prevent ugly E_NOTICE
896 $this->callstack[$value][$callstack] = 0;
899 $this->callstack[$value][$callstack] += (float) $duration;
903 * Returns the current UserAgent as a String
905 * @return string the UserAgent as a String
907 public function getUserAgent()
910 FRIENDICA_PLATFORM . " '" .
911 FRIENDICA_CODENAME . "' " .
912 FRIENDICA_VERSION . '-' .
913 DB_UPDATE_VERSION . '; ' .
918 * Checks, if the call is from the Friendica App
921 * The friendica client has problems with the GUID in the notify. this is some workaround
923 private function checkFriendicaApp()
926 $this->isFriendicaApp = isset($_SERVER['HTTP_USER_AGENT']) && $_SERVER['HTTP_USER_AGENT'] == 'Apache-HttpClient/UNAVAILABLE (java 1.4)';
930 * Is the call via the Friendica app? (not a "normale" call)
932 * @return bool true if it's from the Friendica app
934 public function isFriendicaApp()
936 return $this->isFriendicaApp;
940 * @brief Checks if the site is called via a backend process
942 * This isn't a perfect solution. But we need this check very early.
943 * So we cannot wait until the modules are loaded.
945 * @param string $backend true, if the backend flag was set during App initialization
948 private function checkBackend($backend) {
971 // Check if current module is in backend or backend flag is set
972 $this->isBackend = (in_array($this->module, $backends) || $backend || $this->isBackend);
976 * Returns true, if the call is from a backend node (f.e. from a worker)
978 * @return bool Is it a known backend?
980 public function isBackend()
982 return $this->isBackend;
986 * @brief Checks if the maximum number of database processes is reached
988 * @return bool Is the limit reached?
990 public function isMaxProcessesReached()
992 // Deactivated, needs more investigating if this check really makes sense
996 * Commented out to suppress static analyzer issues
998 if ($this->is_backend()) {
999 $process = 'backend';
1000 $max_processes = Core\Config::get('system', 'max_processes_backend');
1001 if (intval($max_processes) == 0) {
1005 $process = 'frontend';
1006 $max_processes = Core\Config::get('system', 'max_processes_frontend');
1007 if (intval($max_processes) == 0) {
1008 $max_processes = 20;
1012 $processlist = DBA::processlist();
1013 if ($processlist['list'] != '') {
1014 Core\Logger::log('Processcheck: Processes: ' . $processlist['amount'] . ' - Processlist: ' . $processlist['list'], Core\Logger::DEBUG);
1016 if ($processlist['amount'] > $max_processes) {
1017 Core\Logger::log('Processcheck: Maximum number of processes for ' . $process . ' tasks (' . $max_processes . ') reached.', Core\Logger::DEBUG);
1026 * @brief Checks if the minimal memory is reached
1028 * @return bool Is the memory limit reached?
1030 public function isMinMemoryReached()
1032 $min_memory = Core\Config::get('system', 'min_memory', 0);
1033 if ($min_memory == 0) {
1037 if (!is_readable('/proc/meminfo')) {
1041 $memdata = explode("\n", file_get_contents('/proc/meminfo'));
1044 foreach ($memdata as $line) {
1045 $data = explode(':', $line);
1046 if (count($data) != 2) {
1049 list($key, $val) = $data;
1050 $meminfo[$key] = (int) trim(str_replace('kB', '', $val));
1051 $meminfo[$key] = (int) ($meminfo[$key] / 1024);
1054 if (!isset($meminfo['MemFree'])) {
1058 $free = $meminfo['MemFree'];
1060 $reached = ($free < $min_memory);
1063 Core\Logger::log('Minimal memory reached: ' . $free . '/' . $meminfo['MemTotal'] . ' - limit ' . $min_memory, Core\Logger::DEBUG);
1070 * @brief Checks if the maximum load is reached
1072 * @return bool Is the load reached?
1074 public function isMaxLoadReached()
1076 if ($this->isBackend()) {
1077 $process = 'backend';
1078 $maxsysload = intval(Core\Config::get('system', 'maxloadavg'));
1079 if ($maxsysload < 1) {
1083 $process = 'frontend';
1084 $maxsysload = intval(Core\Config::get('system', 'maxloadavg_frontend'));
1085 if ($maxsysload < 1) {
1090 $load = Core\System::currentLoad();
1092 if (intval($load) > $maxsysload) {
1093 Core\Logger::log('system: load ' . $load . ' for ' . $process . ' tasks (' . $maxsysload . ') too high.');
1101 * Executes a child process with 'proc_open'
1103 * @param string $command The command to execute
1104 * @param array $args Arguments to pass to the command ( [ 'key' => value, 'key2' => value2, ... ]
1106 public function proc_run($command, $args)
1108 if (!function_exists('proc_open')) {
1112 $cmdline = $this->getConfigValue('config', 'php_path', 'php') . ' ' . escapeshellarg($command);
1114 foreach ($args as $key => $value) {
1115 if (!is_null($value) && is_bool($value) && !$value) {
1119 $cmdline .= ' --' . $key;
1120 if (!is_null($value) && !is_bool($value)) {
1121 $cmdline .= ' ' . $value;
1125 if ($this->isMinMemoryReached()) {
1129 if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
1130 $resource = proc_open('cmd /c start /b ' . $cmdline, [], $foo, $this->getBasePath());
1132 $resource = proc_open($cmdline . ' &', [], $foo, $this->getBasePath());
1134 if (!is_resource($resource)) {
1135 Core\Logger::log('We got no resource for command ' . $cmdline, Core\Logger::DEBUG);
1138 proc_close($resource);
1142 * @brief Returns the system user that is executing the script
1144 * This mostly returns something like "www-data".
1146 * @return string system username
1148 private static function getSystemUser()
1150 if (!function_exists('posix_getpwuid') || !function_exists('posix_geteuid')) {
1154 $processUser = posix_getpwuid(posix_geteuid());
1155 return $processUser['name'];
1159 * @brief Checks if a given directory is usable for the system
1161 * @return boolean the directory is usable
1163 public static function isDirectoryUsable($directory, $check_writable = true)
1165 if ($directory == '') {
1166 Core\Logger::log('Directory is empty. This shouldn\'t happen.', Core\Logger::DEBUG);
1170 if (!file_exists($directory)) {
1171 Core\Logger::log('Path "' . $directory . '" does not exist for user ' . self::getSystemUser(), Core\Logger::DEBUG);
1175 if (is_file($directory)) {
1176 Core\Logger::log('Path "' . $directory . '" is a file for user ' . self::getSystemUser(), Core\Logger::DEBUG);
1180 if (!is_dir($directory)) {
1181 Core\Logger::log('Path "' . $directory . '" is not a directory for user ' . self::getSystemUser(), Core\Logger::DEBUG);
1185 if ($check_writable && !is_writable($directory)) {
1186 Core\Logger::log('Path "' . $directory . '" is not writable for user ' . self::getSystemUser(), Core\Logger::DEBUG);
1194 * @param string $cat Config category
1195 * @param string $k Config key
1196 * @param mixed $default Default value if it isn't set
1198 * @return string Returns the value of the Config entry
1200 public function getConfigValue($cat, $k, $default = null)
1204 if ($cat === 'config') {
1205 if (isset($this->config[$k])) {
1206 $return = $this->config[$k];
1209 if (isset($this->config[$cat][$k])) {
1210 $return = $this->config[$cat][$k];
1218 * Sets a default value in the config cache. Ignores already existing keys.
1220 * @param string $cat Config category
1221 * @param string $k Config key
1222 * @param mixed $v Default value to set
1224 private function setDefaultConfigValue($cat, $k, $v)
1226 if (!isset($this->config[$cat][$k])) {
1227 $this->setConfigValue($cat, $k, $v);
1232 * Sets a value in the config cache. Accepts raw output from the config table
1234 * @param string $cat Config category
1235 * @param string $k Config key
1236 * @param mixed $v Value to set
1238 public function setConfigValue($cat, $k, $v)
1240 // Only arrays are serialized in database, so we have to unserialize sparingly
1241 $value = is_string($v) && preg_match("|^a:[0-9]+:{.*}$|s", $v) ? unserialize($v) : $v;
1243 if ($cat === 'config') {
1244 $this->config[$k] = $value;
1246 if (!isset($this->config[$cat])) {
1247 $this->config[$cat] = [];
1250 $this->config[$cat][$k] = $value;
1255 * Deletes a value from the config cache
1257 * @param string $cat Config category
1258 * @param string $k Config key
1260 public function deleteConfigValue($cat, $k)
1262 if ($cat === 'config') {
1263 if (isset($this->config[$k])) {
1264 unset($this->config[$k]);
1267 if (isset($this->config[$cat][$k])) {
1268 unset($this->config[$cat][$k]);
1275 * Retrieves a value from the user config cache
1277 * @param int $uid User Id
1278 * @param string $cat Config category
1279 * @param string $k Config key
1280 * @param mixed $default Default value if key isn't set
1282 * @return string The value of the config entry
1284 public function getPConfigValue($uid, $cat, $k, $default = null)
1288 if (isset($this->config[$uid][$cat][$k])) {
1289 $return = $this->config[$uid][$cat][$k];
1296 * Sets a value in the user config cache
1298 * Accepts raw output from the pconfig table
1300 * @param int $uid User Id
1301 * @param string $cat Config category
1302 * @param string $k Config key
1303 * @param mixed $v Value to set
1305 public function setPConfigValue($uid, $cat, $k, $v)
1307 // Only arrays are serialized in database, so we have to unserialize sparingly
1308 $value = is_string($v) && preg_match("|^a:[0-9]+:{.*}$|s", $v) ? unserialize($v) : $v;
1310 if (!isset($this->config[$uid]) || !is_array($this->config[$uid])) {
1311 $this->config[$uid] = [];
1314 if (!isset($this->config[$uid][$cat]) || !is_array($this->config[$uid][$cat])) {
1315 $this->config[$uid][$cat] = [];
1318 $this->config[$uid][$cat][$k] = $value;
1322 * Deletes a value from the user config cache
1324 * @param int $uid User Id
1325 * @param string $cat Config category
1326 * @param string $k Config key
1328 public function deletePConfigValue($uid, $cat, $k)
1330 if (isset($this->config[$uid][$cat][$k])) {
1331 unset($this->config[$uid][$cat][$k]);
1336 * Generates the site's default sender email address
1340 public function getSenderEmailAddress()
1342 $sender_email = Core\Config::get('config', 'sender_email');
1343 if (empty($sender_email)) {
1344 $hostname = $this->getHostName();
1345 if (strpos($hostname, ':')) {
1346 $hostname = substr($hostname, 0, strpos($hostname, ':'));
1349 $sender_email = 'noreply@' . $hostname;
1352 return $sender_email;
1356 * Returns the current theme name.
1358 * @return string the name of the current theme
1360 public function getCurrentTheme()
1362 if ($this->getMode()->isInstall()) {
1366 //// @TODO Compute the current theme only once (this behavior has
1367 /// already been implemented, but it didn't work well -
1368 /// https://github.com/friendica/friendica/issues/5092)
1369 $this->computeCurrentTheme();
1371 return $this->currentTheme;
1375 * Computes the current theme name based on the node settings, the user settings and the device type
1379 private function computeCurrentTheme()
1381 $system_theme = Core\Config::get('system', 'theme');
1382 if (!$system_theme) {
1383 throw new Exception(Core\L10n::t('No system theme config value set.'));
1387 $this->currentTheme = $system_theme;
1389 $allowed_themes = explode(',', Core\Config::get('system', 'allowed_themes', $system_theme));
1392 // Find the theme that belongs to the user whose stuff we are looking at
1393 if ($this->profile_uid && ($this->profile_uid != local_user())) {
1394 // Allow folks to override user themes and always use their own on their own site.
1395 // This works only if the user is on the same server
1396 $user = DBA::selectFirst('user', ['theme'], ['uid' => $this->profile_uid]);
1397 if (DBA::isResult($user) && !Core\PConfig::get(local_user(), 'system', 'always_my_theme')) {
1398 $page_theme = $user['theme'];
1402 $user_theme = Core\Session::get('theme', $system_theme);
1404 // Specific mobile theme override
1405 if (($this->is_mobile || $this->is_tablet) && Core\Session::get('show-mobile', true)) {
1406 $system_mobile_theme = Core\Config::get('system', 'mobile-theme');
1407 $user_mobile_theme = Core\Session::get('mobile-theme', $system_mobile_theme);
1409 // --- means same mobile theme as desktop
1410 if (!empty($user_mobile_theme) && $user_mobile_theme !== '---') {
1411 $user_theme = $user_mobile_theme;
1416 $theme_name = $page_theme;
1418 $theme_name = $user_theme;
1422 && in_array($theme_name, $allowed_themes)
1423 && (file_exists('view/theme/' . $theme_name . '/style.css')
1424 || file_exists('view/theme/' . $theme_name . '/style.php'))
1426 $this->currentTheme = $theme_name;
1431 * @brief Return full URL to theme which is currently in effect.
1433 * Provide a sane default if nothing is chosen or the specified theme does not exist.
1437 public function getCurrentThemeStylesheetPath()
1439 return Core\Theme::getStylesheetPath($this->getCurrentTheme());
1443 * Check if request was an AJAX (xmlhttprequest) request.
1445 * @return boolean true if it was an AJAX request
1447 public function isAjax()
1449 return $this->isAjax;
1453 * Returns the value of a argv key
1454 * TODO there are a lot of $a->argv usages in combination with defaults() which can be replaced with this method
1456 * @param int $position the position of the argument
1457 * @param mixed $default the default value if not found
1459 * @return mixed returns the value of the argument
1461 public function getArgumentValue($position, $default = '')
1463 if (array_key_exists($position, $this->argv)) {
1464 return $this->argv[$position];
1471 * Sets the base url for use in cmdline programs which don't have
1472 * $_SERVER variables
1474 public function checkURL()
1476 $url = Core\Config::get('system', 'url');
1478 // if the url isn't set or the stored url is radically different
1479 // than the currently visited url, store the current value accordingly.
1480 // "Radically different" ignores common variations such as http vs https
1481 // and www.example.com vs example.com.
1482 // We will only change the url to an ip address if there is no existing setting
1484 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()))) {
1485 Core\Config::set('system', 'url', $this->getBaseURL());
1490 * Frontend App script
1492 * The App object behaves like a container and a dispatcher at the same time, including a representation of the
1493 * request and a representation of the response.
1495 * This probably should change to limit the size of this monster method.
1497 public function runFrontend()
1499 // Missing DB connection: ERROR
1500 if ($this->getMode()->has(App\Mode::LOCALCONFIGPRESENT) && !$this->getMode()->has(App\Mode::DBAVAILABLE)) {
1501 Core\System::httpExit(500, ['title' => 'Error 500 - Internal Server Error', 'description' => 'Apologies but the website is unavailable at the moment.']);
1504 // Max Load Average reached: ERROR
1505 if ($this->isMaxProcessesReached() || $this->isMaxLoadReached()) {
1506 header('Retry-After: 120');
1507 header('Refresh: 120; url=' . $this->getBaseURL() . "/" . $this->query_string);
1509 Core\System::httpExit(503, ['title' => 'Error 503 - Service Temporarily Unavailable', 'description' => 'Core\System is currently overloaded. Please try again later.']);
1512 if (strstr($this->query_string, '.well-known/host-meta') && ($this->query_string != '.well-known/host-meta')) {
1513 Core\System::httpExit(404);
1516 if (!$this->getMode()->isInstall()) {
1517 // Force SSL redirection
1518 if (Core\Config::get('system', 'force_ssl') && ($this->getScheme() == "http")
1519 && intval(Core\Config::get('system', 'ssl_policy')) == SSL_POLICY_FULL
1520 && strpos($this->getBaseURL(), 'https://') === 0
1521 && $_SERVER['REQUEST_METHOD'] == 'GET') {
1522 header('HTTP/1.1 302 Moved Temporarily');
1523 header('Location: ' . $this->getBaseURL() . '/' . $this->query_string);
1527 Core\Session::init();
1528 Core\Addon::callHooks('init_1');
1531 // Exclude the backend processes from the session management
1532 if (!$this->isBackend()) {
1533 $stamp1 = microtime(true);
1535 $this->saveTimestamp($stamp1, 'parser');
1536 Core\L10n::setSessionVariable();
1537 Core\L10n::setLangFromSession();
1540 Core\Worker::executeIfIdle();
1544 if (!empty($_GET['zrl']) && $this->getMode()->isNormal()) {
1545 $this->query_string = Model\Profile::stripZrls($this->query_string);
1546 if (!local_user()) {
1547 // Only continue when the given profile link seems valid
1548 // Valid profile links contain a path with "/profile/" and no query parameters
1549 if ((parse_url($_GET['zrl'], PHP_URL_QUERY) == "") &&
1550 strstr(parse_url($_GET['zrl'], PHP_URL_PATH), "/profile/")) {
1551 if (defaults($_SESSION, "visitor_home", "") != $_GET["zrl"]) {
1552 $_SESSION['my_url'] = $_GET['zrl'];
1553 $_SESSION['authenticated'] = 0;
1555 Model\Profile::zrlInit($this);
1557 // Someone came with an invalid parameter, maybe as a DDoS attempt
1558 // We simply stop processing here
1559 Core\Logger::log("Invalid ZRL parameter " . $_GET['zrl'], Core\Logger::DEBUG);
1560 Core\System::httpExit(403, ['title' => '403 Forbidden']);
1565 if (!empty($_GET['owt']) && $this->getMode()->isNormal()) {
1566 $token = $_GET['owt'];
1567 $this->query_string = Model\Profile::stripQueryParam($this->query_string, 'owt');
1568 Model\Profile::openWebAuthInit($token);
1571 Module\Login::sessionAuth();
1573 if (empty($_SESSION['authenticated'])) {
1574 header('X-Account-Management-Status: none');
1577 $_SESSION['sysmsg'] = defaults($_SESSION, 'sysmsg' , []);
1578 $_SESSION['sysmsg_info'] = defaults($_SESSION, 'sysmsg_info' , []);
1579 $_SESSION['last_updated'] = defaults($_SESSION, 'last_updated', []);
1582 * check_config() is responsible for running update scripts. These automatically
1583 * update the DB schema whenever we push a new one out. It also checks to see if
1584 * any addons have been added or removed and reacts accordingly.
1587 // in install mode, any url loads install module
1588 // but we need "view" module for stylesheet
1589 if ($this->getMode()->isInstall() && $this->module != 'view') {
1590 $this->module = 'install';
1591 } elseif (!$this->getMode()->has(App\Mode::MAINTENANCEDISABLED) && $this->module != 'view') {
1592 $this->module = 'maintenance';
1595 Core\Update::check(false);
1596 Core\Addon::loadAddons();
1597 Core\Hook::loadHooks();
1608 'right_aside' => '',
1613 if (strlen($this->module)) {
1614 // Compatibility with the Android Diaspora client
1615 if ($this->module == 'stream') {
1616 $this->internalRedirect('network?f=&order=post');
1619 if ($this->module == 'conversations') {
1620 $this->internalRedirect('message');
1623 if ($this->module == 'commented') {
1624 $this->internalRedirect('network?f=&order=comment');
1627 if ($this->module == 'liked') {
1628 $this->internalRedirect('network?f=&order=comment');
1631 if ($this->module == 'activity') {
1632 $this->internalRedirect('network/?f=&conv=1');
1635 if (($this->module == 'status_messages') && ($this->cmd == 'status_messages/new')) {
1636 $this->internalRedirect('bookmarklet');
1639 if (($this->module == 'user') && ($this->cmd == 'user/edit')) {
1640 $this->internalRedirect('settings');
1643 if (($this->module == 'tag_followings') && ($this->cmd == 'tag_followings/manage')) {
1644 $this->internalRedirect('search');
1647 // Compatibility with the Firefox App
1648 if (($this->module == "users") && ($this->cmd == "users/sign_in")) {
1649 $this->module = "login";
1652 $privateapps = Core\Config::get('config', 'private_addons', false);
1653 if (Core\Addon::isEnabled($this->module) && file_exists("addon/{$this->module}/{$this->module}.php")) {
1654 //Check if module is an app and if public access to apps is allowed or not
1655 if ((!local_user()) && Core\Hook::isAddonApp($this->module) && $privateapps) {
1656 info(Core\L10n::t("You must be logged in to use addons. "));
1658 include_once "addon/{$this->module}/{$this->module}.php";
1659 if (function_exists($this->module . '_module')) {
1660 LegacyModule::setModuleFile("addon/{$this->module}/{$this->module}.php");
1661 $this->module_class = 'Friendica\\LegacyModule';
1662 $this->module_loaded = true;
1667 // Controller class routing
1668 if (! $this->module_loaded && class_exists('Friendica\\Module\\' . ucfirst($this->module))) {
1669 $this->module_class = 'Friendica\\Module\\' . ucfirst($this->module);
1670 $this->module_loaded = true;
1673 /* If not, next look for a 'standard' program module in the 'mod' directory
1674 * We emulate a Module class through the LegacyModule class
1676 if (! $this->module_loaded && file_exists("mod/{$this->module}.php")) {
1677 LegacyModule::setModuleFile("mod/{$this->module}.php");
1678 $this->module_class = 'Friendica\\LegacyModule';
1679 $this->module_loaded = true;
1682 /* The URL provided does not resolve to a valid module.
1684 * On Dreamhost sites, quite often things go wrong for no apparent reason and they send us to '/internal_error.html'.
1685 * We don't like doing this, but as it occasionally accounts for 10-20% or more of all site traffic -
1686 * 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
1687 * this will often succeed and eventually do the right thing.
1689 * Otherwise we are going to emit a 404 not found.
1691 if (! $this->module_loaded) {
1692 // Stupid browser tried to pre-fetch our Javascript img template. Don't log the event or return anything - just quietly exit.
1693 if (!empty($_SERVER['QUERY_STRING']) && preg_match('/{[0-9]}/', $_SERVER['QUERY_STRING']) !== 0) {
1697 if (!empty($_SERVER['QUERY_STRING']) && ($_SERVER['QUERY_STRING'] === 'q=internal_error.html') && isset($dreamhost_error_hack)) {
1698 Core\Logger::log('index.php: dreamhost_error_hack invoked. Original URI =' . $_SERVER['REQUEST_URI']);
1699 $this->internalRedirect($_SERVER['REQUEST_URI']);
1702 Core\Logger::log('index.php: page not found: ' . $_SERVER['REQUEST_URI'] . ' ADDRESS: ' . $_SERVER['REMOTE_ADDR'] . ' QUERY: ' . $_SERVER['QUERY_STRING'], Core\Logger::DEBUG);
1704 header($_SERVER["SERVER_PROTOCOL"] . ' 404 ' . Core\L10n::t('Not Found'));
1705 $tpl = Core\Renderer::getMarkupTemplate("404.tpl");
1706 $this->page['content'] = Core\Renderer::replaceMacros($tpl, [
1707 '$message' => Core\L10n::t('Page not found.')
1712 // Load current theme info
1713 $theme_info_file = 'view/theme/' . $this->getCurrentTheme() . '/theme.php';
1714 if (file_exists($theme_info_file)) {
1715 require_once $theme_info_file;
1718 // initialise content region
1719 if ($this->getMode()->isNormal()) {
1720 Core\Addon::callHooks('page_content_top', $this->page['content']);
1723 // Call module functions
1724 if ($this->module_loaded) {
1725 $this->page['page_title'] = $this->module;
1728 Core\Addon::callHooks($this->module . '_mod_init', $placeholder);
1730 call_user_func([$this->module_class, 'init']);
1732 // "rawContent" is especially meant for technical endpoints.
1733 // This endpoint doesn't need any theme initialization or other comparable stuff.
1734 if (!$this->error) {
1735 call_user_func([$this->module_class, 'rawContent']);
1738 if (function_exists(str_replace('-', '_', $this->getCurrentTheme()) . '_init')) {
1739 $func = str_replace('-', '_', $this->getCurrentTheme()) . '_init';
1743 if (! $this->error && $_SERVER['REQUEST_METHOD'] === 'POST') {
1744 Core\Addon::callHooks($this->module . '_mod_post', $_POST);
1745 call_user_func([$this->module_class, 'post']);
1748 if (! $this->error) {
1749 Core\Addon::callHooks($this->module . '_mod_afterpost', $placeholder);
1750 call_user_func([$this->module_class, 'afterpost']);
1753 if (! $this->error) {
1754 $arr = ['content' => $this->page['content']];
1755 Core\Addon::callHooks($this->module . '_mod_content', $arr);
1756 $this->page['content'] = $arr['content'];
1757 $arr = ['content' => call_user_func([$this->module_class, 'content'])];
1758 Core\Addon::callHooks($this->module . '_mod_aftercontent', $arr);
1759 $this->page['content'] .= $arr['content'];
1762 if (function_exists(str_replace('-', '_', $this->getCurrentTheme()) . '_content_loaded')) {
1763 $func = str_replace('-', '_', $this->getCurrentTheme()) . '_content_loaded';
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 (filter_var($toUrl, FILTER_VALIDATE_URL)) {
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 (filter_var($toUrl, FILTER_VALIDATE_URL)) {
1901 Core\System::externalRedirect($toUrl);
1903 $this->internalRedirect($toUrl);