8 use Friendica\App\Arguments;
9 use Friendica\App\BaseURL;
10 use Friendica\App\Authentication;
11 use Friendica\Core\Config\Cache\ConfigCache;
12 use Friendica\Core\Config\IConfiguration;
13 use Friendica\Core\Config\IPConfiguration;
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\Special\HTTPException as ModuleHTTPException;
20 use Friendica\Network\HTTPException;
21 use Friendica\Util\ConfigFileLoader;
22 use Friendica\Util\HTTPSignature;
23 use Friendica\Util\Profiler;
24 use Friendica\Util\Strings;
25 use Psr\Log\LoggerInterface;
31 * @brief Our main application structure for the life of this page.
33 * Primarily deals with the URL that got us here
34 * and tries to make some sense of it, and
35 * stores our page contents and config storage
36 * and anything else that might need to be passed around
37 * before we spit the page out.
51 /** @deprecated 2019.09 - use App\Arguments->getArgv() or Arguments->get() */
53 /** @deprecated 2019.09 - use App\Arguments->getArgc() */
56 public $interactive = true;
58 public $theme_info = [];
60 // Allow themes to control internal parameters
61 // by changing App values in theme.php
63 public $sourcename = '';
64 public $videowidth = 425;
65 public $videoheight = 350;
66 public $force_max_items = 0;
67 public $theme_events_in_profile = true;
71 * @var App\Mode The Mode of the Application
80 /** @var string The name of the current theme */
81 private $currentTheme;
82 /** @var string The name of the current mobile theme */
83 private $currentMobileTheme;
86 * @var IConfiguration The config
91 * @var LoggerInterface The logger
96 * @var Profiler The profiler of this app
101 * @var Database The Friendica database connection
106 * @var L10n The translator
116 * @var Core\Process The process methods
121 * @var IPConfiguration
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 IConfiguration $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
156 * @param IPConfiguration $pConfig Personal configuration
158 public function __construct(Database $database, IConfiguration $config, App\Mode $mode, BaseURL $baseURL, LoggerInterface $logger, Profiler $profiler, L10n $l10n, Arguments $args, Core\Process $process, IPConfiguration $pConfig)
160 $this->database = $database;
161 $this->config = $config;
163 $this->baseURL = $baseURL;
164 $this->profiler = $profiler;
165 $this->logger = $logger;
168 $this->process = $process;
169 $this->pConfig = $pConfig;
171 $this->argv = $args->getArgv();
172 $this->argc = $args->getArgc();
178 * Load the whole app instance
180 public function load()
184 // This has to be quite large to deal with embedded private photos
185 ini_set('pcre.backtrack_limit', 500000);
188 get_include_path() . PATH_SEPARATOR
189 . $this->getBasePath() . DIRECTORY_SEPARATOR . 'include' . PATH_SEPARATOR
190 . $this->getBasePath() . DIRECTORY_SEPARATOR . 'library' . PATH_SEPARATOR
191 . $this->getBasePath());
193 $this->profiler->reset();
195 if ($this->mode->has(App\Mode::DBAVAILABLE)) {
196 $this->profiler->update($this->config);
198 Core\Hook::loadHooks();
199 $loader = new ConfigFileLoader($this->getBasePath());
200 Core\Hook::callAll('load_config', $loader);
203 $this->loadDefaultTimezone();
204 // Register template engines
205 Core\Renderer::registerTemplateEngine('Friendica\Render\FriendicaSmartyEngine');
209 * Loads the default timezone
211 * Include support for legacy $default_timezone
213 * @global string $default_timezone
215 private function loadDefaultTimezone()
217 if ($this->config->get('system', 'default_timezone')) {
218 $this->timezone = $this->config->get('system', 'default_timezone');
220 global $default_timezone;
221 $this->timezone = !empty($default_timezone) ? $default_timezone : 'UTC';
224 if ($this->timezone) {
225 date_default_timezone_set($this->timezone);
230 * Returns the current UserAgent as a String
232 * @return string the UserAgent as a String
233 * @throws HTTPException\InternalServerErrorException
235 public function getUserAgent()
238 FRIENDICA_PLATFORM . " '" .
239 FRIENDICA_CODENAME . "' " .
240 FRIENDICA_VERSION . '-' .
241 DB_UPDATE_VERSION . '; ' .
242 $this->baseURL->get();
246 * Generates the site's default sender email address
249 * @throws HTTPException\InternalServerErrorException
251 public function getSenderEmailAddress()
253 $sender_email = $this->config->get('config', 'sender_email');
254 if (empty($sender_email)) {
255 $hostname = $this->baseURL->getHostname();
256 if (strpos($hostname, ':')) {
257 $hostname = substr($hostname, 0, strpos($hostname, ':'));
260 $sender_email = 'noreply@' . $hostname;
263 return $sender_email;
267 * Returns the current theme name. May be overriden by the mobile theme name.
272 public function getCurrentTheme()
274 if ($this->mode->isInstall()) {
278 // Specific mobile theme override
279 if (($this->mode->isMobile() || $this->mode->isTablet()) && Core\Session::get('show-mobile', true)) {
280 $user_mobile_theme = $this->getCurrentMobileTheme();
282 // --- means same mobile theme as desktop
283 if (!empty($user_mobile_theme) && $user_mobile_theme !== '---') {
284 return $user_mobile_theme;
288 if (!$this->currentTheme) {
289 $this->computeCurrentTheme();
292 return $this->currentTheme;
296 * Returns the current mobile theme name.
301 public function getCurrentMobileTheme()
303 if ($this->mode->isInstall()) {
307 if (is_null($this->currentMobileTheme)) {
308 $this->computeCurrentMobileTheme();
311 return $this->currentMobileTheme;
314 public function setCurrentTheme($theme)
316 $this->currentTheme = $theme;
319 public function setCurrentMobileTheme($theme)
321 $this->currentMobileTheme = $theme;
325 * Computes the current theme name based on the node settings, the page owner settings and the user settings
329 private function computeCurrentTheme()
331 $system_theme = $this->config->get('system', 'theme');
332 if (!$system_theme) {
333 throw new Exception($this->l10n->t('No system theme config value set.'));
337 $this->setCurrentTheme($system_theme);
340 // Find the theme that belongs to the user whose stuff we are looking at
341 if ($this->profile_uid && ($this->profile_uid != local_user())) {
342 // Allow folks to override user themes and always use their own on their own site.
343 // This works only if the user is on the same server
344 $user = $this->database->selectFirst('user', ['theme'], ['uid' => $this->profile_uid]);
345 if ($this->database->isResult($user) && !$this->pConfig->get(local_user(), 'system', 'always_my_theme')) {
346 $page_theme = $user['theme'];
350 $theme_name = $page_theme ?: Core\Session::get('theme', $system_theme);
352 $theme_name = Strings::sanitizeFilePathItem($theme_name);
354 && in_array($theme_name, Theme::getAllowedList())
355 && (file_exists('view/theme/' . $theme_name . '/style.css')
356 || file_exists('view/theme/' . $theme_name . '/style.php'))
358 $this->setCurrentTheme($theme_name);
363 * Computes the current mobile theme name based on the node settings, the page owner settings and the user settings
365 private function computeCurrentMobileTheme()
367 $system_mobile_theme = $this->config->get('system', 'mobile-theme', '');
370 $this->setCurrentMobileTheme($system_mobile_theme);
372 $page_mobile_theme = null;
373 // Find the theme that belongs to the user whose stuff we are looking at
374 if ($this->profile_uid && ($this->profile_uid != local_user())) {
375 // Allow folks to override user themes and always use their own on their own site.
376 // This works only if the user is on the same server
377 if (!$this->pConfig->get(local_user(), 'system', 'always_my_theme')) {
378 $page_mobile_theme = $this->pConfig->get($this->profile_uid, 'system', 'mobile-theme');
382 $mobile_theme_name = $page_mobile_theme ?: Core\Session::get('mobile-theme', $system_mobile_theme);
384 $mobile_theme_name = Strings::sanitizeFilePathItem($mobile_theme_name);
385 if ($mobile_theme_name == '---'
387 in_array($mobile_theme_name, Theme::getAllowedList())
388 && (file_exists('view/theme/' . $mobile_theme_name . '/style.css')
389 || file_exists('view/theme/' . $mobile_theme_name . '/style.php'))
391 $this->setCurrentMobileTheme($mobile_theme_name);
396 * @brief Return full URL to theme which is currently in effect.
398 * Provide a sane default if nothing is chosen or the specified theme does not exist.
403 public function getCurrentThemeStylesheetPath()
405 return Core\Theme::getStylesheetPath($this->getCurrentTheme());
409 * Sets the base url for use in cmdline programs which don't have
412 public function checkURL()
414 $url = $this->config->get('system', 'url');
416 // if the url isn't set or the stored url is radically different
417 // than the currently visited url, store the current value accordingly.
418 // "Radically different" ignores common variations such as http vs https
419 // and www.example.com vs example.com.
420 // We will only change the url to an ip address if there is no existing setting
422 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()))) {
423 $this->config->set('system', 'url', $this->baseURL->get());
428 * Frontend App script
430 * The App object behaves like a container and a dispatcher at the same time, including a representation of the
431 * request and a representation of the response.
433 * This probably should change to limit the size of this monster method.
435 * @param App\Module $module The determined module
436 * @param App\Router $router
437 * @param IPConfiguration $pconfig
438 * @param Authentication $auth The Authentication backend of the node
439 * @param App\Page $page The Friendica page printing container
440 * @throws HTTPException\InternalServerErrorException
441 * @throws \ImagickException
443 public function runFrontend(App\Module $module, App\Router $router, IPConfiguration $pconfig, Authentication $auth, App\Page $page)
445 $moduleName = $module->getName();
448 // Missing DB connection: ERROR
449 if ($this->mode->has(App\Mode::LOCALCONFIGPRESENT) && !$this->mode->has(App\Mode::DBAVAILABLE)) {
450 throw new HTTPException\InternalServerErrorException('Apologies but the website is unavailable at the moment.');
453 // Max Load Average reached: ERROR
454 if ($this->process->isMaxProcessesReached() || $this->process->isMaxLoadReached()) {
455 header('Retry-After: 120');
456 header('Refresh: 120; url=' . $this->baseURL->get() . "/" . $this->args->getQueryString());
458 throw new HTTPException\ServiceUnavailableException('The node is currently overloaded. Please try again later.');
461 if (!$this->mode->isInstall()) {
462 // Force SSL redirection
463 if ($this->baseURL->checkRedirectHttps()) {
464 System::externalRedirect($this->baseURL->get() . '/' . $this->args->getQueryString());
467 Core\Hook::callAll('init_1');
470 // Exclude the backend processes from the session management
471 if ($this->mode->isBackend()) {
472 Core\Worker::executeIfIdle();
475 if ($this->mode->isNormal()) {
476 $requester = HTTPSignature::getSigner('', $_SERVER);
477 if (!empty($requester)) {
478 Profile::addVisitorCookieForHandle($requester);
483 if (!empty($_GET['zrl']) && $this->mode->isNormal()) {
485 // Only continue when the given profile link seems valid
486 // Valid profile links contain a path with "/profile/" and no query parameters
487 if ((parse_url($_GET['zrl'], PHP_URL_QUERY) == "") &&
488 strstr(parse_url($_GET['zrl'], PHP_URL_PATH), "/profile/")) {
489 if (Core\Session::get('visitor_home') != $_GET["zrl"]) {
490 Core\Session::set('my_url', $_GET['zrl']);
491 Core\Session::set('authenticated', 0);
494 Model\Profile::zrlInit($this);
496 // Someone came with an invalid parameter, maybe as a DDoS attempt
497 // We simply stop processing here
498 $this->logger->debug('Invalid ZRL parameter.', ['zrl' => $_GET['zrl']]);
499 throw new HTTPException\ForbiddenException();
504 if (!empty($_GET['owt']) && $this->mode->isNormal()) {
505 $token = $_GET['owt'];
506 Model\Profile::openWebAuthInit($token);
509 $auth->withSession($this);
511 if (empty($_SESSION['authenticated'])) {
512 header('X-Account-Management-Status: none');
515 $_SESSION['sysmsg'] = Core\Session::get('sysmsg', []);
516 $_SESSION['sysmsg_info'] = Core\Session::get('sysmsg_info', []);
517 $_SESSION['last_updated'] = Core\Session::get('last_updated', []);
520 * check_config() is responsible for running update scripts. These automatically
521 * update the DB schema whenever we push a new one out. It also checks to see if
522 * any addons have been added or removed and reacts accordingly.
525 // in install mode, any url loads install module
526 // but we need "view" module for stylesheet
527 if ($this->mode->isInstall() && $moduleName !== 'install') {
528 $this->baseURL->redirect('install');
529 } elseif (!$this->mode->isInstall() && !$this->mode->has(App\Mode::MAINTENANCEDISABLED) && $moduleName !== 'maintenance') {
530 $this->baseURL->redirect('maintenance');
533 Core\Update::check($this->getBasePath(), false, $this->mode);
534 Core\Addon::loadAddons();
535 Core\Hook::loadHooks();
538 // Compatibility with the Android Diaspora client
539 if ($moduleName == 'stream') {
540 $this->baseURL->redirect('network?order=post');
543 if ($moduleName == 'conversations') {
544 $this->baseURL->redirect('message');
547 if ($moduleName == 'commented') {
548 $this->baseURL->redirect('network?order=comment');
551 if ($moduleName == 'liked') {
552 $this->baseURL->redirect('network?order=comment');
555 if ($moduleName == 'activity') {
556 $this->baseURL->redirect('network?conv=1');
559 if (($moduleName == 'status_messages') && ($this->args->getCommand() == 'status_messages/new')) {
560 $this->baseURL->redirect('bookmarklet');
563 if (($moduleName == 'user') && ($this->args->getCommand() == 'user/edit')) {
564 $this->baseURL->redirect('settings');
567 if (($moduleName == 'tag_followings') && ($this->args->getCommand() == 'tag_followings/manage')) {
568 $this->baseURL->redirect('search');
571 // Initialize module that can set the current theme in the init() method, either directly or via App->profile_uid
572 $page['page_title'] = $moduleName;
574 // determine the module class and save it to the module instance
575 // @todo there's an implicit dependency due SESSION::start(), so it has to be called here (yet)
576 $module = $module->determineClass($this->args, $router, $this->config);
578 // Let the module run it's internal process (init, get, post, ...)
579 $module->run($this->l10n, $this->baseURL, $this->logger, $_SERVER, $_POST);
580 } catch (HTTPException $e) {
581 ModuleHTTPException::rawContent($e);
584 $page->run($this, $this->baseURL, $this->mode, $module, $this->l10n, $this->config, $pconfig);
588 * Automatically redirects to relative or absolute URL
589 * Should only be used if it isn't clear if the URL is either internal or external
591 * @param string $toUrl The target URL
593 * @throws HTTPException\InternalServerErrorException
595 public function redirect($toUrl)
597 if (!empty(parse_url($toUrl, PHP_URL_SCHEME))) {
598 Core\System::externalRedirect($toUrl);
600 $this->baseURL->redirect($toUrl);