]> git.mxchange.org Git - friendica.git/blob - src/App.php
Some changes for better code quality
[friendica.git] / src / App.php
1 <?php
2 /**
3  * @file src/App.php
4  */
5 namespace Friendica;
6
7 use Detection\MobileDetect;
8 use Exception;
9 use Friendica\Core\Config;
10 use Friendica\Core\L10n;
11 use Friendica\Core\PConfig;
12 use Friendica\Core\System;
13 use Friendica\Database\DBA;
14
15 require_once 'boot.php';
16 require_once 'include/dba.php';
17 require_once 'include/text.php';
18
19 /**
20  *
21  * class: App
22  *
23  * @brief Our main application structure for the life of this page.
24  *
25  * Primarily deals with the URL that got us here
26  * and tries to make some sense of it, and
27  * stores our page contents and config storage
28  * and anything else that might need to be passed around
29  * before we spit the page out.
30  *
31  */
32 class App
33 {
34         const MODE_LOCALCONFIGPRESENT = 1;
35         const MODE_DBAVAILABLE = 2;
36         const MODE_DBCONFIGAVAILABLE = 4;
37         const MODE_MAINTENANCEDISABLED = 8;
38
39         /**
40          * @deprecated since version 2008.08 Use App->isInstallMode() instead to check for install mode.
41          */
42         const MODE_INSTALL = 0;
43
44         /**
45          * @deprecated since version 2008.08 Use the precise mode constant to check for a specific capability instead.
46          */
47         const MODE_NORMAL = App::MODE_LOCALCONFIGPRESENT | App::MODE_DBAVAILABLE | App::MODE_DBCONFIGAVAILABLE | App::MODE_MAINTENANCEDISABLED;
48
49         public $module_loaded = false;
50         public $module_class = null;
51         public $query_string = '';
52         public $config = [];
53         public $page = [];
54         public $pager = [];
55         public $page_offset;
56         public $profile;
57         public $profile_uid;
58         public $user;
59         public $cid;
60         public $contact;
61         public $contacts;
62         public $page_contact;
63         public $content;
64         public $data = [];
65         public $error = false;
66         public $cmd = '';
67         public $argv;
68         public $argc;
69         public $module;
70         public $mode = App::MODE_INSTALL;
71         public $strings;
72         public $basepath;
73         public $urlpath;
74         public $hooks = [];
75         public $timezone;
76         public $interactive = true;
77         public $addons;
78         public $addons_admin = [];
79         public $apps = [];
80         public $identities;
81         public $is_mobile = false;
82         public $is_tablet = false;
83         public $is_friendica_app;
84         public $performance = [];
85         public $callstack = [];
86         public $theme_info = [];
87         public $backend = true;
88         public $nav_sel;
89         public $category;
90         // Allow themes to control internal parameters
91         // by changing App values in theme.php
92
93         public $sourcename = '';
94         public $videowidth = 425;
95         public $videoheight = 350;
96         public $force_max_items = 0;
97         public $theme_events_in_profile = true;
98
99         /**
100          * @brief An array for all theme-controllable parameters
101          *
102          * Mostly unimplemented yet. Only options 'template_engine' and
103          * beyond are used.
104          */
105         public $theme = [
106                 'sourcename' => '',
107                 'videowidth' => 425,
108                 'videoheight' => 350,
109                 'force_max_items' => 0,
110                 'stylesheet' => '',
111                 'template_engine' => 'smarty3',
112         ];
113
114         /**
115          * @brief An array of registered template engines ('name'=>'class name')
116          */
117         public $template_engines = [];
118
119         /**
120          * @brief An array of instanced template engines ('name'=>'instance')
121          */
122         public $template_engine_instance = [];
123         public $process_id;
124         public $queue;
125         private $ldelim = [
126                 'internal' => '',
127                 'smarty3' => '{{'
128         ];
129         private $rdelim = [
130                 'internal' => '',
131                 'smarty3' => '}}'
132         ];
133         private $scheme;
134         private $hostname;
135         private $curl_code;
136         private $curl_content_type;
137         private $curl_headers;
138
139         /**
140          * @brief App constructor.
141          *
142          * @param string $basepath Path to the app base folder
143          *
144          * @throws Exception if the Basepath is not usable
145          */
146         public function __construct($basepath)
147         {
148                 if (!static::directory_usable($basepath, false)) {
149                         throw new Exception('Basepath ' . $basepath . ' isn\'t usable.');
150                 }
151
152                 BaseObject::setApp($this);
153
154                 $this->basepath = rtrim($basepath, DIRECTORY_SEPARATOR);
155
156                 $this->performance['start'] = microtime(true);
157                 $this->performance['database'] = 0;
158                 $this->performance['database_write'] = 0;
159                 $this->performance['cache'] = 0;
160                 $this->performance['cache_write'] = 0;
161                 $this->performance['network'] = 0;
162                 $this->performance['file'] = 0;
163                 $this->performance['rendering'] = 0;
164                 $this->performance['parser'] = 0;
165                 $this->performance['marktime'] = 0;
166                 $this->performance['markstart'] = microtime(true);
167
168                 $this->callstack['database'] = [];
169                 $this->callstack['database_write'] = [];
170                 $this->callstack['cache'] = [];
171                 $this->callstack['cache_write'] = [];
172                 $this->callstack['network'] = [];
173                 $this->callstack['file'] = [];
174                 $this->callstack['rendering'] = [];
175                 $this->callstack['parser'] = [];
176
177                 $this->reload();
178
179                 set_time_limit(0);
180
181                 // This has to be quite large to deal with embedded private photos
182                 ini_set('pcre.backtrack_limit', 500000);
183
184                 $this->scheme = 'http';
185
186                 if ((x($_SERVER, 'HTTPS') && $_SERVER['HTTPS']) ||
187                         (x($_SERVER, 'HTTP_FORWARDED') && preg_match('/proto=https/', $_SERVER['HTTP_FORWARDED'])) ||
188                         (x($_SERVER, 'HTTP_X_FORWARDED_PROTO') && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') ||
189                         (x($_SERVER, 'HTTP_X_FORWARDED_SSL') && $_SERVER['HTTP_X_FORWARDED_SSL'] == 'on') ||
190                         (x($_SERVER, 'FRONT_END_HTTPS') && $_SERVER['FRONT_END_HTTPS'] == 'on') ||
191                         (x($_SERVER, 'SERVER_PORT') && (intval($_SERVER['SERVER_PORT']) == 443)) // XXX: reasonable assumption, but isn't this hardcoding too much?
192                 ) {
193                         $this->scheme = 'https';
194                 }
195
196                 if (x($_SERVER, 'SERVER_NAME')) {
197                         $this->hostname = $_SERVER['SERVER_NAME'];
198
199                         if (x($_SERVER, 'SERVER_PORT') && $_SERVER['SERVER_PORT'] != 80 && $_SERVER['SERVER_PORT'] != 443) {
200                                 $this->hostname .= ':' . $_SERVER['SERVER_PORT'];
201                         }
202                 }
203
204                 set_include_path(
205                         get_include_path() . PATH_SEPARATOR
206                         . $this->basepath . DIRECTORY_SEPARATOR . 'include' . PATH_SEPARATOR
207                         . $this->basepath . DIRECTORY_SEPARATOR . 'library' . PATH_SEPARATOR
208                         . $this->basepath);
209
210                 if ((x($_SERVER, 'QUERY_STRING')) && substr($_SERVER['QUERY_STRING'], 0, 9) === 'pagename=') {
211                         $this->query_string = substr($_SERVER['QUERY_STRING'], 9);
212                 } elseif ((x($_SERVER, 'QUERY_STRING')) && substr($_SERVER['QUERY_STRING'], 0, 2) === 'q=') {
213                         $this->query_string = substr($_SERVER['QUERY_STRING'], 2);
214                 }
215
216                 // removing trailing / - maybe a nginx problem
217                 $this->query_string = ltrim($this->query_string, '/');
218
219                 if (!empty($_GET['pagename'])) {
220                         $this->cmd = trim($_GET['pagename'], '/\\');
221                 } elseif (!empty($_GET['q'])) {
222                         $this->cmd = trim($_GET['q'], '/\\');
223                 }
224
225                 // fix query_string
226                 $this->query_string = str_replace($this->cmd . '&', $this->cmd . '?', $this->query_string);
227
228                 // unix style "homedir"
229                 if (substr($this->cmd, 0, 1) === '~') {
230                         $this->cmd = 'profile/' . substr($this->cmd, 1);
231                 }
232
233                 // Diaspora style profile url
234                 if (substr($this->cmd, 0, 2) === 'u/') {
235                         $this->cmd = 'profile/' . substr($this->cmd, 2);
236                 }
237
238                 /*
239                  * Break the URL path into C style argc/argv style arguments for our
240                  * modules. Given "http://example.com/module/arg1/arg2", $this->argc
241                  * will be 3 (integer) and $this->argv will contain:
242                  *   [0] => 'module'
243                  *   [1] => 'arg1'
244                  *   [2] => 'arg2'
245                  *
246                  *
247                  * There will always be one argument. If provided a naked domain
248                  * URL, $this->argv[0] is set to "home".
249                  */
250
251                 $this->argv = explode('/', $this->cmd);
252                 $this->argc = count($this->argv);
253                 if ((array_key_exists('0', $this->argv)) && strlen($this->argv[0])) {
254                         $this->module = str_replace('.', '_', $this->argv[0]);
255                         $this->module = str_replace('-', '_', $this->module);
256                 } else {
257                         $this->argc = 1;
258                         $this->argv = ['home'];
259                         $this->module = 'home';
260                 }
261
262                 // See if there is any page number information, and initialise pagination
263                 $this->pager['page'] = ((x($_GET, 'page') && intval($_GET['page']) > 0) ? intval($_GET['page']) : 1);
264                 $this->pager['itemspage'] = 50;
265                 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
266
267                 if ($this->pager['start'] < 0) {
268                         $this->pager['start'] = 0;
269                 }
270                 $this->pager['total'] = 0;
271
272                 // Detect mobile devices
273                 $mobile_detect = new MobileDetect();
274                 $this->is_mobile = $mobile_detect->isMobile();
275                 $this->is_tablet = $mobile_detect->isTablet();
276
277                 // Friendica-Client
278                 $this->is_friendica_app = isset($_SERVER['HTTP_USER_AGENT']) && $_SERVER['HTTP_USER_AGENT'] == 'Apache-HttpClient/UNAVAILABLE (java 1.4)';
279
280                 // Register template engines
281                 $this->register_template_engine('Friendica\Render\FriendicaSmartyEngine');
282         }
283
284         /**
285          * Reloads the whole app instance
286          */
287         public function reload()
288         {
289                 // The order of the following calls is important to ensure proper initialization
290                 $this->loadConfigFiles();
291
292                 $this->loadDatabase();
293
294                 $this->determineMode();
295
296                 $this->determineUrlPath();
297
298                 Config::load();
299
300                 if ($this->mode & self::MODE_DBAVAILABLE) {
301                         Core\Addon::loadHooks();
302
303                         $this->loadAddonConfig();
304                 }
305
306                 $this->loadDefaultTimezone();
307
308                 $this->page = [
309                         'aside' => '',
310                         'bottom' => '',
311                         'content' => '',
312                         'end' => '',
313                         'footer' => '',
314                         'htmlhead' => '',
315                         'nav' => '',
316                         'page_title' => '',
317                         'right_aside' => '',
318                         'template' => '',
319                         'title' => ''
320                 ];
321
322                 $this->process_id = System::processID('log');
323         }
324
325         /**
326          * Load the configuration files
327          *
328          * First loads the default value for all the configuration keys, then the legacy configuration files, then the
329          * expected local.ini.php
330          */
331         private function loadConfigFiles()
332         {
333                 $this->loadConfigFile($this->basepath . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'config.ini.php');
334                 $this->loadConfigFile($this->basepath . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'settings.ini.php');
335
336                 // Legacy .htconfig.php support
337                 if (file_exists($this->basepath . DIRECTORY_SEPARATOR . '.htpreconfig.php')) {
338                         $a = $this;
339                         include $this->basepath . DIRECTORY_SEPARATOR . '.htpreconfig.php';
340                 }
341
342                 // Legacy .htconfig.php support
343                 if (file_exists($this->basepath . DIRECTORY_SEPARATOR . '.htconfig.php')) {
344                         $a = $this;
345
346                         include $this->basepath . DIRECTORY_SEPARATOR . '.htconfig.php';
347
348                         $this->setConfigValue('database', 'hostname', $db_host);
349                         $this->setConfigValue('database', 'username', $db_user);
350                         $this->setConfigValue('database', 'password', $db_pass);
351                         $this->setConfigValue('database', 'database', $db_data);
352                         if (isset($a->config['system']['db_charset'])) {
353                                 $this->setConfigValue('database', 'charset', $a->config['system']['db_charset']);
354                         }
355
356                         unset($db_host, $db_user, $db_pass, $db_data);
357
358                         if (isset($default_timezone)) {
359                                 $this->setConfigValue('system', 'default_timezone', $default_timezone);
360                                 unset($default_timezone);
361                         }
362
363                         if (isset($pidfile)) {
364                                 $this->setConfigValue('system', 'pidfile', $pidfile);
365                                 unset($pidfile);
366                         }
367
368                         if (isset($lang)) {
369                                 $this->setConfigValue('system', 'language', $lang);
370                                 unset($lang);
371                         }
372                 }
373
374                 if (file_exists($this->basepath . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'local.ini.php')) {
375                         $this->loadConfigFile($this->basepath . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'local.ini.php', true);
376                 }
377         }
378
379         /**
380          * Tries to load the specified configuration file into the App->config array.
381          * Doesn't overwrite previously set values by default to prevent default config files to supersede DB Config.
382          *
383          * The config format is INI and the template for configuration files is the following:
384          *
385          * <?php return <<<INI
386          *
387          * [section]
388          * key = value
389          *
390          * INI;
391          * // Keep this line
392          *
393          * @param type $filepath
394          * @param bool $overwrite Force value overwrite if the config key already exists
395          * @throws Exception
396          */
397         public function loadConfigFile($filepath, $overwrite = false)
398         {
399                 if (!file_exists($filepath)) {
400                         throw new Exception('Error parsing non-existent config file ' . $filepath);
401                 }
402
403                 $contents = include($filepath);
404
405                 $config = parse_ini_string($contents, true, INI_SCANNER_TYPED);
406
407                 if ($config === false) {
408                         throw new Exception('Error parsing config file ' . $filepath);
409                 }
410
411                 foreach ($config as $category => $values) {
412                         foreach ($values as $key => $value) {
413                                 if ($overwrite) {
414                                         $this->setConfigValue($category, $key, $value);
415                                 } else {
416                                         $this->setDefaultConfigValue($category, $key, $value);
417                                 }
418                         }
419                 }
420         }
421
422         /**
423          * Loads addons configuration files
424          *
425          * First loads all activated addons default configuration throught the load_config hook, then load the local.ini.php
426          * again to overwrite potential local addon configuration.
427          */
428         private function loadAddonConfig()
429         {
430                 // Loads addons default config
431                 Core\Addon::callHooks('load_config');
432
433                 // Load the local addon config file to overwritten default addon config values
434                 if (file_exists($this->basepath . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'addon.ini.php')) {
435                         $this->loadConfigFile($this->basepath . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'addon.ini.php', true);
436                 }
437         }
438
439         /**
440          * Loads the default timezone
441          *
442          * Include support for legacy $default_timezone
443          *
444          * @global string $default_timezone
445          */
446         private function loadDefaultTimezone()
447         {
448                 if ($this->getConfigValue('system', 'default_timezone')) {
449                         $this->timezone = $this->getConfigValue('system', 'default_timezone');
450                 } else {
451                         global $default_timezone;
452                         $this->timezone = !empty($default_timezone) ? $default_timezone : 'UTC';
453                 }
454
455                 if ($this->timezone) {
456                         date_default_timezone_set($this->timezone);
457                 }
458         }
459
460         /**
461          * Figure out if we are running at the top of a domain or in a sub-directory and adjust accordingly
462          */
463         private function determineUrlPath()
464         {
465                 $this->urlpath = $this->getConfigValue('system', 'urlpath');
466
467                 /* SCRIPT_URL gives /path/to/friendica/module/parameter
468                  * QUERY_STRING gives pagename=module/parameter
469                  *
470                  * To get /path/to/friendica we perform dirname() for as many levels as there are slashes in the QUERY_STRING
471                  */
472                 if (!empty($_SERVER['SCRIPT_URL'])) {
473                         // Module
474                         if (!empty($_SERVER['QUERY_STRING'])) {
475                                 $path = trim(dirname($_SERVER['SCRIPT_URL'], substr_count(trim($_SERVER['QUERY_STRING'], '/'), '/') + 1), '/');
476                         } else {
477                                 // Root page
478                                 $path = trim($_SERVER['SCRIPT_URL'], '/');
479                         }
480
481                         if ($path && $path != $this->urlpath) {
482                                 $this->urlpath = $path;
483                         }
484                 }
485         }
486
487         /**
488          * Sets the App mode
489          *
490          * - App::MODE_INSTALL    : Either the database connection can't be established or the config table doesn't exist
491          * - App::MODE_MAINTENANCE: The maintenance mode has been set
492          * - App::MODE_NORMAL     : Normal run with all features enabled
493          *
494          * @return type
495          */
496         private function determineMode()
497         {
498                 $this->mode = 0;
499
500                 if (!file_exists($this->basepath . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'local.ini.php')
501                         && !file_exists($this->basepath . DIRECTORY_SEPARATOR . '.htconfig.php')) {
502                         return;
503                 }
504
505                 $this->mode |= App::MODE_LOCALCONFIGPRESENT;
506
507                 if (!DBA::connected()) {
508                         return;
509                 }
510
511                 $this->mode |= App::MODE_DBAVAILABLE;
512
513                 if (DBA::fetchFirst("SHOW TABLES LIKE 'config'") === false) {
514                         return;
515                 }
516
517                 $this->mode |= App::MODE_DBCONFIGAVAILABLE;
518
519                 if (Config::get('system', 'maintenance')) {
520                         return;
521                 }
522
523                 $this->mode |= App::MODE_MAINTENANCEDISABLED;
524         }
525
526         public function loadDatabase()
527         {
528                 if (DBA::connected()) {
529                         return;
530                 }
531
532                 $db_host = $this->getConfigValue('database', 'hostname');
533                 $db_user = $this->getConfigValue('database', 'username');
534                 $db_pass = $this->getConfigValue('database', 'password');
535                 $db_data = $this->getConfigValue('database', 'database');
536                 $charset = $this->getConfigValue('database', 'charset');
537
538                 // Use environment variables for mysql if they are set beforehand
539                 if (!empty(getenv('MYSQL_HOST'))
540                         && (!empty(getenv('MYSQL_USERNAME')) || !empty(getenv('MYSQL_USER')))
541                         && getenv('MYSQL_PASSWORD') !== false
542                         && !empty(getenv('MYSQL_DATABASE')))
543                 {
544                         $db_host = getenv('MYSQL_HOST');
545                         if (!empty(getenv('MYSQL_PORT'))) {
546                                 $db_host .= ':' . getenv('MYSQL_PORT');
547                         }
548                         if (!empty(getenv('MYSQL_USERNAME'))) {
549                                 $db_user = getenv('MYSQL_USERNAME');
550                         } else {
551                                 $db_user = getenv('MYSQL_USER');
552                         }
553                         $db_pass = (string) getenv('MYSQL_PASSWORD');
554                         $db_data = getenv('MYSQL_DATABASE');
555                 }
556
557                 $stamp1 = microtime(true);
558
559                 DBA::connect($db_host, $db_user, $db_pass, $db_data, $charset);
560                 unset($db_host, $db_user, $db_pass, $db_data, $charset);
561
562                 $this->save_timestamp($stamp1, 'network');
563         }
564
565         /**
566          * Install mode is when the local config file is missing or the DB schema hasn't been installed yet.
567          *
568          * @return bool
569          */
570         public function isInstallMode()
571         {
572                 return !($this->mode & App::MODE_LOCALCONFIGPRESENT) || !($this->mode & App::MODE_DBCONFIGAVAILABLE);
573         }
574
575         /**
576          * @brief Returns the base filesystem path of the App
577          *
578          * It first checks for the internal variable, then for DOCUMENT_ROOT and
579          * finally for PWD
580          *
581          * @return string
582          */
583         public function get_basepath()
584         {
585                 $basepath = $this->basepath;
586
587                 if (!$basepath) {
588                         $basepath = Config::get('system', 'basepath');
589                 }
590
591                 if (!$basepath && x($_SERVER, 'DOCUMENT_ROOT')) {
592                         $basepath = $_SERVER['DOCUMENT_ROOT'];
593                 }
594
595                 if (!$basepath && x($_SERVER, 'PWD')) {
596                         $basepath = $_SERVER['PWD'];
597                 }
598
599                 return self::realpath($basepath);
600         }
601
602         /**
603          * @brief Returns a normalized file path
604          *
605          * This is a wrapper for the "realpath" function.
606          * That function cannot detect the real path when some folders aren't readable.
607          * Since this could happen with some hosters we need to handle this.
608          *
609          * @param string $path The path that is about to be normalized
610          * @return string normalized path - when possible
611          */
612         public static function realpath($path)
613         {
614                 $normalized = realpath($path);
615
616                 if (!is_bool($normalized)) {
617                         return $normalized;
618                 } else {
619                         return $path;
620                 }
621         }
622
623         public function get_scheme()
624         {
625                 return $this->scheme;
626         }
627
628         /**
629          * @brief Retrieves the Friendica instance base URL
630          *
631          * This function assembles the base URL from multiple parts:
632          * - Protocol is determined either by the request or a combination of
633          * system.ssl_policy and the $ssl parameter.
634          * - Host name is determined either by system.hostname or inferred from request
635          * - Path is inferred from SCRIPT_NAME
636          *
637          * Note: $ssl parameter value doesn't directly correlate with the resulting protocol
638          *
639          * @param bool $ssl Whether to append http or https under SSL_POLICY_SELFSIGN
640          * @return string Friendica server base URL
641          */
642         public function get_baseurl($ssl = false)
643         {
644                 $scheme = $this->scheme;
645
646                 if (Config::get('system', 'ssl_policy') == SSL_POLICY_FULL) {
647                         $scheme = 'https';
648                 }
649
650                 //      Basically, we have $ssl = true on any links which can only be seen by a logged in user
651                 //      (and also the login link). Anything seen by an outsider will have it turned off.
652
653                 if (Config::get('system', 'ssl_policy') == SSL_POLICY_SELFSIGN) {
654                         if ($ssl) {
655                                 $scheme = 'https';
656                         } else {
657                                 $scheme = 'http';
658                         }
659                 }
660
661                 if (Config::get('config', 'hostname') != '') {
662                         $this->hostname = Config::get('config', 'hostname');
663                 }
664
665                 return $scheme . '://' . $this->hostname . (!empty($this->urlpath) ? '/' . $this->urlpath : '' );
666         }
667
668         /**
669          * @brief Initializes the baseurl components
670          *
671          * Clears the baseurl cache to prevent inconsistencies
672          *
673          * @param string $url
674          */
675         public function set_baseurl($url)
676         {
677                 $parsed = @parse_url($url);
678                 $hostname = '';
679
680                 if (x($parsed)) {
681                         if (!empty($parsed['scheme'])) {
682                                 $this->scheme = $parsed['scheme'];
683                         }
684
685                         if (!empty($parsed['host'])) {
686                                 $hostname = $parsed['host'];
687                         }
688
689                         if (x($parsed, 'port')) {
690                                 $hostname .= ':' . $parsed['port'];
691                         }
692                         if (x($parsed, 'path')) {
693                                 $this->urlpath = trim($parsed['path'], '\\/');
694                         }
695
696                         if (file_exists($this->basepath . DIRECTORY_SEPARATOR . '.htpreconfig.php')) {
697                                 include $this->basepath . DIRECTORY_SEPARATOR . '.htpreconfig.php';
698                         }
699
700                         if (Config::get('config', 'hostname') != '') {
701                                 $this->hostname = Config::get('config', 'hostname');
702                         }
703
704                         if (!isset($this->hostname) || ($this->hostname == '')) {
705                                 $this->hostname = $hostname;
706                         }
707                 }
708         }
709
710         public function get_hostname()
711         {
712                 if (Config::get('config', 'hostname') != '') {
713                         $this->hostname = Config::get('config', 'hostname');
714                 }
715
716                 return $this->hostname;
717         }
718
719         public function get_path()
720         {
721                 return $this->urlpath;
722         }
723
724         public function set_pager_total($n)
725         {
726                 $this->pager['total'] = intval($n);
727         }
728
729         public function set_pager_itemspage($n)
730         {
731                 $this->pager['itemspage'] = ((intval($n) > 0) ? intval($n) : 0);
732                 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
733         }
734
735         public function set_pager_page($n)
736         {
737                 $this->pager['page'] = $n;
738                 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
739         }
740
741         public function init_pagehead()
742         {
743                 $interval = ((local_user()) ? PConfig::get(local_user(), 'system', 'update_interval') : 40000);
744
745                 // If the update is 'deactivated' set it to the highest integer number (~24 days)
746                 if ($interval < 0) {
747                         $interval = 2147483647;
748                 }
749
750                 if ($interval < 10000) {
751                         $interval = 40000;
752                 }
753
754                 // compose the page title from the sitename and the
755                 // current module called
756                 if (!$this->module == '') {
757                         $this->page['title'] = $this->config['sitename'] . ' (' . $this->module . ')';
758                 } else {
759                         $this->page['title'] = $this->config['sitename'];
760                 }
761
762                 /* put the head template at the beginning of page['htmlhead']
763                  * since the code added by the modules frequently depends on it
764                  * being first
765                  */
766                 if (!isset($this->page['htmlhead'])) {
767                         $this->page['htmlhead'] = '';
768                 }
769
770                 // If we're using Smarty, then doing replace_macros() will replace
771                 // any unrecognized variables with a blank string. Since we delay
772                 // replacing $stylesheet until later, we need to replace it now
773                 // with another variable name
774                 if ($this->theme['template_engine'] === 'smarty3') {
775                         $stylesheet = $this->get_template_ldelim('smarty3') . '$stylesheet' . $this->get_template_rdelim('smarty3');
776                 } else {
777                         $stylesheet = '$stylesheet';
778                 }
779
780                 $shortcut_icon = Config::get('system', 'shortcut_icon');
781                 if ($shortcut_icon == '') {
782                         $shortcut_icon = 'images/friendica-32.png';
783                 }
784
785                 $touch_icon = Config::get('system', 'touch_icon');
786                 if ($touch_icon == '') {
787                         $touch_icon = 'images/friendica-128.png';
788                 }
789
790                 // get data wich is needed for infinite scroll on the network page
791                 $invinite_scroll = infinite_scroll_data($this->module);
792
793                 $tpl = get_markup_template('head.tpl');
794                 $this->page['htmlhead'] = replace_macros($tpl, [
795                         '$baseurl'         => $this->get_baseurl(),
796                         '$local_user'      => local_user(),
797                         '$generator'       => 'Friendica' . ' ' . FRIENDICA_VERSION,
798                         '$delitem'         => L10n::t('Delete this item?'),
799                         '$showmore'        => L10n::t('show more'),
800                         '$showfewer'       => L10n::t('show fewer'),
801                         '$update_interval' => $interval,
802                         '$shortcut_icon'   => $shortcut_icon,
803                         '$touch_icon'      => $touch_icon,
804                         '$stylesheet'      => $stylesheet,
805                         '$infinite_scroll' => $invinite_scroll,
806                         '$block_public'    => intval(Config::get('system', 'block_public')),
807                 ]) . $this->page['htmlhead'];
808         }
809
810         public function init_page_end()
811         {
812                 if (!isset($this->page['end'])) {
813                         $this->page['end'] = '';
814                 }
815                 $tpl = get_markup_template('end.tpl');
816                 $this->page['end'] = replace_macros($tpl, [
817                         '$baseurl' => $this->get_baseurl()
818                 ]) . $this->page['end'];
819         }
820
821         public function set_curl_code($code)
822         {
823                 $this->curl_code = $code;
824         }
825
826         public function get_curl_code()
827         {
828                 return $this->curl_code;
829         }
830
831         public function set_curl_content_type($content_type)
832         {
833                 $this->curl_content_type = $content_type;
834         }
835
836         public function get_curl_content_type()
837         {
838                 return $this->curl_content_type;
839         }
840
841         public function set_curl_headers($headers)
842         {
843                 $this->curl_headers = $headers;
844         }
845
846         public function get_curl_headers()
847         {
848                 return $this->curl_headers;
849         }
850
851         /**
852          * @brief Removes the base url from an url. This avoids some mixed content problems.
853          *
854          * @param string $orig_url
855          *
856          * @return string The cleaned url
857          */
858         public function remove_baseurl($orig_url)
859         {
860                 // Remove the hostname from the url if it is an internal link
861                 $nurl = normalise_link($orig_url);
862                 $base = normalise_link($this->get_baseurl());
863                 $url = str_replace($base . '/', '', $nurl);
864
865                 // if it is an external link return the orignal value
866                 if ($url == normalise_link($orig_url)) {
867                         return $orig_url;
868                 } else {
869                         return $url;
870                 }
871         }
872
873         /**
874          * @brief Register template engine class
875          *
876          * @param string $class
877          */
878         private function register_template_engine($class)
879         {
880                 $v = get_class_vars($class);
881                 if (x($v, 'name')) {
882                         $name = $v['name'];
883                         $this->template_engines[$name] = $class;
884                 } else {
885                         echo "template engine <tt>$class</tt> cannot be registered without a name.\n";
886                         die();
887                 }
888         }
889
890         /**
891          * @brief Return template engine instance.
892          *
893          * If $name is not defined, return engine defined by theme,
894          * or default
895          *
896          * @return object Template Engine instance
897          */
898         public function template_engine()
899         {
900                 $template_engine = 'smarty3';
901                 if (x($this->theme, 'template_engine')) {
902                         $template_engine = $this->theme['template_engine'];
903                 }
904
905                 if (isset($this->template_engines[$template_engine])) {
906                         if (isset($this->template_engine_instance[$template_engine])) {
907                                 return $this->template_engine_instance[$template_engine];
908                         } else {
909                                 $class = $this->template_engines[$template_engine];
910                                 $obj = new $class;
911                                 $this->template_engine_instance[$template_engine] = $obj;
912                                 return $obj;
913                         }
914                 }
915
916                 echo "template engine <tt>$template_engine</tt> is not registered!\n";
917                 killme();
918         }
919
920         /**
921          * @brief Returns the active template engine.
922          *
923          * @return string
924          */
925         public function get_template_engine()
926         {
927                 return $this->theme['template_engine'];
928         }
929
930         public function set_template_engine($engine = 'smarty3')
931         {
932                 $this->theme['template_engine'] = $engine;
933         }
934
935         public function get_template_ldelim($engine = 'smarty3')
936         {
937                 return $this->ldelim[$engine];
938         }
939
940         public function get_template_rdelim($engine = 'smarty3')
941         {
942                 return $this->rdelim[$engine];
943         }
944
945         public function save_timestamp($stamp, $value)
946         {
947                 if (!isset($this->config['system']['profiler']) || !$this->config['system']['profiler']) {
948                         return;
949                 }
950
951                 $duration = (float) (microtime(true) - $stamp);
952
953                 if (!isset($this->performance[$value])) {
954                         // Prevent ugly E_NOTICE
955                         $this->performance[$value] = 0;
956                 }
957
958                 $this->performance[$value] += (float) $duration;
959                 $this->performance['marktime'] += (float) $duration;
960
961                 $callstack = System::callstack();
962
963                 if (!isset($this->callstack[$value][$callstack])) {
964                         // Prevent ugly E_NOTICE
965                         $this->callstack[$value][$callstack] = 0;
966                 }
967
968                 $this->callstack[$value][$callstack] += (float) $duration;
969         }
970
971         public function get_useragent()
972         {
973                 return
974                         FRIENDICA_PLATFORM . " '" .
975                         FRIENDICA_CODENAME . "' " .
976                         FRIENDICA_VERSION . '-' .
977                         DB_UPDATE_VERSION . '; ' .
978                         $this->get_baseurl();
979         }
980
981         public function is_friendica_app()
982         {
983                 return $this->is_friendica_app;
984         }
985
986         /**
987          * @brief Checks if the site is called via a backend process
988          *
989          * This isn't a perfect solution. But we need this check very early.
990          * So we cannot wait until the modules are loaded.
991          *
992          * @return bool Is it a known backend?
993          */
994         public function is_backend()
995         {
996                 static $backends = [
997                         '_well_known',
998                         'api',
999                         'dfrn_notify',
1000                         'fetch',
1001                         'hcard',
1002                         'hostxrd',
1003                         'nodeinfo',
1004                         'noscrape',
1005                         'p',
1006                         'poco',
1007                         'post',
1008                         'proxy',
1009                         'pubsub',
1010                         'pubsubhubbub',
1011                         'receive',
1012                         'rsd_xml',
1013                         'salmon',
1014                         'statistics_json',
1015                         'xrd',
1016                 ];
1017
1018                 // Check if current module is in backend or backend flag is set
1019                 return (in_array($this->module, $backends) || $this->backend);
1020         }
1021
1022         /**
1023          * @brief Checks if the maximum number of database processes is reached
1024          *
1025          * @return bool Is the limit reached?
1026          */
1027         public function isMaxProcessesReached()
1028         {
1029                 // Deactivated, needs more investigating if this check really makes sense
1030                 return false;
1031
1032                 /*
1033                  * Commented out to suppress static analyzer issues
1034                  *
1035                 if ($this->is_backend()) {
1036                         $process = 'backend';
1037                         $max_processes = Config::get('system', 'max_processes_backend');
1038                         if (intval($max_processes) == 0) {
1039                                 $max_processes = 5;
1040                         }
1041                 } else {
1042                         $process = 'frontend';
1043                         $max_processes = Config::get('system', 'max_processes_frontend');
1044                         if (intval($max_processes) == 0) {
1045                                 $max_processes = 20;
1046                         }
1047                 }
1048
1049                 $processlist = DBA::processlist();
1050                 if ($processlist['list'] != '') {
1051                         logger('Processcheck: Processes: ' . $processlist['amount'] . ' - Processlist: ' . $processlist['list'], LOGGER_DEBUG);
1052
1053                         if ($processlist['amount'] > $max_processes) {
1054                                 logger('Processcheck: Maximum number of processes for ' . $process . ' tasks (' . $max_processes . ') reached.', LOGGER_DEBUG);
1055                                 return true;
1056                         }
1057                 }
1058                 return false;
1059                  */
1060         }
1061
1062         /**
1063          * @brief Checks if the minimal memory is reached
1064          *
1065          * @return bool Is the memory limit reached?
1066          */
1067         public function min_memory_reached()
1068         {
1069                 $min_memory = Config::get('system', 'min_memory', 0);
1070                 if ($min_memory == 0) {
1071                         return false;
1072                 }
1073
1074                 if (!is_readable('/proc/meminfo')) {
1075                         return false;
1076                 }
1077
1078                 $memdata = explode("\n", file_get_contents('/proc/meminfo'));
1079
1080                 $meminfo = [];
1081                 foreach ($memdata as $line) {
1082                         $data = explode(':', $line);
1083                         if (count($data) != 2) {
1084                                 continue;
1085                         }
1086                         list($key, $val) = $data;
1087                         $meminfo[$key] = (int) trim(str_replace('kB', '', $val));
1088                         $meminfo[$key] = (int) ($meminfo[$key] / 1024);
1089                 }
1090
1091                 if (!isset($meminfo['MemAvailable']) || !isset($meminfo['MemFree'])) {
1092                         return false;
1093                 }
1094
1095                 $free = $meminfo['MemAvailable'] + $meminfo['MemFree'];
1096
1097                 $reached = ($free < $min_memory);
1098
1099                 if ($reached) {
1100                         logger('Minimal memory reached: ' . $free . '/' . $meminfo['MemTotal'] . ' - limit ' . $min_memory, LOGGER_DEBUG);
1101                 }
1102
1103                 return $reached;
1104         }
1105
1106         /**
1107          * @brief Checks if the maximum load is reached
1108          *
1109          * @return bool Is the load reached?
1110          */
1111         public function isMaxLoadReached()
1112         {
1113                 if ($this->is_backend()) {
1114                         $process = 'backend';
1115                         $maxsysload = intval(Config::get('system', 'maxloadavg'));
1116                         if ($maxsysload < 1) {
1117                                 $maxsysload = 50;
1118                         }
1119                 } else {
1120                         $process = 'frontend';
1121                         $maxsysload = intval(Config::get('system', 'maxloadavg_frontend'));
1122                         if ($maxsysload < 1) {
1123                                 $maxsysload = 50;
1124                         }
1125                 }
1126
1127                 $load = current_load();
1128                 if ($load) {
1129                         if (intval($load) > $maxsysload) {
1130                                 logger('system: load ' . $load . ' for ' . $process . ' tasks (' . $maxsysload . ') too high.');
1131                                 return true;
1132                         }
1133                 }
1134                 return false;
1135         }
1136
1137         /**
1138          * Executes a child process with 'proc_open'
1139          *
1140          * @param string $command The command to execute
1141          * @param array  $args    Arguments to pass to the command ( [ 'key' => value, 'key2' => value2, ... ]
1142          */
1143         public function proc_run($command, $args)
1144         {
1145                 if (!function_exists('proc_open')) {
1146                         return;
1147                 }
1148
1149                 $cmdline = $this->getConfigValue('config', 'php_path', 'php') . ' ' . escapeshellarg($command);
1150
1151                 foreach ($args as $key => $value) {
1152                         if (!is_null($value) && is_bool($value) && !$value) {
1153                                 continue;
1154                         }
1155
1156                         $cmdline .= ' --' . $key;
1157                         if (!is_null($value) && !is_bool($value)) {
1158                                 $cmdline .= ' ' . $value;
1159                         }
1160                 }
1161
1162                 if ($this->min_memory_reached()) {
1163                         return;
1164                 }
1165
1166                 if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
1167                         $resource = proc_open('cmd /c start /b ' . $cmdline, [], $foo, $this->get_basepath());
1168                 } else {
1169                         $resource = proc_open($cmdline . ' &', [], $foo, $this->get_basepath());
1170                 }
1171                 if (!is_resource($resource)) {
1172                         logger('We got no resource for command ' . $cmdline, LOGGER_DEBUG);
1173                         return;
1174                 }
1175                 proc_close($resource);
1176         }
1177
1178         /**
1179          * @brief Returns the system user that is executing the script
1180          *
1181          * This mostly returns something like "www-data".
1182          *
1183          * @return string system username
1184          */
1185         private static function systemuser()
1186         {
1187                 if (!function_exists('posix_getpwuid') || !function_exists('posix_geteuid')) {
1188                         return '';
1189                 }
1190
1191                 $processUser = posix_getpwuid(posix_geteuid());
1192                 return $processUser['name'];
1193         }
1194
1195         /**
1196          * @brief Checks if a given directory is usable for the system
1197          *
1198          * @return boolean the directory is usable
1199          */
1200         public static function directory_usable($directory, $check_writable = true)
1201         {
1202                 if ($directory == '') {
1203                         logger('Directory is empty. This shouldn\'t happen.', LOGGER_DEBUG);
1204                         return false;
1205                 }
1206
1207                 if (!file_exists($directory)) {
1208                         logger('Path "' . $directory . '" does not exist for user ' . self::systemuser(), LOGGER_DEBUG);
1209                         return false;
1210                 }
1211
1212                 if (is_file($directory)) {
1213                         logger('Path "' . $directory . '" is a file for user ' . self::systemuser(), LOGGER_DEBUG);
1214                         return false;
1215                 }
1216
1217                 if (!is_dir($directory)) {
1218                         logger('Path "' . $directory . '" is not a directory for user ' . self::systemuser(), LOGGER_DEBUG);
1219                         return false;
1220                 }
1221
1222                 if ($check_writable && !is_writable($directory)) {
1223                         logger('Path "' . $directory . '" is not writable for user ' . self::systemuser(), LOGGER_DEBUG);
1224                         return false;
1225                 }
1226
1227                 return true;
1228         }
1229
1230         /**
1231          * @param string $cat     Config category
1232          * @param string $k       Config key
1233          * @param mixed  $default Default value if it isn't set
1234          */
1235         public function getConfigValue($cat, $k, $default = null)
1236         {
1237                 $return = $default;
1238
1239                 if ($cat === 'config') {
1240                         if (isset($this->config[$k])) {
1241                                 $return = $this->config[$k];
1242                         }
1243                 } else {
1244                         if (isset($this->config[$cat][$k])) {
1245                                 $return = $this->config[$cat][$k];
1246                         }
1247                 }
1248
1249                 return $return;
1250         }
1251
1252         /**
1253          * Sets a default value in the config cache. Ignores already existing keys.
1254          *
1255          * @param string $cat Config category
1256          * @param string $k   Config key
1257          * @param mixed  $v   Default value to set
1258          */
1259         private function setDefaultConfigValue($cat, $k, $v)
1260         {
1261                 if (!isset($this->config[$cat][$k])) {
1262                         $this->setConfigValue($cat, $k, $v);
1263                 }
1264         }
1265
1266         /**
1267          * Sets a value in the config cache. Accepts raw output from the config table
1268          *
1269          * @param string $cat Config category
1270          * @param string $k   Config key
1271          * @param mixed  $v   Value to set
1272          */
1273         public function setConfigValue($cat, $k, $v)
1274         {
1275                 // Only arrays are serialized in database, so we have to unserialize sparingly
1276                 $value = is_string($v) && preg_match("|^a:[0-9]+:{.*}$|s", $v) ? unserialize($v) : $v;
1277
1278                 if ($cat === 'config') {
1279                         $this->config[$k] = $value;
1280                 } else {
1281                         if (!isset($this->config[$cat])) {
1282                                 $this->config[$cat] = [];
1283                         }
1284
1285                         $this->config[$cat][$k] = $value;
1286                 }
1287         }
1288
1289         /**
1290          * Deletes a value from the config cache
1291          *
1292          * @param string $cat Config category
1293          * @param string $k   Config key
1294          */
1295         public function deleteConfigValue($cat, $k)
1296         {
1297                 if ($cat === 'config') {
1298                         if (isset($this->config[$k])) {
1299                                 unset($this->config[$k]);
1300                         }
1301                 } else {
1302                         if (isset($this->config[$cat][$k])) {
1303                                 unset($this->config[$cat][$k]);
1304                         }
1305                 }
1306         }
1307
1308
1309         /**
1310          * Retrieves a value from the user config cache
1311          *
1312          * @param int    $uid     User Id
1313          * @param string $cat     Config category
1314          * @param string $k       Config key
1315          * @param mixed  $default Default value if key isn't set
1316          */
1317         public function getPConfigValue($uid, $cat, $k, $default = null)
1318         {
1319                 $return = $default;
1320
1321                 if (isset($this->config[$uid][$cat][$k])) {
1322                         $return = $this->config[$uid][$cat][$k];
1323                 }
1324
1325                 return $return;
1326         }
1327
1328         /**
1329          * Sets a value in the user config cache
1330          *
1331          * Accepts raw output from the pconfig table
1332          *
1333          * @param int    $uid User Id
1334          * @param string $cat Config category
1335          * @param string $k   Config key
1336          * @param mixed  $v   Value to set
1337          */
1338         public function setPConfigValue($uid, $cat, $k, $v)
1339         {
1340                 // Only arrays are serialized in database, so we have to unserialize sparingly
1341                 $value = is_string($v) && preg_match("|^a:[0-9]+:{.*}$|s", $v) ? unserialize($v) : $v;
1342
1343                 if (!isset($this->config[$uid]) || !is_array($this->config[$uid])) {
1344                         $this->config[$uid] = [];
1345                 }
1346
1347                 if (!isset($this->config[$uid][$cat]) || !is_array($this->config[$uid][$cat])) {
1348                         $this->config[$uid][$cat] = [];
1349                 }
1350
1351                 $this->config[$uid][$cat][$k] = $value;
1352         }
1353
1354         /**
1355          * Deletes a value from the user config cache
1356          *
1357          * @param int    $uid User Id
1358          * @param string $cat Config category
1359          * @param string $k   Config key
1360          */
1361         public function deletePConfigValue($uid, $cat, $k)
1362         {
1363                 if (isset($this->config[$uid][$cat][$k])) {
1364                         unset($this->config[$uid][$cat][$k]);
1365                 }
1366         }
1367
1368         /**
1369          * Generates the site's default sender email address
1370          *
1371          * @return string
1372          */
1373         public function getSenderEmailAddress()
1374         {
1375                 $sender_email = Config::get('config', 'sender_email');
1376                 if (empty($sender_email)) {
1377                         $hostname = $this->get_hostname();
1378                         if (strpos($hostname, ':')) {
1379                                 $hostname = substr($hostname, 0, strpos($hostname, ':'));
1380                         }
1381
1382                         $sender_email = 'noreply@' . $hostname;
1383                 }
1384
1385                 return $sender_email;
1386         }
1387
1388         /**
1389          * Returns the current theme name.
1390          *
1391          * @return string
1392          */
1393         public function getCurrentTheme()
1394         {
1395                 if ($this->isInstallMode()) {
1396                         return '';
1397                 }
1398
1399                 //// @TODO Compute the current theme only once (this behavior has
1400                 /// already been implemented, but it didn't work well -
1401                 /// https://github.com/friendica/friendica/issues/5092)
1402                 $this->computeCurrentTheme();
1403
1404                 return $this->current_theme;
1405         }
1406
1407         /**
1408          * Computes the current theme name based on the node settings, the user settings and the device type
1409          *
1410          * @throws Exception
1411          */
1412         private function computeCurrentTheme()
1413         {
1414                 $system_theme = Config::get('system', 'theme');
1415                 if (!$system_theme) {
1416                         throw new Exception(L10n::t('No system theme config value set.'));
1417                 }
1418
1419                 // Sane default
1420                 $this->current_theme = $system_theme;
1421
1422                 $allowed_themes = explode(',', Config::get('system', 'allowed_themes', $system_theme));
1423
1424                 $page_theme = null;
1425                 // Find the theme that belongs to the user whose stuff we are looking at
1426                 if ($this->profile_uid && ($this->profile_uid != local_user())) {
1427                         // Allow folks to override user themes and always use their own on their own site.
1428                         // This works only if the user is on the same server
1429                         $user = DBA::selectFirst('user', ['theme'], ['uid' => $this->profile_uid]);
1430                         if (DBA::isResult($user) && !PConfig::get(local_user(), 'system', 'always_my_theme')) {
1431                                 $page_theme = $user['theme'];
1432                         }
1433                 }
1434
1435                 $user_theme = Core\Session::get('theme', $system_theme);
1436
1437                 // Specific mobile theme override
1438                 if (($this->is_mobile || $this->is_tablet) && Core\Session::get('show-mobile', true)) {
1439                         $system_mobile_theme = Config::get('system', 'mobile-theme');
1440                         $user_mobile_theme = Core\Session::get('mobile-theme', $system_mobile_theme);
1441
1442                         // --- means same mobile theme as desktop
1443                         if (!empty($user_mobile_theme) && $user_mobile_theme !== '---') {
1444                                 $user_theme = $user_mobile_theme;
1445                         }
1446                 }
1447
1448                 if ($page_theme) {
1449                         $theme_name = $page_theme;
1450                 } else {
1451                         $theme_name = $user_theme;
1452                 }
1453
1454                 if ($theme_name
1455                         && in_array($theme_name, $allowed_themes)
1456                         && (file_exists('view/theme/' . $theme_name . '/style.css')
1457                         || file_exists('view/theme/' . $theme_name . '/style.php'))
1458                 ) {
1459                         $this->current_theme = $theme_name;
1460                 }
1461         }
1462
1463         /**
1464          * @brief Return full URL to theme which is currently in effect.
1465          *
1466          * Provide a sane default if nothing is chosen or the specified theme does not exist.
1467          *
1468          * @return string
1469          */
1470         public function getCurrentThemeStylesheetPath()
1471         {
1472                 return Core\Theme::getStylesheetPath($this->getCurrentTheme());
1473         }
1474 }