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