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() */
61 public $interactive = true;
63 public $theme_info = [];
65 // Allow themes to control internal parameters
66 // by changing App values in theme.php
68 public $sourcename = '';
69 public $videowidth = 425;
70 public $videoheight = 350;
71 public $force_max_items = 0;
72 public $theme_events_in_profile = true;
76 * @var App\Mode The Mode of the Application
85 /** @var string The name of the current theme */
86 private $currentTheme;
87 /** @var string The name of the current mobile theme */
88 private $currentMobileTheme;
91 * @var Configuration The config
96 * @var LoggerInterface The logger
101 * @var Profiler The profiler of this app
106 * @var Database The Friendica database connection
111 * @var L10n The translator
121 * @var Core\Process The process methods
126 * Returns the current config cache of this node
128 * @return ConfigCache
130 public function getConfigCache()
132 return $this->config->getCache();
136 * The basepath of this app
140 public function getBasePath()
142 // Don't use the basepath of the config table for basepath (it should always be the config-file one)
143 return $this->config->getCache()->get('system', 'basepath');
147 * @param Database $database The Friendica Database
148 * @param Configuration $config The Configuration
149 * @param App\Mode $mode The mode of this Friendica app
150 * @param BaseURL $baseURL The full base URL of this Friendica app
151 * @param LoggerInterface $logger The current app logger
152 * @param Profiler $profiler The profiler of this application
153 * @param L10n $l10n The translator instance
154 * @param App\Arguments $args The Friendica Arguments of the call
155 * @param Core\Process $process The process methods
157 public function __construct(Database $database, Configuration $config, App\Mode $mode, BaseURL $baseURL, LoggerInterface $logger, Profiler $profiler, L10n $l10n, Arguments $args, App\Page $page, Core\Process $process)
159 $this->database = $database;
160 $this->config = $config;
162 $this->baseURL = $baseURL;
163 $this->profiler = $profiler;
164 $this->logger = $logger;
167 $this->process = $process;
169 $this->argv = $args->getArgv();
170 $this->argc = $args->getArgc();
177 * Load the whole app instance
179 public function load()
183 // This has to be quite large to deal with embedded private photos
184 ini_set('pcre.backtrack_limit', 500000);
187 get_include_path() . PATH_SEPARATOR
188 . $this->getBasePath() . DIRECTORY_SEPARATOR . 'include' . PATH_SEPARATOR
189 . $this->getBasePath() . DIRECTORY_SEPARATOR . 'library' . PATH_SEPARATOR
190 . $this->getBasePath());
192 $this->profiler->reset();
194 if ($this->mode->has(App\Mode::DBAVAILABLE)) {
195 $this->profiler->update($this->config);
197 Core\Hook::loadHooks();
198 $loader = new ConfigFileLoader($this->getBasePath());
199 Core\Hook::callAll('load_config', $loader);
202 $this->loadDefaultTimezone();
203 // Register template engines
204 Core\Renderer::registerTemplateEngine('Friendica\Render\FriendicaSmartyEngine');
208 * Loads the default timezone
210 * Include support for legacy $default_timezone
212 * @global string $default_timezone
214 private function loadDefaultTimezone()
216 if ($this->config->get('system', 'default_timezone')) {
217 $this->timezone = $this->config->get('system', 'default_timezone');
219 global $default_timezone;
220 $this->timezone = !empty($default_timezone) ? $default_timezone : 'UTC';
223 if ($this->timezone) {
224 date_default_timezone_set($this->timezone);
229 * Returns the current UserAgent as a String
231 * @return string the UserAgent as a String
232 * @throws HTTPException\InternalServerErrorException
234 public function getUserAgent()
237 FRIENDICA_PLATFORM . " '" .
238 FRIENDICA_CODENAME . "' " .
239 FRIENDICA_VERSION . '-' .
240 DB_UPDATE_VERSION . '; ' .
241 $this->baseURL->get();
245 * Generates the site's default sender email address
248 * @throws HTTPException\InternalServerErrorException
250 public function getSenderEmailAddress()
252 $sender_email = $this->config->get('config', 'sender_email');
253 if (empty($sender_email)) {
254 $hostname = $this->baseURL->getHostname();
255 if (strpos($hostname, ':')) {
256 $hostname = substr($hostname, 0, strpos($hostname, ':'));
259 $sender_email = 'noreply@' . $hostname;
262 return $sender_email;
266 * Returns the current theme name. May be overriden by the mobile theme name.
271 public function getCurrentTheme()
273 if ($this->mode->isInstall()) {
277 // Specific mobile theme override
278 if (($this->mode->isMobile() || $this->mode->isTablet()) && Core\Session::get('show-mobile', true)) {
279 $user_mobile_theme = $this->getCurrentMobileTheme();
281 // --- means same mobile theme as desktop
282 if (!empty($user_mobile_theme) && $user_mobile_theme !== '---') {
283 return $user_mobile_theme;
287 if (!$this->currentTheme) {
288 $this->computeCurrentTheme();
291 return $this->currentTheme;
295 * Returns the current mobile theme name.
300 public function getCurrentMobileTheme()
302 if ($this->mode->isInstall()) {
306 if (is_null($this->currentMobileTheme)) {
307 $this->computeCurrentMobileTheme();
310 return $this->currentMobileTheme;
313 public function setCurrentTheme($theme)
315 $this->currentTheme = $theme;
318 public function setCurrentMobileTheme($theme)
320 $this->currentMobileTheme = $theme;
324 * Computes the current theme name based on the node settings, the page owner settings and the user settings
328 private function computeCurrentTheme()
330 $system_theme = $this->config->get('system', 'theme');
331 if (!$system_theme) {
332 throw new Exception($this->l10n->t('No system theme config value set.'));
336 $this->setCurrentTheme($system_theme);
339 // Find the theme that belongs to the user whose stuff we are looking at
340 if ($this->profile_uid && ($this->profile_uid != local_user())) {
341 // Allow folks to override user themes and always use their own on their own site.
342 // This works only if the user is on the same server
343 $user = $this->database->selectFirst('user', ['theme'], ['uid' => $this->profile_uid]);
344 if ($this->database->isResult($user) && !Core\PConfig::get(local_user(), 'system', 'always_my_theme')) {
345 $page_theme = $user['theme'];
349 $theme_name = $page_theme ?: Core\Session::get('theme', $system_theme);
351 $theme_name = Strings::sanitizeFilePathItem($theme_name);
353 && in_array($theme_name, Theme::getAllowedList())
354 && (file_exists('view/theme/' . $theme_name . '/style.css')
355 || file_exists('view/theme/' . $theme_name . '/style.php'))
357 $this->setCurrentTheme($theme_name);
362 * Computes the current mobile theme name based on the node settings, the page owner settings and the user settings
364 private function computeCurrentMobileTheme()
366 $system_mobile_theme = $this->config->get('system', 'mobile-theme', '');
369 $this->setCurrentMobileTheme($system_mobile_theme);
371 $page_mobile_theme = null;
372 // Find the theme that belongs to the user whose stuff we are looking at
373 if ($this->profile_uid && ($this->profile_uid != local_user())) {
374 // Allow folks to override user themes and always use their own on their own site.
375 // This works only if the user is on the same server
376 if (!Core\PConfig::get(local_user(), 'system', 'always_my_theme')) {
377 $page_mobile_theme = Core\PConfig::get($this->profile_uid, 'system', 'mobile-theme');
381 $mobile_theme_name = $page_mobile_theme ?: Core\Session::get('mobile-theme', $system_mobile_theme);
383 $mobile_theme_name = Strings::sanitizeFilePathItem($mobile_theme_name);
384 if ($mobile_theme_name == '---'
386 in_array($mobile_theme_name, Theme::getAllowedList())
387 && (file_exists('view/theme/' . $mobile_theme_name . '/style.css')
388 || file_exists('view/theme/' . $mobile_theme_name . '/style.php'))
390 $this->setCurrentMobileTheme($mobile_theme_name);
395 * @brief Return full URL to theme which is currently in effect.
397 * Provide a sane default if nothing is chosen or the specified theme does not exist.
402 public function getCurrentThemeStylesheetPath()
404 return Core\Theme::getStylesheetPath($this->getCurrentTheme());
408 * Sets the base url for use in cmdline programs which don't have
411 public function checkURL()
413 $url = $this->config->get('system', 'url');
415 // if the url isn't set or the stored url is radically different
416 // than the currently visited url, store the current value accordingly.
417 // "Radically different" ignores common variations such as http vs https
418 // and www.example.com vs example.com.
419 // We will only change the url to an ip address if there is no existing setting
421 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()))) {
422 $this->config->set('system', 'url', $this->baseURL->get());
427 * Frontend App script
429 * The App object behaves like a container and a dispatcher at the same time, including a representation of the
430 * request and a representation of the response.
432 * This probably should change to limit the size of this monster method.
434 * @param App\Module $module The determined module
435 * @param App\Router $router
436 * @param PConfiguration $pconfig
437 * @param Authentication $auth The Authentication backend of the node
438 * @throws HTTPException\InternalServerErrorException
439 * @throws \ImagickException
441 public function runFrontend(App\Module $module, App\Router $router, PConfiguration $pconfig, Authentication $auth)
443 $moduleName = $module->getName();
446 // Missing DB connection: ERROR
447 if ($this->mode->has(App\Mode::LOCALCONFIGPRESENT) && !$this->mode->has(App\Mode::DBAVAILABLE)) {
448 throw new HTTPException\InternalServerErrorException('Apologies but the website is unavailable at the moment.');
451 // Max Load Average reached: ERROR
452 if ($this->process->isMaxProcessesReached() || $this->process->isMaxLoadReached()) {
453 header('Retry-After: 120');
454 header('Refresh: 120; url=' . $this->baseURL->get() . "/" . $this->args->getQueryString());
456 throw new HTTPException\ServiceUnavailableException('The node is currently overloaded. Please try again later.');
459 if (!$this->mode->isInstall()) {
460 // Force SSL redirection
461 if ($this->baseURL->checkRedirectHttps()) {
462 System::externalRedirect($this->baseURL->get() . '/' . $this->args->getQueryString());
465 Core\Hook::callAll('init_1');
468 // Exclude the backend processes from the session management
469 if ($this->mode->isBackend()) {
470 Core\Worker::executeIfIdle();
473 if ($this->mode->isNormal()) {
474 $requester = HTTPSignature::getSigner('', $_SERVER);
475 if (!empty($requester)) {
476 Profile::addVisitorCookieForHandle($requester);
481 if (!empty($_GET['zrl']) && $this->mode->isNormal()) {
483 // Only continue when the given profile link seems valid
484 // Valid profile links contain a path with "/profile/" and no query parameters
485 if ((parse_url($_GET['zrl'], PHP_URL_QUERY) == "") &&
486 strstr(parse_url($_GET['zrl'], PHP_URL_PATH), "/profile/")) {
487 if (Core\Session::get('visitor_home') != $_GET["zrl"]) {
488 Core\Session::set('my_url', $_GET['zrl']);
489 Core\Session::set('authenticated', 0);
492 Model\Profile::zrlInit($this);
494 // Someone came with an invalid parameter, maybe as a DDoS attempt
495 // We simply stop processing here
496 $this->logger->debug('Invalid ZRL parameter.', ['zrl' => $_GET['zrl']]);
497 throw new HTTPException\ForbiddenException();
502 if (!empty($_GET['owt']) && $this->mode->isNormal()) {
503 $token = $_GET['owt'];
504 Model\Profile::openWebAuthInit($token);
507 $auth->withSession($this);
509 if (empty($_SESSION['authenticated'])) {
510 header('X-Account-Management-Status: none');
513 $_SESSION['sysmsg'] = Core\Session::get('sysmsg', []);
514 $_SESSION['sysmsg_info'] = Core\Session::get('sysmsg_info', []);
515 $_SESSION['last_updated'] = Core\Session::get('last_updated', []);
518 * check_config() is responsible for running update scripts. These automatically
519 * update the DB schema whenever we push a new one out. It also checks to see if
520 * any addons have been added or removed and reacts accordingly.
523 // in install mode, any url loads install module
524 // but we need "view" module for stylesheet
525 if ($this->mode->isInstall() && $moduleName !== 'install') {
526 $this->baseURL->redirect('install');
527 } elseif (!$this->mode->isInstall() && !$this->mode->has(App\Mode::MAINTENANCEDISABLED) && $moduleName !== 'maintenance') {
528 $this->baseURL->redirect('maintenance');
531 Core\Update::check($this->getBasePath(), false, $this->mode);
532 Core\Addon::loadAddons();
533 Core\Hook::loadHooks();
536 // Compatibility with the Android Diaspora client
537 if ($moduleName == 'stream') {
538 $this->baseURL->redirect('network?order=post');
541 if ($moduleName == 'conversations') {
542 $this->baseURL->redirect('message');
545 if ($moduleName == 'commented') {
546 $this->baseURL->redirect('network?order=comment');
549 if ($moduleName == 'liked') {
550 $this->baseURL->redirect('network?order=comment');
553 if ($moduleName == 'activity') {
554 $this->baseURL->redirect('network?conv=1');
557 if (($moduleName == 'status_messages') && ($this->args->getCommand() == 'status_messages/new')) {
558 $this->baseURL->redirect('bookmarklet');
561 if (($moduleName == 'user') && ($this->args->getCommand() == 'user/edit')) {
562 $this->baseURL->redirect('settings');
565 if (($moduleName == 'tag_followings') && ($this->args->getCommand() == 'tag_followings/manage')) {
566 $this->baseURL->redirect('search');
569 // Initialize module that can set the current theme in the init() method, either directly or via App->profile_uid
570 $this->page['page_title'] = $moduleName;
572 // determine the module class and save it to the module instance
573 // @todo there's an implicit dependency due SESSION::start(), so it has to be called here (yet)
574 $module = $module->determineClass($this->args, $router, $this->config);
576 // Let the module run it's internal process (init, get, post, ...)
577 $module->run($this->l10n, $this->baseURL, $this->logger, $_SERVER, $_POST);
578 } catch (HTTPException $e) {
579 ModuleHTTPException::rawContent($e);
582 $this->page->run($this, $this->baseURL, $this->mode, $module, $this->l10n, $this->config, $pconfig);
586 * Automatically redirects to relative or absolute URL
587 * Should only be used if it isn't clear if the URL is either internal or external
589 * @param string $toUrl The target URL
591 * @throws HTTPException\InternalServerErrorException
593 public function redirect($toUrl)
595 if (!empty(parse_url($toUrl, PHP_URL_SCHEME))) {
596 Core\System::externalRedirect($toUrl);
598 $this->baseURL->redirect($toUrl);