8 use Friendica\App\Arguments;
9 use Friendica\App\BaseURL;
10 use Friendica\App\Page;
11 use Friendica\App\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\Session;
17 use Friendica\Core\System;
18 use Friendica\Core\Theme;
19 use Friendica\Database\Database;
20 use Friendica\Model\Profile;
21 use Friendica\Module\Security\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() */
48 * @var Page The current page environment
60 /** @deprecated 2019.09 - use App\Arguments->getCommand() */
62 /** @deprecated 2019.09 - use App\Arguments->getArgv() or Arguments->get() */
64 /** @deprecated 2019.09 - use App\Arguments->getArgc() */
66 /** @deprecated 2019.09 - Use App\Module->getName() instead */
69 public $interactive = true;
71 /** @deprecated 2019.09 - Use App\Mode->isMobile() instead */
73 /** @deprecated 2019.09 - Use App\Mode->isTable() instead */
75 public $theme_info = [];
77 // Allow themes to control internal parameters
78 // by changing App values in theme.php
80 public $sourcename = '';
81 public $videowidth = 425;
82 public $videoheight = 350;
83 public $force_max_items = 0;
84 public $theme_events_in_profile = true;
88 * @var App\Mode The Mode of the Application
97 /** @var string The name of the current theme */
98 private $currentTheme;
99 /** @var string The name of the current mobile theme */
100 private $currentMobileTheme;
103 * @var Configuration The config
108 * @var LoggerInterface The logger
113 * @var Profiler The profiler of this app
118 * @var Database The Friendica database connection
123 * @var L10n The translator
133 * @var Core\Process The process methods
138 * Returns the current config cache of this node
140 * @return ConfigCache
142 public function getConfigCache()
144 return $this->config->getCache();
148 * The basepath of this app
152 public function getBasePath()
154 // Don't use the basepath of the config table for basepath (it should always be the config-file one)
155 return $this->config->getCache()->get('system', 'basepath');
159 * The Logger of this app
161 * @return LoggerInterface
163 public function getLogger()
165 return $this->logger;
169 * The profiler of this app
173 public function getProfiler()
175 return $this->profiler;
179 * Returns the Mode of the Application
181 * @return App\Mode The Application Mode
183 public function getMode()
189 * Returns the Database of the Application
193 public function getDBA()
195 return $this->database;
199 * @deprecated 2019.09 - use Page->registerStylesheet instead
200 * @see Page::registerStylesheet()
202 public function registerStylesheet($path)
204 $this->page->registerStylesheet($path);
208 * @deprecated 2019.09 - use Page->registerFooterScript instead
209 * @see Page::registerFooterScript()
211 public function registerFooterScript($path)
213 $this->page->registerFooterScript($path);
217 * @param Database $database The Friendica Database
218 * @param Configuration $config The Configuration
219 * @param App\Mode $mode The mode of this Friendica app
220 * @param BaseURL $baseURL The full base URL of this Friendica app
221 * @param LoggerInterface $logger The current app logger
222 * @param Profiler $profiler The profiler of this application
223 * @param L10n $l10n The translator instance
224 * @param App\Arguments $args The Friendica Arguments of the call
225 * @param Core\Process $process The process methods
227 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)
229 $this->database = $database;
230 $this->config = $config;
232 $this->baseURL = $baseURL;
233 $this->profiler = $profiler;
234 $this->logger = $logger;
237 $this->process = $process;
239 $this->cmd = $args->getCommand();
240 $this->argv = $args->getArgv();
241 $this->argc = $args->getArgc();
242 $this->query_string = $args->getQueryString();
243 $this->module = $module->getName();
246 $this->is_mobile = $mode->isMobile();
247 $this->is_tablet = $mode->isTablet();
253 * Load the whole app instance
255 public function load()
259 // This has to be quite large to deal with embedded private photos
260 ini_set('pcre.backtrack_limit', 500000);
263 get_include_path() . PATH_SEPARATOR
264 . $this->getBasePath() . DIRECTORY_SEPARATOR . 'include' . PATH_SEPARATOR
265 . $this->getBasePath() . DIRECTORY_SEPARATOR . 'library' . PATH_SEPARATOR
266 . $this->getBasePath());
268 $this->profiler->reset();
270 if ($this->mode->has(App\Mode::DBAVAILABLE)) {
271 $this->profiler->update($this->config);
273 Core\Hook::loadHooks();
274 $loader = new ConfigFileLoader($this->getBasePath());
275 Core\Hook::callAll('load_config', $loader);
278 $this->loadDefaultTimezone();
279 // Register template engines
280 Core\Renderer::registerTemplateEngine('Friendica\Render\FriendicaSmartyEngine');
284 * Loads the default timezone
286 * Include support for legacy $default_timezone
288 * @global string $default_timezone
290 private function loadDefaultTimezone()
292 if ($this->config->get('system', 'default_timezone')) {
293 $this->timezone = $this->config->get('system', 'default_timezone');
295 global $default_timezone;
296 $this->timezone = !empty($default_timezone) ? $default_timezone : 'UTC';
299 if ($this->timezone) {
300 date_default_timezone_set($this->timezone);
305 * Returns the scheme of the current call
309 * @deprecated 2019.06 - use BaseURL->getScheme() instead
311 public function getScheme()
313 return $this->baseURL->getScheme();
317 * Retrieves the Friendica instance base URL
319 * @param bool $ssl Whether to append http or https under BaseURL::SSL_POLICY_SELFSIGN
321 * @return string Friendica server base URL
323 * @deprecated 2019.09 - use BaseUrl->get($ssl) instead
325 public function getBaseURL($ssl = false)
327 return $this->baseURL->get($ssl);
331 * @brief Initializes the baseurl components
333 * Clears the baseurl cache to prevent inconsistencies
337 * @deprecated 2019.06 - use BaseURL->saveByURL($url) instead
339 public function setBaseURL($url)
341 $this->baseURL->saveByURL($url);
345 * Returns the current hostname
349 * @deprecated 2019.06 - use BaseURL->getHostname() instead
351 public function getHostName()
353 return $this->baseURL->getHostname();
357 * Returns the sub-path of the full URL
361 * @deprecated 2019.06 - use BaseURL->getUrlPath() instead
363 public function getURLPath()
365 return $this->baseURL->getUrlPath();
369 * @brief Removes the base url from an url. This avoids some mixed content problems.
371 * @param string $origURL
373 * @return string The cleaned url
375 * @deprecated 2019.09 - Use BaseURL->remove() instead
376 * @see BaseURL::remove()
378 public function removeBaseURL(string $origURL)
380 return $this->baseURL->remove($origURL);
384 * Returns the current UserAgent as a String
386 * @return string the UserAgent as a String
387 * @throws HTTPException\InternalServerErrorException
389 public function getUserAgent()
392 FRIENDICA_PLATFORM . " '" .
393 FRIENDICA_CODENAME . "' " .
394 FRIENDICA_VERSION . '-' .
395 DB_UPDATE_VERSION . '; ' .
400 * @deprecated 2019.09 - use Core\Process->isMaxProcessesReached() instead
402 public function isMaxProcessesReached()
404 return $this->process->isMaxProcessesReached();
408 * @deprecated 2019.09 - use Core\Process->isMinMemoryReached() instead
410 public function isMinMemoryReached()
412 return $this->process->isMinMemoryReached();
416 * @deprecated 2019.09 - use Core\Process->isMaxLoadReached() instead
418 public function isMaxLoadReached()
420 return $this->process->isMaxLoadReached();
424 * Generates the site's default sender email address
427 * @throws HTTPException\InternalServerErrorException
429 public function getSenderEmailAddress()
431 $sender_email = $this->config->get('config', 'sender_email');
432 if (empty($sender_email)) {
433 $hostname = $this->baseURL->getHostname();
434 if (strpos($hostname, ':')) {
435 $hostname = substr($hostname, 0, strpos($hostname, ':'));
438 $sender_email = 'noreply@' . $hostname;
441 return $sender_email;
445 * Returns the current theme name. May be overriden by the mobile theme name.
450 public function getCurrentTheme()
452 if ($this->mode->isInstall()) {
456 // Specific mobile theme override
457 if (($this->mode->isMobile() || $this->mode->isTablet()) && Core\Session::get('show-mobile', true)) {
458 $user_mobile_theme = $this->getCurrentMobileTheme();
460 // --- means same mobile theme as desktop
461 if (!empty($user_mobile_theme) && $user_mobile_theme !== '---') {
462 return $user_mobile_theme;
466 if (!$this->currentTheme) {
467 $this->computeCurrentTheme();
470 return $this->currentTheme;
474 * Returns the current mobile theme name.
479 public function getCurrentMobileTheme()
481 if ($this->mode->isInstall()) {
485 if (is_null($this->currentMobileTheme)) {
486 $this->computeCurrentMobileTheme();
489 return $this->currentMobileTheme;
492 public function setCurrentTheme($theme)
494 $this->currentTheme = $theme;
497 public function setCurrentMobileTheme($theme)
499 $this->currentMobileTheme = $theme;
503 * Computes the current theme name based on the node settings, the page owner settings and the user settings
507 private function computeCurrentTheme()
509 $system_theme = $this->config->get('system', 'theme');
510 if (!$system_theme) {
511 throw new Exception($this->l10n->t('No system theme config value set.'));
515 $this->setCurrentTheme($system_theme);
518 // Find the theme that belongs to the user whose stuff we are looking at
519 if ($this->profile_uid && ($this->profile_uid != local_user())) {
520 // Allow folks to override user themes and always use their own on their own site.
521 // This works only if the user is on the same server
522 $user = $this->database->selectFirst('user', ['theme'], ['uid' => $this->profile_uid]);
523 if ($this->database->isResult($user) && !Core\PConfig::get(local_user(), 'system', 'always_my_theme')) {
524 $page_theme = $user['theme'];
528 $theme_name = $page_theme ?: Core\Session::get('theme', $system_theme);
530 $theme_name = Strings::sanitizeFilePathItem($theme_name);
532 && in_array($theme_name, Theme::getAllowedList())
533 && (file_exists('view/theme/' . $theme_name . '/style.css')
534 || file_exists('view/theme/' . $theme_name . '/style.php'))
536 $this->setCurrentTheme($theme_name);
541 * Computes the current mobile theme name based on the node settings, the page owner settings and the user settings
543 private function computeCurrentMobileTheme()
545 $system_mobile_theme = $this->config->get('system', 'mobile-theme', '');
548 $this->setCurrentMobileTheme($system_mobile_theme);
550 $page_mobile_theme = null;
551 // Find the theme that belongs to the user whose stuff we are looking at
552 if ($this->profile_uid && ($this->profile_uid != local_user())) {
553 // Allow folks to override user themes and always use their own on their own site.
554 // This works only if the user is on the same server
555 if (!Core\PConfig::get(local_user(), 'system', 'always_my_theme')) {
556 $page_mobile_theme = Core\PConfig::get($this->profile_uid, 'system', 'mobile-theme');
560 $mobile_theme_name = $page_mobile_theme ?: Core\Session::get('mobile-theme', $system_mobile_theme);
562 $mobile_theme_name = Strings::sanitizeFilePathItem($mobile_theme_name);
563 if ($mobile_theme_name == '---'
565 in_array($mobile_theme_name, Theme::getAllowedList())
566 && (file_exists('view/theme/' . $mobile_theme_name . '/style.css')
567 || file_exists('view/theme/' . $mobile_theme_name . '/style.php'))
569 $this->setCurrentMobileTheme($mobile_theme_name);
574 * @brief Return full URL to theme which is currently in effect.
576 * Provide a sane default if nothing is chosen or the specified theme does not exist.
581 public function getCurrentThemeStylesheetPath()
583 return Core\Theme::getStylesheetPath($this->getCurrentTheme());
587 * @deprecated 2019.09 - use App\Mode->isAjax() instead
588 * @see App\Mode::isAjax()
590 public function isAjax()
592 return $this->mode->isAjax();
596 * @deprecated use Arguments->get() instead
600 public function getArgumentValue($position, $default = '')
602 return $this->args->get($position, $default);
606 * Sets the base url for use in cmdline programs which don't have
609 public function checkURL()
611 $url = $this->config->get('system', 'url');
613 // if the url isn't set or the stored url is radically different
614 // than the currently visited url, store the current value accordingly.
615 // "Radically different" ignores common variations such as http vs https
616 // and www.example.com vs example.com.
617 // We will only change the url to an ip address if there is no existing setting
619 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()))) {
620 $this->config->set('system', 'url', $this->getBaseURL());
625 * Frontend App script
627 * The App object behaves like a container and a dispatcher at the same time, including a representation of the
628 * request and a representation of the response.
630 * This probably should change to limit the size of this monster method.
632 * @param App\Module $module The determined module
633 * @param App\Router $router
634 * @param PConfiguration $pconfig
635 * @param Authentication $auth The Authentication backend of the node
636 * @throws HTTPException\InternalServerErrorException
637 * @throws \ImagickException
639 public function runFrontend(App\Module $module, App\Router $router, PConfiguration $pconfig, Authentication $auth)
641 $moduleName = $module->getName();
644 // Missing DB connection: ERROR
645 if ($this->mode->has(App\Mode::LOCALCONFIGPRESENT) && !$this->mode->has(App\Mode::DBAVAILABLE)) {
646 throw new HTTPException\InternalServerErrorException('Apologies but the website is unavailable at the moment.');
649 // Max Load Average reached: ERROR
650 if ($this->process->isMaxProcessesReached() || $this->process->isMaxLoadReached()) {
651 header('Retry-After: 120');
652 header('Refresh: 120; url=' . $this->baseURL->get() . "/" . $this->args->getQueryString());
654 throw new HTTPException\ServiceUnavailableException('The node is currently overloaded. Please try again later.');
657 if (!$this->mode->isInstall()) {
658 // Force SSL redirection
659 if ($this->baseURL->checkRedirectHttps()) {
660 System::externalRedirect($this->baseURL->get() . '/' . $this->args->getQueryString());
663 Core\Hook::callAll('init_1');
666 // Exclude the backend processes from the session management
667 if ($this->mode->isBackend()) {
668 Core\Worker::executeIfIdle();
671 if ($this->mode->isNormal()) {
672 $requester = HTTPSignature::getSigner('', $_SERVER);
673 if (!empty($requester)) {
674 Profile::addVisitorCookieForHandle($requester);
679 if (!empty($_GET['zrl']) && $this->mode->isNormal()) {
681 // Only continue when the given profile link seems valid
682 // Valid profile links contain a path with "/profile/" and no query parameters
683 if ((parse_url($_GET['zrl'], PHP_URL_QUERY) == "") &&
684 strstr(parse_url($_GET['zrl'], PHP_URL_PATH), "/profile/")) {
685 if (Core\Session::get('visitor_home') != $_GET["zrl"]) {
686 Core\Session::set('my_url', $_GET['zrl']);
687 Core\Session::set('authenticated', 0);
690 Model\Profile::zrlInit($this);
692 // Someone came with an invalid parameter, maybe as a DDoS attempt
693 // We simply stop processing here
694 $this->logger->debug('Invalid ZRL parameter.', ['zrl' => $_GET['zrl']]);
695 throw new HTTPException\ForbiddenException();
700 if (!empty($_GET['owt']) && $this->mode->isNormal()) {
701 $token = $_GET['owt'];
702 Model\Profile::openWebAuthInit($token);
705 $auth->withSession($this);
707 if (empty($_SESSION['authenticated'])) {
708 header('X-Account-Management-Status: none');
711 $_SESSION['sysmsg'] = Core\Session::get('sysmsg', []);
712 $_SESSION['sysmsg_info'] = Core\Session::get('sysmsg_info', []);
713 $_SESSION['last_updated'] = Core\Session::get('last_updated', []);
716 * check_config() is responsible for running update scripts. These automatically
717 * update the DB schema whenever we push a new one out. It also checks to see if
718 * any addons have been added or removed and reacts accordingly.
721 // in install mode, any url loads install module
722 // but we need "view" module for stylesheet
723 if ($this->mode->isInstall() && $moduleName !== 'install') {
724 $this->internalRedirect('install');
725 } elseif (!$this->mode->isInstall() && !$this->mode->has(App\Mode::MAINTENANCEDISABLED) && $moduleName !== 'maintenance') {
726 $this->internalRedirect('maintenance');
729 Core\Update::check($this->getBasePath(), false, $this->mode);
730 Core\Addon::loadAddons();
731 Core\Hook::loadHooks();
734 // Compatibility with the Android Diaspora client
735 if ($moduleName == 'stream') {
736 $this->internalRedirect('network?order=post');
739 if ($moduleName == 'conversations') {
740 $this->internalRedirect('message');
743 if ($moduleName == 'commented') {
744 $this->internalRedirect('network?order=comment');
747 if ($moduleName == 'liked') {
748 $this->internalRedirect('network?order=comment');
751 if ($moduleName == 'activity') {
752 $this->internalRedirect('network?conv=1');
755 if (($moduleName == 'status_messages') && ($this->args->getCommand() == 'status_messages/new')) {
756 $this->internalRedirect('bookmarklet');
759 if (($moduleName == 'user') && ($this->args->getCommand() == 'user/edit')) {
760 $this->internalRedirect('settings');
763 if (($moduleName == 'tag_followings') && ($this->args->getCommand() == 'tag_followings/manage')) {
764 $this->internalRedirect('search');
767 // Initialize module that can set the current theme in the init() method, either directly or via App->profile_uid
768 $this->page['page_title'] = $moduleName;
770 // determine the module class and save it to the module instance
771 // @todo there's an implicit dependency due SESSION::start(), so it has to be called here (yet)
772 $module = $module->determineClass($this->args, $router, $this->config);
774 // Let the module run it's internal process (init, get, post, ...)
775 $module->run($this->l10n, $this, $this->logger, $_SERVER, $_POST);
776 } catch (HTTPException $e) {
777 ModuleHTTPException::rawContent($e);
780 $this->page->run($this, $this->baseURL, $this->mode, $module, $this->l10n, $this->config, $pconfig);
784 * @deprecated 2019.12 use BaseUrl::redirect instead
785 * @see BaseURL::redirect()
787 public function internalRedirect($toUrl = '', $ssl = false)
789 $this->baseURL->redirect($toUrl, $ssl);
793 * Automatically redirects to relative or absolute URL
794 * Should only be used if it isn't clear if the URL is either internal or external
796 * @param string $toUrl The target URL
798 * @throws HTTPException\InternalServerErrorException
800 public function redirect($toUrl)
802 if (!empty(parse_url($toUrl, PHP_URL_SCHEME))) {
803 Core\System::externalRedirect($toUrl);
805 $this->baseURL->redirect($toUrl);