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