8 use Friendica\App\Arguments;
9 use Friendica\App\BaseURL;
10 use Friendica\App\Page;
11 use Friendica\Core\Config\Cache\ConfigCache;
12 use Friendica\Core\Config\Configuration;
13 use Friendica\Core\Config\PConfiguration;
14 use Friendica\Core\L10n\L10n;
15 use Friendica\Core\System;
16 use Friendica\Core\Theme;
17 use Friendica\Database\Database;
18 use Friendica\Model\Profile;
19 use Friendica\Module\Login;
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
96 * @var string The name of the current theme
98 private $currentTheme;
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 * Returns the current config of this node
148 * @return Configuration
150 public function getConfig()
152 return $this->config;
156 * The basepath of this app
160 public function getBasePath()
162 // Don't use the basepath of the config table for basepath (it should always be the config-file one)
163 return $this->config->getCache()->get('system', 'basepath');
167 * The Logger of this app
169 * @return LoggerInterface
171 public function getLogger()
173 return $this->logger;
177 * The profiler of this app
181 public function getProfiler()
183 return $this->profiler;
187 * Returns the Mode of the Application
189 * @return App\Mode The Application Mode
191 public function getMode()
197 * Returns the Database of the Application
201 public function getDBA()
203 return $this->database;
207 * @deprecated 2019.09 - use Page->registerStylesheet instead
208 * @see Page::registerStylesheet()
210 public function registerStylesheet($path)
212 $this->page->registerStylesheet($path);
216 * @deprecated 2019.09 - use Page->registerFooterScript instead
217 * @see Page::registerFooterScript()
219 public function registerFooterScript($path)
221 $this->page->registerFooterScript($path);
225 * @param Database $database The Friendica Database
226 * @param Configuration $config The Configuration
227 * @param App\Mode $mode The mode of this Friendica app
228 * @param BaseURL $baseURL The full base URL of this Friendica app
229 * @param LoggerInterface $logger The current app logger
230 * @param Profiler $profiler The profiler of this application
231 * @param L10n $l10n The translator instance
232 * @param App\Arguments $args The Friendica Arguments of the call
233 * @param Core\Process $process The process methods
235 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)
237 $this->database = $database;
238 $this->config = $config;
240 $this->baseURL = $baseURL;
241 $this->profiler = $profiler;
242 $this->logger = $logger;
245 $this->process = $process;
247 $this->cmd = $args->getCommand();
248 $this->argv = $args->getArgv();
249 $this->argc = $args->getArgc();
250 $this->query_string = $args->getQueryString();
251 $this->module = $module->getName();
254 $this->is_mobile = $mode->isMobile();
255 $this->is_tablet = $mode->isTablet();
261 * Load the whole app instance
263 public function load()
267 // This has to be quite large to deal with embedded private photos
268 ini_set('pcre.backtrack_limit', 500000);
271 get_include_path() . PATH_SEPARATOR
272 . $this->getBasePath() . DIRECTORY_SEPARATOR . 'include' . PATH_SEPARATOR
273 . $this->getBasePath() . DIRECTORY_SEPARATOR . 'library' . PATH_SEPARATOR
274 . $this->getBasePath());
276 $this->profiler->reset();
278 if ($this->mode->has(App\Mode::DBAVAILABLE)) {
279 $this->profiler->update($this->config);
281 Core\Hook::loadHooks();
282 $loader = new ConfigFileLoader($this->getBasePath());
283 Core\Hook::callAll('load_config', $loader);
286 $this->loadDefaultTimezone();
287 // Register template engines
288 Core\Renderer::registerTemplateEngine('Friendica\Render\FriendicaSmartyEngine');
292 * Loads the default timezone
294 * Include support for legacy $default_timezone
296 * @global string $default_timezone
298 private function loadDefaultTimezone()
300 if ($this->config->get('system', 'default_timezone')) {
301 $this->timezone = $this->config->get('system', 'default_timezone');
303 global $default_timezone;
304 $this->timezone = !empty($default_timezone) ? $default_timezone : 'UTC';
307 if ($this->timezone) {
308 date_default_timezone_set($this->timezone);
313 * Returns the scheme of the current call
317 * @deprecated 2019.06 - use BaseURL->getScheme() instead
319 public function getScheme()
321 return $this->baseURL->getScheme();
325 * Retrieves the Friendica instance base URL
327 * @param bool $ssl Whether to append http or https under BaseURL::SSL_POLICY_SELFSIGN
329 * @return string Friendica server base URL
331 * @deprecated 2019.09 - use BaseUrl->get($ssl) instead
333 public function getBaseURL($ssl = false)
335 return $this->baseURL->get($ssl);
339 * @brief Initializes the baseurl components
341 * Clears the baseurl cache to prevent inconsistencies
345 * @deprecated 2019.06 - use BaseURL->saveByURL($url) instead
347 public function setBaseURL($url)
349 $this->baseURL->saveByURL($url);
353 * Returns the current hostname
357 * @deprecated 2019.06 - use BaseURL->getHostname() instead
359 public function getHostName()
361 return $this->baseURL->getHostname();
365 * Returns the sub-path of the full URL
369 * @deprecated 2019.06 - use BaseURL->getUrlPath() instead
371 public function getURLPath()
373 return $this->baseURL->getUrlPath();
377 * @brief Removes the base url from an url. This avoids some mixed content problems.
379 * @param string $origURL
381 * @return string The cleaned url
383 * @deprecated 2019.09 - Use BaseURL->remove() instead
384 * @see BaseURL::remove()
386 public function removeBaseURL($origURL)
388 return $this->baseURL->remove($origURL);
392 * Returns the current UserAgent as a String
394 * @return string the UserAgent as a String
395 * @throws HTTPException\InternalServerErrorException
397 public function getUserAgent()
400 FRIENDICA_PLATFORM . " '" .
401 FRIENDICA_CODENAME . "' " .
402 FRIENDICA_VERSION . '-' .
403 DB_UPDATE_VERSION . '; ' .
408 * @deprecated 2019.09 - use Core\Process->isMaxProcessesReached() instead
410 public function isMaxProcessesReached()
412 return $this->process->isMaxProcessesReached();
416 * @deprecated 2019.09 - use Core\Process->isMinMemoryReached() instead
418 public function isMinMemoryReached()
420 return $this->process->isMinMemoryReached();
424 * @deprecated 2019.09 - use Core\Process->isMaxLoadReached() instead
426 public function isMaxLoadReached()
428 return $this->process->isMaxLoadReached();
432 * Generates the site's default sender email address
435 * @throws HTTPException\InternalServerErrorException
437 public function getSenderEmailAddress()
439 $sender_email = $this->config->get('config', 'sender_email');
440 if (empty($sender_email)) {
441 $hostname = $this->baseURL->getHostname();
442 if (strpos($hostname, ':')) {
443 $hostname = substr($hostname, 0, strpos($hostname, ':'));
446 $sender_email = 'noreply@' . $hostname;
449 return $sender_email;
453 * Returns the current theme name.
455 * @return string the name of the current theme
456 * @throws HTTPException\InternalServerErrorException
458 public function getCurrentTheme()
460 if ($this->mode->isInstall()) {
464 if (!$this->currentTheme) {
465 $this->computeCurrentTheme();
468 return $this->currentTheme;
471 public function setCurrentTheme($theme)
473 $this->currentTheme = $theme;
477 * Computes the current theme name based on the node settings, the user settings and the device type
481 private function computeCurrentTheme()
483 $system_theme = $this->config->get('system', 'theme');
484 if (!$system_theme) {
485 throw new Exception($this->l10n->t('No system theme config value set.'));
489 $this->currentTheme = $system_theme;
492 // Find the theme that belongs to the user whose stuff we are looking at
493 if ($this->profile_uid && ($this->profile_uid != local_user())) {
494 // Allow folks to override user themes and always use their own on their own site.
495 // This works only if the user is on the same server
496 $user = $this->database->selectFirst('user', ['theme'], ['uid' => $this->profile_uid]);
497 if ($this->database->isResult($user) && !Core\PConfig::get(local_user(), 'system', 'always_my_theme')) {
498 $page_theme = $user['theme'];
502 $user_theme = Core\Session::get('theme', $system_theme);
504 // Specific mobile theme override
505 if (($this->is_mobile || $this->is_tablet) && Core\Session::get('show-mobile', true)) {
506 $system_mobile_theme = $this->config->get('system', 'mobile-theme');
507 $user_mobile_theme = Core\Session::get('mobile-theme', $system_mobile_theme);
509 // --- means same mobile theme as desktop
510 if (!empty($user_mobile_theme) && $user_mobile_theme !== '---') {
511 $user_theme = $user_mobile_theme;
516 $theme_name = $page_theme;
518 $theme_name = $user_theme;
521 $theme_name = Strings::sanitizeFilePathItem($theme_name);
523 && in_array($theme_name, Theme::getAllowedList())
524 && (file_exists('view/theme/' . $theme_name . '/style.css')
525 || file_exists('view/theme/' . $theme_name . '/style.php'))
527 $this->currentTheme = $theme_name;
532 * @brief Return full URL to theme which is currently in effect.
534 * Provide a sane default if nothing is chosen or the specified theme does not exist.
537 * @throws HTTPException\InternalServerErrorException
539 public function getCurrentThemeStylesheetPath()
541 return Core\Theme::getStylesheetPath($this->getCurrentTheme());
545 * @deprecated 2019.09 - use App\Mode->isAjax() instead
546 * @see App\Mode::isAjax()
548 public function isAjax()
550 return $this->mode->isAjax();
554 * @deprecated use Arguments->get() instead
558 public function getArgumentValue($position, $default = '')
560 return $this->args->get($position, $default);
564 * Sets the base url for use in cmdline programs which don't have
567 public function checkURL()
569 $url = $this->config->get('system', 'url');
571 // if the url isn't set or the stored url is radically different
572 // than the currently visited url, store the current value accordingly.
573 // "Radically different" ignores common variations such as http vs https
574 // and www.example.com vs example.com.
575 // We will only change the url to an ip address if there is no existing setting
577 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()))) {
578 $this->config->set('system', 'url', $this->getBaseURL());
583 * Frontend App script
585 * The App object behaves like a container and a dispatcher at the same time, including a representation of the
586 * request and a representation of the response.
588 * This probably should change to limit the size of this monster method.
590 * @param App\Module $module The determined module
592 public function runFrontend(App\Module $module, App\Router $router, PConfiguration $pconfig)
594 $moduleName = $module->getName();
597 // Missing DB connection: ERROR
598 if ($this->mode->has(App\Mode::LOCALCONFIGPRESENT) && !$this->mode->has(App\Mode::DBAVAILABLE)) {
599 throw new HTTPException\InternalServerErrorException('Apologies but the website is unavailable at the moment.');
602 // Max Load Average reached: ERROR
603 if ($this->process->isMaxProcessesReached() || $this->process->isMaxLoadReached()) {
604 header('Retry-After: 120');
605 header('Refresh: 120; url=' . $this->baseURL->get() . "/" . $this->args->getQueryString());
607 throw new HTTPException\ServiceUnavailableException('The node is currently overloaded. Please try again later.');
610 if (!$this->mode->isInstall()) {
611 // Force SSL redirection
612 if ($this->baseURL->checkRedirectHttps()) {
613 System::externalRedirect($this->baseURL->get() . '/' . $this->args->getQueryString());
616 Core\Session::init();
617 Core\Hook::callAll('init_1');
620 // Exclude the backend processes from the session management
621 if (!$this->mode->isBackend()) {
622 $stamp1 = microtime(true);
624 $this->profiler->saveTimestamp($stamp1, 'parser', Core\System::callstack());
625 $this->l10n->setSessionVariable();
626 $this->l10n->setLangFromSession();
629 Core\Worker::executeIfIdle();
632 if ($this->mode->isNormal()) {
633 $requester = HTTPSignature::getSigner('', $_SERVER);
634 if (!empty($requester)) {
635 Profile::addVisitorCookieForHandle($requester);
640 if (!empty($_GET['zrl']) && $this->mode->isNormal()) {
642 // Only continue when the given profile link seems valid
643 // Valid profile links contain a path with "/profile/" and no query parameters
644 if ((parse_url($_GET['zrl'], PHP_URL_QUERY) == "") &&
645 strstr(parse_url($_GET['zrl'], PHP_URL_PATH), "/profile/")) {
646 if (Core\Session::get('visitor_home') != $_GET["zrl"]) {
647 Core\Session::set('my_url', $_GET['zrl']);
648 Core\Session::set('authenticated', 0);
651 Model\Profile::zrlInit($this);
653 // Someone came with an invalid parameter, maybe as a DDoS attempt
654 // We simply stop processing here
655 $this->logger->debug('Invalid ZRL parameter.', ['zrl' => $_GET['zrl']]);
656 throw new HTTPException\ForbiddenException();
661 if (!empty($_GET['owt']) && $this->mode->isNormal()) {
662 $token = $_GET['owt'];
663 Model\Profile::openWebAuthInit($token);
666 Login::sessionAuth();
668 if (empty($_SESSION['authenticated'])) {
669 header('X-Account-Management-Status: none');
672 $_SESSION['sysmsg'] = Core\Session::get('sysmsg', []);
673 $_SESSION['sysmsg_info'] = Core\Session::get('sysmsg_info', []);
674 $_SESSION['last_updated'] = Core\Session::get('last_updated', []);
677 * check_config() is responsible for running update scripts. These automatically
678 * update the DB schema whenever we push a new one out. It also checks to see if
679 * any addons have been added or removed and reacts accordingly.
682 // in install mode, any url loads install module
683 // but we need "view" module for stylesheet
684 if ($this->mode->isInstall() && $moduleName !== 'install') {
685 $this->internalRedirect('install');
686 } elseif (!$this->mode->isInstall() && !$this->mode->has(App\Mode::MAINTENANCEDISABLED) && $moduleName !== 'maintenance') {
687 $this->internalRedirect('maintenance');
690 Core\Update::check($this->getBasePath(), false, $this->mode);
691 Core\Addon::loadAddons();
692 Core\Hook::loadHooks();
695 // Compatibility with the Android Diaspora client
696 if ($moduleName == 'stream') {
697 $this->internalRedirect('network?order=post');
700 if ($moduleName == 'conversations') {
701 $this->internalRedirect('message');
704 if ($moduleName == 'commented') {
705 $this->internalRedirect('network?order=comment');
708 if ($moduleName == 'liked') {
709 $this->internalRedirect('network?order=comment');
712 if ($moduleName == 'activity') {
713 $this->internalRedirect('network?conv=1');
716 if (($moduleName == 'status_messages') && ($this->args->getCommand() == 'status_messages/new')) {
717 $this->internalRedirect('bookmarklet');
720 if (($moduleName == 'user') && ($this->args->getCommand() == 'user/edit')) {
721 $this->internalRedirect('settings');
724 if (($moduleName == 'tag_followings') && ($this->args->getCommand() == 'tag_followings/manage')) {
725 $this->internalRedirect('search');
728 // Initialize module that can set the current theme in the init() method, either directly or via App->profile_uid
729 $this->page['page_title'] = $moduleName;
731 // determine the module class and save it to the module instance
732 // @todo there's an implicit dependency due SESSION::start(), so it has to be called here (yet)
733 $module = $module->determineClass($this->args, $router, $this->config);
735 // Let the module run it's internal process (init, get, post, ...)
736 $module->run($this->l10n, $this, $this->logger, $this->getCurrentTheme(), $_SERVER, $_POST);
738 } catch (HTTPException $e) {
739 ModuleHTTPException::rawContent($e);
742 $this->page->run($this, $this->baseURL, $this->mode, $module, $this->l10n, $this->config, $pconfig);
746 * Redirects to another module relative to the current Friendica base.
747 * If you want to redirect to a external URL, use System::externalRedirectTo()
749 * @param string $toUrl The destination URL (Default is empty, which is the default page of the Friendica node)
750 * @param bool $ssl if true, base URL will try to get called with https:// (works just for relative paths)
752 * @throws HTTPException\InternalServerErrorException In Case the given URL is not relative to the Friendica node
754 public function internalRedirect($toUrl = '', $ssl = false)
756 if (!empty(parse_url($toUrl, PHP_URL_SCHEME))) {
757 throw new HTTPException\InternalServerErrorException("'$toUrl is not a relative path, please use System::externalRedirectTo");
760 $redirectTo = $this->baseURL->get($ssl) . '/' . ltrim($toUrl, '/');
761 Core\System::externalRedirect($redirectTo);
765 * Automatically redirects to relative or absolute URL
766 * Should only be used if it isn't clear if the URL is either internal or external
768 * @param string $toUrl The target URL
770 * @throws HTTPException\InternalServerErrorException
772 public function redirect($toUrl)
774 if (!empty(parse_url($toUrl, PHP_URL_SCHEME))) {
775 Core\System::externalRedirect($toUrl);
777 $this->internalRedirect($toUrl);