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