3 * @copyright Copyright (C) 2010-2022, the Friendica project
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
25 use Friendica\App\Arguments;
26 use Friendica\App\BaseURL;
27 use Friendica\Capabilities\ICanCreateResponses;
28 use Friendica\Core\Config\Factory\Config;
29 use Friendica\Core\Session\Capability\IHandleUserSessions;
30 use Friendica\Model\User;
31 use Friendica\Module\Maintenance;
32 use Friendica\Security\Authentication;
33 use Friendica\Core\Config\ValueObject\Cache;
34 use Friendica\Core\Config\Capability\IManageConfigValues;
35 use Friendica\Core\PConfig\Capability\IManagePersonalConfigValues;
36 use Friendica\Core\L10n;
37 use Friendica\Core\System;
38 use Friendica\Core\Theme;
39 use Friendica\Database\Database;
40 use Friendica\Model\Contact;
41 use Friendica\Model\Profile;
42 use Friendica\Module\Special\HTTPException as ModuleHTTPException;
43 use Friendica\Network\HTTPException;
44 use Friendica\Util\DateTimeFormat;
45 use Friendica\Util\HTTPInputData;
46 use Friendica\Util\HTTPSignature;
47 use Friendica\Util\Profiler;
48 use Friendica\Util\Strings;
49 use Psr\Log\LoggerInterface;
52 * Our main application structure for the life of this page.
54 * Primarily deals with the URL that got us here
55 * and tries to make some sense of it, and
56 * stores our page contents and config storage
57 * and anything else that might need to be passed around
58 * before we spit the page out.
63 const PLATFORM = 'Friendica';
64 const CODENAME = 'Giant Rhubarb';
65 const VERSION = '2022.12-dev';
67 // Allow themes to control internal parameters
68 // by changing App values in theme.php
69 private $theme_info = [
72 'events_in_profile' => true
76 private $nickname = '';
77 private $timezone = '';
78 private $profile_owner = 0;
79 private $contact_id = 0;
83 * @var App\Mode The Mode of the Application
92 /** @var string The name of the current theme */
93 private $currentTheme;
94 /** @var string The name of the current mobile theme */
95 private $currentMobileTheme;
98 * @var IManageConfigValues The config
103 * @var LoggerInterface The logger
108 * @var Profiler The profiler of this app
113 * @var Database The Friendica database connection
118 * @var L10n The translator
128 * @var IManagePersonalConfigValues
133 * @var IHandleUserSessions
140 * @param int $user_id
143 public function setLoggedInUserId(int $user_id)
145 $this->user_id = $user_id;
151 * @param int $user_id
154 public function setLoggedInUserNickname(string $nickname)
156 $this->nickname = $nickname;
159 public function isLoggedIn(): bool
161 return $this->session->getLocalUserId() && $this->user_id && ($this->user_id == $this->session->getLocalUserId());
165 * Check if current user has admin role.
167 * @return bool true if user is an admin
170 public function isSiteAdmin(): bool
173 $this->session->getLocalUserId()
174 && $this->database->exists('user', [
175 'uid' => $this->getLoggedInUserId(),
176 'email' => User::getAdminEmailList()
182 * @return int User id
184 public function getLoggedInUserId(): int
186 return $this->user_id;
190 * Fetch the user nick name
191 * @return string User's nickname
193 public function getLoggedInUserNickname(): string
195 return $this->nickname;
199 * Set the profile owner ID
201 * @param int $owner_id
204 public function setProfileOwner(int $owner_id)
206 $this->profile_owner = $owner_id;
210 * Get the profile owner ID
214 public function getProfileOwner(): int
216 return $this->profile_owner;
222 * @param int $contact_id
225 public function setContactId(int $contact_id)
227 $this->contact_id = $contact_id;
235 public function getContactId(): int
237 return $this->contact_id;
243 * @param string $timezone A valid time zone identifier, see https://www.php.net/manual/en/timezones.php
246 public function setTimeZone(string $timezone)
248 $this->timezone = (new \DateTimeZone($timezone))->getName();
249 DateTimeFormat::setLocalTimeZone($this->timezone);
257 public function getTimeZone(): string
259 return $this->timezone;
263 * Set workerqueue information
265 * @param array $queue
268 public function setQueue(array $queue)
270 $this->queue = $queue;
274 * Fetch workerqueue information
276 * @return array Worker queue
278 public function getQueue(): array
280 return $this->queue ?? [];
284 * Fetch a specific workerqueue field
286 * @param string $index Work queue record to fetch
287 * @return mixed Work queue item or NULL if not found
289 public function getQueueValue(string $index)
291 return $this->queue[$index] ?? null;
294 public function setThemeInfoValue(string $index, $value)
296 $this->theme_info[$index] = $value;
299 public function getThemeInfo()
301 return $this->theme_info;
304 public function getThemeInfoValue(string $index, $default = null)
306 return $this->theme_info[$index] ?? $default;
310 * Returns the current config cache of this node
314 public function getConfigCache()
316 return $this->config->getCache();
320 * The basepath of this app
322 * @return string Base path from configuration
324 public function getBasePath(): string
326 // Don't use the basepath of the config table for basepath (it should always be the config-file one)
327 return $this->config->getCache()->get('system', 'basepath');
331 * @param Database $database The Friendica Database
332 * @param IManageConfigValues $config The Configuration
333 * @param App\Mode $mode The mode of this Friendica app
334 * @param BaseURL $baseURL The full base URL of this Friendica app
335 * @param LoggerInterface $logger The current app logger
336 * @param Profiler $profiler The profiler of this application
337 * @param L10n $l10n The translator instance
338 * @param App\Arguments $args The Friendica Arguments of the call
339 * @param IManagePersonalConfigValues $pConfig Personal configuration
340 * @param IHandleUserSessions $session The (User)Session handler
342 public function __construct(Database $database, IManageConfigValues $config, App\Mode $mode, BaseURL $baseURL, LoggerInterface $logger, Profiler $profiler, L10n $l10n, Arguments $args, IManagePersonalConfigValues $pConfig, IHandleUserSessions $session)
344 $this->database = $database;
345 $this->config = $config;
347 $this->baseURL = $baseURL;
348 $this->profiler = $profiler;
349 $this->logger = $logger;
352 $this->pConfig = $pConfig;
353 $this->session = $session;
359 * Load the whole app instance
361 public function load()
365 // Normally this constant is defined - but not if "pcntl" isn't installed
366 if (!defined('SIGTERM')) {
367 define('SIGTERM', 15);
370 // Ensure that all "strtotime" operations do run timezone independent
371 date_default_timezone_set('UTC');
373 // This has to be quite large to deal with embedded private photos
374 ini_set('pcre.backtrack_limit', 500000);
377 get_include_path() . PATH_SEPARATOR
378 . $this->getBasePath() . DIRECTORY_SEPARATOR . 'include' . PATH_SEPARATOR
379 . $this->getBasePath() . DIRECTORY_SEPARATOR . 'library' . PATH_SEPARATOR
380 . $this->getBasePath());
382 $this->profiler->reset();
384 if ($this->mode->has(App\Mode::DBAVAILABLE)) {
385 $this->profiler->update($this->config);
387 Core\Hook::loadHooks();
388 $loader = (new Config())->createConfigFileLoader($this->getBasePath(), $_SERVER);
389 Core\Hook::callAll('load_config', $loader);
392 $this->loadDefaultTimezone();
393 // Register template engines
394 Core\Renderer::registerTemplateEngine('Friendica\Render\FriendicaSmartyEngine');
398 * Loads the default timezone
400 * Include support for legacy $default_timezone
402 * @global string $default_timezone
404 private function loadDefaultTimezone()
406 if ($this->config->get('system', 'default_timezone')) {
407 $timezone = $this->config->get('system', 'default_timezone', 'UTC');
409 global $default_timezone;
410 $timezone = $default_timezone ?? '' ?: 'UTC';
413 $this->setTimeZone($timezone);
417 * Returns the current theme name. May be overriden by the mobile theme name.
419 * @return string Current theme name or empty string in installation phase
422 public function getCurrentTheme(): string
424 if ($this->mode->isInstall()) {
428 // Specific mobile theme override
429 if (($this->mode->isMobile() || $this->mode->isTablet()) && $this->session->get('show-mobile', true)) {
430 $user_mobile_theme = $this->getCurrentMobileTheme();
432 // --- means same mobile theme as desktop
433 if (!empty($user_mobile_theme) && $user_mobile_theme !== '---') {
434 return $user_mobile_theme;
438 if (!$this->currentTheme) {
439 $this->computeCurrentTheme();
442 return $this->currentTheme;
446 * Returns the current mobile theme name.
448 * @return string Mobile theme name or empty string if installer
451 public function getCurrentMobileTheme(): string
453 if ($this->mode->isInstall()) {
457 if (is_null($this->currentMobileTheme)) {
458 $this->computeCurrentMobileTheme();
461 return $this->currentMobileTheme;
465 * Setter for current theme name
467 * @param string $theme Name of current theme
469 public function setCurrentTheme(string $theme)
471 $this->currentTheme = $theme;
475 * Setter for current mobile theme name
477 * @param string $theme Name of current mobile theme
479 public function setCurrentMobileTheme(string $theme)
481 $this->currentMobileTheme = $theme;
485 * Computes the current theme name based on the node settings, the page owner settings and the user settings
489 private function computeCurrentTheme()
491 $system_theme = $this->config->get('system', 'theme');
492 if (!$system_theme) {
493 throw new Exception($this->l10n->t('No system theme config value set.'));
497 $this->setCurrentTheme($system_theme);
500 // Find the theme that belongs to the user whose stuff we are looking at
501 if (!empty($this->profile_owner) && ($this->profile_owner != $this->session->getLocalUserId())) {
502 // Allow folks to override user themes and always use their own on their own site.
503 // This works only if the user is on the same server
504 $user = $this->database->selectFirst('user', ['theme'], ['uid' => $this->profile_owner]);
505 if ($this->database->isResult($user) && !$this->session->getLocalUserId()) {
506 $page_theme = $user['theme'];
510 $theme_name = $page_theme ?: $this->session->get('theme', $system_theme);
512 $theme_name = Strings::sanitizeFilePathItem($theme_name);
514 && in_array($theme_name, Theme::getAllowedList())
515 && (file_exists('view/theme/' . $theme_name . '/style.css')
516 || file_exists('view/theme/' . $theme_name . '/style.php'))
518 $this->setCurrentTheme($theme_name);
523 * Computes the current mobile theme name based on the node settings, the page owner settings and the user settings
525 private function computeCurrentMobileTheme()
527 $system_mobile_theme = $this->config->get('system', 'mobile-theme', '');
530 $this->setCurrentMobileTheme($system_mobile_theme);
532 $page_mobile_theme = null;
533 // Find the theme that belongs to the user whose stuff we are looking at
534 if (!empty($this->profile_owner) && ($this->profile_owner != $this->session->getLocalUserId())) {
535 // Allow folks to override user themes and always use their own on their own site.
536 // This works only if the user is on the same server
537 if (!$this->session->getLocalUserId()) {
538 $page_mobile_theme = $this->pConfig->get($this->profile_owner, 'system', 'mobile-theme');
542 $mobile_theme_name = $page_mobile_theme ?: $this->session->get('mobile-theme', $system_mobile_theme);
544 $mobile_theme_name = Strings::sanitizeFilePathItem($mobile_theme_name);
545 if ($mobile_theme_name == '---'
547 in_array($mobile_theme_name, Theme::getAllowedList())
548 && (file_exists('view/theme/' . $mobile_theme_name . '/style.css')
549 || file_exists('view/theme/' . $mobile_theme_name . '/style.php'))
551 $this->setCurrentMobileTheme($mobile_theme_name);
556 * Provide a sane default if nothing is chosen or the specified theme does not exist.
558 * @return string Current theme's stylsheet path
561 public function getCurrentThemeStylesheetPath(): string
563 return Core\Theme::getStylesheetPath($this->getCurrentTheme());
567 * Sets the base url for use in cmdline programs which don't have
570 public function checkURL()
572 $url = $this->config->get('system', 'url');
574 // if the url isn't set or the stored url is radically different
575 // than the currently visited url, store the current value accordingly.
576 // "Radically different" ignores common variations such as http vs https
577 // and www.example.com vs example.com.
578 // We will only change the url to an ip address if there is no existing setting
580 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()))) {
581 $this->config->set('system', 'url', $this->baseURL->get());
586 * Frontend App script
588 * The App object behaves like a container and a dispatcher at the same time, including a representation of the
589 * request and a representation of the response.
591 * This probably should change to limit the size of this monster method.
593 * @param App\Router $router
594 * @param IManagePersonalConfigValues $pconfig
595 * @param Authentication $auth The Authentication backend of the node
596 * @param App\Page $page The Friendica page printing container
597 * @param HTTPInputData $httpInput A library for processing PHP input streams
598 * @param float $start_time The start time of the overall script execution
600 * @throws HTTPException\InternalServerErrorException
601 * @throws \ImagickException
603 public function runFrontend(App\Router $router, IManagePersonalConfigValues $pconfig, Authentication $auth, App\Page $page, HTTPInputData $httpInput, float $start_time)
605 $this->profiler->set($start_time, 'start');
606 $this->profiler->set(microtime(true), 'classinit');
608 $moduleName = $this->args->getModuleName();
609 $page->setLogging($this->args->getMethod(), $this->args->getModuleName(), $this->args->getCommand());
612 // Missing DB connection: ERROR
613 if ($this->mode->has(App\Mode::LOCALCONFIGPRESENT) && !$this->mode->has(App\Mode::DBAVAILABLE)) {
614 throw new HTTPException\InternalServerErrorException($this->l10n->t('Apologies but the website is unavailable at the moment.'));
617 if (!$this->mode->isInstall()) {
618 // Force SSL redirection
619 if ($this->baseURL->checkRedirectHttps()) {
620 System::externalRedirect($this->baseURL->get() . '/' . $this->args->getQueryString());
623 Core\Hook::callAll('init_1');
626 if ($this->mode->isNormal() && !$this->mode->isBackend()) {
627 $requester = HTTPSignature::getSigner('', $_SERVER);
628 if (!empty($requester)) {
629 Profile::addVisitorCookieForHandle($requester);
634 if (!empty($_GET['zrl']) && $this->mode->isNormal() && !$this->mode->isBackend() && !$this->session->getLocalUserId()) {
635 // Only continue when the given profile link seems valid
636 // Valid profile links contain a path with "/profile/" and no query parameters
637 if ((parse_url($_GET['zrl'], PHP_URL_QUERY) == '') &&
638 strstr(parse_url($_GET['zrl'], PHP_URL_PATH), '/profile/')) {
639 if ($this->session->get('visitor_home') != $_GET['zrl']) {
640 $this->session->set('my_url', $_GET['zrl']);
641 $this->session->set('authenticated', 0);
643 $remote_contact = Contact::getByURL($_GET['zrl'], false, ['subscribe']);
644 if (!empty($remote_contact['subscribe'])) {
645 $_SESSION['remote_comment'] = $remote_contact['subscribe'];
649 Model\Profile::zrlInit($this);
651 // Someone came with an invalid parameter, maybe as a DDoS attempt
652 // We simply stop processing here
653 $this->logger->debug('Invalid ZRL parameter.', ['zrl' => $_GET['zrl']]);
654 throw new HTTPException\ForbiddenException();
658 if (!empty($_GET['owt']) && $this->mode->isNormal()) {
659 $token = $_GET['owt'];
660 Model\Profile::openWebAuthInit($token);
663 if (!$this->mode->isBackend()) {
664 $auth->withSession($this);
667 if (empty($_SESSION['authenticated'])) {
668 header('X-Account-Management-Status: none');
672 * check_config() is responsible for running update scripts. These automatically
673 * update the DB schema whenever we push a new one out. It also checks to see if
674 * any addons have been added or removed and reacts accordingly.
677 // in install mode, any url loads install module
678 // but we need "view" module for stylesheet
679 if ($this->mode->isInstall() && $moduleName !== 'install') {
680 $this->baseURL->redirect('install');
683 Core\Update::check($this->getBasePath(), false, $this->mode);
684 Core\Addon::loadAddons();
685 Core\Hook::loadHooks();
688 // Compatibility with the Android Diaspora client
689 if ($moduleName == 'stream') {
690 $this->baseURL->redirect('network?order=post');
693 if ($moduleName == 'conversations') {
694 $this->baseURL->redirect('message');
697 if ($moduleName == 'commented') {
698 $this->baseURL->redirect('network?order=comment');
701 if ($moduleName == 'liked') {
702 $this->baseURL->redirect('network?order=comment');
705 if ($moduleName == 'activity') {
706 $this->baseURL->redirect('network?conv=1');
709 if (($moduleName == 'status_messages') && ($this->args->getCommand() == 'status_messages/new')) {
710 $this->baseURL->redirect('bookmarklet');
713 if (($moduleName == 'user') && ($this->args->getCommand() == 'user/edit')) {
714 $this->baseURL->redirect('settings');
717 if (($moduleName == 'tag_followings') && ($this->args->getCommand() == 'tag_followings/manage')) {
718 $this->baseURL->redirect('search');
721 // Initialize module that can set the current theme in the init() method, either directly or via App->setProfileOwner
722 $page['page_title'] = $moduleName;
724 // The "view" module is required to show the theme CSS
725 if (!$this->mode->isInstall() && !$this->mode->has(App\Mode::MAINTENANCEDISABLED) && $moduleName !== 'view') {
726 $module = $router->getModule(Maintenance::class);
728 // determine the module class and save it to the module instance
729 // @todo there's an implicit dependency due SESSION::start(), so it has to be called here (yet)
730 $module = $router->getModule();
733 // Processes data from GET requests
734 $httpinput = $httpInput->process();
735 $input = array_merge($httpinput['variables'], $httpinput['files'], $request ?? $_REQUEST);
737 // Let the module run it's internal process (init, get, post, ...)
738 $timestamp = microtime(true);
739 $response = $module->run($input);
740 $this->profiler->set(microtime(true) - $timestamp, 'content');
741 if ($response->getHeaderLine(ICanCreateResponses::X_HEADER) === ICanCreateResponses::TYPE_HTML) {
742 $page->run($this, $this->baseURL, $this->args, $this->mode, $response, $this->l10n, $this->profiler, $this->config, $pconfig, $this->session->getLocalUserId());
744 $page->exit($response);
746 } catch (HTTPException $e) {
747 (new ModuleHTTPException())->rawContent($e);
749 $page->logRuntime($this->config, 'runFrontend');
753 * Automatically redirects to relative or absolute URL
754 * Should only be used if it isn't clear if the URL is either internal or external
756 * @param string $toUrl The target URL
758 * @throws HTTPException\InternalServerErrorException
760 public function redirect(string $toUrl)
762 if (!empty(parse_url($toUrl, PHP_URL_SCHEME))) {
763 Core\System::externalRedirect($toUrl);
765 $this->baseURL->redirect($toUrl);