7 use Detection\MobileDetect;
11 use Friendica\Core\Config\Cache\ConfigCache;
12 use Friendica\Core\Config\Configuration;
13 use Friendica\Core\Hook;
14 use Friendica\Core\L10n\L10n;
15 use Friendica\Core\Theme;
16 use Friendica\Database\Database;
17 use Friendica\Database\DBA;
18 use Friendica\Model\Profile;
19 use Friendica\Network\HTTPException;
20 use Friendica\Util\BaseURL;
21 use Friendica\Util\ConfigFileLoader;
22 use Friendica\Util\HTTPSignature;
23 use Friendica\Util\Profiler;
24 use Friendica\Util\Strings;
25 use Psr\Log\LoggerInterface;
31 * @brief Our main application structure for the life of this page.
33 * Primarily deals with the URL that got us here
34 * and tries to make some sense of it, and
35 * stores our page contents and config storage
36 * and anything else that might need to be passed around
37 * before we spit the page out.
42 public $module_class = null;
43 public $query_string = '';
59 public $interactive = true;
61 public $is_mobile = false;
62 public $is_tablet = false;
63 public $theme_info = [];
65 // Allow themes to control internal parameters
66 // by changing App values in theme.php
68 public $sourcename = '';
69 public $videowidth = 425;
70 public $videoheight = 350;
71 public $force_max_items = 0;
72 public $theme_events_in_profile = true;
74 public $stylesheets = [];
75 public $footerScripts = [];
78 * @var App\Mode The Mode of the Application
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
110 public $mobileDetect;
113 * @var Configuration The config
118 * @var LoggerInterface The logger
123 * @var Profiler The profiler of this app
128 * @var Database The Friendica database connection
133 * @var L10n The translator
138 * Returns the current config cache of this node
140 * @return ConfigCache
142 public function getConfigCache()
144 return $this->config->getCache();
148 * Returns the current config of this node
150 * @return Configuration
152 public function getConfig()
154 return $this->config;
158 * The basepath of this app
162 public function getBasePath()
164 // Don't use the basepath of the config table for basepath (it should always be the config-file one)
165 return $this->config->getCache()->get('system', 'basepath');
169 * The Logger of this app
171 * @return LoggerInterface
173 public function getLogger()
175 return $this->logger;
179 * The profiler of this app
183 public function getProfiler()
185 return $this->profiler;
189 * Returns the Mode of the Application
191 * @return App\Mode The Application Mode
193 public function getMode()
199 * Returns the router of the Application
203 public function getRouter()
205 return $this->router;
211 public function getDatabase()
213 return $this->database;
219 public function getL10n()
225 * Register a stylesheet file path to be included in the <head> tag of every page.
226 * Inclusion is done in App->initHead().
227 * The path can be absolute or relative to the Friendica installation base folder.
231 * @param string $path
233 public function registerStylesheet($path)
235 if (mb_strpos($path, $this->getBasePath() . DIRECTORY_SEPARATOR) === 0) {
236 $path = mb_substr($path, mb_strlen($this->getBasePath() . DIRECTORY_SEPARATOR));
239 $this->stylesheets[] = trim($path, '/');
243 * Register a javascript file path to be included in the <footer> tag of every page.
244 * Inclusion is done in App->initFooter().
245 * The path can be absolute or relative to the Friendica installation base folder.
249 * @param string $path
251 public function registerFooterScript($path)
253 $url = str_replace($this->getBasePath() . DIRECTORY_SEPARATOR, '', $path);
255 $this->footerScripts[] = trim($url, '/');
261 * @brief App constructor.
263 * @param Database $database The Friendica Database
264 * @param Configuration $config The Configuration
265 * @param App\Mode $mode The mode of this Friendica app
266 * @param App\Router $router The router of this Friendica app
267 * @param BaseURL $baseURL The full base URL of this Friendica app
268 * @param LoggerInterface $logger The current app logger
269 * @param Profiler $profiler The profiler of this application
270 * @param L10n $l10n The translator instance
271 * @param bool $isBackend Whether it is used for backend or frontend (Default true=backend)
273 * @throws Exception if the Basepath is not usable
275 public function __construct(Database $database, Configuration $config, App\Mode $mode, App\Router $router, BaseURL $baseURL, LoggerInterface $logger, Profiler $profiler, L10n $l10n, $isBackend = true)
277 BaseObject::setApp($this);
279 $this->database = $database;
280 $this->config = $config;
282 $this->router = $router;
283 $this->baseURL = $baseURL;
284 $this->profiler = $profiler;
285 $this->logger = $logger;
288 $this->profiler->reset();
294 // This has to be quite large to deal with embedded private photos
295 ini_set('pcre.backtrack_limit', 500000);
298 get_include_path() . PATH_SEPARATOR
299 . $this->getBasePath() . DIRECTORY_SEPARATOR . 'include' . PATH_SEPARATOR
300 . $this->getBasePath() . DIRECTORY_SEPARATOR . 'library' . PATH_SEPARATOR
301 . $this->getBasePath());
303 if (!empty($_SERVER['QUERY_STRING']) && strpos($_SERVER['QUERY_STRING'], 'pagename=') === 0) {
304 $this->query_string = substr($_SERVER['QUERY_STRING'], 9);
305 } elseif (!empty($_SERVER['QUERY_STRING']) && strpos($_SERVER['QUERY_STRING'], 'q=') === 0) {
306 $this->query_string = substr($_SERVER['QUERY_STRING'], 2);
309 // removing trailing / - maybe a nginx problem
310 $this->query_string = ltrim($this->query_string, '/');
312 if (!empty($_GET['pagename'])) {
313 $this->cmd = trim($_GET['pagename'], '/\\');
314 } elseif (!empty($_GET['q'])) {
315 $this->cmd = trim($_GET['q'], '/\\');
319 $this->query_string = str_replace($this->cmd . '&', $this->cmd . '?', $this->query_string);
321 // unix style "homedir"
322 if (substr($this->cmd, 0, 1) === '~') {
323 $this->cmd = 'profile/' . substr($this->cmd, 1);
326 // Diaspora style profile url
327 if (substr($this->cmd, 0, 2) === 'u/') {
328 $this->cmd = 'profile/' . substr($this->cmd, 2);
332 * Break the URL path into C style argc/argv style arguments for our
333 * modules. Given "http://example.com/module/arg1/arg2", $this->argc
334 * will be 3 (integer) and $this->argv will contain:
340 * There will always be one argument. If provided a naked domain
341 * URL, $this->argv[0] is set to "home".
344 $this->argv = explode('/', $this->cmd);
345 $this->argc = count($this->argv);
346 if ((array_key_exists('0', $this->argv)) && strlen($this->argv[0])) {
347 $this->module = str_replace('.', '_', $this->argv[0]);
348 $this->module = str_replace('-', '_', $this->module);
351 $this->argv = ['home'];
352 $this->module = 'home';
355 $this->isBackend = $isBackend || $this->checkBackend($this->module);
357 // Detect mobile devices
358 $mobile_detect = new MobileDetect();
360 $this->mobileDetect = $mobile_detect;
362 $this->is_mobile = $mobile_detect->isMobile();
363 $this->is_tablet = $mobile_detect->isTablet();
365 $this->isAjax = strtolower(defaults($_SERVER, 'HTTP_X_REQUESTED_WITH', '')) == 'xmlhttprequest';
367 // Register template engines
368 Core\Renderer::registerTemplateEngine('Friendica\Render\FriendicaSmartyEngine');
372 * Reloads the whole app instance
374 public function reload()
376 $this->getMode()->determine($this->getBasePath());
378 if ($this->getMode()->has(App\Mode::DBAVAILABLE)) {
379 $this->profiler->update($this->config);
381 Core\Hook::loadHooks();
382 $loader = new ConfigFileLoader($this->getBasePath());
383 Core\Hook::callAll('load_config', $loader);
386 $this->loadDefaultTimezone();
390 * Loads the default timezone
392 * Include support for legacy $default_timezone
394 * @global string $default_timezone
396 private function loadDefaultTimezone()
398 if ($this->config->get('system', 'default_timezone')) {
399 $this->timezone = $this->config->get('system', 'default_timezone');
401 global $default_timezone;
402 $this->timezone = !empty($default_timezone) ? $default_timezone : 'UTC';
405 if ($this->timezone) {
406 date_default_timezone_set($this->timezone);
411 * Returns the scheme of the current call
414 * @deprecated 2019.06 - use BaseURL->getScheme() instead
416 public function getScheme()
418 return $this->baseURL->getScheme();
422 * Retrieves the Friendica instance base URL
424 * @param bool $ssl Whether to append http or https under BaseURL::SSL_POLICY_SELFSIGN
426 * @return string Friendica server base URL
428 public function getBaseURL($ssl = false)
430 return $this->baseURL->get($ssl);
434 * @brief Initializes the baseurl components
436 * Clears the baseurl cache to prevent inconsistencies
440 * @deprecated 2019.06 - use BaseURL->saveByURL($url) instead
442 public function setBaseURL($url)
444 $this->baseURL->saveByURL($url);
448 * Returns the current hostname
452 * @deprecated 2019.06 - use BaseURL->getHostname() instead
454 public function getHostName()
456 return $this->baseURL->getHostname();
460 * Returns the sub-path of the full URL
464 * @deprecated 2019.06 - use BaseURL->getUrlPath() instead
466 public function getURLPath()
468 return $this->baseURL->getUrlPath();
472 * Initializes App->page['htmlhead'].
477 * - Registered stylesheets (through App->registerStylesheet())
478 * - Infinite scroll data
479 * - head.tpl template
481 public function initHead()
483 $interval = ((local_user()) ? Core\PConfig::get(local_user(), 'system', 'update_interval') : 40000);
485 // If the update is 'deactivated' set it to the highest integer number (~24 days)
487 $interval = 2147483647;
490 if ($interval < 10000) {
494 // Default title: current module called
495 if (empty($this->page['title']) && $this->module) {
496 $this->page['title'] = ucfirst($this->module);
499 // Prepend the sitename to the page title
500 $this->page['title'] = $this->config->get('config', 'sitename', '') . (!empty($this->page['title']) ? ' | ' . $this->page['title'] : '');
502 if (!empty(Core\Renderer::$theme['stylesheet'])) {
503 $stylesheet = Core\Renderer::$theme['stylesheet'];
505 $stylesheet = $this->getCurrentThemeStylesheetPath();
508 $this->registerStylesheet($stylesheet);
510 $shortcut_icon = $this->config->get('system', 'shortcut_icon');
511 if ($shortcut_icon == '') {
512 $shortcut_icon = 'images/friendica-32.png';
515 $touch_icon = $this->config->get('system', 'touch_icon');
516 if ($touch_icon == '') {
517 $touch_icon = 'images/friendica-128.png';
520 Core\Hook::callAll('head', $this->page['htmlhead']);
522 $tpl = Core\Renderer::getMarkupTemplate('head.tpl');
523 /* put the head template at the beginning of page['htmlhead']
524 * since the code added by the modules frequently depends on it
527 $this->page['htmlhead'] = Core\Renderer::replaceMacros($tpl, [
528 '$local_user' => local_user(),
529 '$generator' => 'Friendica' . ' ' . FRIENDICA_VERSION,
530 '$delitem' => $this->l10n->t('Delete this item?'),
531 '$update_interval' => $interval,
532 '$shortcut_icon' => $shortcut_icon,
533 '$touch_icon' => $touch_icon,
534 '$block_public' => intval($this->config->get('system', 'block_public')),
535 '$stylesheets' => $this->stylesheets,
536 ]) . $this->page['htmlhead'];
540 * Initializes App->page['footer'].
543 * - Javascript homebase
544 * - Mobile toggle link
545 * - Registered footer scripts (through App->registerFooterScript())
546 * - footer.tpl template
548 public function initFooter()
550 // If you're just visiting, let javascript take you home
551 if (!empty($_SESSION['visitor_home'])) {
552 $homebase = $_SESSION['visitor_home'];
553 } elseif (local_user()) {
554 $homebase = 'profile/' . $this->user['nickname'];
557 if (isset($homebase)) {
558 $this->page['footer'] .= '<script>var homebase="' . $homebase . '";</script>' . "\n";
562 * Add a "toggle mobile" link if we're using a mobile device
564 if ($this->is_mobile || $this->is_tablet) {
565 if (isset($_SESSION['show-mobile']) && !$_SESSION['show-mobile']) {
566 $link = 'toggle_mobile?address=' . urlencode(curPageURL());
568 $link = 'toggle_mobile?off=1&address=' . urlencode(curPageURL());
570 $this->page['footer'] .= Core\Renderer::replaceMacros(Core\Renderer::getMarkupTemplate("toggle_mobile_footer.tpl"), [
571 '$toggle_link' => $link,
572 '$toggle_text' => $this->l10n->t('toggle mobile')
576 Core\Hook::callAll('footer', $this->page['footer']);
578 $tpl = Core\Renderer::getMarkupTemplate('footer.tpl');
579 $this->page['footer'] = Core\Renderer::replaceMacros($tpl, [
580 '$footerScripts' => $this->footerScripts,
581 ]) . $this->page['footer'];
585 * @brief Removes the base url from an url. This avoids some mixed content problems.
587 * @param string $origURL
589 * @return string The cleaned url
590 * @throws HTTPException\InternalServerErrorException
592 public function removeBaseURL($origURL)
594 // Remove the hostname from the url if it is an internal link
595 $nurl = Util\Strings::normaliseLink($origURL);
596 $base = Util\Strings::normaliseLink($this->getBaseURL());
597 $url = str_replace($base . '/', '', $nurl);
599 // if it is an external link return the orignal value
600 if ($url == Util\Strings::normaliseLink($origURL)) {
608 * Returns the current UserAgent as a String
610 * @return string the UserAgent as a String
611 * @throws HTTPException\InternalServerErrorException
613 public function getUserAgent()
616 FRIENDICA_PLATFORM . " '" .
617 FRIENDICA_CODENAME . "' " .
618 FRIENDICA_VERSION . '-' .
619 DB_UPDATE_VERSION . '; ' .
624 * @brief Checks if the site is called via a backend process
626 * This isn't a perfect solution. But we need this check very early.
627 * So we cannot wait until the modules are loaded.
629 * @param string $module
632 private function checkBackend($module) {
661 // Check if current module is in backend or backend flag is set
662 return in_array($module, $backends);
666 * Returns true, if the call is from a backend node (f.e. from a worker)
668 * @return bool Is it a known backend?
670 public function isBackend()
672 return $this->isBackend;
676 * @brief Checks if the maximum number of database processes is reached
678 * @return bool Is the limit reached?
680 public function isMaxProcessesReached()
682 // Deactivated, needs more investigating if this check really makes sense
686 * Commented out to suppress static analyzer issues
688 if ($this->is_backend()) {
689 $process = 'backend';
690 $max_processes = $this->config->get('system', 'max_processes_backend');
691 if (intval($max_processes) == 0) {
695 $process = 'frontend';
696 $max_processes = $this->config->get('system', 'max_processes_frontend');
697 if (intval($max_processes) == 0) {
702 $processlist = DBA::processlist();
703 if ($processlist['list'] != '') {
704 Core\Logger::log('Processcheck: Processes: ' . $processlist['amount'] . ' - Processlist: ' . $processlist['list'], Core\Logger::DEBUG);
706 if ($processlist['amount'] > $max_processes) {
707 Core\Logger::log('Processcheck: Maximum number of processes for ' . $process . ' tasks (' . $max_processes . ') reached.', Core\Logger::DEBUG);
716 * @brief Checks if the minimal memory is reached
718 * @return bool Is the memory limit reached?
719 * @throws HTTPException\InternalServerErrorException
721 public function isMinMemoryReached()
723 $min_memory = $this->config->get('system', 'min_memory', 0);
724 if ($min_memory == 0) {
728 if (!is_readable('/proc/meminfo')) {
732 $memdata = explode("\n", file_get_contents('/proc/meminfo'));
735 foreach ($memdata as $line) {
736 $data = explode(':', $line);
737 if (count($data) != 2) {
740 list($key, $val) = $data;
741 $meminfo[$key] = (int) trim(str_replace('kB', '', $val));
742 $meminfo[$key] = (int) ($meminfo[$key] / 1024);
745 if (!isset($meminfo['MemFree'])) {
749 $free = $meminfo['MemFree'];
751 $reached = ($free < $min_memory);
754 Core\Logger::log('Minimal memory reached: ' . $free . '/' . $meminfo['MemTotal'] . ' - limit ' . $min_memory, Core\Logger::DEBUG);
761 * @brief Checks if the maximum load is reached
763 * @return bool Is the load reached?
764 * @throws HTTPException\InternalServerErrorException
766 public function isMaxLoadReached()
768 if ($this->isBackend()) {
769 $process = 'backend';
770 $maxsysload = intval($this->config->get('system', 'maxloadavg'));
771 if ($maxsysload < 1) {
775 $process = 'frontend';
776 $maxsysload = intval($this->config->get('system', 'maxloadavg_frontend'));
777 if ($maxsysload < 1) {
782 $load = Core\System::currentLoad();
784 if (intval($load) > $maxsysload) {
785 Core\Logger::log('system: load ' . $load . ' for ' . $process . ' tasks (' . $maxsysload . ') too high.');
793 * Executes a child process with 'proc_open'
795 * @param string $command The command to execute
796 * @param array $args Arguments to pass to the command ( [ 'key' => value, 'key2' => value2, ... ]
797 * @throws HTTPException\InternalServerErrorException
799 public function proc_run($command, $args)
801 if (!function_exists('proc_open')) {
805 $cmdline = $this->config->get('config', 'php_path', 'php') . ' ' . escapeshellarg($command);
807 foreach ($args as $key => $value) {
808 if (!is_null($value) && is_bool($value) && !$value) {
812 $cmdline .= ' --' . $key;
813 if (!is_null($value) && !is_bool($value)) {
814 $cmdline .= ' ' . $value;
818 if ($this->isMinMemoryReached()) {
822 if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
823 $resource = proc_open('cmd /c start /b ' . $cmdline, [], $foo, $this->getBasePath());
825 $resource = proc_open($cmdline . ' &', [], $foo, $this->getBasePath());
827 if (!is_resource($resource)) {
828 Core\Logger::log('We got no resource for command ' . $cmdline, Core\Logger::DEBUG);
831 proc_close($resource);
835 * Generates the site's default sender email address
838 * @throws HTTPException\InternalServerErrorException
840 public function getSenderEmailAddress()
842 $sender_email = $this->config->get('config', 'sender_email');
843 if (empty($sender_email)) {
844 $hostname = $this->baseURL->getHostname();
845 if (strpos($hostname, ':')) {
846 $hostname = substr($hostname, 0, strpos($hostname, ':'));
849 $sender_email = 'noreply@' . $hostname;
852 return $sender_email;
856 * Returns the current theme name.
858 * @return string the name of the current theme
859 * @throws HTTPException\InternalServerErrorException
861 public function getCurrentTheme()
863 if ($this->getMode()->isInstall()) {
867 if (!$this->currentTheme) {
868 $this->computeCurrentTheme();
871 return $this->currentTheme;
874 public function setCurrentTheme($theme)
876 $this->currentTheme = $theme;
880 * Computes the current theme name based on the node settings, the user settings and the device type
884 private function computeCurrentTheme()
886 $system_theme = $this->config->get('system', 'theme');
887 if (!$system_theme) {
888 throw new Exception($this->l10n->t('No system theme config value set.'));
892 $this->currentTheme = $system_theme;
895 // Find the theme that belongs to the user whose stuff we are looking at
896 if ($this->profile_uid && ($this->profile_uid != local_user())) {
897 // Allow folks to override user themes and always use their own on their own site.
898 // This works only if the user is on the same server
899 $user = DBA::selectFirst('user', ['theme'], ['uid' => $this->profile_uid]);
900 if (DBA::isResult($user) && !Core\PConfig::get(local_user(), 'system', 'always_my_theme')) {
901 $page_theme = $user['theme'];
905 $user_theme = Core\Session::get('theme', $system_theme);
907 // Specific mobile theme override
908 if (($this->is_mobile || $this->is_tablet) && Core\Session::get('show-mobile', true)) {
909 $system_mobile_theme = $this->config->get('system', 'mobile-theme');
910 $user_mobile_theme = Core\Session::get('mobile-theme', $system_mobile_theme);
912 // --- means same mobile theme as desktop
913 if (!empty($user_mobile_theme) && $user_mobile_theme !== '---') {
914 $user_theme = $user_mobile_theme;
919 $theme_name = $page_theme;
921 $theme_name = $user_theme;
924 $theme_name = Strings::sanitizeFilePathItem($theme_name);
926 && in_array($theme_name, Theme::getAllowedList())
927 && (file_exists('view/theme/' . $theme_name . '/style.css')
928 || file_exists('view/theme/' . $theme_name . '/style.php'))
930 $this->currentTheme = $theme_name;
935 * @brief Return full URL to theme which is currently in effect.
937 * Provide a sane default if nothing is chosen or the specified theme does not exist.
940 * @throws HTTPException\InternalServerErrorException
942 public function getCurrentThemeStylesheetPath()
944 return Core\Theme::getStylesheetPath($this->getCurrentTheme());
948 * Check if request was an AJAX (xmlhttprequest) request.
950 * @return boolean true if it was an AJAX request
952 public function isAjax()
954 return $this->isAjax;
958 * Returns the value of a argv key
959 * TODO there are a lot of $a->argv usages in combination with defaults() which can be replaced with this method
961 * @param int $position the position of the argument
962 * @param mixed $default the default value if not found
964 * @return mixed returns the value of the argument
966 public function getArgumentValue($position, $default = '')
968 if (array_key_exists($position, $this->argv)) {
969 return $this->argv[$position];
976 * Sets the base url for use in cmdline programs which don't have
979 public function checkURL()
981 $url = $this->config->get('system', 'url');
983 // if the url isn't set or the stored url is radically different
984 // than the currently visited url, store the current value accordingly.
985 // "Radically different" ignores common variations such as http vs https
986 // and www.example.com vs example.com.
987 // We will only change the url to an ip address if there is no existing setting
989 if (empty($url) || (!Util\Strings::compareLink($url, $this->getBaseURL())) && (!preg_match("/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/", $this->baseURL->getHostname()))) {
990 $this->config->set('system', 'url', $this->getBaseURL());
995 * Frontend App script
997 * The App object behaves like a container and a dispatcher at the same time, including a representation of the
998 * request and a representation of the response.
1000 * This probably should change to limit the size of this monster method.
1002 public function runFrontend()
1004 // Missing DB connection: ERROR
1005 if ($this->getMode()->has(App\Mode::LOCALCONFIGPRESENT) && !$this->getMode()->has(App\Mode::DBAVAILABLE)) {
1006 Module\Special\HTTPException::rawContent(
1007 new HTTPException\InternalServerErrorException('Apologies but the website is unavailable at the moment.')
1011 // Max Load Average reached: ERROR
1012 if ($this->isMaxProcessesReached() || $this->isMaxLoadReached()) {
1013 header('Retry-After: 120');
1014 header('Refresh: 120; url=' . $this->getBaseURL() . "/" . $this->query_string);
1016 Module\Special\HTTPException::rawContent(
1017 new HTTPException\ServiceUnavailableException('The node is currently overloaded. Please try again later.')
1021 if (!$this->getMode()->isInstall()) {
1022 // Force SSL redirection
1023 if ($this->baseURL->checkRedirectHttps()) {
1024 header('HTTP/1.1 302 Moved Temporarily');
1025 header('Location: ' . $this->getBaseURL() . '/' . $this->query_string);
1029 Core\Session::init();
1030 Core\Hook::callAll('init_1');
1033 // Exclude the backend processes from the session management
1034 if (!$this->isBackend()) {
1035 $stamp1 = microtime(true);
1037 $this->profiler->saveTimestamp($stamp1, 'parser', Core\System::callstack());
1038 $this->l10n->setSessionVariable();
1039 $this->l10n->setLangFromSession();
1042 Core\Worker::executeIfIdle();
1045 if ($this->getMode()->isNormal()) {
1046 $requester = HTTPSignature::getSigner('', $_SERVER);
1047 if (!empty($requester)) {
1048 Profile::addVisitorCookieForHandle($requester);
1053 if (!empty($_GET['zrl']) && $this->getMode()->isNormal()) {
1054 $this->query_string = Model\Profile::stripZrls($this->query_string);
1055 if (!local_user()) {
1056 // Only continue when the given profile link seems valid
1057 // Valid profile links contain a path with "/profile/" and no query parameters
1058 if ((parse_url($_GET['zrl'], PHP_URL_QUERY) == "") &&
1059 strstr(parse_url($_GET['zrl'], PHP_URL_PATH), "/profile/")) {
1060 if (Core\Session::get('visitor_home') != $_GET["zrl"]) {
1061 Core\Session::set('my_url', $_GET['zrl']);
1062 Core\Session::set('authenticated', 0);
1065 Model\Profile::zrlInit($this);
1067 // Someone came with an invalid parameter, maybe as a DDoS attempt
1068 // We simply stop processing here
1069 Core\Logger::log("Invalid ZRL parameter " . $_GET['zrl'], Core\Logger::DEBUG);
1070 Module\Special\HTTPException::rawContent(
1071 new HTTPException\ForbiddenException()
1077 if (!empty($_GET['owt']) && $this->getMode()->isNormal()) {
1078 $token = $_GET['owt'];
1079 $this->query_string = Model\Profile::stripQueryParam($this->query_string, 'owt');
1080 Model\Profile::openWebAuthInit($token);
1083 Module\Login::sessionAuth();
1085 if (empty($_SESSION['authenticated'])) {
1086 header('X-Account-Management-Status: none');
1089 $_SESSION['sysmsg'] = Core\Session::get('sysmsg', []);
1090 $_SESSION['sysmsg_info'] = Core\Session::get('sysmsg_info', []);
1091 $_SESSION['last_updated'] = Core\Session::get('last_updated', []);
1094 * check_config() is responsible for running update scripts. These automatically
1095 * update the DB schema whenever we push a new one out. It also checks to see if
1096 * any addons have been added or removed and reacts accordingly.
1099 // in install mode, any url loads install module
1100 // but we need "view" module for stylesheet
1101 if ($this->getMode()->isInstall() && $this->module !== 'install') {
1102 $this->internalRedirect('install');
1103 } elseif (!$this->getMode()->isInstall() && !$this->getMode()->has(App\Mode::MAINTENANCEDISABLED) && $this->module !== 'maintenance') {
1104 $this->internalRedirect('maintenance');
1107 Core\Update::check($this->getBasePath(), false, $this->getMode());
1108 Core\Addon::loadAddons();
1109 Core\Hook::loadHooks();
1120 'right_aside' => '',
1125 // Compatibility with the Android Diaspora client
1126 if ($this->module == 'stream') {
1127 $this->internalRedirect('network?order=post');
1130 if ($this->module == 'conversations') {
1131 $this->internalRedirect('message');
1134 if ($this->module == 'commented') {
1135 $this->internalRedirect('network?order=comment');
1138 if ($this->module == 'liked') {
1139 $this->internalRedirect('network?order=comment');
1142 if ($this->module == 'activity') {
1143 $this->internalRedirect('network?conv=1');
1146 if (($this->module == 'status_messages') && ($this->cmd == 'status_messages/new')) {
1147 $this->internalRedirect('bookmarklet');
1150 if (($this->module == 'user') && ($this->cmd == 'user/edit')) {
1151 $this->internalRedirect('settings');
1154 if (($this->module == 'tag_followings') && ($this->cmd == 'tag_followings/manage')) {
1155 $this->internalRedirect('search');
1158 // Compatibility with the Firefox App
1159 if (($this->module == "users") && ($this->cmd == "users/sign_in")) {
1160 $this->module = "login";
1166 * From the request URL, routing consists of obtaining the name of a BaseModule-extending class of which the
1167 * post() and/or content() static methods can be respectively called to produce a data change or an output.
1170 // First we try explicit routes defined in App\Router
1171 $this->router->collectRoutes();
1173 $data = $this->router->getRouteCollector();
1174 Hook::callAll('route_collection', $data);
1176 $this->module_class = $this->router->getModuleClass($this->cmd);
1178 // Then we try addon-provided modules that we wrap in the LegacyModule class
1179 if (!$this->module_class && Core\Addon::isEnabled($this->module) && file_exists("addon/{$this->module}/{$this->module}.php")) {
1180 //Check if module is an app and if public access to apps is allowed or not
1181 $privateapps = $this->config->get('config', 'private_addons', false);
1182 if ((!local_user()) && Core\Hook::isAddonApp($this->module) && $privateapps) {
1183 info($this->l10n->t("You must be logged in to use addons. "));
1185 include_once "addon/{$this->module}/{$this->module}.php";
1186 if (function_exists($this->module . '_module')) {
1187 LegacyModule::setModuleFile("addon/{$this->module}/{$this->module}.php");
1188 $this->module_class = LegacyModule::class;
1193 /* Finally, we look for a 'standard' program module in the 'mod' directory
1194 * We emulate a Module class through the LegacyModule class
1196 if (!$this->module_class && file_exists("mod/{$this->module}.php")) {
1197 LegacyModule::setModuleFile("mod/{$this->module}.php");
1198 $this->module_class = LegacyModule::class;
1201 /* The URL provided does not resolve to a valid module.
1203 * On Dreamhost sites, quite often things go wrong for no apparent reason and they send us to '/internal_error.html'.
1204 * We don't like doing this, but as it occasionally accounts for 10-20% or more of all site traffic -
1205 * 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
1206 * this will often succeed and eventually do the right thing.
1208 * Otherwise we are going to emit a 404 not found.
1210 if (!$this->module_class) {
1211 // Stupid browser tried to pre-fetch our Javascript img template. Don't log the event or return anything - just quietly exit.
1212 if (!empty($_SERVER['QUERY_STRING']) && preg_match('/{[0-9]}/', $_SERVER['QUERY_STRING']) !== 0) {
1216 if (!empty($_SERVER['QUERY_STRING']) && ($_SERVER['QUERY_STRING'] === 'q=internal_error.html') && isset($dreamhost_error_hack)) {
1217 Core\Logger::log('index.php: dreamhost_error_hack invoked. Original URI =' . $_SERVER['REQUEST_URI']);
1218 $this->internalRedirect($_SERVER['REQUEST_URI']);
1221 Core\Logger::log('index.php: page not found: ' . $_SERVER['REQUEST_URI'] . ' ADDRESS: ' . $_SERVER['REMOTE_ADDR'] . ' QUERY: ' . $_SERVER['QUERY_STRING'], Core\Logger::DEBUG);
1223 $this->module_class = Module\PageNotFound::class;
1226 // Initialize module that can set the current theme in the init() method, either directly or via App->profile_uid
1227 $this->page['page_title'] = $this->module;
1231 Core\Hook::callAll($this->module . '_mod_init', $placeholder);
1233 call_user_func([$this->module_class, 'init']);
1235 // "rawContent" is especially meant for technical endpoints.
1236 // This endpoint doesn't need any theme initialization or other comparable stuff.
1237 call_user_func([$this->module_class, 'rawContent']);
1239 // Load current theme info after module has been initialized as theme could have been set in module
1240 $theme_info_file = 'view/theme/' . $this->getCurrentTheme() . '/theme.php';
1241 if (file_exists($theme_info_file)) {
1242 require_once $theme_info_file;
1245 if (function_exists(str_replace('-', '_', $this->getCurrentTheme()) . '_init')) {
1246 $func = str_replace('-', '_', $this->getCurrentTheme()) . '_init';
1250 if ($_SERVER['REQUEST_METHOD'] === 'POST') {
1251 Core\Hook::callAll($this->module . '_mod_post', $_POST);
1252 call_user_func([$this->module_class, 'post']);
1255 Core\Hook::callAll($this->module . '_mod_afterpost', $placeholder);
1256 call_user_func([$this->module_class, 'afterpost']);
1257 } catch(HTTPException $e) {
1258 Module\Special\HTTPException::rawContent($e);
1264 $arr = ['content' => $content];
1265 Core\Hook::callAll($this->module . '_mod_content', $arr);
1266 $content = $arr['content'];
1267 $arr = ['content' => call_user_func([$this->module_class, 'content'])];
1268 Core\Hook::callAll($this->module . '_mod_aftercontent', $arr);
1269 $content .= $arr['content'];
1270 } catch(HTTPException $e) {
1271 $content = Module\Special\HTTPException::content($e);
1274 // initialise content region
1275 if ($this->getMode()->isNormal()) {
1276 Core\Hook::callAll('page_content_top', $this->page['content']);
1279 $this->page['content'] .= $content;
1281 /* Create the page head after setting the language
1282 * and getting any auth credentials.
1284 * Moved initHead() and initFooter() to after
1285 * all the module functions have executed so that all
1286 * theme choices made by the modules can take effect.
1290 /* Build the page ending -- this is stuff that goes right before
1291 * the closing </body> tag
1293 $this->initFooter();
1295 if (!$this->isAjax()) {
1296 Core\Hook::callAll('page_end', $this->page['content']);
1299 // Add the navigation (menu) template
1300 if ($this->module != 'install' && $this->module != 'maintenance') {
1301 $this->page['htmlhead'] .= Core\Renderer::replaceMacros(Core\Renderer::getMarkupTemplate('nav_head.tpl'), []);
1302 $this->page['nav'] = Content\Nav::build($this);
1305 // Build the page - now that we have all the components
1306 if (isset($_GET["mode"]) && (($_GET["mode"] == "raw") || ($_GET["mode"] == "minimal"))) {
1307 $doc = new DOMDocument();
1309 $target = new DOMDocument();
1310 $target->loadXML("<root></root>");
1312 $content = mb_convert_encoding($this->page["content"], 'HTML-ENTITIES', "UTF-8");
1314 /// @TODO one day, kill those error-surpressing @ stuff, or PHP should ban it
1315 @$doc->loadHTML($content);
1317 $xpath = new DOMXPath($doc);
1319 $list = $xpath->query("//*[contains(@id,'tread-wrapper-')]"); /* */
1321 foreach ($list as $item) {
1322 $item = $target->importNode($item, true);
1324 // And then append it to the target
1325 $target->documentElement->appendChild($item);
1328 if ($_GET["mode"] == "raw") {
1329 header("Content-type: text/html; charset=utf-8");
1331 echo substr($target->saveHTML(), 6, -8);
1337 $page = $this->page;
1338 $profile = $this->profile;
1340 header("X-Friendica-Version: " . FRIENDICA_VERSION);
1341 header("Content-type: text/html; charset=utf-8");
1343 if ($this->config->get('system', 'hsts') && ($this->baseURL->getSSLPolicy() == BaseUrl::SSL_POLICY_FULL)) {
1344 header("Strict-Transport-Security: max-age=31536000");
1347 // Some security stuff
1348 header('X-Content-Type-Options: nosniff');
1349 header('X-XSS-Protection: 1; mode=block');
1350 header('X-Permitted-Cross-Domain-Policies: none');
1351 header('X-Frame-Options: sameorigin');
1353 // Things like embedded OSM maps don't work, when this is enabled
1354 // 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'");
1356 /* We use $_GET["mode"] for special page templates. So we will check if we have
1357 * to load another page template than the default one.
1358 * The page templates are located in /view/php/ or in the theme directory.
1360 if (isset($_GET["mode"])) {
1361 $template = Core\Theme::getPathForFile($_GET["mode"] . '.php');
1364 // If there is no page template use the default page template
1365 if (empty($template)) {
1366 $template = Core\Theme::getPathForFile("default.php");
1369 // Theme templates expect $a as an App instance
1372 // Used as is in view/php/default.php
1373 $lang = $this->l10n->getCurrentLang();
1375 /// @TODO Looks unsafe (remote-inclusion), is maybe not but Core\Theme::getPathForFile() uses file_exists() but does not escape anything
1376 require_once $template;
1380 * Redirects to another module relative to the current Friendica base.
1381 * If you want to redirect to a external URL, use System::externalRedirectTo()
1383 * @param string $toUrl The destination URL (Default is empty, which is the default page of the Friendica node)
1384 * @param bool $ssl if true, base URL will try to get called with https:// (works just for relative paths)
1386 * @throws HTTPException\InternalServerErrorException In Case the given URL is not relative to the Friendica node
1388 public function internalRedirect($toUrl = '', $ssl = false)
1390 if (!empty(parse_url($toUrl, PHP_URL_SCHEME))) {
1391 throw new HTTPException\InternalServerErrorException("'$toUrl is not a relative path, please use System::externalRedirectTo");
1394 $redirectTo = $this->getBaseURL($ssl) . '/' . ltrim($toUrl, '/');
1395 Core\System::externalRedirect($redirectTo);
1399 * Automatically redirects to relative or absolute URL
1400 * Should only be used if it isn't clear if the URL is either internal or external
1402 * @param string $toUrl The target URL
1403 * @throws HTTPException\InternalServerErrorException
1405 public function redirect($toUrl)
1407 if (!empty(parse_url($toUrl, PHP_URL_SCHEME))) {
1408 Core\System::externalRedirect($toUrl);
1410 $this->internalRedirect($toUrl);