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