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