7 use Detection\MobileDetect;
11 use Friendica\App\Arguments;
12 use Friendica\App\BaseURL;
13 use Friendica\Core\Config\Cache\ConfigCache;
14 use Friendica\Core\Config\Configuration;
15 use Friendica\Core\Config\PConfiguration;
16 use Friendica\Core\L10n\L10n;
17 use Friendica\Core\System;
18 use Friendica\Core\Theme;
19 use Friendica\Database\Database;
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\ConfigFileLoader;
25 use Friendica\Util\HTTPSignature;
26 use Friendica\Util\Profiler;
27 use Friendica\Util\Strings;
28 use Psr\Log\LoggerInterface;
34 * @brief Our main application structure for the life of this page.
36 * Primarily deals with the URL that got us here
37 * and tries to make some sense of it, and
38 * stores our page contents and config storage
39 * and anything else that might need to be passed around
40 * before we spit the page out.
45 /** @deprecated 2019.09 - use App\Arguments->getQueryString() */
57 /** @deprecated 2019.09 - use App\Arguments->getCommand() */
59 /** @deprecated 2019.09 - use App\Arguments->getArgv() or Arguments->get() */
61 /** @deprecated 2019.09 - use App\Arguments->getArgc() */
63 /** @deprecated 2019.09 - Use App\Module->getName() instead */
66 public $interactive = true;
70 public $theme_info = [];
72 // Allow themes to control internal parameters
73 // by changing App values in theme.php
75 public $sourcename = '';
76 public $videowidth = 425;
77 public $videoheight = 350;
78 public $force_max_items = 0;
79 public $theme_events_in_profile = true;
81 public $stylesheets = [];
82 public $footerScripts = [];
85 * @var App\Mode The Mode of the Application
100 * @var string The name of the current theme
102 private $currentTheme;
105 * @var bool check if request was an AJAX (xmlhttprequest) request
112 public $mobileDetect;
115 * @var Configuration The config
120 * @var LoggerInterface The logger
125 * @var Profiler The profiler of this app
130 * @var Database The Friendica database connection
135 * @var L10n The translator
145 * Returns the current config cache of this node
147 * @return ConfigCache
149 public function getConfigCache()
151 return $this->config->getCache();
155 * Returns the current config of this node
157 * @return Configuration
159 public function getConfig()
161 return $this->config;
165 * The basepath of this app
169 public function getBasePath()
171 // Don't use the basepath of the config table for basepath (it should always be the config-file one)
172 return $this->config->getCache()->get('system', 'basepath');
176 * The Logger of this app
178 * @return LoggerInterface
180 public function getLogger()
182 return $this->logger;
186 * The profiler of this app
190 public function getProfiler()
192 return $this->profiler;
196 * Returns the Mode of the Application
198 * @return App\Mode The Application Mode
200 public function getMode()
206 * Returns the Database of the Application
210 public function getDBA()
212 return $this->database;
216 * Register a stylesheet file path to be included in the <head> tag of every page.
217 * Inclusion is done in App->initHead().
218 * The path can be absolute or relative to the Friendica installation base folder.
220 * @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.
239 * @param string $path
244 public function registerFooterScript($path)
246 $url = str_replace($this->getBasePath() . DIRECTORY_SEPARATOR, '', $path);
248 $this->footerScripts[] = trim($url, '/');
254 * @param Database $database The Friendica Database
255 * @param Configuration $config The Configuration
256 * @param App\Mode $mode The mode of this Friendica app
257 * @param App\Router $router The router of this Friendica app
258 * @param BaseURL $baseURL The full base URL of this Friendica app
259 * @param LoggerInterface $logger The current app logger
260 * @param Profiler $profiler The profiler of this application
261 * @param L10n $l10n The translator instance
262 * @param App\Arguments $args The Friendica Arguments of the call
263 * @param MobileDetect $mobileDetect A mobile detection class
265 public function __construct(Database $database, Configuration $config, App\Mode $mode, App\Router $router, BaseURL $baseURL, LoggerInterface $logger, Profiler $profiler, L10n $l10n, Arguments $args, App\Module $module, MobileDetect $mobileDetect)
267 $this->database = $database;
268 $this->config = $config;
270 $this->router = $router;
271 $this->baseURL = $baseURL;
272 $this->profiler = $profiler;
273 $this->logger = $logger;
276 $this->mobileDetect = $mobileDetect;
278 $this->cmd = $args->getCommand();
279 $this->argv = $args->getArgv();
280 $this->argc = $args->getArgc();
281 $this->query_string = $args->getQueryString();
282 $this->module = $module->getName();
284 $this->is_mobile = $mobileDetect->isMobile();
285 $this->is_tablet = $mobileDetect->isTablet();
287 $this->isAjax = strtolower(defaults($_SERVER, 'HTTP_X_REQUESTED_WITH', '')) == 'xmlhttprequest';
306 * Load the whole app instance
308 public function load()
312 // This has to be quite large to deal with embedded private photos
313 ini_set('pcre.backtrack_limit', 500000);
316 get_include_path() . PATH_SEPARATOR
317 . $this->getBasePath() . DIRECTORY_SEPARATOR . 'include' . PATH_SEPARATOR
318 . $this->getBasePath() . DIRECTORY_SEPARATOR . 'library' . PATH_SEPARATOR
319 . $this->getBasePath());
321 $this->profiler->reset();
323 if ($this->mode->has(App\Mode::DBAVAILABLE)) {
324 $this->profiler->update($this->config);
326 Core\Hook::loadHooks();
327 $loader = new ConfigFileLoader($this->getBasePath());
328 Core\Hook::callAll('load_config', $loader);
331 $this->loadDefaultTimezone();
332 // Register template engines
333 Core\Renderer::registerTemplateEngine('Friendica\Render\FriendicaSmartyEngine');
337 * Loads the default timezone
339 * Include support for legacy $default_timezone
341 * @global string $default_timezone
343 private function loadDefaultTimezone()
345 if ($this->config->get('system', 'default_timezone')) {
346 $this->timezone = $this->config->get('system', 'default_timezone');
348 global $default_timezone;
349 $this->timezone = !empty($default_timezone) ? $default_timezone : 'UTC';
352 if ($this->timezone) {
353 date_default_timezone_set($this->timezone);
358 * Returns the scheme of the current call
362 * @deprecated 2019.06 - use BaseURL->getScheme() instead
364 public function getScheme()
366 return $this->baseURL->getScheme();
370 * Retrieves the Friendica instance base URL
372 * @param bool $ssl Whether to append http or https under BaseURL::SSL_POLICY_SELFSIGN
374 * @return string Friendica server base URL
376 * @deprecated 2019.09 - use BaseUrl->get($ssl) instead
378 public function getBaseURL($ssl = false)
380 return $this->baseURL->get($ssl);
384 * @brief Initializes the baseurl components
386 * Clears the baseurl cache to prevent inconsistencies
390 * @deprecated 2019.06 - use BaseURL->saveByURL($url) instead
392 public function setBaseURL($url)
394 $this->baseURL->saveByURL($url);
398 * Returns the current hostname
402 * @deprecated 2019.06 - use BaseURL->getHostname() instead
404 public function getHostName()
406 return $this->baseURL->getHostname();
410 * Returns the sub-path of the full URL
414 * @deprecated 2019.06 - use BaseURL->getUrlPath() instead
416 public function getURLPath()
418 return $this->baseURL->getUrlPath();
422 * Initializes App->page['htmlhead'].
427 * - Registered stylesheets (through App->registerStylesheet())
428 * - Infinite scroll data
429 * - head.tpl template
431 private function initHead(App\Module $module, PConfiguration $pconfig)
433 $interval = ((local_user()) ? $pconfig->get(local_user(), 'system', 'update_interval') : 40000);
435 // If the update is 'deactivated' set it to the highest integer number (~24 days)
437 $interval = 2147483647;
440 if ($interval < 10000) {
444 // Default title: current module called
445 if (empty($this->page['title']) && $module->getName()) {
446 $this->page['title'] = ucfirst($module->getName());
449 // Prepend the sitename to the page title
450 $this->page['title'] = $this->config->get('config', 'sitename', '') . (!empty($this->page['title']) ? ' | ' . $this->page['title'] : '');
452 if (!empty(Core\Renderer::$theme['stylesheet'])) {
453 $stylesheet = Core\Renderer::$theme['stylesheet'];
455 $stylesheet = $this->getCurrentThemeStylesheetPath();
458 $this->registerStylesheet($stylesheet);
460 $shortcut_icon = $this->config->get('system', 'shortcut_icon');
461 if ($shortcut_icon == '') {
462 $shortcut_icon = 'images/friendica-32.png';
465 $touch_icon = $this->config->get('system', 'touch_icon');
466 if ($touch_icon == '') {
467 $touch_icon = 'images/friendica-128.png';
470 Core\Hook::callAll('head', $this->page['htmlhead']);
472 $tpl = Core\Renderer::getMarkupTemplate('head.tpl');
473 /* put the head template at the beginning of page['htmlhead']
474 * since the code added by the modules frequently depends on it
477 $this->page['htmlhead'] = Core\Renderer::replaceMacros($tpl, [
478 '$local_user' => local_user(),
479 '$generator' => 'Friendica' . ' ' . FRIENDICA_VERSION,
480 '$delitem' => $this->l10n->t('Delete this item?'),
481 '$update_interval' => $interval,
482 '$shortcut_icon' => $shortcut_icon,
483 '$touch_icon' => $touch_icon,
484 '$block_public' => intval($this->config->get('system', 'block_public')),
485 '$stylesheets' => $this->stylesheets,
486 ]) . $this->page['htmlhead'];
490 * Initializes App->page['footer'].
493 * - Javascript homebase
494 * - Mobile toggle link
495 * - Registered footer scripts (through App->registerFooterScript())
496 * - footer.tpl template
498 private function initFooter()
500 // If you're just visiting, let javascript take you home
501 if (!empty($_SESSION['visitor_home'])) {
502 $homebase = $_SESSION['visitor_home'];
503 } elseif (local_user()) {
504 $homebase = 'profile/' . $this->user['nickname'];
507 if (isset($homebase)) {
508 $this->page['footer'] .= '<script>var homebase="' . $homebase . '";</script>' . "\n";
512 * Add a "toggle mobile" link if we're using a mobile device
514 if ($this->is_mobile || $this->is_tablet) {
515 if (isset($_SESSION['show-mobile']) && !$_SESSION['show-mobile']) {
516 $link = 'toggle_mobile?address=' . urlencode(curPageURL());
518 $link = 'toggle_mobile?off=1&address=' . urlencode(curPageURL());
520 $this->page['footer'] .= Core\Renderer::replaceMacros(Core\Renderer::getMarkupTemplate("toggle_mobile_footer.tpl"), [
521 '$toggle_link' => $link,
522 '$toggle_text' => $this->l10n->t('toggle mobile')
526 Core\Hook::callAll('footer', $this->page['footer']);
528 $tpl = Core\Renderer::getMarkupTemplate('footer.tpl');
529 $this->page['footer'] = Core\Renderer::replaceMacros($tpl, [
530 '$footerScripts' => $this->footerScripts,
531 ]) . $this->page['footer'];
535 * @brief Removes the base url from an url. This avoids some mixed content problems.
537 * @param string $origURL
539 * @return string The cleaned url
541 * @deprecated 2019.09 - Use BaseURL->remove() instead
542 * @see BaseURL::remove()
544 public function removeBaseURL($origURL)
546 return $this->baseURL->remove($origURL);
550 * Returns the current UserAgent as a String
552 * @return string the UserAgent as a String
553 * @throws HTTPException\InternalServerErrorException
555 public function getUserAgent()
558 FRIENDICA_PLATFORM . " '" .
559 FRIENDICA_CODENAME . "' " .
560 FRIENDICA_VERSION . '-' .
561 DB_UPDATE_VERSION . '; ' .
566 * Returns true, if the call is from a backend node (f.e. from a worker)
568 * @return bool Is it a known backend?
570 * @deprecated 2019.09 - use App\Mode->isBackend() instead
571 * @see App\Mode::isBackend()
572 * Use BaseObject::getClass(App\Mode::class) to get the global instance of Mode
574 public function isBackend()
576 return $this->mode->isBackend();
580 * @brief Checks if the maximum number of database processes is reached
582 * @return bool Is the limit reached?
584 public function isMaxProcessesReached()
586 // Deactivated, needs more investigating if this check really makes sense
590 * Commented out to suppress static analyzer issues
592 if ($this->is_backend()) {
593 $process = 'backend';
594 $max_processes = $this->config->get('system', 'max_processes_backend');
595 if (intval($max_processes) == 0) {
599 $process = 'frontend';
600 $max_processes = $this->config->get('system', 'max_processes_frontend');
601 if (intval($max_processes) == 0) {
606 $processlist = DBA::processlist();
607 if ($processlist['list'] != '') {
608 $this->logger->debug('Processcheck: Processes: ' . $processlist['amount'] . ' - Processlist: ' . $processlist['list']);
610 if ($processlist['amount'] > $max_processes) {
611 $this->logger->debug('Processcheck: Maximum number of processes for ' . $process . ' tasks (' . $max_processes . ') reached.');
620 * @brief Checks if the minimal memory is reached
622 * @return bool Is the memory limit reached?
623 * @throws HTTPException\InternalServerErrorException
625 public function isMinMemoryReached()
627 $min_memory = $this->config->get('system', 'min_memory', 0);
628 if ($min_memory == 0) {
632 if (!is_readable('/proc/meminfo')) {
636 $memdata = explode("\n", file_get_contents('/proc/meminfo'));
639 foreach ($memdata as $line) {
640 $data = explode(':', $line);
641 if (count($data) != 2) {
644 list($key, $val) = $data;
645 $meminfo[$key] = (int)trim(str_replace('kB', '', $val));
646 $meminfo[$key] = (int)($meminfo[$key] / 1024);
649 if (!isset($meminfo['MemFree'])) {
653 $free = $meminfo['MemFree'];
655 $reached = ($free < $min_memory);
658 $this->logger->debug('Minimal memory reached.', ['free' => $free, 'memtotal' => $meminfo['MemTotal'], 'limit' => $min_memory]);
665 * @brief Checks if the maximum load is reached
667 * @return bool Is the load reached?
668 * @throws HTTPException\InternalServerErrorException
670 public function isMaxLoadReached()
672 if ($this->mode->isBackend()) {
673 $process = 'backend';
674 $maxsysload = intval($this->config->get('system', 'maxloadavg'));
675 if ($maxsysload < 1) {
679 $process = 'frontend';
680 $maxsysload = intval($this->config->get('system', 'maxloadavg_frontend'));
681 if ($maxsysload < 1) {
686 $load = Core\System::currentLoad();
688 if (intval($load) > $maxsysload) {
689 $this->logger->info('system load for process too high.', ['load' => $load, 'process' => $process, 'maxsysload' => $maxsysload]);
697 * Executes a child process with 'proc_open'
699 * @param string $command The command to execute
700 * @param array $args Arguments to pass to the command ( [ 'key' => value, 'key2' => value2, ... ]
702 * @throws HTTPException\InternalServerErrorException
704 public function proc_run($command, $args)
706 if (!function_exists('proc_open')) {
710 $cmdline = $this->config->get('config', 'php_path', 'php') . ' ' . escapeshellarg($command);
712 foreach ($args as $key => $value) {
713 if (!is_null($value) && is_bool($value) && !$value) {
717 $cmdline .= ' --' . $key;
718 if (!is_null($value) && !is_bool($value)) {
719 $cmdline .= ' ' . $value;
723 if ($this->isMinMemoryReached()) {
727 if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
728 $resource = proc_open('cmd /c start /b ' . $cmdline, [], $foo, $this->getBasePath());
730 $resource = proc_open($cmdline . ' &', [], $foo, $this->getBasePath());
732 if (!is_resource($resource)) {
733 $this->logger->debug('We got no resource for command.', ['cmd' => $cmdline]);
736 proc_close($resource);
740 * Generates the site's default sender email address
743 * @throws HTTPException\InternalServerErrorException
745 public function getSenderEmailAddress()
747 $sender_email = $this->config->get('config', 'sender_email');
748 if (empty($sender_email)) {
749 $hostname = $this->baseURL->getHostname();
750 if (strpos($hostname, ':')) {
751 $hostname = substr($hostname, 0, strpos($hostname, ':'));
754 $sender_email = 'noreply@' . $hostname;
757 return $sender_email;
761 * Returns the current theme name.
763 * @return string the name of the current theme
764 * @throws HTTPException\InternalServerErrorException
766 public function getCurrentTheme()
768 if ($this->mode->isInstall()) {
772 if (!$this->currentTheme) {
773 $this->computeCurrentTheme();
776 return $this->currentTheme;
779 public function setCurrentTheme($theme)
781 $this->currentTheme = $theme;
785 * Computes the current theme name based on the node settings, the user settings and the device type
789 private function computeCurrentTheme()
791 $system_theme = $this->config->get('system', 'theme');
792 if (!$system_theme) {
793 throw new Exception($this->l10n->t('No system theme config value set.'));
797 $this->currentTheme = $system_theme;
800 // Find the theme that belongs to the user whose stuff we are looking at
801 if ($this->profile_uid && ($this->profile_uid != local_user())) {
802 // Allow folks to override user themes and always use their own on their own site.
803 // This works only if the user is on the same server
804 $user = $this->database->selectFirst('user', ['theme'], ['uid' => $this->profile_uid]);
805 if ($this->database->isResult($user) && !Core\PConfig::get(local_user(), 'system', 'always_my_theme')) {
806 $page_theme = $user['theme'];
810 $user_theme = Core\Session::get('theme', $system_theme);
812 // Specific mobile theme override
813 if (($this->is_mobile || $this->is_tablet) && Core\Session::get('show-mobile', true)) {
814 $system_mobile_theme = $this->config->get('system', 'mobile-theme');
815 $user_mobile_theme = Core\Session::get('mobile-theme', $system_mobile_theme);
817 // --- means same mobile theme as desktop
818 if (!empty($user_mobile_theme) && $user_mobile_theme !== '---') {
819 $user_theme = $user_mobile_theme;
824 $theme_name = $page_theme;
826 $theme_name = $user_theme;
829 $theme_name = Strings::sanitizeFilePathItem($theme_name);
831 && in_array($theme_name, Theme::getAllowedList())
832 && (file_exists('view/theme/' . $theme_name . '/style.css')
833 || file_exists('view/theme/' . $theme_name . '/style.php'))
835 $this->currentTheme = $theme_name;
840 * @brief Return full URL to theme which is currently in effect.
842 * Provide a sane default if nothing is chosen or the specified theme does not exist.
845 * @throws HTTPException\InternalServerErrorException
847 public function getCurrentThemeStylesheetPath()
849 return Core\Theme::getStylesheetPath($this->getCurrentTheme());
853 * Check if request was an AJAX (xmlhttprequest) request.
855 * @return boolean true if it was an AJAX request
857 public function isAjax()
859 return $this->isAjax;
863 * @deprecated use Arguments->get() instead
867 public function getArgumentValue($position, $default = '')
869 return $this->args->get($position, $default);
873 * Sets the base url for use in cmdline programs which don't have
876 public function checkURL()
878 $url = $this->config->get('system', 'url');
880 // if the url isn't set or the stored url is radically different
881 // than the currently visited url, store the current value accordingly.
882 // "Radically different" ignores common variations such as http vs https
883 // and www.example.com vs example.com.
884 // We will only change the url to an ip address if there is no existing setting
886 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()))) {
887 $this->config->set('system', 'url', $this->getBaseURL());
892 * Frontend App script
894 * The App object behaves like a container and a dispatcher at the same time, including a representation of the
895 * request and a representation of the response.
897 * This probably should change to limit the size of this monster method.
899 * @param App\Module $module The determined module
901 public function runFrontend(App\Module $module, App\Router $router, PConfiguration $pconfig)
903 $moduleName = $module->getName();
906 // Missing DB connection: ERROR
907 if ($this->mode->has(App\Mode::LOCALCONFIGPRESENT) && !$this->mode->has(App\Mode::DBAVAILABLE)) {
908 throw new HTTPException\InternalServerErrorException('Apologies but the website is unavailable at the moment.');
911 // Max Load Average reached: ERROR
912 if ($this->isMaxProcessesReached() || $this->isMaxLoadReached()) {
913 header('Retry-After: 120');
914 header('Refresh: 120; url=' . $this->baseURL->get() . "/" . $this->args->getQueryString());
916 throw new HTTPException\ServiceUnavailableException('The node is currently overloaded. Please try again later.');
919 if (!$this->mode->isInstall()) {
920 // Force SSL redirection
921 if ($this->baseURL->checkRedirectHttps()) {
922 System::externalRedirect($this->baseURL->get() . '/' . $this->args->getQueryString());
925 Core\Session::init();
926 Core\Hook::callAll('init_1');
929 // Exclude the backend processes from the session management
930 if (!$this->mode->isBackend()) {
931 $stamp1 = microtime(true);
933 $this->profiler->saveTimestamp($stamp1, 'parser', Core\System::callstack());
934 $this->l10n->setSessionVariable();
935 $this->l10n->setLangFromSession();
938 Core\Worker::executeIfIdle();
941 if ($this->mode->isNormal()) {
942 $requester = HTTPSignature::getSigner('', $_SERVER);
943 if (!empty($requester)) {
944 Profile::addVisitorCookieForHandle($requester);
949 if (!empty($_GET['zrl']) && $this->mode->isNormal()) {
951 // Only continue when the given profile link seems valid
952 // Valid profile links contain a path with "/profile/" and no query parameters
953 if ((parse_url($_GET['zrl'], PHP_URL_QUERY) == "") &&
954 strstr(parse_url($_GET['zrl'], PHP_URL_PATH), "/profile/")) {
955 if (Core\Session::get('visitor_home') != $_GET["zrl"]) {
956 Core\Session::set('my_url', $_GET['zrl']);
957 Core\Session::set('authenticated', 0);
960 Model\Profile::zrlInit($this);
962 // Someone came with an invalid parameter, maybe as a DDoS attempt
963 // We simply stop processing here
964 $this->logger->debug('Invalid ZRL parameter.', ['zrl' => $_GET['zrl']]);
965 throw new HTTPException\ForbiddenException();
970 if (!empty($_GET['owt']) && $this->mode->isNormal()) {
971 $token = $_GET['owt'];
972 Model\Profile::openWebAuthInit($token);
975 Login::sessionAuth();
977 if (empty($_SESSION['authenticated'])) {
978 header('X-Account-Management-Status: none');
981 $_SESSION['sysmsg'] = Core\Session::get('sysmsg', []);
982 $_SESSION['sysmsg_info'] = Core\Session::get('sysmsg_info', []);
983 $_SESSION['last_updated'] = Core\Session::get('last_updated', []);
986 * check_config() is responsible for running update scripts. These automatically
987 * update the DB schema whenever we push a new one out. It also checks to see if
988 * any addons have been added or removed and reacts accordingly.
991 // in install mode, any url loads install module
992 // but we need "view" module for stylesheet
993 if ($this->mode->isInstall() && $moduleName !== 'install') {
994 $this->internalRedirect('install');
995 } elseif (!$this->mode->isInstall() && !$this->mode->has(App\Mode::MAINTENANCEDISABLED) && $moduleName !== 'maintenance') {
996 $this->internalRedirect('maintenance');
999 Core\Update::check($this->getBasePath(), false, $this->mode);
1000 Core\Addon::loadAddons();
1001 Core\Hook::loadHooks();
1004 // Compatibility with the Android Diaspora client
1005 if ($moduleName == 'stream') {
1006 $this->internalRedirect('network?order=post');
1009 if ($moduleName == 'conversations') {
1010 $this->internalRedirect('message');
1013 if ($moduleName == 'commented') {
1014 $this->internalRedirect('network?order=comment');
1017 if ($moduleName == 'liked') {
1018 $this->internalRedirect('network?order=comment');
1021 if ($moduleName == 'activity') {
1022 $this->internalRedirect('network?conv=1');
1025 if (($moduleName == 'status_messages') && ($this->args->getCommand() == 'status_messages/new')) {
1026 $this->internalRedirect('bookmarklet');
1029 if (($moduleName == 'user') && ($this->args->getCommand() == 'user/edit')) {
1030 $this->internalRedirect('settings');
1033 if (($moduleName == 'tag_followings') && ($this->args->getCommand() == 'tag_followings/manage')) {
1034 $this->internalRedirect('search');
1037 // Initialize module that can set the current theme in the init() method, either directly or via App->profile_uid
1038 $this->page['page_title'] = $moduleName;
1040 // determine the module class and save it to the module instance
1041 // @todo there's an implicit dependency due SESSION::start(), so it has to be called here (yet)
1042 $module = $module->determineClass($this->args, $router, $this->config);
1044 // Let the module run it's internal process (init, get, post, ...)
1045 $module->run($this->l10n, $this, $this->logger, $this->getCurrentTheme(), $_SERVER, $_POST);
1047 } catch (HTTPException $e) {
1048 ModuleHTTPException::rawContent($e);
1054 $moduleClass = $module->getClassName();
1056 $arr = ['content' => $content];
1057 Core\Hook::callAll($moduleClass . '_mod_content', $arr);
1058 $content = $arr['content'];
1059 $arr = ['content' => call_user_func([$moduleClass, 'content'])];
1060 Core\Hook::callAll($moduleClass . '_mod_aftercontent', $arr);
1061 $content .= $arr['content'];
1062 } catch (HTTPException $e) {
1063 $content = ModuleHTTPException::content($e);
1066 // initialise content region
1067 if ($this->mode->isNormal()) {
1068 Core\Hook::callAll('page_content_top', $this->page['content']);
1071 $this->page['content'] .= $content;
1073 /* Create the page head after setting the language
1074 * and getting any auth credentials.
1076 * Moved initHead() and initFooter() to after
1077 * all the module functions have executed so that all
1078 * theme choices made by the modules can take effect.
1080 $this->initHead($module, $pconfig);
1082 /* Build the page ending -- this is stuff that goes right before
1083 * the closing </body> tag
1085 $this->initFooter();
1087 if (!$this->isAjax()) {
1088 Core\Hook::callAll('page_end', $this->page['content']);
1091 // Add the navigation (menu) template
1092 if ($moduleName != 'install' && $moduleName != 'maintenance') {
1093 $this->page['htmlhead'] .= Core\Renderer::replaceMacros(Core\Renderer::getMarkupTemplate('nav_head.tpl'), []);
1094 $this->page['nav'] = Content\Nav::build($this);
1097 // Build the page - now that we have all the components
1098 if (isset($_GET["mode"]) && (($_GET["mode"] == "raw") || ($_GET["mode"] == "minimal"))) {
1099 $doc = new DOMDocument();
1101 $target = new DOMDocument();
1102 $target->loadXML("<root></root>");
1104 $content = mb_convert_encoding($this->page["content"], 'HTML-ENTITIES', "UTF-8");
1106 /// @TODO one day, kill those error-surpressing @ stuff, or PHP should ban it
1107 @$doc->loadHTML($content);
1109 $xpath = new DOMXPath($doc);
1111 $list = $xpath->query("//*[contains(@id,'tread-wrapper-')]"); /* */
1113 foreach ($list as $item) {
1114 $item = $target->importNode($item, true);
1116 // And then append it to the target
1117 $target->documentElement->appendChild($item);
1120 if ($_GET["mode"] == "raw") {
1121 header("Content-type: text/html; charset=utf-8");
1123 echo substr($target->saveHTML(), 6, -8);
1129 $page = $this->page;
1130 $profile = $this->profile;
1132 header("X-Friendica-Version: " . FRIENDICA_VERSION);
1133 header("Content-type: text/html; charset=utf-8");
1135 if ($this->config->get('system', 'hsts') && ($this->baseURL->getSSLPolicy() == BaseURL::SSL_POLICY_FULL)) {
1136 header("Strict-Transport-Security: max-age=31536000");
1139 // Some security stuff
1140 header('X-Content-Type-Options: nosniff');
1141 header('X-XSS-Protection: 1; mode=block');
1142 header('X-Permitted-Cross-Domain-Policies: none');
1143 header('X-Frame-Options: sameorigin');
1145 // Things like embedded OSM maps don't work, when this is enabled
1146 // 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'");
1148 /* We use $_GET["mode"] for special page templates. So we will check if we have
1149 * to load another page template than the default one.
1150 * The page templates are located in /view/php/ or in the theme directory.
1152 if (isset($_GET["mode"])) {
1153 $template = Core\Theme::getPathForFile($_GET["mode"] . '.php');
1156 // If there is no page template use the default page template
1157 if (empty($template)) {
1158 $template = Core\Theme::getPathForFile("default.php");
1161 // Theme templates expect $a as an App instance
1164 // Used as is in view/php/default.php
1165 $lang = $this->l10n->getCurrentLang();
1167 /// @TODO Looks unsafe (remote-inclusion), is maybe not but Core\Theme::getPathForFile() uses file_exists() but does not escape anything
1168 require_once $template;
1172 * Redirects to another module relative to the current Friendica base.
1173 * If you want to redirect to a external URL, use System::externalRedirectTo()
1175 * @param string $toUrl The destination URL (Default is empty, which is the default page of the Friendica node)
1176 * @param bool $ssl if true, base URL will try to get called with https:// (works just for relative paths)
1178 * @throws HTTPException\InternalServerErrorException In Case the given URL is not relative to the Friendica node
1180 public function internalRedirect($toUrl = '', $ssl = false)
1182 if (!empty(parse_url($toUrl, PHP_URL_SCHEME))) {
1183 throw new HTTPException\InternalServerErrorException("'$toUrl is not a relative path, please use System::externalRedirectTo");
1186 $redirectTo = $this->baseURL->get($ssl) . '/' . ltrim($toUrl, '/');
1187 Core\System::externalRedirect($redirectTo);
1191 * Automatically redirects to relative or absolute URL
1192 * Should only be used if it isn't clear if the URL is either internal or external
1194 * @param string $toUrl The target URL
1196 * @throws HTTPException\InternalServerErrorException
1198 public function redirect($toUrl)
1200 if (!empty(parse_url($toUrl, PHP_URL_SCHEME))) {
1201 Core\System::externalRedirect($toUrl);
1203 $this->internalRedirect($toUrl);