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\IConfiguration;
14 use Friendica\Core\Config\IPConfiguration;
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.
52 /** @deprecated 2019.09 - use App\Arguments->getArgv() or Arguments->get() */
54 /** @deprecated 2019.09 - use App\Arguments->getArgc() */
57 public $interactive = true;
59 public $theme_info = [];
61 // Allow themes to control internal parameters
62 // by changing App values in theme.php
64 public $sourcename = '';
65 public $videowidth = 425;
66 public $videoheight = 350;
67 public $force_max_items = 0;
68 public $theme_events_in_profile = true;
72 * @var App\Mode The Mode of the Application
81 /** @var string The name of the current theme */
82 private $currentTheme;
83 /** @var string The name of the current mobile theme */
84 private $currentMobileTheme;
87 * @var IConfiguration The config
92 * @var LoggerInterface The logger
97 * @var Profiler The profiler of this app
102 * @var Database The Friendica database connection
107 * @var L10n The translator
117 * @var Core\Process The process methods
122 * Returns the current config cache of this node
124 * @return ConfigCache
126 public function getConfigCache()
128 return $this->config->getCache();
132 * The basepath of this app
136 public function getBasePath()
138 // Don't use the basepath of the config table for basepath (it should always be the config-file one)
139 return $this->config->getCache()->get('system', 'basepath');
143 * @param Database $database The Friendica Database
144 * @param IConfiguration $config The Configuration
145 * @param App\Mode $mode The mode of this Friendica app
146 * @param BaseURL $baseURL The full base URL of this Friendica app
147 * @param LoggerInterface $logger The current app logger
148 * @param Profiler $profiler The profiler of this application
149 * @param L10n $l10n The translator instance
150 * @param App\Arguments $args The Friendica Arguments of the call
151 * @param Core\Process $process The process methods
153 public function __construct(Database $database, IConfiguration $config, App\Mode $mode, BaseURL $baseURL, LoggerInterface $logger, Profiler $profiler, L10n $l10n, Arguments $args, Core\Process $process)
155 $this->database = $database;
156 $this->config = $config;
158 $this->baseURL = $baseURL;
159 $this->profiler = $profiler;
160 $this->logger = $logger;
163 $this->process = $process;
165 $this->argv = $args->getArgv();
166 $this->argc = $args->getArgc();
172 * Load the whole app instance
174 public function load()
178 // This has to be quite large to deal with embedded private photos
179 ini_set('pcre.backtrack_limit', 500000);
182 get_include_path() . PATH_SEPARATOR
183 . $this->getBasePath() . DIRECTORY_SEPARATOR . 'include' . PATH_SEPARATOR
184 . $this->getBasePath() . DIRECTORY_SEPARATOR . 'library' . PATH_SEPARATOR
185 . $this->getBasePath());
187 $this->profiler->reset();
189 if ($this->mode->has(App\Mode::DBAVAILABLE)) {
190 $this->profiler->update($this->config);
192 Core\Hook::loadHooks();
193 $loader = new ConfigFileLoader($this->getBasePath());
194 Core\Hook::callAll('load_config', $loader);
197 $this->loadDefaultTimezone();
198 // Register template engines
199 Core\Renderer::registerTemplateEngine('Friendica\Render\FriendicaSmartyEngine');
203 * Loads the default timezone
205 * Include support for legacy $default_timezone
207 * @global string $default_timezone
209 private function loadDefaultTimezone()
211 if ($this->config->get('system', 'default_timezone')) {
212 $this->timezone = $this->config->get('system', 'default_timezone');
214 global $default_timezone;
215 $this->timezone = !empty($default_timezone) ? $default_timezone : 'UTC';
218 if ($this->timezone) {
219 date_default_timezone_set($this->timezone);
224 * Returns the current UserAgent as a String
226 * @return string the UserAgent as a String
227 * @throws HTTPException\InternalServerErrorException
229 public function getUserAgent()
232 FRIENDICA_PLATFORM . " '" .
233 FRIENDICA_CODENAME . "' " .
234 FRIENDICA_VERSION . '-' .
235 DB_UPDATE_VERSION . '; ' .
236 $this->baseURL->get();
240 * Generates the site's default sender email address
243 * @throws HTTPException\InternalServerErrorException
245 public function getSenderEmailAddress()
247 $sender_email = $this->config->get('config', 'sender_email');
248 if (empty($sender_email)) {
249 $hostname = $this->baseURL->getHostname();
250 if (strpos($hostname, ':')) {
251 $hostname = substr($hostname, 0, strpos($hostname, ':'));
254 $sender_email = 'noreply@' . $hostname;
257 return $sender_email;
261 * Returns the current theme name. May be overriden by the mobile theme name.
266 public function getCurrentTheme()
268 if ($this->mode->isInstall()) {
272 // Specific mobile theme override
273 if (($this->mode->isMobile() || $this->mode->isTablet()) && Core\Session::get('show-mobile', true)) {
274 $user_mobile_theme = $this->getCurrentMobileTheme();
276 // --- means same mobile theme as desktop
277 if (!empty($user_mobile_theme) && $user_mobile_theme !== '---') {
278 return $user_mobile_theme;
282 if (!$this->currentTheme) {
283 $this->computeCurrentTheme();
286 return $this->currentTheme;
290 * Returns the current mobile theme name.
295 public function getCurrentMobileTheme()
297 if ($this->mode->isInstall()) {
301 if (is_null($this->currentMobileTheme)) {
302 $this->computeCurrentMobileTheme();
305 return $this->currentMobileTheme;
308 public function setCurrentTheme($theme)
310 $this->currentTheme = $theme;
313 public function setCurrentMobileTheme($theme)
315 $this->currentMobileTheme = $theme;
319 * Computes the current theme name based on the node settings, the page owner settings and the user settings
323 private function computeCurrentTheme()
325 $system_theme = $this->config->get('system', 'theme');
326 if (!$system_theme) {
327 throw new Exception($this->l10n->t('No system theme config value set.'));
331 $this->setCurrentTheme($system_theme);
334 // Find the theme that belongs to the user whose stuff we are looking at
335 if ($this->profile_uid && ($this->profile_uid != local_user())) {
336 // Allow folks to override user themes and always use their own on their own site.
337 // This works only if the user is on the same server
338 $user = $this->database->selectFirst('user', ['theme'], ['uid' => $this->profile_uid]);
339 if ($this->database->isResult($user) && !Core\PConfig::get(local_user(), 'system', 'always_my_theme')) {
340 $page_theme = $user['theme'];
344 $theme_name = $page_theme ?: Core\Session::get('theme', $system_theme);
346 $theme_name = Strings::sanitizeFilePathItem($theme_name);
348 && in_array($theme_name, Theme::getAllowedList())
349 && (file_exists('view/theme/' . $theme_name . '/style.css')
350 || file_exists('view/theme/' . $theme_name . '/style.php'))
352 $this->setCurrentTheme($theme_name);
357 * Computes the current mobile theme name based on the node settings, the page owner settings and the user settings
359 private function computeCurrentMobileTheme()
361 $system_mobile_theme = $this->config->get('system', 'mobile-theme', '');
364 $this->setCurrentMobileTheme($system_mobile_theme);
366 $page_mobile_theme = null;
367 // Find the theme that belongs to the user whose stuff we are looking at
368 if ($this->profile_uid && ($this->profile_uid != local_user())) {
369 // Allow folks to override user themes and always use their own on their own site.
370 // This works only if the user is on the same server
371 if (!Core\PConfig::get(local_user(), 'system', 'always_my_theme')) {
372 $page_mobile_theme = Core\PConfig::get($this->profile_uid, 'system', 'mobile-theme');
376 $mobile_theme_name = $page_mobile_theme ?: Core\Session::get('mobile-theme', $system_mobile_theme);
378 $mobile_theme_name = Strings::sanitizeFilePathItem($mobile_theme_name);
379 if ($mobile_theme_name == '---'
381 in_array($mobile_theme_name, Theme::getAllowedList())
382 && (file_exists('view/theme/' . $mobile_theme_name . '/style.css')
383 || file_exists('view/theme/' . $mobile_theme_name . '/style.php'))
385 $this->setCurrentMobileTheme($mobile_theme_name);
390 * @brief Return full URL to theme which is currently in effect.
392 * Provide a sane default if nothing is chosen or the specified theme does not exist.
397 public function getCurrentThemeStylesheetPath()
399 return Core\Theme::getStylesheetPath($this->getCurrentTheme());
403 * Sets the base url for use in cmdline programs which don't have
406 public function checkURL()
408 $url = $this->config->get('system', 'url');
410 // if the url isn't set or the stored url is radically different
411 // than the currently visited url, store the current value accordingly.
412 // "Radically different" ignores common variations such as http vs https
413 // and www.example.com vs example.com.
414 // We will only change the url to an ip address if there is no existing setting
416 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()))) {
417 $this->config->set('system', 'url', $this->baseURL->get());
422 * Frontend App script
424 * The App object behaves like a container and a dispatcher at the same time, including a representation of the
425 * request and a representation of the response.
427 * This probably should change to limit the size of this monster method.
429 * @param App\Module $module The determined module
430 * @param App\Router $router
431 * @param IPConfiguration $pconfig
432 * @param Authentication $auth The Authentication backend of the node
433 * @param App\Page $page The Friendica page printing container
434 * @throws HTTPException\InternalServerErrorException
435 * @throws \ImagickException
437 public function runFrontend(App\Module $module, App\Router $router, IPConfiguration $pconfig, Authentication $auth, App\Page $page)
439 $moduleName = $module->getName();
442 // Missing DB connection: ERROR
443 if ($this->mode->has(App\Mode::LOCALCONFIGPRESENT) && !$this->mode->has(App\Mode::DBAVAILABLE)) {
444 throw new HTTPException\InternalServerErrorException('Apologies but the website is unavailable at the moment.');
447 // Max Load Average reached: ERROR
448 if ($this->process->isMaxProcessesReached() || $this->process->isMaxLoadReached()) {
449 header('Retry-After: 120');
450 header('Refresh: 120; url=' . $this->baseURL->get() . "/" . $this->args->getQueryString());
452 throw new HTTPException\ServiceUnavailableException('The node is currently overloaded. Please try again later.');
455 if (!$this->mode->isInstall()) {
456 // Force SSL redirection
457 if ($this->baseURL->checkRedirectHttps()) {
458 System::externalRedirect($this->baseURL->get() . '/' . $this->args->getQueryString());
461 Core\Hook::callAll('init_1');
464 // Exclude the backend processes from the session management
465 if ($this->mode->isBackend()) {
466 Core\Worker::executeIfIdle();
469 if ($this->mode->isNormal()) {
470 $requester = HTTPSignature::getSigner('', $_SERVER);
471 if (!empty($requester)) {
472 Profile::addVisitorCookieForHandle($requester);
477 if (!empty($_GET['zrl']) && $this->mode->isNormal()) {
479 // Only continue when the given profile link seems valid
480 // Valid profile links contain a path with "/profile/" and no query parameters
481 if ((parse_url($_GET['zrl'], PHP_URL_QUERY) == "") &&
482 strstr(parse_url($_GET['zrl'], PHP_URL_PATH), "/profile/")) {
483 if (Core\Session::get('visitor_home') != $_GET["zrl"]) {
484 Core\Session::set('my_url', $_GET['zrl']);
485 Core\Session::set('authenticated', 0);
488 Model\Profile::zrlInit($this);
490 // Someone came with an invalid parameter, maybe as a DDoS attempt
491 // We simply stop processing here
492 $this->logger->debug('Invalid ZRL parameter.', ['zrl' => $_GET['zrl']]);
493 throw new HTTPException\ForbiddenException();
498 if (!empty($_GET['owt']) && $this->mode->isNormal()) {
499 $token = $_GET['owt'];
500 Model\Profile::openWebAuthInit($token);
503 $auth->withSession($this);
505 if (empty($_SESSION['authenticated'])) {
506 header('X-Account-Management-Status: none');
509 $_SESSION['sysmsg'] = Core\Session::get('sysmsg', []);
510 $_SESSION['sysmsg_info'] = Core\Session::get('sysmsg_info', []);
511 $_SESSION['last_updated'] = Core\Session::get('last_updated', []);
514 * check_config() is responsible for running update scripts. These automatically
515 * update the DB schema whenever we push a new one out. It also checks to see if
516 * any addons have been added or removed and reacts accordingly.
519 // in install mode, any url loads install module
520 // but we need "view" module for stylesheet
521 if ($this->mode->isInstall() && $moduleName !== 'install') {
522 $this->baseURL->redirect('install');
523 } elseif (!$this->mode->isInstall() && !$this->mode->has(App\Mode::MAINTENANCEDISABLED) && $moduleName !== 'maintenance') {
524 $this->baseURL->redirect('maintenance');
527 Core\Update::check($this->getBasePath(), false, $this->mode);
528 Core\Addon::loadAddons();
529 Core\Hook::loadHooks();
532 // Compatibility with the Android Diaspora client
533 if ($moduleName == 'stream') {
534 $this->baseURL->redirect('network?order=post');
537 if ($moduleName == 'conversations') {
538 $this->baseURL->redirect('message');
541 if ($moduleName == 'commented') {
542 $this->baseURL->redirect('network?order=comment');
545 if ($moduleName == 'liked') {
546 $this->baseURL->redirect('network?order=comment');
549 if ($moduleName == 'activity') {
550 $this->baseURL->redirect('network?conv=1');
553 if (($moduleName == 'status_messages') && ($this->args->getCommand() == 'status_messages/new')) {
554 $this->baseURL->redirect('bookmarklet');
557 if (($moduleName == 'user') && ($this->args->getCommand() == 'user/edit')) {
558 $this->baseURL->redirect('settings');
561 if (($moduleName == 'tag_followings') && ($this->args->getCommand() == 'tag_followings/manage')) {
562 $this->baseURL->redirect('search');
565 // Initialize module that can set the current theme in the init() method, either directly or via App->profile_uid
566 $page['page_title'] = $moduleName;
568 // determine the module class and save it to the module instance
569 // @todo there's an implicit dependency due SESSION::start(), so it has to be called here (yet)
570 $module = $module->determineClass($this->args, $router, $this->config);
572 // Let the module run it's internal process (init, get, post, ...)
573 $module->run($this->l10n, $this->baseURL, $this->logger, $_SERVER, $_POST);
574 } catch (HTTPException $e) {
575 ModuleHTTPException::rawContent($e);
578 $page->run($this, $this->baseURL, $this->mode, $module, $this->l10n, $this->config, $pconfig);
582 * Automatically redirects to relative or absolute URL
583 * Should only be used if it isn't clear if the URL is either internal or external
585 * @param string $toUrl The target URL
587 * @throws HTTPException\InternalServerErrorException
589 public function redirect($toUrl)
591 if (!empty(parse_url($toUrl, PHP_URL_SCHEME))) {
592 Core\System::externalRedirect($toUrl);
594 $this->baseURL->redirect($toUrl);