]> git.mxchange.org Git - friendica.git/blob - src/App.php
Create own base URL class which holds the whole base url business logic
[friendica.git] / src / App.php
1 <?php
2 /**
3  * @file src/App.php
4  */
5 namespace Friendica;
6
7 use Detection\MobileDetect;
8 use DOMDocument;
9 use DOMXPath;
10 use Exception;
11 use Friendica\Core\Config\Cache\IConfigCache;
12 use Friendica\Core\Config\Configuration;
13 use Friendica\Core\Hook;
14 use Friendica\Core\Theme;
15 use Friendica\Database\DBA;
16 use Friendica\Model\Profile;
17 use Friendica\Network\HTTPException\InternalServerErrorException;
18 use Friendica\Util\BaseURL;
19 use Friendica\Util\Config\ConfigFileLoader;
20 use Friendica\Util\HTTPSignature;
21 use Friendica\Util\Profiler;
22 use Friendica\Util\Strings;
23 use Psr\Log\LoggerInterface;
24
25 /**
26  *
27  * class: App
28  *
29  * @brief Our main application structure for the life of this page.
30  *
31  * Primarily deals with the URL that got us here
32  * and tries to make some sense of it, and
33  * stores our page contents and config storage
34  * and anything else that might need to be passed around
35  * before we spit the page out.
36  *
37  */
38 class App
39 {
40         public $module_class = null;
41         public $query_string = '';
42         public $page = [];
43         public $profile;
44         public $profile_uid;
45         public $user;
46         public $cid;
47         public $contact;
48         public $contacts;
49         public $page_contact;
50         public $content;
51         public $data = [];
52         public $error = false;
53         public $cmd = '';
54         public $argv;
55         public $argc;
56         public $module;
57         public $timezone;
58         public $interactive = true;
59         public $identities;
60         public $is_mobile = false;
61         public $is_tablet = false;
62         public $theme_info = [];
63         public $category;
64         // Allow themes to control internal parameters
65         // by changing App values in theme.php
66
67         public $sourcename = '';
68         public $videowidth = 425;
69         public $videoheight = 350;
70         public $force_max_items = 0;
71         public $theme_events_in_profile = true;
72
73         public $stylesheets = [];
74         public $footerScripts = [];
75
76         /**
77          * @var App\Mode The Mode of the Application
78          */
79         private $mode;
80
81         /**
82          * @var App\Router
83          */
84         private $router;
85
86         /**
87          * @var BaseURL
88          */
89         private $baseURL;
90
91         /**
92          * @var bool true, if the call is from the Friendica APP, otherwise false
93          */
94         private $isFriendicaApp;
95
96         /**
97          * @var bool true, if the call is from an backend node (f.e. worker)
98          */
99         private $isBackend;
100
101         /**
102          * @var string The name of the current theme
103          */
104         private $currentTheme;
105
106         /**
107          * @var bool check if request was an AJAX (xmlhttprequest) request
108          */
109         private $isAjax;
110
111         /**
112          * @var MobileDetect
113          */
114         public $mobileDetect;
115
116         /**
117          * @var Configuration The config
118          */
119         private $config;
120
121         /**
122          * @var LoggerInterface The logger
123          */
124         private $logger;
125
126         /**
127          * @var Profiler The profiler of this app
128          */
129         private $profiler;
130
131         /**
132          * Returns the current config cache of this node
133          *
134          * @return IConfigCache
135          */
136         public function getConfigCache()
137         {
138                 return $this->config->getCache();
139         }
140
141         /**
142          * The basepath of this app
143          *
144          * @return string
145          */
146         public function getBasePath()
147         {
148                 return $this->config->get('system', 'basepath');
149         }
150
151         /**
152          * The Logger of this app
153          *
154          * @return LoggerInterface
155          */
156         public function getLogger()
157         {
158                 return $this->logger;
159         }
160
161         /**
162          * The profiler of this app
163          *
164          * @return Profiler
165          */
166         public function getProfiler()
167         {
168                 return $this->profiler;
169         }
170
171         /**
172          * Returns the Mode of the Application
173          *
174          * @return App\Mode The Application Mode
175          */
176         public function getMode()
177         {
178                 return $this->mode;
179         }
180
181         /**
182          * Returns the router of the Application
183          *
184          * @return App\Router
185          */
186         public function getRouter()
187         {
188                 return $this->router;
189         }
190
191         /**
192          * Register a stylesheet file path to be included in the <head> tag of every page.
193          * Inclusion is done in App->initHead().
194          * The path can be absolute or relative to the Friendica installation base folder.
195          *
196          * @see initHead()
197          *
198          * @param string $path
199          * @throws InternalServerErrorException
200          */
201         public function registerStylesheet($path)
202         {
203                 if (mb_strpos($path, $this->getBasePath() . DIRECTORY_SEPARATOR) === 0) {
204                         $path = mb_substr($path, mb_strlen($this->getBasePath() . DIRECTORY_SEPARATOR));
205                 }
206
207                 $this->stylesheets[] = trim($path, '/');
208         }
209
210         /**
211          * Register a javascript file path to be included in the <footer> tag of every page.
212          * Inclusion is done in App->initFooter().
213          * The path can be absolute or relative to the Friendica installation base folder.
214          *
215          * @see initFooter()
216          *
217          * @param string $path
218          * @throws InternalServerErrorException
219          */
220         public function registerFooterScript($path)
221         {
222                 $url = str_replace($this->getBasePath() . DIRECTORY_SEPARATOR, '', $path);
223
224                 $this->footerScripts[] = trim($url, '/');
225         }
226
227         public $queue;
228
229         /**
230          * @brief App constructor.
231          *
232          * @param Configuration    $config    The Configuration
233          * @param App\Mode         $mode      The mode of this Friendica app
234          * @param App\Router       $router    The router of this Friendica app
235          * @param BaseURL          $baseURL   The full base URL of this Friendica app
236          * @param LoggerInterface  $logger    The current app logger
237          * @param Profiler         $profiler  The profiler of this application
238          * @param bool             $isBackend Whether it is used for backend or frontend (Default true=backend)
239          *
240          * @throws Exception if the Basepath is not usable
241          */
242         public function __construct(Configuration $config, App\Mode $mode, App\Router $router, BaseURL $baseURL, LoggerInterface $logger, Profiler $profiler, $isBackend = true)
243         {
244                 BaseObject::setApp($this);
245
246                 $this->config   = $config;
247                 $this->mode     = $mode;
248                 $this->router   = $router;
249                 $this->baseURL  = $baseURL;
250                 $this->profiler = $profiler;
251                 $this->logger   = $logger;
252
253                 $this->checkBackend($isBackend);
254                 $this->checkFriendicaApp();
255
256                 $this->profiler->reset();
257
258                 $this->reload();
259
260                 set_time_limit(0);
261
262                 // This has to be quite large to deal with embedded private photos
263                 ini_set('pcre.backtrack_limit', 500000);
264
265                 set_include_path(
266                         get_include_path() . PATH_SEPARATOR
267                         . $this->getBasePath() . DIRECTORY_SEPARATOR . 'include' . PATH_SEPARATOR
268                         . $this->getBasePath() . DIRECTORY_SEPARATOR . 'library' . PATH_SEPARATOR
269                         . $this->getBasePath());
270
271                 if (!empty($_SERVER['QUERY_STRING']) && strpos($_SERVER['QUERY_STRING'], 'pagename=') === 0) {
272                         $this->query_string = substr($_SERVER['QUERY_STRING'], 9);
273                 } elseif (!empty($_SERVER['QUERY_STRING']) && strpos($_SERVER['QUERY_STRING'], 'q=') === 0) {
274                         $this->query_string = substr($_SERVER['QUERY_STRING'], 2);
275                 }
276
277                 // removing trailing / - maybe a nginx problem
278                 $this->query_string = ltrim($this->query_string, '/');
279
280                 if (!empty($_GET['pagename'])) {
281                         $this->cmd = trim($_GET['pagename'], '/\\');
282                 } elseif (!empty($_GET['q'])) {
283                         $this->cmd = trim($_GET['q'], '/\\');
284                 }
285
286                 // fix query_string
287                 $this->query_string = str_replace($this->cmd . '&', $this->cmd . '?', $this->query_string);
288
289                 // unix style "homedir"
290                 if (substr($this->cmd, 0, 1) === '~') {
291                         $this->cmd = 'profile/' . substr($this->cmd, 1);
292                 }
293
294                 // Diaspora style profile url
295                 if (substr($this->cmd, 0, 2) === 'u/') {
296                         $this->cmd = 'profile/' . substr($this->cmd, 2);
297                 }
298
299                 /*
300                  * Break the URL path into C style argc/argv style arguments for our
301                  * modules. Given "http://example.com/module/arg1/arg2", $this->argc
302                  * will be 3 (integer) and $this->argv will contain:
303                  *   [0] => 'module'
304                  *   [1] => 'arg1'
305                  *   [2] => 'arg2'
306                  *
307                  *
308                  * There will always be one argument. If provided a naked domain
309                  * URL, $this->argv[0] is set to "home".
310                  */
311
312                 $this->argv = explode('/', $this->cmd);
313                 $this->argc = count($this->argv);
314                 if ((array_key_exists('0', $this->argv)) && strlen($this->argv[0])) {
315                         $this->module = str_replace('.', '_', $this->argv[0]);
316                         $this->module = str_replace('-', '_', $this->module);
317                 } else {
318                         $this->argc = 1;
319                         $this->argv = ['home'];
320                         $this->module = 'home';
321                 }
322
323                 // Detect mobile devices
324                 $mobile_detect = new MobileDetect();
325
326                 $this->mobileDetect = $mobile_detect;
327
328                 $this->is_mobile = $mobile_detect->isMobile();
329                 $this->is_tablet = $mobile_detect->isTablet();
330
331                 $this->isAjax = strtolower(defaults($_SERVER, 'HTTP_X_REQUESTED_WITH', '')) == 'xmlhttprequest';
332
333                 // Register template engines
334                 Core\Renderer::registerTemplateEngine('Friendica\Render\FriendicaSmartyEngine');
335         }
336
337         /**
338          * Reloads the whole app instance
339          */
340         public function reload()
341         {
342                 $this->getMode()->determine($this->getBasePath());
343
344                 if ($this->getMode()->has(App\Mode::DBAVAILABLE)) {
345                         $loader = new ConfigFileLoader($this->getBasePath(), $this->getMode());
346                         $this->config->getCache()->load($loader->loadCoreConfig('addon'), true);
347
348                         $this->profiler->update(
349                                 $this->config->get('system', 'profiler', false),
350                                 $this->config->get('rendertime', 'callstack', false));
351
352                         Core\Hook::loadHooks();
353                         $loader = new ConfigFileLoader($this->getBasePath(), $this->mode);
354                         Core\Hook::callAll('load_config', $loader);
355                 }
356
357                 $this->loadDefaultTimezone();
358
359                 Core\L10n::init();
360         }
361
362         /**
363          * Loads the default timezone
364          *
365          * Include support for legacy $default_timezone
366          *
367          * @global string $default_timezone
368          */
369         private function loadDefaultTimezone()
370         {
371                 if ($this->config->get('system', 'default_timezone')) {
372                         $this->timezone = $this->config->get('system', 'default_timezone');
373                 } else {
374                         global $default_timezone;
375                         $this->timezone = !empty($default_timezone) ? $default_timezone : 'UTC';
376                 }
377
378                 if ($this->timezone) {
379                         date_default_timezone_set($this->timezone);
380                 }
381         }
382
383         /**
384          * Returns the scheme of the current call
385          * @return string
386          *
387          * @deprecated 2019.06 - use BaseURL->getScheme() instead
388          */
389         public function getScheme()
390         {
391                 return $this->baseURL->getScheme();
392         }
393
394         /**
395          * Retrieves the Friendica instance base URL
396          *
397          * @param bool $ssl Whether to append http or https under BaseURL::SSL_POLICY_SELFSIGN
398          *
399          * @return string Friendica server base URL
400          *
401          * @deprecated 2019.06 - use BaseURL->get($ssl) instead
402          */
403         public function getBaseURL($ssl = false)
404         {
405                 return $this->baseURL->get($ssl);
406         }
407
408         /**
409          * @brief Initializes the baseurl components
410          *
411          * Clears the baseurl cache to prevent inconsistencies
412          *
413          * @param string $url
414          *
415          * @deprecated 2019.06 - use BaseURL->saveByURL($url) instead
416          */
417         public function setBaseURL($url)
418         {
419                 $this->baseURL->saveByURL($url);
420         }
421
422         /**
423          * Returns the current hostname
424          *
425          * @return string
426          *
427          * @deprecated 2019.06 - use BaseURL->getHostname() instead
428          */
429         public function getHostName()
430         {
431                 return $this->baseURL->getHostname();
432         }
433
434         /**
435          * Returns the sub-path of the full URL
436          *
437          * @return string
438          *
439          * @deprecated 2019.06 - use BaseURL->getUrlPath() instead
440          */
441         public function getURLPath()
442         {
443                 return $this->baseURL->getUrlPath();
444         }
445
446         /**
447          * Initializes App->page['htmlhead'].
448          *
449          * Includes:
450          * - Page title
451          * - Favicons
452          * - Registered stylesheets (through App->registerStylesheet())
453          * - Infinite scroll data
454          * - head.tpl template
455          */
456         public function initHead()
457         {
458                 $interval = ((local_user()) ? Core\PConfig::get(local_user(), 'system', 'update_interval') : 40000);
459
460                 // If the update is 'deactivated' set it to the highest integer number (~24 days)
461                 if ($interval < 0) {
462                         $interval = 2147483647;
463                 }
464
465                 if ($interval < 10000) {
466                         $interval = 40000;
467                 }
468
469                 // Default title: current module called
470                 if (empty($this->page['title']) && $this->module) {
471                         $this->page['title'] = ucfirst($this->module);
472                 }
473
474                 // Prepend the sitename to the page title
475                 $this->page['title'] = $this->config->get('config', 'sitename', '') . (!empty($this->page['title']) ? ' | ' . $this->page['title'] : '');
476
477                 if (!empty(Core\Renderer::$theme['stylesheet'])) {
478                         $stylesheet = Core\Renderer::$theme['stylesheet'];
479                 } else {
480                         $stylesheet = $this->getCurrentThemeStylesheetPath();
481                 }
482
483                 $this->registerStylesheet($stylesheet);
484
485                 $shortcut_icon = $this->config->get('system', 'shortcut_icon');
486                 if ($shortcut_icon == '') {
487                         $shortcut_icon = 'images/friendica-32.png';
488                 }
489
490                 $touch_icon = $this->config->get('system', 'touch_icon');
491                 if ($touch_icon == '') {
492                         $touch_icon = 'images/friendica-128.png';
493                 }
494
495                 Core\Hook::callAll('head', $this->page['htmlhead']);
496
497                 $tpl = Core\Renderer::getMarkupTemplate('head.tpl');
498                 /* put the head template at the beginning of page['htmlhead']
499                  * since the code added by the modules frequently depends on it
500                  * being first
501                  */
502                 $this->page['htmlhead'] = Core\Renderer::replaceMacros($tpl, [
503                         '$baseurl'         => $this->getBaseURL(),
504                         '$local_user'      => local_user(),
505                         '$generator'       => 'Friendica' . ' ' . FRIENDICA_VERSION,
506                         '$delitem'         => Core\L10n::t('Delete this item?'),
507                         '$update_interval' => $interval,
508                         '$shortcut_icon'   => $shortcut_icon,
509                         '$touch_icon'      => $touch_icon,
510                         '$block_public'    => intval($this->config->get('system', 'block_public')),
511                         '$stylesheets'     => $this->stylesheets,
512                 ]) . $this->page['htmlhead'];
513         }
514
515         /**
516          * Initializes App->page['footer'].
517          *
518          * Includes:
519          * - Javascript homebase
520          * - Mobile toggle link
521          * - Registered footer scripts (through App->registerFooterScript())
522          * - footer.tpl template
523          */
524         public function initFooter()
525         {
526                 // If you're just visiting, let javascript take you home
527                 if (!empty($_SESSION['visitor_home'])) {
528                         $homebase = $_SESSION['visitor_home'];
529                 } elseif (local_user()) {
530                         $homebase = 'profile/' . $this->user['nickname'];
531                 }
532
533                 if (isset($homebase)) {
534                         $this->page['footer'] .= '<script>var homebase="' . $homebase . '";</script>' . "\n";
535                 }
536
537                 /*
538                  * Add a "toggle mobile" link if we're using a mobile device
539                  */
540                 if ($this->is_mobile || $this->is_tablet) {
541                         if (isset($_SESSION['show-mobile']) && !$_SESSION['show-mobile']) {
542                                 $link = 'toggle_mobile?address=' . urlencode(curPageURL());
543                         } else {
544                                 $link = 'toggle_mobile?off=1&address=' . urlencode(curPageURL());
545                         }
546                         $this->page['footer'] .= Core\Renderer::replaceMacros(Core\Renderer::getMarkupTemplate("toggle_mobile_footer.tpl"), [
547                                 '$toggle_link' => $link,
548                                 '$toggle_text' => Core\L10n::t('toggle mobile')
549                         ]);
550                 }
551
552                 Core\Hook::callAll('footer', $this->page['footer']);
553
554                 $tpl = Core\Renderer::getMarkupTemplate('footer.tpl');
555                 $this->page['footer'] = Core\Renderer::replaceMacros($tpl, [
556                         '$baseurl' => $this->getBaseURL(),
557                         '$footerScripts' => $this->footerScripts,
558                 ]) . $this->page['footer'];
559         }
560
561         /**
562          * @brief Removes the base url from an url. This avoids some mixed content problems.
563          *
564          * @param string $origURL
565          *
566          * @return string The cleaned url
567          * @throws InternalServerErrorException
568          */
569         public function removeBaseURL($origURL)
570         {
571                 // Remove the hostname from the url if it is an internal link
572                 $nurl = Util\Strings::normaliseLink($origURL);
573                 $base = Util\Strings::normaliseLink($this->getBaseURL());
574                 $url = str_replace($base . '/', '', $nurl);
575
576                 // if it is an external link return the orignal value
577                 if ($url == Util\Strings::normaliseLink($origURL)) {
578                         return $origURL;
579                 } else {
580                         return $url;
581                 }
582         }
583
584         /**
585          * Returns the current UserAgent as a String
586          *
587          * @return string the UserAgent as a String
588          * @throws InternalServerErrorException
589          */
590         public function getUserAgent()
591         {
592                 return
593                         FRIENDICA_PLATFORM . " '" .
594                         FRIENDICA_CODENAME . "' " .
595                         FRIENDICA_VERSION . '-' .
596                         DB_UPDATE_VERSION . '; ' .
597                         $this->getBaseURL();
598         }
599
600         /**
601          * Checks, if the call is from the Friendica App
602          *
603          * Reason:
604          * The friendica client has problems with the GUID in the notify. this is some workaround
605          */
606         private function checkFriendicaApp()
607         {
608                 // Friendica-Client
609                 $this->isFriendicaApp = isset($_SERVER['HTTP_USER_AGENT']) && $_SERVER['HTTP_USER_AGENT'] == 'Apache-HttpClient/UNAVAILABLE (java 1.4)';
610         }
611
612         /**
613          *      Is the call via the Friendica app? (not a "normale" call)
614          *
615          * @return bool true if it's from the Friendica app
616          */
617         public function isFriendicaApp()
618         {
619                 return $this->isFriendicaApp;
620         }
621
622         /**
623          * @brief Checks if the site is called via a backend process
624          *
625          * This isn't a perfect solution. But we need this check very early.
626          * So we cannot wait until the modules are loaded.
627          *
628          * @param string $backend true, if the backend flag was set during App initialization
629          *
630          */
631         private function checkBackend($backend) {
632                 static $backends = [
633                         '_well_known',
634                         'api',
635                         'dfrn_notify',
636                         'fetch',
637                         'hcard',
638                         'hostxrd',
639                         'manifest',
640                         'nodeinfo',
641                         'noscrape',
642                         'p',
643                         'poco',
644                         'post',
645                         'proxy',
646                         'pubsub',
647                         'pubsubhubbub',
648                         'receive',
649                         'rsd_xml',
650                         'salmon',
651                         'statistics_json',
652                         'xrd',
653                 ];
654
655                 // Check if current module is in backend or backend flag is set
656                 $this->isBackend = (in_array($this->module, $backends) || $backend || $this->isBackend);
657         }
658
659         /**
660          * Returns true, if the call is from a backend node (f.e. from a worker)
661          *
662          * @return bool Is it a known backend?
663          */
664         public function isBackend()
665         {
666                 return $this->isBackend;
667         }
668
669         /**
670          * @brief Checks if the maximum number of database processes is reached
671          *
672          * @return bool Is the limit reached?
673          */
674         public function isMaxProcessesReached()
675         {
676                 // Deactivated, needs more investigating if this check really makes sense
677                 return false;
678
679                 /*
680                  * Commented out to suppress static analyzer issues
681                  *
682                 if ($this->is_backend()) {
683                         $process = 'backend';
684                         $max_processes = $this->config->get('system', 'max_processes_backend');
685                         if (intval($max_processes) == 0) {
686                                 $max_processes = 5;
687                         }
688                 } else {
689                         $process = 'frontend';
690                         $max_processes = $this->config->get('system', 'max_processes_frontend');
691                         if (intval($max_processes) == 0) {
692                                 $max_processes = 20;
693                         }
694                 }
695
696                 $processlist = DBA::processlist();
697                 if ($processlist['list'] != '') {
698                         Core\Logger::log('Processcheck: Processes: ' . $processlist['amount'] . ' - Processlist: ' . $processlist['list'], Core\Logger::DEBUG);
699
700                         if ($processlist['amount'] > $max_processes) {
701                                 Core\Logger::log('Processcheck: Maximum number of processes for ' . $process . ' tasks (' . $max_processes . ') reached.', Core\Logger::DEBUG);
702                                 return true;
703                         }
704                 }
705                 return false;
706                  */
707         }
708
709         /**
710          * @brief Checks if the minimal memory is reached
711          *
712          * @return bool Is the memory limit reached?
713          * @throws InternalServerErrorException
714          */
715         public function isMinMemoryReached()
716         {
717                 $min_memory = $this->config->get('system', 'min_memory', 0);
718                 if ($min_memory == 0) {
719                         return false;
720                 }
721
722                 if (!is_readable('/proc/meminfo')) {
723                         return false;
724                 }
725
726                 $memdata = explode("\n", file_get_contents('/proc/meminfo'));
727
728                 $meminfo = [];
729                 foreach ($memdata as $line) {
730                         $data = explode(':', $line);
731                         if (count($data) != 2) {
732                                 continue;
733                         }
734                         list($key, $val) = $data;
735                         $meminfo[$key] = (int) trim(str_replace('kB', '', $val));
736                         $meminfo[$key] = (int) ($meminfo[$key] / 1024);
737                 }
738
739                 if (!isset($meminfo['MemFree'])) {
740                         return false;
741                 }
742
743                 $free = $meminfo['MemFree'];
744
745                 $reached = ($free < $min_memory);
746
747                 if ($reached) {
748                         Core\Logger::log('Minimal memory reached: ' . $free . '/' . $meminfo['MemTotal'] . ' - limit ' . $min_memory, Core\Logger::DEBUG);
749                 }
750
751                 return $reached;
752         }
753
754         /**
755          * @brief Checks if the maximum load is reached
756          *
757          * @return bool Is the load reached?
758          * @throws InternalServerErrorException
759          */
760         public function isMaxLoadReached()
761         {
762                 if ($this->isBackend()) {
763                         $process = 'backend';
764                         $maxsysload = intval($this->config->get('system', 'maxloadavg'));
765                         if ($maxsysload < 1) {
766                                 $maxsysload = 50;
767                         }
768                 } else {
769                         $process = 'frontend';
770                         $maxsysload = intval($this->config->get('system', 'maxloadavg_frontend'));
771                         if ($maxsysload < 1) {
772                                 $maxsysload = 50;
773                         }
774                 }
775
776                 $load = Core\System::currentLoad();
777                 if ($load) {
778                         if (intval($load) > $maxsysload) {
779                                 Core\Logger::log('system: load ' . $load . ' for ' . $process . ' tasks (' . $maxsysload . ') too high.');
780                                 return true;
781                         }
782                 }
783                 return false;
784         }
785
786         /**
787          * Executes a child process with 'proc_open'
788          *
789          * @param string $command The command to execute
790          * @param array  $args    Arguments to pass to the command ( [ 'key' => value, 'key2' => value2, ... ]
791          * @throws InternalServerErrorException
792          */
793         public function proc_run($command, $args)
794         {
795                 if (!function_exists('proc_open')) {
796                         return;
797                 }
798
799                 $cmdline = $this->config->get('config', 'php_path', 'php') . ' ' . escapeshellarg($command);
800
801                 foreach ($args as $key => $value) {
802                         if (!is_null($value) && is_bool($value) && !$value) {
803                                 continue;
804                         }
805
806                         $cmdline .= ' --' . $key;
807                         if (!is_null($value) && !is_bool($value)) {
808                                 $cmdline .= ' ' . $value;
809                         }
810                 }
811
812                 if ($this->isMinMemoryReached()) {
813                         return;
814                 }
815
816                 if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
817                         $resource = proc_open('cmd /c start /b ' . $cmdline, [], $foo, $this->getBasePath());
818                 } else {
819                         $resource = proc_open($cmdline . ' &', [], $foo, $this->getBasePath());
820                 }
821                 if (!is_resource($resource)) {
822                         Core\Logger::log('We got no resource for command ' . $cmdline, Core\Logger::DEBUG);
823                         return;
824                 }
825                 proc_close($resource);
826         }
827
828         /**
829          * Generates the site's default sender email address
830          *
831          * @return string
832          * @throws InternalServerErrorException
833          */
834         public function getSenderEmailAddress()
835         {
836                 $sender_email = $this->config->get('config', 'sender_email');
837                 if (empty($sender_email)) {
838                         $hostname = $this->getHostName();
839                         if (strpos($hostname, ':')) {
840                                 $hostname = substr($hostname, 0, strpos($hostname, ':'));
841                         }
842
843                         $sender_email = 'noreply@' . $hostname;
844                 }
845
846                 return $sender_email;
847         }
848
849         /**
850          * Returns the current theme name.
851          *
852          * @return string the name of the current theme
853          * @throws InternalServerErrorException
854          */
855         public function getCurrentTheme()
856         {
857                 if ($this->getMode()->isInstall()) {
858                         return '';
859                 }
860
861                 if (!$this->currentTheme) {
862                         $this->computeCurrentTheme();
863                 }
864
865                 return $this->currentTheme;
866         }
867
868         public function setCurrentTheme($theme)
869         {
870                 $this->currentTheme = $theme;
871         }
872
873         /**
874          * Computes the current theme name based on the node settings, the user settings and the device type
875          *
876          * @throws Exception
877          */
878         private function computeCurrentTheme()
879         {
880                 $system_theme = $this->config->get('system', 'theme');
881                 if (!$system_theme) {
882                         throw new Exception(Core\L10n::t('No system theme config value set.'));
883                 }
884
885                 // Sane default
886                 $this->currentTheme = $system_theme;
887
888                 $page_theme = null;
889                 // Find the theme that belongs to the user whose stuff we are looking at
890                 if ($this->profile_uid && ($this->profile_uid != local_user())) {
891                         // Allow folks to override user themes and always use their own on their own site.
892                         // This works only if the user is on the same server
893                         $user = DBA::selectFirst('user', ['theme'], ['uid' => $this->profile_uid]);
894                         if (DBA::isResult($user) && !Core\PConfig::get(local_user(), 'system', 'always_my_theme')) {
895                                 $page_theme = $user['theme'];
896                         }
897                 }
898
899                 $user_theme = Core\Session::get('theme', $system_theme);
900
901                 // Specific mobile theme override
902                 if (($this->is_mobile || $this->is_tablet) && Core\Session::get('show-mobile', true)) {
903                         $system_mobile_theme = $this->config->get('system', 'mobile-theme');
904                         $user_mobile_theme = Core\Session::get('mobile-theme', $system_mobile_theme);
905
906                         // --- means same mobile theme as desktop
907                         if (!empty($user_mobile_theme) && $user_mobile_theme !== '---') {
908                                 $user_theme = $user_mobile_theme;
909                         }
910                 }
911
912                 if ($page_theme) {
913                         $theme_name = $page_theme;
914                 } else {
915                         $theme_name = $user_theme;
916                 }
917
918                 $theme_name = Strings::sanitizeFilePathItem($theme_name);
919                 if ($theme_name
920                         && in_array($theme_name, Theme::getAllowedList())
921                         && (file_exists('view/theme/' . $theme_name . '/style.css')
922                         || file_exists('view/theme/' . $theme_name . '/style.php'))
923                 ) {
924                         $this->currentTheme = $theme_name;
925                 }
926         }
927
928         /**
929          * @brief Return full URL to theme which is currently in effect.
930          *
931          * Provide a sane default if nothing is chosen or the specified theme does not exist.
932          *
933          * @return string
934          * @throws InternalServerErrorException
935          */
936         public function getCurrentThemeStylesheetPath()
937         {
938                 return Core\Theme::getStylesheetPath($this->getCurrentTheme());
939         }
940
941         /**
942          * Check if request was an AJAX (xmlhttprequest) request.
943          *
944          * @return boolean true if it was an AJAX request
945          */
946         public function isAjax()
947         {
948                 return $this->isAjax;
949         }
950
951         /**
952          * Returns the value of a argv key
953          * TODO there are a lot of $a->argv usages in combination with defaults() which can be replaced with this method
954          *
955          * @param int $position the position of the argument
956          * @param mixed $default the default value if not found
957          *
958          * @return mixed returns the value of the argument
959          */
960         public function getArgumentValue($position, $default = '')
961         {
962                 if (array_key_exists($position, $this->argv)) {
963                         return $this->argv[$position];
964                 }
965
966                 return $default;
967         }
968
969         /**
970          * Sets the base url for use in cmdline programs which don't have
971          * $_SERVER variables
972          */
973         public function checkURL()
974         {
975                 $url = $this->config->get('system', 'url');
976
977                 // if the url isn't set or the stored url is radically different
978                 // than the currently visited url, store the current value accordingly.
979                 // "Radically different" ignores common variations such as http vs https
980                 // and www.example.com vs example.com.
981                 // We will only change the url to an ip address if there is no existing setting
982
983                 if (empty($url) || (!Util\Strings::compareLink($url, $this->getBaseURL())) && (!preg_match("/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/", $this->getHostName()))) {
984                         $this->config->set('system', 'url', $this->getBaseURL());
985                 }
986         }
987
988         /**
989          * Frontend App script
990          *
991          * The App object behaves like a container and a dispatcher at the same time, including a representation of the
992          * request and a representation of the response.
993          *
994          * This probably should change to limit the size of this monster method.
995          */
996         public function runFrontend()
997         {
998                 // Missing DB connection: ERROR
999                 if ($this->getMode()->has(App\Mode::LOCALCONFIGPRESENT) && !$this->getMode()->has(App\Mode::DBAVAILABLE)) {
1000                         Core\System::httpExit(500, ['title' => 'Error 500 - Internal Server Error', 'description' => 'Apologies but the website is unavailable at the moment.']);
1001                 }
1002
1003                 // Max Load Average reached: ERROR
1004                 if ($this->isMaxProcessesReached() || $this->isMaxLoadReached()) {
1005                         header('Retry-After: 120');
1006                         header('Refresh: 120; url=' . $this->getBaseURL() . "/" . $this->query_string);
1007
1008                         Core\System::httpExit(503, ['title' => 'Error 503 - Service Temporarily Unavailable', 'description' => 'Core\System is currently overloaded. Please try again later.']);
1009                 }
1010
1011                 if (strstr($this->query_string, '.well-known/host-meta') && ($this->query_string != '.well-known/host-meta')) {
1012                         Core\System::httpExit(404);
1013                 }
1014
1015                 if (!$this->getMode()->isInstall()) {
1016                         // Force SSL redirection
1017                         if ($this->config->get('system', 'force_ssl') && ($this->getScheme() == "http")
1018                                 && intval($this->config->get('system', 'ssl_policy')) == BaseURL::SSL_POLICY_FULL
1019                                 && strpos($this->getBaseURL(), 'https://') === 0
1020                                 && $_SERVER['REQUEST_METHOD'] == 'GET') {
1021                                 header('HTTP/1.1 302 Moved Temporarily');
1022                                 header('Location: ' . $this->getBaseURL() . '/' . $this->query_string);
1023                                 exit();
1024                         }
1025
1026                         Core\Session::init();
1027                         Core\Hook::callAll('init_1');
1028                 }
1029
1030                 // Exclude the backend processes from the session management
1031                 if (!$this->isBackend()) {
1032                         $stamp1 = microtime(true);
1033                         session_start();
1034                         $this->profiler->saveTimestamp($stamp1, 'parser', Core\System::callstack());
1035                         Core\L10n::setSessionVariable();
1036                         Core\L10n::setLangFromSession();
1037                 } else {
1038                         $_SESSION = [];
1039                         Core\Worker::executeIfIdle();
1040                 }
1041
1042                 if ($this->getMode()->isNormal()) {
1043                         $requester = HTTPSignature::getSigner('', $_SERVER);
1044                         if (!empty($requester)) {
1045                                 Profile::addVisitorCookieForHandle($requester);
1046                         }
1047                 }
1048
1049                 // ZRL
1050                 if (!empty($_GET['zrl']) && $this->getMode()->isNormal()) {
1051                         $this->query_string = Model\Profile::stripZrls($this->query_string);
1052                         if (!local_user()) {
1053                                 // Only continue when the given profile link seems valid
1054                                 // Valid profile links contain a path with "/profile/" and no query parameters
1055                                 if ((parse_url($_GET['zrl'], PHP_URL_QUERY) == "") &&
1056                                         strstr(parse_url($_GET['zrl'], PHP_URL_PATH), "/profile/")) {
1057                                         if (defaults($_SESSION, "visitor_home", "") != $_GET["zrl"]) {
1058                                                 $_SESSION['my_url'] = $_GET['zrl'];
1059                                                 $_SESSION['authenticated'] = 0;
1060                                         }
1061                                         Model\Profile::zrlInit($this);
1062                                 } else {
1063                                         // Someone came with an invalid parameter, maybe as a DDoS attempt
1064                                         // We simply stop processing here
1065                                         Core\Logger::log("Invalid ZRL parameter " . $_GET['zrl'], Core\Logger::DEBUG);
1066                                         Core\System::httpExit(403, ['title' => '403 Forbidden']);
1067                                 }
1068                         }
1069                 }
1070
1071                 if (!empty($_GET['owt']) && $this->getMode()->isNormal()) {
1072                         $token = $_GET['owt'];
1073                         $this->query_string = Model\Profile::stripQueryParam($this->query_string, 'owt');
1074                         Model\Profile::openWebAuthInit($token);
1075                 }
1076
1077                 Module\Login::sessionAuth();
1078
1079                 if (empty($_SESSION['authenticated'])) {
1080                         header('X-Account-Management-Status: none');
1081                 }
1082
1083                 $_SESSION['sysmsg']       = defaults($_SESSION, 'sysmsg'      , []);
1084                 $_SESSION['sysmsg_info']  = defaults($_SESSION, 'sysmsg_info' , []);
1085                 $_SESSION['last_updated'] = defaults($_SESSION, 'last_updated', []);
1086
1087                 /*
1088                  * check_config() is responsible for running update scripts. These automatically
1089                  * update the DB schema whenever we push a new one out. It also checks to see if
1090                  * any addons have been added or removed and reacts accordingly.
1091                  */
1092
1093                 // in install mode, any url loads install module
1094                 // but we need "view" module for stylesheet
1095                 if ($this->getMode()->isInstall() && $this->module != 'view') {
1096                         $this->module = 'install';
1097                 } elseif (!$this->getMode()->has(App\Mode::MAINTENANCEDISABLED) && $this->module != 'view') {
1098                         $this->module = 'maintenance';
1099                 } else {
1100                         $this->checkURL();
1101                         Core\Update::check($this->getBasePath(), false, $this->getMode());
1102                         Core\Addon::loadAddons();
1103                         Core\Hook::loadHooks();
1104                 }
1105
1106                 $this->page = [
1107                         'aside' => '',
1108                         'bottom' => '',
1109                         'content' => '',
1110                         'footer' => '',
1111                         'htmlhead' => '',
1112                         'nav' => '',
1113                         'page_title' => '',
1114                         'right_aside' => '',
1115                         'template' => '',
1116                         'title' => ''
1117                 ];
1118
1119                 if (strlen($this->module)) {
1120                         // Compatibility with the Android Diaspora client
1121                         if ($this->module == 'stream') {
1122                                 $this->internalRedirect('network?f=&order=post');
1123                         }
1124
1125                         if ($this->module == 'conversations') {
1126                                 $this->internalRedirect('message');
1127                         }
1128
1129                         if ($this->module == 'commented') {
1130                                 $this->internalRedirect('network?f=&order=comment');
1131                         }
1132
1133                         if ($this->module == 'liked') {
1134                                 $this->internalRedirect('network?f=&order=comment');
1135                         }
1136
1137                         if ($this->module == 'activity') {
1138                                 $this->internalRedirect('network/?f=&conv=1');
1139                         }
1140
1141                         if (($this->module == 'status_messages') && ($this->cmd == 'status_messages/new')) {
1142                                 $this->internalRedirect('bookmarklet');
1143                         }
1144
1145                         if (($this->module == 'user') && ($this->cmd == 'user/edit')) {
1146                                 $this->internalRedirect('settings');
1147                         }
1148
1149                         if (($this->module == 'tag_followings') && ($this->cmd == 'tag_followings/manage')) {
1150                                 $this->internalRedirect('search');
1151                         }
1152
1153                         // Compatibility with the Firefox App
1154                         if (($this->module == "users") && ($this->cmd == "users/sign_in")) {
1155                                 $this->module = "login";
1156                         }
1157
1158                         /*
1159                          * ROUTING
1160                          *
1161                          * From the request URL, routing consists of obtaining the name of a BaseModule-extending class of which the
1162                          * post() and/or content() static methods can be respectively called to produce a data change or an output.
1163                          */
1164
1165                         // First we try explicit routes defined in App\Router
1166                         $this->router->collectRoutes();
1167
1168                         $data = $this->router->getRouteCollector();
1169                         Hook::callAll('route_collection', $data);
1170
1171                         $this->module_class = $this->router->getModuleClass($this->cmd);
1172
1173                         // Then we try addon-provided modules that we wrap in the LegacyModule class
1174                         if (!$this->module_class && Core\Addon::isEnabled($this->module) && file_exists("addon/{$this->module}/{$this->module}.php")) {
1175                                 //Check if module is an app and if public access to apps is allowed or not
1176                                 $privateapps = $this->config->get('config', 'private_addons', false);
1177                                 if ((!local_user()) && Core\Hook::isAddonApp($this->module) && $privateapps) {
1178                                         info(Core\L10n::t("You must be logged in to use addons. "));
1179                                 } else {
1180                                         include_once "addon/{$this->module}/{$this->module}.php";
1181                                         if (function_exists($this->module . '_module')) {
1182                                                 LegacyModule::setModuleFile("addon/{$this->module}/{$this->module}.php");
1183                                                 $this->module_class = 'Friendica\\LegacyModule';
1184                                         }
1185                                 }
1186                         }
1187
1188                         // Then we try name-matching a Friendica\Module class
1189                         if (!$this->module_class && class_exists('Friendica\\Module\\' . ucfirst($this->module))) {
1190                                 $this->module_class = 'Friendica\\Module\\' . ucfirst($this->module);
1191                         }
1192
1193                         /* Finally, we look for a 'standard' program module in the 'mod' directory
1194                          * We emulate a Module class through the LegacyModule class
1195                          */
1196                         if (!$this->module_class && file_exists("mod/{$this->module}.php")) {
1197                                 LegacyModule::setModuleFile("mod/{$this->module}.php");
1198                                 $this->module_class = 'Friendica\\LegacyModule';
1199                         }
1200
1201                         /* The URL provided does not resolve to a valid module.
1202                          *
1203                          * On Dreamhost sites, quite often things go wrong for no apparent reason and they send us to '/internal_error.html'.
1204                          * We don't like doing this, but as it occasionally accounts for 10-20% or more of all site traffic -
1205                          * we are going to trap this and redirect back to the requested page. As long as you don't have a critical error on your page
1206                          * this will often succeed and eventually do the right thing.
1207                          *
1208                          * Otherwise we are going to emit a 404 not found.
1209                          */
1210                         if (!$this->module_class) {
1211                                 // Stupid browser tried to pre-fetch our Javascript img template. Don't log the event or return anything - just quietly exit.
1212                                 if (!empty($_SERVER['QUERY_STRING']) && preg_match('/{[0-9]}/', $_SERVER['QUERY_STRING']) !== 0) {
1213                                         exit();
1214                                 }
1215
1216                                 if (!empty($_SERVER['QUERY_STRING']) && ($_SERVER['QUERY_STRING'] === 'q=internal_error.html') && isset($dreamhost_error_hack)) {
1217                                         Core\Logger::log('index.php: dreamhost_error_hack invoked. Original URI =' . $_SERVER['REQUEST_URI']);
1218                                         $this->internalRedirect($_SERVER['REQUEST_URI']);
1219                                 }
1220
1221                                 Core\Logger::log('index.php: page not found: ' . $_SERVER['REQUEST_URI'] . ' ADDRESS: ' . $_SERVER['REMOTE_ADDR'] . ' QUERY: ' . $_SERVER['QUERY_STRING'], Core\Logger::DEBUG);
1222
1223                                 header($_SERVER["SERVER_PROTOCOL"] . ' 404 ' . Core\L10n::t('Not Found'));
1224                                 $tpl = Core\Renderer::getMarkupTemplate("404.tpl");
1225                                 $this->page['content'] = Core\Renderer::replaceMacros($tpl, [
1226                                         '$message' =>  Core\L10n::t('Page not found.')
1227                                 ]);
1228                         }
1229                 }
1230
1231                 $content = '';
1232
1233                 // Initialize module that can set the current theme in the init() method, either directly or via App->profile_uid
1234                 if ($this->module_class) {
1235                         $this->page['page_title'] = $this->module;
1236                         $placeholder = '';
1237
1238                         Core\Hook::callAll($this->module . '_mod_init', $placeholder);
1239
1240                         call_user_func([$this->module_class, 'init']);
1241
1242                         // "rawContent" is especially meant for technical endpoints.
1243                         // This endpoint doesn't need any theme initialization or other comparable stuff.
1244                         if (!$this->error) {
1245                                 call_user_func([$this->module_class, 'rawContent']);
1246                         }
1247                 }
1248
1249                 // Load current theme info after module has been initialized as theme could have been set in module
1250                 $theme_info_file = 'view/theme/' . $this->getCurrentTheme() . '/theme.php';
1251                 if (file_exists($theme_info_file)) {
1252                         require_once $theme_info_file;
1253                 }
1254
1255                 if (function_exists(str_replace('-', '_', $this->getCurrentTheme()) . '_init')) {
1256                         $func = str_replace('-', '_', $this->getCurrentTheme()) . '_init';
1257                         $func($this);
1258                 }
1259
1260                 if ($this->module_class) {
1261                         if (! $this->error && $_SERVER['REQUEST_METHOD'] === 'POST') {
1262                                 Core\Hook::callAll($this->module . '_mod_post', $_POST);
1263                                 call_user_func([$this->module_class, 'post']);
1264                         }
1265
1266                         if (! $this->error) {
1267                                 Core\Hook::callAll($this->module . '_mod_afterpost', $placeholder);
1268                                 call_user_func([$this->module_class, 'afterpost']);
1269                         }
1270
1271                         if (! $this->error) {
1272                                 $arr = ['content' => $content];
1273                                 Core\Hook::callAll($this->module . '_mod_content', $arr);
1274                                 $content = $arr['content'];
1275                                 $arr = ['content' => call_user_func([$this->module_class, 'content'])];
1276                                 Core\Hook::callAll($this->module . '_mod_aftercontent', $arr);
1277                                 $content .= $arr['content'];
1278                         }
1279                 }
1280
1281                 // initialise content region
1282                 if ($this->getMode()->isNormal()) {
1283                         Core\Hook::callAll('page_content_top', $this->page['content']);
1284                 }
1285
1286                 $this->page['content'] .= $content;
1287
1288                 /* Create the page head after setting the language
1289                  * and getting any auth credentials.
1290                  *
1291                  * Moved initHead() and initFooter() to after
1292                  * all the module functions have executed so that all
1293                  * theme choices made by the modules can take effect.
1294                  */
1295                 $this->initHead();
1296
1297                 /* Build the page ending -- this is stuff that goes right before
1298                  * the closing </body> tag
1299                  */
1300                 $this->initFooter();
1301
1302                 /* now that we've been through the module content, see if the page reported
1303                  * a permission problem and if so, a 403 response would seem to be in order.
1304                  */
1305                 if (stristr(implode("", $_SESSION['sysmsg']), Core\L10n::t('Permission denied'))) {
1306                         header($_SERVER["SERVER_PROTOCOL"] . ' 403 ' . Core\L10n::t('Permission denied.'));
1307                 }
1308
1309                 // Report anything which needs to be communicated in the notification area (before the main body)
1310                 Core\Hook::callAll('page_end', $this->page['content']);
1311
1312                 // Add the navigation (menu) template
1313                 if ($this->module != 'install' && $this->module != 'maintenance') {
1314                         $this->page['htmlhead'] .= Core\Renderer::replaceMacros(Core\Renderer::getMarkupTemplate('nav_head.tpl'), []);
1315                         $this->page['nav']       = Content\Nav::build($this);
1316                 }
1317
1318                 // Build the page - now that we have all the components
1319                 if (isset($_GET["mode"]) && (($_GET["mode"] == "raw") || ($_GET["mode"] == "minimal"))) {
1320                         $doc = new DOMDocument();
1321
1322                         $target = new DOMDocument();
1323                         $target->loadXML("<root></root>");
1324
1325                         $content = mb_convert_encoding($this->page["content"], 'HTML-ENTITIES', "UTF-8");
1326
1327                         /// @TODO one day, kill those error-surpressing @ stuff, or PHP should ban it
1328                         @$doc->loadHTML($content);
1329
1330                         $xpath = new DOMXPath($doc);
1331
1332                         $list = $xpath->query("//*[contains(@id,'tread-wrapper-')]");  /* */
1333
1334                         foreach ($list as $item) {
1335                                 $item = $target->importNode($item, true);
1336
1337                                 // And then append it to the target
1338                                 $target->documentElement->appendChild($item);
1339                         }
1340
1341                         if ($_GET["mode"] == "raw") {
1342                                 header("Content-type: text/html; charset=utf-8");
1343
1344                                 echo substr($target->saveHTML(), 6, -8);
1345
1346                                 exit();
1347                         }
1348                 }
1349
1350                 $page    = $this->page;
1351                 $profile = $this->profile;
1352
1353                 header("X-Friendica-Version: " . FRIENDICA_VERSION);
1354                 header("Content-type: text/html; charset=utf-8");
1355
1356                 if ($this->config->get('system', 'hsts') && ($this->config->get('system', 'ssl_policy') == BaseUrl::SSL_POLICY_FULL)) {
1357                         header("Strict-Transport-Security: max-age=31536000");
1358                 }
1359
1360                 // Some security stuff
1361                 header('X-Content-Type-Options: nosniff');
1362                 header('X-XSS-Protection: 1; mode=block');
1363                 header('X-Permitted-Cross-Domain-Policies: none');
1364                 header('X-Frame-Options: sameorigin');
1365
1366                 // Things like embedded OSM maps don't work, when this is enabled
1367                 // header("Content-Security-Policy: default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; connect-src 'self'; style-src 'self' 'unsafe-inline'; font-src 'self'; img-src 'self' https: data:; media-src 'self' https:; child-src 'self' https:; object-src 'none'");
1368
1369                 /* We use $_GET["mode"] for special page templates. So we will check if we have
1370                  * to load another page template than the default one.
1371                  * The page templates are located in /view/php/ or in the theme directory.
1372                  */
1373                 if (isset($_GET["mode"])) {
1374                         $template = Core\Theme::getPathForFile($_GET["mode"] . '.php');
1375                 }
1376
1377                 // If there is no page template use the default page template
1378                 if (empty($template)) {
1379                         $template = Core\Theme::getPathForFile("default.php");
1380                 }
1381
1382                 // Theme templates expect $a as an App instance
1383                 $a = $this;
1384
1385                 // Used as is in view/php/default.php
1386                 $lang = Core\L10n::getCurrentLang();
1387
1388                 /// @TODO Looks unsafe (remote-inclusion), is maybe not but Core\Theme::getPathForFile() uses file_exists() but does not escape anything
1389                 require_once $template;
1390         }
1391
1392         /**
1393          * Redirects to another module relative to the current Friendica base.
1394          * If you want to redirect to a external URL, use System::externalRedirectTo()
1395          *
1396          * @param string $toUrl The destination URL (Default is empty, which is the default page of the Friendica node)
1397          * @param bool $ssl if true, base URL will try to get called with https:// (works just for relative paths)
1398          *
1399          * @throws InternalServerErrorException In Case the given URL is not relative to the Friendica node
1400          */
1401         public function internalRedirect($toUrl = '', $ssl = false)
1402         {
1403                 if (!empty(parse_url($toUrl, PHP_URL_SCHEME))) {
1404                         throw new InternalServerErrorException("'$toUrl is not a relative path, please use System::externalRedirectTo");
1405                 }
1406
1407                 $redirectTo = $this->getBaseURL($ssl) . '/' . ltrim($toUrl, '/');
1408                 Core\System::externalRedirect($redirectTo);
1409         }
1410
1411         /**
1412          * Automatically redirects to relative or absolute URL
1413          * Should only be used if it isn't clear if the URL is either internal or external
1414          *
1415          * @param string $toUrl The target URL
1416          * @throws InternalServerErrorException
1417          */
1418         public function redirect($toUrl)
1419         {
1420                 if (!empty(parse_url($toUrl, PHP_URL_SCHEME))) {
1421                         Core\System::externalRedirect($toUrl);
1422                 } else {
1423                         $this->internalRedirect($toUrl);
1424                 }
1425         }
1426 }