7 use Detection\MobileDetect;
11 use FastRoute\RouteCollector;
12 use Friendica\Core\Config\Cache\IConfigCache;
13 use Friendica\Core\Config\Configuration;
14 use Friendica\Core\Hook;
15 use Friendica\Core\Theme;
16 use Friendica\Database\DBA;
17 use Friendica\Model\Profile;
18 use Friendica\Network\HTTPException\InternalServerErrorException;
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 = '';
52 public $error = false;
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
82 * @var string The App URL path
87 * @var bool true, if the call is from the Friendica APP, otherwise false
89 private $isFriendicaApp;
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 * Returns the current config cache of this node
129 * @return IConfigCache
131 public function getConfigCache()
133 return $this->config->getCache();
137 * The basepath of this app
141 public function getBasePath()
143 return $this->config->get('system', 'basepath');
147 * The Logger of this app
149 * @return LoggerInterface
151 public function getLogger()
153 return $this->logger;
157 * The profiler of this app
161 public function getProfiler()
163 return $this->profiler;
167 * Returns the Mode of the Application
169 * @return App\Mode The Application Mode
171 public function getMode()
177 * Register a stylesheet file path to be included in the <head> tag of every page.
178 * Inclusion is done in App->initHead().
179 * The path can be absolute or relative to the Friendica installation base folder.
183 * @param string $path
184 * @throws InternalServerErrorException
186 public function registerStylesheet($path)
188 if (mb_strpos($path, $this->getBasePath() . DIRECTORY_SEPARATOR) === 0) {
189 $path = mb_substr($path, mb_strlen($this->getBasePath() . DIRECTORY_SEPARATOR));
192 $this->stylesheets[] = trim($path, '/');
196 * Register a javascript file path to be included in the <footer> tag of every page.
197 * Inclusion is done in App->initFooter().
198 * The path can be absolute or relative to the Friendica installation base folder.
202 * @param string $path
203 * @throws InternalServerErrorException
205 public function registerFooterScript($path)
207 $url = str_replace($this->getBasePath() . DIRECTORY_SEPARATOR, '', $path);
209 $this->footerScripts[] = trim($url, '/');
217 * @brief App constructor.
219 * @param Configuration $config The Configuration
220 * @param App\Mode $mode The mode of this Friendica app
221 * @param LoggerInterface $logger The current app logger
222 * @param Profiler $profiler The profiler of this application
223 * @param bool $isBackend Whether it is used for backend or frontend (Default true=backend)
225 * @throws Exception if the Basepath is not usable
227 public function __construct(Configuration $config, App\Mode $mode, LoggerInterface $logger, Profiler $profiler, $isBackend = true)
229 BaseObject::setApp($this);
231 $this->logger = $logger;
232 $this->config = $config;
233 $this->profiler = $profiler;
236 $this->checkBackend($isBackend);
237 $this->checkFriendicaApp();
239 $this->profiler->reset();
245 // This has to be quite large to deal with embedded private photos
246 ini_set('pcre.backtrack_limit', 500000);
248 $this->scheme = 'http';
250 if (!empty($_SERVER['HTTPS']) ||
251 !empty($_SERVER['HTTP_FORWARDED']) && preg_match('/proto=https/', $_SERVER['HTTP_FORWARDED']) ||
252 !empty($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https' ||
253 !empty($_SERVER['HTTP_X_FORWARDED_SSL']) && $_SERVER['HTTP_X_FORWARDED_SSL'] == 'on' ||
254 !empty($_SERVER['FRONT_END_HTTPS']) && $_SERVER['FRONT_END_HTTPS'] == 'on' ||
255 !empty($_SERVER['SERVER_PORT']) && (intval($_SERVER['SERVER_PORT']) == 443) // XXX: reasonable assumption, but isn't this hardcoding too much?
257 $this->scheme = 'https';
260 if (!empty($_SERVER['SERVER_NAME'])) {
261 $this->hostname = $_SERVER['SERVER_NAME'];
263 if (!empty($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] != 80 && $_SERVER['SERVER_PORT'] != 443) {
264 $this->hostname .= ':' . $_SERVER['SERVER_PORT'];
269 get_include_path() . PATH_SEPARATOR
270 . $this->getBasePath() . DIRECTORY_SEPARATOR . 'include' . PATH_SEPARATOR
271 . $this->getBasePath() . DIRECTORY_SEPARATOR . 'library' . PATH_SEPARATOR
272 . $this->getBasePath());
274 if (!empty($_SERVER['QUERY_STRING']) && strpos($_SERVER['QUERY_STRING'], 'pagename=') === 0) {
275 $this->query_string = substr($_SERVER['QUERY_STRING'], 9);
276 } elseif (!empty($_SERVER['QUERY_STRING']) && strpos($_SERVER['QUERY_STRING'], 'q=') === 0) {
277 $this->query_string = substr($_SERVER['QUERY_STRING'], 2);
280 // removing trailing / - maybe a nginx problem
281 $this->query_string = ltrim($this->query_string, '/');
283 if (!empty($_GET['pagename'])) {
284 $this->cmd = trim($_GET['pagename'], '/\\');
285 } elseif (!empty($_GET['q'])) {
286 $this->cmd = trim($_GET['q'], '/\\');
290 $this->query_string = str_replace($this->cmd . '&', $this->cmd . '?', $this->query_string);
292 // unix style "homedir"
293 if (substr($this->cmd, 0, 1) === '~') {
294 $this->cmd = 'profile/' . substr($this->cmd, 1);
297 // Diaspora style profile url
298 if (substr($this->cmd, 0, 2) === 'u/') {
299 $this->cmd = 'profile/' . substr($this->cmd, 2);
303 * Break the URL path into C style argc/argv style arguments for our
304 * modules. Given "http://example.com/module/arg1/arg2", $this->argc
305 * will be 3 (integer) and $this->argv will contain:
311 * There will always be one argument. If provided a naked domain
312 * URL, $this->argv[0] is set to "home".
315 $this->argv = explode('/', $this->cmd);
316 $this->argc = count($this->argv);
317 if ((array_key_exists('0', $this->argv)) && strlen($this->argv[0])) {
318 $this->module = str_replace('.', '_', $this->argv[0]);
319 $this->module = str_replace('-', '_', $this->module);
322 $this->argv = ['home'];
323 $this->module = 'home';
326 // Detect mobile devices
327 $mobile_detect = new MobileDetect();
329 $this->mobileDetect = $mobile_detect;
331 $this->is_mobile = $mobile_detect->isMobile();
332 $this->is_tablet = $mobile_detect->isTablet();
334 $this->isAjax = strtolower(defaults($_SERVER, 'HTTP_X_REQUESTED_WITH', '')) == 'xmlhttprequest';
336 // Register template engines
337 Core\Renderer::registerTemplateEngine('Friendica\Render\FriendicaSmartyEngine');
341 * Reloads the whole app instance
343 public function reload()
345 $this->determineURLPath();
347 $this->getMode()->determine($this->getBasePath());
349 if ($this->getMode()->has(App\Mode::DBAVAILABLE)) {
350 $loader = new ConfigFileLoader($this->getBasePath(), $this->getMode());
351 $this->config->getCache()->load($loader->loadCoreConfig('addon'), true);
353 $this->profiler->update(
354 $this->config->get('system', 'profiler', false),
355 $this->config->get('rendertime', 'callstack', false));
357 Core\Hook::loadHooks();
358 $loader = new ConfigFileLoader($this->getBasePath(), $this->mode);
359 Core\Hook::callAll('load_config', $loader);
362 $this->loadDefaultTimezone();
368 * Loads the default timezone
370 * Include support for legacy $default_timezone
372 * @global string $default_timezone
374 private function loadDefaultTimezone()
376 if ($this->config->get('system', 'default_timezone')) {
377 $this->timezone = $this->config->get('system', 'default_timezone');
379 global $default_timezone;
380 $this->timezone = !empty($default_timezone) ? $default_timezone : 'UTC';
383 if ($this->timezone) {
384 date_default_timezone_set($this->timezone);
389 * Figure out if we are running at the top of a domain or in a sub-directory and adjust accordingly
391 private function determineURLPath()
394 * The automatic path detection in this function is currently deactivated,
395 * see issue https://github.com/friendica/friendica/issues/6679
397 * The problem is that the function seems to be confused with some url.
398 * These then confuses the detection which changes the url path.
401 /* Relative script path to the web server root
402 * Not all of those $_SERVER properties can be present, so we do by inverse priority order
405 $relative_script_path = '';
406 $relative_script_path = defaults($_SERVER, 'REDIRECT_URL' , $relative_script_path);
407 $relative_script_path = defaults($_SERVER, 'REDIRECT_URI' , $relative_script_path);
408 $relative_script_path = defaults($_SERVER, 'REDIRECT_SCRIPT_URL', $relative_script_path);
409 $relative_script_path = defaults($_SERVER, 'SCRIPT_URL' , $relative_script_path);
410 $relative_script_path = defaults($_SERVER, 'REQUEST_URI' , $relative_script_path);
412 $this->urlPath = $this->config->get('system', 'urlpath');
414 /* $relative_script_path gives /relative/path/to/friendica/module/parameter
415 * QUERY_STRING gives pagename=module/parameter
417 * To get /relative/path/to/friendica we perform dirname() for as many levels as there are slashes in the QUERY_STRING
420 if (!empty($relative_script_path)) {
422 if (!empty($_SERVER['QUERY_STRING'])) {
423 $path = trim(rdirname($relative_script_path, substr_count(trim($_SERVER['QUERY_STRING'], '/'), '/') + 1), '/');
426 $path = trim($relative_script_path, '/');
429 if ($path && $path != $this->urlPath) {
430 $this->urlPath = $path;
436 public function getScheme()
438 return $this->scheme;
442 * @brief Retrieves the Friendica instance base URL
444 * This function assembles the base URL from multiple parts:
445 * - Protocol is determined either by the request or a combination of
446 * system.ssl_policy and the $ssl parameter.
447 * - Host name is determined either by system.hostname or inferred from request
448 * - Path is inferred from SCRIPT_NAME
450 * Note: $ssl parameter value doesn't directly correlate with the resulting protocol
452 * @param bool $ssl Whether to append http or https under SSL_POLICY_SELFSIGN
453 * @return string Friendica server base URL
454 * @throws InternalServerErrorException
456 public function getBaseURL($ssl = false)
458 $scheme = $this->scheme;
460 if ($this->config->get('system', 'ssl_policy') == SSL_POLICY_FULL) {
464 // Basically, we have $ssl = true on any links which can only be seen by a logged in user
465 // (and also the login link). Anything seen by an outsider will have it turned off.
467 if ($this->config->get('system', 'ssl_policy') == SSL_POLICY_SELFSIGN) {
475 if ($this->config->get('config', 'hostname') != '') {
476 $this->hostname = $this->config->get('config', 'hostname');
479 return $scheme . '://' . $this->hostname . (!empty($this->getURLPath()) ? '/' . $this->getURLPath() : '' );
483 * @brief Initializes the baseurl components
485 * Clears the baseurl cache to prevent inconsistencies
488 * @throws InternalServerErrorException
490 public function setBaseURL($url)
492 $parsed = @parse_url($url);
495 if (!empty($parsed)) {
496 if (!empty($parsed['scheme'])) {
497 $this->scheme = $parsed['scheme'];
500 if (!empty($parsed['host'])) {
501 $hostname = $parsed['host'];
504 if (!empty($parsed['port'])) {
505 $hostname .= ':' . $parsed['port'];
507 if (!empty($parsed['path'])) {
508 $this->urlPath = trim($parsed['path'], '\\/');
511 if (file_exists($this->getBasePath() . '/.htpreconfig.php')) {
512 include $this->getBasePath() . '/.htpreconfig.php';
515 if ($this->config->get('config', 'hostname') != '') {
516 $this->hostname = $this->config->get('config', 'hostname');
519 if (!isset($this->hostname) || ($this->hostname == '')) {
520 $this->hostname = $hostname;
525 public function getHostName()
527 if ($this->config->get('config', 'hostname') != '') {
528 $this->hostname = $this->config->get('config', 'hostname');
531 return $this->hostname;
534 public function getURLPath()
536 return $this->urlPath;
540 * Initializes App->page['htmlhead'].
545 * - Registered stylesheets (through App->registerStylesheet())
546 * - Infinite scroll data
547 * - head.tpl template
549 public function initHead()
551 $interval = ((local_user()) ? Core\PConfig::get(local_user(), 'system', 'update_interval') : 40000);
553 // If the update is 'deactivated' set it to the highest integer number (~24 days)
555 $interval = 2147483647;
558 if ($interval < 10000) {
562 // Default title: current module called
563 if (empty($this->page['title']) && $this->module) {
564 $this->page['title'] = ucfirst($this->module);
567 // Prepend the sitename to the page title
568 $this->page['title'] = $this->config->get('config', 'sitename', '') . (!empty($this->page['title']) ? ' | ' . $this->page['title'] : '');
570 if (!empty(Core\Renderer::$theme['stylesheet'])) {
571 $stylesheet = Core\Renderer::$theme['stylesheet'];
573 $stylesheet = $this->getCurrentThemeStylesheetPath();
576 $this->registerStylesheet($stylesheet);
578 $shortcut_icon = $this->config->get('system', 'shortcut_icon');
579 if ($shortcut_icon == '') {
580 $shortcut_icon = 'images/friendica-32.png';
583 $touch_icon = $this->config->get('system', 'touch_icon');
584 if ($touch_icon == '') {
585 $touch_icon = 'images/friendica-128.png';
588 Core\Hook::callAll('head', $this->page['htmlhead']);
590 $tpl = Core\Renderer::getMarkupTemplate('head.tpl');
591 /* put the head template at the beginning of page['htmlhead']
592 * since the code added by the modules frequently depends on it
595 $this->page['htmlhead'] = Core\Renderer::replaceMacros($tpl, [
596 '$baseurl' => $this->getBaseURL(),
597 '$local_user' => local_user(),
598 '$generator' => 'Friendica' . ' ' . FRIENDICA_VERSION,
599 '$delitem' => Core\L10n::t('Delete this item?'),
600 '$update_interval' => $interval,
601 '$shortcut_icon' => $shortcut_icon,
602 '$touch_icon' => $touch_icon,
603 '$block_public' => intval($this->config->get('system', 'block_public')),
604 '$stylesheets' => $this->stylesheets,
605 ]) . $this->page['htmlhead'];
609 * Initializes App->page['footer'].
612 * - Javascript homebase
613 * - Mobile toggle link
614 * - Registered footer scripts (through App->registerFooterScript())
615 * - footer.tpl template
617 public function initFooter()
619 // If you're just visiting, let javascript take you home
620 if (!empty($_SESSION['visitor_home'])) {
621 $homebase = $_SESSION['visitor_home'];
622 } elseif (local_user()) {
623 $homebase = 'profile/' . $this->user['nickname'];
626 if (isset($homebase)) {
627 $this->page['footer'] .= '<script>var homebase="' . $homebase . '";</script>' . "\n";
631 * Add a "toggle mobile" link if we're using a mobile device
633 if ($this->is_mobile || $this->is_tablet) {
634 if (isset($_SESSION['show-mobile']) && !$_SESSION['show-mobile']) {
635 $link = 'toggle_mobile?address=' . urlencode(curPageURL());
637 $link = 'toggle_mobile?off=1&address=' . urlencode(curPageURL());
639 $this->page['footer'] .= Core\Renderer::replaceMacros(Core\Renderer::getMarkupTemplate("toggle_mobile_footer.tpl"), [
640 '$toggle_link' => $link,
641 '$toggle_text' => Core\L10n::t('toggle mobile')
645 Core\Hook::callAll('footer', $this->page['footer']);
647 $tpl = Core\Renderer::getMarkupTemplate('footer.tpl');
648 $this->page['footer'] = Core\Renderer::replaceMacros($tpl, [
649 '$baseurl' => $this->getBaseURL(),
650 '$footerScripts' => $this->footerScripts,
651 ]) . $this->page['footer'];
655 * @brief Removes the base url from an url. This avoids some mixed content problems.
657 * @param string $origURL
659 * @return string The cleaned url
660 * @throws InternalServerErrorException
662 public function removeBaseURL($origURL)
664 // Remove the hostname from the url if it is an internal link
665 $nurl = Util\Strings::normaliseLink($origURL);
666 $base = Util\Strings::normaliseLink($this->getBaseURL());
667 $url = str_replace($base . '/', '', $nurl);
669 // if it is an external link return the orignal value
670 if ($url == Util\Strings::normaliseLink($origURL)) {
678 * Returns the current UserAgent as a String
680 * @return string the UserAgent as a String
681 * @throws InternalServerErrorException
683 public function getUserAgent()
686 FRIENDICA_PLATFORM . " '" .
687 FRIENDICA_CODENAME . "' " .
688 FRIENDICA_VERSION . '-' .
689 DB_UPDATE_VERSION . '; ' .
694 * Checks, if the call is from the Friendica App
697 * The friendica client has problems with the GUID in the notify. this is some workaround
699 private function checkFriendicaApp()
702 $this->isFriendicaApp = isset($_SERVER['HTTP_USER_AGENT']) && $_SERVER['HTTP_USER_AGENT'] == 'Apache-HttpClient/UNAVAILABLE (java 1.4)';
706 * Is the call via the Friendica app? (not a "normale" call)
708 * @return bool true if it's from the Friendica app
710 public function isFriendicaApp()
712 return $this->isFriendicaApp;
716 * @brief Checks if the site is called via a backend process
718 * This isn't a perfect solution. But we need this check very early.
719 * So we cannot wait until the modules are loaded.
721 * @param string $backend true, if the backend flag was set during App initialization
724 private function checkBackend($backend) {
748 // Check if current module is in backend or backend flag is set
749 $this->isBackend = (in_array($this->module, $backends) || $backend || $this->isBackend);
753 * Returns true, if the call is from a backend node (f.e. from a worker)
755 * @return bool Is it a known backend?
757 public function isBackend()
759 return $this->isBackend;
763 * @brief Checks if the maximum number of database processes is reached
765 * @return bool Is the limit reached?
767 public function isMaxProcessesReached()
769 // Deactivated, needs more investigating if this check really makes sense
773 * Commented out to suppress static analyzer issues
775 if ($this->is_backend()) {
776 $process = 'backend';
777 $max_processes = $this->config->get('system', 'max_processes_backend');
778 if (intval($max_processes) == 0) {
782 $process = 'frontend';
783 $max_processes = $this->config->get('system', 'max_processes_frontend');
784 if (intval($max_processes) == 0) {
789 $processlist = DBA::processlist();
790 if ($processlist['list'] != '') {
791 Core\Logger::log('Processcheck: Processes: ' . $processlist['amount'] . ' - Processlist: ' . $processlist['list'], Core\Logger::DEBUG);
793 if ($processlist['amount'] > $max_processes) {
794 Core\Logger::log('Processcheck: Maximum number of processes for ' . $process . ' tasks (' . $max_processes . ') reached.', Core\Logger::DEBUG);
803 * @brief Checks if the minimal memory is reached
805 * @return bool Is the memory limit reached?
806 * @throws InternalServerErrorException
808 public function isMinMemoryReached()
810 $min_memory = $this->config->get('system', 'min_memory', 0);
811 if ($min_memory == 0) {
815 if (!is_readable('/proc/meminfo')) {
819 $memdata = explode("\n", file_get_contents('/proc/meminfo'));
822 foreach ($memdata as $line) {
823 $data = explode(':', $line);
824 if (count($data) != 2) {
827 list($key, $val) = $data;
828 $meminfo[$key] = (int) trim(str_replace('kB', '', $val));
829 $meminfo[$key] = (int) ($meminfo[$key] / 1024);
832 if (!isset($meminfo['MemFree'])) {
836 $free = $meminfo['MemFree'];
838 $reached = ($free < $min_memory);
841 Core\Logger::log('Minimal memory reached: ' . $free . '/' . $meminfo['MemTotal'] . ' - limit ' . $min_memory, Core\Logger::DEBUG);
848 * @brief Checks if the maximum load is reached
850 * @return bool Is the load reached?
851 * @throws InternalServerErrorException
853 public function isMaxLoadReached()
855 if ($this->isBackend()) {
856 $process = 'backend';
857 $maxsysload = intval($this->config->get('system', 'maxloadavg'));
858 if ($maxsysload < 1) {
862 $process = 'frontend';
863 $maxsysload = intval($this->config->get('system', 'maxloadavg_frontend'));
864 if ($maxsysload < 1) {
869 $load = Core\System::currentLoad();
871 if (intval($load) > $maxsysload) {
872 Core\Logger::log('system: load ' . $load . ' for ' . $process . ' tasks (' . $maxsysload . ') too high.');
880 * Executes a child process with 'proc_open'
882 * @param string $command The command to execute
883 * @param array $args Arguments to pass to the command ( [ 'key' => value, 'key2' => value2, ... ]
884 * @throws InternalServerErrorException
886 public function proc_run($command, $args)
888 if (!function_exists('proc_open')) {
892 $cmdline = $this->config->get('config', 'php_path', 'php') . ' ' . escapeshellarg($command);
894 foreach ($args as $key => $value) {
895 if (!is_null($value) && is_bool($value) && !$value) {
899 $cmdline .= ' --' . $key;
900 if (!is_null($value) && !is_bool($value)) {
901 $cmdline .= ' ' . $value;
905 if ($this->isMinMemoryReached()) {
909 if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
910 $resource = proc_open('cmd /c start /b ' . $cmdline, [], $foo, $this->getBasePath());
912 $resource = proc_open($cmdline . ' &', [], $foo, $this->getBasePath());
914 if (!is_resource($resource)) {
915 Core\Logger::log('We got no resource for command ' . $cmdline, Core\Logger::DEBUG);
918 proc_close($resource);
922 * Generates the site's default sender email address
925 * @throws InternalServerErrorException
927 public function getSenderEmailAddress()
929 $sender_email = $this->config->get('config', 'sender_email');
930 if (empty($sender_email)) {
931 $hostname = $this->getHostName();
932 if (strpos($hostname, ':')) {
933 $hostname = substr($hostname, 0, strpos($hostname, ':'));
936 $sender_email = 'noreply@' . $hostname;
939 return $sender_email;
943 * Returns the current theme name.
945 * @return string the name of the current theme
946 * @throws InternalServerErrorException
948 public function getCurrentTheme()
950 if ($this->getMode()->isInstall()) {
954 if (!$this->currentTheme) {
955 $this->computeCurrentTheme();
958 return $this->currentTheme;
961 public function setCurrentTheme($theme)
963 $this->currentTheme = $theme;
967 * Computes the current theme name based on the node settings, the user settings and the device type
971 private function computeCurrentTheme()
973 $system_theme = $this->config->get('system', 'theme');
974 if (!$system_theme) {
975 throw new Exception(Core\L10n::t('No system theme config value set.'));
979 $this->currentTheme = $system_theme;
982 // Find the theme that belongs to the user whose stuff we are looking at
983 if ($this->profile_uid && ($this->profile_uid != local_user())) {
984 // Allow folks to override user themes and always use their own on their own site.
985 // This works only if the user is on the same server
986 $user = DBA::selectFirst('user', ['theme'], ['uid' => $this->profile_uid]);
987 if (DBA::isResult($user) && !Core\PConfig::get(local_user(), 'system', 'always_my_theme')) {
988 $page_theme = $user['theme'];
992 $user_theme = Core\Session::get('theme', $system_theme);
994 // Specific mobile theme override
995 if (($this->is_mobile || $this->is_tablet) && Core\Session::get('show-mobile', true)) {
996 $system_mobile_theme = $this->config->get('system', 'mobile-theme');
997 $user_mobile_theme = Core\Session::get('mobile-theme', $system_mobile_theme);
999 // --- means same mobile theme as desktop
1000 if (!empty($user_mobile_theme) && $user_mobile_theme !== '---') {
1001 $user_theme = $user_mobile_theme;
1006 $theme_name = $page_theme;
1008 $theme_name = $user_theme;
1011 $theme_name = Strings::sanitizeFilePathItem($theme_name);
1013 && in_array($theme_name, Theme::getAllowedList())
1014 && (file_exists('view/theme/' . $theme_name . '/style.css')
1015 || file_exists('view/theme/' . $theme_name . '/style.php'))
1017 $this->currentTheme = $theme_name;
1022 * @brief Return full URL to theme which is currently in effect.
1024 * Provide a sane default if nothing is chosen or the specified theme does not exist.
1027 * @throws InternalServerErrorException
1029 public function getCurrentThemeStylesheetPath()
1031 return Core\Theme::getStylesheetPath($this->getCurrentTheme());
1035 * Check if request was an AJAX (xmlhttprequest) request.
1037 * @return boolean true if it was an AJAX request
1039 public function isAjax()
1041 return $this->isAjax;
1045 * Returns the value of a argv key
1046 * TODO there are a lot of $a->argv usages in combination with defaults() which can be replaced with this method
1048 * @param int $position the position of the argument
1049 * @param mixed $default the default value if not found
1051 * @return mixed returns the value of the argument
1053 public function getArgumentValue($position, $default = '')
1055 if (array_key_exists($position, $this->argv)) {
1056 return $this->argv[$position];
1063 * Sets the base url for use in cmdline programs which don't have
1064 * $_SERVER variables
1066 public function checkURL()
1068 $url = $this->config->get('system', 'url');
1070 // if the url isn't set or the stored url is radically different
1071 // than the currently visited url, store the current value accordingly.
1072 // "Radically different" ignores common variations such as http vs https
1073 // and www.example.com vs example.com.
1074 // We will only change the url to an ip address if there is no existing setting
1076 if (empty($url) || (!Util\Strings::compareLink($url, $this->getBaseURL())) && (!preg_match("/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/", $this->getHostName()))) {
1077 $this->config->set('system', 'url', $this->getBaseURL());
1082 * Frontend App script
1084 * The App object behaves like a container and a dispatcher at the same time, including a representation of the
1085 * request and a representation of the response.
1087 * This probably should change to limit the size of this monster method.
1089 public function runFrontend()
1091 // Missing DB connection: ERROR
1092 if ($this->getMode()->has(App\Mode::LOCALCONFIGPRESENT) && !$this->getMode()->has(App\Mode::DBAVAILABLE)) {
1093 Core\System::httpExit(500, ['title' => 'Error 500 - Internal Server Error', 'description' => 'Apologies but the website is unavailable at the moment.']);
1096 // Max Load Average reached: ERROR
1097 if ($this->isMaxProcessesReached() || $this->isMaxLoadReached()) {
1098 header('Retry-After: 120');
1099 header('Refresh: 120; url=' . $this->getBaseURL() . "/" . $this->query_string);
1101 Core\System::httpExit(503, ['title' => 'Error 503 - Service Temporarily Unavailable', 'description' => 'Core\System is currently overloaded. Please try again later.']);
1104 if (strstr($this->query_string, '.well-known/host-meta') && ($this->query_string != '.well-known/host-meta')) {
1105 Core\System::httpExit(404);
1108 if (!$this->getMode()->isInstall()) {
1109 // Force SSL redirection
1110 if ($this->config->get('system', 'force_ssl') && ($this->getScheme() == "http")
1111 && intval($this->config->get('system', 'ssl_policy')) == SSL_POLICY_FULL
1112 && strpos($this->getBaseURL(), 'https://') === 0
1113 && $_SERVER['REQUEST_METHOD'] == 'GET') {
1114 header('HTTP/1.1 302 Moved Temporarily');
1115 header('Location: ' . $this->getBaseURL() . '/' . $this->query_string);
1119 Core\Session::init();
1120 Core\Hook::callAll('init_1');
1123 // Exclude the backend processes from the session management
1124 if (!$this->isBackend()) {
1125 $stamp1 = microtime(true);
1127 $this->profiler->saveTimestamp($stamp1, 'parser', Core\System::callstack());
1128 Core\L10n::setSessionVariable();
1129 Core\L10n::setLangFromSession();
1132 Core\Worker::executeIfIdle();
1135 if ($this->getMode()->isNormal()) {
1136 $requester = HTTPSignature::getSigner('', $_SERVER);
1137 if (!empty($requester)) {
1138 Profile::addVisitorCookieForHandle($requester);
1143 if (!empty($_GET['zrl']) && $this->getMode()->isNormal()) {
1144 $this->query_string = Model\Profile::stripZrls($this->query_string);
1145 if (!local_user()) {
1146 // Only continue when the given profile link seems valid
1147 // Valid profile links contain a path with "/profile/" and no query parameters
1148 if ((parse_url($_GET['zrl'], PHP_URL_QUERY) == "") &&
1149 strstr(parse_url($_GET['zrl'], PHP_URL_PATH), "/profile/")) {
1150 if (defaults($_SESSION, "visitor_home", "") != $_GET["zrl"]) {
1151 $_SESSION['my_url'] = $_GET['zrl'];
1152 $_SESSION['authenticated'] = 0;
1154 Model\Profile::zrlInit($this);
1156 // Someone came with an invalid parameter, maybe as a DDoS attempt
1157 // We simply stop processing here
1158 Core\Logger::log("Invalid ZRL parameter " . $_GET['zrl'], Core\Logger::DEBUG);
1159 Core\System::httpExit(403, ['title' => '403 Forbidden']);
1164 if (!empty($_GET['owt']) && $this->getMode()->isNormal()) {
1165 $token = $_GET['owt'];
1166 $this->query_string = Model\Profile::stripQueryParam($this->query_string, 'owt');
1167 Model\Profile::openWebAuthInit($token);
1170 Module\Login::sessionAuth();
1172 if (empty($_SESSION['authenticated'])) {
1173 header('X-Account-Management-Status: none');
1176 $_SESSION['sysmsg'] = defaults($_SESSION, 'sysmsg' , []);
1177 $_SESSION['sysmsg_info'] = defaults($_SESSION, 'sysmsg_info' , []);
1178 $_SESSION['last_updated'] = defaults($_SESSION, 'last_updated', []);
1181 * check_config() is responsible for running update scripts. These automatically
1182 * update the DB schema whenever we push a new one out. It also checks to see if
1183 * any addons have been added or removed and reacts accordingly.
1186 // in install mode, any url loads install module
1187 // but we need "view" module for stylesheet
1188 if ($this->getMode()->isInstall() && $this->module != 'view') {
1189 $this->module = 'install';
1190 } elseif (!$this->getMode()->has(App\Mode::MAINTENANCEDISABLED) && $this->module != 'view') {
1191 $this->module = 'maintenance';
1194 Core\Update::check($this->getBasePath(), false, $this->getMode());
1195 Core\Addon::loadAddons();
1196 Core\Hook::loadHooks();
1207 'right_aside' => '',
1212 if (strlen($this->module)) {
1213 // Compatibility with the Android Diaspora client
1214 if ($this->module == 'stream') {
1215 $this->internalRedirect('network?f=&order=post');
1218 if ($this->module == 'conversations') {
1219 $this->internalRedirect('message');
1222 if ($this->module == 'commented') {
1223 $this->internalRedirect('network?f=&order=comment');
1226 if ($this->module == 'liked') {
1227 $this->internalRedirect('network?f=&order=comment');
1230 if ($this->module == 'activity') {
1231 $this->internalRedirect('network/?f=&conv=1');
1234 if (($this->module == 'status_messages') && ($this->cmd == 'status_messages/new')) {
1235 $this->internalRedirect('bookmarklet');
1238 if (($this->module == 'user') && ($this->cmd == 'user/edit')) {
1239 $this->internalRedirect('settings');
1242 if (($this->module == 'tag_followings') && ($this->cmd == 'tag_followings/manage')) {
1243 $this->internalRedirect('search');
1246 // Compatibility with the Firefox App
1247 if (($this->module == "users") && ($this->cmd == "users/sign_in")) {
1248 $this->module = "login";
1251 $router = new App\Router();
1252 $this->collectRoutes($router->getRouteCollector());
1254 $this->module_class = $router->getModuleClass($this->cmd);
1256 $privateapps = $this->config->get('config', 'private_addons', false);
1257 if (!$this->module_class && Core\Addon::isEnabled($this->module) && file_exists("addon/{$this->module}/{$this->module}.php")) {
1258 //Check if module is an app and if public access to apps is allowed or not
1259 if ((!local_user()) && Core\Hook::isAddonApp($this->module) && $privateapps) {
1260 info(Core\L10n::t("You must be logged in to use addons. "));
1262 include_once "addon/{$this->module}/{$this->module}.php";
1263 if (function_exists($this->module . '_module')) {
1264 LegacyModule::setModuleFile("addon/{$this->module}/{$this->module}.php");
1265 $this->module_class = 'Friendica\\LegacyModule';
1270 // Controller class routing
1271 if (!$this->module_class && class_exists('Friendica\\Module\\' . ucfirst($this->module))) {
1272 $this->module_class = 'Friendica\\Module\\' . ucfirst($this->module);
1275 /* If not, next look for a 'standard' program module in the 'mod' directory
1276 * We emulate a Module class through the LegacyModule class
1278 if (!$this->module_class && file_exists("mod/{$this->module}.php")) {
1279 LegacyModule::setModuleFile("mod/{$this->module}.php");
1280 $this->module_class = 'Friendica\\LegacyModule';
1283 /* The URL provided does not resolve to a valid module.
1285 * On Dreamhost sites, quite often things go wrong for no apparent reason and they send us to '/internal_error.html'.
1286 * We don't like doing this, but as it occasionally accounts for 10-20% or more of all site traffic -
1287 * 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
1288 * this will often succeed and eventually do the right thing.
1290 * Otherwise we are going to emit a 404 not found.
1292 if (!$this->module_class) {
1293 // Stupid browser tried to pre-fetch our Javascript img template. Don't log the event or return anything - just quietly exit.
1294 if (!empty($_SERVER['QUERY_STRING']) && preg_match('/{[0-9]}/', $_SERVER['QUERY_STRING']) !== 0) {
1298 if (!empty($_SERVER['QUERY_STRING']) && ($_SERVER['QUERY_STRING'] === 'q=internal_error.html') && isset($dreamhost_error_hack)) {
1299 Core\Logger::log('index.php: dreamhost_error_hack invoked. Original URI =' . $_SERVER['REQUEST_URI']);
1300 $this->internalRedirect($_SERVER['REQUEST_URI']);
1303 Core\Logger::log('index.php: page not found: ' . $_SERVER['REQUEST_URI'] . ' ADDRESS: ' . $_SERVER['REMOTE_ADDR'] . ' QUERY: ' . $_SERVER['QUERY_STRING'], Core\Logger::DEBUG);
1305 header($_SERVER["SERVER_PROTOCOL"] . ' 404 ' . Core\L10n::t('Not Found'));
1306 $tpl = Core\Renderer::getMarkupTemplate("404.tpl");
1307 $this->page['content'] = Core\Renderer::replaceMacros($tpl, [
1308 '$message' => Core\L10n::t('Page not found.')
1315 // Initialize module that can set the current theme in the init() method, either directly or via App->profile_uid
1316 if ($this->module_class) {
1317 $this->page['page_title'] = $this->module;
1320 Core\Hook::callAll($this->module . '_mod_init', $placeholder);
1322 call_user_func([$this->module_class, 'init']);
1324 // "rawContent" is especially meant for technical endpoints.
1325 // This endpoint doesn't need any theme initialization or other comparable stuff.
1326 if (!$this->error) {
1327 call_user_func([$this->module_class, 'rawContent']);
1331 // Load current theme info after module has been initialized as theme could have been set in module
1332 $theme_info_file = 'view/theme/' . $this->getCurrentTheme() . '/theme.php';
1333 if (file_exists($theme_info_file)) {
1334 require_once $theme_info_file;
1337 if (function_exists(str_replace('-', '_', $this->getCurrentTheme()) . '_init')) {
1338 $func = str_replace('-', '_', $this->getCurrentTheme()) . '_init';
1342 if ($this->module_class) {
1343 if (! $this->error && $_SERVER['REQUEST_METHOD'] === 'POST') {
1344 Core\Hook::callAll($this->module . '_mod_post', $_POST);
1345 call_user_func([$this->module_class, 'post']);
1348 if (! $this->error) {
1349 Core\Hook::callAll($this->module . '_mod_afterpost', $placeholder);
1350 call_user_func([$this->module_class, 'afterpost']);
1353 if (! $this->error) {
1354 $arr = ['content' => $content];
1355 Core\Hook::callAll($this->module . '_mod_content', $arr);
1356 $content = $arr['content'];
1357 $arr = ['content' => call_user_func([$this->module_class, 'content'])];
1358 Core\Hook::callAll($this->module . '_mod_aftercontent', $arr);
1359 $content .= $arr['content'];
1363 // initialise content region
1364 if ($this->getMode()->isNormal()) {
1365 Core\Hook::callAll('page_content_top', $this->page['content']);
1368 $this->page['content'] .= $content;
1370 /* Create the page head after setting the language
1371 * and getting any auth credentials.
1373 * Moved initHead() and initFooter() to after
1374 * all the module functions have executed so that all
1375 * theme choices made by the modules can take effect.
1379 /* Build the page ending -- this is stuff that goes right before
1380 * the closing </body> tag
1382 $this->initFooter();
1384 /* now that we've been through the module content, see if the page reported
1385 * a permission problem and if so, a 403 response would seem to be in order.
1387 if (stristr(implode("", $_SESSION['sysmsg']), Core\L10n::t('Permission denied'))) {
1388 header($_SERVER["SERVER_PROTOCOL"] . ' 403 ' . Core\L10n::t('Permission denied.'));
1391 // Report anything which needs to be communicated in the notification area (before the main body)
1392 Core\Hook::callAll('page_end', $this->page['content']);
1394 // Add the navigation (menu) template
1395 if ($this->module != 'install' && $this->module != 'maintenance') {
1396 $this->page['htmlhead'] .= Core\Renderer::replaceMacros(Core\Renderer::getMarkupTemplate('nav_head.tpl'), []);
1397 $this->page['nav'] = Content\Nav::build($this);
1400 // Build the page - now that we have all the components
1401 if (isset($_GET["mode"]) && (($_GET["mode"] == "raw") || ($_GET["mode"] == "minimal"))) {
1402 $doc = new DOMDocument();
1404 $target = new DOMDocument();
1405 $target->loadXML("<root></root>");
1407 $content = mb_convert_encoding($this->page["content"], 'HTML-ENTITIES', "UTF-8");
1409 /// @TODO one day, kill those error-surpressing @ stuff, or PHP should ban it
1410 @$doc->loadHTML($content);
1412 $xpath = new DOMXPath($doc);
1414 $list = $xpath->query("//*[contains(@id,'tread-wrapper-')]"); /* */
1416 foreach ($list as $item) {
1417 $item = $target->importNode($item, true);
1419 // And then append it to the target
1420 $target->documentElement->appendChild($item);
1423 if ($_GET["mode"] == "raw") {
1424 header("Content-type: text/html; charset=utf-8");
1426 echo substr($target->saveHTML(), 6, -8);
1432 $page = $this->page;
1433 $profile = $this->profile;
1435 header("X-Friendica-Version: " . FRIENDICA_VERSION);
1436 header("Content-type: text/html; charset=utf-8");
1438 if ($this->config->get('system', 'hsts') && ($this->config->get('system', 'ssl_policy') == SSL_POLICY_FULL)) {
1439 header("Strict-Transport-Security: max-age=31536000");
1442 // Some security stuff
1443 header('X-Content-Type-Options: nosniff');
1444 header('X-XSS-Protection: 1; mode=block');
1445 header('X-Permitted-Cross-Domain-Policies: none');
1446 header('X-Frame-Options: sameorigin');
1448 // Things like embedded OSM maps don't work, when this is enabled
1449 // 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'");
1451 /* We use $_GET["mode"] for special page templates. So we will check if we have
1452 * to load another page template than the default one.
1453 * The page templates are located in /view/php/ or in the theme directory.
1455 if (isset($_GET["mode"])) {
1456 $template = Core\Theme::getPathForFile($_GET["mode"] . '.php');
1459 // If there is no page template use the default page template
1460 if (empty($template)) {
1461 $template = Core\Theme::getPathForFile("default.php");
1464 // Theme templates expect $a as an App instance
1467 // Used as is in view/php/default.php
1468 $lang = Core\L10n::getCurrentLang();
1470 /// @TODO Looks unsafe (remote-inclusion), is maybe not but Core\Theme::getPathForFile() uses file_exists() but does not escape anything
1471 require_once $template;
1475 * Redirects to another module relative to the current Friendica base.
1476 * If you want to redirect to a external URL, use System::externalRedirectTo()
1478 * @param string $toUrl The destination URL (Default is empty, which is the default page of the Friendica node)
1479 * @param bool $ssl if true, base URL will try to get called with https:// (works just for relative paths)
1481 * @throws InternalServerErrorException In Case the given URL is not relative to the Friendica node
1483 public function internalRedirect($toUrl = '', $ssl = false)
1485 if (!empty(parse_url($toUrl, PHP_URL_SCHEME))) {
1486 throw new InternalServerErrorException("'$toUrl is not a relative path, please use System::externalRedirectTo");
1489 $redirectTo = $this->getBaseURL($ssl) . '/' . ltrim($toUrl, '/');
1490 Core\System::externalRedirect($redirectTo);
1494 * Automatically redirects to relative or absolute URL
1495 * Should only be used if it isn't clear if the URL is either internal or external
1497 * @param string $toUrl The target URL
1498 * @throws InternalServerErrorException
1500 public function redirect($toUrl)
1502 if (!empty(parse_url($toUrl, PHP_URL_SCHEME))) {
1503 Core\System::externalRedirect($toUrl);
1505 $this->internalRedirect($toUrl);
1510 * Static declaration of Friendica routes.
1516 * - HTTP method other than GET
1517 * - Named parameters
1519 * Handler must be the name of a class extending Friendica\BaseModule.
1521 * @brief Static declaration of Friendica routes.
1522 * @param RouteCollector $routeCollector
1523 * @throws InternalServerErrorException
1525 private function collectRoutes(RouteCollector $routeCollector)
1527 $routeCollector->addRoute(['GET', 'POST'], '/itemsource[/{guid}]', Module\Itemsource::class);
1529 Hook::callAll('route_collection', $routeCollector);