8 use Friendica\App\Arguments;
9 use Friendica\App\BaseURL;
10 use Friendica\App\Page;
11 use Friendica\Core\Authentication;
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\Model\Profile;
20 use Friendica\Module\Login;
21 use Friendica\Module\Special\HTTPException as ModuleHTTPException;
22 use Friendica\Network\HTTPException;
23 use Friendica\Util\ConfigFileLoader;
24 use Friendica\Util\HTTPSignature;
25 use Friendica\Util\Profiler;
26 use Friendica\Util\Strings;
27 use Psr\Log\LoggerInterface;
33 * @brief Our main application structure for the life of this page.
35 * Primarily deals with the URL that got us here
36 * and tries to make some sense of it, and
37 * stores our page contents and config storage
38 * and anything else that might need to be passed around
39 * before we spit the page out.
44 /** @deprecated 2019.09 - use App\Arguments->getQueryString() */
47 * @var Page The current page environment
59 /** @deprecated 2019.09 - use App\Arguments->getCommand() */
61 /** @deprecated 2019.09 - use App\Arguments->getArgv() or Arguments->get() */
63 /** @deprecated 2019.09 - use App\Arguments->getArgc() */
65 /** @deprecated 2019.09 - Use App\Module->getName() instead */
68 public $interactive = true;
70 /** @deprecated 2019.09 - Use App\Mode->isMobile() instead */
72 /** @deprecated 2019.09 - Use App\Mode->isTable() instead */
74 public $theme_info = [];
76 // Allow themes to control internal parameters
77 // by changing App values in theme.php
79 public $sourcename = '';
80 public $videowidth = 425;
81 public $videoheight = 350;
82 public $force_max_items = 0;
83 public $theme_events_in_profile = true;
87 * @var App\Mode The Mode of the Application
96 /** @var string The name of the current theme */
97 private $currentTheme;
98 /** @var string The name of the current mobile theme */
99 private $currentMobileTheme;
102 * @var Configuration The config
107 * @var LoggerInterface The logger
112 * @var Profiler The profiler of this app
117 * @var Database The Friendica database connection
122 * @var L10n The translator
132 * @var Core\Process The process methods
137 * Returns the current config cache of this node
139 * @return ConfigCache
141 public function getConfigCache()
143 return $this->config->getCache();
147 * Returns the current config of this node
149 * @return Configuration
151 public function getConfig()
153 return $this->config;
157 * The basepath of this app
161 public function getBasePath()
163 // Don't use the basepath of the config table for basepath (it should always be the config-file one)
164 return $this->config->getCache()->get('system', 'basepath');
168 * The Logger of this app
170 * @return LoggerInterface
172 public function getLogger()
174 return $this->logger;
178 * The profiler of this app
182 public function getProfiler()
184 return $this->profiler;
188 * Returns the Mode of the Application
190 * @return App\Mode The Application Mode
192 public function getMode()
198 * Returns the Database of the Application
202 public function getDBA()
204 return $this->database;
208 * @deprecated 2019.09 - use Page->registerStylesheet instead
209 * @see Page::registerStylesheet()
211 public function registerStylesheet($path)
213 $this->page->registerStylesheet($path);
217 * @deprecated 2019.09 - use Page->registerFooterScript instead
218 * @see Page::registerFooterScript()
220 public function registerFooterScript($path)
222 $this->page->registerFooterScript($path);
226 * @param Database $database The Friendica Database
227 * @param Configuration $config The Configuration
228 * @param App\Mode $mode The mode of this Friendica app
229 * @param BaseURL $baseURL The full base URL of this Friendica app
230 * @param LoggerInterface $logger The current app logger
231 * @param Profiler $profiler The profiler of this application
232 * @param L10n $l10n The translator instance
233 * @param App\Arguments $args The Friendica Arguments of the call
234 * @param Core\Process $process The process methods
236 public function __construct(Database $database, Configuration $config, App\Mode $mode, BaseURL $baseURL, LoggerInterface $logger, Profiler $profiler, L10n $l10n, Arguments $args, App\Module $module, App\Page $page, Core\Process $process)
238 $this->database = $database;
239 $this->config = $config;
241 $this->baseURL = $baseURL;
242 $this->profiler = $profiler;
243 $this->logger = $logger;
246 $this->process = $process;
248 $this->cmd = $args->getCommand();
249 $this->argv = $args->getArgv();
250 $this->argc = $args->getArgc();
251 $this->query_string = $args->getQueryString();
252 $this->module = $module->getName();
255 $this->is_mobile = $mode->isMobile();
256 $this->is_tablet = $mode->isTablet();
262 * Load the whole app instance
264 public function load()
268 // This has to be quite large to deal with embedded private photos
269 ini_set('pcre.backtrack_limit', 500000);
272 get_include_path() . PATH_SEPARATOR
273 . $this->getBasePath() . DIRECTORY_SEPARATOR . 'include' . PATH_SEPARATOR
274 . $this->getBasePath() . DIRECTORY_SEPARATOR . 'library' . PATH_SEPARATOR
275 . $this->getBasePath());
277 $this->profiler->reset();
279 if ($this->mode->has(App\Mode::DBAVAILABLE)) {
280 $this->profiler->update($this->config);
282 Core\Hook::loadHooks();
283 $loader = new ConfigFileLoader($this->getBasePath());
284 Core\Hook::callAll('load_config', $loader);
287 $this->loadDefaultTimezone();
288 // Register template engines
289 Core\Renderer::registerTemplateEngine('Friendica\Render\FriendicaSmartyEngine');
293 * Loads the default timezone
295 * Include support for legacy $default_timezone
297 * @global string $default_timezone
299 private function loadDefaultTimezone()
301 if ($this->config->get('system', 'default_timezone')) {
302 $this->timezone = $this->config->get('system', 'default_timezone');
304 global $default_timezone;
305 $this->timezone = !empty($default_timezone) ? $default_timezone : 'UTC';
308 if ($this->timezone) {
309 date_default_timezone_set($this->timezone);
314 * Returns the scheme of the current call
318 * @deprecated 2019.06 - use BaseURL->getScheme() instead
320 public function getScheme()
322 return $this->baseURL->getScheme();
326 * Retrieves the Friendica instance base URL
328 * @param bool $ssl Whether to append http or https under BaseURL::SSL_POLICY_SELFSIGN
330 * @return string Friendica server base URL
332 * @deprecated 2019.09 - use BaseUrl->get($ssl) instead
334 public function getBaseURL($ssl = false)
336 return $this->baseURL->get($ssl);
340 * @brief Initializes the baseurl components
342 * Clears the baseurl cache to prevent inconsistencies
346 * @deprecated 2019.06 - use BaseURL->saveByURL($url) instead
348 public function setBaseURL($url)
350 $this->baseURL->saveByURL($url);
354 * Returns the current hostname
358 * @deprecated 2019.06 - use BaseURL->getHostname() instead
360 public function getHostName()
362 return $this->baseURL->getHostname();
366 * Returns the sub-path of the full URL
370 * @deprecated 2019.06 - use BaseURL->getUrlPath() instead
372 public function getURLPath()
374 return $this->baseURL->getUrlPath();
378 * @brief Removes the base url from an url. This avoids some mixed content problems.
380 * @param string $origURL
382 * @return string The cleaned url
384 * @deprecated 2019.09 - Use BaseURL->remove() instead
385 * @see BaseURL::remove()
387 public function removeBaseURL($origURL)
389 return $this->baseURL->remove($origURL);
393 * Returns the current UserAgent as a String
395 * @return string the UserAgent as a String
396 * @throws HTTPException\InternalServerErrorException
398 public function getUserAgent()
401 FRIENDICA_PLATFORM . " '" .
402 FRIENDICA_CODENAME . "' " .
403 FRIENDICA_VERSION . '-' .
404 DB_UPDATE_VERSION . '; ' .
409 * @deprecated 2019.09 - use Core\Process->isMaxProcessesReached() instead
411 public function isMaxProcessesReached()
413 return $this->process->isMaxProcessesReached();
417 * @deprecated 2019.09 - use Core\Process->isMinMemoryReached() instead
419 public function isMinMemoryReached()
421 return $this->process->isMinMemoryReached();
425 * @deprecated 2019.09 - use Core\Process->isMaxLoadReached() instead
427 public function isMaxLoadReached()
429 return $this->process->isMaxLoadReached();
433 * Generates the site's default sender email address
436 * @throws HTTPException\InternalServerErrorException
438 public function getSenderEmailAddress()
440 $sender_email = $this->config->get('config', 'sender_email');
441 if (empty($sender_email)) {
442 $hostname = $this->baseURL->getHostname();
443 if (strpos($hostname, ':')) {
444 $hostname = substr($hostname, 0, strpos($hostname, ':'));
447 $sender_email = 'noreply@' . $hostname;
450 return $sender_email;
454 * Returns the current theme name. May be overriden by the mobile theme name.
459 public function getCurrentTheme()
461 if ($this->mode->isInstall()) {
465 // Specific mobile theme override
466 if (($this->mode->isMobile() || $this->mode->isTablet()) && Core\Session::get('show-mobile', true)) {
467 $user_mobile_theme = $this->getCurrentMobileTheme();
469 // --- means same mobile theme as desktop
470 if (!empty($user_mobile_theme) && $user_mobile_theme !== '---') {
471 return $user_mobile_theme;
475 if (!$this->currentTheme) {
476 $this->computeCurrentTheme();
479 return $this->currentTheme;
483 * Returns the current mobile theme name.
488 public function getCurrentMobileTheme()
490 if ($this->mode->isInstall()) {
494 if (is_null($this->currentMobileTheme)) {
495 $this->computeCurrentMobileTheme();
498 return $this->currentMobileTheme;
501 public function setCurrentTheme($theme)
503 $this->currentTheme = $theme;
506 public function setCurrentMobileTheme($theme)
508 $this->currentMobileTheme = $theme;
512 * Computes the current theme name based on the node settings, the page owner settings and the user settings
516 private function computeCurrentTheme()
518 $system_theme = $this->config->get('system', 'theme');
519 if (!$system_theme) {
520 throw new Exception($this->l10n->t('No system theme config value set.'));
524 $this->setCurrentTheme($system_theme);
527 // Find the theme that belongs to the user whose stuff we are looking at
528 if ($this->profile_uid && ($this->profile_uid != local_user())) {
529 // Allow folks to override user themes and always use their own on their own site.
530 // This works only if the user is on the same server
531 $user = $this->database->selectFirst('user', ['theme'], ['uid' => $this->profile_uid]);
532 if ($this->database->isResult($user) && !Core\PConfig::get(local_user(), 'system', 'always_my_theme')) {
533 $page_theme = $user['theme'];
537 $theme_name = $page_theme ?: Core\Session::get('theme', $system_theme);
539 $theme_name = Strings::sanitizeFilePathItem($theme_name);
541 && in_array($theme_name, Theme::getAllowedList())
542 && (file_exists('view/theme/' . $theme_name . '/style.css')
543 || file_exists('view/theme/' . $theme_name . '/style.php'))
545 $this->setCurrentTheme($theme_name);
550 * Computes the current mobile theme name based on the node settings, the page owner settings and the user settings
552 private function computeCurrentMobileTheme()
554 $system_mobile_theme = $this->config->get('system', 'mobile-theme', '');
557 $this->setCurrentMobileTheme($system_mobile_theme);
559 $page_mobile_theme = null;
560 // Find the theme that belongs to the user whose stuff we are looking at
561 if ($this->profile_uid && ($this->profile_uid != local_user())) {
562 // Allow folks to override user themes and always use their own on their own site.
563 // This works only if the user is on the same server
564 if (!Core\PConfig::get(local_user(), 'system', 'always_my_theme')) {
565 $page_mobile_theme = Core\PConfig::get($this->profile_uid, 'system', 'mobile-theme');
569 $mobile_theme_name = $page_mobile_theme ?: Core\Session::get('mobile-theme', $system_mobile_theme);
571 $mobile_theme_name = Strings::sanitizeFilePathItem($mobile_theme_name);
572 if ($mobile_theme_name == '---'
574 in_array($mobile_theme_name, Theme::getAllowedList())
575 && (file_exists('view/theme/' . $mobile_theme_name . '/style.css')
576 || file_exists('view/theme/' . $mobile_theme_name . '/style.php'))
578 $this->setCurrentMobileTheme($mobile_theme_name);
583 * @brief Return full URL to theme which is currently in effect.
585 * Provide a sane default if nothing is chosen or the specified theme does not exist.
590 public function getCurrentThemeStylesheetPath()
592 return Core\Theme::getStylesheetPath($this->getCurrentTheme());
596 * @deprecated 2019.09 - use App\Mode->isAjax() instead
597 * @see App\Mode::isAjax()
599 public function isAjax()
601 return $this->mode->isAjax();
605 * @deprecated use Arguments->get() instead
609 public function getArgumentValue($position, $default = '')
611 return $this->args->get($position, $default);
615 * Sets the base url for use in cmdline programs which don't have
618 public function checkURL()
620 $url = $this->config->get('system', 'url');
622 // if the url isn't set or the stored url is radically different
623 // than the currently visited url, store the current value accordingly.
624 // "Radically different" ignores common variations such as http vs https
625 // and www.example.com vs example.com.
626 // We will only change the url to an ip address if there is no existing setting
628 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()))) {
629 $this->config->set('system', 'url', $this->getBaseURL());
634 * Frontend App script
636 * The App object behaves like a container and a dispatcher at the same time, including a representation of the
637 * request and a representation of the response.
639 * This probably should change to limit the size of this monster method.
641 * @param App\Module $module The determined module
642 * @param App\Router $router
643 * @param PConfiguration $pconfig
644 * @throws HTTPException\InternalServerErrorException
645 * @throws \ImagickException
647 public function runFrontend(App\Module $module, App\Router $router, PConfiguration $pconfig)
649 $moduleName = $module->getName();
652 // Missing DB connection: ERROR
653 if ($this->mode->has(App\Mode::LOCALCONFIGPRESENT) && !$this->mode->has(App\Mode::DBAVAILABLE)) {
654 throw new HTTPException\InternalServerErrorException('Apologies but the website is unavailable at the moment.');
657 // Max Load Average reached: ERROR
658 if ($this->process->isMaxProcessesReached() || $this->process->isMaxLoadReached()) {
659 header('Retry-After: 120');
660 header('Refresh: 120; url=' . $this->baseURL->get() . "/" . $this->args->getQueryString());
662 throw new HTTPException\ServiceUnavailableException('The node is currently overloaded. Please try again later.');
665 if (!$this->mode->isInstall()) {
666 // Force SSL redirection
667 if ($this->baseURL->checkRedirectHttps()) {
668 System::externalRedirect($this->baseURL->get() . '/' . $this->args->getQueryString());
671 Core\Session::init();
672 Core\Hook::callAll('init_1');
675 // Exclude the backend processes from the session management
676 if (!$this->mode->isBackend()) {
677 $stamp1 = microtime(true);
679 $this->profiler->saveTimestamp($stamp1, 'parser', Core\System::callstack());
680 $this->l10n->setSessionVariable();
681 $this->l10n->setLangFromSession();
684 Core\Worker::executeIfIdle();
687 if ($this->mode->isNormal()) {
688 $requester = HTTPSignature::getSigner('', $_SERVER);
689 if (!empty($requester)) {
690 Profile::addVisitorCookieForHandle($requester);
695 if (!empty($_GET['zrl']) && $this->mode->isNormal()) {
697 // Only continue when the given profile link seems valid
698 // Valid profile links contain a path with "/profile/" and no query parameters
699 if ((parse_url($_GET['zrl'], PHP_URL_QUERY) == "") &&
700 strstr(parse_url($_GET['zrl'], PHP_URL_PATH), "/profile/")) {
701 if (Core\Session::get('visitor_home') != $_GET["zrl"]) {
702 Core\Session::set('my_url', $_GET['zrl']);
703 Core\Session::set('authenticated', 0);
706 Model\Profile::zrlInit($this);
708 // Someone came with an invalid parameter, maybe as a DDoS attempt
709 // We simply stop processing here
710 $this->logger->debug('Invalid ZRL parameter.', ['zrl' => $_GET['zrl']]);
711 throw new HTTPException\ForbiddenException();
716 if (!empty($_GET['owt']) && $this->mode->isNormal()) {
717 $token = $_GET['owt'];
718 Model\Profile::openWebAuthInit($token);
721 Authentication::sessionAuth();
723 if (empty($_SESSION['authenticated'])) {
724 header('X-Account-Management-Status: none');
727 $_SESSION['sysmsg'] = Core\Session::get('sysmsg', []);
728 $_SESSION['sysmsg_info'] = Core\Session::get('sysmsg_info', []);
729 $_SESSION['last_updated'] = Core\Session::get('last_updated', []);
732 * check_config() is responsible for running update scripts. These automatically
733 * update the DB schema whenever we push a new one out. It also checks to see if
734 * any addons have been added or removed and reacts accordingly.
737 // in install mode, any url loads install module
738 // but we need "view" module for stylesheet
739 if ($this->mode->isInstall() && $moduleName !== 'install') {
740 $this->internalRedirect('install');
741 } elseif (!$this->mode->isInstall() && !$this->mode->has(App\Mode::MAINTENANCEDISABLED) && $moduleName !== 'maintenance') {
742 $this->internalRedirect('maintenance');
745 Core\Update::check($this->getBasePath(), false, $this->mode);
746 Core\Addon::loadAddons();
747 Core\Hook::loadHooks();
750 // Compatibility with the Android Diaspora client
751 if ($moduleName == 'stream') {
752 $this->internalRedirect('network?order=post');
755 if ($moduleName == 'conversations') {
756 $this->internalRedirect('message');
759 if ($moduleName == 'commented') {
760 $this->internalRedirect('network?order=comment');
763 if ($moduleName == 'liked') {
764 $this->internalRedirect('network?order=comment');
767 if ($moduleName == 'activity') {
768 $this->internalRedirect('network?conv=1');
771 if (($moduleName == 'status_messages') && ($this->args->getCommand() == 'status_messages/new')) {
772 $this->internalRedirect('bookmarklet');
775 if (($moduleName == 'user') && ($this->args->getCommand() == 'user/edit')) {
776 $this->internalRedirect('settings');
779 if (($moduleName == 'tag_followings') && ($this->args->getCommand() == 'tag_followings/manage')) {
780 $this->internalRedirect('search');
783 // Initialize module that can set the current theme in the init() method, either directly or via App->profile_uid
784 $this->page['page_title'] = $moduleName;
786 // determine the module class and save it to the module instance
787 // @todo there's an implicit dependency due SESSION::start(), so it has to be called here (yet)
788 $module = $module->determineClass($this->args, $router, $this->config);
790 // Let the module run it's internal process (init, get, post, ...)
791 $module->run($this->l10n, $this, $this->logger, $_SERVER, $_POST);
792 } catch (HTTPException $e) {
793 ModuleHTTPException::rawContent($e);
796 $this->page->run($this, $this->baseURL, $this->mode, $module, $this->l10n, $this->config, $pconfig);
800 * @deprecated 2019.12 use BaseUrl::redirect instead
801 * @see BaseURL::redirect()
803 public function internalRedirect($toUrl = '', $ssl = false)
805 $this->baseURL->redirect($toUrl, $ssl);
809 * Automatically redirects to relative or absolute URL
810 * Should only be used if it isn't clear if the URL is either internal or external
812 * @param string $toUrl The target URL
814 * @throws HTTPException\InternalServerErrorException
816 public function redirect($toUrl)
818 if (!empty(parse_url($toUrl, PHP_URL_SCHEME))) {
819 Core\System::externalRedirect($toUrl);
821 $this->baseURL->redirect($toUrl);