]> git.mxchange.org Git - friendica.git/blob - src/App.php
f37e185353e0ba38a3cd35dacb4440b50bbad0ba
[friendica.git] / src / App.php
1 <?php
2 /**
3  * @file src/App.php
4  */
5 namespace Friendica;
6
7 use Detection\MobileDetect;
8 use Exception;
9 use Friendica\App\Arguments;
10 use Friendica\App\BaseURL;
11 use Friendica\App\Page;
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\Login;
21 use Friendica\Module\Special\HTTPException as ModuleHTTPException;
22 use Friendica\Network\HTTPException;
23 use Friendica\Util\ConfigFileLoader;
24 use Friendica\Util\HTTPSignature;
25 use Friendica\Util\Profiler;
26 use Friendica\Util\Strings;
27 use Psr\Log\LoggerInterface;
28
29 /**
30  *
31  * class: App
32  *
33  * @brief Our main application structure for the life of this page.
34  *
35  * Primarily deals with the URL that got us here
36  * and tries to make some sense of it, and
37  * stores our page contents and config storage
38  * and anything else that might need to be passed around
39  * before we spit the page out.
40  *
41  */
42 class App
43 {
44         /** @deprecated 2019.09 - use App\Arguments->getQueryString() */
45         public $query_string;
46         /**
47          * @var Page The current page environment
48          */
49         public $page;
50         public $profile;
51         public $profile_uid;
52         public $user;
53         public $cid;
54         public $contact;
55         public $contacts;
56         public $page_contact;
57         public $content;
58         public $data = [];
59         /** @deprecated 2019.09 - use App\Arguments->getCommand() */
60         public $cmd = '';
61         /** @deprecated 2019.09 - use App\Arguments->getArgv() or Arguments->get() */
62         public $argv;
63         /** @deprecated 2019.09 - use App\Arguments->getArgc() */
64         public $argc;
65         /** @deprecated 2019.09 - Use App\Module->getName() instead */
66         public $module;
67         public $timezone;
68         public $interactive = true;
69         public $identities;
70         public $is_mobile;
71         public $is_tablet;
72         public $theme_info  = [];
73         public $category;
74         // Allow themes to control internal parameters
75         // by changing App values in theme.php
76
77         public $sourcename              = '';
78         public $videowidth              = 425;
79         public $videoheight             = 350;
80         public $force_max_items         = 0;
81         public $theme_events_in_profile = true;
82         public $queue;
83
84         /**
85          * @var App\Mode The Mode of the Application
86          */
87         private $mode;
88
89         /**
90          * @var App\Router
91          */
92         private $router;
93
94         /**
95          * @var BaseURL
96          */
97         private $baseURL;
98
99         /**
100          * @var string The name of the current theme
101          */
102         private $currentTheme;
103
104         /**
105          * @var bool check if request was an AJAX (xmlhttprequest) request
106          */
107         private $isAjax;
108
109         /**
110          * @var MobileDetect
111          */
112         public $mobileDetect;
113
114         /**
115          * @var Configuration The config
116          */
117         private $config;
118
119         /**
120          * @var LoggerInterface The logger
121          */
122         private $logger;
123
124         /**
125          * @var Profiler The profiler of this app
126          */
127         private $profiler;
128
129         /**
130          * @var Database The Friendica database connection
131          */
132         private $database;
133
134         /**
135          * @var L10n The translator
136          */
137         private $l10n;
138
139         /**
140          * @var App\Arguments
141          */
142         private $args;
143
144         /**
145          * Returns the current config cache of this node
146          *
147          * @return ConfigCache
148          */
149         public function getConfigCache()
150         {
151                 return $this->config->getCache();
152         }
153
154         /**
155          * Returns the current config of this node
156          *
157          * @return Configuration
158          */
159         public function getConfig()
160         {
161                 return $this->config;
162         }
163
164         /**
165          * The basepath of this app
166          *
167          * @return string
168          */
169         public function getBasePath()
170         {
171                 // Don't use the basepath of the config table for basepath (it should always be the config-file one)
172                 return $this->config->getCache()->get('system', 'basepath');
173         }
174
175         /**
176          * The Logger of this app
177          *
178          * @return LoggerInterface
179          */
180         public function getLogger()
181         {
182                 return $this->logger;
183         }
184
185         /**
186          * The profiler of this app
187          *
188          * @return Profiler
189          */
190         public function getProfiler()
191         {
192                 return $this->profiler;
193         }
194
195         /**
196          * Returns the Mode of the Application
197          *
198          * @return App\Mode The Application Mode
199          */
200         public function getMode()
201         {
202                 return $this->mode;
203         }
204
205         /**
206          * Returns the Database of the Application
207          *
208          * @return Database
209          */
210         public function getDBA()
211         {
212                 return $this->database;
213         }
214
215         /**
216          * @deprecated 2019.09 - use Page->registerStylesheet instead
217          * @see Page::registerStylesheet()
218          */
219         public function registerStylesheet($path)
220         {
221                 $this->page->registerStylesheet($path);
222         }
223
224         /**
225          * @deprecated 2019.09 - use Page->registerFooterScript instead
226          * @see Page::registerFooterScript()
227          */
228         public function registerFooterScript($path)
229         {
230                 $this->page->registerFooterScript($path);
231         }
232
233         /**
234          * @param Database        $database     The Friendica Database
235          * @param Configuration   $config       The Configuration
236          * @param App\Mode        $mode         The mode of this Friendica app
237          * @param App\Router      $router       The router of this Friendica app
238          * @param BaseURL         $baseURL      The full base URL of this Friendica app
239          * @param LoggerInterface $logger       The current app logger
240          * @param Profiler        $profiler     The profiler of this application
241          * @param L10n            $l10n         The translator instance
242          * @param App\Arguments   $args         The Friendica Arguments of the call
243          * @param MobileDetect    $mobileDetect A mobile detection class
244          */
245         public function __construct(Database $database, Configuration $config, App\Mode $mode, App\Router $router, BaseURL $baseURL, LoggerInterface $logger, Profiler $profiler, L10n $l10n, Arguments $args, App\Module $module, App\Page $page, MobileDetect $mobileDetect)
246         {
247                 $this->database     = $database;
248                 $this->config       = $config;
249                 $this->mode         = $mode;
250                 $this->router       = $router;
251                 $this->baseURL      = $baseURL;
252                 $this->profiler     = $profiler;
253                 $this->logger       = $logger;
254                 $this->l10n         = $l10n;
255                 $this->args         = $args;
256                 $this->mobileDetect = $mobileDetect;
257
258                 $this->cmd          = $args->getCommand();
259                 $this->argv         = $args->getArgv();
260                 $this->argc         = $args->getArgc();
261                 $this->query_string = $args->getQueryString();
262                 $this->module       = $module->getName();
263                 $this->page         = $page;
264
265                 $this->is_mobile = $mobileDetect->isMobile();
266                 $this->is_tablet = $mobileDetect->isTablet();
267
268                 $this->isAjax = strtolower(defaults($_SERVER, 'HTTP_X_REQUESTED_WITH', '')) == 'xmlhttprequest';
269
270                 $this->load();
271         }
272
273         /**
274          * Load the whole app instance
275          */
276         public function load()
277         {
278                 set_time_limit(0);
279
280                 // This has to be quite large to deal with embedded private photos
281                 ini_set('pcre.backtrack_limit', 500000);
282
283                 set_include_path(
284                         get_include_path() . PATH_SEPARATOR
285                         . $this->getBasePath() . DIRECTORY_SEPARATOR . 'include' . PATH_SEPARATOR
286                         . $this->getBasePath() . DIRECTORY_SEPARATOR . 'library' . PATH_SEPARATOR
287                         . $this->getBasePath());
288
289                 $this->profiler->reset();
290
291                 if ($this->mode->has(App\Mode::DBAVAILABLE)) {
292                         $this->profiler->update($this->config);
293
294                         Core\Hook::loadHooks();
295                         $loader = new ConfigFileLoader($this->getBasePath());
296                         Core\Hook::callAll('load_config', $loader);
297                 }
298
299                 $this->loadDefaultTimezone();
300                 // Register template engines
301                 Core\Renderer::registerTemplateEngine('Friendica\Render\FriendicaSmartyEngine');
302         }
303
304         /**
305          * Loads the default timezone
306          *
307          * Include support for legacy $default_timezone
308          *
309          * @global string $default_timezone
310          */
311         private function loadDefaultTimezone()
312         {
313                 if ($this->config->get('system', 'default_timezone')) {
314                         $this->timezone = $this->config->get('system', 'default_timezone');
315                 } else {
316                         global $default_timezone;
317                         $this->timezone = !empty($default_timezone) ? $default_timezone : 'UTC';
318                 }
319
320                 if ($this->timezone) {
321                         date_default_timezone_set($this->timezone);
322                 }
323         }
324
325         /**
326          * Returns the scheme of the current call
327          *
328          * @return string
329          *
330          * @deprecated 2019.06 - use BaseURL->getScheme() instead
331          */
332         public function getScheme()
333         {
334                 return $this->baseURL->getScheme();
335         }
336
337         /**
338          * Retrieves the Friendica instance base URL
339          *
340          * @param bool $ssl Whether to append http or https under BaseURL::SSL_POLICY_SELFSIGN
341          *
342          * @return string Friendica server base URL
343          *
344          * @deprecated 2019.09 - use BaseUrl->get($ssl) instead
345          */
346         public function getBaseURL($ssl = false)
347         {
348                 return $this->baseURL->get($ssl);
349         }
350
351         /**
352          * @brief      Initializes the baseurl components
353          *
354          * Clears the baseurl cache to prevent inconsistencies
355          *
356          * @param string $url
357          *
358          * @deprecated 2019.06 - use BaseURL->saveByURL($url) instead
359          */
360         public function setBaseURL($url)
361         {
362                 $this->baseURL->saveByURL($url);
363         }
364
365         /**
366          * Returns the current hostname
367          *
368          * @return string
369          *
370          * @deprecated 2019.06 - use BaseURL->getHostname() instead
371          */
372         public function getHostName()
373         {
374                 return $this->baseURL->getHostname();
375         }
376
377         /**
378          * Returns the sub-path of the full URL
379          *
380          * @return string
381          *
382          * @deprecated 2019.06 - use BaseURL->getUrlPath() instead
383          */
384         public function getURLPath()
385         {
386                 return $this->baseURL->getUrlPath();
387         }
388
389         /**
390          * @brief      Removes the base url from an url. This avoids some mixed content problems.
391          *
392          * @param string $origURL
393          *
394          * @return string The cleaned url
395          *
396          * @deprecated 2019.09 - Use BaseURL->remove() instead
397          * @see        BaseURL::remove()
398          */
399         public function removeBaseURL($origURL)
400         {
401                 return $this->baseURL->remove($origURL);
402         }
403
404         /**
405          * Returns the current UserAgent as a String
406          *
407          * @return string the UserAgent as a String
408          * @throws HTTPException\InternalServerErrorException
409          */
410         public function getUserAgent()
411         {
412                 return
413                         FRIENDICA_PLATFORM . " '" .
414                         FRIENDICA_CODENAME . "' " .
415                         FRIENDICA_VERSION . '-' .
416                         DB_UPDATE_VERSION . '; ' .
417                         $this->getBaseURL();
418         }
419
420         /**
421          * Returns true, if the call is from a backend node (f.e. from a worker)
422          *
423          * @return bool Is it a known backend?
424          *
425          * @deprecated 2019.09 - use App\Mode->isBackend() instead
426          * @see        App\Mode::isBackend()
427          * Use BaseObject::getClass(App\Mode::class) to get the global instance of Mode
428          */
429         public function isBackend()
430         {
431                 return $this->mode->isBackend();
432         }
433
434         /**
435          * @brief Checks if the maximum number of database processes is reached
436          *
437          * @return bool Is the limit reached?
438          */
439         public function isMaxProcessesReached()
440         {
441                 // Deactivated, needs more investigating if this check really makes sense
442                 return false;
443
444                 /*
445                  * Commented out to suppress static analyzer issues
446                  *
447                 if ($this->is_backend()) {
448                         $process = 'backend';
449                         $max_processes = $this->config->get('system', 'max_processes_backend');
450                         if (intval($max_processes) == 0) {
451                                 $max_processes = 5;
452                         }
453                 } else {
454                         $process = 'frontend';
455                         $max_processes = $this->config->get('system', 'max_processes_frontend');
456                         if (intval($max_processes) == 0) {
457                                 $max_processes = 20;
458                         }
459                 }
460
461                 $processlist = DBA::processlist();
462                 if ($processlist['list'] != '') {
463                         $this->logger->debug('Processcheck: Processes: ' . $processlist['amount'] . ' - Processlist: ' . $processlist['list']);
464
465                         if ($processlist['amount'] > $max_processes) {
466                                 $this->logger->debug('Processcheck: Maximum number of processes for ' . $process . ' tasks (' . $max_processes . ') reached.');
467                                 return true;
468                         }
469                 }
470                 return false;
471                  */
472         }
473
474         /**
475          * @brief Checks if the minimal memory is reached
476          *
477          * @return bool Is the memory limit reached?
478          * @throws HTTPException\InternalServerErrorException
479          */
480         public function isMinMemoryReached()
481         {
482                 $min_memory = $this->config->get('system', 'min_memory', 0);
483                 if ($min_memory == 0) {
484                         return false;
485                 }
486
487                 if (!is_readable('/proc/meminfo')) {
488                         return false;
489                 }
490
491                 $memdata = explode("\n", file_get_contents('/proc/meminfo'));
492
493                 $meminfo = [];
494                 foreach ($memdata as $line) {
495                         $data = explode(':', $line);
496                         if (count($data) != 2) {
497                                 continue;
498                         }
499                         list($key, $val) = $data;
500                         $meminfo[$key] = (int)trim(str_replace('kB', '', $val));
501                         $meminfo[$key] = (int)($meminfo[$key] / 1024);
502                 }
503
504                 if (!isset($meminfo['MemFree'])) {
505                         return false;
506                 }
507
508                 $free = $meminfo['MemFree'];
509
510                 $reached = ($free < $min_memory);
511
512                 if ($reached) {
513                         $this->logger->debug('Minimal memory reached.', ['free' => $free, 'memtotal' => $meminfo['MemTotal'], 'limit' => $min_memory]);
514                 }
515
516                 return $reached;
517         }
518
519         /**
520          * @brief Checks if the maximum load is reached
521          *
522          * @return bool Is the load reached?
523          * @throws HTTPException\InternalServerErrorException
524          */
525         public function isMaxLoadReached()
526         {
527                 if ($this->mode->isBackend()) {
528                         $process    = 'backend';
529                         $maxsysload = intval($this->config->get('system', 'maxloadavg'));
530                         if ($maxsysload < 1) {
531                                 $maxsysload = 50;
532                         }
533                 } else {
534                         $process    = 'frontend';
535                         $maxsysload = intval($this->config->get('system', 'maxloadavg_frontend'));
536                         if ($maxsysload < 1) {
537                                 $maxsysload = 50;
538                         }
539                 }
540
541                 $load = Core\System::currentLoad();
542                 if ($load) {
543                         if (intval($load) > $maxsysload) {
544                                 $this->logger->info('system load for process too high.', ['load' => $load, 'process' => $process, 'maxsysload' => $maxsysload]);
545                                 return true;
546                         }
547                 }
548                 return false;
549         }
550
551         /**
552          * Executes a child process with 'proc_open'
553          *
554          * @param string $command The command to execute
555          * @param array  $args    Arguments to pass to the command ( [ 'key' => value, 'key2' => value2, ... ]
556          *
557          * @throws HTTPException\InternalServerErrorException
558          */
559         public function proc_run($command, $args)
560         {
561                 if (!function_exists('proc_open')) {
562                         return;
563                 }
564
565                 $cmdline = $this->config->get('config', 'php_path', 'php') . ' ' . escapeshellarg($command);
566
567                 foreach ($args as $key => $value) {
568                         if (!is_null($value) && is_bool($value) && !$value) {
569                                 continue;
570                         }
571
572                         $cmdline .= ' --' . $key;
573                         if (!is_null($value) && !is_bool($value)) {
574                                 $cmdline .= ' ' . $value;
575                         }
576                 }
577
578                 if ($this->isMinMemoryReached()) {
579                         return;
580                 }
581
582                 if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
583                         $resource = proc_open('cmd /c start /b ' . $cmdline, [], $foo, $this->getBasePath());
584                 } else {
585                         $resource = proc_open($cmdline . ' &', [], $foo, $this->getBasePath());
586                 }
587                 if (!is_resource($resource)) {
588                         $this->logger->debug('We got no resource for command.', ['cmd' => $cmdline]);
589                         return;
590                 }
591                 proc_close($resource);
592         }
593
594         /**
595          * Generates the site's default sender email address
596          *
597          * @return string
598          * @throws HTTPException\InternalServerErrorException
599          */
600         public function getSenderEmailAddress()
601         {
602                 $sender_email = $this->config->get('config', 'sender_email');
603                 if (empty($sender_email)) {
604                         $hostname = $this->baseURL->getHostname();
605                         if (strpos($hostname, ':')) {
606                                 $hostname = substr($hostname, 0, strpos($hostname, ':'));
607                         }
608
609                         $sender_email = 'noreply@' . $hostname;
610                 }
611
612                 return $sender_email;
613         }
614
615         /**
616          * Returns the current theme name.
617          *
618          * @return string the name of the current theme
619          * @throws HTTPException\InternalServerErrorException
620          */
621         public function getCurrentTheme()
622         {
623                 if ($this->mode->isInstall()) {
624                         return '';
625                 }
626
627                 if (!$this->currentTheme) {
628                         $this->computeCurrentTheme();
629                 }
630
631                 return $this->currentTheme;
632         }
633
634         public function setCurrentTheme($theme)
635         {
636                 $this->currentTheme = $theme;
637         }
638
639         /**
640          * Computes the current theme name based on the node settings, the user settings and the device type
641          *
642          * @throws Exception
643          */
644         private function computeCurrentTheme()
645         {
646                 $system_theme = $this->config->get('system', 'theme');
647                 if (!$system_theme) {
648                         throw new Exception($this->l10n->t('No system theme config value set.'));
649                 }
650
651                 // Sane default
652                 $this->currentTheme = $system_theme;
653
654                 $page_theme = null;
655                 // Find the theme that belongs to the user whose stuff we are looking at
656                 if ($this->profile_uid && ($this->profile_uid != local_user())) {
657                         // Allow folks to override user themes and always use their own on their own site.
658                         // This works only if the user is on the same server
659                         $user = $this->database->selectFirst('user', ['theme'], ['uid' => $this->profile_uid]);
660                         if ($this->database->isResult($user) && !Core\PConfig::get(local_user(), 'system', 'always_my_theme')) {
661                                 $page_theme = $user['theme'];
662                         }
663                 }
664
665                 $user_theme = Core\Session::get('theme', $system_theme);
666
667                 // Specific mobile theme override
668                 if (($this->is_mobile || $this->is_tablet) && Core\Session::get('show-mobile', true)) {
669                         $system_mobile_theme = $this->config->get('system', 'mobile-theme');
670                         $user_mobile_theme   = Core\Session::get('mobile-theme', $system_mobile_theme);
671
672                         // --- means same mobile theme as desktop
673                         if (!empty($user_mobile_theme) && $user_mobile_theme !== '---') {
674                                 $user_theme = $user_mobile_theme;
675                         }
676                 }
677
678                 if ($page_theme) {
679                         $theme_name = $page_theme;
680                 } else {
681                         $theme_name = $user_theme;
682                 }
683
684                 $theme_name = Strings::sanitizeFilePathItem($theme_name);
685                 if ($theme_name
686                     && in_array($theme_name, Theme::getAllowedList())
687                     && (file_exists('view/theme/' . $theme_name . '/style.css')
688                         || file_exists('view/theme/' . $theme_name . '/style.php'))
689                 ) {
690                         $this->currentTheme = $theme_name;
691                 }
692         }
693
694         /**
695          * @brief Return full URL to theme which is currently in effect.
696          *
697          * Provide a sane default if nothing is chosen or the specified theme does not exist.
698          *
699          * @return string
700          * @throws HTTPException\InternalServerErrorException
701          */
702         public function getCurrentThemeStylesheetPath()
703         {
704                 return Core\Theme::getStylesheetPath($this->getCurrentTheme());
705         }
706
707         /**
708          * Check if request was an AJAX (xmlhttprequest) request.
709          *
710          * @return boolean true if it was an AJAX request
711          */
712         public function isAjax()
713         {
714                 return $this->isAjax;
715         }
716
717         /**
718          * @deprecated use Arguments->get() instead
719          *
720          * @see        App\Arguments
721          */
722         public function getArgumentValue($position, $default = '')
723         {
724                 return $this->args->get($position, $default);
725         }
726
727         /**
728          * Sets the base url for use in cmdline programs which don't have
729          * $_SERVER variables
730          */
731         public function checkURL()
732         {
733                 $url = $this->config->get('system', 'url');
734
735                 // if the url isn't set or the stored url is radically different
736                 // than the currently visited url, store the current value accordingly.
737                 // "Radically different" ignores common variations such as http vs https
738                 // and www.example.com vs example.com.
739                 // We will only change the url to an ip address if there is no existing setting
740
741                 if (empty($url) || (!Util\Strings::compareLink($url, $this->getBaseURL())) && (!preg_match("/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/", $this->baseURL->getHostname()))) {
742                         $this->config->set('system', 'url', $this->getBaseURL());
743                 }
744         }
745
746         /**
747          * Frontend App script
748          *
749          * The App object behaves like a container and a dispatcher at the same time, including a representation of the
750          * request and a representation of the response.
751          *
752          * This probably should change to limit the size of this monster method.
753          *
754          * @param App\Module $module The determined module
755          */
756         public function runFrontend(App\Module $module, App\Router $router, PConfiguration $pconfig)
757         {
758                 $moduleName = $module->getName();
759
760                 try {
761                         // Missing DB connection: ERROR
762                         if ($this->mode->has(App\Mode::LOCALCONFIGPRESENT) && !$this->mode->has(App\Mode::DBAVAILABLE)) {
763                                 throw new HTTPException\InternalServerErrorException('Apologies but the website is unavailable at the moment.');
764                         }
765
766                         // Max Load Average reached: ERROR
767                         if ($this->isMaxProcessesReached() || $this->isMaxLoadReached()) {
768                                 header('Retry-After: 120');
769                                 header('Refresh: 120; url=' . $this->baseURL->get() . "/" . $this->args->getQueryString());
770
771                                 throw new HTTPException\ServiceUnavailableException('The node is currently overloaded. Please try again later.');
772                         }
773
774                         if (!$this->mode->isInstall()) {
775                                 // Force SSL redirection
776                                 if ($this->baseURL->checkRedirectHttps()) {
777                                         System::externalRedirect($this->baseURL->get() . '/' . $this->args->getQueryString());
778                                 }
779
780                                 Core\Session::init();
781                                 Core\Hook::callAll('init_1');
782                         }
783
784                         // Exclude the backend processes from the session management
785                         if (!$this->mode->isBackend()) {
786                                 $stamp1 = microtime(true);
787                                 session_start();
788                                 $this->profiler->saveTimestamp($stamp1, 'parser', Core\System::callstack());
789                                 $this->l10n->setSessionVariable();
790                                 $this->l10n->setLangFromSession();
791                         } else {
792                                 $_SESSION = [];
793                                 Core\Worker::executeIfIdle();
794                         }
795
796                         if ($this->mode->isNormal()) {
797                                 $requester = HTTPSignature::getSigner('', $_SERVER);
798                                 if (!empty($requester)) {
799                                         Profile::addVisitorCookieForHandle($requester);
800                                 }
801                         }
802
803                         // ZRL
804                         if (!empty($_GET['zrl']) && $this->mode->isNormal()) {
805                                 if (!local_user()) {
806                                         // Only continue when the given profile link seems valid
807                                         // Valid profile links contain a path with "/profile/" and no query parameters
808                                         if ((parse_url($_GET['zrl'], PHP_URL_QUERY) == "") &&
809                                             strstr(parse_url($_GET['zrl'], PHP_URL_PATH), "/profile/")) {
810                                                 if (Core\Session::get('visitor_home') != $_GET["zrl"]) {
811                                                         Core\Session::set('my_url', $_GET['zrl']);
812                                                         Core\Session::set('authenticated', 0);
813                                                 }
814
815                                                 Model\Profile::zrlInit($this);
816                                         } else {
817                                                 // Someone came with an invalid parameter, maybe as a DDoS attempt
818                                                 // We simply stop processing here
819                                                 $this->logger->debug('Invalid ZRL parameter.', ['zrl' => $_GET['zrl']]);
820                                                 throw new HTTPException\ForbiddenException();
821                                         }
822                                 }
823                         }
824
825                         if (!empty($_GET['owt']) && $this->mode->isNormal()) {
826                                 $token = $_GET['owt'];
827                                 Model\Profile::openWebAuthInit($token);
828                         }
829
830                         Login::sessionAuth();
831
832                         if (empty($_SESSION['authenticated'])) {
833                                 header('X-Account-Management-Status: none');
834                         }
835
836                         $_SESSION['sysmsg']       = Core\Session::get('sysmsg', []);
837                         $_SESSION['sysmsg_info']  = Core\Session::get('sysmsg_info', []);
838                         $_SESSION['last_updated'] = Core\Session::get('last_updated', []);
839
840                         /*
841                          * check_config() is responsible for running update scripts. These automatically
842                          * update the DB schema whenever we push a new one out. It also checks to see if
843                          * any addons have been added or removed and reacts accordingly.
844                          */
845
846                         // in install mode, any url loads install module
847                         // but we need "view" module for stylesheet
848                         if ($this->mode->isInstall() && $moduleName !== 'install') {
849                                 $this->internalRedirect('install');
850                         } elseif (!$this->mode->isInstall() && !$this->mode->has(App\Mode::MAINTENANCEDISABLED) && $moduleName !== 'maintenance') {
851                                 $this->internalRedirect('maintenance');
852                         } else {
853                                 $this->checkURL();
854                                 Core\Update::check($this->getBasePath(), false, $this->mode);
855                                 Core\Addon::loadAddons();
856                                 Core\Hook::loadHooks();
857                         }
858
859                         // Compatibility with the Android Diaspora client
860                         if ($moduleName == 'stream') {
861                                 $this->internalRedirect('network?order=post');
862                         }
863
864                         if ($moduleName == 'conversations') {
865                                 $this->internalRedirect('message');
866                         }
867
868                         if ($moduleName == 'commented') {
869                                 $this->internalRedirect('network?order=comment');
870                         }
871
872                         if ($moduleName == 'liked') {
873                                 $this->internalRedirect('network?order=comment');
874                         }
875
876                         if ($moduleName == 'activity') {
877                                 $this->internalRedirect('network?conv=1');
878                         }
879
880                         if (($moduleName == 'status_messages') && ($this->args->getCommand() == 'status_messages/new')) {
881                                 $this->internalRedirect('bookmarklet');
882                         }
883
884                         if (($moduleName == 'user') && ($this->args->getCommand() == 'user/edit')) {
885                                 $this->internalRedirect('settings');
886                         }
887
888                         if (($moduleName == 'tag_followings') && ($this->args->getCommand() == 'tag_followings/manage')) {
889                                 $this->internalRedirect('search');
890                         }
891
892                         // Initialize module that can set the current theme in the init() method, either directly or via App->profile_uid
893                         $this->page['page_title'] = $moduleName;
894
895                         // determine the module class and save it to the module instance
896                         // @todo there's an implicit dependency due SESSION::start(), so it has to be called here (yet)
897                         $module = $module->determineClass($this->args, $router, $this->config);
898
899                         // Let the module run it's internal process (init, get, post, ...)
900                         $module->run($this->l10n, $this, $this->logger, $this->getCurrentTheme(), $_SERVER, $_POST);
901
902                 } catch (HTTPException $e) {
903                         ModuleHTTPException::rawContent($e);
904                 }
905
906                 $this->page->run($this, $this->baseURL, $this->mode, $module, $this->l10n, $this->config, $pconfig);
907         }
908
909         /**
910          * Redirects to another module relative to the current Friendica base.
911          * If you want to redirect to a external URL, use System::externalRedirectTo()
912          *
913          * @param string $toUrl The destination URL (Default is empty, which is the default page of the Friendica node)
914          * @param bool   $ssl   if true, base URL will try to get called with https:// (works just for relative paths)
915          *
916          * @throws HTTPException\InternalServerErrorException In Case the given URL is not relative to the Friendica node
917          */
918         public function internalRedirect($toUrl = '', $ssl = false)
919         {
920                 if (!empty(parse_url($toUrl, PHP_URL_SCHEME))) {
921                         throw new HTTPException\InternalServerErrorException("'$toUrl is not a relative path, please use System::externalRedirectTo");
922                 }
923
924                 $redirectTo = $this->baseURL->get($ssl) . '/' . ltrim($toUrl, '/');
925                 Core\System::externalRedirect($redirectTo);
926         }
927
928         /**
929          * Automatically redirects to relative or absolute URL
930          * Should only be used if it isn't clear if the URL is either internal or external
931          *
932          * @param string $toUrl The target URL
933          *
934          * @throws HTTPException\InternalServerErrorException
935          */
936         public function redirect($toUrl)
937         {
938                 if (!empty(parse_url($toUrl, PHP_URL_SCHEME))) {
939                         Core\System::externalRedirect($toUrl);
940                 } else {
941                         $this->internalRedirect($toUrl);
942                 }
943         }
944 }