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 * @deprecated 2019.09 - use Page->registerStylesheet instead
160 * @see Page::registerStylesheet()
162 public function registerStylesheet($path)
164 $this->page->registerStylesheet($path);
168 * @deprecated 2019.09 - use Page->registerFooterScript instead
169 * @see Page::registerFooterScript()
171 public function registerFooterScript($path)
173 $this->page->registerFooterScript($path);
177 * @param Database $database The Friendica Database
178 * @param Configuration $config The Configuration
179 * @param App\Mode $mode The mode of this Friendica app
180 * @param BaseURL $baseURL The full base URL of this Friendica app
181 * @param LoggerInterface $logger The current app logger
182 * @param Profiler $profiler The profiler of this application
183 * @param L10n $l10n The translator instance
184 * @param App\Arguments $args The Friendica Arguments of the call
185 * @param Core\Process $process The process methods
187 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)
189 $this->database = $database;
190 $this->config = $config;
192 $this->baseURL = $baseURL;
193 $this->profiler = $profiler;
194 $this->logger = $logger;
197 $this->process = $process;
199 $this->cmd = $args->getCommand();
200 $this->argv = $args->getArgv();
201 $this->argc = $args->getArgc();
202 $this->query_string = $args->getQueryString();
203 $this->module = $module->getName();
206 $this->is_mobile = $mode->isMobile();
207 $this->is_tablet = $mode->isTablet();
213 * Load the whole app instance
215 public function load()
219 // This has to be quite large to deal with embedded private photos
220 ini_set('pcre.backtrack_limit', 500000);
223 get_include_path() . PATH_SEPARATOR
224 . $this->getBasePath() . DIRECTORY_SEPARATOR . 'include' . PATH_SEPARATOR
225 . $this->getBasePath() . DIRECTORY_SEPARATOR . 'library' . PATH_SEPARATOR
226 . $this->getBasePath());
228 $this->profiler->reset();
230 if ($this->mode->has(App\Mode::DBAVAILABLE)) {
231 $this->profiler->update($this->config);
233 Core\Hook::loadHooks();
234 $loader = new ConfigFileLoader($this->getBasePath());
235 Core\Hook::callAll('load_config', $loader);
238 $this->loadDefaultTimezone();
239 // Register template engines
240 Core\Renderer::registerTemplateEngine('Friendica\Render\FriendicaSmartyEngine');
244 * Loads the default timezone
246 * Include support for legacy $default_timezone
248 * @global string $default_timezone
250 private function loadDefaultTimezone()
252 if ($this->config->get('system', 'default_timezone')) {
253 $this->timezone = $this->config->get('system', 'default_timezone');
255 global $default_timezone;
256 $this->timezone = !empty($default_timezone) ? $default_timezone : 'UTC';
259 if ($this->timezone) {
260 date_default_timezone_set($this->timezone);
265 * Returns the scheme of the current call
269 * @deprecated 2019.06 - use BaseURL->getScheme() instead
271 public function getScheme()
273 return $this->baseURL->getScheme();
277 * Retrieves the Friendica instance base URL
279 * @param bool $ssl Whether to append http or https under BaseURL::SSL_POLICY_SELFSIGN
281 * @return string Friendica server base URL
283 * @deprecated 2019.09 - use BaseUrl->get($ssl) instead
285 public function getBaseURL($ssl = false)
287 return $this->baseURL->get($ssl);
291 * @brief Initializes the baseurl components
293 * Clears the baseurl cache to prevent inconsistencies
297 * @deprecated 2019.06 - use BaseURL->saveByURL($url) instead
299 public function setBaseURL($url)
301 $this->baseURL->saveByURL($url);
305 * Returns the current hostname
309 * @deprecated 2019.06 - use BaseURL->getHostname() instead
311 public function getHostName()
313 return $this->baseURL->getHostname();
317 * Returns the sub-path of the full URL
321 * @deprecated 2019.06 - use BaseURL->getUrlPath() instead
323 public function getURLPath()
325 return $this->baseURL->getUrlPath();
329 * @brief Removes the base url from an url. This avoids some mixed content problems.
331 * @param string $origURL
333 * @return string The cleaned url
335 * @deprecated 2019.09 - Use BaseURL->remove() instead
336 * @see BaseURL::remove()
338 public function removeBaseURL(string $origURL)
340 return $this->baseURL->remove($origURL);
344 * Returns the current UserAgent as a String
346 * @return string the UserAgent as a String
347 * @throws HTTPException\InternalServerErrorException
349 public function getUserAgent()
352 FRIENDICA_PLATFORM . " '" .
353 FRIENDICA_CODENAME . "' " .
354 FRIENDICA_VERSION . '-' .
355 DB_UPDATE_VERSION . '; ' .
360 * @deprecated 2019.09 - use Core\Process->isMaxProcessesReached() instead
362 public function isMaxProcessesReached()
364 return $this->process->isMaxProcessesReached();
368 * @deprecated 2019.09 - use Core\Process->isMinMemoryReached() instead
370 public function isMinMemoryReached()
372 return $this->process->isMinMemoryReached();
376 * @deprecated 2019.09 - use Core\Process->isMaxLoadReached() instead
378 public function isMaxLoadReached()
380 return $this->process->isMaxLoadReached();
384 * Generates the site's default sender email address
387 * @throws HTTPException\InternalServerErrorException
389 public function getSenderEmailAddress()
391 $sender_email = $this->config->get('config', 'sender_email');
392 if (empty($sender_email)) {
393 $hostname = $this->baseURL->getHostname();
394 if (strpos($hostname, ':')) {
395 $hostname = substr($hostname, 0, strpos($hostname, ':'));
398 $sender_email = 'noreply@' . $hostname;
401 return $sender_email;
405 * Returns the current theme name. May be overriden by the mobile theme name.
410 public function getCurrentTheme()
412 if ($this->mode->isInstall()) {
416 // Specific mobile theme override
417 if (($this->mode->isMobile() || $this->mode->isTablet()) && Core\Session::get('show-mobile', true)) {
418 $user_mobile_theme = $this->getCurrentMobileTheme();
420 // --- means same mobile theme as desktop
421 if (!empty($user_mobile_theme) && $user_mobile_theme !== '---') {
422 return $user_mobile_theme;
426 if (!$this->currentTheme) {
427 $this->computeCurrentTheme();
430 return $this->currentTheme;
434 * Returns the current mobile theme name.
439 public function getCurrentMobileTheme()
441 if ($this->mode->isInstall()) {
445 if (is_null($this->currentMobileTheme)) {
446 $this->computeCurrentMobileTheme();
449 return $this->currentMobileTheme;
452 public function setCurrentTheme($theme)
454 $this->currentTheme = $theme;
457 public function setCurrentMobileTheme($theme)
459 $this->currentMobileTheme = $theme;
463 * Computes the current theme name based on the node settings, the page owner settings and the user settings
467 private function computeCurrentTheme()
469 $system_theme = $this->config->get('system', 'theme');
470 if (!$system_theme) {
471 throw new Exception($this->l10n->t('No system theme config value set.'));
475 $this->setCurrentTheme($system_theme);
478 // Find the theme that belongs to the user whose stuff we are looking at
479 if ($this->profile_uid && ($this->profile_uid != local_user())) {
480 // Allow folks to override user themes and always use their own on their own site.
481 // This works only if the user is on the same server
482 $user = $this->database->selectFirst('user', ['theme'], ['uid' => $this->profile_uid]);
483 if ($this->database->isResult($user) && !Core\PConfig::get(local_user(), 'system', 'always_my_theme')) {
484 $page_theme = $user['theme'];
488 $theme_name = $page_theme ?: Core\Session::get('theme', $system_theme);
490 $theme_name = Strings::sanitizeFilePathItem($theme_name);
492 && in_array($theme_name, Theme::getAllowedList())
493 && (file_exists('view/theme/' . $theme_name . '/style.css')
494 || file_exists('view/theme/' . $theme_name . '/style.php'))
496 $this->setCurrentTheme($theme_name);
501 * Computes the current mobile theme name based on the node settings, the page owner settings and the user settings
503 private function computeCurrentMobileTheme()
505 $system_mobile_theme = $this->config->get('system', 'mobile-theme', '');
508 $this->setCurrentMobileTheme($system_mobile_theme);
510 $page_mobile_theme = null;
511 // Find the theme that belongs to the user whose stuff we are looking at
512 if ($this->profile_uid && ($this->profile_uid != local_user())) {
513 // Allow folks to override user themes and always use their own on their own site.
514 // This works only if the user is on the same server
515 if (!Core\PConfig::get(local_user(), 'system', 'always_my_theme')) {
516 $page_mobile_theme = Core\PConfig::get($this->profile_uid, 'system', 'mobile-theme');
520 $mobile_theme_name = $page_mobile_theme ?: Core\Session::get('mobile-theme', $system_mobile_theme);
522 $mobile_theme_name = Strings::sanitizeFilePathItem($mobile_theme_name);
523 if ($mobile_theme_name == '---'
525 in_array($mobile_theme_name, Theme::getAllowedList())
526 && (file_exists('view/theme/' . $mobile_theme_name . '/style.css')
527 || file_exists('view/theme/' . $mobile_theme_name . '/style.php'))
529 $this->setCurrentMobileTheme($mobile_theme_name);
534 * @brief Return full URL to theme which is currently in effect.
536 * Provide a sane default if nothing is chosen or the specified theme does not exist.
541 public function getCurrentThemeStylesheetPath()
543 return Core\Theme::getStylesheetPath($this->getCurrentTheme());
547 * @deprecated use Arguments->get() instead
551 public function getArgumentValue($position, $default = '')
553 return $this->args->get($position, $default);
557 * Sets the base url for use in cmdline programs which don't have
560 public function checkURL()
562 $url = $this->config->get('system', 'url');
564 // if the url isn't set or the stored url is radically different
565 // than the currently visited url, store the current value accordingly.
566 // "Radically different" ignores common variations such as http vs https
567 // and www.example.com vs example.com.
568 // We will only change the url to an ip address if there is no existing setting
570 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()))) {
571 $this->config->set('system', 'url', $this->getBaseURL());
576 * Frontend App script
578 * The App object behaves like a container and a dispatcher at the same time, including a representation of the
579 * request and a representation of the response.
581 * This probably should change to limit the size of this monster method.
583 * @param App\Module $module The determined module
584 * @param App\Router $router
585 * @param PConfiguration $pconfig
586 * @param Authentication $auth The Authentication backend of the node
587 * @throws HTTPException\InternalServerErrorException
588 * @throws \ImagickException
590 public function runFrontend(App\Module $module, App\Router $router, PConfiguration $pconfig, Authentication $auth)
592 $moduleName = $module->getName();
595 // Missing DB connection: ERROR
596 if ($this->mode->has(App\Mode::LOCALCONFIGPRESENT) && !$this->mode->has(App\Mode::DBAVAILABLE)) {
597 throw new HTTPException\InternalServerErrorException('Apologies but the website is unavailable at the moment.');
600 // Max Load Average reached: ERROR
601 if ($this->process->isMaxProcessesReached() || $this->process->isMaxLoadReached()) {
602 header('Retry-After: 120');
603 header('Refresh: 120; url=' . $this->baseURL->get() . "/" . $this->args->getQueryString());
605 throw new HTTPException\ServiceUnavailableException('The node is currently overloaded. Please try again later.');
608 if (!$this->mode->isInstall()) {
609 // Force SSL redirection
610 if ($this->baseURL->checkRedirectHttps()) {
611 System::externalRedirect($this->baseURL->get() . '/' . $this->args->getQueryString());
614 Core\Hook::callAll('init_1');
617 // Exclude the backend processes from the session management
618 if ($this->mode->isBackend()) {
619 Core\Worker::executeIfIdle();
622 if ($this->mode->isNormal()) {
623 $requester = HTTPSignature::getSigner('', $_SERVER);
624 if (!empty($requester)) {
625 Profile::addVisitorCookieForHandle($requester);
630 if (!empty($_GET['zrl']) && $this->mode->isNormal()) {
632 // Only continue when the given profile link seems valid
633 // Valid profile links contain a path with "/profile/" and no query parameters
634 if ((parse_url($_GET['zrl'], PHP_URL_QUERY) == "") &&
635 strstr(parse_url($_GET['zrl'], PHP_URL_PATH), "/profile/")) {
636 if (Core\Session::get('visitor_home') != $_GET["zrl"]) {
637 Core\Session::set('my_url', $_GET['zrl']);
638 Core\Session::set('authenticated', 0);
641 Model\Profile::zrlInit($this);
643 // Someone came with an invalid parameter, maybe as a DDoS attempt
644 // We simply stop processing here
645 $this->logger->debug('Invalid ZRL parameter.', ['zrl' => $_GET['zrl']]);
646 throw new HTTPException\ForbiddenException();
651 if (!empty($_GET['owt']) && $this->mode->isNormal()) {
652 $token = $_GET['owt'];
653 Model\Profile::openWebAuthInit($token);
656 $auth->withSession($this);
658 if (empty($_SESSION['authenticated'])) {
659 header('X-Account-Management-Status: none');
662 $_SESSION['sysmsg'] = Core\Session::get('sysmsg', []);
663 $_SESSION['sysmsg_info'] = Core\Session::get('sysmsg_info', []);
664 $_SESSION['last_updated'] = Core\Session::get('last_updated', []);
667 * check_config() is responsible for running update scripts. These automatically
668 * update the DB schema whenever we push a new one out. It also checks to see if
669 * any addons have been added or removed and reacts accordingly.
672 // in install mode, any url loads install module
673 // but we need "view" module for stylesheet
674 if ($this->mode->isInstall() && $moduleName !== 'install') {
675 $this->baseURL->redirect('install');
676 } elseif (!$this->mode->isInstall() && !$this->mode->has(App\Mode::MAINTENANCEDISABLED) && $moduleName !== 'maintenance') {
677 $this->baseURL->redirect('maintenance');
680 Core\Update::check($this->getBasePath(), false, $this->mode);
681 Core\Addon::loadAddons();
682 Core\Hook::loadHooks();
685 // Compatibility with the Android Diaspora client
686 if ($moduleName == 'stream') {
687 $this->baseURL->redirect('network?order=post');
690 if ($moduleName == 'conversations') {
691 $this->baseURL->redirect('message');
694 if ($moduleName == 'commented') {
695 $this->baseURL->redirect('network?order=comment');
698 if ($moduleName == 'liked') {
699 $this->baseURL->redirect('network?order=comment');
702 if ($moduleName == 'activity') {
703 $this->baseURL->redirect('network?conv=1');
706 if (($moduleName == 'status_messages') && ($this->args->getCommand() == 'status_messages/new')) {
707 $this->baseURL->redirect('bookmarklet');
710 if (($moduleName == 'user') && ($this->args->getCommand() == 'user/edit')) {
711 $this->baseURL->redirect('settings');
714 if (($moduleName == 'tag_followings') && ($this->args->getCommand() == 'tag_followings/manage')) {
715 $this->baseURL->redirect('search');
718 // Initialize module that can set the current theme in the init() method, either directly or via App->profile_uid
719 $this->page['page_title'] = $moduleName;
721 // determine the module class and save it to the module instance
722 // @todo there's an implicit dependency due SESSION::start(), so it has to be called here (yet)
723 $module = $module->determineClass($this->args, $router, $this->config);
725 // Let the module run it's internal process (init, get, post, ...)
726 $module->run($this->l10n, $this->baseURL, $this->logger, $_SERVER, $_POST);
727 } catch (HTTPException $e) {
728 ModuleHTTPException::rawContent($e);
731 $this->page->run($this, $this->baseURL, $this->mode, $module, $this->l10n, $this->config, $pconfig);
735 * Automatically redirects to relative or absolute URL
736 * Should only be used if it isn't clear if the URL is either internal or external
738 * @param string $toUrl The target URL
740 * @throws HTTPException\InternalServerErrorException
742 public function redirect($toUrl)
744 if (!empty(parse_url($toUrl, PHP_URL_SCHEME))) {
745 Core\System::externalRedirect($toUrl);
747 $this->baseURL->redirect($toUrl);