7 use Detection\MobileDetect;
9 use Friendica\App\Arguments;
10 use Friendica\App\BaseURL;
11 use Friendica\App\Page;
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\Login;
21 use Friendica\Module\Special\HTTPException as ModuleHTTPException;
22 use Friendica\Network\HTTPException;
23 use Friendica\Util\ConfigFileLoader;
24 use Friendica\Util\HTTPSignature;
25 use Friendica\Util\Profiler;
26 use Friendica\Util\Strings;
27 use Psr\Log\LoggerInterface;
33 * @brief Our main application structure for the life of this page.
35 * Primarily deals with the URL that got us here
36 * and tries to make some sense of it, and
37 * stores our page contents and config storage
38 * and anything else that might need to be passed around
39 * before we spit the page out.
44 /** @deprecated 2019.09 - use App\Arguments->getQueryString() */
47 * @var Page The current page environment
59 /** @deprecated 2019.09 - use App\Arguments->getCommand() */
61 /** @deprecated 2019.09 - use App\Arguments->getArgv() or Arguments->get() */
63 /** @deprecated 2019.09 - use App\Arguments->getArgc() */
65 /** @deprecated 2019.09 - Use App\Module->getName() instead */
68 public $interactive = true;
72 public $theme_info = [];
74 // Allow themes to control internal parameters
75 // by changing App values in theme.php
77 public $sourcename = '';
78 public $videowidth = 425;
79 public $videoheight = 350;
80 public $force_max_items = 0;
81 public $theme_events_in_profile = true;
85 * @var App\Mode The Mode of the Application
100 * @var string The name of the current theme
102 private $currentTheme;
105 * @var bool check if request was an AJAX (xmlhttprequest) request
112 public $mobileDetect;
115 * @var Configuration The config
120 * @var LoggerInterface The logger
125 * @var Profiler The profiler of this app
130 * @var Database The Friendica database connection
135 * @var L10n The translator
145 * Returns the current config cache of this node
147 * @return ConfigCache
149 public function getConfigCache()
151 return $this->config->getCache();
155 * Returns the current config of this node
157 * @return Configuration
159 public function getConfig()
161 return $this->config;
165 * The basepath of this app
169 public function getBasePath()
171 // Don't use the basepath of the config table for basepath (it should always be the config-file one)
172 return $this->config->getCache()->get('system', 'basepath');
176 * The Logger of this app
178 * @return LoggerInterface
180 public function getLogger()
182 return $this->logger;
186 * The profiler of this app
190 public function getProfiler()
192 return $this->profiler;
196 * Returns the Mode of the Application
198 * @return App\Mode The Application Mode
200 public function getMode()
206 * Returns the Database of the Application
210 public function getDBA()
212 return $this->database;
216 * @deprecated 2019.09 - use Page->registerStylesheet instead
217 * @see Page::registerStylesheet()
219 public function registerStylesheet($path)
221 $this->page->registerStylesheet($path);
225 * @deprecated 2019.09 - use Page->registerFooterScript instead
226 * @see Page::registerFooterScript()
228 public function registerFooterScript($path)
230 $this->page->registerFooterScript($path);
234 * @param Database $database The Friendica Database
235 * @param Configuration $config The Configuration
236 * @param App\Mode $mode The mode of this Friendica app
237 * @param App\Router $router The router of this Friendica app
238 * @param BaseURL $baseURL The full base URL of this Friendica app
239 * @param LoggerInterface $logger The current app logger
240 * @param Profiler $profiler The profiler of this application
241 * @param L10n $l10n The translator instance
242 * @param App\Arguments $args The Friendica Arguments of the call
243 * @param MobileDetect $mobileDetect A mobile detection class
245 public function __construct(Database $database, Configuration $config, App\Mode $mode, App\Router $router, BaseURL $baseURL, LoggerInterface $logger, Profiler $profiler, L10n $l10n, Arguments $args, App\Module $module, App\Page $page, MobileDetect $mobileDetect)
247 $this->database = $database;
248 $this->config = $config;
250 $this->router = $router;
251 $this->baseURL = $baseURL;
252 $this->profiler = $profiler;
253 $this->logger = $logger;
256 $this->mobileDetect = $mobileDetect;
258 $this->cmd = $args->getCommand();
259 $this->argv = $args->getArgv();
260 $this->argc = $args->getArgc();
261 $this->query_string = $args->getQueryString();
262 $this->module = $module->getName();
265 $this->is_mobile = $mobileDetect->isMobile();
266 $this->is_tablet = $mobileDetect->isTablet();
268 $this->isAjax = strtolower(defaults($_SERVER, 'HTTP_X_REQUESTED_WITH', '')) == 'xmlhttprequest';
274 * Load the whole app instance
276 public function load()
280 // This has to be quite large to deal with embedded private photos
281 ini_set('pcre.backtrack_limit', 500000);
284 get_include_path() . PATH_SEPARATOR
285 . $this->getBasePath() . DIRECTORY_SEPARATOR . 'include' . PATH_SEPARATOR
286 . $this->getBasePath() . DIRECTORY_SEPARATOR . 'library' . PATH_SEPARATOR
287 . $this->getBasePath());
289 $this->profiler->reset();
291 if ($this->mode->has(App\Mode::DBAVAILABLE)) {
292 $this->profiler->update($this->config);
294 Core\Hook::loadHooks();
295 $loader = new ConfigFileLoader($this->getBasePath());
296 Core\Hook::callAll('load_config', $loader);
299 $this->loadDefaultTimezone();
300 // Register template engines
301 Core\Renderer::registerTemplateEngine('Friendica\Render\FriendicaSmartyEngine');
305 * Loads the default timezone
307 * Include support for legacy $default_timezone
309 * @global string $default_timezone
311 private function loadDefaultTimezone()
313 if ($this->config->get('system', 'default_timezone')) {
314 $this->timezone = $this->config->get('system', 'default_timezone');
316 global $default_timezone;
317 $this->timezone = !empty($default_timezone) ? $default_timezone : 'UTC';
320 if ($this->timezone) {
321 date_default_timezone_set($this->timezone);
326 * Returns the scheme of the current call
330 * @deprecated 2019.06 - use BaseURL->getScheme() instead
332 public function getScheme()
334 return $this->baseURL->getScheme();
338 * Retrieves the Friendica instance base URL
340 * @param bool $ssl Whether to append http or https under BaseURL::SSL_POLICY_SELFSIGN
342 * @return string Friendica server base URL
344 * @deprecated 2019.09 - use BaseUrl->get($ssl) instead
346 public function getBaseURL($ssl = false)
348 return $this->baseURL->get($ssl);
352 * @brief Initializes the baseurl components
354 * Clears the baseurl cache to prevent inconsistencies
358 * @deprecated 2019.06 - use BaseURL->saveByURL($url) instead
360 public function setBaseURL($url)
362 $this->baseURL->saveByURL($url);
366 * Returns the current hostname
370 * @deprecated 2019.06 - use BaseURL->getHostname() instead
372 public function getHostName()
374 return $this->baseURL->getHostname();
378 * Returns the sub-path of the full URL
382 * @deprecated 2019.06 - use BaseURL->getUrlPath() instead
384 public function getURLPath()
386 return $this->baseURL->getUrlPath();
390 * @brief Removes the base url from an url. This avoids some mixed content problems.
392 * @param string $origURL
394 * @return string The cleaned url
396 * @deprecated 2019.09 - Use BaseURL->remove() instead
397 * @see BaseURL::remove()
399 public function removeBaseURL($origURL)
401 return $this->baseURL->remove($origURL);
405 * Returns the current UserAgent as a String
407 * @return string the UserAgent as a String
408 * @throws HTTPException\InternalServerErrorException
410 public function getUserAgent()
413 FRIENDICA_PLATFORM . " '" .
414 FRIENDICA_CODENAME . "' " .
415 FRIENDICA_VERSION . '-' .
416 DB_UPDATE_VERSION . '; ' .
421 * Returns true, if the call is from a backend node (f.e. from a worker)
423 * @return bool Is it a known backend?
425 * @deprecated 2019.09 - use App\Mode->isBackend() instead
426 * @see App\Mode::isBackend()
427 * Use BaseObject::getClass(App\Mode::class) to get the global instance of Mode
429 public function isBackend()
431 return $this->mode->isBackend();
435 * @brief Checks if the maximum number of database processes is reached
437 * @return bool Is the limit reached?
439 public function isMaxProcessesReached()
441 // Deactivated, needs more investigating if this check really makes sense
445 * Commented out to suppress static analyzer issues
447 if ($this->is_backend()) {
448 $process = 'backend';
449 $max_processes = $this->config->get('system', 'max_processes_backend');
450 if (intval($max_processes) == 0) {
454 $process = 'frontend';
455 $max_processes = $this->config->get('system', 'max_processes_frontend');
456 if (intval($max_processes) == 0) {
461 $processlist = DBA::processlist();
462 if ($processlist['list'] != '') {
463 $this->logger->debug('Processcheck: Processes: ' . $processlist['amount'] . ' - Processlist: ' . $processlist['list']);
465 if ($processlist['amount'] > $max_processes) {
466 $this->logger->debug('Processcheck: Maximum number of processes for ' . $process . ' tasks (' . $max_processes . ') reached.');
475 * @brief Checks if the minimal memory is reached
477 * @return bool Is the memory limit reached?
478 * @throws HTTPException\InternalServerErrorException
480 public function isMinMemoryReached()
482 $min_memory = $this->config->get('system', 'min_memory', 0);
483 if ($min_memory == 0) {
487 if (!is_readable('/proc/meminfo')) {
491 $memdata = explode("\n", file_get_contents('/proc/meminfo'));
494 foreach ($memdata as $line) {
495 $data = explode(':', $line);
496 if (count($data) != 2) {
499 list($key, $val) = $data;
500 $meminfo[$key] = (int)trim(str_replace('kB', '', $val));
501 $meminfo[$key] = (int)($meminfo[$key] / 1024);
504 if (!isset($meminfo['MemFree'])) {
508 $free = $meminfo['MemFree'];
510 $reached = ($free < $min_memory);
513 $this->logger->debug('Minimal memory reached.', ['free' => $free, 'memtotal' => $meminfo['MemTotal'], 'limit' => $min_memory]);
520 * @brief Checks if the maximum load is reached
522 * @return bool Is the load reached?
523 * @throws HTTPException\InternalServerErrorException
525 public function isMaxLoadReached()
527 if ($this->mode->isBackend()) {
528 $process = 'backend';
529 $maxsysload = intval($this->config->get('system', 'maxloadavg'));
530 if ($maxsysload < 1) {
534 $process = 'frontend';
535 $maxsysload = intval($this->config->get('system', 'maxloadavg_frontend'));
536 if ($maxsysload < 1) {
541 $load = Core\System::currentLoad();
543 if (intval($load) > $maxsysload) {
544 $this->logger->info('system load for process too high.', ['load' => $load, 'process' => $process, 'maxsysload' => $maxsysload]);
552 * Executes a child process with 'proc_open'
554 * @param string $command The command to execute
555 * @param array $args Arguments to pass to the command ( [ 'key' => value, 'key2' => value2, ... ]
557 * @throws HTTPException\InternalServerErrorException
559 public function proc_run($command, $args)
561 if (!function_exists('proc_open')) {
565 $cmdline = $this->config->get('config', 'php_path', 'php') . ' ' . escapeshellarg($command);
567 foreach ($args as $key => $value) {
568 if (!is_null($value) && is_bool($value) && !$value) {
572 $cmdline .= ' --' . $key;
573 if (!is_null($value) && !is_bool($value)) {
574 $cmdline .= ' ' . $value;
578 if ($this->isMinMemoryReached()) {
582 if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
583 $resource = proc_open('cmd /c start /b ' . $cmdline, [], $foo, $this->getBasePath());
585 $resource = proc_open($cmdline . ' &', [], $foo, $this->getBasePath());
587 if (!is_resource($resource)) {
588 $this->logger->debug('We got no resource for command.', ['cmd' => $cmdline]);
591 proc_close($resource);
595 * Generates the site's default sender email address
598 * @throws HTTPException\InternalServerErrorException
600 public function getSenderEmailAddress()
602 $sender_email = $this->config->get('config', 'sender_email');
603 if (empty($sender_email)) {
604 $hostname = $this->baseURL->getHostname();
605 if (strpos($hostname, ':')) {
606 $hostname = substr($hostname, 0, strpos($hostname, ':'));
609 $sender_email = 'noreply@' . $hostname;
612 return $sender_email;
616 * Returns the current theme name.
618 * @return string the name of the current theme
619 * @throws HTTPException\InternalServerErrorException
621 public function getCurrentTheme()
623 if ($this->mode->isInstall()) {
627 if (!$this->currentTheme) {
628 $this->computeCurrentTheme();
631 return $this->currentTheme;
634 public function setCurrentTheme($theme)
636 $this->currentTheme = $theme;
640 * Computes the current theme name based on the node settings, the user settings and the device type
644 private function computeCurrentTheme()
646 $system_theme = $this->config->get('system', 'theme');
647 if (!$system_theme) {
648 throw new Exception($this->l10n->t('No system theme config value set.'));
652 $this->currentTheme = $system_theme;
655 // Find the theme that belongs to the user whose stuff we are looking at
656 if ($this->profile_uid && ($this->profile_uid != local_user())) {
657 // Allow folks to override user themes and always use their own on their own site.
658 // This works only if the user is on the same server
659 $user = $this->database->selectFirst('user', ['theme'], ['uid' => $this->profile_uid]);
660 if ($this->database->isResult($user) && !Core\PConfig::get(local_user(), 'system', 'always_my_theme')) {
661 $page_theme = $user['theme'];
665 $user_theme = Core\Session::get('theme', $system_theme);
667 // Specific mobile theme override
668 if (($this->is_mobile || $this->is_tablet) && Core\Session::get('show-mobile', true)) {
669 $system_mobile_theme = $this->config->get('system', 'mobile-theme');
670 $user_mobile_theme = Core\Session::get('mobile-theme', $system_mobile_theme);
672 // --- means same mobile theme as desktop
673 if (!empty($user_mobile_theme) && $user_mobile_theme !== '---') {
674 $user_theme = $user_mobile_theme;
679 $theme_name = $page_theme;
681 $theme_name = $user_theme;
684 $theme_name = Strings::sanitizeFilePathItem($theme_name);
686 && in_array($theme_name, Theme::getAllowedList())
687 && (file_exists('view/theme/' . $theme_name . '/style.css')
688 || file_exists('view/theme/' . $theme_name . '/style.php'))
690 $this->currentTheme = $theme_name;
695 * @brief Return full URL to theme which is currently in effect.
697 * Provide a sane default if nothing is chosen or the specified theme does not exist.
700 * @throws HTTPException\InternalServerErrorException
702 public function getCurrentThemeStylesheetPath()
704 return Core\Theme::getStylesheetPath($this->getCurrentTheme());
708 * Check if request was an AJAX (xmlhttprequest) request.
710 * @return boolean true if it was an AJAX request
712 public function isAjax()
714 return $this->isAjax;
718 * @deprecated use Arguments->get() instead
722 public function getArgumentValue($position, $default = '')
724 return $this->args->get($position, $default);
728 * Sets the base url for use in cmdline programs which don't have
731 public function checkURL()
733 $url = $this->config->get('system', 'url');
735 // if the url isn't set or the stored url is radically different
736 // than the currently visited url, store the current value accordingly.
737 // "Radically different" ignores common variations such as http vs https
738 // and www.example.com vs example.com.
739 // We will only change the url to an ip address if there is no existing setting
741 if (empty($url) || (!Util\Strings::compareLink($url, $this->getBaseURL())) && (!preg_match("/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/", $this->baseURL->getHostname()))) {
742 $this->config->set('system', 'url', $this->getBaseURL());
747 * Frontend App script
749 * The App object behaves like a container and a dispatcher at the same time, including a representation of the
750 * request and a representation of the response.
752 * This probably should change to limit the size of this monster method.
754 * @param App\Module $module The determined module
756 public function runFrontend(App\Module $module, App\Router $router, PConfiguration $pconfig)
758 $moduleName = $module->getName();
761 // Missing DB connection: ERROR
762 if ($this->mode->has(App\Mode::LOCALCONFIGPRESENT) && !$this->mode->has(App\Mode::DBAVAILABLE)) {
763 throw new HTTPException\InternalServerErrorException('Apologies but the website is unavailable at the moment.');
766 // Max Load Average reached: ERROR
767 if ($this->isMaxProcessesReached() || $this->isMaxLoadReached()) {
768 header('Retry-After: 120');
769 header('Refresh: 120; url=' . $this->baseURL->get() . "/" . $this->args->getQueryString());
771 throw new HTTPException\ServiceUnavailableException('The node is currently overloaded. Please try again later.');
774 if (!$this->mode->isInstall()) {
775 // Force SSL redirection
776 if ($this->baseURL->checkRedirectHttps()) {
777 System::externalRedirect($this->baseURL->get() . '/' . $this->args->getQueryString());
780 Core\Session::init();
781 Core\Hook::callAll('init_1');
784 // Exclude the backend processes from the session management
785 if (!$this->mode->isBackend()) {
786 $stamp1 = microtime(true);
788 $this->profiler->saveTimestamp($stamp1, 'parser', Core\System::callstack());
789 $this->l10n->setSessionVariable();
790 $this->l10n->setLangFromSession();
793 Core\Worker::executeIfIdle();
796 if ($this->mode->isNormal()) {
797 $requester = HTTPSignature::getSigner('', $_SERVER);
798 if (!empty($requester)) {
799 Profile::addVisitorCookieForHandle($requester);
804 if (!empty($_GET['zrl']) && $this->mode->isNormal()) {
806 // Only continue when the given profile link seems valid
807 // Valid profile links contain a path with "/profile/" and no query parameters
808 if ((parse_url($_GET['zrl'], PHP_URL_QUERY) == "") &&
809 strstr(parse_url($_GET['zrl'], PHP_URL_PATH), "/profile/")) {
810 if (Core\Session::get('visitor_home') != $_GET["zrl"]) {
811 Core\Session::set('my_url', $_GET['zrl']);
812 Core\Session::set('authenticated', 0);
815 Model\Profile::zrlInit($this);
817 // Someone came with an invalid parameter, maybe as a DDoS attempt
818 // We simply stop processing here
819 $this->logger->debug('Invalid ZRL parameter.', ['zrl' => $_GET['zrl']]);
820 throw new HTTPException\ForbiddenException();
825 if (!empty($_GET['owt']) && $this->mode->isNormal()) {
826 $token = $_GET['owt'];
827 Model\Profile::openWebAuthInit($token);
830 Login::sessionAuth();
832 if (empty($_SESSION['authenticated'])) {
833 header('X-Account-Management-Status: none');
836 $_SESSION['sysmsg'] = Core\Session::get('sysmsg', []);
837 $_SESSION['sysmsg_info'] = Core\Session::get('sysmsg_info', []);
838 $_SESSION['last_updated'] = Core\Session::get('last_updated', []);
841 * check_config() is responsible for running update scripts. These automatically
842 * update the DB schema whenever we push a new one out. It also checks to see if
843 * any addons have been added or removed and reacts accordingly.
846 // in install mode, any url loads install module
847 // but we need "view" module for stylesheet
848 if ($this->mode->isInstall() && $moduleName !== 'install') {
849 $this->internalRedirect('install');
850 } elseif (!$this->mode->isInstall() && !$this->mode->has(App\Mode::MAINTENANCEDISABLED) && $moduleName !== 'maintenance') {
851 $this->internalRedirect('maintenance');
854 Core\Update::check($this->getBasePath(), false, $this->mode);
855 Core\Addon::loadAddons();
856 Core\Hook::loadHooks();
859 // Compatibility with the Android Diaspora client
860 if ($moduleName == 'stream') {
861 $this->internalRedirect('network?order=post');
864 if ($moduleName == 'conversations') {
865 $this->internalRedirect('message');
868 if ($moduleName == 'commented') {
869 $this->internalRedirect('network?order=comment');
872 if ($moduleName == 'liked') {
873 $this->internalRedirect('network?order=comment');
876 if ($moduleName == 'activity') {
877 $this->internalRedirect('network?conv=1');
880 if (($moduleName == 'status_messages') && ($this->args->getCommand() == 'status_messages/new')) {
881 $this->internalRedirect('bookmarklet');
884 if (($moduleName == 'user') && ($this->args->getCommand() == 'user/edit')) {
885 $this->internalRedirect('settings');
888 if (($moduleName == 'tag_followings') && ($this->args->getCommand() == 'tag_followings/manage')) {
889 $this->internalRedirect('search');
892 // Initialize module that can set the current theme in the init() method, either directly or via App->profile_uid
893 $this->page['page_title'] = $moduleName;
895 // determine the module class and save it to the module instance
896 // @todo there's an implicit dependency due SESSION::start(), so it has to be called here (yet)
897 $module = $module->determineClass($this->args, $router, $this->config);
899 // Let the module run it's internal process (init, get, post, ...)
900 $module->run($this->l10n, $this, $this->logger, $this->getCurrentTheme(), $_SERVER, $_POST);
902 } catch (HTTPException $e) {
903 ModuleHTTPException::rawContent($e);
906 $this->page->run($this, $this->baseURL, $this->mode, $module, $this->l10n, $this->config, $pconfig);
910 * Redirects to another module relative to the current Friendica base.
911 * If you want to redirect to a external URL, use System::externalRedirectTo()
913 * @param string $toUrl The destination URL (Default is empty, which is the default page of the Friendica node)
914 * @param bool $ssl if true, base URL will try to get called with https:// (works just for relative paths)
916 * @throws HTTPException\InternalServerErrorException In Case the given URL is not relative to the Friendica node
918 public function internalRedirect($toUrl = '', $ssl = false)
920 if (!empty(parse_url($toUrl, PHP_URL_SCHEME))) {
921 throw new HTTPException\InternalServerErrorException("'$toUrl is not a relative path, please use System::externalRedirectTo");
924 $redirectTo = $this->baseURL->get($ssl) . '/' . ltrim($toUrl, '/');
925 Core\System::externalRedirect($redirectTo);
929 * Automatically redirects to relative or absolute URL
930 * Should only be used if it isn't clear if the URL is either internal or external
932 * @param string $toUrl The target URL
934 * @throws HTTPException\InternalServerErrorException
936 public function redirect($toUrl)
938 if (!empty(parse_url($toUrl, PHP_URL_SCHEME))) {
939 Core\System::externalRedirect($toUrl);
941 $this->internalRedirect($toUrl);