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