7 use Detection\MobileDetect;
11 use Friendica\Core\Config\Cache\IConfigCache;
12 use Friendica\Core\Config\Configuration;
13 use Friendica\Core\Hook;
14 use Friendica\Core\Theme;
15 use Friendica\Database\DBA;
16 use Friendica\Model\Profile;
17 use Friendica\Network\HTTPException;
18 use Friendica\Util\BaseURL;
19 use Friendica\Util\Config\ConfigFileLoader;
20 use Friendica\Util\HTTPSignature;
21 use Friendica\Util\Profiler;
22 use Friendica\Util\Strings;
23 use Psr\Log\LoggerInterface;
29 * @brief Our main application structure for the life of this page.
31 * Primarily deals with the URL that got us here
32 * and tries to make some sense of it, and
33 * stores our page contents and config storage
34 * and anything else that might need to be passed around
35 * before we spit the page out.
40 public $module_class = null;
41 public $query_string = '';
57 public $interactive = true;
59 public $is_mobile = false;
60 public $is_tablet = false;
61 public $theme_info = [];
63 // Allow themes to control internal parameters
64 // by changing App values in theme.php
66 public $sourcename = '';
67 public $videowidth = 425;
68 public $videoheight = 350;
69 public $force_max_items = 0;
70 public $theme_events_in_profile = true;
72 public $stylesheets = [];
73 public $footerScripts = [];
76 * @var App\Mode The Mode of the Application
91 * @var bool true, if the call is from the Friendica APP, otherwise false
93 private $isFriendicaApp;
96 * @var bool true, if the call is from an backend node (f.e. worker)
101 * @var string The name of the current theme
103 private $currentTheme;
106 * @var bool check if request was an AJAX (xmlhttprequest) request
113 public $mobileDetect;
116 * @var Configuration The config
121 * @var LoggerInterface The logger
126 * @var Profiler The profiler of this app
131 * Returns the current config cache of this node
133 * @return IConfigCache
135 public function getConfigCache()
137 return $this->config->getCache();
141 * Returns the current config of this node
143 * @return Configuration
145 public function getConfig()
147 return $this->config;
151 * The basepath of this app
155 public function getBasePath()
157 return $this->config->get('system', 'basepath');
161 * The Logger of this app
163 * @return LoggerInterface
165 public function getLogger()
167 return $this->logger;
171 * The profiler of this app
175 public function getProfiler()
177 return $this->profiler;
181 * Returns the Mode of the Application
183 * @return App\Mode The Application Mode
185 public function getMode()
191 * Returns the router of the Application
195 public function getRouter()
197 return $this->router;
201 * Register a stylesheet file path to be included in the <head> tag of every page.
202 * Inclusion is done in App->initHead().
203 * The path can be absolute or relative to the Friendica installation base folder.
207 * @param string $path
209 public function registerStylesheet($path)
211 if (mb_strpos($path, $this->getBasePath() . DIRECTORY_SEPARATOR) === 0) {
212 $path = mb_substr($path, mb_strlen($this->getBasePath() . DIRECTORY_SEPARATOR));
215 $this->stylesheets[] = trim($path, '/');
219 * Register a javascript file path to be included in the <footer> tag of every page.
220 * Inclusion is done in App->initFooter().
221 * The path can be absolute or relative to the Friendica installation base folder.
225 * @param string $path
227 public function registerFooterScript($path)
229 $url = str_replace($this->getBasePath() . DIRECTORY_SEPARATOR, '', $path);
231 $this->footerScripts[] = trim($url, '/');
237 * @brief App constructor.
239 * @param Configuration $config The Configuration
240 * @param App\Mode $mode The mode of this Friendica app
241 * @param App\Router $router The router of this Friendica app
242 * @param BaseURL $baseURL The full base URL of this Friendica app
243 * @param LoggerInterface $logger The current app logger
244 * @param Profiler $profiler The profiler of this application
245 * @param bool $isBackend Whether it is used for backend or frontend (Default true=backend)
247 * @throws Exception if the Basepath is not usable
249 public function __construct(Configuration $config, App\Mode $mode, App\Router $router, BaseURL $baseURL, LoggerInterface $logger, Profiler $profiler, $isBackend = true)
251 BaseObject::setApp($this);
253 $this->config = $config;
255 $this->router = $router;
256 $this->baseURL = $baseURL;
257 $this->profiler = $profiler;
258 $this->logger = $logger;
260 $this->checkFriendicaApp();
262 $this->profiler->reset();
268 // This has to be quite large to deal with embedded private photos
269 ini_set('pcre.backtrack_limit', 500000);
272 get_include_path() . PATH_SEPARATOR
273 . $this->getBasePath() . DIRECTORY_SEPARATOR . 'include' . PATH_SEPARATOR
274 . $this->getBasePath() . DIRECTORY_SEPARATOR . 'library' . PATH_SEPARATOR
275 . $this->getBasePath());
277 if (!empty($_SERVER['QUERY_STRING']) && strpos($_SERVER['QUERY_STRING'], 'pagename=') === 0) {
278 $this->query_string = substr($_SERVER['QUERY_STRING'], 9);
279 } elseif (!empty($_SERVER['QUERY_STRING']) && strpos($_SERVER['QUERY_STRING'], 'q=') === 0) {
280 $this->query_string = substr($_SERVER['QUERY_STRING'], 2);
283 // removing trailing / - maybe a nginx problem
284 $this->query_string = ltrim($this->query_string, '/');
286 if (!empty($_GET['pagename'])) {
287 $this->cmd = trim($_GET['pagename'], '/\\');
288 } elseif (!empty($_GET['q'])) {
289 $this->cmd = trim($_GET['q'], '/\\');
293 $this->query_string = str_replace($this->cmd . '&', $this->cmd . '?', $this->query_string);
295 // unix style "homedir"
296 if (substr($this->cmd, 0, 1) === '~') {
297 $this->cmd = 'profile/' . substr($this->cmd, 1);
300 // Diaspora style profile url
301 if (substr($this->cmd, 0, 2) === 'u/') {
302 $this->cmd = 'profile/' . substr($this->cmd, 2);
306 * Break the URL path into C style argc/argv style arguments for our
307 * modules. Given "http://example.com/module/arg1/arg2", $this->argc
308 * will be 3 (integer) and $this->argv will contain:
314 * There will always be one argument. If provided a naked domain
315 * URL, $this->argv[0] is set to "home".
318 $this->argv = explode('/', $this->cmd);
319 $this->argc = count($this->argv);
320 if ((array_key_exists('0', $this->argv)) && strlen($this->argv[0])) {
321 $this->module = str_replace('.', '_', $this->argv[0]);
322 $this->module = str_replace('-', '_', $this->module);
325 $this->argv = ['home'];
326 $this->module = 'home';
329 $this->isBackend = $isBackend || $this->checkBackend($this->module);
331 // Detect mobile devices
332 $mobile_detect = new MobileDetect();
334 $this->mobileDetect = $mobile_detect;
336 $this->is_mobile = $mobile_detect->isMobile();
337 $this->is_tablet = $mobile_detect->isTablet();
339 $this->isAjax = strtolower(defaults($_SERVER, 'HTTP_X_REQUESTED_WITH', '')) == 'xmlhttprequest';
341 // Register template engines
342 Core\Renderer::registerTemplateEngine('Friendica\Render\FriendicaSmartyEngine');
346 * Reloads the whole app instance
348 public function reload()
350 $this->getMode()->determine($this->getBasePath());
352 if ($this->getMode()->has(App\Mode::DBAVAILABLE)) {
353 $loader = new ConfigFileLoader($this->getBasePath(), $this->getMode());
354 $this->config->getCache()->load($loader->loadCoreConfig('addon'), true);
356 $this->profiler->update(
357 $this->config->get('system', 'profiler', false),
358 $this->config->get('rendertime', 'callstack', false));
360 Core\Hook::loadHooks();
361 $loader = new ConfigFileLoader($this->getBasePath(), $this->mode);
362 Core\Hook::callAll('load_config', $loader);
365 $this->loadDefaultTimezone();
371 * Loads the default timezone
373 * Include support for legacy $default_timezone
375 * @global string $default_timezone
377 private function loadDefaultTimezone()
379 if ($this->config->get('system', 'default_timezone')) {
380 $this->timezone = $this->config->get('system', 'default_timezone');
382 global $default_timezone;
383 $this->timezone = !empty($default_timezone) ? $default_timezone : 'UTC';
386 if ($this->timezone) {
387 date_default_timezone_set($this->timezone);
392 * Returns the scheme of the current call
395 * @deprecated 2019.06 - use BaseURL->getScheme() instead
397 public function getScheme()
399 return $this->baseURL->getScheme();
403 * Retrieves the Friendica instance base URL
405 * @param bool $ssl Whether to append http or https under BaseURL::SSL_POLICY_SELFSIGN
407 * @return string Friendica server base URL
409 public function getBaseURL($ssl = false)
411 return $this->baseURL->get($ssl);
415 * @brief Initializes the baseurl components
417 * Clears the baseurl cache to prevent inconsistencies
421 * @deprecated 2019.06 - use BaseURL->saveByURL($url) instead
423 public function setBaseURL($url)
425 $this->baseURL->saveByURL($url);
429 * Returns the current hostname
433 * @deprecated 2019.06 - use BaseURL->getHostname() instead
435 public function getHostName()
437 return $this->baseURL->getHostname();
441 * Returns the sub-path of the full URL
445 * @deprecated 2019.06 - use BaseURL->getUrlPath() instead
447 public function getURLPath()
449 return $this->baseURL->getUrlPath();
453 * Initializes App->page['htmlhead'].
458 * - Registered stylesheets (through App->registerStylesheet())
459 * - Infinite scroll data
460 * - head.tpl template
462 public function initHead()
464 $interval = ((local_user()) ? Core\PConfig::get(local_user(), 'system', 'update_interval') : 40000);
466 // If the update is 'deactivated' set it to the highest integer number (~24 days)
468 $interval = 2147483647;
471 if ($interval < 10000) {
475 // Default title: current module called
476 if (empty($this->page['title']) && $this->module) {
477 $this->page['title'] = ucfirst($this->module);
480 // Prepend the sitename to the page title
481 $this->page['title'] = $this->config->get('config', 'sitename', '') . (!empty($this->page['title']) ? ' | ' . $this->page['title'] : '');
483 if (!empty(Core\Renderer::$theme['stylesheet'])) {
484 $stylesheet = Core\Renderer::$theme['stylesheet'];
486 $stylesheet = $this->getCurrentThemeStylesheetPath();
489 $this->registerStylesheet($stylesheet);
491 $shortcut_icon = $this->config->get('system', 'shortcut_icon');
492 if ($shortcut_icon == '') {
493 $shortcut_icon = 'images/friendica-32.png';
496 $touch_icon = $this->config->get('system', 'touch_icon');
497 if ($touch_icon == '') {
498 $touch_icon = 'images/friendica-128.png';
501 Core\Hook::callAll('head', $this->page['htmlhead']);
503 $tpl = Core\Renderer::getMarkupTemplate('head.tpl');
504 /* put the head template at the beginning of page['htmlhead']
505 * since the code added by the modules frequently depends on it
508 $this->page['htmlhead'] = Core\Renderer::replaceMacros($tpl, [
509 '$local_user' => local_user(),
510 '$generator' => 'Friendica' . ' ' . FRIENDICA_VERSION,
511 '$delitem' => Core\L10n::t('Delete this item?'),
512 '$update_interval' => $interval,
513 '$shortcut_icon' => $shortcut_icon,
514 '$touch_icon' => $touch_icon,
515 '$block_public' => intval($this->config->get('system', 'block_public')),
516 '$stylesheets' => $this->stylesheets,
517 ]) . $this->page['htmlhead'];
521 * Initializes App->page['footer'].
524 * - Javascript homebase
525 * - Mobile toggle link
526 * - Registered footer scripts (through App->registerFooterScript())
527 * - footer.tpl template
529 public function initFooter()
531 // If you're just visiting, let javascript take you home
532 if (!empty($_SESSION['visitor_home'])) {
533 $homebase = $_SESSION['visitor_home'];
534 } elseif (local_user()) {
535 $homebase = 'profile/' . $this->user['nickname'];
538 if (isset($homebase)) {
539 $this->page['footer'] .= '<script>var homebase="' . $homebase . '";</script>' . "\n";
543 * Add a "toggle mobile" link if we're using a mobile device
545 if ($this->is_mobile || $this->is_tablet) {
546 if (isset($_SESSION['show-mobile']) && !$_SESSION['show-mobile']) {
547 $link = 'toggle_mobile?address=' . urlencode(curPageURL());
549 $link = 'toggle_mobile?off=1&address=' . urlencode(curPageURL());
551 $this->page['footer'] .= Core\Renderer::replaceMacros(Core\Renderer::getMarkupTemplate("toggle_mobile_footer.tpl"), [
552 '$toggle_link' => $link,
553 '$toggle_text' => Core\L10n::t('toggle mobile')
557 Core\Hook::callAll('footer', $this->page['footer']);
559 $tpl = Core\Renderer::getMarkupTemplate('footer.tpl');
560 $this->page['footer'] = Core\Renderer::replaceMacros($tpl, [
561 '$footerScripts' => $this->footerScripts,
562 ]) . $this->page['footer'];
566 * @brief Removes the base url from an url. This avoids some mixed content problems.
568 * @param string $origURL
570 * @return string The cleaned url
571 * @throws HTTPException\InternalServerErrorException
573 public function removeBaseURL($origURL)
575 // Remove the hostname from the url if it is an internal link
576 $nurl = Util\Strings::normaliseLink($origURL);
577 $base = Util\Strings::normaliseLink($this->getBaseURL());
578 $url = str_replace($base . '/', '', $nurl);
580 // if it is an external link return the orignal value
581 if ($url == Util\Strings::normaliseLink($origURL)) {
589 * Returns the current UserAgent as a String
591 * @return string the UserAgent as a String
592 * @throws HTTPException\InternalServerErrorException
594 public function getUserAgent()
597 FRIENDICA_PLATFORM . " '" .
598 FRIENDICA_CODENAME . "' " .
599 FRIENDICA_VERSION . '-' .
600 DB_UPDATE_VERSION . '; ' .
605 * Checks, if the call is from the Friendica App
608 * The friendica client has problems with the GUID in the notify. this is some workaround
610 private function checkFriendicaApp()
613 $this->isFriendicaApp = isset($_SERVER['HTTP_USER_AGENT']) && $_SERVER['HTTP_USER_AGENT'] == 'Apache-HttpClient/UNAVAILABLE (java 1.4)';
617 * Is the call via the Friendica app? (not a "normale" call)
619 * @return bool true if it's from the Friendica app
621 public function isFriendicaApp()
623 return $this->isFriendicaApp;
627 * @brief Checks if the site is called via a backend process
629 * This isn't a perfect solution. But we need this check very early.
630 * So we cannot wait until the modules are loaded.
632 * @param string $module
635 private function checkBackend($module) {
664 // Check if current module is in backend or backend flag is set
665 return in_array($module, $backends);
669 * Returns true, if the call is from a backend node (f.e. from a worker)
671 * @return bool Is it a known backend?
673 public function isBackend()
675 return $this->isBackend;
679 * @brief Checks if the maximum number of database processes is reached
681 * @return bool Is the limit reached?
683 public function isMaxProcessesReached()
685 // Deactivated, needs more investigating if this check really makes sense
689 * Commented out to suppress static analyzer issues
691 if ($this->is_backend()) {
692 $process = 'backend';
693 $max_processes = $this->config->get('system', 'max_processes_backend');
694 if (intval($max_processes) == 0) {
698 $process = 'frontend';
699 $max_processes = $this->config->get('system', 'max_processes_frontend');
700 if (intval($max_processes) == 0) {
705 $processlist = DBA::processlist();
706 if ($processlist['list'] != '') {
707 Core\Logger::log('Processcheck: Processes: ' . $processlist['amount'] . ' - Processlist: ' . $processlist['list'], Core\Logger::DEBUG);
709 if ($processlist['amount'] > $max_processes) {
710 Core\Logger::log('Processcheck: Maximum number of processes for ' . $process . ' tasks (' . $max_processes . ') reached.', Core\Logger::DEBUG);
719 * @brief Checks if the minimal memory is reached
721 * @return bool Is the memory limit reached?
722 * @throws HTTPException\InternalServerErrorException
724 public function isMinMemoryReached()
726 $min_memory = $this->config->get('system', 'min_memory', 0);
727 if ($min_memory == 0) {
731 if (!is_readable('/proc/meminfo')) {
735 $memdata = explode("\n", file_get_contents('/proc/meminfo'));
738 foreach ($memdata as $line) {
739 $data = explode(':', $line);
740 if (count($data) != 2) {
743 list($key, $val) = $data;
744 $meminfo[$key] = (int) trim(str_replace('kB', '', $val));
745 $meminfo[$key] = (int) ($meminfo[$key] / 1024);
748 if (!isset($meminfo['MemFree'])) {
752 $free = $meminfo['MemFree'];
754 $reached = ($free < $min_memory);
757 Core\Logger::log('Minimal memory reached: ' . $free . '/' . $meminfo['MemTotal'] . ' - limit ' . $min_memory, Core\Logger::DEBUG);
764 * @brief Checks if the maximum load is reached
766 * @return bool Is the load reached?
767 * @throws HTTPException\InternalServerErrorException
769 public function isMaxLoadReached()
771 if ($this->isBackend()) {
772 $process = 'backend';
773 $maxsysload = intval($this->config->get('system', 'maxloadavg'));
774 if ($maxsysload < 1) {
778 $process = 'frontend';
779 $maxsysload = intval($this->config->get('system', 'maxloadavg_frontend'));
780 if ($maxsysload < 1) {
785 $load = Core\System::currentLoad();
787 if (intval($load) > $maxsysload) {
788 Core\Logger::log('system: load ' . $load . ' for ' . $process . ' tasks (' . $maxsysload . ') too high.');
796 * Executes a child process with 'proc_open'
798 * @param string $command The command to execute
799 * @param array $args Arguments to pass to the command ( [ 'key' => value, 'key2' => value2, ... ]
800 * @throws HTTPException\InternalServerErrorException
802 public function proc_run($command, $args)
804 if (!function_exists('proc_open')) {
808 $cmdline = $this->config->get('config', 'php_path', 'php') . ' ' . escapeshellarg($command);
810 foreach ($args as $key => $value) {
811 if (!is_null($value) && is_bool($value) && !$value) {
815 $cmdline .= ' --' . $key;
816 if (!is_null($value) && !is_bool($value)) {
817 $cmdline .= ' ' . $value;
821 if ($this->isMinMemoryReached()) {
825 if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
826 $resource = proc_open('cmd /c start /b ' . $cmdline, [], $foo, $this->getBasePath());
828 $resource = proc_open($cmdline . ' &', [], $foo, $this->getBasePath());
830 if (!is_resource($resource)) {
831 Core\Logger::log('We got no resource for command ' . $cmdline, Core\Logger::DEBUG);
834 proc_close($resource);
838 * Generates the site's default sender email address
841 * @throws HTTPException\InternalServerErrorException
843 public function getSenderEmailAddress()
845 $sender_email = $this->config->get('config', 'sender_email');
846 if (empty($sender_email)) {
847 $hostname = $this->baseURL->getHostname();
848 if (strpos($hostname, ':')) {
849 $hostname = substr($hostname, 0, strpos($hostname, ':'));
852 $sender_email = 'noreply@' . $hostname;
855 return $sender_email;
859 * Returns the current theme name.
861 * @return string the name of the current theme
862 * @throws HTTPException\InternalServerErrorException
864 public function getCurrentTheme()
866 if ($this->getMode()->isInstall()) {
870 if (!$this->currentTheme) {
871 $this->computeCurrentTheme();
874 return $this->currentTheme;
877 public function setCurrentTheme($theme)
879 $this->currentTheme = $theme;
883 * Computes the current theme name based on the node settings, the user settings and the device type
887 private function computeCurrentTheme()
889 $system_theme = $this->config->get('system', 'theme');
890 if (!$system_theme) {
891 throw new Exception(Core\L10n::t('No system theme config value set.'));
895 $this->currentTheme = $system_theme;
898 // Find the theme that belongs to the user whose stuff we are looking at
899 if ($this->profile_uid && ($this->profile_uid != local_user())) {
900 // Allow folks to override user themes and always use their own on their own site.
901 // This works only if the user is on the same server
902 $user = DBA::selectFirst('user', ['theme'], ['uid' => $this->profile_uid]);
903 if (DBA::isResult($user) && !Core\PConfig::get(local_user(), 'system', 'always_my_theme')) {
904 $page_theme = $user['theme'];
908 $user_theme = Core\Session::get('theme', $system_theme);
910 // Specific mobile theme override
911 if (($this->is_mobile || $this->is_tablet) && Core\Session::get('show-mobile', true)) {
912 $system_mobile_theme = $this->config->get('system', 'mobile-theme');
913 $user_mobile_theme = Core\Session::get('mobile-theme', $system_mobile_theme);
915 // --- means same mobile theme as desktop
916 if (!empty($user_mobile_theme) && $user_mobile_theme !== '---') {
917 $user_theme = $user_mobile_theme;
922 $theme_name = $page_theme;
924 $theme_name = $user_theme;
927 $theme_name = Strings::sanitizeFilePathItem($theme_name);
929 && in_array($theme_name, Theme::getAllowedList())
930 && (file_exists('view/theme/' . $theme_name . '/style.css')
931 || file_exists('view/theme/' . $theme_name . '/style.php'))
933 $this->currentTheme = $theme_name;
938 * @brief Return full URL to theme which is currently in effect.
940 * Provide a sane default if nothing is chosen or the specified theme does not exist.
943 * @throws HTTPException\InternalServerErrorException
945 public function getCurrentThemeStylesheetPath()
947 return Core\Theme::getStylesheetPath($this->getCurrentTheme());
951 * Check if request was an AJAX (xmlhttprequest) request.
953 * @return boolean true if it was an AJAX request
955 public function isAjax()
957 return $this->isAjax;
961 * Returns the value of a argv key
962 * TODO there are a lot of $a->argv usages in combination with defaults() which can be replaced with this method
964 * @param int $position the position of the argument
965 * @param mixed $default the default value if not found
967 * @return mixed returns the value of the argument
969 public function getArgumentValue($position, $default = '')
971 if (array_key_exists($position, $this->argv)) {
972 return $this->argv[$position];
979 * Sets the base url for use in cmdline programs which don't have
982 public function checkURL()
984 $url = $this->config->get('system', 'url');
986 // if the url isn't set or the stored url is radically different
987 // than the currently visited url, store the current value accordingly.
988 // "Radically different" ignores common variations such as http vs https
989 // and www.example.com vs example.com.
990 // We will only change the url to an ip address if there is no existing setting
992 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()))) {
993 $this->config->set('system', 'url', $this->getBaseURL());
998 * Frontend App script
1000 * The App object behaves like a container and a dispatcher at the same time, including a representation of the
1001 * request and a representation of the response.
1003 * This probably should change to limit the size of this monster method.
1005 public function runFrontend()
1007 // Missing DB connection: ERROR
1008 if ($this->getMode()->has(App\Mode::LOCALCONFIGPRESENT) && !$this->getMode()->has(App\Mode::DBAVAILABLE)) {
1009 echo Module\Special\HTTPException::rawContent(
1010 new HTTPException\InternalServerErrorException('Apologies but the website is unavailable at the moment.')
1015 // Max Load Average reached: ERROR
1016 if ($this->isMaxProcessesReached() || $this->isMaxLoadReached()) {
1017 header('Retry-After: 120');
1018 header('Refresh: 120; url=' . $this->getBaseURL() . "/" . $this->query_string);
1020 echo Module\Special\HTTPException::rawContent(
1021 new HTTPException\ServiceUnavaiableException('The node is currently overloaded. Please try again later.')
1026 if (strstr($this->query_string, '.well-known/host-meta') && ($this->query_string != '.well-known/host-meta')) {
1027 echo Module\Special\HTTPException::rawContent(
1028 new HTTPException\NotFoundException()
1033 if (!$this->getMode()->isInstall()) {
1034 // Force SSL redirection
1035 if ($this->baseURL->checkRedirectHttps()) {
1036 header('HTTP/1.1 302 Moved Temporarily');
1037 header('Location: ' . $this->getBaseURL() . '/' . $this->query_string);
1041 Core\Session::init();
1042 Core\Hook::callAll('init_1');
1045 // Exclude the backend processes from the session management
1046 if (!$this->isBackend()) {
1047 $stamp1 = microtime(true);
1049 $this->profiler->saveTimestamp($stamp1, 'parser', Core\System::callstack());
1050 Core\L10n::setSessionVariable();
1051 Core\L10n::setLangFromSession();
1054 Core\Worker::executeIfIdle();
1057 if ($this->getMode()->isNormal()) {
1058 $requester = HTTPSignature::getSigner('', $_SERVER);
1059 if (!empty($requester)) {
1060 Profile::addVisitorCookieForHandle($requester);
1065 if (!empty($_GET['zrl']) && $this->getMode()->isNormal()) {
1066 $this->query_string = Model\Profile::stripZrls($this->query_string);
1067 if (!local_user()) {
1068 // Only continue when the given profile link seems valid
1069 // Valid profile links contain a path with "/profile/" and no query parameters
1070 if ((parse_url($_GET['zrl'], PHP_URL_QUERY) == "") &&
1071 strstr(parse_url($_GET['zrl'], PHP_URL_PATH), "/profile/")) {
1072 if (defaults($_SESSION, "visitor_home", "") != $_GET["zrl"]) {
1073 $_SESSION['my_url'] = $_GET['zrl'];
1074 $_SESSION['authenticated'] = 0;
1076 Model\Profile::zrlInit($this);
1078 // Someone came with an invalid parameter, maybe as a DDoS attempt
1079 // We simply stop processing here
1080 Core\Logger::log("Invalid ZRL parameter " . $_GET['zrl'], Core\Logger::DEBUG);
1081 echo Module\Special\HTTPException::rawContent(
1082 new HTTPException\ForbiddenException()
1089 if (!empty($_GET['owt']) && $this->getMode()->isNormal()) {
1090 $token = $_GET['owt'];
1091 $this->query_string = Model\Profile::stripQueryParam($this->query_string, 'owt');
1092 Model\Profile::openWebAuthInit($token);
1095 Module\Login::sessionAuth();
1097 if (empty($_SESSION['authenticated'])) {
1098 header('X-Account-Management-Status: none');
1101 $_SESSION['sysmsg'] = defaults($_SESSION, 'sysmsg' , []);
1102 $_SESSION['sysmsg_info'] = defaults($_SESSION, 'sysmsg_info' , []);
1103 $_SESSION['last_updated'] = defaults($_SESSION, 'last_updated', []);
1106 * check_config() is responsible for running update scripts. These automatically
1107 * update the DB schema whenever we push a new one out. It also checks to see if
1108 * any addons have been added or removed and reacts accordingly.
1111 // in install mode, any url loads install module
1112 // but we need "view" module for stylesheet
1113 if ($this->getMode()->isInstall() && $this->module != 'view') {
1114 $this->module = 'install';
1115 } elseif (!$this->getMode()->has(App\Mode::MAINTENANCEDISABLED) && $this->module != 'view') {
1116 $this->module = 'maintenance';
1119 Core\Update::check($this->getBasePath(), false, $this->getMode());
1120 Core\Addon::loadAddons();
1121 Core\Hook::loadHooks();
1132 'right_aside' => '',
1137 // Compatibility with the Android Diaspora client
1138 if ($this->module == 'stream') {
1139 $this->internalRedirect('network?f=&order=post');
1142 if ($this->module == 'conversations') {
1143 $this->internalRedirect('message');
1146 if ($this->module == 'commented') {
1147 $this->internalRedirect('network?f=&order=comment');
1150 if ($this->module == 'liked') {
1151 $this->internalRedirect('network?f=&order=comment');
1154 if ($this->module == 'activity') {
1155 $this->internalRedirect('network/?f=&conv=1');
1158 if (($this->module == 'status_messages') && ($this->cmd == 'status_messages/new')) {
1159 $this->internalRedirect('bookmarklet');
1162 if (($this->module == 'user') && ($this->cmd == 'user/edit')) {
1163 $this->internalRedirect('settings');
1166 if (($this->module == 'tag_followings') && ($this->cmd == 'tag_followings/manage')) {
1167 $this->internalRedirect('search');
1170 // Compatibility with the Firefox App
1171 if (($this->module == "users") && ($this->cmd == "users/sign_in")) {
1172 $this->module = "login";
1178 * From the request URL, routing consists of obtaining the name of a BaseModule-extending class of which the
1179 * post() and/or content() static methods can be respectively called to produce a data change or an output.
1182 // First we try explicit routes defined in App\Router
1183 $this->router->collectRoutes();
1185 $data = $this->router->getRouteCollector();
1186 Hook::callAll('route_collection', $data);
1188 $this->module_class = $this->router->getModuleClass($this->cmd);
1190 // Then we try addon-provided modules that we wrap in the LegacyModule class
1191 if (!$this->module_class && Core\Addon::isEnabled($this->module) && file_exists("addon/{$this->module}/{$this->module}.php")) {
1192 //Check if module is an app and if public access to apps is allowed or not
1193 $privateapps = $this->config->get('config', 'private_addons', false);
1194 if ((!local_user()) && Core\Hook::isAddonApp($this->module) && $privateapps) {
1195 info(Core\L10n::t("You must be logged in to use addons. "));
1197 include_once "addon/{$this->module}/{$this->module}.php";
1198 if (function_exists($this->module . '_module')) {
1199 LegacyModule::setModuleFile("addon/{$this->module}/{$this->module}.php");
1200 $this->module_class = LegacyModule::class;
1205 // Then we try name-matching a Friendica\Module class
1206 if (!$this->module_class && class_exists('Friendica\\Module\\' . ucfirst($this->module))) {
1207 $this->module_class = 'Friendica\\Module\\' . ucfirst($this->module);
1210 /* Finally, we look for a 'standard' program module in the 'mod' directory
1211 * We emulate a Module class through the LegacyModule class
1213 if (!$this->module_class && file_exists("mod/{$this->module}.php")) {
1214 LegacyModule::setModuleFile("mod/{$this->module}.php");
1215 $this->module_class = LegacyModule::class;
1218 /* The URL provided does not resolve to a valid module.
1220 * On Dreamhost sites, quite often things go wrong for no apparent reason and they send us to '/internal_error.html'.
1221 * We don't like doing this, but as it occasionally accounts for 10-20% or more of all site traffic -
1222 * 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
1223 * this will often succeed and eventually do the right thing.
1225 * Otherwise we are going to emit a 404 not found.
1227 if (!$this->module_class) {
1228 // Stupid browser tried to pre-fetch our Javascript img template. Don't log the event or return anything - just quietly exit.
1229 if (!empty($_SERVER['QUERY_STRING']) && preg_match('/{[0-9]}/', $_SERVER['QUERY_STRING']) !== 0) {
1233 if (!empty($_SERVER['QUERY_STRING']) && ($_SERVER['QUERY_STRING'] === 'q=internal_error.html') && isset($dreamhost_error_hack)) {
1234 Core\Logger::log('index.php: dreamhost_error_hack invoked. Original URI =' . $_SERVER['REQUEST_URI']);
1235 $this->internalRedirect($_SERVER['REQUEST_URI']);
1238 Core\Logger::log('index.php: page not found: ' . $_SERVER['REQUEST_URI'] . ' ADDRESS: ' . $_SERVER['REMOTE_ADDR'] . ' QUERY: ' . $_SERVER['QUERY_STRING'], Core\Logger::DEBUG);
1240 $this->module_class = Module\PageNotFound::class;
1243 // Initialize module that can set the current theme in the init() method, either directly or via App->profile_uid
1244 $this->page['page_title'] = $this->module;
1248 Core\Hook::callAll($this->module . '_mod_init', $placeholder);
1250 call_user_func([$this->module_class, 'init']);
1252 // "rawContent" is especially meant for technical endpoints.
1253 // This endpoint doesn't need any theme initialization or other comparable stuff.
1254 call_user_func([$this->module_class, 'rawContent']);
1256 // Load current theme info after module has been initialized as theme could have been set in module
1257 $theme_info_file = 'view/theme/' . $this->getCurrentTheme() . '/theme.php';
1258 if (file_exists($theme_info_file)) {
1259 require_once $theme_info_file;
1262 if (function_exists(str_replace('-', '_', $this->getCurrentTheme()) . '_init')) {
1263 $func = str_replace('-', '_', $this->getCurrentTheme()) . '_init';
1267 if ($_SERVER['REQUEST_METHOD'] === 'POST') {
1268 Core\Hook::callAll($this->module . '_mod_post', $_POST);
1269 call_user_func([$this->module_class, 'post']);
1272 Core\Hook::callAll($this->module . '_mod_afterpost', $placeholder);
1273 call_user_func([$this->module_class, 'afterpost']);
1274 } catch(HTTPException $e) {
1275 echo Module\Special\HTTPException::rawContent($e);
1282 $arr = ['content' => $content];
1283 Core\Hook::callAll($this->module . '_mod_content', $arr);
1284 $content = $arr['content'];
1285 $arr = ['content' => call_user_func([$this->module_class, 'content'])];
1286 Core\Hook::callAll($this->module . '_mod_aftercontent', $arr);
1287 $content .= $arr['content'];
1288 } catch(HTTPException $e) {
1289 $content = Module\Special\HTTPException::content($e);
1292 // initialise content region
1293 if ($this->getMode()->isNormal()) {
1294 Core\Hook::callAll('page_content_top', $this->page['content']);
1297 $this->page['content'] .= $content;
1299 /* Create the page head after setting the language
1300 * and getting any auth credentials.
1302 * Moved initHead() and initFooter() to after
1303 * all the module functions have executed so that all
1304 * theme choices made by the modules can take effect.
1308 /* Build the page ending -- this is stuff that goes right before
1309 * the closing </body> tag
1311 $this->initFooter();
1313 if (!$this->isAjax()) {
1314 Core\Hook::callAll('page_end', $this->page['content']);
1317 // Add the navigation (menu) template
1318 if ($this->module != 'install' && $this->module != 'maintenance') {
1319 $this->page['htmlhead'] .= Core\Renderer::replaceMacros(Core\Renderer::getMarkupTemplate('nav_head.tpl'), []);
1320 $this->page['nav'] = Content\Nav::build($this);
1323 // Build the page - now that we have all the components
1324 if (isset($_GET["mode"]) && (($_GET["mode"] == "raw") || ($_GET["mode"] == "minimal"))) {
1325 $doc = new DOMDocument();
1327 $target = new DOMDocument();
1328 $target->loadXML("<root></root>");
1330 $content = mb_convert_encoding($this->page["content"], 'HTML-ENTITIES', "UTF-8");
1332 /// @TODO one day, kill those error-surpressing @ stuff, or PHP should ban it
1333 @$doc->loadHTML($content);
1335 $xpath = new DOMXPath($doc);
1337 $list = $xpath->query("//*[contains(@id,'tread-wrapper-')]"); /* */
1339 foreach ($list as $item) {
1340 $item = $target->importNode($item, true);
1342 // And then append it to the target
1343 $target->documentElement->appendChild($item);
1346 if ($_GET["mode"] == "raw") {
1347 header("Content-type: text/html; charset=utf-8");
1349 echo substr($target->saveHTML(), 6, -8);
1355 $page = $this->page;
1356 $profile = $this->profile;
1358 header("X-Friendica-Version: " . FRIENDICA_VERSION);
1359 header("Content-type: text/html; charset=utf-8");
1361 if ($this->config->get('system', 'hsts') && ($this->baseURL->getSSLPolicy() == BaseUrl::SSL_POLICY_FULL)) {
1362 header("Strict-Transport-Security: max-age=31536000");
1365 // Some security stuff
1366 header('X-Content-Type-Options: nosniff');
1367 header('X-XSS-Protection: 1; mode=block');
1368 header('X-Permitted-Cross-Domain-Policies: none');
1369 header('X-Frame-Options: sameorigin');
1371 // Things like embedded OSM maps don't work, when this is enabled
1372 // 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'");
1374 /* We use $_GET["mode"] for special page templates. So we will check if we have
1375 * to load another page template than the default one.
1376 * The page templates are located in /view/php/ or in the theme directory.
1378 if (isset($_GET["mode"])) {
1379 $template = Core\Theme::getPathForFile($_GET["mode"] . '.php');
1382 // If there is no page template use the default page template
1383 if (empty($template)) {
1384 $template = Core\Theme::getPathForFile("default.php");
1387 // Theme templates expect $a as an App instance
1390 // Used as is in view/php/default.php
1391 $lang = Core\L10n::getCurrentLang();
1393 /// @TODO Looks unsafe (remote-inclusion), is maybe not but Core\Theme::getPathForFile() uses file_exists() but does not escape anything
1394 require_once $template;
1398 * Redirects to another module relative to the current Friendica base.
1399 * If you want to redirect to a external URL, use System::externalRedirectTo()
1401 * @param string $toUrl The destination URL (Default is empty, which is the default page of the Friendica node)
1402 * @param bool $ssl if true, base URL will try to get called with https:// (works just for relative paths)
1404 * @throws HTTPException\InternalServerErrorException In Case the given URL is not relative to the Friendica node
1406 public function internalRedirect($toUrl = '', $ssl = false)
1408 if (!empty(parse_url($toUrl, PHP_URL_SCHEME))) {
1409 throw new HTTPException\InternalServerErrorException("'$toUrl is not a relative path, please use System::externalRedirectTo");
1412 $redirectTo = $this->getBaseURL($ssl) . '/' . ltrim($toUrl, '/');
1413 Core\System::externalRedirect($redirectTo);
1417 * Automatically redirects to relative or absolute URL
1418 * Should only be used if it isn't clear if the URL is either internal or external
1420 * @param string $toUrl The target URL
1421 * @throws HTTPException\InternalServerErrorException
1423 public function redirect($toUrl)
1425 if (!empty(parse_url($toUrl, PHP_URL_SCHEME))) {
1426 Core\System::externalRedirect($toUrl);
1428 $this->internalRedirect($toUrl);