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