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\Theme;
15 use Friendica\Database\Database;
16 use Friendica\Database\DBA;
17 use Friendica\Model\Profile;
18 use Friendica\Network\HTTPException;
19 use Friendica\Util\BaseURL;
20 use Friendica\Util\Config\ConfigFileLoader;
21 use Friendica\Util\HTTPSignature;
22 use Friendica\Util\Profiler;
23 use Friendica\Util\Strings;
24 use Psr\Log\LoggerInterface;
30 * @brief Our main application structure for the life of this page.
32 * Primarily deals with the URL that got us here
33 * and tries to make some sense of it, and
34 * stores our page contents and config storage
35 * and anything else that might need to be passed around
36 * before we spit the page out.
41 public $module_class = null;
42 public $query_string = '';
58 public $interactive = true;
60 public $is_mobile = false;
61 public $is_tablet = false;
62 public $theme_info = [];
64 // Allow themes to control internal parameters
65 // by changing App values in theme.php
67 public $sourcename = '';
68 public $videowidth = 425;
69 public $videoheight = 350;
70 public $force_max_items = 0;
71 public $theme_events_in_profile = true;
73 public $stylesheets = [];
74 public $footerScripts = [];
77 * @var App\Mode The Mode of the Application
92 * @var bool true, if the call is from an backend node (f.e. worker)
97 * @var string The name of the current theme
99 private $currentTheme;
102 * @var bool check if request was an AJAX (xmlhttprequest) request
109 public $mobileDetect;
112 * @var Configuration The config
117 * @var LoggerInterface The logger
122 * @var Profiler The profiler of this app
127 * @var Database The Friendica database connection
132 * Returns the current config cache of this node
134 * @return ConfigCache
136 public function getConfigCache()
138 return $this->config->getCache();
142 * Returns the current config of this node
144 * @return Configuration
146 public function getConfig()
148 return $this->config;
152 * The basepath of this app
156 public function getBasePath()
158 // Don't use the basepath of the config table for basepath (it should always be the config-file one)
159 return $this->config->getCache()->get('system', 'basepath');
163 * The Logger of this app
165 * @return LoggerInterface
167 public function getLogger()
169 return $this->logger;
173 * The profiler of this app
177 public function getProfiler()
179 return $this->profiler;
183 * Returns the Mode of the Application
185 * @return App\Mode The Application Mode
187 public function getMode()
193 * Returns the router of the Application
197 public function getRouter()
199 return $this->router;
205 public function getDatabase()
207 return $this->database;
211 * Register a stylesheet file path to be included in the <head> tag of every page.
212 * Inclusion is done in App->initHead().
213 * The path can be absolute or relative to the Friendica installation base folder.
217 * @param string $path
219 public function registerStylesheet($path)
221 if (mb_strpos($path, $this->getBasePath() . DIRECTORY_SEPARATOR) === 0) {
222 $path = mb_substr($path, mb_strlen($this->getBasePath() . DIRECTORY_SEPARATOR));
225 $this->stylesheets[] = trim($path, '/');
229 * Register a javascript file path to be included in the <footer> tag of every page.
230 * Inclusion is done in App->initFooter().
231 * The path can be absolute or relative to the Friendica installation base folder.
235 * @param string $path
237 public function registerFooterScript($path)
239 $url = str_replace($this->getBasePath() . DIRECTORY_SEPARATOR, '', $path);
241 $this->footerScripts[] = trim($url, '/');
247 * @brief App constructor.
249 * @param Database $database The Friendica Database
250 * @param Configuration $config The Configuration
251 * @param App\Mode $mode The mode of this Friendica app
252 * @param App\Router $router The router of this Friendica app
253 * @param BaseURL $baseURL The full base URL of this Friendica app
254 * @param LoggerInterface $logger The current app logger
255 * @param Profiler $profiler The profiler of this application
256 * @param bool $isBackend Whether it is used for backend or frontend (Default true=backend)
258 * @throws Exception if the Basepath is not usable
260 public function __construct(Database $database, Configuration $config, App\Mode $mode, App\Router $router, BaseURL $baseURL, LoggerInterface $logger, Profiler $profiler, $isBackend = true)
262 BaseObject::setApp($this);
264 $this->database = $database;
265 $this->config = $config;
267 $this->router = $router;
268 $this->baseURL = $baseURL;
269 $this->profiler = $profiler;
270 $this->logger = $logger;
272 $this->profiler->reset();
278 // This has to be quite large to deal with embedded private photos
279 ini_set('pcre.backtrack_limit', 500000);
282 get_include_path() . PATH_SEPARATOR
283 . $this->getBasePath() . DIRECTORY_SEPARATOR . 'include' . PATH_SEPARATOR
284 . $this->getBasePath() . DIRECTORY_SEPARATOR . 'library' . PATH_SEPARATOR
285 . $this->getBasePath());
287 if (!empty($_SERVER['QUERY_STRING']) && strpos($_SERVER['QUERY_STRING'], 'pagename=') === 0) {
288 $this->query_string = substr($_SERVER['QUERY_STRING'], 9);
289 } elseif (!empty($_SERVER['QUERY_STRING']) && strpos($_SERVER['QUERY_STRING'], 'q=') === 0) {
290 $this->query_string = substr($_SERVER['QUERY_STRING'], 2);
293 // removing trailing / - maybe a nginx problem
294 $this->query_string = ltrim($this->query_string, '/');
296 if (!empty($_GET['pagename'])) {
297 $this->cmd = trim($_GET['pagename'], '/\\');
298 } elseif (!empty($_GET['q'])) {
299 $this->cmd = trim($_GET['q'], '/\\');
303 $this->query_string = str_replace($this->cmd . '&', $this->cmd . '?', $this->query_string);
305 // unix style "homedir"
306 if (substr($this->cmd, 0, 1) === '~') {
307 $this->cmd = 'profile/' . substr($this->cmd, 1);
310 // Diaspora style profile url
311 if (substr($this->cmd, 0, 2) === 'u/') {
312 $this->cmd = 'profile/' . substr($this->cmd, 2);
316 * Break the URL path into C style argc/argv style arguments for our
317 * modules. Given "http://example.com/module/arg1/arg2", $this->argc
318 * will be 3 (integer) and $this->argv will contain:
324 * There will always be one argument. If provided a naked domain
325 * URL, $this->argv[0] is set to "home".
328 $this->argv = explode('/', $this->cmd);
329 $this->argc = count($this->argv);
330 if ((array_key_exists('0', $this->argv)) && strlen($this->argv[0])) {
331 $this->module = str_replace('.', '_', $this->argv[0]);
332 $this->module = str_replace('-', '_', $this->module);
335 $this->argv = ['home'];
336 $this->module = 'home';
339 $this->isBackend = $isBackend || $this->checkBackend($this->module);
341 // Detect mobile devices
342 $mobile_detect = new MobileDetect();
344 $this->mobileDetect = $mobile_detect;
346 $this->is_mobile = $mobile_detect->isMobile();
347 $this->is_tablet = $mobile_detect->isTablet();
349 $this->isAjax = strtolower(defaults($_SERVER, 'HTTP_X_REQUESTED_WITH', '')) == 'xmlhttprequest';
351 // Register template engines
352 Core\Renderer::registerTemplateEngine('Friendica\Render\FriendicaSmartyEngine');
356 * Reloads the whole app instance
358 public function reload()
360 $this->getMode()->determine($this->getBasePath());
362 if ($this->getMode()->has(App\Mode::DBAVAILABLE)) {
363 $loader = new ConfigFileLoader($this->getBasePath(), $this->getMode());
364 $this->config->getCache()->load($loader->loadCoreConfig('addon'), true);
366 $this->profiler->update(
367 $this->config->get('system', 'profiler', false),
368 $this->config->get('rendertime', 'callstack', false));
370 Core\Hook::loadHooks();
371 $loader = new ConfigFileLoader($this->getBasePath(), $this->mode);
372 Core\Hook::callAll('load_config', $loader);
375 $this->loadDefaultTimezone();
381 * Loads the default timezone
383 * Include support for legacy $default_timezone
385 * @global string $default_timezone
387 private function loadDefaultTimezone()
389 if ($this->config->get('system', 'default_timezone')) {
390 $this->timezone = $this->config->get('system', 'default_timezone');
392 global $default_timezone;
393 $this->timezone = !empty($default_timezone) ? $default_timezone : 'UTC';
396 if ($this->timezone) {
397 date_default_timezone_set($this->timezone);
402 * Returns the scheme of the current call
405 * @deprecated 2019.06 - use BaseURL->getScheme() instead
407 public function getScheme()
409 return $this->baseURL->getScheme();
413 * Retrieves the Friendica instance base URL
415 * @param bool $ssl Whether to append http or https under BaseURL::SSL_POLICY_SELFSIGN
417 * @return string Friendica server base URL
419 public function getBaseURL($ssl = false)
421 return $this->baseURL->get($ssl);
425 * @brief Initializes the baseurl components
427 * Clears the baseurl cache to prevent inconsistencies
431 * @deprecated 2019.06 - use BaseURL->saveByURL($url) instead
433 public function setBaseURL($url)
435 $this->baseURL->saveByURL($url);
439 * Returns the current hostname
443 * @deprecated 2019.06 - use BaseURL->getHostname() instead
445 public function getHostName()
447 return $this->baseURL->getHostname();
451 * Returns the sub-path of the full URL
455 * @deprecated 2019.06 - use BaseURL->getUrlPath() instead
457 public function getURLPath()
459 return $this->baseURL->getUrlPath();
463 * Initializes App->page['htmlhead'].
468 * - Registered stylesheets (through App->registerStylesheet())
469 * - Infinite scroll data
470 * - head.tpl template
472 public function initHead()
474 $interval = ((local_user()) ? Core\PConfig::get(local_user(), 'system', 'update_interval') : 40000);
476 // If the update is 'deactivated' set it to the highest integer number (~24 days)
478 $interval = 2147483647;
481 if ($interval < 10000) {
485 // Default title: current module called
486 if (empty($this->page['title']) && $this->module) {
487 $this->page['title'] = ucfirst($this->module);
490 // Prepend the sitename to the page title
491 $this->page['title'] = $this->config->get('config', 'sitename', '') . (!empty($this->page['title']) ? ' | ' . $this->page['title'] : '');
493 if (!empty(Core\Renderer::$theme['stylesheet'])) {
494 $stylesheet = Core\Renderer::$theme['stylesheet'];
496 $stylesheet = $this->getCurrentThemeStylesheetPath();
499 $this->registerStylesheet($stylesheet);
501 $shortcut_icon = $this->config->get('system', 'shortcut_icon');
502 if ($shortcut_icon == '') {
503 $shortcut_icon = 'images/friendica-32.png';
506 $touch_icon = $this->config->get('system', 'touch_icon');
507 if ($touch_icon == '') {
508 $touch_icon = 'images/friendica-128.png';
511 Core\Hook::callAll('head', $this->page['htmlhead']);
513 $tpl = Core\Renderer::getMarkupTemplate('head.tpl');
514 /* put the head template at the beginning of page['htmlhead']
515 * since the code added by the modules frequently depends on it
518 $this->page['htmlhead'] = Core\Renderer::replaceMacros($tpl, [
519 '$local_user' => local_user(),
520 '$generator' => 'Friendica' . ' ' . FRIENDICA_VERSION,
521 '$delitem' => Core\L10n::t('Delete this item?'),
522 '$update_interval' => $interval,
523 '$shortcut_icon' => $shortcut_icon,
524 '$touch_icon' => $touch_icon,
525 '$block_public' => intval($this->config->get('system', 'block_public')),
526 '$stylesheets' => $this->stylesheets,
527 ]) . $this->page['htmlhead'];
531 * Initializes App->page['footer'].
534 * - Javascript homebase
535 * - Mobile toggle link
536 * - Registered footer scripts (through App->registerFooterScript())
537 * - footer.tpl template
539 public function initFooter()
541 // If you're just visiting, let javascript take you home
542 if (!empty($_SESSION['visitor_home'])) {
543 $homebase = $_SESSION['visitor_home'];
544 } elseif (local_user()) {
545 $homebase = 'profile/' . $this->user['nickname'];
548 if (isset($homebase)) {
549 $this->page['footer'] .= '<script>var homebase="' . $homebase . '";</script>' . "\n";
553 * Add a "toggle mobile" link if we're using a mobile device
555 if ($this->is_mobile || $this->is_tablet) {
556 if (isset($_SESSION['show-mobile']) && !$_SESSION['show-mobile']) {
557 $link = 'toggle_mobile?address=' . urlencode(curPageURL());
559 $link = 'toggle_mobile?off=1&address=' . urlencode(curPageURL());
561 $this->page['footer'] .= Core\Renderer::replaceMacros(Core\Renderer::getMarkupTemplate("toggle_mobile_footer.tpl"), [
562 '$toggle_link' => $link,
563 '$toggle_text' => Core\L10n::t('toggle mobile')
567 Core\Hook::callAll('footer', $this->page['footer']);
569 $tpl = Core\Renderer::getMarkupTemplate('footer.tpl');
570 $this->page['footer'] = Core\Renderer::replaceMacros($tpl, [
571 '$footerScripts' => $this->footerScripts,
572 ]) . $this->page['footer'];
576 * @brief Removes the base url from an url. This avoids some mixed content problems.
578 * @param string $origURL
580 * @return string The cleaned url
581 * @throws HTTPException\InternalServerErrorException
583 public function removeBaseURL($origURL)
585 // Remove the hostname from the url if it is an internal link
586 $nurl = Util\Strings::normaliseLink($origURL);
587 $base = Util\Strings::normaliseLink($this->getBaseURL());
588 $url = str_replace($base . '/', '', $nurl);
590 // if it is an external link return the orignal value
591 if ($url == Util\Strings::normaliseLink($origURL)) {
599 * Returns the current UserAgent as a String
601 * @return string the UserAgent as a String
602 * @throws HTTPException\InternalServerErrorException
604 public function getUserAgent()
607 FRIENDICA_PLATFORM . " '" .
608 FRIENDICA_CODENAME . "' " .
609 FRIENDICA_VERSION . '-' .
610 DB_UPDATE_VERSION . '; ' .
615 * @brief Checks if the site is called via a backend process
617 * This isn't a perfect solution. But we need this check very early.
618 * So we cannot wait until the modules are loaded.
620 * @param string $module
623 private function checkBackend($module) {
652 // Check if current module is in backend or backend flag is set
653 return in_array($module, $backends);
657 * Returns true, if the call is from a backend node (f.e. from a worker)
659 * @return bool Is it a known backend?
661 public function isBackend()
663 return $this->isBackend;
667 * @brief Checks if the maximum number of database processes is reached
669 * @return bool Is the limit reached?
671 public function isMaxProcessesReached()
673 // Deactivated, needs more investigating if this check really makes sense
677 * Commented out to suppress static analyzer issues
679 if ($this->is_backend()) {
680 $process = 'backend';
681 $max_processes = $this->config->get('system', 'max_processes_backend');
682 if (intval($max_processes) == 0) {
686 $process = 'frontend';
687 $max_processes = $this->config->get('system', 'max_processes_frontend');
688 if (intval($max_processes) == 0) {
693 $processlist = DBA::processlist();
694 if ($processlist['list'] != '') {
695 Core\Logger::log('Processcheck: Processes: ' . $processlist['amount'] . ' - Processlist: ' . $processlist['list'], Core\Logger::DEBUG);
697 if ($processlist['amount'] > $max_processes) {
698 Core\Logger::log('Processcheck: Maximum number of processes for ' . $process . ' tasks (' . $max_processes . ') reached.', Core\Logger::DEBUG);
707 * @brief Checks if the minimal memory is reached
709 * @return bool Is the memory limit reached?
710 * @throws HTTPException\InternalServerErrorException
712 public function isMinMemoryReached()
714 $min_memory = $this->config->get('system', 'min_memory', 0);
715 if ($min_memory == 0) {
719 if (!is_readable('/proc/meminfo')) {
723 $memdata = explode("\n", file_get_contents('/proc/meminfo'));
726 foreach ($memdata as $line) {
727 $data = explode(':', $line);
728 if (count($data) != 2) {
731 list($key, $val) = $data;
732 $meminfo[$key] = (int) trim(str_replace('kB', '', $val));
733 $meminfo[$key] = (int) ($meminfo[$key] / 1024);
736 if (!isset($meminfo['MemFree'])) {
740 $free = $meminfo['MemFree'];
742 $reached = ($free < $min_memory);
745 Core\Logger::log('Minimal memory reached: ' . $free . '/' . $meminfo['MemTotal'] . ' - limit ' . $min_memory, Core\Logger::DEBUG);
752 * @brief Checks if the maximum load is reached
754 * @return bool Is the load reached?
755 * @throws HTTPException\InternalServerErrorException
757 public function isMaxLoadReached()
759 if ($this->isBackend()) {
760 $process = 'backend';
761 $maxsysload = intval($this->config->get('system', 'maxloadavg'));
762 if ($maxsysload < 1) {
766 $process = 'frontend';
767 $maxsysload = intval($this->config->get('system', 'maxloadavg_frontend'));
768 if ($maxsysload < 1) {
773 $load = Core\System::currentLoad();
775 if (intval($load) > $maxsysload) {
776 Core\Logger::log('system: load ' . $load . ' for ' . $process . ' tasks (' . $maxsysload . ') too high.');
784 * Executes a child process with 'proc_open'
786 * @param string $command The command to execute
787 * @param array $args Arguments to pass to the command ( [ 'key' => value, 'key2' => value2, ... ]
788 * @throws HTTPException\InternalServerErrorException
790 public function proc_run($command, $args)
792 if (!function_exists('proc_open')) {
796 $cmdline = $this->config->get('config', 'php_path', 'php') . ' ' . escapeshellarg($command);
798 foreach ($args as $key => $value) {
799 if (!is_null($value) && is_bool($value) && !$value) {
803 $cmdline .= ' --' . $key;
804 if (!is_null($value) && !is_bool($value)) {
805 $cmdline .= ' ' . $value;
809 if ($this->isMinMemoryReached()) {
813 if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
814 $resource = proc_open('cmd /c start /b ' . $cmdline, [], $foo, $this->getBasePath());
816 $resource = proc_open($cmdline . ' &', [], $foo, $this->getBasePath());
818 if (!is_resource($resource)) {
819 Core\Logger::log('We got no resource for command ' . $cmdline, Core\Logger::DEBUG);
822 proc_close($resource);
826 * Generates the site's default sender email address
829 * @throws HTTPException\InternalServerErrorException
831 public function getSenderEmailAddress()
833 $sender_email = $this->config->get('config', 'sender_email');
834 if (empty($sender_email)) {
835 $hostname = $this->baseURL->getHostname();
836 if (strpos($hostname, ':')) {
837 $hostname = substr($hostname, 0, strpos($hostname, ':'));
840 $sender_email = 'noreply@' . $hostname;
843 return $sender_email;
847 * Returns the current theme name.
849 * @return string the name of the current theme
850 * @throws HTTPException\InternalServerErrorException
852 public function getCurrentTheme()
854 if ($this->getMode()->isInstall()) {
858 if (!$this->currentTheme) {
859 $this->computeCurrentTheme();
862 return $this->currentTheme;
865 public function setCurrentTheme($theme)
867 $this->currentTheme = $theme;
871 * Computes the current theme name based on the node settings, the user settings and the device type
875 private function computeCurrentTheme()
877 $system_theme = $this->config->get('system', 'theme');
878 if (!$system_theme) {
879 throw new Exception(Core\L10n::t('No system theme config value set.'));
883 $this->currentTheme = $system_theme;
886 // Find the theme that belongs to the user whose stuff we are looking at
887 if ($this->profile_uid && ($this->profile_uid != local_user())) {
888 // Allow folks to override user themes and always use their own on their own site.
889 // This works only if the user is on the same server
890 $user = DBA::selectFirst('user', ['theme'], ['uid' => $this->profile_uid]);
891 if (DBA::isResult($user) && !Core\PConfig::get(local_user(), 'system', 'always_my_theme')) {
892 $page_theme = $user['theme'];
896 $user_theme = Core\Session::get('theme', $system_theme);
898 // Specific mobile theme override
899 if (($this->is_mobile || $this->is_tablet) && Core\Session::get('show-mobile', true)) {
900 $system_mobile_theme = $this->config->get('system', 'mobile-theme');
901 $user_mobile_theme = Core\Session::get('mobile-theme', $system_mobile_theme);
903 // --- means same mobile theme as desktop
904 if (!empty($user_mobile_theme) && $user_mobile_theme !== '---') {
905 $user_theme = $user_mobile_theme;
910 $theme_name = $page_theme;
912 $theme_name = $user_theme;
915 $theme_name = Strings::sanitizeFilePathItem($theme_name);
917 && in_array($theme_name, Theme::getAllowedList())
918 && (file_exists('view/theme/' . $theme_name . '/style.css')
919 || file_exists('view/theme/' . $theme_name . '/style.php'))
921 $this->currentTheme = $theme_name;
926 * @brief Return full URL to theme which is currently in effect.
928 * Provide a sane default if nothing is chosen or the specified theme does not exist.
931 * @throws HTTPException\InternalServerErrorException
933 public function getCurrentThemeStylesheetPath()
935 return Core\Theme::getStylesheetPath($this->getCurrentTheme());
939 * Check if request was an AJAX (xmlhttprequest) request.
941 * @return boolean true if it was an AJAX request
943 public function isAjax()
945 return $this->isAjax;
949 * Returns the value of a argv key
950 * TODO there are a lot of $a->argv usages in combination with defaults() which can be replaced with this method
952 * @param int $position the position of the argument
953 * @param mixed $default the default value if not found
955 * @return mixed returns the value of the argument
957 public function getArgumentValue($position, $default = '')
959 if (array_key_exists($position, $this->argv)) {
960 return $this->argv[$position];
967 * Sets the base url for use in cmdline programs which don't have
970 public function checkURL()
972 $url = $this->config->get('system', 'url');
974 // if the url isn't set or the stored url is radically different
975 // than the currently visited url, store the current value accordingly.
976 // "Radically different" ignores common variations such as http vs https
977 // and www.example.com vs example.com.
978 // We will only change the url to an ip address if there is no existing setting
980 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()))) {
981 $this->config->set('system', 'url', $this->getBaseURL());
986 * Frontend App script
988 * The App object behaves like a container and a dispatcher at the same time, including a representation of the
989 * request and a representation of the response.
991 * This probably should change to limit the size of this monster method.
993 public function runFrontend()
995 // Missing DB connection: ERROR
996 if ($this->getMode()->has(App\Mode::LOCALCONFIGPRESENT) && !$this->getMode()->has(App\Mode::DBAVAILABLE)) {
997 Module\Special\HTTPException::rawContent(
998 new HTTPException\InternalServerErrorException('Apologies but the website is unavailable at the moment.')
1002 // Max Load Average reached: ERROR
1003 if ($this->isMaxProcessesReached() || $this->isMaxLoadReached()) {
1004 header('Retry-After: 120');
1005 header('Refresh: 120; url=' . $this->getBaseURL() . "/" . $this->query_string);
1007 Module\Special\HTTPException::rawContent(
1008 new HTTPException\ServiceUnavailableException('The node is currently overloaded. Please try again later.')
1012 if (!$this->getMode()->isInstall()) {
1013 // Force SSL redirection
1014 if ($this->baseURL->checkRedirectHttps()) {
1015 header('HTTP/1.1 302 Moved Temporarily');
1016 header('Location: ' . $this->getBaseURL() . '/' . $this->query_string);
1020 Core\Session::init();
1021 Core\Hook::callAll('init_1');
1024 // Exclude the backend processes from the session management
1025 if (!$this->isBackend()) {
1026 $stamp1 = microtime(true);
1028 $this->profiler->saveTimestamp($stamp1, 'parser', Core\System::callstack());
1029 Core\L10n::setSessionVariable();
1030 Core\L10n::setLangFromSession();
1033 Core\Worker::executeIfIdle();
1036 if ($this->getMode()->isNormal()) {
1037 $requester = HTTPSignature::getSigner('', $_SERVER);
1038 if (!empty($requester)) {
1039 Profile::addVisitorCookieForHandle($requester);
1044 if (!empty($_GET['zrl']) && $this->getMode()->isNormal()) {
1045 $this->query_string = Model\Profile::stripZrls($this->query_string);
1046 if (!local_user()) {
1047 // Only continue when the given profile link seems valid
1048 // Valid profile links contain a path with "/profile/" and no query parameters
1049 if ((parse_url($_GET['zrl'], PHP_URL_QUERY) == "") &&
1050 strstr(parse_url($_GET['zrl'], PHP_URL_PATH), "/profile/")) {
1051 if (Core\Session::get('visitor_home') != $_GET["zrl"]) {
1052 Core\Session::set('my_url', $_GET['zrl']);
1053 Core\Session::set('authenticated', 0);
1056 Model\Profile::zrlInit($this);
1058 // Someone came with an invalid parameter, maybe as a DDoS attempt
1059 // We simply stop processing here
1060 Core\Logger::log("Invalid ZRL parameter " . $_GET['zrl'], Core\Logger::DEBUG);
1061 Module\Special\HTTPException::rawContent(
1062 new HTTPException\ForbiddenException()
1068 if (!empty($_GET['owt']) && $this->getMode()->isNormal()) {
1069 $token = $_GET['owt'];
1070 $this->query_string = Model\Profile::stripQueryParam($this->query_string, 'owt');
1071 Model\Profile::openWebAuthInit($token);
1074 Module\Login::sessionAuth();
1076 if (empty($_SESSION['authenticated'])) {
1077 header('X-Account-Management-Status: none');
1080 $_SESSION['sysmsg'] = Core\Session::get('sysmsg', []);
1081 $_SESSION['sysmsg_info'] = Core\Session::get('sysmsg_info', []);
1082 $_SESSION['last_updated'] = Core\Session::get('last_updated', []);
1085 * check_config() is responsible for running update scripts. These automatically
1086 * update the DB schema whenever we push a new one out. It also checks to see if
1087 * any addons have been added or removed and reacts accordingly.
1090 // in install mode, any url loads install module
1091 // but we need "view" module for stylesheet
1092 if ($this->getMode()->isInstall() && $this->module !== 'install') {
1093 $this->internalRedirect('install');
1094 } elseif (!$this->getMode()->isInstall() && !$this->getMode()->has(App\Mode::MAINTENANCEDISABLED) && $this->module !== 'maintenance') {
1095 $this->internalRedirect('maintenance');
1098 Core\Update::check($this->getBasePath(), false, $this->getMode());
1099 Core\Addon::loadAddons();
1100 Core\Hook::loadHooks();
1111 'right_aside' => '',
1116 // Compatibility with the Android Diaspora client
1117 if ($this->module == 'stream') {
1118 $this->internalRedirect('network?order=post');
1121 if ($this->module == 'conversations') {
1122 $this->internalRedirect('message');
1125 if ($this->module == 'commented') {
1126 $this->internalRedirect('network?order=comment');
1129 if ($this->module == 'liked') {
1130 $this->internalRedirect('network?order=comment');
1133 if ($this->module == 'activity') {
1134 $this->internalRedirect('network?conv=1');
1137 if (($this->module == 'status_messages') && ($this->cmd == 'status_messages/new')) {
1138 $this->internalRedirect('bookmarklet');
1141 if (($this->module == 'user') && ($this->cmd == 'user/edit')) {
1142 $this->internalRedirect('settings');
1145 if (($this->module == 'tag_followings') && ($this->cmd == 'tag_followings/manage')) {
1146 $this->internalRedirect('search');
1149 // Compatibility with the Firefox App
1150 if (($this->module == "users") && ($this->cmd == "users/sign_in")) {
1151 $this->module = "login";
1157 * From the request URL, routing consists of obtaining the name of a BaseModule-extending class of which the
1158 * post() and/or content() static methods can be respectively called to produce a data change or an output.
1161 // First we try explicit routes defined in App\Router
1162 $this->router->collectRoutes();
1164 $data = $this->router->getRouteCollector();
1165 Hook::callAll('route_collection', $data);
1167 $this->module_class = $this->router->getModuleClass($this->cmd);
1169 // Then we try addon-provided modules that we wrap in the LegacyModule class
1170 if (!$this->module_class && Core\Addon::isEnabled($this->module) && file_exists("addon/{$this->module}/{$this->module}.php")) {
1171 //Check if module is an app and if public access to apps is allowed or not
1172 $privateapps = $this->config->get('config', 'private_addons', false);
1173 if ((!local_user()) && Core\Hook::isAddonApp($this->module) && $privateapps) {
1174 info(Core\L10n::t("You must be logged in to use addons. "));
1176 include_once "addon/{$this->module}/{$this->module}.php";
1177 if (function_exists($this->module . '_module')) {
1178 LegacyModule::setModuleFile("addon/{$this->module}/{$this->module}.php");
1179 $this->module_class = LegacyModule::class;
1184 /* Finally, we look for a 'standard' program module in the 'mod' directory
1185 * We emulate a Module class through the LegacyModule class
1187 if (!$this->module_class && file_exists("mod/{$this->module}.php")) {
1188 LegacyModule::setModuleFile("mod/{$this->module}.php");
1189 $this->module_class = LegacyModule::class;
1192 /* The URL provided does not resolve to a valid module.
1194 * On Dreamhost sites, quite often things go wrong for no apparent reason and they send us to '/internal_error.html'.
1195 * We don't like doing this, but as it occasionally accounts for 10-20% or more of all site traffic -
1196 * 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
1197 * this will often succeed and eventually do the right thing.
1199 * Otherwise we are going to emit a 404 not found.
1201 if (!$this->module_class) {
1202 // Stupid browser tried to pre-fetch our Javascript img template. Don't log the event or return anything - just quietly exit.
1203 if (!empty($_SERVER['QUERY_STRING']) && preg_match('/{[0-9]}/', $_SERVER['QUERY_STRING']) !== 0) {
1207 if (!empty($_SERVER['QUERY_STRING']) && ($_SERVER['QUERY_STRING'] === 'q=internal_error.html') && isset($dreamhost_error_hack)) {
1208 Core\Logger::log('index.php: dreamhost_error_hack invoked. Original URI =' . $_SERVER['REQUEST_URI']);
1209 $this->internalRedirect($_SERVER['REQUEST_URI']);
1212 Core\Logger::log('index.php: page not found: ' . $_SERVER['REQUEST_URI'] . ' ADDRESS: ' . $_SERVER['REMOTE_ADDR'] . ' QUERY: ' . $_SERVER['QUERY_STRING'], Core\Logger::DEBUG);
1214 $this->module_class = Module\PageNotFound::class;
1217 // Initialize module that can set the current theme in the init() method, either directly or via App->profile_uid
1218 $this->page['page_title'] = $this->module;
1222 Core\Hook::callAll($this->module . '_mod_init', $placeholder);
1224 call_user_func([$this->module_class, 'init']);
1226 // "rawContent" is especially meant for technical endpoints.
1227 // This endpoint doesn't need any theme initialization or other comparable stuff.
1228 call_user_func([$this->module_class, 'rawContent']);
1230 // Load current theme info after module has been initialized as theme could have been set in module
1231 $theme_info_file = 'view/theme/' . $this->getCurrentTheme() . '/theme.php';
1232 if (file_exists($theme_info_file)) {
1233 require_once $theme_info_file;
1236 if (function_exists(str_replace('-', '_', $this->getCurrentTheme()) . '_init')) {
1237 $func = str_replace('-', '_', $this->getCurrentTheme()) . '_init';
1241 if ($_SERVER['REQUEST_METHOD'] === 'POST') {
1242 Core\Hook::callAll($this->module . '_mod_post', $_POST);
1243 call_user_func([$this->module_class, 'post']);
1246 Core\Hook::callAll($this->module . '_mod_afterpost', $placeholder);
1247 call_user_func([$this->module_class, 'afterpost']);
1248 } catch(HTTPException $e) {
1249 Module\Special\HTTPException::rawContent($e);
1255 $arr = ['content' => $content];
1256 Core\Hook::callAll($this->module . '_mod_content', $arr);
1257 $content = $arr['content'];
1258 $arr = ['content' => call_user_func([$this->module_class, 'content'])];
1259 Core\Hook::callAll($this->module . '_mod_aftercontent', $arr);
1260 $content .= $arr['content'];
1261 } catch(HTTPException $e) {
1262 $content = Module\Special\HTTPException::content($e);
1265 // initialise content region
1266 if ($this->getMode()->isNormal()) {
1267 Core\Hook::callAll('page_content_top', $this->page['content']);
1270 $this->page['content'] .= $content;
1272 /* Create the page head after setting the language
1273 * and getting any auth credentials.
1275 * Moved initHead() and initFooter() to after
1276 * all the module functions have executed so that all
1277 * theme choices made by the modules can take effect.
1281 /* Build the page ending -- this is stuff that goes right before
1282 * the closing </body> tag
1284 $this->initFooter();
1286 if (!$this->isAjax()) {
1287 Core\Hook::callAll('page_end', $this->page['content']);
1290 // Add the navigation (menu) template
1291 if ($this->module != 'install' && $this->module != 'maintenance') {
1292 $this->page['htmlhead'] .= Core\Renderer::replaceMacros(Core\Renderer::getMarkupTemplate('nav_head.tpl'), []);
1293 $this->page['nav'] = Content\Nav::build($this);
1296 // Build the page - now that we have all the components
1297 if (isset($_GET["mode"]) && (($_GET["mode"] == "raw") || ($_GET["mode"] == "minimal"))) {
1298 $doc = new DOMDocument();
1300 $target = new DOMDocument();
1301 $target->loadXML("<root></root>");
1303 $content = mb_convert_encoding($this->page["content"], 'HTML-ENTITIES', "UTF-8");
1305 /// @TODO one day, kill those error-surpressing @ stuff, or PHP should ban it
1306 @$doc->loadHTML($content);
1308 $xpath = new DOMXPath($doc);
1310 $list = $xpath->query("//*[contains(@id,'tread-wrapper-')]"); /* */
1312 foreach ($list as $item) {
1313 $item = $target->importNode($item, true);
1315 // And then append it to the target
1316 $target->documentElement->appendChild($item);
1319 if ($_GET["mode"] == "raw") {
1320 header("Content-type: text/html; charset=utf-8");
1322 echo substr($target->saveHTML(), 6, -8);
1328 $page = $this->page;
1329 $profile = $this->profile;
1331 header("X-Friendica-Version: " . FRIENDICA_VERSION);
1332 header("Content-type: text/html; charset=utf-8");
1334 if ($this->config->get('system', 'hsts') && ($this->baseURL->getSSLPolicy() == BaseUrl::SSL_POLICY_FULL)) {
1335 header("Strict-Transport-Security: max-age=31536000");
1338 // Some security stuff
1339 header('X-Content-Type-Options: nosniff');
1340 header('X-XSS-Protection: 1; mode=block');
1341 header('X-Permitted-Cross-Domain-Policies: none');
1342 header('X-Frame-Options: sameorigin');
1344 // Things like embedded OSM maps don't work, when this is enabled
1345 // 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'");
1347 /* We use $_GET["mode"] for special page templates. So we will check if we have
1348 * to load another page template than the default one.
1349 * The page templates are located in /view/php/ or in the theme directory.
1351 if (isset($_GET["mode"])) {
1352 $template = Core\Theme::getPathForFile($_GET["mode"] . '.php');
1355 // If there is no page template use the default page template
1356 if (empty($template)) {
1357 $template = Core\Theme::getPathForFile("default.php");
1360 // Theme templates expect $a as an App instance
1363 // Used as is in view/php/default.php
1364 $lang = Core\L10n::getCurrentLang();
1366 /// @TODO Looks unsafe (remote-inclusion), is maybe not but Core\Theme::getPathForFile() uses file_exists() but does not escape anything
1367 require_once $template;
1371 * Redirects to another module relative to the current Friendica base.
1372 * If you want to redirect to a external URL, use System::externalRedirectTo()
1374 * @param string $toUrl The destination URL (Default is empty, which is the default page of the Friendica node)
1375 * @param bool $ssl if true, base URL will try to get called with https:// (works just for relative paths)
1377 * @throws HTTPException\InternalServerErrorException In Case the given URL is not relative to the Friendica node
1379 public function internalRedirect($toUrl = '', $ssl = false)
1381 if (!empty(parse_url($toUrl, PHP_URL_SCHEME))) {
1382 throw new HTTPException\InternalServerErrorException("'$toUrl is not a relative path, please use System::externalRedirectTo");
1385 $redirectTo = $this->getBaseURL($ssl) . '/' . ltrim($toUrl, '/');
1386 Core\System::externalRedirect($redirectTo);
1390 * Automatically redirects to relative or absolute URL
1391 * Should only be used if it isn't clear if the URL is either internal or external
1393 * @param string $toUrl The target URL
1394 * @throws HTTPException\InternalServerErrorException
1396 public function redirect($toUrl)
1398 if (!empty(parse_url($toUrl, PHP_URL_SCHEME))) {
1399 Core\System::externalRedirect($toUrl);
1401 $this->internalRedirect($toUrl);