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.
44 * @var Page The current page environment
56 /** @deprecated 2019.09 - use App\Arguments->getArgv() or Arguments->get() */
58 /** @deprecated 2019.09 - use App\Arguments->getArgc() */
60 /** @deprecated 2019.09 - Use App\Module->getName() instead */
63 public $interactive = true;
65 public $theme_info = [];
67 // Allow themes to control internal parameters
68 // by changing App values in theme.php
70 public $sourcename = '';
71 public $videowidth = 425;
72 public $videoheight = 350;
73 public $force_max_items = 0;
74 public $theme_events_in_profile = true;
78 * @var App\Mode The Mode of the Application
87 /** @var string The name of the current theme */
88 private $currentTheme;
89 /** @var string The name of the current mobile theme */
90 private $currentMobileTheme;
93 * @var Configuration The config
98 * @var LoggerInterface The logger
103 * @var Profiler The profiler of this app
108 * @var Database The Friendica database connection
113 * @var L10n The translator
123 * @var Core\Process The process methods
128 * Returns the current config cache of this node
130 * @return ConfigCache
132 public function getConfigCache()
134 return $this->config->getCache();
138 * The basepath of this app
142 public function getBasePath()
144 // Don't use the basepath of the config table for basepath (it should always be the config-file one)
145 return $this->config->getCache()->get('system', 'basepath');
149 * @param Database $database The Friendica Database
150 * @param Configuration $config The Configuration
151 * @param App\Mode $mode The mode of this Friendica app
152 * @param BaseURL $baseURL The full base URL of this Friendica app
153 * @param LoggerInterface $logger The current app logger
154 * @param Profiler $profiler The profiler of this application
155 * @param L10n $l10n The translator instance
156 * @param App\Arguments $args The Friendica Arguments of the call
157 * @param Core\Process $process The process methods
159 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)
161 $this->database = $database;
162 $this->config = $config;
164 $this->baseURL = $baseURL;
165 $this->profiler = $profiler;
166 $this->logger = $logger;
169 $this->process = $process;
171 $this->argv = $args->getArgv();
172 $this->argc = $args->getArgc();
173 $this->module = $module->getName();
180 * Load the whole app instance
182 public function load()
186 // This has to be quite large to deal with embedded private photos
187 ini_set('pcre.backtrack_limit', 500000);
190 get_include_path() . PATH_SEPARATOR
191 . $this->getBasePath() . DIRECTORY_SEPARATOR . 'include' . PATH_SEPARATOR
192 . $this->getBasePath() . DIRECTORY_SEPARATOR . 'library' . PATH_SEPARATOR
193 . $this->getBasePath());
195 $this->profiler->reset();
197 if ($this->mode->has(App\Mode::DBAVAILABLE)) {
198 $this->profiler->update($this->config);
200 Core\Hook::loadHooks();
201 $loader = new ConfigFileLoader($this->getBasePath());
202 Core\Hook::callAll('load_config', $loader);
205 $this->loadDefaultTimezone();
206 // Register template engines
207 Core\Renderer::registerTemplateEngine('Friendica\Render\FriendicaSmartyEngine');
211 * Loads the default timezone
213 * Include support for legacy $default_timezone
215 * @global string $default_timezone
217 private function loadDefaultTimezone()
219 if ($this->config->get('system', 'default_timezone')) {
220 $this->timezone = $this->config->get('system', 'default_timezone');
222 global $default_timezone;
223 $this->timezone = !empty($default_timezone) ? $default_timezone : 'UTC';
226 if ($this->timezone) {
227 date_default_timezone_set($this->timezone);
232 * Returns the current UserAgent as a String
234 * @return string the UserAgent as a String
235 * @throws HTTPException\InternalServerErrorException
237 public function getUserAgent()
240 FRIENDICA_PLATFORM . " '" .
241 FRIENDICA_CODENAME . "' " .
242 FRIENDICA_VERSION . '-' .
243 DB_UPDATE_VERSION . '; ' .
244 $this->baseURL->get();
248 * Generates the site's default sender email address
251 * @throws HTTPException\InternalServerErrorException
253 public function getSenderEmailAddress()
255 $sender_email = $this->config->get('config', 'sender_email');
256 if (empty($sender_email)) {
257 $hostname = $this->baseURL->getHostname();
258 if (strpos($hostname, ':')) {
259 $hostname = substr($hostname, 0, strpos($hostname, ':'));
262 $sender_email = 'noreply@' . $hostname;
265 return $sender_email;
269 * Returns the current theme name. May be overriden by the mobile theme name.
274 public function getCurrentTheme()
276 if ($this->mode->isInstall()) {
280 // Specific mobile theme override
281 if (($this->mode->isMobile() || $this->mode->isTablet()) && Core\Session::get('show-mobile', true)) {
282 $user_mobile_theme = $this->getCurrentMobileTheme();
284 // --- means same mobile theme as desktop
285 if (!empty($user_mobile_theme) && $user_mobile_theme !== '---') {
286 return $user_mobile_theme;
290 if (!$this->currentTheme) {
291 $this->computeCurrentTheme();
294 return $this->currentTheme;
298 * Returns the current mobile theme name.
303 public function getCurrentMobileTheme()
305 if ($this->mode->isInstall()) {
309 if (is_null($this->currentMobileTheme)) {
310 $this->computeCurrentMobileTheme();
313 return $this->currentMobileTheme;
316 public function setCurrentTheme($theme)
318 $this->currentTheme = $theme;
321 public function setCurrentMobileTheme($theme)
323 $this->currentMobileTheme = $theme;
327 * Computes the current theme name based on the node settings, the page owner settings and the user settings
331 private function computeCurrentTheme()
333 $system_theme = $this->config->get('system', 'theme');
334 if (!$system_theme) {
335 throw new Exception($this->l10n->t('No system theme config value set.'));
339 $this->setCurrentTheme($system_theme);
342 // Find the theme that belongs to the user whose stuff we are looking at
343 if ($this->profile_uid && ($this->profile_uid != local_user())) {
344 // Allow folks to override user themes and always use their own on their own site.
345 // This works only if the user is on the same server
346 $user = $this->database->selectFirst('user', ['theme'], ['uid' => $this->profile_uid]);
347 if ($this->database->isResult($user) && !Core\PConfig::get(local_user(), 'system', 'always_my_theme')) {
348 $page_theme = $user['theme'];
352 $theme_name = $page_theme ?: Core\Session::get('theme', $system_theme);
354 $theme_name = Strings::sanitizeFilePathItem($theme_name);
356 && in_array($theme_name, Theme::getAllowedList())
357 && (file_exists('view/theme/' . $theme_name . '/style.css')
358 || file_exists('view/theme/' . $theme_name . '/style.php'))
360 $this->setCurrentTheme($theme_name);
365 * Computes the current mobile theme name based on the node settings, the page owner settings and the user settings
367 private function computeCurrentMobileTheme()
369 $system_mobile_theme = $this->config->get('system', 'mobile-theme', '');
372 $this->setCurrentMobileTheme($system_mobile_theme);
374 $page_mobile_theme = null;
375 // Find the theme that belongs to the user whose stuff we are looking at
376 if ($this->profile_uid && ($this->profile_uid != local_user())) {
377 // Allow folks to override user themes and always use their own on their own site.
378 // This works only if the user is on the same server
379 if (!Core\PConfig::get(local_user(), 'system', 'always_my_theme')) {
380 $page_mobile_theme = Core\PConfig::get($this->profile_uid, 'system', 'mobile-theme');
384 $mobile_theme_name = $page_mobile_theme ?: Core\Session::get('mobile-theme', $system_mobile_theme);
386 $mobile_theme_name = Strings::sanitizeFilePathItem($mobile_theme_name);
387 if ($mobile_theme_name == '---'
389 in_array($mobile_theme_name, Theme::getAllowedList())
390 && (file_exists('view/theme/' . $mobile_theme_name . '/style.css')
391 || file_exists('view/theme/' . $mobile_theme_name . '/style.php'))
393 $this->setCurrentMobileTheme($mobile_theme_name);
398 * @brief Return full URL to theme which is currently in effect.
400 * Provide a sane default if nothing is chosen or the specified theme does not exist.
405 public function getCurrentThemeStylesheetPath()
407 return Core\Theme::getStylesheetPath($this->getCurrentTheme());
411 * Sets the base url for use in cmdline programs which don't have
414 public function checkURL()
416 $url = $this->config->get('system', 'url');
418 // if the url isn't set or the stored url is radically different
419 // than the currently visited url, store the current value accordingly.
420 // "Radically different" ignores common variations such as http vs https
421 // and www.example.com vs example.com.
422 // We will only change the url to an ip address if there is no existing setting
424 if (empty($url) || (!Util\Strings::compareLink($url, $this->baseURL->get())) && (!preg_match("/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/", $this->baseURL->getHostname()))) {
425 $this->config->set('system', 'url', $this->baseURL->get());
430 * Frontend App script
432 * The App object behaves like a container and a dispatcher at the same time, including a representation of the
433 * request and a representation of the response.
435 * This probably should change to limit the size of this monster method.
437 * @param App\Module $module The determined module
438 * @param App\Router $router
439 * @param PConfiguration $pconfig
440 * @param Authentication $auth The Authentication backend of the node
441 * @throws HTTPException\InternalServerErrorException
442 * @throws \ImagickException
444 public function runFrontend(App\Module $module, App\Router $router, PConfiguration $pconfig, Authentication $auth)
446 $moduleName = $module->getName();
449 // Missing DB connection: ERROR
450 if ($this->mode->has(App\Mode::LOCALCONFIGPRESENT) && !$this->mode->has(App\Mode::DBAVAILABLE)) {
451 throw new HTTPException\InternalServerErrorException('Apologies but the website is unavailable at the moment.');
454 // Max Load Average reached: ERROR
455 if ($this->process->isMaxProcessesReached() || $this->process->isMaxLoadReached()) {
456 header('Retry-After: 120');
457 header('Refresh: 120; url=' . $this->baseURL->get() . "/" . $this->args->getQueryString());
459 throw new HTTPException\ServiceUnavailableException('The node is currently overloaded. Please try again later.');
462 if (!$this->mode->isInstall()) {
463 // Force SSL redirection
464 if ($this->baseURL->checkRedirectHttps()) {
465 System::externalRedirect($this->baseURL->get() . '/' . $this->args->getQueryString());
468 Core\Hook::callAll('init_1');
471 // Exclude the backend processes from the session management
472 if ($this->mode->isBackend()) {
473 Core\Worker::executeIfIdle();
476 if ($this->mode->isNormal()) {
477 $requester = HTTPSignature::getSigner('', $_SERVER);
478 if (!empty($requester)) {
479 Profile::addVisitorCookieForHandle($requester);
484 if (!empty($_GET['zrl']) && $this->mode->isNormal()) {
486 // Only continue when the given profile link seems valid
487 // Valid profile links contain a path with "/profile/" and no query parameters
488 if ((parse_url($_GET['zrl'], PHP_URL_QUERY) == "") &&
489 strstr(parse_url($_GET['zrl'], PHP_URL_PATH), "/profile/")) {
490 if (Core\Session::get('visitor_home') != $_GET["zrl"]) {
491 Core\Session::set('my_url', $_GET['zrl']);
492 Core\Session::set('authenticated', 0);
495 Model\Profile::zrlInit($this);
497 // Someone came with an invalid parameter, maybe as a DDoS attempt
498 // We simply stop processing here
499 $this->logger->debug('Invalid ZRL parameter.', ['zrl' => $_GET['zrl']]);
500 throw new HTTPException\ForbiddenException();
505 if (!empty($_GET['owt']) && $this->mode->isNormal()) {
506 $token = $_GET['owt'];
507 Model\Profile::openWebAuthInit($token);
510 $auth->withSession($this);
512 if (empty($_SESSION['authenticated'])) {
513 header('X-Account-Management-Status: none');
516 $_SESSION['sysmsg'] = Core\Session::get('sysmsg', []);
517 $_SESSION['sysmsg_info'] = Core\Session::get('sysmsg_info', []);
518 $_SESSION['last_updated'] = Core\Session::get('last_updated', []);
521 * check_config() is responsible for running update scripts. These automatically
522 * update the DB schema whenever we push a new one out. It also checks to see if
523 * any addons have been added or removed and reacts accordingly.
526 // in install mode, any url loads install module
527 // but we need "view" module for stylesheet
528 if ($this->mode->isInstall() && $moduleName !== 'install') {
529 $this->baseURL->redirect('install');
530 } elseif (!$this->mode->isInstall() && !$this->mode->has(App\Mode::MAINTENANCEDISABLED) && $moduleName !== 'maintenance') {
531 $this->baseURL->redirect('maintenance');
534 Core\Update::check($this->getBasePath(), false, $this->mode);
535 Core\Addon::loadAddons();
536 Core\Hook::loadHooks();
539 // Compatibility with the Android Diaspora client
540 if ($moduleName == 'stream') {
541 $this->baseURL->redirect('network?order=post');
544 if ($moduleName == 'conversations') {
545 $this->baseURL->redirect('message');
548 if ($moduleName == 'commented') {
549 $this->baseURL->redirect('network?order=comment');
552 if ($moduleName == 'liked') {
553 $this->baseURL->redirect('network?order=comment');
556 if ($moduleName == 'activity') {
557 $this->baseURL->redirect('network?conv=1');
560 if (($moduleName == 'status_messages') && ($this->args->getCommand() == 'status_messages/new')) {
561 $this->baseURL->redirect('bookmarklet');
564 if (($moduleName == 'user') && ($this->args->getCommand() == 'user/edit')) {
565 $this->baseURL->redirect('settings');
568 if (($moduleName == 'tag_followings') && ($this->args->getCommand() == 'tag_followings/manage')) {
569 $this->baseURL->redirect('search');
572 // Initialize module that can set the current theme in the init() method, either directly or via App->profile_uid
573 $this->page['page_title'] = $moduleName;
575 // determine the module class and save it to the module instance
576 // @todo there's an implicit dependency due SESSION::start(), so it has to be called here (yet)
577 $module = $module->determineClass($this->args, $router, $this->config);
579 // Let the module run it's internal process (init, get, post, ...)
580 $module->run($this->l10n, $this->baseURL, $this->logger, $_SERVER, $_POST);
581 } catch (HTTPException $e) {
582 ModuleHTTPException::rawContent($e);
585 $this->page->run($this, $this->baseURL, $this->mode, $module, $this->l10n, $this->config, $pconfig);
589 * Automatically redirects to relative or absolute URL
590 * Should only be used if it isn't clear if the URL is either internal or external
592 * @param string $toUrl The target URL
594 * @throws HTTPException\InternalServerErrorException
596 public function redirect($toUrl)
598 if (!empty(parse_url($toUrl, PHP_URL_SCHEME))) {
599 Core\System::externalRedirect($toUrl);
601 $this->baseURL->redirect($toUrl);