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