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\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 * Returns the current config of this node
150 * @return Configuration
152 public function getConfig()
154 return $this->config;
158 * The basepath of this app
162 public function getBasePath()
164 // Don't use the basepath of the config table for basepath (it should always be the config-file one)
165 return $this->config->getCache()->get('system', 'basepath');
169 * The Logger of this app
171 * @return LoggerInterface
173 public function getLogger()
175 return $this->logger;
179 * The profiler of this app
183 public function getProfiler()
185 return $this->profiler;
189 * Returns the Mode of the Application
191 * @return App\Mode The Application Mode
193 public function getMode()
199 * Returns the Database of the Application
203 public function getDBA()
205 return $this->database;
209 * @deprecated 2019.09 - use Page->registerStylesheet instead
210 * @see Page::registerStylesheet()
212 public function registerStylesheet($path)
214 $this->page->registerStylesheet($path);
218 * @deprecated 2019.09 - use Page->registerFooterScript instead
219 * @see Page::registerFooterScript()
221 public function registerFooterScript($path)
223 $this->page->registerFooterScript($path);
227 * @param Database $database The Friendica Database
228 * @param Configuration $config The Configuration
229 * @param App\Mode $mode The mode of this Friendica app
230 * @param BaseURL $baseURL The full base URL of this Friendica app
231 * @param LoggerInterface $logger The current app logger
232 * @param Profiler $profiler The profiler of this application
233 * @param L10n $l10n The translator instance
234 * @param App\Arguments $args The Friendica Arguments of the call
235 * @param Core\Process $process The process methods
237 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)
239 $this->database = $database;
240 $this->config = $config;
242 $this->baseURL = $baseURL;
243 $this->profiler = $profiler;
244 $this->logger = $logger;
247 $this->process = $process;
249 $this->cmd = $args->getCommand();
250 $this->argv = $args->getArgv();
251 $this->argc = $args->getArgc();
252 $this->query_string = $args->getQueryString();
253 $this->module = $module->getName();
256 $this->is_mobile = $mode->isMobile();
257 $this->is_tablet = $mode->isTablet();
263 * Load the whole app instance
265 public function load()
269 // This has to be quite large to deal with embedded private photos
270 ini_set('pcre.backtrack_limit', 500000);
273 get_include_path() . PATH_SEPARATOR
274 . $this->getBasePath() . DIRECTORY_SEPARATOR . 'include' . PATH_SEPARATOR
275 . $this->getBasePath() . DIRECTORY_SEPARATOR . 'library' . PATH_SEPARATOR
276 . $this->getBasePath());
278 $this->profiler->reset();
280 if ($this->mode->has(App\Mode::DBAVAILABLE)) {
281 $this->profiler->update($this->config);
283 Core\Hook::loadHooks();
284 $loader = new ConfigFileLoader($this->getBasePath());
285 Core\Hook::callAll('load_config', $loader);
288 $this->loadDefaultTimezone();
289 // Register template engines
290 Core\Renderer::registerTemplateEngine('Friendica\Render\FriendicaSmartyEngine');
294 * Loads the default timezone
296 * Include support for legacy $default_timezone
298 * @global string $default_timezone
300 private function loadDefaultTimezone()
302 if ($this->config->get('system', 'default_timezone')) {
303 $this->timezone = $this->config->get('system', 'default_timezone');
305 global $default_timezone;
306 $this->timezone = !empty($default_timezone) ? $default_timezone : 'UTC';
309 if ($this->timezone) {
310 date_default_timezone_set($this->timezone);
315 * Returns the scheme of the current call
319 * @deprecated 2019.06 - use BaseURL->getScheme() instead
321 public function getScheme()
323 return $this->baseURL->getScheme();
327 * Retrieves the Friendica instance base URL
329 * @param bool $ssl Whether to append http or https under BaseURL::SSL_POLICY_SELFSIGN
331 * @return string Friendica server base URL
333 * @deprecated 2019.09 - use BaseUrl->get($ssl) instead
335 public function getBaseURL($ssl = false)
337 return $this->baseURL->get($ssl);
341 * @brief Initializes the baseurl components
343 * Clears the baseurl cache to prevent inconsistencies
347 * @deprecated 2019.06 - use BaseURL->saveByURL($url) instead
349 public function setBaseURL($url)
351 $this->baseURL->saveByURL($url);
355 * Returns the current hostname
359 * @deprecated 2019.06 - use BaseURL->getHostname() instead
361 public function getHostName()
363 return $this->baseURL->getHostname();
367 * Returns the sub-path of the full URL
371 * @deprecated 2019.06 - use BaseURL->getUrlPath() instead
373 public function getURLPath()
375 return $this->baseURL->getUrlPath();
379 * @brief Removes the base url from an url. This avoids some mixed content problems.
381 * @param string $origURL
383 * @return string The cleaned url
385 * @deprecated 2019.09 - Use BaseURL->remove() instead
386 * @see BaseURL::remove()
388 public function removeBaseURL(string $origURL)
390 return $this->baseURL->remove($origURL);
394 * Returns the current UserAgent as a String
396 * @return string the UserAgent as a String
397 * @throws HTTPException\InternalServerErrorException
399 public function getUserAgent()
402 FRIENDICA_PLATFORM . " '" .
403 FRIENDICA_CODENAME . "' " .
404 FRIENDICA_VERSION . '-' .
405 DB_UPDATE_VERSION . '; ' .
410 * @deprecated 2019.09 - use Core\Process->isMaxProcessesReached() instead
412 public function isMaxProcessesReached()
414 return $this->process->isMaxProcessesReached();
418 * @deprecated 2019.09 - use Core\Process->isMinMemoryReached() instead
420 public function isMinMemoryReached()
422 return $this->process->isMinMemoryReached();
426 * @deprecated 2019.09 - use Core\Process->isMaxLoadReached() instead
428 public function isMaxLoadReached()
430 return $this->process->isMaxLoadReached();
434 * Generates the site's default sender email address
437 * @throws HTTPException\InternalServerErrorException
439 public function getSenderEmailAddress()
441 $sender_email = $this->config->get('config', 'sender_email');
442 if (empty($sender_email)) {
443 $hostname = $this->baseURL->getHostname();
444 if (strpos($hostname, ':')) {
445 $hostname = substr($hostname, 0, strpos($hostname, ':'));
448 $sender_email = 'noreply@' . $hostname;
451 return $sender_email;
455 * Returns the current theme name. May be overriden by the mobile theme name.
460 public function getCurrentTheme()
462 if ($this->mode->isInstall()) {
466 // Specific mobile theme override
467 if (($this->mode->isMobile() || $this->mode->isTablet()) && Core\Session::get('show-mobile', true)) {
468 $user_mobile_theme = $this->getCurrentMobileTheme();
470 // --- means same mobile theme as desktop
471 if (!empty($user_mobile_theme) && $user_mobile_theme !== '---') {
472 return $user_mobile_theme;
476 if (!$this->currentTheme) {
477 $this->computeCurrentTheme();
480 return $this->currentTheme;
484 * Returns the current mobile theme name.
489 public function getCurrentMobileTheme()
491 if ($this->mode->isInstall()) {
495 if (is_null($this->currentMobileTheme)) {
496 $this->computeCurrentMobileTheme();
499 return $this->currentMobileTheme;
502 public function setCurrentTheme($theme)
504 $this->currentTheme = $theme;
507 public function setCurrentMobileTheme($theme)
509 $this->currentMobileTheme = $theme;
513 * Computes the current theme name based on the node settings, the page owner settings and the user settings
517 private function computeCurrentTheme()
519 $system_theme = $this->config->get('system', 'theme');
520 if (!$system_theme) {
521 throw new Exception($this->l10n->t('No system theme config value set.'));
525 $this->setCurrentTheme($system_theme);
528 // Find the theme that belongs to the user whose stuff we are looking at
529 if ($this->profile_uid && ($this->profile_uid != local_user())) {
530 // Allow folks to override user themes and always use their own on their own site.
531 // This works only if the user is on the same server
532 $user = $this->database->selectFirst('user', ['theme'], ['uid' => $this->profile_uid]);
533 if ($this->database->isResult($user) && !Core\PConfig::get(local_user(), 'system', 'always_my_theme')) {
534 $page_theme = $user['theme'];
538 $theme_name = $page_theme ?: Core\Session::get('theme', $system_theme);
540 $theme_name = Strings::sanitizeFilePathItem($theme_name);
542 && in_array($theme_name, Theme::getAllowedList())
543 && (file_exists('view/theme/' . $theme_name . '/style.css')
544 || file_exists('view/theme/' . $theme_name . '/style.php'))
546 $this->setCurrentTheme($theme_name);
551 * Computes the current mobile theme name based on the node settings, the page owner settings and the user settings
553 private function computeCurrentMobileTheme()
555 $system_mobile_theme = $this->config->get('system', 'mobile-theme', '');
558 $this->setCurrentMobileTheme($system_mobile_theme);
560 $page_mobile_theme = null;
561 // Find the theme that belongs to the user whose stuff we are looking at
562 if ($this->profile_uid && ($this->profile_uid != local_user())) {
563 // Allow folks to override user themes and always use their own on their own site.
564 // This works only if the user is on the same server
565 if (!Core\PConfig::get(local_user(), 'system', 'always_my_theme')) {
566 $page_mobile_theme = Core\PConfig::get($this->profile_uid, 'system', 'mobile-theme');
570 $mobile_theme_name = $page_mobile_theme ?: Core\Session::get('mobile-theme', $system_mobile_theme);
572 $mobile_theme_name = Strings::sanitizeFilePathItem($mobile_theme_name);
573 if ($mobile_theme_name == '---'
575 in_array($mobile_theme_name, Theme::getAllowedList())
576 && (file_exists('view/theme/' . $mobile_theme_name . '/style.css')
577 || file_exists('view/theme/' . $mobile_theme_name . '/style.php'))
579 $this->setCurrentMobileTheme($mobile_theme_name);
584 * @brief Return full URL to theme which is currently in effect.
586 * Provide a sane default if nothing is chosen or the specified theme does not exist.
591 public function getCurrentThemeStylesheetPath()
593 return Core\Theme::getStylesheetPath($this->getCurrentTheme());
597 * @deprecated 2019.09 - use App\Mode->isAjax() instead
598 * @see App\Mode::isAjax()
600 public function isAjax()
602 return $this->mode->isAjax();
606 * @deprecated use Arguments->get() instead
610 public function getArgumentValue($position, $default = '')
612 return $this->args->get($position, $default);
616 * Sets the base url for use in cmdline programs which don't have
619 public function checkURL()
621 $url = $this->config->get('system', 'url');
623 // if the url isn't set or the stored url is radically different
624 // than the currently visited url, store the current value accordingly.
625 // "Radically different" ignores common variations such as http vs https
626 // and www.example.com vs example.com.
627 // We will only change the url to an ip address if there is no existing setting
629 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()))) {
630 $this->config->set('system', 'url', $this->getBaseURL());
635 * Frontend App script
637 * The App object behaves like a container and a dispatcher at the same time, including a representation of the
638 * request and a representation of the response.
640 * This probably should change to limit the size of this monster method.
642 * @param App\Module $module The determined module
643 * @param App\Router $router
644 * @param PConfiguration $pconfig
645 * @param Authentication $auth The Authentication backend of the node
646 * @throws HTTPException\InternalServerErrorException
647 * @throws \ImagickException
649 public function runFrontend(App\Module $module, App\Router $router, PConfiguration $pconfig, Authentication $auth)
651 $moduleName = $module->getName();
654 // Missing DB connection: ERROR
655 if ($this->mode->has(App\Mode::LOCALCONFIGPRESENT) && !$this->mode->has(App\Mode::DBAVAILABLE)) {
656 throw new HTTPException\InternalServerErrorException('Apologies but the website is unavailable at the moment.');
659 // Max Load Average reached: ERROR
660 if ($this->process->isMaxProcessesReached() || $this->process->isMaxLoadReached()) {
661 header('Retry-After: 120');
662 header('Refresh: 120; url=' . $this->baseURL->get() . "/" . $this->args->getQueryString());
664 throw new HTTPException\ServiceUnavailableException('The node is currently overloaded. Please try again later.');
667 if (!$this->mode->isInstall()) {
668 // Force SSL redirection
669 if ($this->baseURL->checkRedirectHttps()) {
670 System::externalRedirect($this->baseURL->get() . '/' . $this->args->getQueryString());
673 Core\Hook::callAll('init_1');
676 // Exclude the backend processes from the session management
677 if ($this->mode->isBackend()) {
678 Core\Worker::executeIfIdle();
681 if ($this->mode->isNormal()) {
682 $requester = HTTPSignature::getSigner('', $_SERVER);
683 if (!empty($requester)) {
684 Profile::addVisitorCookieForHandle($requester);
689 if (!empty($_GET['zrl']) && $this->mode->isNormal()) {
691 // Only continue when the given profile link seems valid
692 // Valid profile links contain a path with "/profile/" and no query parameters
693 if ((parse_url($_GET['zrl'], PHP_URL_QUERY) == "") &&
694 strstr(parse_url($_GET['zrl'], PHP_URL_PATH), "/profile/")) {
695 if (Core\Session::get('visitor_home') != $_GET["zrl"]) {
696 Core\Session::set('my_url', $_GET['zrl']);
697 Core\Session::set('authenticated', 0);
700 Model\Profile::zrlInit($this);
702 // Someone came with an invalid parameter, maybe as a DDoS attempt
703 // We simply stop processing here
704 $this->logger->debug('Invalid ZRL parameter.', ['zrl' => $_GET['zrl']]);
705 throw new HTTPException\ForbiddenException();
710 if (!empty($_GET['owt']) && $this->mode->isNormal()) {
711 $token = $_GET['owt'];
712 Model\Profile::openWebAuthInit($token);
715 $auth->withSession($this);
717 if (empty($_SESSION['authenticated'])) {
718 header('X-Account-Management-Status: none');
721 $_SESSION['sysmsg'] = Core\Session::get('sysmsg', []);
722 $_SESSION['sysmsg_info'] = Core\Session::get('sysmsg_info', []);
723 $_SESSION['last_updated'] = Core\Session::get('last_updated', []);
726 * check_config() is responsible for running update scripts. These automatically
727 * update the DB schema whenever we push a new one out. It also checks to see if
728 * any addons have been added or removed and reacts accordingly.
731 // in install mode, any url loads install module
732 // but we need "view" module for stylesheet
733 if ($this->mode->isInstall() && $moduleName !== 'install') {
734 $this->internalRedirect('install');
735 } elseif (!$this->mode->isInstall() && !$this->mode->has(App\Mode::MAINTENANCEDISABLED) && $moduleName !== 'maintenance') {
736 $this->internalRedirect('maintenance');
739 Core\Update::check($this->getBasePath(), false, $this->mode);
740 Core\Addon::loadAddons();
741 Core\Hook::loadHooks();
744 // Compatibility with the Android Diaspora client
745 if ($moduleName == 'stream') {
746 $this->internalRedirect('network?order=post');
749 if ($moduleName == 'conversations') {
750 $this->internalRedirect('message');
753 if ($moduleName == 'commented') {
754 $this->internalRedirect('network?order=comment');
757 if ($moduleName == 'liked') {
758 $this->internalRedirect('network?order=comment');
761 if ($moduleName == 'activity') {
762 $this->internalRedirect('network?conv=1');
765 if (($moduleName == 'status_messages') && ($this->args->getCommand() == 'status_messages/new')) {
766 $this->internalRedirect('bookmarklet');
769 if (($moduleName == 'user') && ($this->args->getCommand() == 'user/edit')) {
770 $this->internalRedirect('settings');
773 if (($moduleName == 'tag_followings') && ($this->args->getCommand() == 'tag_followings/manage')) {
774 $this->internalRedirect('search');
777 // Initialize module that can set the current theme in the init() method, either directly or via App->profile_uid
778 $this->page['page_title'] = $moduleName;
780 // determine the module class and save it to the module instance
781 // @todo there's an implicit dependency due SESSION::start(), so it has to be called here (yet)
782 $module = $module->determineClass($this->args, $router, $this->config);
784 // Let the module run it's internal process (init, get, post, ...)
785 $module->run($this->l10n, $this, $this->logger, $_SERVER, $_POST);
786 } catch (HTTPException $e) {
787 ModuleHTTPException::rawContent($e);
790 $this->page->run($this, $this->baseURL, $this->mode, $module, $this->l10n, $this->config, $pconfig);
794 * @deprecated 2019.12 use BaseUrl::redirect instead
795 * @see BaseURL::redirect()
797 public function internalRedirect($toUrl = '', $ssl = false)
799 $this->baseURL->redirect($toUrl, $ssl);
803 * Automatically redirects to relative or absolute URL
804 * Should only be used if it isn't clear if the URL is either internal or external
806 * @param string $toUrl The target URL
808 * @throws HTTPException\InternalServerErrorException
810 public function redirect($toUrl)
812 if (!empty(parse_url($toUrl, PHP_URL_SCHEME))) {
813 Core\System::externalRedirect($toUrl);
815 $this->baseURL->redirect($toUrl);