8 use Friendica\App\Arguments;
9 use Friendica\App\BaseURL;
10 use Friendica\App\Page;
11 use Friendica\Core\Config\Cache\ConfigCache;
12 use Friendica\Core\Config\Configuration;
13 use Friendica\Core\Config\PConfiguration;
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\Login;
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.
43 /** @deprecated 2019.09 - use App\Arguments->getQueryString() */
46 * @var Page The current page environment
58 /** @deprecated 2019.09 - use App\Arguments->getCommand() */
60 /** @deprecated 2019.09 - use App\Arguments->getArgv() or Arguments->get() */
62 /** @deprecated 2019.09 - use App\Arguments->getArgc() */
64 /** @deprecated 2019.09 - Use App\Module->getName() instead */
67 public $interactive = true;
69 /** @deprecated 2019.09 - Use App\Mode->isMobile() instead */
71 /** @deprecated 2019.09 - Use App\Mode->isTable() instead */
73 public $theme_info = [];
75 // Allow themes to control internal parameters
76 // by changing App values in theme.php
78 public $sourcename = '';
79 public $videowidth = 425;
80 public $videoheight = 350;
81 public $force_max_items = 0;
82 public $theme_events_in_profile = true;
86 * @var App\Mode The Mode of the Application
96 * @var string The name of the current theme
98 private $currentTheme;
101 * @var Configuration The config
106 * @var LoggerInterface The logger
111 * @var Profiler The profiler of this app
116 * @var Database The Friendica database connection
121 * @var L10n The translator
131 * Returns the current config cache of this node
133 * @return ConfigCache
135 public function getConfigCache()
137 return $this->config->getCache();
141 * Returns the current config of this node
143 * @return Configuration
145 public function getConfig()
147 return $this->config;
151 * The basepath of this app
155 public function getBasePath()
157 // Don't use the basepath of the config table for basepath (it should always be the config-file one)
158 return $this->config->getCache()->get('system', 'basepath');
162 * The Logger of this app
164 * @return LoggerInterface
166 public function getLogger()
168 return $this->logger;
172 * The profiler of this app
176 public function getProfiler()
178 return $this->profiler;
182 * Returns the Mode of the Application
184 * @return App\Mode The Application Mode
186 public function getMode()
192 * Returns the Database of the Application
196 public function getDBA()
198 return $this->database;
202 * @deprecated 2019.09 - use Page->registerStylesheet instead
203 * @see Page::registerStylesheet()
205 public function registerStylesheet($path)
207 $this->page->registerStylesheet($path);
211 * @deprecated 2019.09 - use Page->registerFooterScript instead
212 * @see Page::registerFooterScript()
214 public function registerFooterScript($path)
216 $this->page->registerFooterScript($path);
220 * @param Database $database The Friendica Database
221 * @param Configuration $config The Configuration
222 * @param App\Mode $mode The mode of this Friendica app
223 * @param BaseURL $baseURL The full base URL of this Friendica app
224 * @param LoggerInterface $logger The current app logger
225 * @param Profiler $profiler The profiler of this application
226 * @param L10n $l10n The translator instance
227 * @param App\Arguments $args The Friendica Arguments of the call
229 public function __construct(Database $database, Configuration $config, App\Mode $mode, BaseURL $baseURL, LoggerInterface $logger, Profiler $profiler, L10n $l10n, Arguments $args, App\Module $module, App\Page $page)
231 $this->database = $database;
232 $this->config = $config;
234 $this->baseURL = $baseURL;
235 $this->profiler = $profiler;
236 $this->logger = $logger;
240 $this->cmd = $args->getCommand();
241 $this->argv = $args->getArgv();
242 $this->argc = $args->getArgc();
243 $this->query_string = $args->getQueryString();
244 $this->module = $module->getName();
247 $this->is_mobile = $mode->isMobile();
248 $this->is_tablet = $mode->isTablet();
254 * Load the whole app instance
256 public function load()
260 // This has to be quite large to deal with embedded private photos
261 ini_set('pcre.backtrack_limit', 500000);
264 get_include_path() . PATH_SEPARATOR
265 . $this->getBasePath() . DIRECTORY_SEPARATOR . 'include' . PATH_SEPARATOR
266 . $this->getBasePath() . DIRECTORY_SEPARATOR . 'library' . PATH_SEPARATOR
267 . $this->getBasePath());
269 $this->profiler->reset();
271 if ($this->mode->has(App\Mode::DBAVAILABLE)) {
272 $this->profiler->update($this->config);
274 Core\Hook::loadHooks();
275 $loader = new ConfigFileLoader($this->getBasePath());
276 Core\Hook::callAll('load_config', $loader);
279 $this->loadDefaultTimezone();
280 // Register template engines
281 Core\Renderer::registerTemplateEngine('Friendica\Render\FriendicaSmartyEngine');
285 * Loads the default timezone
287 * Include support for legacy $default_timezone
289 * @global string $default_timezone
291 private function loadDefaultTimezone()
293 if ($this->config->get('system', 'default_timezone')) {
294 $this->timezone = $this->config->get('system', 'default_timezone');
296 global $default_timezone;
297 $this->timezone = !empty($default_timezone) ? $default_timezone : 'UTC';
300 if ($this->timezone) {
301 date_default_timezone_set($this->timezone);
306 * Returns the scheme of the current call
310 * @deprecated 2019.06 - use BaseURL->getScheme() instead
312 public function getScheme()
314 return $this->baseURL->getScheme();
318 * Retrieves the Friendica instance base URL
320 * @param bool $ssl Whether to append http or https under BaseURL::SSL_POLICY_SELFSIGN
322 * @return string Friendica server base URL
324 * @deprecated 2019.09 - use BaseUrl->get($ssl) instead
326 public function getBaseURL($ssl = false)
328 return $this->baseURL->get($ssl);
332 * @brief Initializes the baseurl components
334 * Clears the baseurl cache to prevent inconsistencies
338 * @deprecated 2019.06 - use BaseURL->saveByURL($url) instead
340 public function setBaseURL($url)
342 $this->baseURL->saveByURL($url);
346 * Returns the current hostname
350 * @deprecated 2019.06 - use BaseURL->getHostname() instead
352 public function getHostName()
354 return $this->baseURL->getHostname();
358 * Returns the sub-path of the full URL
362 * @deprecated 2019.06 - use BaseURL->getUrlPath() instead
364 public function getURLPath()
366 return $this->baseURL->getUrlPath();
370 * @brief Removes the base url from an url. This avoids some mixed content problems.
372 * @param string $origURL
374 * @return string The cleaned url
376 * @deprecated 2019.09 - Use BaseURL->remove() instead
377 * @see BaseURL::remove()
379 public function removeBaseURL($origURL)
381 return $this->baseURL->remove($origURL);
385 * Returns the current UserAgent as a String
387 * @return string the UserAgent as a String
388 * @throws HTTPException\InternalServerErrorException
390 public function getUserAgent()
393 FRIENDICA_PLATFORM . " '" .
394 FRIENDICA_CODENAME . "' " .
395 FRIENDICA_VERSION . '-' .
396 DB_UPDATE_VERSION . '; ' .
401 * @brief Checks if the maximum number of database processes is reached
403 * @return bool Is the limit reached?
405 public function isMaxProcessesReached()
407 // Deactivated, needs more investigating if this check really makes sense
411 * Commented out to suppress static analyzer issues
413 if ($this->is_backend()) {
414 $process = 'backend';
415 $max_processes = $this->config->get('system', 'max_processes_backend');
416 if (intval($max_processes) == 0) {
420 $process = 'frontend';
421 $max_processes = $this->config->get('system', 'max_processes_frontend');
422 if (intval($max_processes) == 0) {
427 $processlist = DBA::processlist();
428 if ($processlist['list'] != '') {
429 $this->logger->debug('Processcheck: Processes: ' . $processlist['amount'] . ' - Processlist: ' . $processlist['list']);
431 if ($processlist['amount'] > $max_processes) {
432 $this->logger->debug('Processcheck: Maximum number of processes for ' . $process . ' tasks (' . $max_processes . ') reached.');
441 * @brief Checks if the minimal memory is reached
443 * @return bool Is the memory limit reached?
444 * @throws HTTPException\InternalServerErrorException
446 public function isMinMemoryReached()
448 $min_memory = $this->config->get('system', 'min_memory', 0);
449 if ($min_memory == 0) {
453 if (!is_readable('/proc/meminfo')) {
457 $memdata = explode("\n", file_get_contents('/proc/meminfo'));
460 foreach ($memdata as $line) {
461 $data = explode(':', $line);
462 if (count($data) != 2) {
465 list($key, $val) = $data;
466 $meminfo[$key] = (int)trim(str_replace('kB', '', $val));
467 $meminfo[$key] = (int)($meminfo[$key] / 1024);
470 if (!isset($meminfo['MemFree'])) {
474 $free = $meminfo['MemFree'];
476 $reached = ($free < $min_memory);
479 $this->logger->debug('Minimal memory reached.', ['free' => $free, 'memtotal' => $meminfo['MemTotal'], 'limit' => $min_memory]);
486 * @brief Checks if the maximum load is reached
488 * @return bool Is the load reached?
489 * @throws HTTPException\InternalServerErrorException
491 public function isMaxLoadReached()
493 if ($this->mode->isBackend()) {
494 $process = 'backend';
495 $maxsysload = intval($this->config->get('system', 'maxloadavg'));
496 if ($maxsysload < 1) {
500 $process = 'frontend';
501 $maxsysload = intval($this->config->get('system', 'maxloadavg_frontend'));
502 if ($maxsysload < 1) {
507 $load = Core\System::currentLoad();
509 if (intval($load) > $maxsysload) {
510 $this->logger->info('system load for process too high.', ['load' => $load, 'process' => $process, 'maxsysload' => $maxsysload]);
518 * Executes a child process with 'proc_open'
520 * @param string $command The command to execute
521 * @param array $args Arguments to pass to the command ( [ 'key' => value, 'key2' => value2, ... ]
523 * @throws HTTPException\InternalServerErrorException
525 public function proc_run($command, $args)
527 if (!function_exists('proc_open')) {
531 $cmdline = $this->config->get('config', 'php_path', 'php') . ' ' . escapeshellarg($command);
533 foreach ($args as $key => $value) {
534 if (!is_null($value) && is_bool($value) && !$value) {
538 $cmdline .= ' --' . $key;
539 if (!is_null($value) && !is_bool($value)) {
540 $cmdline .= ' ' . $value;
544 if ($this->isMinMemoryReached()) {
548 if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
549 $resource = proc_open('cmd /c start /b ' . $cmdline, [], $foo, $this->getBasePath());
551 $resource = proc_open($cmdline . ' &', [], $foo, $this->getBasePath());
553 if (!is_resource($resource)) {
554 $this->logger->debug('We got no resource for command.', ['cmd' => $cmdline]);
557 proc_close($resource);
561 * Generates the site's default sender email address
564 * @throws HTTPException\InternalServerErrorException
566 public function getSenderEmailAddress()
568 $sender_email = $this->config->get('config', 'sender_email');
569 if (empty($sender_email)) {
570 $hostname = $this->baseURL->getHostname();
571 if (strpos($hostname, ':')) {
572 $hostname = substr($hostname, 0, strpos($hostname, ':'));
575 $sender_email = 'noreply@' . $hostname;
578 return $sender_email;
582 * Returns the current theme name.
584 * @return string the name of the current theme
585 * @throws HTTPException\InternalServerErrorException
587 public function getCurrentTheme()
589 if ($this->mode->isInstall()) {
593 if (!$this->currentTheme) {
594 $this->computeCurrentTheme();
597 return $this->currentTheme;
600 public function setCurrentTheme($theme)
602 $this->currentTheme = $theme;
606 * Computes the current theme name based on the node settings, the user settings and the device type
610 private function computeCurrentTheme()
612 $system_theme = $this->config->get('system', 'theme');
613 if (!$system_theme) {
614 throw new Exception($this->l10n->t('No system theme config value set.'));
618 $this->currentTheme = $system_theme;
621 // Find the theme that belongs to the user whose stuff we are looking at
622 if ($this->profile_uid && ($this->profile_uid != local_user())) {
623 // Allow folks to override user themes and always use their own on their own site.
624 // This works only if the user is on the same server
625 $user = $this->database->selectFirst('user', ['theme'], ['uid' => $this->profile_uid]);
626 if ($this->database->isResult($user) && !Core\PConfig::get(local_user(), 'system', 'always_my_theme')) {
627 $page_theme = $user['theme'];
631 $user_theme = Core\Session::get('theme', $system_theme);
633 // Specific mobile theme override
634 if (($this->is_mobile || $this->is_tablet) && Core\Session::get('show-mobile', true)) {
635 $system_mobile_theme = $this->config->get('system', 'mobile-theme');
636 $user_mobile_theme = Core\Session::get('mobile-theme', $system_mobile_theme);
638 // --- means same mobile theme as desktop
639 if (!empty($user_mobile_theme) && $user_mobile_theme !== '---') {
640 $user_theme = $user_mobile_theme;
645 $theme_name = $page_theme;
647 $theme_name = $user_theme;
650 $theme_name = Strings::sanitizeFilePathItem($theme_name);
652 && in_array($theme_name, Theme::getAllowedList())
653 && (file_exists('view/theme/' . $theme_name . '/style.css')
654 || file_exists('view/theme/' . $theme_name . '/style.php'))
656 $this->currentTheme = $theme_name;
661 * @brief Return full URL to theme which is currently in effect.
663 * Provide a sane default if nothing is chosen or the specified theme does not exist.
666 * @throws HTTPException\InternalServerErrorException
668 public function getCurrentThemeStylesheetPath()
670 return Core\Theme::getStylesheetPath($this->getCurrentTheme());
674 * @deprecated 2019.09 - use App\Mode->isAjax() instead
675 * @see App\Mode::isAjax()
677 public function isAjax()
679 return $this->mode->isAjax();
683 * @deprecated use Arguments->get() instead
687 public function getArgumentValue($position, $default = '')
689 return $this->args->get($position, $default);
693 * Sets the base url for use in cmdline programs which don't have
696 public function checkURL()
698 $url = $this->config->get('system', 'url');
700 // if the url isn't set or the stored url is radically different
701 // than the currently visited url, store the current value accordingly.
702 // "Radically different" ignores common variations such as http vs https
703 // and www.example.com vs example.com.
704 // We will only change the url to an ip address if there is no existing setting
706 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()))) {
707 $this->config->set('system', 'url', $this->getBaseURL());
712 * Frontend App script
714 * The App object behaves like a container and a dispatcher at the same time, including a representation of the
715 * request and a representation of the response.
717 * This probably should change to limit the size of this monster method.
719 * @param App\Module $module The determined module
721 public function runFrontend(App\Module $module, App\Router $router, PConfiguration $pconfig)
723 $moduleName = $module->getName();
726 // Missing DB connection: ERROR
727 if ($this->mode->has(App\Mode::LOCALCONFIGPRESENT) && !$this->mode->has(App\Mode::DBAVAILABLE)) {
728 throw new HTTPException\InternalServerErrorException('Apologies but the website is unavailable at the moment.');
731 // Max Load Average reached: ERROR
732 if ($this->isMaxProcessesReached() || $this->isMaxLoadReached()) {
733 header('Retry-After: 120');
734 header('Refresh: 120; url=' . $this->baseURL->get() . "/" . $this->args->getQueryString());
736 throw new HTTPException\ServiceUnavailableException('The node is currently overloaded. Please try again later.');
739 if (!$this->mode->isInstall()) {
740 // Force SSL redirection
741 if ($this->baseURL->checkRedirectHttps()) {
742 System::externalRedirect($this->baseURL->get() . '/' . $this->args->getQueryString());
745 Core\Session::init();
746 Core\Hook::callAll('init_1');
749 // Exclude the backend processes from the session management
750 if (!$this->mode->isBackend()) {
751 $stamp1 = microtime(true);
753 $this->profiler->saveTimestamp($stamp1, 'parser', Core\System::callstack());
754 $this->l10n->setSessionVariable();
755 $this->l10n->setLangFromSession();
758 Core\Worker::executeIfIdle();
761 if ($this->mode->isNormal()) {
762 $requester = HTTPSignature::getSigner('', $_SERVER);
763 if (!empty($requester)) {
764 Profile::addVisitorCookieForHandle($requester);
769 if (!empty($_GET['zrl']) && $this->mode->isNormal()) {
771 // Only continue when the given profile link seems valid
772 // Valid profile links contain a path with "/profile/" and no query parameters
773 if ((parse_url($_GET['zrl'], PHP_URL_QUERY) == "") &&
774 strstr(parse_url($_GET['zrl'], PHP_URL_PATH), "/profile/")) {
775 if (Core\Session::get('visitor_home') != $_GET["zrl"]) {
776 Core\Session::set('my_url', $_GET['zrl']);
777 Core\Session::set('authenticated', 0);
780 Model\Profile::zrlInit($this);
782 // Someone came with an invalid parameter, maybe as a DDoS attempt
783 // We simply stop processing here
784 $this->logger->debug('Invalid ZRL parameter.', ['zrl' => $_GET['zrl']]);
785 throw new HTTPException\ForbiddenException();
790 if (!empty($_GET['owt']) && $this->mode->isNormal()) {
791 $token = $_GET['owt'];
792 Model\Profile::openWebAuthInit($token);
795 Login::sessionAuth();
797 if (empty($_SESSION['authenticated'])) {
798 header('X-Account-Management-Status: none');
801 $_SESSION['sysmsg'] = Core\Session::get('sysmsg', []);
802 $_SESSION['sysmsg_info'] = Core\Session::get('sysmsg_info', []);
803 $_SESSION['last_updated'] = Core\Session::get('last_updated', []);
806 * check_config() is responsible for running update scripts. These automatically
807 * update the DB schema whenever we push a new one out. It also checks to see if
808 * any addons have been added or removed and reacts accordingly.
811 // in install mode, any url loads install module
812 // but we need "view" module for stylesheet
813 if ($this->mode->isInstall() && $moduleName !== 'install') {
814 $this->internalRedirect('install');
815 } elseif (!$this->mode->isInstall() && !$this->mode->has(App\Mode::MAINTENANCEDISABLED) && $moduleName !== 'maintenance') {
816 $this->internalRedirect('maintenance');
819 Core\Update::check($this->getBasePath(), false, $this->mode);
820 Core\Addon::loadAddons();
821 Core\Hook::loadHooks();
824 // Compatibility with the Android Diaspora client
825 if ($moduleName == 'stream') {
826 $this->internalRedirect('network?order=post');
829 if ($moduleName == 'conversations') {
830 $this->internalRedirect('message');
833 if ($moduleName == 'commented') {
834 $this->internalRedirect('network?order=comment');
837 if ($moduleName == 'liked') {
838 $this->internalRedirect('network?order=comment');
841 if ($moduleName == 'activity') {
842 $this->internalRedirect('network?conv=1');
845 if (($moduleName == 'status_messages') && ($this->args->getCommand() == 'status_messages/new')) {
846 $this->internalRedirect('bookmarklet');
849 if (($moduleName == 'user') && ($this->args->getCommand() == 'user/edit')) {
850 $this->internalRedirect('settings');
853 if (($moduleName == 'tag_followings') && ($this->args->getCommand() == 'tag_followings/manage')) {
854 $this->internalRedirect('search');
857 // Initialize module that can set the current theme in the init() method, either directly or via App->profile_uid
858 $this->page['page_title'] = $moduleName;
860 // determine the module class and save it to the module instance
861 // @todo there's an implicit dependency due SESSION::start(), so it has to be called here (yet)
862 $module = $module->determineClass($this->args, $router, $this->config);
864 // Let the module run it's internal process (init, get, post, ...)
865 $module->run($this->l10n, $this, $this->logger, $this->getCurrentTheme(), $_SERVER, $_POST);
867 } catch (HTTPException $e) {
868 ModuleHTTPException::rawContent($e);
871 $this->page->run($this, $this->baseURL, $this->mode, $module, $this->l10n, $this->config, $pconfig);
875 * Redirects to another module relative to the current Friendica base.
876 * If you want to redirect to a external URL, use System::externalRedirectTo()
878 * @param string $toUrl The destination URL (Default is empty, which is the default page of the Friendica node)
879 * @param bool $ssl if true, base URL will try to get called with https:// (works just for relative paths)
881 * @throws HTTPException\InternalServerErrorException In Case the given URL is not relative to the Friendica node
883 public function internalRedirect($toUrl = '', $ssl = false)
885 if (!empty(parse_url($toUrl, PHP_URL_SCHEME))) {
886 throw new HTTPException\InternalServerErrorException("'$toUrl is not a relative path, please use System::externalRedirectTo");
889 $redirectTo = $this->baseURL->get($ssl) . '/' . ltrim($toUrl, '/');
890 Core\System::externalRedirect($redirectTo);
894 * Automatically redirects to relative or absolute URL
895 * Should only be used if it isn't clear if the URL is either internal or external
897 * @param string $toUrl The target URL
899 * @throws HTTPException\InternalServerErrorException
901 public function redirect($toUrl)
903 if (!empty(parse_url($toUrl, PHP_URL_SCHEME))) {
904 Core\System::externalRedirect($toUrl);
906 $this->internalRedirect($toUrl);