]> git.mxchange.org Git - friendica.git/blob - src/App.php
e213b741a3f3fa85bdb0d26033e705a269171461
[friendica.git] / src / App.php
1 <?php
2 /**
3  * @file src/App.php
4  */
5 namespace Friendica;
6
7 use Exception;
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\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\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;
27
28 /**
29  *
30  * class: App
31  *
32  * @brief Our main application structure for the life of this page.
33  *
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.
39  *
40  */
41 class App
42 {
43         /** @deprecated 2019.09 - use App\Arguments->getQueryString() */
44         public $query_string;
45         /**
46          * @var Page The current page environment
47          */
48         public $page;
49         public $profile;
50         public $profile_uid;
51         public $user;
52         public $cid;
53         public $contact;
54         public $contacts;
55         public $page_contact;
56         public $content;
57         public $data = [];
58         /** @deprecated 2019.09 - use App\Arguments->getCommand() */
59         public $cmd = '';
60         /** @deprecated 2019.09 - use App\Arguments->getArgv() or Arguments->get() */
61         public $argv;
62         /** @deprecated 2019.09 - use App\Arguments->getArgc() */
63         public $argc;
64         /** @deprecated 2019.09 - Use App\Module->getName() instead */
65         public $module;
66         public $timezone;
67         public $interactive = true;
68         public $identities;
69         /** @deprecated 2019.09 - Use App\Mode->isMobile() instead */
70         public $is_mobile;
71         /** @deprecated 2019.09 - Use App\Mode->isTable() instead */
72         public $is_tablet;
73         public $theme_info = [];
74         public $category;
75         // Allow themes to control internal parameters
76         // by changing App values in theme.php
77
78         public $sourcename              = '';
79         public $videowidth              = 425;
80         public $videoheight             = 350;
81         public $force_max_items         = 0;
82         public $theme_events_in_profile = true;
83         public $queue;
84
85         /**
86          * @var App\Mode The Mode of the Application
87          */
88         private $mode;
89
90         /**
91          * @var BaseURL
92          */
93         private $baseURL;
94
95         /** @var string The name of the current theme */
96         private $currentTheme;
97         /** @var string The name of the current mobile theme */
98         private $currentMobileTheme;
99
100         /**
101          * @var Configuration The config
102          */
103         private $config;
104
105         /**
106          * @var LoggerInterface The logger
107          */
108         private $logger;
109
110         /**
111          * @var Profiler The profiler of this app
112          */
113         private $profiler;
114
115         /**
116          * @var Database The Friendica database connection
117          */
118         private $database;
119
120         /**
121          * @var L10n The translator
122          */
123         private $l10n;
124
125         /**
126          * @var App\Arguments
127          */
128         private $args;
129
130         /**
131          * @var Core\Process The process methods
132          */
133         private $process;
134
135         /**
136          * Returns the current config cache of this node
137          *
138          * @return ConfigCache
139          */
140         public function getConfigCache()
141         {
142                 return $this->config->getCache();
143         }
144
145         /**
146          * The basepath of this app
147          *
148          * @return string
149          */
150         public function getBasePath()
151         {
152                 // Don't use the basepath of the config table for basepath (it should always be the config-file one)
153                 return $this->config->getCache()->get('system', 'basepath');
154         }
155
156         /**
157          * @deprecated 2019.09 - use Page->registerStylesheet instead
158          * @see        Page::registerStylesheet()
159          */
160         public function registerStylesheet($path)
161         {
162                 $this->page->registerStylesheet($path);
163         }
164
165         /**
166          * @deprecated 2019.09 - use Page->registerFooterScript instead
167          * @see        Page::registerFooterScript()
168          */
169         public function registerFooterScript($path)
170         {
171                 $this->page->registerFooterScript($path);
172         }
173
174         /**
175          * @param Database        $database The Friendica Database
176          * @param Configuration   $config   The Configuration
177          * @param App\Mode        $mode     The mode of this Friendica app
178          * @param BaseURL         $baseURL  The full base URL of this Friendica app
179          * @param LoggerInterface $logger   The current app logger
180          * @param Profiler        $profiler The profiler of this application
181          * @param L10n            $l10n     The translator instance
182          * @param App\Arguments   $args     The Friendica Arguments of the call
183          * @param Core\Process    $process  The process methods
184          */
185         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, Core\Process $process)
186         {
187                 $this->database = $database;
188                 $this->config   = $config;
189                 $this->mode     = $mode;
190                 $this->baseURL  = $baseURL;
191                 $this->profiler = $profiler;
192                 $this->logger   = $logger;
193                 $this->l10n     = $l10n;
194                 $this->args     = $args;
195                 $this->process  = $process;
196
197                 $this->cmd          = $args->getCommand();
198                 $this->argv         = $args->getArgv();
199                 $this->argc         = $args->getArgc();
200                 $this->query_string = $args->getQueryString();
201                 $this->module       = $module->getName();
202                 $this->page         = $page;
203
204                 $this->is_mobile = $mode->isMobile();
205                 $this->is_tablet = $mode->isTablet();
206
207                 $this->load();
208         }
209
210         /**
211          * Load the whole app instance
212          */
213         public function load()
214         {
215                 set_time_limit(0);
216
217                 // This has to be quite large to deal with embedded private photos
218                 ini_set('pcre.backtrack_limit', 500000);
219
220                 set_include_path(
221                         get_include_path() . PATH_SEPARATOR
222                         . $this->getBasePath() . DIRECTORY_SEPARATOR . 'include' . PATH_SEPARATOR
223                         . $this->getBasePath() . DIRECTORY_SEPARATOR . 'library' . PATH_SEPARATOR
224                         . $this->getBasePath());
225
226                 $this->profiler->reset();
227
228                 if ($this->mode->has(App\Mode::DBAVAILABLE)) {
229                         $this->profiler->update($this->config);
230
231                         Core\Hook::loadHooks();
232                         $loader = new ConfigFileLoader($this->getBasePath());
233                         Core\Hook::callAll('load_config', $loader);
234                 }
235
236                 $this->loadDefaultTimezone();
237                 // Register template engines
238                 Core\Renderer::registerTemplateEngine('Friendica\Render\FriendicaSmartyEngine');
239         }
240
241         /**
242          * Loads the default timezone
243          *
244          * Include support for legacy $default_timezone
245          *
246          * @global string $default_timezone
247          */
248         private function loadDefaultTimezone()
249         {
250                 if ($this->config->get('system', 'default_timezone')) {
251                         $this->timezone = $this->config->get('system', 'default_timezone');
252                 } else {
253                         global $default_timezone;
254                         $this->timezone = !empty($default_timezone) ? $default_timezone : 'UTC';
255                 }
256
257                 if ($this->timezone) {
258                         date_default_timezone_set($this->timezone);
259                 }
260         }
261
262         /**
263          * Returns the scheme of the current call
264          *
265          * @return string
266          *
267          * @deprecated 2019.06 - use BaseURL->getScheme() instead
268          */
269         public function getScheme()
270         {
271                 return $this->baseURL->getScheme();
272         }
273
274         /**
275          * Retrieves the Friendica instance base URL
276          *
277          * @param bool $ssl Whether to append http or https under BaseURL::SSL_POLICY_SELFSIGN
278          *
279          * @return string Friendica server base URL
280          *
281          * @deprecated 2019.09 - use BaseUrl->get($ssl) instead
282          */
283         public function getBaseURL($ssl = false)
284         {
285                 return $this->baseURL->get($ssl);
286         }
287
288         /**
289          * @brief      Initializes the baseurl components
290          *
291          * Clears the baseurl cache to prevent inconsistencies
292          *
293          * @param string $url
294          *
295          * @deprecated 2019.06 - use BaseURL->saveByURL($url) instead
296          */
297         public function setBaseURL($url)
298         {
299                 $this->baseURL->saveByURL($url);
300         }
301
302         /**
303          * Returns the current hostname
304          *
305          * @return string
306          *
307          * @deprecated 2019.06 - use BaseURL->getHostname() instead
308          */
309         public function getHostName()
310         {
311                 return $this->baseURL->getHostname();
312         }
313
314         /**
315          * Returns the sub-path of the full URL
316          *
317          * @return string
318          *
319          * @deprecated 2019.06 - use BaseURL->getUrlPath() instead
320          */
321         public function getURLPath()
322         {
323                 return $this->baseURL->getUrlPath();
324         }
325
326         /**
327          * @brief      Removes the base url from an url. This avoids some mixed content problems.
328          *
329          * @param string $origURL
330          *
331          * @return string The cleaned url
332          *
333          * @deprecated 2019.09 - Use BaseURL->remove() instead
334          * @see        BaseURL::remove()
335          */
336         public function removeBaseURL(string $origURL)
337         {
338                 return $this->baseURL->remove($origURL);
339         }
340
341         /**
342          * Returns the current UserAgent as a String
343          *
344          * @return string the UserAgent as a String
345          * @throws HTTPException\InternalServerErrorException
346          */
347         public function getUserAgent()
348         {
349                 return
350                         FRIENDICA_PLATFORM . " '" .
351                         FRIENDICA_CODENAME . "' " .
352                         FRIENDICA_VERSION . '-' .
353                         DB_UPDATE_VERSION . '; ' .
354                         $this->getBaseURL();
355         }
356
357         /**
358          * Generates the site's default sender email address
359          *
360          * @return string
361          * @throws HTTPException\InternalServerErrorException
362          */
363         public function getSenderEmailAddress()
364         {
365                 $sender_email = $this->config->get('config', 'sender_email');
366                 if (empty($sender_email)) {
367                         $hostname = $this->baseURL->getHostname();
368                         if (strpos($hostname, ':')) {
369                                 $hostname = substr($hostname, 0, strpos($hostname, ':'));
370                         }
371
372                         $sender_email = 'noreply@' . $hostname;
373                 }
374
375                 return $sender_email;
376         }
377
378         /**
379          * Returns the current theme name. May be overriden by the mobile theme name.
380          *
381          * @return string
382          * @throws Exception
383          */
384         public function getCurrentTheme()
385         {
386                 if ($this->mode->isInstall()) {
387                         return '';
388                 }
389
390                 // Specific mobile theme override
391                 if (($this->mode->isMobile() || $this->mode->isTablet()) && Core\Session::get('show-mobile', true)) {
392                         $user_mobile_theme = $this->getCurrentMobileTheme();
393
394                         // --- means same mobile theme as desktop
395                         if (!empty($user_mobile_theme) && $user_mobile_theme !== '---') {
396                                 return $user_mobile_theme;
397                         }
398                 }
399
400                 if (!$this->currentTheme) {
401                         $this->computeCurrentTheme();
402                 }
403
404                 return $this->currentTheme;
405         }
406
407         /**
408          * Returns the current mobile theme name.
409          *
410          * @return string
411          * @throws Exception
412          */
413         public function getCurrentMobileTheme()
414         {
415                 if ($this->mode->isInstall()) {
416                         return '';
417                 }
418
419                 if (is_null($this->currentMobileTheme)) {
420                         $this->computeCurrentMobileTheme();
421                 }
422
423                 return $this->currentMobileTheme;
424         }
425
426         public function setCurrentTheme($theme)
427         {
428                 $this->currentTheme = $theme;
429         }
430
431         public function setCurrentMobileTheme($theme)
432         {
433                 $this->currentMobileTheme = $theme;
434         }
435
436         /**
437          * Computes the current theme name based on the node settings, the page owner settings and the user settings
438          *
439          * @throws Exception
440          */
441         private function computeCurrentTheme()
442         {
443                 $system_theme = $this->config->get('system', 'theme');
444                 if (!$system_theme) {
445                         throw new Exception($this->l10n->t('No system theme config value set.'));
446                 }
447
448                 // Sane default
449                 $this->setCurrentTheme($system_theme);
450
451                 $page_theme = null;
452                 // Find the theme that belongs to the user whose stuff we are looking at
453                 if ($this->profile_uid && ($this->profile_uid != local_user())) {
454                         // Allow folks to override user themes and always use their own on their own site.
455                         // This works only if the user is on the same server
456                         $user = $this->database->selectFirst('user', ['theme'], ['uid' => $this->profile_uid]);
457                         if ($this->database->isResult($user) && !Core\PConfig::get(local_user(), 'system', 'always_my_theme')) {
458                                 $page_theme = $user['theme'];
459                         }
460                 }
461
462                 $theme_name = $page_theme ?: Core\Session::get('theme', $system_theme);
463
464                 $theme_name = Strings::sanitizeFilePathItem($theme_name);
465                 if ($theme_name
466                     && in_array($theme_name, Theme::getAllowedList())
467                     && (file_exists('view/theme/' . $theme_name . '/style.css')
468                         || file_exists('view/theme/' . $theme_name . '/style.php'))
469                 ) {
470                         $this->setCurrentTheme($theme_name);
471                 }
472         }
473
474         /**
475          * Computes the current mobile theme name based on the node settings, the page owner settings and the user settings
476          */
477         private function computeCurrentMobileTheme()
478         {
479                 $system_mobile_theme = $this->config->get('system', 'mobile-theme', '');
480
481                 // Sane default
482                 $this->setCurrentMobileTheme($system_mobile_theme);
483
484                 $page_mobile_theme = null;
485                 // Find the theme that belongs to the user whose stuff we are looking at
486                 if ($this->profile_uid && ($this->profile_uid != local_user())) {
487                         // Allow folks to override user themes and always use their own on their own site.
488                         // This works only if the user is on the same server
489                         if (!Core\PConfig::get(local_user(), 'system', 'always_my_theme')) {
490                                 $page_mobile_theme = Core\PConfig::get($this->profile_uid, 'system', 'mobile-theme');
491                         }
492                 }
493
494                 $mobile_theme_name = $page_mobile_theme ?: Core\Session::get('mobile-theme', $system_mobile_theme);
495
496                 $mobile_theme_name = Strings::sanitizeFilePathItem($mobile_theme_name);
497                 if ($mobile_theme_name == '---'
498                         ||
499                         in_array($mobile_theme_name, Theme::getAllowedList())
500                         && (file_exists('view/theme/' . $mobile_theme_name . '/style.css')
501                                 || file_exists('view/theme/' . $mobile_theme_name . '/style.php'))
502                 ) {
503                         $this->setCurrentMobileTheme($mobile_theme_name);
504                 }
505         }
506
507         /**
508          * @brief Return full URL to theme which is currently in effect.
509          *
510          * Provide a sane default if nothing is chosen or the specified theme does not exist.
511          *
512          * @return string
513          * @throws Exception
514          */
515         public function getCurrentThemeStylesheetPath()
516         {
517                 return Core\Theme::getStylesheetPath($this->getCurrentTheme());
518         }
519
520         /**
521          * Sets the base url for use in cmdline programs which don't have
522          * $_SERVER variables
523          */
524         public function checkURL()
525         {
526                 $url = $this->config->get('system', 'url');
527
528                 // if the url isn't set or the stored url is radically different
529                 // than the currently visited url, store the current value accordingly.
530                 // "Radically different" ignores common variations such as http vs https
531                 // and www.example.com vs example.com.
532                 // We will only change the url to an ip address if there is no existing setting
533
534                 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()))) {
535                         $this->config->set('system', 'url', $this->getBaseURL());
536                 }
537         }
538
539         /**
540          * Frontend App script
541          *
542          * The App object behaves like a container and a dispatcher at the same time, including a representation of the
543          * request and a representation of the response.
544          *
545          * This probably should change to limit the size of this monster method.
546          *
547          * @param App\Module     $module The determined module
548          * @param App\Router     $router
549          * @param PConfiguration $pconfig
550          * @param Authentication $auth The Authentication backend of the node
551          * @throws HTTPException\InternalServerErrorException
552          * @throws \ImagickException
553          */
554         public function runFrontend(App\Module $module, App\Router $router, PConfiguration $pconfig, Authentication $auth)
555         {
556                 $moduleName = $module->getName();
557
558                 try {
559                         // Missing DB connection: ERROR
560                         if ($this->mode->has(App\Mode::LOCALCONFIGPRESENT) && !$this->mode->has(App\Mode::DBAVAILABLE)) {
561                                 throw new HTTPException\InternalServerErrorException('Apologies but the website is unavailable at the moment.');
562                         }
563
564                         // Max Load Average reached: ERROR
565                         if ($this->process->isMaxProcessesReached() || $this->process->isMaxLoadReached()) {
566                                 header('Retry-After: 120');
567                                 header('Refresh: 120; url=' . $this->baseURL->get() . "/" . $this->args->getQueryString());
568
569                                 throw new HTTPException\ServiceUnavailableException('The node is currently overloaded. Please try again later.');
570                         }
571
572                         if (!$this->mode->isInstall()) {
573                                 // Force SSL redirection
574                                 if ($this->baseURL->checkRedirectHttps()) {
575                                         System::externalRedirect($this->baseURL->get() . '/' . $this->args->getQueryString());
576                                 }
577
578                                 Core\Hook::callAll('init_1');
579                         }
580
581                         // Exclude the backend processes from the session management
582                         if ($this->mode->isBackend()) {
583                                 Core\Worker::executeIfIdle();
584                         }
585
586                         if ($this->mode->isNormal()) {
587                                 $requester = HTTPSignature::getSigner('', $_SERVER);
588                                 if (!empty($requester)) {
589                                         Profile::addVisitorCookieForHandle($requester);
590                                 }
591                         }
592
593                         // ZRL
594                         if (!empty($_GET['zrl']) && $this->mode->isNormal()) {
595                                 if (!local_user()) {
596                                         // Only continue when the given profile link seems valid
597                                         // Valid profile links contain a path with "/profile/" and no query parameters
598                                         if ((parse_url($_GET['zrl'], PHP_URL_QUERY) == "") &&
599                                             strstr(parse_url($_GET['zrl'], PHP_URL_PATH), "/profile/")) {
600                                                 if (Core\Session::get('visitor_home') != $_GET["zrl"]) {
601                                                         Core\Session::set('my_url', $_GET['zrl']);
602                                                         Core\Session::set('authenticated', 0);
603                                                 }
604
605                                                 Model\Profile::zrlInit($this);
606                                         } else {
607                                                 // Someone came with an invalid parameter, maybe as a DDoS attempt
608                                                 // We simply stop processing here
609                                                 $this->logger->debug('Invalid ZRL parameter.', ['zrl' => $_GET['zrl']]);
610                                                 throw new HTTPException\ForbiddenException();
611                                         }
612                                 }
613                         }
614
615                         if (!empty($_GET['owt']) && $this->mode->isNormal()) {
616                                 $token = $_GET['owt'];
617                                 Model\Profile::openWebAuthInit($token);
618                         }
619
620                         $auth->withSession($this);
621
622                         if (empty($_SESSION['authenticated'])) {
623                                 header('X-Account-Management-Status: none');
624                         }
625
626                         $_SESSION['sysmsg']       = Core\Session::get('sysmsg', []);
627                         $_SESSION['sysmsg_info']  = Core\Session::get('sysmsg_info', []);
628                         $_SESSION['last_updated'] = Core\Session::get('last_updated', []);
629
630                         /*
631                          * check_config() is responsible for running update scripts. These automatically
632                          * update the DB schema whenever we push a new one out. It also checks to see if
633                          * any addons have been added or removed and reacts accordingly.
634                          */
635
636                         // in install mode, any url loads install module
637                         // but we need "view" module for stylesheet
638                         if ($this->mode->isInstall() && $moduleName !== 'install') {
639                                 $this->baseURL->redirect('install');
640                         } elseif (!$this->mode->isInstall() && !$this->mode->has(App\Mode::MAINTENANCEDISABLED) && $moduleName !== 'maintenance') {
641                                 $this->baseURL->redirect('maintenance');
642                         } else {
643                                 $this->checkURL();
644                                 Core\Update::check($this->getBasePath(), false, $this->mode);
645                                 Core\Addon::loadAddons();
646                                 Core\Hook::loadHooks();
647                         }
648
649                         // Compatibility with the Android Diaspora client
650                         if ($moduleName == 'stream') {
651                                 $this->baseURL->redirect('network?order=post');
652                         }
653
654                         if ($moduleName == 'conversations') {
655                                 $this->baseURL->redirect('message');
656                         }
657
658                         if ($moduleName == 'commented') {
659                                 $this->baseURL->redirect('network?order=comment');
660                         }
661
662                         if ($moduleName == 'liked') {
663                                 $this->baseURL->redirect('network?order=comment');
664                         }
665
666                         if ($moduleName == 'activity') {
667                                 $this->baseURL->redirect('network?conv=1');
668                         }
669
670                         if (($moduleName == 'status_messages') && ($this->args->getCommand() == 'status_messages/new')) {
671                                 $this->baseURL->redirect('bookmarklet');
672                         }
673
674                         if (($moduleName == 'user') && ($this->args->getCommand() == 'user/edit')) {
675                                 $this->baseURL->redirect('settings');
676                         }
677
678                         if (($moduleName == 'tag_followings') && ($this->args->getCommand() == 'tag_followings/manage')) {
679                                 $this->baseURL->redirect('search');
680                         }
681
682                         // Initialize module that can set the current theme in the init() method, either directly or via App->profile_uid
683                         $this->page['page_title'] = $moduleName;
684
685                         // determine the module class and save it to the module instance
686                         // @todo there's an implicit dependency due SESSION::start(), so it has to be called here (yet)
687                         $module = $module->determineClass($this->args, $router, $this->config);
688
689                         // Let the module run it's internal process (init, get, post, ...)
690                         $module->run($this->l10n, $this->baseURL, $this->logger, $_SERVER, $_POST);
691                 } catch (HTTPException $e) {
692                         ModuleHTTPException::rawContent($e);
693                 }
694
695                 $this->page->run($this, $this->baseURL, $this->mode, $module, $this->l10n, $this->config, $pconfig);
696         }
697
698         /**
699          * Automatically redirects to relative or absolute URL
700          * Should only be used if it isn't clear if the URL is either internal or external
701          *
702          * @param string $toUrl The target URL
703          *
704          * @throws HTTPException\InternalServerErrorException
705          */
706         public function redirect($toUrl)
707         {
708                 if (!empty(parse_url($toUrl, PHP_URL_SCHEME))) {
709                         Core\System::externalRedirect($toUrl);
710                 } else {
711                         $this->baseURL->redirect($toUrl);
712                 }
713         }
714 }