7 use Detection\MobileDetect;
11 use Friendica\Database\DBA;
12 use Friendica\Network\HTTPException;
13 use Friendica\Network\HTTPException\InternalServerErrorException;
19 * @brief Our main application structure for the life of this page.
21 * Primarily deals with the URL that got us here
22 * and tries to make some sense of it, and
23 * stores our page contents and config storage
24 * and anything else that might need to be passed around
25 * before we spit the page out.
30 public $module_loaded = false;
31 public $module_class = null;
32 public $query_string = '';
44 public $error = false;
50 public $interactive = true;
52 public $is_mobile = false;
53 public $is_tablet = false;
54 public $performance = [];
55 public $callstack = [];
56 public $theme_info = [];
58 // Allow themes to control internal parameters
59 // by changing App values in theme.php
61 public $sourcename = '';
62 public $videowidth = 425;
63 public $videoheight = 350;
64 public $force_max_items = 0;
65 public $theme_events_in_profile = true;
67 public $stylesheets = [];
68 public $footerScripts = [];
71 * @var App\Mode The Mode of the Application
76 * @var string The App base path
81 * @var string The App URL path
86 * @var bool true, if the call is from the Friendica APP, otherwise false
88 private $isFriendicaApp;
91 * @var bool true, if the call is from an backend node (f.e. worker)
96 * @var string The name of the current theme
98 private $currentTheme;
101 * @var bool check if request was an AJAX (xmlhttprequest) request
108 public $mobileDetect;
111 * Register a stylesheet file path to be included in the <head> tag of every page.
112 * Inclusion is done in App->initHead().
113 * The path can be absolute or relative to the Friendica installation base folder.
117 * @param string $path
119 public function registerStylesheet($path)
121 $url = str_replace($this->getBasePath() . DIRECTORY_SEPARATOR, '', $path);
123 $this->stylesheets[] = trim($url, '/');
127 * Register a javascript file path to be included in the <footer> tag of every page.
128 * Inclusion is done in App->initFooter().
129 * The path can be absolute or relative to the Friendica installation base folder.
133 * @param string $path
135 public function registerFooterScript($path)
137 $url = str_replace($this->getBasePath() . DIRECTORY_SEPARATOR, '', $path);
139 $this->footerScripts[] = trim($url, '/');
148 * @brief App constructor.
150 * @param string $basePath Path to the app base folder
151 * @param bool $isBackend Whether it is used for backend or frontend (Default true=backend)
153 * @throws Exception if the Basepath is not usable
155 public function __construct($basePath, $isBackend = true)
157 if (!static::isDirectoryUsable($basePath, false)) {
158 throw new Exception('Basepath ' . $basePath . ' isn\'t usable.');
161 BaseObject::setApp($this);
163 $this->basePath = rtrim($basePath, DIRECTORY_SEPARATOR);
164 $this->checkBackend($isBackend);
165 $this->checkFriendicaApp();
167 $this->performance['start'] = microtime(true);
168 $this->performance['database'] = 0;
169 $this->performance['database_write'] = 0;
170 $this->performance['cache'] = 0;
171 $this->performance['cache_write'] = 0;
172 $this->performance['network'] = 0;
173 $this->performance['file'] = 0;
174 $this->performance['rendering'] = 0;
175 $this->performance['parser'] = 0;
176 $this->performance['marktime'] = 0;
177 $this->performance['markstart'] = microtime(true);
179 $this->callstack['database'] = [];
180 $this->callstack['database_write'] = [];
181 $this->callstack['cache'] = [];
182 $this->callstack['cache_write'] = [];
183 $this->callstack['network'] = [];
184 $this->callstack['file'] = [];
185 $this->callstack['rendering'] = [];
186 $this->callstack['parser'] = [];
188 $this->mode = new App\Mode($basePath);
194 // This has to be quite large to deal with embedded private photos
195 ini_set('pcre.backtrack_limit', 500000);
197 $this->scheme = 'http';
199 if (!empty($_SERVER['HTTPS']) ||
200 !empty($_SERVER['HTTP_FORWARDED']) && preg_match('/proto=https/', $_SERVER['HTTP_FORWARDED']) ||
201 !empty($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https' ||
202 !empty($_SERVER['HTTP_X_FORWARDED_SSL']) && $_SERVER['HTTP_X_FORWARDED_SSL'] == 'on' ||
203 !empty($_SERVER['FRONT_END_HTTPS']) && $_SERVER['FRONT_END_HTTPS'] == 'on' ||
204 !empty($_SERVER['SERVER_PORT']) && (intval($_SERVER['SERVER_PORT']) == 443) // XXX: reasonable assumption, but isn't this hardcoding too much?
206 $this->scheme = 'https';
209 if (!empty($_SERVER['SERVER_NAME'])) {
210 $this->hostname = $_SERVER['SERVER_NAME'];
212 if (!empty($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] != 80 && $_SERVER['SERVER_PORT'] != 443) {
213 $this->hostname .= ':' . $_SERVER['SERVER_PORT'];
218 get_include_path() . PATH_SEPARATOR
219 . $this->getBasePath() . DIRECTORY_SEPARATOR . 'include' . PATH_SEPARATOR
220 . $this->getBasePath() . DIRECTORY_SEPARATOR . 'library' . PATH_SEPARATOR
221 . $this->getBasePath());
223 if (!empty($_SERVER['QUERY_STRING']) && strpos($_SERVER['QUERY_STRING'], 'pagename=') === 0) {
224 $this->query_string = substr($_SERVER['QUERY_STRING'], 9);
225 } elseif (!empty($_SERVER['QUERY_STRING']) && strpos($_SERVER['QUERY_STRING'], 'q=') === 0) {
226 $this->query_string = substr($_SERVER['QUERY_STRING'], 2);
229 // removing trailing / - maybe a nginx problem
230 $this->query_string = ltrim($this->query_string, '/');
232 if (!empty($_GET['pagename'])) {
233 $this->cmd = trim($_GET['pagename'], '/\\');
234 } elseif (!empty($_GET['q'])) {
235 $this->cmd = trim($_GET['q'], '/\\');
239 $this->query_string = str_replace($this->cmd . '&', $this->cmd . '?', $this->query_string);
241 // unix style "homedir"
242 if (substr($this->cmd, 0, 1) === '~') {
243 $this->cmd = 'profile/' . substr($this->cmd, 1);
246 // Diaspora style profile url
247 if (substr($this->cmd, 0, 2) === 'u/') {
248 $this->cmd = 'profile/' . substr($this->cmd, 2);
252 * Break the URL path into C style argc/argv style arguments for our
253 * modules. Given "http://example.com/module/arg1/arg2", $this->argc
254 * will be 3 (integer) and $this->argv will contain:
260 * There will always be one argument. If provided a naked domain
261 * URL, $this->argv[0] is set to "home".
264 $this->argv = explode('/', $this->cmd);
265 $this->argc = count($this->argv);
266 if ((array_key_exists('0', $this->argv)) && strlen($this->argv[0])) {
267 $this->module = str_replace('.', '_', $this->argv[0]);
268 $this->module = str_replace('-', '_', $this->module);
271 $this->argv = ['home'];
272 $this->module = 'home';
275 // Detect mobile devices
276 $mobile_detect = new MobileDetect();
278 $this->mobileDetect = $mobile_detect;
280 $this->is_mobile = $mobile_detect->isMobile();
281 $this->is_tablet = $mobile_detect->isTablet();
283 $this->isAjax = strtolower(defaults($_SERVER, 'HTTP_X_REQUESTED_WITH', '')) == 'xmlhttprequest';
285 // Register template engines
286 Core\Renderer::registerTemplateEngine('Friendica\Render\FriendicaSmartyEngine');
290 * Returns the Mode of the Application
292 * @return App\Mode The Application Mode
294 * @throws InternalServerErrorException when the mode isn't created
296 public function getMode()
298 if (empty($this->mode)) {
299 throw new InternalServerErrorException('Mode of the Application is not defined');
306 * Reloads the whole app instance
308 public function reload()
310 // The order of the following calls is important to ensure proper initialization
311 $this->loadConfigFiles();
313 $this->loadDatabase();
315 $this->getMode()->determine($this->getBasePath());
317 $this->determineURLPath();
321 if ($this->getMode()->has(App\Mode::DBAVAILABLE)) {
322 Core\Hook::loadHooks();
324 $this->loadAddonConfig();
327 $this->loadDefaultTimezone();
331 $this->process_id = Core\System::processID('log');
335 * Load the configuration files
337 * First loads the default value for all the configuration keys, then the legacy configuration files, then the
338 * expected local.config.php
340 private function loadConfigFiles()
342 $this->loadConfigFile($this->getBasePath() . '/config/defaults.config.php');
343 $this->loadConfigFile($this->getBasePath() . '/config/settings.config.php');
345 // Legacy .htconfig.php support
346 if (file_exists($this->getBasePath() . '/.htpreconfig.php')) {
348 include $this->getBasePath() . '/.htpreconfig.php';
351 // Legacy .htconfig.php support
352 if (file_exists($this->getBasePath() . '/.htconfig.php')) {
355 include $this->getBasePath() . '/.htconfig.php';
357 $this->setConfigValue('database', 'hostname', $db_host);
358 $this->setConfigValue('database', 'username', $db_user);
359 $this->setConfigValue('database', 'password', $db_pass);
360 $this->setConfigValue('database', 'database', $db_data);
361 if (isset($a->config['system']['db_charset'])) {
362 $this->setConfigValue('database', 'charset', $a->config['system']['db_charset']);
365 unset($db_host, $db_user, $db_pass, $db_data);
367 if (isset($default_timezone)) {
368 $this->setConfigValue('system', 'default_timezone', $default_timezone);
369 unset($default_timezone);
372 if (isset($pidfile)) {
373 $this->setConfigValue('system', 'pidfile', $pidfile);
378 $this->setConfigValue('system', 'language', $lang);
383 if (file_exists($this->getBasePath() . '/config/local.config.php')) {
384 $this->loadConfigFile($this->getBasePath() . '/config/local.config.php', true);
385 } elseif (file_exists($this->getBasePath() . '/config/local.ini.php')) {
386 $this->loadINIConfigFile($this->getBasePath() . '/config/local.ini.php', true);
391 * Tries to load the specified legacy configuration file into the App->config array.
392 * Doesn't overwrite previously set values by default to prevent default config files to supersede DB Config.
394 * @deprecated since version 2018.12
395 * @param string $filepath
396 * @param bool $overwrite Force value overwrite if the config key already exists
399 public function loadINIConfigFile($filepath, $overwrite = false)
401 if (!file_exists($filepath)) {
402 throw new Exception('Error parsing non-existent INI config file ' . $filepath);
405 $contents = include($filepath);
407 $config = parse_ini_string($contents, true, INI_SCANNER_TYPED);
409 if ($config === false) {
410 throw new Exception('Error parsing INI config file ' . $filepath);
413 $this->loadConfigArray($config, $overwrite);
417 * Tries to load the specified configuration file into the App->config array.
418 * Doesn't overwrite previously set values by default to prevent default config files to supersede DB Config.
420 * The config format is PHP array and the template for configuration files is the following:
428 * @param string $filepath
429 * @param bool $overwrite Force value overwrite if the config key already exists
432 public function loadConfigFile($filepath, $overwrite = false)
434 if (!file_exists($filepath)) {
435 throw new Exception('Error loading non-existent config file ' . $filepath);
438 $config = include($filepath);
440 if (!is_array($config)) {
441 throw new Exception('Error loading config file ' . $filepath);
444 $this->loadConfigArray($config, $overwrite);
448 * Loads addons configuration files
450 * First loads all activated addons default configuration through the load_config hook, then load the local.config.php
451 * again to overwrite potential local addon configuration.
453 private function loadAddonConfig()
455 // Loads addons default config
456 Core\Hook::callAll('load_config');
458 // Load the local addon config file to overwritten default addon config values
459 if (file_exists($this->getBasePath() . '/config/addon.config.php')) {
460 $this->loadConfigFile($this->getBasePath() . '/config/addon.config.php', true);
461 } elseif (file_exists($this->getBasePath() . '/config/addon.ini.php')) {
462 $this->loadINIConfigFile($this->getBasePath() . '/config/addon.ini.php', true);
467 * Tries to load the specified configuration array into the App->config array.
468 * Doesn't overwrite previously set values by default to prevent default config files to supersede DB Config.
470 * @param array $config
471 * @param bool $overwrite Force value overwrite if the config key already exists
473 private function loadConfigArray(array $config, $overwrite = false)
475 foreach ($config as $category => $values) {
476 foreach ($values as $key => $value) {
478 $this->setConfigValue($category, $key, $value);
480 $this->setDefaultConfigValue($category, $key, $value);
487 * Loads the default timezone
489 * Include support for legacy $default_timezone
491 * @global string $default_timezone
493 private function loadDefaultTimezone()
495 if ($this->getConfigValue('system', 'default_timezone')) {
496 $this->timezone = $this->getConfigValue('system', 'default_timezone');
498 global $default_timezone;
499 $this->timezone = !empty($default_timezone) ? $default_timezone : 'UTC';
502 if ($this->timezone) {
503 date_default_timezone_set($this->timezone);
508 * Figure out if we are running at the top of a domain or in a sub-directory and adjust accordingly
510 private function determineURLPath()
512 /* Relative script path to the web server root
513 * Not all of those $_SERVER properties can be present, so we do by inverse priority order
515 $relative_script_path = '';
516 $relative_script_path = defaults($_SERVER, 'REDIRECT_URL' , $relative_script_path);
517 $relative_script_path = defaults($_SERVER, 'REDIRECT_URI' , $relative_script_path);
518 $relative_script_path = defaults($_SERVER, 'REDIRECT_SCRIPT_URL', $relative_script_path);
519 $relative_script_path = defaults($_SERVER, 'SCRIPT_URL' , $relative_script_path);
520 $relative_script_path = defaults($_SERVER, 'REQUEST_URI' , $relative_script_path);
522 $this->urlPath = $this->getConfigValue('system', 'urlpath');
524 /* $relative_script_path gives /relative/path/to/friendica/module/parameter
525 * QUERY_STRING gives pagename=module/parameter
527 * To get /relative/path/to/friendica we perform dirname() for as many levels as there are slashes in the QUERY_STRING
529 if (!empty($relative_script_path)) {
531 if (!empty($_SERVER['QUERY_STRING'])) {
532 $path = trim(rdirname($relative_script_path, substr_count(trim($_SERVER['QUERY_STRING'], '/'), '/') + 1), '/');
535 $path = trim($relative_script_path, '/');
538 if ($path && $path != $this->urlPath) {
539 $this->urlPath = $path;
544 public function loadDatabase()
546 if (DBA::connected()) {
550 $db_host = $this->getConfigValue('database', 'hostname');
551 $db_user = $this->getConfigValue('database', 'username');
552 $db_pass = $this->getConfigValue('database', 'password');
553 $db_data = $this->getConfigValue('database', 'database');
554 $charset = $this->getConfigValue('database', 'charset');
556 // Use environment variables for mysql if they are set beforehand
557 if (!empty(getenv('MYSQL_HOST'))
558 && !empty(getenv('MYSQL_USERNAME') || !empty(getenv('MYSQL_USER')))
559 && getenv('MYSQL_PASSWORD') !== false
560 && !empty(getenv('MYSQL_DATABASE')))
562 $db_host = getenv('MYSQL_HOST');
563 if (!empty(getenv('MYSQL_PORT'))) {
564 $db_host .= ':' . getenv('MYSQL_PORT');
566 if (!empty(getenv('MYSQL_USERNAME'))) {
567 $db_user = getenv('MYSQL_USERNAME');
569 $db_user = getenv('MYSQL_USER');
571 $db_pass = (string) getenv('MYSQL_PASSWORD');
572 $db_data = getenv('MYSQL_DATABASE');
575 $stamp1 = microtime(true);
577 if (DBA::connect($db_host, $db_user, $db_pass, $db_data, $charset)) {
578 // Loads DB_UPDATE_VERSION constant
579 Database\DBStructure::definition(false);
582 unset($db_host, $db_user, $db_pass, $db_data, $charset);
584 $this->saveTimestamp($stamp1, 'network');
588 * @brief Returns the base filesystem path of the App
590 * It first checks for the internal variable, then for DOCUMENT_ROOT and
595 public function getBasePath()
597 $basepath = $this->basePath;
600 $basepath = Core\Config::get('system', 'basepath');
603 if (!$basepath && !empty($_SERVER['DOCUMENT_ROOT'])) {
604 $basepath = $_SERVER['DOCUMENT_ROOT'];
607 if (!$basepath && !empty($_SERVER['PWD'])) {
608 $basepath = $_SERVER['PWD'];
611 return self::getRealPath($basepath);
615 * @brief Returns a normalized file path
617 * This is a wrapper for the "realpath" function.
618 * That function cannot detect the real path when some folders aren't readable.
619 * Since this could happen with some hosters we need to handle this.
621 * @param string $path The path that is about to be normalized
622 * @return string normalized path - when possible
624 public static function getRealPath($path)
626 $normalized = realpath($path);
628 if (!is_bool($normalized)) {
635 public function getScheme()
637 return $this->scheme;
641 * @brief Retrieves the Friendica instance base URL
643 * This function assembles the base URL from multiple parts:
644 * - Protocol is determined either by the request or a combination of
645 * system.ssl_policy and the $ssl parameter.
646 * - Host name is determined either by system.hostname or inferred from request
647 * - Path is inferred from SCRIPT_NAME
649 * Note: $ssl parameter value doesn't directly correlate with the resulting protocol
651 * @param bool $ssl Whether to append http or https under SSL_POLICY_SELFSIGN
652 * @return string Friendica server base URL
654 public function getBaseURL($ssl = false)
656 $scheme = $this->scheme;
658 if (Core\Config::get('system', 'ssl_policy') == SSL_POLICY_FULL) {
662 // Basically, we have $ssl = true on any links which can only be seen by a logged in user
663 // (and also the login link). Anything seen by an outsider will have it turned off.
665 if (Core\Config::get('system', 'ssl_policy') == SSL_POLICY_SELFSIGN) {
673 if (Core\Config::get('config', 'hostname') != '') {
674 $this->hostname = Core\Config::get('config', 'hostname');
677 return $scheme . '://' . $this->hostname . !empty($this->getURLPath() ? '/' . $this->getURLPath() : '' );
681 * @brief Initializes the baseurl components
683 * Clears the baseurl cache to prevent inconsistencies
687 public function setBaseURL($url)
689 $parsed = @parse_url($url);
692 if (!empty($parsed)) {
693 if (!empty($parsed['scheme'])) {
694 $this->scheme = $parsed['scheme'];
697 if (!empty($parsed['host'])) {
698 $hostname = $parsed['host'];
701 if (!empty($parsed['port'])) {
702 $hostname .= ':' . $parsed['port'];
704 if (!empty($parsed['path'])) {
705 $this->urlPath = trim($parsed['path'], '\\/');
708 if (file_exists($this->getBasePath() . '/.htpreconfig.php')) {
709 include $this->getBasePath() . '/.htpreconfig.php';
712 if (Core\Config::get('config', 'hostname') != '') {
713 $this->hostname = Core\Config::get('config', 'hostname');
716 if (!isset($this->hostname) || ($this->hostname == '')) {
717 $this->hostname = $hostname;
722 public function getHostName()
724 if (Core\Config::get('config', 'hostname') != '') {
725 $this->hostname = Core\Config::get('config', 'hostname');
728 return $this->hostname;
731 public function getURLPath()
733 return $this->urlPath;
737 * Initializes App->page['htmlhead'].
742 * - Registered stylesheets (through App->registerStylesheet())
743 * - Infinite scroll data
744 * - head.tpl template
746 public function initHead()
748 $interval = ((local_user()) ? Core\PConfig::get(local_user(), 'system', 'update_interval') : 40000);
750 // If the update is 'deactivated' set it to the highest integer number (~24 days)
752 $interval = 2147483647;
755 if ($interval < 10000) {
759 // compose the page title from the sitename and the
760 // current module called
761 if (!$this->module == '') {
762 $this->page['title'] = $this->config['sitename'] . ' (' . $this->module . ')';
764 $this->page['title'] = $this->config['sitename'];
767 if (!empty(Core\Renderer::$theme['stylesheet'])) {
768 $stylesheet = Core\Renderer::$theme['stylesheet'];
770 $stylesheet = $this->getCurrentThemeStylesheetPath();
773 $this->registerStylesheet($stylesheet);
775 $shortcut_icon = Core\Config::get('system', 'shortcut_icon');
776 if ($shortcut_icon == '') {
777 $shortcut_icon = 'images/friendica-32.png';
780 $touch_icon = Core\Config::get('system', 'touch_icon');
781 if ($touch_icon == '') {
782 $touch_icon = 'images/friendica-128.png';
785 Core\Addon::callHooks('head', $this->page['htmlhead']);
787 $tpl = Core\Renderer::getMarkupTemplate('head.tpl');
788 /* put the head template at the beginning of page['htmlhead']
789 * since the code added by the modules frequently depends on it
792 $this->page['htmlhead'] = Core\Renderer::replaceMacros($tpl, [
793 '$baseurl' => $this->getBaseURL(),
794 '$local_user' => local_user(),
795 '$generator' => 'Friendica' . ' ' . FRIENDICA_VERSION,
796 '$delitem' => Core\L10n::t('Delete this item?'),
797 '$showmore' => Core\L10n::t('show more'),
798 '$showfewer' => Core\L10n::t('show fewer'),
799 '$update_interval' => $interval,
800 '$shortcut_icon' => $shortcut_icon,
801 '$touch_icon' => $touch_icon,
802 '$block_public' => intval(Core\Config::get('system', 'block_public')),
803 '$stylesheets' => $this->stylesheets,
804 ]) . $this->page['htmlhead'];
808 * Initializes App->page['footer'].
811 * - Javascript homebase
812 * - Mobile toggle link
813 * - Registered footer scripts (through App->registerFooterScript())
814 * - footer.tpl template
816 public function initFooter()
818 // If you're just visiting, let javascript take you home
819 if (!empty($_SESSION['visitor_home'])) {
820 $homebase = $_SESSION['visitor_home'];
821 } elseif (local_user()) {
822 $homebase = 'profile/' . $this->user['nickname'];
825 if (isset($homebase)) {
826 $this->page['footer'] .= '<script>var homebase="' . $homebase . '";</script>' . "\n";
830 * Add a "toggle mobile" link if we're using a mobile device
832 if ($this->is_mobile || $this->is_tablet) {
833 if (isset($_SESSION['show-mobile']) && !$_SESSION['show-mobile']) {
834 $link = 'toggle_mobile?address=' . urlencode(curPageURL());
836 $link = 'toggle_mobile?off=1&address=' . urlencode(curPageURL());
838 $this->page['footer'] .= Core\Renderer::replaceMacros(Core\Renderer::getMarkupTemplate("toggle_mobile_footer.tpl"), [
839 '$toggle_link' => $link,
840 '$toggle_text' => Core\L10n::t('toggle mobile')
844 Core\Addon::callHooks('footer', $this->page['footer']);
846 $tpl = Core\Renderer::getMarkupTemplate('footer.tpl');
847 $this->page['footer'] = Core\Renderer::replaceMacros($tpl, [
848 '$baseurl' => $this->getBaseURL(),
849 '$footerScripts' => $this->footerScripts,
850 ]) . $this->page['footer'];
854 * @brief Removes the base url from an url. This avoids some mixed content problems.
856 * @param string $origURL
858 * @return string The cleaned url
860 public function removeBaseURL($origURL)
862 // Remove the hostname from the url if it is an internal link
863 $nurl = Util\Strings::normaliseLink($origURL);
864 $base = Util\Strings::normaliseLink($this->getBaseURL());
865 $url = str_replace($base . '/', '', $nurl);
867 // if it is an external link return the orignal value
868 if ($url == Util\Strings::normaliseLink($origURL)) {
876 * Saves a timestamp for a value - f.e. a call
877 * Necessary for profiling Friendica
879 * @param int $timestamp the Timestamp
880 * @param string $value A value to profile
882 public function saveTimestamp($timestamp, $value)
884 if (!isset($this->config['system']['profiler']) || !$this->config['system']['profiler']) {
888 $duration = (float) (microtime(true) - $timestamp);
890 if (!isset($this->performance[$value])) {
891 // Prevent ugly E_NOTICE
892 $this->performance[$value] = 0;
895 $this->performance[$value] += (float) $duration;
896 $this->performance['marktime'] += (float) $duration;
898 $callstack = Core\System::callstack();
900 if (!isset($this->callstack[$value][$callstack])) {
901 // Prevent ugly E_NOTICE
902 $this->callstack[$value][$callstack] = 0;
905 $this->callstack[$value][$callstack] += (float) $duration;
909 * Returns the current UserAgent as a String
911 * @return string the UserAgent as a String
913 public function getUserAgent()
916 FRIENDICA_PLATFORM . " '" .
917 FRIENDICA_CODENAME . "' " .
918 FRIENDICA_VERSION . '-' .
919 DB_UPDATE_VERSION . '; ' .
924 * Checks, if the call is from the Friendica App
927 * The friendica client has problems with the GUID in the notify. this is some workaround
929 private function checkFriendicaApp()
932 $this->isFriendicaApp = isset($_SERVER['HTTP_USER_AGENT']) && $_SERVER['HTTP_USER_AGENT'] == 'Apache-HttpClient/UNAVAILABLE (java 1.4)';
936 * Is the call via the Friendica app? (not a "normale" call)
938 * @return bool true if it's from the Friendica app
940 public function isFriendicaApp()
942 return $this->isFriendicaApp;
946 * @brief Checks if the site is called via a backend process
948 * This isn't a perfect solution. But we need this check very early.
949 * So we cannot wait until the modules are loaded.
951 * @param string $backend true, if the backend flag was set during App initialization
954 private function checkBackend($backend) {
977 // Check if current module is in backend or backend flag is set
978 $this->isBackend = (in_array($this->module, $backends) || $backend || $this->isBackend);
982 * Returns true, if the call is from a backend node (f.e. from a worker)
984 * @return bool Is it a known backend?
986 public function isBackend()
988 return $this->isBackend;
992 * @brief Checks if the maximum number of database processes is reached
994 * @return bool Is the limit reached?
996 public function isMaxProcessesReached()
998 // Deactivated, needs more investigating if this check really makes sense
1002 * Commented out to suppress static analyzer issues
1004 if ($this->is_backend()) {
1005 $process = 'backend';
1006 $max_processes = Core\Config::get('system', 'max_processes_backend');
1007 if (intval($max_processes) == 0) {
1011 $process = 'frontend';
1012 $max_processes = Core\Config::get('system', 'max_processes_frontend');
1013 if (intval($max_processes) == 0) {
1014 $max_processes = 20;
1018 $processlist = DBA::processlist();
1019 if ($processlist['list'] != '') {
1020 Core\Logger::log('Processcheck: Processes: ' . $processlist['amount'] . ' - Processlist: ' . $processlist['list'], Core\Logger::DEBUG);
1022 if ($processlist['amount'] > $max_processes) {
1023 Core\Logger::log('Processcheck: Maximum number of processes for ' . $process . ' tasks (' . $max_processes . ') reached.', Core\Logger::DEBUG);
1032 * @brief Checks if the minimal memory is reached
1034 * @return bool Is the memory limit reached?
1036 public function isMinMemoryReached()
1038 $min_memory = Core\Config::get('system', 'min_memory', 0);
1039 if ($min_memory == 0) {
1043 if (!is_readable('/proc/meminfo')) {
1047 $memdata = explode("\n", file_get_contents('/proc/meminfo'));
1050 foreach ($memdata as $line) {
1051 $data = explode(':', $line);
1052 if (count($data) != 2) {
1055 list($key, $val) = $data;
1056 $meminfo[$key] = (int) trim(str_replace('kB', '', $val));
1057 $meminfo[$key] = (int) ($meminfo[$key] / 1024);
1060 if (!isset($meminfo['MemFree'])) {
1064 $free = $meminfo['MemFree'];
1066 $reached = ($free < $min_memory);
1069 Core\Logger::log('Minimal memory reached: ' . $free . '/' . $meminfo['MemTotal'] . ' - limit ' . $min_memory, Core\Logger::DEBUG);
1076 * @brief Checks if the maximum load is reached
1078 * @return bool Is the load reached?
1080 public function isMaxLoadReached()
1082 if ($this->isBackend()) {
1083 $process = 'backend';
1084 $maxsysload = intval(Core\Config::get('system', 'maxloadavg'));
1085 if ($maxsysload < 1) {
1089 $process = 'frontend';
1090 $maxsysload = intval(Core\Config::get('system', 'maxloadavg_frontend'));
1091 if ($maxsysload < 1) {
1096 $load = Core\System::currentLoad();
1098 if (intval($load) > $maxsysload) {
1099 Core\Logger::log('system: load ' . $load . ' for ' . $process . ' tasks (' . $maxsysload . ') too high.');
1107 * Executes a child process with 'proc_open'
1109 * @param string $command The command to execute
1110 * @param array $args Arguments to pass to the command ( [ 'key' => value, 'key2' => value2, ... ]
1112 public function proc_run($command, $args)
1114 if (!function_exists('proc_open')) {
1118 $cmdline = $this->getConfigValue('config', 'php_path', 'php') . ' ' . escapeshellarg($command);
1120 foreach ($args as $key => $value) {
1121 if (!is_null($value) && is_bool($value) && !$value) {
1125 $cmdline .= ' --' . $key;
1126 if (!is_null($value) && !is_bool($value)) {
1127 $cmdline .= ' ' . $value;
1131 if ($this->isMinMemoryReached()) {
1135 if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
1136 $resource = proc_open('cmd /c start /b ' . $cmdline, [], $foo, $this->getBasePath());
1138 $resource = proc_open($cmdline . ' &', [], $foo, $this->getBasePath());
1140 if (!is_resource($resource)) {
1141 Core\Logger::log('We got no resource for command ' . $cmdline, Core\Logger::DEBUG);
1144 proc_close($resource);
1148 * @brief Returns the system user that is executing the script
1150 * This mostly returns something like "www-data".
1152 * @return string system username
1154 private static function getSystemUser()
1156 if (!function_exists('posix_getpwuid') || !function_exists('posix_geteuid')) {
1160 $processUser = posix_getpwuid(posix_geteuid());
1161 return $processUser['name'];
1165 * @brief Checks if a given directory is usable for the system
1167 * @return boolean the directory is usable
1169 public static function isDirectoryUsable($directory, $check_writable = true)
1171 if ($directory == '') {
1172 Core\Logger::log('Directory is empty. This shouldn\'t happen.', Core\Logger::DEBUG);
1176 if (!file_exists($directory)) {
1177 Core\Logger::log('Path "' . $directory . '" does not exist for user ' . self::getSystemUser(), Core\Logger::DEBUG);
1181 if (is_file($directory)) {
1182 Core\Logger::log('Path "' . $directory . '" is a file for user ' . self::getSystemUser(), Core\Logger::DEBUG);
1186 if (!is_dir($directory)) {
1187 Core\Logger::log('Path "' . $directory . '" is not a directory for user ' . self::getSystemUser(), Core\Logger::DEBUG);
1191 if ($check_writable && !is_writable($directory)) {
1192 Core\Logger::log('Path "' . $directory . '" is not writable for user ' . self::getSystemUser(), Core\Logger::DEBUG);
1200 * @param string $cat Config category
1201 * @param string $k Config key
1202 * @param mixed $default Default value if it isn't set
1204 * @return string Returns the value of the Config entry
1206 public function getConfigValue($cat, $k, $default = null)
1210 if ($cat === 'config') {
1211 if (isset($this->config[$k])) {
1212 $return = $this->config[$k];
1215 if (isset($this->config[$cat][$k])) {
1216 $return = $this->config[$cat][$k];
1224 * Sets a default value in the config cache. Ignores already existing keys.
1226 * @param string $cat Config category
1227 * @param string $k Config key
1228 * @param mixed $v Default value to set
1230 private function setDefaultConfigValue($cat, $k, $v)
1232 if (!isset($this->config[$cat][$k])) {
1233 $this->setConfigValue($cat, $k, $v);
1238 * Sets a value in the config cache. Accepts raw output from the config table
1240 * @param string $cat Config category
1241 * @param string $k Config key
1242 * @param mixed $v Value to set
1244 public function setConfigValue($cat, $k, $v)
1246 // Only arrays are serialized in database, so we have to unserialize sparingly
1247 $value = is_string($v) && preg_match("|^a:[0-9]+:{.*}$|s", $v) ? unserialize($v) : $v;
1249 if ($cat === 'config') {
1250 $this->config[$k] = $value;
1252 if (!isset($this->config[$cat])) {
1253 $this->config[$cat] = [];
1256 $this->config[$cat][$k] = $value;
1261 * Deletes a value from the config cache
1263 * @param string $cat Config category
1264 * @param string $k Config key
1266 public function deleteConfigValue($cat, $k)
1268 if ($cat === 'config') {
1269 if (isset($this->config[$k])) {
1270 unset($this->config[$k]);
1273 if (isset($this->config[$cat][$k])) {
1274 unset($this->config[$cat][$k]);
1281 * Retrieves a value from the user config cache
1283 * @param int $uid User Id
1284 * @param string $cat Config category
1285 * @param string $k Config key
1286 * @param mixed $default Default value if key isn't set
1288 * @return string The value of the config entry
1290 public function getPConfigValue($uid, $cat, $k, $default = null)
1294 if (isset($this->config[$uid][$cat][$k])) {
1295 $return = $this->config[$uid][$cat][$k];
1302 * Sets a value in the user config cache
1304 * Accepts raw output from the pconfig table
1306 * @param int $uid User Id
1307 * @param string $cat Config category
1308 * @param string $k Config key
1309 * @param mixed $v Value to set
1311 public function setPConfigValue($uid, $cat, $k, $v)
1313 // Only arrays are serialized in database, so we have to unserialize sparingly
1314 $value = is_string($v) && preg_match("|^a:[0-9]+:{.*}$|s", $v) ? unserialize($v) : $v;
1316 if (!isset($this->config[$uid]) || !is_array($this->config[$uid])) {
1317 $this->config[$uid] = [];
1320 if (!isset($this->config[$uid][$cat]) || !is_array($this->config[$uid][$cat])) {
1321 $this->config[$uid][$cat] = [];
1324 $this->config[$uid][$cat][$k] = $value;
1328 * Deletes a value from the user config cache
1330 * @param int $uid User Id
1331 * @param string $cat Config category
1332 * @param string $k Config key
1334 public function deletePConfigValue($uid, $cat, $k)
1336 if (isset($this->config[$uid][$cat][$k])) {
1337 unset($this->config[$uid][$cat][$k]);
1342 * Generates the site's default sender email address
1346 public function getSenderEmailAddress()
1348 $sender_email = Core\Config::get('config', 'sender_email');
1349 if (empty($sender_email)) {
1350 $hostname = $this->getHostName();
1351 if (strpos($hostname, ':')) {
1352 $hostname = substr($hostname, 0, strpos($hostname, ':'));
1355 $sender_email = 'noreply@' . $hostname;
1358 return $sender_email;
1362 * Returns the current theme name.
1364 * @return string the name of the current theme
1366 public function getCurrentTheme()
1368 if ($this->getMode()->isInstall()) {
1372 if (!$this->currentTheme) {
1373 $this->computeCurrentTheme();
1376 return $this->currentTheme;
1379 public function setCurrentTheme($theme)
1381 $this->currentTheme = $theme;
1385 * Computes the current theme name based on the node settings, the user settings and the device type
1389 private function computeCurrentTheme()
1391 $system_theme = Core\Config::get('system', 'theme');
1392 if (!$system_theme) {
1393 throw new Exception(Core\L10n::t('No system theme config value set.'));
1397 $this->currentTheme = $system_theme;
1399 $allowed_themes = explode(',', Core\Config::get('system', 'allowed_themes', $system_theme));
1402 // Find the theme that belongs to the user whose stuff we are looking at
1403 if ($this->profile_uid && ($this->profile_uid != local_user())) {
1404 // Allow folks to override user themes and always use their own on their own site.
1405 // This works only if the user is on the same server
1406 $user = DBA::selectFirst('user', ['theme'], ['uid' => $this->profile_uid]);
1407 if (DBA::isResult($user) && !Core\PConfig::get(local_user(), 'system', 'always_my_theme')) {
1408 $page_theme = $user['theme'];
1412 $user_theme = Core\Session::get('theme', $system_theme);
1414 // Specific mobile theme override
1415 if (($this->is_mobile || $this->is_tablet) && Core\Session::get('show-mobile', true)) {
1416 $system_mobile_theme = Core\Config::get('system', 'mobile-theme');
1417 $user_mobile_theme = Core\Session::get('mobile-theme', $system_mobile_theme);
1419 // --- means same mobile theme as desktop
1420 if (!empty($user_mobile_theme) && $user_mobile_theme !== '---') {
1421 $user_theme = $user_mobile_theme;
1426 $theme_name = $page_theme;
1428 $theme_name = $user_theme;
1432 && in_array($theme_name, $allowed_themes)
1433 && (file_exists('view/theme/' . $theme_name . '/style.css')
1434 || file_exists('view/theme/' . $theme_name . '/style.php'))
1436 $this->currentTheme = $theme_name;
1441 * @brief Return full URL to theme which is currently in effect.
1443 * Provide a sane default if nothing is chosen or the specified theme does not exist.
1447 public function getCurrentThemeStylesheetPath()
1449 return Core\Theme::getStylesheetPath($this->getCurrentTheme());
1453 * Check if request was an AJAX (xmlhttprequest) request.
1455 * @return boolean true if it was an AJAX request
1457 public function isAjax()
1459 return $this->isAjax;
1463 * Returns the value of a argv key
1464 * TODO there are a lot of $a->argv usages in combination with defaults() which can be replaced with this method
1466 * @param int $position the position of the argument
1467 * @param mixed $default the default value if not found
1469 * @return mixed returns the value of the argument
1471 public function getArgumentValue($position, $default = '')
1473 if (array_key_exists($position, $this->argv)) {
1474 return $this->argv[$position];
1481 * Sets the base url for use in cmdline programs which don't have
1482 * $_SERVER variables
1484 public function checkURL()
1486 $url = Core\Config::get('system', 'url');
1488 // if the url isn't set or the stored url is radically different
1489 // than the currently visited url, store the current value accordingly.
1490 // "Radically different" ignores common variations such as http vs https
1491 // and www.example.com vs example.com.
1492 // We will only change the url to an ip address if there is no existing setting
1494 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()))) {
1495 Core\Config::set('system', 'url', $this->getBaseURL());
1500 * Frontend App script
1502 * The App object behaves like a container and a dispatcher at the same time, including a representation of the
1503 * request and a representation of the response.
1505 * This probably should change to limit the size of this monster method.
1507 public function runFrontend()
1509 // Missing DB connection: ERROR
1510 if ($this->getMode()->has(App\Mode::LOCALCONFIGPRESENT) && !$this->getMode()->has(App\Mode::DBAVAILABLE)) {
1511 Core\System::httpExit(500, ['title' => 'Error 500 - Internal Server Error', 'description' => 'Apologies but the website is unavailable at the moment.']);
1514 // Max Load Average reached: ERROR
1515 if ($this->isMaxProcessesReached() || $this->isMaxLoadReached()) {
1516 header('Retry-After: 120');
1517 header('Refresh: 120; url=' . $this->getBaseURL() . "/" . $this->query_string);
1519 Core\System::httpExit(503, ['title' => 'Error 503 - Service Temporarily Unavailable', 'description' => 'Core\System is currently overloaded. Please try again later.']);
1522 if (strstr($this->query_string, '.well-known/host-meta') && ($this->query_string != '.well-known/host-meta')) {
1523 Core\System::httpExit(404);
1526 if (!$this->getMode()->isInstall()) {
1527 // Force SSL redirection
1528 if (Core\Config::get('system', 'force_ssl') && ($this->getScheme() == "http")
1529 && intval(Core\Config::get('system', 'ssl_policy')) == SSL_POLICY_FULL
1530 && strpos($this->getBaseURL(), 'https://') === 0
1531 && $_SERVER['REQUEST_METHOD'] == 'GET') {
1532 header('HTTP/1.1 302 Moved Temporarily');
1533 header('Location: ' . $this->getBaseURL() . '/' . $this->query_string);
1537 Core\Session::init();
1538 Core\Addon::callHooks('init_1');
1541 // Exclude the backend processes from the session management
1542 if (!$this->isBackend()) {
1543 $stamp1 = microtime(true);
1545 $this->saveTimestamp($stamp1, 'parser');
1546 Core\L10n::setSessionVariable();
1547 Core\L10n::setLangFromSession();
1550 Core\Worker::executeIfIdle();
1554 if (!empty($_GET['zrl']) && $this->getMode()->isNormal()) {
1555 $this->query_string = Model\Profile::stripZrls($this->query_string);
1556 if (!local_user()) {
1557 // Only continue when the given profile link seems valid
1558 // Valid profile links contain a path with "/profile/" and no query parameters
1559 if ((parse_url($_GET['zrl'], PHP_URL_QUERY) == "") &&
1560 strstr(parse_url($_GET['zrl'], PHP_URL_PATH), "/profile/")) {
1561 if (defaults($_SESSION, "visitor_home", "") != $_GET["zrl"]) {
1562 $_SESSION['my_url'] = $_GET['zrl'];
1563 $_SESSION['authenticated'] = 0;
1565 Model\Profile::zrlInit($this);
1567 // Someone came with an invalid parameter, maybe as a DDoS attempt
1568 // We simply stop processing here
1569 Core\Logger::log("Invalid ZRL parameter " . $_GET['zrl'], Core\Logger::DEBUG);
1570 Core\System::httpExit(403, ['title' => '403 Forbidden']);
1575 if (!empty($_GET['owt']) && $this->getMode()->isNormal()) {
1576 $token = $_GET['owt'];
1577 $this->query_string = Model\Profile::stripQueryParam($this->query_string, 'owt');
1578 Model\Profile::openWebAuthInit($token);
1581 Module\Login::sessionAuth();
1583 if (empty($_SESSION['authenticated'])) {
1584 header('X-Account-Management-Status: none');
1587 $_SESSION['sysmsg'] = defaults($_SESSION, 'sysmsg' , []);
1588 $_SESSION['sysmsg_info'] = defaults($_SESSION, 'sysmsg_info' , []);
1589 $_SESSION['last_updated'] = defaults($_SESSION, 'last_updated', []);
1592 * check_config() is responsible for running update scripts. These automatically
1593 * update the DB schema whenever we push a new one out. It also checks to see if
1594 * any addons have been added or removed and reacts accordingly.
1597 // in install mode, any url loads install module
1598 // but we need "view" module for stylesheet
1599 if ($this->getMode()->isInstall() && $this->module != 'view') {
1600 $this->module = 'install';
1601 } elseif (!$this->getMode()->has(App\Mode::MAINTENANCEDISABLED) && $this->module != 'view') {
1602 $this->module = 'maintenance';
1605 Core\Update::check(false);
1606 Core\Addon::loadAddons();
1607 Core\Hook::loadHooks();
1618 'right_aside' => '',
1623 if (strlen($this->module)) {
1624 // Compatibility with the Android Diaspora client
1625 if ($this->module == 'stream') {
1626 $this->internalRedirect('network?f=&order=post');
1629 if ($this->module == 'conversations') {
1630 $this->internalRedirect('message');
1633 if ($this->module == 'commented') {
1634 $this->internalRedirect('network?f=&order=comment');
1637 if ($this->module == 'liked') {
1638 $this->internalRedirect('network?f=&order=comment');
1641 if ($this->module == 'activity') {
1642 $this->internalRedirect('network/?f=&conv=1');
1645 if (($this->module == 'status_messages') && ($this->cmd == 'status_messages/new')) {
1646 $this->internalRedirect('bookmarklet');
1649 if (($this->module == 'user') && ($this->cmd == 'user/edit')) {
1650 $this->internalRedirect('settings');
1653 if (($this->module == 'tag_followings') && ($this->cmd == 'tag_followings/manage')) {
1654 $this->internalRedirect('search');
1657 // Compatibility with the Firefox App
1658 if (($this->module == "users") && ($this->cmd == "users/sign_in")) {
1659 $this->module = "login";
1662 $privateapps = Core\Config::get('config', 'private_addons', false);
1663 if (Core\Addon::isEnabled($this->module) && file_exists("addon/{$this->module}/{$this->module}.php")) {
1664 //Check if module is an app and if public access to apps is allowed or not
1665 if ((!local_user()) && Core\Hook::isAddonApp($this->module) && $privateapps) {
1666 info(Core\L10n::t("You must be logged in to use addons. "));
1668 include_once "addon/{$this->module}/{$this->module}.php";
1669 if (function_exists($this->module . '_module')) {
1670 LegacyModule::setModuleFile("addon/{$this->module}/{$this->module}.php");
1671 $this->module_class = 'Friendica\\LegacyModule';
1672 $this->module_loaded = true;
1677 // Controller class routing
1678 if (! $this->module_loaded && class_exists('Friendica\\Module\\' . ucfirst($this->module))) {
1679 $this->module_class = 'Friendica\\Module\\' . ucfirst($this->module);
1680 $this->module_loaded = true;
1683 /* If not, next look for a 'standard' program module in the 'mod' directory
1684 * We emulate a Module class through the LegacyModule class
1686 if (! $this->module_loaded && file_exists("mod/{$this->module}.php")) {
1687 LegacyModule::setModuleFile("mod/{$this->module}.php");
1688 $this->module_class = 'Friendica\\LegacyModule';
1689 $this->module_loaded = true;
1692 /* The URL provided does not resolve to a valid module.
1694 * On Dreamhost sites, quite often things go wrong for no apparent reason and they send us to '/internal_error.html'.
1695 * We don't like doing this, but as it occasionally accounts for 10-20% or more of all site traffic -
1696 * 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
1697 * this will often succeed and eventually do the right thing.
1699 * Otherwise we are going to emit a 404 not found.
1701 if (! $this->module_loaded) {
1702 // Stupid browser tried to pre-fetch our Javascript img template. Don't log the event or return anything - just quietly exit.
1703 if (!empty($_SERVER['QUERY_STRING']) && preg_match('/{[0-9]}/', $_SERVER['QUERY_STRING']) !== 0) {
1707 if (!empty($_SERVER['QUERY_STRING']) && ($_SERVER['QUERY_STRING'] === 'q=internal_error.html') && isset($dreamhost_error_hack)) {
1708 Core\Logger::log('index.php: dreamhost_error_hack invoked. Original URI =' . $_SERVER['REQUEST_URI']);
1709 $this->internalRedirect($_SERVER['REQUEST_URI']);
1712 Core\Logger::log('index.php: page not found: ' . $_SERVER['REQUEST_URI'] . ' ADDRESS: ' . $_SERVER['REMOTE_ADDR'] . ' QUERY: ' . $_SERVER['QUERY_STRING'], Core\Logger::DEBUG);
1714 header($_SERVER["SERVER_PROTOCOL"] . ' 404 ' . Core\L10n::t('Not Found'));
1715 $tpl = Core\Renderer::getMarkupTemplate("404.tpl");
1716 $this->page['content'] = Core\Renderer::replaceMacros($tpl, [
1717 '$message' => Core\L10n::t('Page not found.')
1722 // Initialize module that can set the current theme in the init() method, either directly or via App->profile_uid
1726 // Initialize module that can set the current theme in the init() method, either directly or via App->profile_uid
1727 if ($this->module_loaded) {
1728 $this->page['page_title'] = $this->module;
1731 Core\Addon::callHooks($this->module . '_mod_init', $placeholder);
1733 call_user_func([$this->module_class, 'init']);
1735 // "rawContent" is especially meant for technical endpoints.
1736 // This endpoint doesn't need any theme initialization or other comparable stuff.
1737 if (!$this->error) {
1738 call_user_func([$this->module_class, 'rawContent']);
1742 // Load current theme info after module has been initialized as theme could have been set in module
1743 $theme_info_file = 'view/theme/' . $this->getCurrentTheme() . '/theme.php';
1744 if (file_exists($theme_info_file)) {
1745 require_once $theme_info_file;
1748 if (function_exists(str_replace('-', '_', $this->getCurrentTheme()) . '_init')) {
1749 $func = str_replace('-', '_', $this->getCurrentTheme()) . '_init';
1753 if ($this->module_loaded) {
1754 if (! $this->error && $_SERVER['REQUEST_METHOD'] === 'POST') {
1755 Core\Addon::callHooks($this->module . '_mod_post', $_POST);
1756 call_user_func([$this->module_class, 'post']);
1759 if (! $this->error) {
1760 Core\Addon::callHooks($this->module . '_mod_afterpost', $placeholder);
1761 call_user_func([$this->module_class, 'afterpost']);
1764 if (! $this->error) {
1765 $arr = ['content' => $content];
1766 Core\Addon::callHooks($this->module . '_mod_content', $arr);
1767 $content = $arr['content'];
1768 $arr = ['content' => call_user_func([$this->module_class, 'content'])];
1769 Core\Addon::callHooks($this->module . '_mod_aftercontent', $arr);
1770 $content .= $arr['content'];
1774 // initialise content region
1775 if ($this->getMode()->isNormal()) {
1776 Core\Addon::callHooks('page_content_top', $this->page['content']);
1779 $this->page['content'] .= $content;
1780 } catch (HTTPException $e) {
1781 header($_SERVER["SERVER_PROTOCOL"] . " " . $e->httpcode . " " . $e->httpdesc , true, $e->httpcode);
1782 $error = ($e->getMessage() !== "" ? $e->getMessage() : $e->httpdesc);
1783 $tpl = Core\Renderer::getMarkupTemplate("404.tpl");
1784 $this->page['content'] = Core\Renderer::replaceMacros($tpl, [
1785 '$message' => $error
1789 /* Create the page head after setting the language
1790 * and getting any auth credentials.
1792 * Moved initHead() and initFooter() to after
1793 * all the module functions have executed so that all
1794 * theme choices made by the modules can take effect.
1798 /* Build the page ending -- this is stuff that goes right before
1799 * the closing </body> tag
1801 $this->initFooter();
1803 /* now that we've been through the module content, see if the page reported
1804 * a permission problem and if so, a 403 response would seem to be in order.
1806 if (stristr(implode("", $_SESSION['sysmsg']), Core\L10n::t('Permission denied'))) {
1807 header($_SERVER["SERVER_PROTOCOL"] . ' 403 ' . Core\L10n::t('Permission denied.'));
1810 // Report anything which needs to be communicated in the notification area (before the main body)
1811 Core\Addon::callHooks('page_end', $this->page['content']);
1813 // Add the navigation (menu) template
1814 if ($this->module != 'install' && $this->module != 'maintenance') {
1815 $this->page['htmlhead'] .= Core\Renderer::replaceMacros(Core\Renderer::getMarkupTemplate('nav_head.tpl'), []);
1816 $this->page['nav'] = Content\Nav::build($this);
1819 // Build the page - now that we have all the components
1820 if (isset($_GET["mode"]) && (($_GET["mode"] == "raw") || ($_GET["mode"] == "minimal"))) {
1821 $doc = new DOMDocument();
1823 $target = new DOMDocument();
1824 $target->loadXML("<root></root>");
1826 $content = mb_convert_encoding($this->page["content"], 'HTML-ENTITIES', "UTF-8");
1828 /// @TODO one day, kill those error-surpressing @ stuff, or PHP should ban it
1829 @$doc->loadHTML($content);
1831 $xpath = new DOMXPath($doc);
1833 $list = $xpath->query("//*[contains(@id,'tread-wrapper-')]"); /* */
1835 foreach ($list as $item) {
1836 $item = $target->importNode($item, true);
1838 // And then append it to the target
1839 $target->documentElement->appendChild($item);
1843 if (isset($_GET["mode"]) && ($_GET["mode"] == "raw")) {
1844 header("Content-type: text/html; charset=utf-8");
1846 echo substr($target->saveHTML(), 6, -8);
1851 $page = $this->page;
1852 $profile = $this->profile;
1854 header("X-Friendica-Version: " . FRIENDICA_VERSION);
1855 header("Content-type: text/html; charset=utf-8");
1857 if (Core\Config::get('system', 'hsts') && (Core\Config::get('system', 'ssl_policy') == SSL_POLICY_FULL)) {
1858 header("Strict-Transport-Security: max-age=31536000");
1861 // Some security stuff
1862 header('X-Content-Type-Options: nosniff');
1863 header('X-XSS-Protection: 1; mode=block');
1864 header('X-Permitted-Cross-Domain-Policies: none');
1865 header('X-Frame-Options: sameorigin');
1867 // Things like embedded OSM maps don't work, when this is enabled
1868 // 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'");
1870 /* We use $_GET["mode"] for special page templates. So we will check if we have
1871 * to load another page template than the default one.
1872 * The page templates are located in /view/php/ or in the theme directory.
1874 if (isset($_GET["mode"])) {
1875 $template = Core\Theme::getPathForFile($_GET["mode"] . '.php');
1878 // If there is no page template use the default page template
1879 if (empty($template)) {
1880 $template = Core\Theme::getPathForFile("default.php");
1883 // Theme templates expect $a as an App instance
1886 // Used as is in view/php/default.php
1887 $lang = Core\L10n::getCurrentLang();
1889 /// @TODO Looks unsafe (remote-inclusion), is maybe not but Core\Theme::getPathForFile() uses file_exists() but does not escape anything
1890 require_once $template;
1894 * Redirects to another module relative to the current Friendica base.
1895 * If you want to redirect to a external URL, use System::externalRedirectTo()
1897 * @param string $toUrl The destination URL (Default is empty, which is the default page of the Friendica node)
1898 * @param bool $ssl if true, base URL will try to get called with https:// (works just for relative paths)
1900 * @throws InternalServerErrorException In Case the given URL is not relative to the Friendica node
1902 public function internalRedirect($toUrl = '', $ssl = false)
1904 if (!empty(parse_url($toUrl, PHP_URL_SCHEME))) {
1905 throw new InternalServerErrorException("'$toUrl is not a relative path, please use System::externalRedirectTo");
1908 $redirectTo = $this->getBaseURL($ssl) . '/' . ltrim($toUrl, '/');
1909 Core\System::externalRedirect($redirectTo);
1913 * Automatically redirects to relative or absolute URL
1914 * Should only be used if it isn't clear if the URL is either internal or external
1916 * @param string $toUrl The target URL
1919 public function redirect($toUrl)
1921 if (!empty(parse_url($toUrl, PHP_URL_SCHEME))) {
1922 Core\System::externalRedirect($toUrl);
1924 $this->internalRedirect($toUrl);