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