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\System;
17 use Friendica\Core\Theme;
18 use Friendica\Database\Database;
19 use Friendica\Model\Profile;
20 use Friendica\Module\Special\HTTPException as ModuleHTTPException;
21 use Friendica\Network\HTTPException;
22 use Friendica\Util\ConfigFileLoader;
23 use Friendica\Util\HTTPSignature;
24 use Friendica\Util\Profiler;
25 use Friendica\Util\Strings;
26 use Psr\Log\LoggerInterface;
32 * @brief Our main application structure for the life of this page.
34 * Primarily deals with the URL that got us here
35 * and tries to make some sense of it, and
36 * stores our page contents and config storage
37 * and anything else that might need to be passed around
38 * before we spit the page out.
43 /** @deprecated 2019.09 - use App\Arguments->getQueryString() */
46 * @var Page The current page environment
58 /** @deprecated 2019.09 - use App\Arguments->getCommand() */
60 /** @deprecated 2019.09 - use App\Arguments->getArgv() or Arguments->get() */
62 /** @deprecated 2019.09 - use App\Arguments->getArgc() */
64 /** @deprecated 2019.09 - Use App\Module->getName() instead */
67 public $interactive = true;
69 /** @deprecated 2019.09 - Use App\Mode->isMobile() instead */
71 /** @deprecated 2019.09 - Use App\Mode->isTable() instead */
73 public $theme_info = [];
75 // Allow themes to control internal parameters
76 // by changing App values in theme.php
78 public $sourcename = '';
79 public $videowidth = 425;
80 public $videoheight = 350;
81 public $force_max_items = 0;
82 public $theme_events_in_profile = true;
86 * @var App\Mode The Mode of the Application
95 /** @var string The name of the current theme */
96 private $currentTheme;
97 /** @var string The name of the current mobile theme */
98 private $currentMobileTheme;
101 * @var Configuration The config
106 * @var LoggerInterface The logger
111 * @var Profiler The profiler of this app
116 * @var Database The Friendica database connection
121 * @var L10n The translator
131 * @var Core\Process The process methods
136 * Returns the current config cache of this node
138 * @return ConfigCache
140 public function getConfigCache()
142 return $this->config->getCache();
146 * The basepath of this app
150 public function getBasePath()
152 // Don't use the basepath of the config table for basepath (it should always be the config-file one)
153 return $this->config->getCache()->get('system', 'basepath');
157 * @deprecated 2019.09 - use Page->registerStylesheet instead
158 * @see Page::registerStylesheet()
160 public function registerStylesheet($path)
162 $this->page->registerStylesheet($path);
166 * @deprecated 2019.09 - use Page->registerFooterScript instead
167 * @see Page::registerFooterScript()
169 public function registerFooterScript($path)
171 $this->page->registerFooterScript($path);
175 * @param Database $database The Friendica Database
176 * @param Configuration $config The Configuration
177 * @param App\Mode $mode The mode of this Friendica app
178 * @param BaseURL $baseURL The full base URL of this Friendica app
179 * @param LoggerInterface $logger The current app logger
180 * @param Profiler $profiler The profiler of this application
181 * @param L10n $l10n The translator instance
182 * @param App\Arguments $args The Friendica Arguments of the call
183 * @param Core\Process $process The process methods
185 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)
187 $this->database = $database;
188 $this->config = $config;
190 $this->baseURL = $baseURL;
191 $this->profiler = $profiler;
192 $this->logger = $logger;
195 $this->process = $process;
197 $this->cmd = $args->getCommand();
198 $this->argv = $args->getArgv();
199 $this->argc = $args->getArgc();
200 $this->query_string = $args->getQueryString();
201 $this->module = $module->getName();
204 $this->is_mobile = $mode->isMobile();
205 $this->is_tablet = $mode->isTablet();
211 * Load the whole app instance
213 public function load()
217 // This has to be quite large to deal with embedded private photos
218 ini_set('pcre.backtrack_limit', 500000);
221 get_include_path() . PATH_SEPARATOR
222 . $this->getBasePath() . DIRECTORY_SEPARATOR . 'include' . PATH_SEPARATOR
223 . $this->getBasePath() . DIRECTORY_SEPARATOR . 'library' . PATH_SEPARATOR
224 . $this->getBasePath());
226 $this->profiler->reset();
228 if ($this->mode->has(App\Mode::DBAVAILABLE)) {
229 $this->profiler->update($this->config);
231 Core\Hook::loadHooks();
232 $loader = new ConfigFileLoader($this->getBasePath());
233 Core\Hook::callAll('load_config', $loader);
236 $this->loadDefaultTimezone();
237 // Register template engines
238 Core\Renderer::registerTemplateEngine('Friendica\Render\FriendicaSmartyEngine');
242 * Loads the default timezone
244 * Include support for legacy $default_timezone
246 * @global string $default_timezone
248 private function loadDefaultTimezone()
250 if ($this->config->get('system', 'default_timezone')) {
251 $this->timezone = $this->config->get('system', 'default_timezone');
253 global $default_timezone;
254 $this->timezone = !empty($default_timezone) ? $default_timezone : 'UTC';
257 if ($this->timezone) {
258 date_default_timezone_set($this->timezone);
263 * Returns the scheme of the current call
267 * @deprecated 2019.06 - use BaseURL->getScheme() instead
269 public function getScheme()
271 return $this->baseURL->getScheme();
275 * Retrieves the Friendica instance base URL
277 * @param bool $ssl Whether to append http or https under BaseURL::SSL_POLICY_SELFSIGN
279 * @return string Friendica server base URL
281 * @deprecated 2019.09 - use BaseUrl->get($ssl) instead
283 public function getBaseURL($ssl = false)
285 return $this->baseURL->get($ssl);
289 * @brief Initializes the baseurl components
291 * Clears the baseurl cache to prevent inconsistencies
295 * @deprecated 2019.06 - use BaseURL->saveByURL($url) instead
297 public function setBaseURL($url)
299 $this->baseURL->saveByURL($url);
303 * Returns the current hostname
307 * @deprecated 2019.06 - use BaseURL->getHostname() instead
309 public function getHostName()
311 return $this->baseURL->getHostname();
315 * Returns the sub-path of the full URL
319 * @deprecated 2019.06 - use BaseURL->getUrlPath() instead
321 public function getURLPath()
323 return $this->baseURL->getUrlPath();
327 * Returns the current UserAgent as a String
329 * @return string the UserAgent as a String
330 * @throws HTTPException\InternalServerErrorException
332 public function getUserAgent()
335 FRIENDICA_PLATFORM . " '" .
336 FRIENDICA_CODENAME . "' " .
337 FRIENDICA_VERSION . '-' .
338 DB_UPDATE_VERSION . '; ' .
343 * Generates the site's default sender email address
346 * @throws HTTPException\InternalServerErrorException
348 public function getSenderEmailAddress()
350 $sender_email = $this->config->get('config', 'sender_email');
351 if (empty($sender_email)) {
352 $hostname = $this->baseURL->getHostname();
353 if (strpos($hostname, ':')) {
354 $hostname = substr($hostname, 0, strpos($hostname, ':'));
357 $sender_email = 'noreply@' . $hostname;
360 return $sender_email;
364 * Returns the current theme name. May be overriden by the mobile theme name.
369 public function getCurrentTheme()
371 if ($this->mode->isInstall()) {
375 // Specific mobile theme override
376 if (($this->mode->isMobile() || $this->mode->isTablet()) && Core\Session::get('show-mobile', true)) {
377 $user_mobile_theme = $this->getCurrentMobileTheme();
379 // --- means same mobile theme as desktop
380 if (!empty($user_mobile_theme) && $user_mobile_theme !== '---') {
381 return $user_mobile_theme;
385 if (!$this->currentTheme) {
386 $this->computeCurrentTheme();
389 return $this->currentTheme;
393 * Returns the current mobile theme name.
398 public function getCurrentMobileTheme()
400 if ($this->mode->isInstall()) {
404 if (is_null($this->currentMobileTheme)) {
405 $this->computeCurrentMobileTheme();
408 return $this->currentMobileTheme;
411 public function setCurrentTheme($theme)
413 $this->currentTheme = $theme;
416 public function setCurrentMobileTheme($theme)
418 $this->currentMobileTheme = $theme;
422 * Computes the current theme name based on the node settings, the page owner settings and the user settings
426 private function computeCurrentTheme()
428 $system_theme = $this->config->get('system', 'theme');
429 if (!$system_theme) {
430 throw new Exception($this->l10n->t('No system theme config value set.'));
434 $this->setCurrentTheme($system_theme);
437 // Find the theme that belongs to the user whose stuff we are looking at
438 if ($this->profile_uid && ($this->profile_uid != local_user())) {
439 // Allow folks to override user themes and always use their own on their own site.
440 // This works only if the user is on the same server
441 $user = $this->database->selectFirst('user', ['theme'], ['uid' => $this->profile_uid]);
442 if ($this->database->isResult($user) && !Core\PConfig::get(local_user(), 'system', 'always_my_theme')) {
443 $page_theme = $user['theme'];
447 $theme_name = $page_theme ?: Core\Session::get('theme', $system_theme);
449 $theme_name = Strings::sanitizeFilePathItem($theme_name);
451 && in_array($theme_name, Theme::getAllowedList())
452 && (file_exists('view/theme/' . $theme_name . '/style.css')
453 || file_exists('view/theme/' . $theme_name . '/style.php'))
455 $this->setCurrentTheme($theme_name);
460 * Computes the current mobile theme name based on the node settings, the page owner settings and the user settings
462 private function computeCurrentMobileTheme()
464 $system_mobile_theme = $this->config->get('system', 'mobile-theme', '');
467 $this->setCurrentMobileTheme($system_mobile_theme);
469 $page_mobile_theme = null;
470 // Find the theme that belongs to the user whose stuff we are looking at
471 if ($this->profile_uid && ($this->profile_uid != local_user())) {
472 // Allow folks to override user themes and always use their own on their own site.
473 // This works only if the user is on the same server
474 if (!Core\PConfig::get(local_user(), 'system', 'always_my_theme')) {
475 $page_mobile_theme = Core\PConfig::get($this->profile_uid, 'system', 'mobile-theme');
479 $mobile_theme_name = $page_mobile_theme ?: Core\Session::get('mobile-theme', $system_mobile_theme);
481 $mobile_theme_name = Strings::sanitizeFilePathItem($mobile_theme_name);
482 if ($mobile_theme_name == '---'
484 in_array($mobile_theme_name, Theme::getAllowedList())
485 && (file_exists('view/theme/' . $mobile_theme_name . '/style.css')
486 || file_exists('view/theme/' . $mobile_theme_name . '/style.php'))
488 $this->setCurrentMobileTheme($mobile_theme_name);
493 * @brief Return full URL to theme which is currently in effect.
495 * Provide a sane default if nothing is chosen or the specified theme does not exist.
500 public function getCurrentThemeStylesheetPath()
502 return Core\Theme::getStylesheetPath($this->getCurrentTheme());
506 * Sets the base url for use in cmdline programs which don't have
509 public function checkURL()
511 $url = $this->config->get('system', 'url');
513 // if the url isn't set or the stored url is radically different
514 // than the currently visited url, store the current value accordingly.
515 // "Radically different" ignores common variations such as http vs https
516 // and www.example.com vs example.com.
517 // We will only change the url to an ip address if there is no existing setting
519 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()))) {
520 $this->config->set('system', 'url', $this->getBaseURL());
525 * Frontend App script
527 * The App object behaves like a container and a dispatcher at the same time, including a representation of the
528 * request and a representation of the response.
530 * This probably should change to limit the size of this monster method.
532 * @param App\Module $module The determined module
533 * @param App\Router $router
534 * @param PConfiguration $pconfig
535 * @param Authentication $auth The Authentication backend of the node
536 * @throws HTTPException\InternalServerErrorException
537 * @throws \ImagickException
539 public function runFrontend(App\Module $module, App\Router $router, PConfiguration $pconfig, Authentication $auth)
541 $moduleName = $module->getName();
544 // Missing DB connection: ERROR
545 if ($this->mode->has(App\Mode::LOCALCONFIGPRESENT) && !$this->mode->has(App\Mode::DBAVAILABLE)) {
546 throw new HTTPException\InternalServerErrorException('Apologies but the website is unavailable at the moment.');
549 // Max Load Average reached: ERROR
550 if ($this->process->isMaxProcessesReached() || $this->process->isMaxLoadReached()) {
551 header('Retry-After: 120');
552 header('Refresh: 120; url=' . $this->baseURL->get() . "/" . $this->args->getQueryString());
554 throw new HTTPException\ServiceUnavailableException('The node is currently overloaded. Please try again later.');
557 if (!$this->mode->isInstall()) {
558 // Force SSL redirection
559 if ($this->baseURL->checkRedirectHttps()) {
560 System::externalRedirect($this->baseURL->get() . '/' . $this->args->getQueryString());
563 Core\Hook::callAll('init_1');
566 // Exclude the backend processes from the session management
567 if ($this->mode->isBackend()) {
568 Core\Worker::executeIfIdle();
571 if ($this->mode->isNormal()) {
572 $requester = HTTPSignature::getSigner('', $_SERVER);
573 if (!empty($requester)) {
574 Profile::addVisitorCookieForHandle($requester);
579 if (!empty($_GET['zrl']) && $this->mode->isNormal()) {
581 // Only continue when the given profile link seems valid
582 // Valid profile links contain a path with "/profile/" and no query parameters
583 if ((parse_url($_GET['zrl'], PHP_URL_QUERY) == "") &&
584 strstr(parse_url($_GET['zrl'], PHP_URL_PATH), "/profile/")) {
585 if (Core\Session::get('visitor_home') != $_GET["zrl"]) {
586 Core\Session::set('my_url', $_GET['zrl']);
587 Core\Session::set('authenticated', 0);
590 Model\Profile::zrlInit($this);
592 // Someone came with an invalid parameter, maybe as a DDoS attempt
593 // We simply stop processing here
594 $this->logger->debug('Invalid ZRL parameter.', ['zrl' => $_GET['zrl']]);
595 throw new HTTPException\ForbiddenException();
600 if (!empty($_GET['owt']) && $this->mode->isNormal()) {
601 $token = $_GET['owt'];
602 Model\Profile::openWebAuthInit($token);
605 $auth->withSession($this);
607 if (empty($_SESSION['authenticated'])) {
608 header('X-Account-Management-Status: none');
611 $_SESSION['sysmsg'] = Core\Session::get('sysmsg', []);
612 $_SESSION['sysmsg_info'] = Core\Session::get('sysmsg_info', []);
613 $_SESSION['last_updated'] = Core\Session::get('last_updated', []);
616 * check_config() is responsible for running update scripts. These automatically
617 * update the DB schema whenever we push a new one out. It also checks to see if
618 * any addons have been added or removed and reacts accordingly.
621 // in install mode, any url loads install module
622 // but we need "view" module for stylesheet
623 if ($this->mode->isInstall() && $moduleName !== 'install') {
624 $this->baseURL->redirect('install');
625 } elseif (!$this->mode->isInstall() && !$this->mode->has(App\Mode::MAINTENANCEDISABLED) && $moduleName !== 'maintenance') {
626 $this->baseURL->redirect('maintenance');
629 Core\Update::check($this->getBasePath(), false, $this->mode);
630 Core\Addon::loadAddons();
631 Core\Hook::loadHooks();
634 // Compatibility with the Android Diaspora client
635 if ($moduleName == 'stream') {
636 $this->baseURL->redirect('network?order=post');
639 if ($moduleName == 'conversations') {
640 $this->baseURL->redirect('message');
643 if ($moduleName == 'commented') {
644 $this->baseURL->redirect('network?order=comment');
647 if ($moduleName == 'liked') {
648 $this->baseURL->redirect('network?order=comment');
651 if ($moduleName == 'activity') {
652 $this->baseURL->redirect('network?conv=1');
655 if (($moduleName == 'status_messages') && ($this->args->getCommand() == 'status_messages/new')) {
656 $this->baseURL->redirect('bookmarklet');
659 if (($moduleName == 'user') && ($this->args->getCommand() == 'user/edit')) {
660 $this->baseURL->redirect('settings');
663 if (($moduleName == 'tag_followings') && ($this->args->getCommand() == 'tag_followings/manage')) {
664 $this->baseURL->redirect('search');
667 // Initialize module that can set the current theme in the init() method, either directly or via App->profile_uid
668 $this->page['page_title'] = $moduleName;
670 // determine the module class and save it to the module instance
671 // @todo there's an implicit dependency due SESSION::start(), so it has to be called here (yet)
672 $module = $module->determineClass($this->args, $router, $this->config);
674 // Let the module run it's internal process (init, get, post, ...)
675 $module->run($this->l10n, $this->baseURL, $this->logger, $_SERVER, $_POST);
676 } catch (HTTPException $e) {
677 ModuleHTTPException::rawContent($e);
680 $this->page->run($this, $this->baseURL, $this->mode, $module, $this->l10n, $this->config, $pconfig);
684 * Automatically redirects to relative or absolute URL
685 * Should only be used if it isn't clear if the URL is either internal or external
687 * @param string $toUrl The target URL
689 * @throws HTTPException\InternalServerErrorException
691 public function redirect($toUrl)
693 if (!empty(parse_url($toUrl, PHP_URL_SCHEME))) {
694 Core\System::externalRedirect($toUrl);
696 $this->baseURL->redirect($toUrl);