7 use Detection\MobileDetect;
11 use Friendica\App\Arguments;
12 use Friendica\Core\Config\Cache\ConfigCache;
13 use Friendica\Core\Config\Configuration;
14 use Friendica\Core\Config\PConfiguration;
15 use Friendica\Core\L10n\L10n;
16 use Friendica\Core\System;
17 use Friendica\Core\Theme;
18 use Friendica\Database\Database;
19 use Friendica\Database\DBA;
20 use Friendica\Model\Profile;
21 use Friendica\Module\Login;
22 use Friendica\Module\Special\HTTPException as ModuleHTTPException;
23 use Friendica\Network\HTTPException;
24 use Friendica\Util\BaseURL;
25 use Friendica\Util\ConfigFileLoader;
26 use Friendica\Util\HTTPSignature;
27 use Friendica\Util\Profiler;
28 use Friendica\Util\Strings;
29 use Psr\Log\LoggerInterface;
35 * @brief Our main application structure for the life of this page.
37 * Primarily deals with the URL that got us here
38 * and tries to make some sense of it, and
39 * stores our page contents and config storage
40 * and anything else that might need to be passed around
41 * before we spit the page out.
46 /** @deprecated 2019.09 - use App\Arguments->getQueryString() */
47 public $query_string = '';
58 /** @deprecated 2019.09 - use App\Arguments->getCommand() */
60 /** @deprecated 2019.09 - use App\Arguments->getArgv() or Arguments->get() */
62 /** @deprecated 2019.09 - use App\Arguments->getArgc() */
64 /** @deprecated 2019.09 - Use App\Module->getName() instead */
67 public $interactive = true;
69 public $is_mobile = false;
70 public $is_tablet = false;
71 public $theme_info = [];
73 // Allow themes to control internal parameters
74 // by changing App values in theme.php
76 public $sourcename = '';
77 public $videowidth = 425;
78 public $videoheight = 350;
79 public $force_max_items = 0;
80 public $theme_events_in_profile = true;
82 public $stylesheets = [];
83 public $footerScripts = [];
86 * @var App\Mode The Mode of the Application
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 * @var Database The Friendica database connection
136 * @var L10n The translator
146 * Returns the current config cache of this node
148 * @return ConfigCache
150 public function getConfigCache()
152 return $this->config->getCache();
156 * Returns the current config of this node
158 * @return Configuration
160 public function getConfig()
162 return $this->config;
166 * The basepath of this app
170 public function getBasePath()
172 // Don't use the basepath of the config table for basepath (it should always be the config-file one)
173 return $this->config->getCache()->get('system', 'basepath');
177 * The Logger of this app
179 * @return LoggerInterface
181 public function getLogger()
183 return $this->logger;
187 * The profiler of this app
191 public function getProfiler()
193 return $this->profiler;
197 * Returns the Mode of the Application
199 * @return App\Mode The Application Mode
201 public function getMode()
207 * Returns the Database of the Application
211 public function getDBA()
213 return $this->database;
217 * Register a stylesheet file path to be included in the <head> tag of every page.
218 * Inclusion is done in App->initHead().
219 * The path can be absolute or relative to the Friendica installation base folder.
223 * @param string $path
225 public function registerStylesheet($path)
227 if (mb_strpos($path, $this->getBasePath() . DIRECTORY_SEPARATOR) === 0) {
228 $path = mb_substr($path, mb_strlen($this->getBasePath() . DIRECTORY_SEPARATOR));
231 $this->stylesheets[] = trim($path, '/');
235 * Register a javascript file path to be included in the <footer> tag of every page.
236 * Inclusion is done in App->initFooter().
237 * The path can be absolute or relative to the Friendica installation base folder.
241 * @param string $path
243 public function registerFooterScript($path)
245 $url = str_replace($this->getBasePath() . DIRECTORY_SEPARATOR, '', $path);
247 $this->footerScripts[] = trim($url, '/');
253 * @brief App constructor.
255 * @param Database $database The Friendica Database
256 * @param Configuration $config The Configuration
257 * @param App\Mode $mode The mode of this Friendica app
258 * @param App\Router $router The router of this Friendica app
259 * @param BaseURL $baseURL The full base URL of this Friendica app
260 * @param LoggerInterface $logger The current app logger
261 * @param Profiler $profiler The profiler of this application
262 * @param L10n $l10n The translator instance
264 * @throws Exception if the Basepath is not usable
266 public function __construct(Database $database, Configuration $config, App\Mode $mode, App\Router $router, BaseURL $baseURL, LoggerInterface $logger, Profiler $profiler, L10n $l10n, Arguments $args)
268 $this->database = $database;
269 $this->config = $config;
271 $this->router = $router;
272 $this->baseURL = $baseURL;
273 $this->profiler = $profiler;
274 $this->logger = $logger;
278 $this->profiler->reset();
284 // This has to be quite large to deal with embedded private photos
285 ini_set('pcre.backtrack_limit', 500000);
288 get_include_path() . PATH_SEPARATOR
289 . $this->getBasePath() . DIRECTORY_SEPARATOR . 'include' . PATH_SEPARATOR
290 . $this->getBasePath() . DIRECTORY_SEPARATOR . 'library' . PATH_SEPARATOR
291 . $this->getBasePath());
293 $this->cmd = $args->getCommand();
294 $this->argv = $args->getArgv();
295 $this->argc = $args->getArgc();
296 $this->query_string = $args->getQueryString();
298 // Detect mobile devices
299 $mobile_detect = new MobileDetect();
301 $this->mobileDetect = $mobile_detect;
303 $this->is_mobile = $mobile_detect->isMobile();
304 $this->is_tablet = $mobile_detect->isTablet();
306 $this->isAjax = strtolower(defaults($_SERVER, 'HTTP_X_REQUESTED_WITH', '')) == 'xmlhttprequest';
308 // Register template engines
309 Core\Renderer::registerTemplateEngine('Friendica\Render\FriendicaSmartyEngine');
313 * Reloads the whole app instance
315 public function reload()
317 if ($this->getMode()->has(App\Mode::DBAVAILABLE)) {
318 $this->profiler->update($this->config);
320 Core\Hook::loadHooks();
321 $loader = new ConfigFileLoader($this->getBasePath());
322 Core\Hook::callAll('load_config', $loader);
325 $this->loadDefaultTimezone();
329 * Loads the default timezone
331 * Include support for legacy $default_timezone
333 * @global string $default_timezone
335 private function loadDefaultTimezone()
337 if ($this->config->get('system', 'default_timezone')) {
338 $this->timezone = $this->config->get('system', 'default_timezone');
340 global $default_timezone;
341 $this->timezone = !empty($default_timezone) ? $default_timezone : 'UTC';
344 if ($this->timezone) {
345 date_default_timezone_set($this->timezone);
350 * Returns the scheme of the current call
353 * @deprecated 2019.06 - use BaseURL->getScheme() instead
355 public function getScheme()
357 return $this->baseURL->getScheme();
361 * Retrieves the Friendica instance base URL
363 * @param bool $ssl Whether to append http or https under BaseURL::SSL_POLICY_SELFSIGN
365 * @return string Friendica server base URL
367 * @deprecated 2019.09 - use BaseUrl->get($ssl) instead
369 public function getBaseURL($ssl = false)
371 return $this->baseURL->get($ssl);
375 * @brief Initializes the baseurl components
377 * Clears the baseurl cache to prevent inconsistencies
381 * @deprecated 2019.06 - use BaseURL->saveByURL($url) instead
383 public function setBaseURL($url)
385 $this->baseURL->saveByURL($url);
389 * Returns the current hostname
393 * @deprecated 2019.06 - use BaseURL->getHostname() instead
395 public function getHostName()
397 return $this->baseURL->getHostname();
401 * Returns the sub-path of the full URL
405 * @deprecated 2019.06 - use BaseURL->getUrlPath() instead
407 public function getURLPath()
409 return $this->baseURL->getUrlPath();
413 * Initializes App->page['htmlhead'].
418 * - Registered stylesheets (through App->registerStylesheet())
419 * - Infinite scroll data
420 * - head.tpl template
422 private function initHead(App\Module $module, PConfiguration $pconfig)
424 $interval = ((local_user()) ? $pconfig->get(local_user(), 'system', 'update_interval') : 40000);
426 // If the update is 'deactivated' set it to the highest integer number (~24 days)
428 $interval = 2147483647;
431 if ($interval < 10000) {
435 // Default title: current module called
436 if (empty($this->page['title']) && $module->getName()) {
437 $this->page['title'] = ucfirst($module->getName());
440 // Prepend the sitename to the page title
441 $this->page['title'] = $this->config->get('config', 'sitename', '') . (!empty($this->page['title']) ? ' | ' . $this->page['title'] : '');
443 if (!empty(Core\Renderer::$theme['stylesheet'])) {
444 $stylesheet = Core\Renderer::$theme['stylesheet'];
446 $stylesheet = $this->getCurrentThemeStylesheetPath();
449 $this->registerStylesheet($stylesheet);
451 $shortcut_icon = $this->config->get('system', 'shortcut_icon');
452 if ($shortcut_icon == '') {
453 $shortcut_icon = 'images/friendica-32.png';
456 $touch_icon = $this->config->get('system', 'touch_icon');
457 if ($touch_icon == '') {
458 $touch_icon = 'images/friendica-128.png';
461 Core\Hook::callAll('head', $this->page['htmlhead']);
463 $tpl = Core\Renderer::getMarkupTemplate('head.tpl');
464 /* put the head template at the beginning of page['htmlhead']
465 * since the code added by the modules frequently depends on it
468 $this->page['htmlhead'] = Core\Renderer::replaceMacros($tpl, [
469 '$local_user' => local_user(),
470 '$generator' => 'Friendica' . ' ' . FRIENDICA_VERSION,
471 '$delitem' => $this->l10n->t('Delete this item?'),
472 '$update_interval' => $interval,
473 '$shortcut_icon' => $shortcut_icon,
474 '$touch_icon' => $touch_icon,
475 '$block_public' => intval($this->config->get('system', 'block_public')),
476 '$stylesheets' => $this->stylesheets,
477 ]) . $this->page['htmlhead'];
481 * Initializes App->page['footer'].
484 * - Javascript homebase
485 * - Mobile toggle link
486 * - Registered footer scripts (through App->registerFooterScript())
487 * - footer.tpl template
489 private function initFooter()
491 // If you're just visiting, let javascript take you home
492 if (!empty($_SESSION['visitor_home'])) {
493 $homebase = $_SESSION['visitor_home'];
494 } elseif (local_user()) {
495 $homebase = 'profile/' . $this->user['nickname'];
498 if (isset($homebase)) {
499 $this->page['footer'] .= '<script>var homebase="' . $homebase . '";</script>' . "\n";
503 * Add a "toggle mobile" link if we're using a mobile device
505 if ($this->is_mobile || $this->is_tablet) {
506 if (isset($_SESSION['show-mobile']) && !$_SESSION['show-mobile']) {
507 $link = 'toggle_mobile?address=' . urlencode(curPageURL());
509 $link = 'toggle_mobile?off=1&address=' . urlencode(curPageURL());
511 $this->page['footer'] .= Core\Renderer::replaceMacros(Core\Renderer::getMarkupTemplate("toggle_mobile_footer.tpl"), [
512 '$toggle_link' => $link,
513 '$toggle_text' => $this->l10n->t('toggle mobile')
517 Core\Hook::callAll('footer', $this->page['footer']);
519 $tpl = Core\Renderer::getMarkupTemplate('footer.tpl');
520 $this->page['footer'] = Core\Renderer::replaceMacros($tpl, [
521 '$footerScripts' => $this->footerScripts,
522 ]) . $this->page['footer'];
526 * @brief Removes the base url from an url. This avoids some mixed content problems.
528 * @param string $origURL
530 * @return string The cleaned url
531 * @throws HTTPException\InternalServerErrorException
533 public function removeBaseURL($origURL)
535 // Remove the hostname from the url if it is an internal link
536 $nurl = Util\Strings::normaliseLink($origURL);
537 $base = Util\Strings::normaliseLink($this->getBaseURL());
538 $url = str_replace($base . '/', '', $nurl);
540 // if it is an external link return the orignal value
541 if ($url == Util\Strings::normaliseLink($origURL)) {
549 * Returns the current UserAgent as a String
551 * @return string the UserAgent as a String
552 * @throws HTTPException\InternalServerErrorException
554 public function getUserAgent()
557 FRIENDICA_PLATFORM . " '" .
558 FRIENDICA_CODENAME . "' " .
559 FRIENDICA_VERSION . '-' .
560 DB_UPDATE_VERSION . '; ' .
565 * Returns true, if the call is from a backend node (f.e. from a worker)
567 * @return bool Is it a known backend?
569 * @deprecated 2019.09 - use App\Mode->isBackend() instead
570 * @see App\Mode::isBackend()
571 * Use BaseObject::getClass(App\Mode::class) to get the global instance of Mode
573 public function isBackend()
575 return $this->mode->isBackend();
579 * @brief Checks if the maximum number of database processes is reached
581 * @return bool Is the limit reached?
583 public function isMaxProcessesReached()
585 // Deactivated, needs more investigating if this check really makes sense
589 * Commented out to suppress static analyzer issues
591 if ($this->is_backend()) {
592 $process = 'backend';
593 $max_processes = $this->config->get('system', 'max_processes_backend');
594 if (intval($max_processes) == 0) {
598 $process = 'frontend';
599 $max_processes = $this->config->get('system', 'max_processes_frontend');
600 if (intval($max_processes) == 0) {
605 $processlist = DBA::processlist();
606 if ($processlist['list'] != '') {
607 Core\Logger::log('Processcheck: Processes: ' . $processlist['amount'] . ' - Processlist: ' . $processlist['list'], Core\Logger::DEBUG);
609 if ($processlist['amount'] > $max_processes) {
610 Core\Logger::log('Processcheck: Maximum number of processes for ' . $process . ' tasks (' . $max_processes . ') reached.', Core\Logger::DEBUG);
619 * @brief Checks if the minimal memory is reached
621 * @return bool Is the memory limit reached?
622 * @throws HTTPException\InternalServerErrorException
624 public function isMinMemoryReached()
626 $min_memory = $this->config->get('system', 'min_memory', 0);
627 if ($min_memory == 0) {
631 if (!is_readable('/proc/meminfo')) {
635 $memdata = explode("\n", file_get_contents('/proc/meminfo'));
638 foreach ($memdata as $line) {
639 $data = explode(':', $line);
640 if (count($data) != 2) {
643 list($key, $val) = $data;
644 $meminfo[$key] = (int) trim(str_replace('kB', '', $val));
645 $meminfo[$key] = (int) ($meminfo[$key] / 1024);
648 if (!isset($meminfo['MemFree'])) {
652 $free = $meminfo['MemFree'];
654 $reached = ($free < $min_memory);
657 Core\Logger::log('Minimal memory reached: ' . $free . '/' . $meminfo['MemTotal'] . ' - limit ' . $min_memory, Core\Logger::DEBUG);
664 * @brief Checks if the maximum load is reached
666 * @return bool Is the load reached?
667 * @throws HTTPException\InternalServerErrorException
669 public function isMaxLoadReached()
671 if ($this->isBackend()) {
672 $process = 'backend';
673 $maxsysload = intval($this->config->get('system', 'maxloadavg'));
674 if ($maxsysload < 1) {
678 $process = 'frontend';
679 $maxsysload = intval($this->config->get('system', 'maxloadavg_frontend'));
680 if ($maxsysload < 1) {
685 $load = Core\System::currentLoad();
687 if (intval($load) > $maxsysload) {
688 Core\Logger::log('system: load ' . $load . ' for ' . $process . ' tasks (' . $maxsysload . ') too high.');
696 * Executes a child process with 'proc_open'
698 * @param string $command The command to execute
699 * @param array $args Arguments to pass to the command ( [ 'key' => value, 'key2' => value2, ... ]
700 * @throws HTTPException\InternalServerErrorException
702 public function proc_run($command, $args)
704 if (!function_exists('proc_open')) {
708 $cmdline = $this->config->get('config', 'php_path', 'php') . ' ' . escapeshellarg($command);
710 foreach ($args as $key => $value) {
711 if (!is_null($value) && is_bool($value) && !$value) {
715 $cmdline .= ' --' . $key;
716 if (!is_null($value) && !is_bool($value)) {
717 $cmdline .= ' ' . $value;
721 if ($this->isMinMemoryReached()) {
725 if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
726 $resource = proc_open('cmd /c start /b ' . $cmdline, [], $foo, $this->getBasePath());
728 $resource = proc_open($cmdline . ' &', [], $foo, $this->getBasePath());
730 if (!is_resource($resource)) {
731 Core\Logger::log('We got no resource for command ' . $cmdline, Core\Logger::DEBUG);
734 proc_close($resource);
738 * Generates the site's default sender email address
741 * @throws HTTPException\InternalServerErrorException
743 public function getSenderEmailAddress()
745 $sender_email = $this->config->get('config', 'sender_email');
746 if (empty($sender_email)) {
747 $hostname = $this->baseURL->getHostname();
748 if (strpos($hostname, ':')) {
749 $hostname = substr($hostname, 0, strpos($hostname, ':'));
752 $sender_email = 'noreply@' . $hostname;
755 return $sender_email;
759 * Returns the current theme name.
761 * @return string the name of the current theme
762 * @throws HTTPException\InternalServerErrorException
764 public function getCurrentTheme()
766 if ($this->getMode()->isInstall()) {
770 if (!$this->currentTheme) {
771 $this->computeCurrentTheme();
774 return $this->currentTheme;
777 public function setCurrentTheme($theme)
779 $this->currentTheme = $theme;
783 * Computes the current theme name based on the node settings, the user settings and the device type
787 private function computeCurrentTheme()
789 $system_theme = $this->config->get('system', 'theme');
790 if (!$system_theme) {
791 throw new Exception($this->l10n->t('No system theme config value set.'));
795 $this->currentTheme = $system_theme;
798 // Find the theme that belongs to the user whose stuff we are looking at
799 if ($this->profile_uid && ($this->profile_uid != local_user())) {
800 // Allow folks to override user themes and always use their own on their own site.
801 // This works only if the user is on the same server
802 $user = DBA::selectFirst('user', ['theme'], ['uid' => $this->profile_uid]);
803 if (DBA::isResult($user) && !Core\PConfig::get(local_user(), 'system', 'always_my_theme')) {
804 $page_theme = $user['theme'];
808 $user_theme = Core\Session::get('theme', $system_theme);
810 // Specific mobile theme override
811 if (($this->is_mobile || $this->is_tablet) && Core\Session::get('show-mobile', true)) {
812 $system_mobile_theme = $this->config->get('system', 'mobile-theme');
813 $user_mobile_theme = Core\Session::get('mobile-theme', $system_mobile_theme);
815 // --- means same mobile theme as desktop
816 if (!empty($user_mobile_theme) && $user_mobile_theme !== '---') {
817 $user_theme = $user_mobile_theme;
822 $theme_name = $page_theme;
824 $theme_name = $user_theme;
827 $theme_name = Strings::sanitizeFilePathItem($theme_name);
829 && in_array($theme_name, Theme::getAllowedList())
830 && (file_exists('view/theme/' . $theme_name . '/style.css')
831 || file_exists('view/theme/' . $theme_name . '/style.php'))
833 $this->currentTheme = $theme_name;
838 * @brief Return full URL to theme which is currently in effect.
840 * Provide a sane default if nothing is chosen or the specified theme does not exist.
843 * @throws HTTPException\InternalServerErrorException
845 public function getCurrentThemeStylesheetPath()
847 return Core\Theme::getStylesheetPath($this->getCurrentTheme());
851 * Check if request was an AJAX (xmlhttprequest) request.
853 * @return boolean true if it was an AJAX request
855 public function isAjax()
857 return $this->isAjax;
861 * @deprecated use Arguments->get() instead
865 public function getArgumentValue($position, $default = '')
867 return $this->args->get($position, $default);
871 * Sets the base url for use in cmdline programs which don't have
874 public function checkURL()
876 $url = $this->config->get('system', 'url');
878 // if the url isn't set or the stored url is radically different
879 // than the currently visited url, store the current value accordingly.
880 // "Radically different" ignores common variations such as http vs https
881 // and www.example.com vs example.com.
882 // We will only change the url to an ip address if there is no existing setting
884 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()))) {
885 $this->config->set('system', 'url', $this->getBaseURL());
890 * Frontend App script
892 * The App object behaves like a container and a dispatcher at the same time, including a representation of the
893 * request and a representation of the response.
895 * This probably should change to limit the size of this monster method.
897 * @param App\Module $module The determined module
899 public function runFrontend(App\Module $module, App\Router $router, PConfiguration $pconfig)
901 $moduleName = $module->getName();
904 // Missing DB connection: ERROR
905 if ($this->getMode()->has(App\Mode::LOCALCONFIGPRESENT) && !$this->getMode()->has(App\Mode::DBAVAILABLE)) {
906 throw new HTTPException\InternalServerErrorException('Apologies but the website is unavailable at the moment.');
909 // Max Load Average reached: ERROR
910 if ($this->isMaxProcessesReached() || $this->isMaxLoadReached()) {
911 header('Retry-After: 120');
912 header('Refresh: 120; url=' . $this->baseURL->get() . "/" . $this->args->getQueryString());
914 throw new HTTPException\ServiceUnavailableException('The node is currently overloaded. Please try again later.');
917 if (!$this->getMode()->isInstall()) {
918 // Force SSL redirection
919 if ($this->baseURL->checkRedirectHttps()) {
920 System::externalRedirect($this->baseURL->get() . '/' . $this->args->getQueryString());
923 Core\Session::init();
924 Core\Hook::callAll('init_1');
927 // Exclude the backend processes from the session management
928 if (!$this->isBackend()) {
929 $stamp1 = microtime(true);
931 $this->profiler->saveTimestamp($stamp1, 'parser', Core\System::callstack());
932 $this->l10n->setSessionVariable();
933 $this->l10n->setLangFromSession();
936 Core\Worker::executeIfIdle();
939 if ($this->getMode()->isNormal()) {
940 $requester = HTTPSignature::getSigner('', $_SERVER);
941 if (!empty($requester)) {
942 Profile::addVisitorCookieForHandle($requester);
947 if (!empty($_GET['zrl']) && $this->getMode()->isNormal()) {
949 // Only continue when the given profile link seems valid
950 // Valid profile links contain a path with "/profile/" and no query parameters
951 if ((parse_url($_GET['zrl'], PHP_URL_QUERY) == "") &&
952 strstr(parse_url($_GET['zrl'], PHP_URL_PATH), "/profile/")) {
953 if (Core\Session::get('visitor_home') != $_GET["zrl"]) {
954 Core\Session::set('my_url', $_GET['zrl']);
955 Core\Session::set('authenticated', 0);
958 Model\Profile::zrlInit($this);
960 // Someone came with an invalid parameter, maybe as a DDoS attempt
961 // We simply stop processing here
962 Core\Logger::log("Invalid ZRL parameter " . $_GET['zrl'], Core\Logger::DEBUG);
963 throw new HTTPException\ForbiddenException();
968 if (!empty($_GET['owt']) && $this->getMode()->isNormal()) {
969 $token = $_GET['owt'];
970 Model\Profile::openWebAuthInit($token);
973 Login::sessionAuth();
975 if (empty($_SESSION['authenticated'])) {
976 header('X-Account-Management-Status: none');
979 $_SESSION['sysmsg'] = Core\Session::get('sysmsg', []);
980 $_SESSION['sysmsg_info'] = Core\Session::get('sysmsg_info', []);
981 $_SESSION['last_updated'] = Core\Session::get('last_updated', []);
984 * check_config() is responsible for running update scripts. These automatically
985 * update the DB schema whenever we push a new one out. It also checks to see if
986 * any addons have been added or removed and reacts accordingly.
989 // in install mode, any url loads install module
990 // but we need "view" module for stylesheet
991 if ($this->getMode()->isInstall() && $moduleName !== 'install') {
992 $this->internalRedirect('install');
993 } elseif (!$this->getMode()->isInstall() && !$this->getMode()->has(App\Mode::MAINTENANCEDISABLED) && $moduleName !== 'maintenance') {
994 $this->internalRedirect('maintenance');
997 Core\Update::check($this->getBasePath(), false, $this->getMode());
998 Core\Addon::loadAddons();
999 Core\Hook::loadHooks();
1010 'right_aside' => '',
1015 // Compatibility with the Android Diaspora client
1016 if ($moduleName == 'stream') {
1017 $this->internalRedirect('network?order=post');
1020 if ($moduleName == 'conversations') {
1021 $this->internalRedirect('message');
1024 if ($moduleName == 'commented') {
1025 $this->internalRedirect('network?order=comment');
1028 if ($moduleName == 'liked') {
1029 $this->internalRedirect('network?order=comment');
1032 if ($moduleName == 'activity') {
1033 $this->internalRedirect('network?conv=1');
1036 if (($moduleName == 'status_messages') && ($this->args->getCommand() == 'status_messages/new')) {
1037 $this->internalRedirect('bookmarklet');
1040 if (($moduleName == 'user') && ($this->args->getCommand() == 'user/edit')) {
1041 $this->internalRedirect('settings');
1044 if (($moduleName == 'tag_followings') && ($this->args->getCommand() == 'tag_followings/manage')) {
1045 $this->internalRedirect('search');
1048 // Initialize module that can set the current theme in the init() method, either directly or via App->profile_uid
1049 $this->page['page_title'] = $moduleName;
1051 // determine the module class and save it to the module instance
1052 // @todo there's an implicit dependency due SESSION::start(), so it has to be called here (yet)
1053 $module = $module->determineClass($this->args, $router, $this->config);
1055 // Let the module run it's internal process (init, get, post, ...)
1056 $module->run($this->l10n, $this, $this->logger, $this->getCurrentTheme(), $_SERVER, $_POST);
1058 } catch(HTTPException $e) {
1059 ModuleHTTPException::rawContent($e);
1065 $moduleClass = $module->getClassName();
1067 $arr = ['content' => $content];
1068 Core\Hook::callAll($moduleClass . '_mod_content', $arr);
1069 $content = $arr['content'];
1070 $arr = ['content' => call_user_func([$moduleClass, 'content'])];
1071 Core\Hook::callAll($moduleClass . '_mod_aftercontent', $arr);
1072 $content .= $arr['content'];
1073 } catch(HTTPException $e) {
1074 $content = ModuleHTTPException::content($e);
1077 // initialise content region
1078 if ($this->getMode()->isNormal()) {
1079 Core\Hook::callAll('page_content_top', $this->page['content']);
1082 $this->page['content'] .= $content;
1084 /* Create the page head after setting the language
1085 * and getting any auth credentials.
1087 * Moved initHead() and initFooter() to after
1088 * all the module functions have executed so that all
1089 * theme choices made by the modules can take effect.
1091 $this->initHead($module, $pconfig);
1093 /* Build the page ending -- this is stuff that goes right before
1094 * the closing </body> tag
1096 $this->initFooter();
1098 if (!$this->isAjax()) {
1099 Core\Hook::callAll('page_end', $this->page['content']);
1102 // Add the navigation (menu) template
1103 if ($moduleName != 'install' && $moduleName != 'maintenance') {
1104 $this->page['htmlhead'] .= Core\Renderer::replaceMacros(Core\Renderer::getMarkupTemplate('nav_head.tpl'), []);
1105 $this->page['nav'] = Content\Nav::build($this);
1108 // Build the page - now that we have all the components
1109 if (isset($_GET["mode"]) && (($_GET["mode"] == "raw") || ($_GET["mode"] == "minimal"))) {
1110 $doc = new DOMDocument();
1112 $target = new DOMDocument();
1113 $target->loadXML("<root></root>");
1115 $content = mb_convert_encoding($this->page["content"], 'HTML-ENTITIES', "UTF-8");
1117 /// @TODO one day, kill those error-surpressing @ stuff, or PHP should ban it
1118 @$doc->loadHTML($content);
1120 $xpath = new DOMXPath($doc);
1122 $list = $xpath->query("//*[contains(@id,'tread-wrapper-')]"); /* */
1124 foreach ($list as $item) {
1125 $item = $target->importNode($item, true);
1127 // And then append it to the target
1128 $target->documentElement->appendChild($item);
1131 if ($_GET["mode"] == "raw") {
1132 header("Content-type: text/html; charset=utf-8");
1134 echo substr($target->saveHTML(), 6, -8);
1140 $page = $this->page;
1141 $profile = $this->profile;
1143 header("X-Friendica-Version: " . FRIENDICA_VERSION);
1144 header("Content-type: text/html; charset=utf-8");
1146 if ($this->config->get('system', 'hsts') && ($this->baseURL->getSSLPolicy() == BaseUrl::SSL_POLICY_FULL)) {
1147 header("Strict-Transport-Security: max-age=31536000");
1150 // Some security stuff
1151 header('X-Content-Type-Options: nosniff');
1152 header('X-XSS-Protection: 1; mode=block');
1153 header('X-Permitted-Cross-Domain-Policies: none');
1154 header('X-Frame-Options: sameorigin');
1156 // Things like embedded OSM maps don't work, when this is enabled
1157 // 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'");
1159 /* We use $_GET["mode"] for special page templates. So we will check if we have
1160 * to load another page template than the default one.
1161 * The page templates are located in /view/php/ or in the theme directory.
1163 if (isset($_GET["mode"])) {
1164 $template = Core\Theme::getPathForFile($_GET["mode"] . '.php');
1167 // If there is no page template use the default page template
1168 if (empty($template)) {
1169 $template = Core\Theme::getPathForFile("default.php");
1172 // Theme templates expect $a as an App instance
1175 // Used as is in view/php/default.php
1176 $lang = $this->l10n->getCurrentLang();
1178 /// @TODO Looks unsafe (remote-inclusion), is maybe not but Core\Theme::getPathForFile() uses file_exists() but does not escape anything
1179 require_once $template;
1183 * Redirects to another module relative to the current Friendica base.
1184 * If you want to redirect to a external URL, use System::externalRedirectTo()
1186 * @param string $toUrl The destination URL (Default is empty, which is the default page of the Friendica node)
1187 * @param bool $ssl if true, base URL will try to get called with https:// (works just for relative paths)
1189 * @throws HTTPException\InternalServerErrorException In Case the given URL is not relative to the Friendica node
1191 public function internalRedirect($toUrl = '', $ssl = false)
1193 if (!empty(parse_url($toUrl, PHP_URL_SCHEME))) {
1194 throw new HTTPException\InternalServerErrorException("'$toUrl is not a relative path, please use System::externalRedirectTo");
1197 $redirectTo = $this->getBaseURL($ssl) . '/' . ltrim($toUrl, '/');
1198 Core\System::externalRedirect($redirectTo);
1202 * Automatically redirects to relative or absolute URL
1203 * Should only be used if it isn't clear if the URL is either internal or external
1205 * @param string $toUrl The target URL
1206 * @throws HTTPException\InternalServerErrorException
1208 public function redirect($toUrl)
1210 if (!empty(parse_url($toUrl, PHP_URL_SCHEME))) {
1211 Core\System::externalRedirect($toUrl);
1213 $this->internalRedirect($toUrl);