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 * @param Database $database The Friendica Database
158 * @param Configuration $config The Configuration
159 * @param App\Mode $mode The mode of this Friendica app
160 * @param BaseURL $baseURL The full base URL of this Friendica app
161 * @param LoggerInterface $logger The current app logger
162 * @param Profiler $profiler The profiler of this application
163 * @param L10n $l10n The translator instance
164 * @param App\Arguments $args The Friendica Arguments of the call
165 * @param Core\Process $process The process methods
167 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)
169 $this->database = $database;
170 $this->config = $config;
172 $this->baseURL = $baseURL;
173 $this->profiler = $profiler;
174 $this->logger = $logger;
177 $this->process = $process;
179 $this->cmd = $args->getCommand();
180 $this->argv = $args->getArgv();
181 $this->argc = $args->getArgc();
182 $this->query_string = $args->getQueryString();
183 $this->module = $module->getName();
186 $this->is_mobile = $mode->isMobile();
187 $this->is_tablet = $mode->isTablet();
193 * Load the whole app instance
195 public function load()
199 // This has to be quite large to deal with embedded private photos
200 ini_set('pcre.backtrack_limit', 500000);
203 get_include_path() . PATH_SEPARATOR
204 . $this->getBasePath() . DIRECTORY_SEPARATOR . 'include' . PATH_SEPARATOR
205 . $this->getBasePath() . DIRECTORY_SEPARATOR . 'library' . PATH_SEPARATOR
206 . $this->getBasePath());
208 $this->profiler->reset();
210 if ($this->mode->has(App\Mode::DBAVAILABLE)) {
211 $this->profiler->update($this->config);
213 Core\Hook::loadHooks();
214 $loader = new ConfigFileLoader($this->getBasePath());
215 Core\Hook::callAll('load_config', $loader);
218 $this->loadDefaultTimezone();
219 // Register template engines
220 Core\Renderer::registerTemplateEngine('Friendica\Render\FriendicaSmartyEngine');
224 * Loads the default timezone
226 * Include support for legacy $default_timezone
228 * @global string $default_timezone
230 private function loadDefaultTimezone()
232 if ($this->config->get('system', 'default_timezone')) {
233 $this->timezone = $this->config->get('system', 'default_timezone');
235 global $default_timezone;
236 $this->timezone = !empty($default_timezone) ? $default_timezone : 'UTC';
239 if ($this->timezone) {
240 date_default_timezone_set($this->timezone);
245 * Returns the current UserAgent as a String
247 * @return string the UserAgent as a String
248 * @throws HTTPException\InternalServerErrorException
250 public function getUserAgent()
253 FRIENDICA_PLATFORM . " '" .
254 FRIENDICA_CODENAME . "' " .
255 FRIENDICA_VERSION . '-' .
256 DB_UPDATE_VERSION . '; ' .
257 $this->baseURL->get();
261 * Generates the site's default sender email address
264 * @throws HTTPException\InternalServerErrorException
266 public function getSenderEmailAddress()
268 $sender_email = $this->config->get('config', 'sender_email');
269 if (empty($sender_email)) {
270 $hostname = $this->baseURL->getHostname();
271 if (strpos($hostname, ':')) {
272 $hostname = substr($hostname, 0, strpos($hostname, ':'));
275 $sender_email = 'noreply@' . $hostname;
278 return $sender_email;
282 * Returns the current theme name. May be overriden by the mobile theme name.
287 public function getCurrentTheme()
289 if ($this->mode->isInstall()) {
293 // Specific mobile theme override
294 if (($this->mode->isMobile() || $this->mode->isTablet()) && Core\Session::get('show-mobile', true)) {
295 $user_mobile_theme = $this->getCurrentMobileTheme();
297 // --- means same mobile theme as desktop
298 if (!empty($user_mobile_theme) && $user_mobile_theme !== '---') {
299 return $user_mobile_theme;
303 if (!$this->currentTheme) {
304 $this->computeCurrentTheme();
307 return $this->currentTheme;
311 * Returns the current mobile theme name.
316 public function getCurrentMobileTheme()
318 if ($this->mode->isInstall()) {
322 if (is_null($this->currentMobileTheme)) {
323 $this->computeCurrentMobileTheme();
326 return $this->currentMobileTheme;
329 public function setCurrentTheme($theme)
331 $this->currentTheme = $theme;
334 public function setCurrentMobileTheme($theme)
336 $this->currentMobileTheme = $theme;
340 * Computes the current theme name based on the node settings, the page owner settings and the user settings
344 private function computeCurrentTheme()
346 $system_theme = $this->config->get('system', 'theme');
347 if (!$system_theme) {
348 throw new Exception($this->l10n->t('No system theme config value set.'));
352 $this->setCurrentTheme($system_theme);
355 // Find the theme that belongs to the user whose stuff we are looking at
356 if ($this->profile_uid && ($this->profile_uid != local_user())) {
357 // Allow folks to override user themes and always use their own on their own site.
358 // This works only if the user is on the same server
359 $user = $this->database->selectFirst('user', ['theme'], ['uid' => $this->profile_uid]);
360 if ($this->database->isResult($user) && !Core\PConfig::get(local_user(), 'system', 'always_my_theme')) {
361 $page_theme = $user['theme'];
365 $theme_name = $page_theme ?: Core\Session::get('theme', $system_theme);
367 $theme_name = Strings::sanitizeFilePathItem($theme_name);
369 && in_array($theme_name, Theme::getAllowedList())
370 && (file_exists('view/theme/' . $theme_name . '/style.css')
371 || file_exists('view/theme/' . $theme_name . '/style.php'))
373 $this->setCurrentTheme($theme_name);
378 * Computes the current mobile theme name based on the node settings, the page owner settings and the user settings
380 private function computeCurrentMobileTheme()
382 $system_mobile_theme = $this->config->get('system', 'mobile-theme', '');
385 $this->setCurrentMobileTheme($system_mobile_theme);
387 $page_mobile_theme = null;
388 // Find the theme that belongs to the user whose stuff we are looking at
389 if ($this->profile_uid && ($this->profile_uid != local_user())) {
390 // Allow folks to override user themes and always use their own on their own site.
391 // This works only if the user is on the same server
392 if (!Core\PConfig::get(local_user(), 'system', 'always_my_theme')) {
393 $page_mobile_theme = Core\PConfig::get($this->profile_uid, 'system', 'mobile-theme');
397 $mobile_theme_name = $page_mobile_theme ?: Core\Session::get('mobile-theme', $system_mobile_theme);
399 $mobile_theme_name = Strings::sanitizeFilePathItem($mobile_theme_name);
400 if ($mobile_theme_name == '---'
402 in_array($mobile_theme_name, Theme::getAllowedList())
403 && (file_exists('view/theme/' . $mobile_theme_name . '/style.css')
404 || file_exists('view/theme/' . $mobile_theme_name . '/style.php'))
406 $this->setCurrentMobileTheme($mobile_theme_name);
411 * @brief Return full URL to theme which is currently in effect.
413 * Provide a sane default if nothing is chosen or the specified theme does not exist.
418 public function getCurrentThemeStylesheetPath()
420 return Core\Theme::getStylesheetPath($this->getCurrentTheme());
424 * Sets the base url for use in cmdline programs which don't have
427 public function checkURL()
429 $url = $this->config->get('system', 'url');
431 // if the url isn't set or the stored url is radically different
432 // than the currently visited url, store the current value accordingly.
433 // "Radically different" ignores common variations such as http vs https
434 // and www.example.com vs example.com.
435 // We will only change the url to an ip address if there is no existing setting
437 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()))) {
438 $this->config->set('system', 'url', $this->baseURL->get());
443 * Frontend App script
445 * The App object behaves like a container and a dispatcher at the same time, including a representation of the
446 * request and a representation of the response.
448 * This probably should change to limit the size of this monster method.
450 * @param App\Module $module The determined module
451 * @param App\Router $router
452 * @param PConfiguration $pconfig
453 * @param Authentication $auth The Authentication backend of the node
454 * @throws HTTPException\InternalServerErrorException
455 * @throws \ImagickException
457 public function runFrontend(App\Module $module, App\Router $router, PConfiguration $pconfig, Authentication $auth)
459 $moduleName = $module->getName();
462 // Missing DB connection: ERROR
463 if ($this->mode->has(App\Mode::LOCALCONFIGPRESENT) && !$this->mode->has(App\Mode::DBAVAILABLE)) {
464 throw new HTTPException\InternalServerErrorException('Apologies but the website is unavailable at the moment.');
467 // Max Load Average reached: ERROR
468 if ($this->process->isMaxProcessesReached() || $this->process->isMaxLoadReached()) {
469 header('Retry-After: 120');
470 header('Refresh: 120; url=' . $this->baseURL->get() . "/" . $this->args->getQueryString());
472 throw new HTTPException\ServiceUnavailableException('The node is currently overloaded. Please try again later.');
475 if (!$this->mode->isInstall()) {
476 // Force SSL redirection
477 if ($this->baseURL->checkRedirectHttps()) {
478 System::externalRedirect($this->baseURL->get() . '/' . $this->args->getQueryString());
481 Core\Hook::callAll('init_1');
484 // Exclude the backend processes from the session management
485 if ($this->mode->isBackend()) {
486 Core\Worker::executeIfIdle();
489 if ($this->mode->isNormal()) {
490 $requester = HTTPSignature::getSigner('', $_SERVER);
491 if (!empty($requester)) {
492 Profile::addVisitorCookieForHandle($requester);
497 if (!empty($_GET['zrl']) && $this->mode->isNormal()) {
499 // Only continue when the given profile link seems valid
500 // Valid profile links contain a path with "/profile/" and no query parameters
501 if ((parse_url($_GET['zrl'], PHP_URL_QUERY) == "") &&
502 strstr(parse_url($_GET['zrl'], PHP_URL_PATH), "/profile/")) {
503 if (Core\Session::get('visitor_home') != $_GET["zrl"]) {
504 Core\Session::set('my_url', $_GET['zrl']);
505 Core\Session::set('authenticated', 0);
508 Model\Profile::zrlInit($this);
510 // Someone came with an invalid parameter, maybe as a DDoS attempt
511 // We simply stop processing here
512 $this->logger->debug('Invalid ZRL parameter.', ['zrl' => $_GET['zrl']]);
513 throw new HTTPException\ForbiddenException();
518 if (!empty($_GET['owt']) && $this->mode->isNormal()) {
519 $token = $_GET['owt'];
520 Model\Profile::openWebAuthInit($token);
523 $auth->withSession($this);
525 if (empty($_SESSION['authenticated'])) {
526 header('X-Account-Management-Status: none');
529 $_SESSION['sysmsg'] = Core\Session::get('sysmsg', []);
530 $_SESSION['sysmsg_info'] = Core\Session::get('sysmsg_info', []);
531 $_SESSION['last_updated'] = Core\Session::get('last_updated', []);
534 * check_config() is responsible for running update scripts. These automatically
535 * update the DB schema whenever we push a new one out. It also checks to see if
536 * any addons have been added or removed and reacts accordingly.
539 // in install mode, any url loads install module
540 // but we need "view" module for stylesheet
541 if ($this->mode->isInstall() && $moduleName !== 'install') {
542 $this->baseURL->redirect('install');
543 } elseif (!$this->mode->isInstall() && !$this->mode->has(App\Mode::MAINTENANCEDISABLED) && $moduleName !== 'maintenance') {
544 $this->baseURL->redirect('maintenance');
547 Core\Update::check($this->getBasePath(), false, $this->mode);
548 Core\Addon::loadAddons();
549 Core\Hook::loadHooks();
552 // Compatibility with the Android Diaspora client
553 if ($moduleName == 'stream') {
554 $this->baseURL->redirect('network?order=post');
557 if ($moduleName == 'conversations') {
558 $this->baseURL->redirect('message');
561 if ($moduleName == 'commented') {
562 $this->baseURL->redirect('network?order=comment');
565 if ($moduleName == 'liked') {
566 $this->baseURL->redirect('network?order=comment');
569 if ($moduleName == 'activity') {
570 $this->baseURL->redirect('network?conv=1');
573 if (($moduleName == 'status_messages') && ($this->args->getCommand() == 'status_messages/new')) {
574 $this->baseURL->redirect('bookmarklet');
577 if (($moduleName == 'user') && ($this->args->getCommand() == 'user/edit')) {
578 $this->baseURL->redirect('settings');
581 if (($moduleName == 'tag_followings') && ($this->args->getCommand() == 'tag_followings/manage')) {
582 $this->baseURL->redirect('search');
585 // Initialize module that can set the current theme in the init() method, either directly or via App->profile_uid
586 $this->page['page_title'] = $moduleName;
588 // determine the module class and save it to the module instance
589 // @todo there's an implicit dependency due SESSION::start(), so it has to be called here (yet)
590 $module = $module->determineClass($this->args, $router, $this->config);
592 // Let the module run it's internal process (init, get, post, ...)
593 $module->run($this->l10n, $this->baseURL, $this->logger, $_SERVER, $_POST);
594 } catch (HTTPException $e) {
595 ModuleHTTPException::rawContent($e);
598 $this->page->run($this, $this->baseURL, $this->mode, $module, $this->l10n, $this->config, $pconfig);
602 * Automatically redirects to relative or absolute URL
603 * Should only be used if it isn't clear if the URL is either internal or external
605 * @param string $toUrl The target URL
607 * @throws HTTPException\InternalServerErrorException
609 public function redirect($toUrl)
611 if (!empty(parse_url($toUrl, PHP_URL_SCHEME))) {
612 Core\System::externalRedirect($toUrl);
614 $this->baseURL->redirect($toUrl);