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