]> git.mxchange.org Git - friendica.git/blob - src/App.php
488c2301b6738be5a9162383862b9b4de9b726d4
[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');
376                 }
377         }
378
379         /**
380          * Tries to load the specified configuration file into the App->config array.
381          * Overwrites previously set values.
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          * @throws Exception
395          */
396         public function loadConfigFile($filepath)
397         {
398                 if (!file_exists($filepath)) {
399                         throw new Exception('Error parsing non-existent config file ' . $filepath);
400                 }
401
402                 $contents = include($filepath);
403
404                 $config = parse_ini_string($contents, true, INI_SCANNER_TYPED);
405
406                 if ($config === false) {
407                         throw new Exception('Error parsing config file ' . $filepath);
408                 }
409
410                 foreach ($config as $category => $values) {
411                         foreach ($values as $key => $value) {
412                                 $this->setConfigValue($category, $key, $value);
413                         }
414                 }
415         }
416
417         /**
418          * Loads addons configuration files
419          *
420          * First loads all activated addons default configuration throught the load_config hook, then load the local.ini.php
421          * again to overwrite potential local addon configuration.
422          */
423         private function loadAddonConfig()
424         {
425                 // Loads addons default config
426                 Core\Addon::callHooks('load_config');
427
428                 // Load the local addon config file to overwritten default addon config values
429                 if (file_exists($this->basepath . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'addon.ini.php')) {
430                         $this->loadConfigFile($this->basepath . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'addon.ini.php');
431                 }
432         }
433
434         /**
435          * Loads the default timezone
436          *
437          * Include support for legacy $default_timezone
438          *
439          * @global string $default_timezone
440          */
441         private function loadDefaultTimezone()
442         {
443                 if ($this->getConfigValue('system', 'default_timezone')) {
444                         $this->timezone = $this->getConfigValue('system', 'default_timezone');
445                 } else {
446                         global $default_timezone;
447                         $this->timezone = !empty($default_timezone) ? $default_timezone : 'UTC';
448                 }
449
450                 if ($this->timezone) {
451                         date_default_timezone_set($this->timezone);
452                 }
453         }
454
455         /**
456          * Figure out if we are running at the top of a domain or in a sub-directory and adjust accordingly
457          */
458         private function determineUrlPath()
459         {
460                 $this->urlpath = $this->getConfigValue('system', 'urlpath');
461
462                 /* SCRIPT_URL gives /path/to/friendica/module/parameter
463                  * QUERY_STRING gives pagename=module/parameter
464                  *
465                  * To get /path/to/friendica we perform dirname() for as many levels as there are slashes in the QUERY_STRING
466                  */
467                 if (!empty($_SERVER['SCRIPT_URL'])) {
468                         // Module
469                         if (!empty($_SERVER['QUERY_STRING'])) {
470                                 $path = trim(dirname($_SERVER['SCRIPT_URL'], substr_count(trim($_SERVER['QUERY_STRING'], '/'), '/') + 1), '/');
471                         } else {
472                                 // Root page
473                                 $path = trim($_SERVER['SCRIPT_URL'], '/');
474                         }
475
476                         if ($path && $path != $this->urlpath) {
477                                 $this->urlpath = $path;
478                         }
479                 }
480         }
481
482         /**
483          * Sets the App mode
484          *
485          * - App::MODE_INSTALL    : Either the database connection can't be established or the config table doesn't exist
486          * - App::MODE_MAINTENANCE: The maintenance mode has been set
487          * - App::MODE_NORMAL     : Normal run with all features enabled
488          *
489          * @return type
490          */
491         private function determineMode()
492         {
493                 $this->mode = 0;
494
495                 if (!file_exists($this->basepath . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'local.ini.php')
496                         && !file_exists($this->basepath . DIRECTORY_SEPARATOR . '.htconfig.php')) {
497                         return;
498                 }
499
500                 $this->mode |= App::MODE_LOCALCONFIGPRESENT;
501
502                 if (!DBA::connected()) {
503                         return;
504                 }
505
506                 $this->mode |= App::MODE_DBAVAILABLE;
507
508                 if (DBA::fetchFirst("SHOW TABLES LIKE 'config'") === false) {
509                         return;
510                 }
511
512                 $this->mode |= App::MODE_DBCONFIGAVAILABLE;
513
514                 if (Config::get('system', 'maintenance')) {
515                         return;
516                 }
517
518                 $this->mode |= App::MODE_MAINTENANCEDISABLED;
519         }
520
521         public function loadDatabase()
522         {
523                 if (DBA::connected()) {
524                         return;
525                 }
526
527                 $db_host = $this->getConfigValue('database', 'hostname');
528                 $db_user = $this->getConfigValue('database', 'username');
529                 $db_pass = $this->getConfigValue('database', 'password');
530                 $db_data = $this->getConfigValue('database', 'database');
531                 $charset = $this->getConfigValue('database', 'charset');
532
533                 // Use environment variables for mysql if they are set beforehand
534                 if (!empty(getenv('MYSQL_HOST'))
535                         && (!empty(getenv('MYSQL_USERNAME')) || !empty(getenv('MYSQL_USER')))
536                         && getenv('MYSQL_PASSWORD') !== false
537                         && !empty(getenv('MYSQL_DATABASE')))
538                 {
539                         $db_host = getenv('MYSQL_HOST');
540                         if (!empty(getenv('MYSQL_PORT'))) {
541                                 $db_host .= ':' . getenv('MYSQL_PORT');
542                         }
543                         if (!empty(getenv('MYSQL_USERNAME'))) {
544                                 $db_user = getenv('MYSQL_USERNAME');
545                         } else {
546                                 $db_user = getenv('MYSQL_USER');
547                         }
548                         $db_pass = (string) getenv('MYSQL_PASSWORD');
549                         $db_data = getenv('MYSQL_DATABASE');
550                 }
551
552                 $stamp1 = microtime(true);
553
554                 DBA::connect($db_host, $db_user, $db_pass, $db_data, $charset);
555                 unset($db_host, $db_user, $db_pass, $db_data, $charset);
556
557                 $this->save_timestamp($stamp1, 'network');
558         }
559
560         /**
561          * Install mode is when the local config file is missing or the DB schema hasn't been installed yet.
562          *
563          * @return bool
564          */
565         public function isInstallMode()
566         {
567                 return !($this->mode & App::MODE_LOCALCONFIGPRESENT) || !($this->mode & App::MODE_DBCONFIGAVAILABLE);
568         }
569
570         /**
571          * @brief Returns the base filesystem path of the App
572          *
573          * It first checks for the internal variable, then for DOCUMENT_ROOT and
574          * finally for PWD
575          *
576          * @return string
577          */
578         public function get_basepath()
579         {
580                 $basepath = $this->basepath;
581
582                 if (!$basepath) {
583                         $basepath = Config::get('system', 'basepath');
584                 }
585
586                 if (!$basepath && x($_SERVER, 'DOCUMENT_ROOT')) {
587                         $basepath = $_SERVER['DOCUMENT_ROOT'];
588                 }
589
590                 if (!$basepath && x($_SERVER, 'PWD')) {
591                         $basepath = $_SERVER['PWD'];
592                 }
593
594                 return self::realpath($basepath);
595         }
596
597         /**
598          * @brief Returns a normalized file path
599          *
600          * This is a wrapper for the "realpath" function.
601          * That function cannot detect the real path when some folders aren't readable.
602          * Since this could happen with some hosters we need to handle this.
603          *
604          * @param string $path The path that is about to be normalized
605          * @return string normalized path - when possible
606          */
607         public static function realpath($path)
608         {
609                 $normalized = realpath($path);
610
611                 if (!is_bool($normalized)) {
612                         return $normalized;
613                 } else {
614                         return $path;
615                 }
616         }
617
618         public function get_scheme()
619         {
620                 return $this->scheme;
621         }
622
623         /**
624          * @brief Retrieves the Friendica instance base URL
625          *
626          * This function assembles the base URL from multiple parts:
627          * - Protocol is determined either by the request or a combination of
628          * system.ssl_policy and the $ssl parameter.
629          * - Host name is determined either by system.hostname or inferred from request
630          * - Path is inferred from SCRIPT_NAME
631          *
632          * Note: $ssl parameter value doesn't directly correlate with the resulting protocol
633          *
634          * @param bool $ssl Whether to append http or https under SSL_POLICY_SELFSIGN
635          * @return string Friendica server base URL
636          */
637         public function get_baseurl($ssl = false)
638         {
639                 $scheme = $this->scheme;
640
641                 if (Config::get('system', 'ssl_policy') == SSL_POLICY_FULL) {
642                         $scheme = 'https';
643                 }
644
645                 //      Basically, we have $ssl = true on any links which can only be seen by a logged in user
646                 //      (and also the login link). Anything seen by an outsider will have it turned off.
647
648                 if (Config::get('system', 'ssl_policy') == SSL_POLICY_SELFSIGN) {
649                         if ($ssl) {
650                                 $scheme = 'https';
651                         } else {
652                                 $scheme = 'http';
653                         }
654                 }
655
656                 if (Config::get('config', 'hostname') != '') {
657                         $this->hostname = Config::get('config', 'hostname');
658                 }
659
660                 return $scheme . '://' . $this->hostname . (!empty($this->urlpath) ? '/' . $this->urlpath : '' );
661         }
662
663         /**
664          * @brief Initializes the baseurl components
665          *
666          * Clears the baseurl cache to prevent inconsistencies
667          *
668          * @param string $url
669          */
670         public function set_baseurl($url)
671         {
672                 $parsed = @parse_url($url);
673                 $hostname = '';
674
675                 if (x($parsed)) {
676                         if (!empty($parsed['scheme'])) {
677                                 $this->scheme = $parsed['scheme'];
678                         }
679
680                         if (!empty($parsed['host'])) {
681                                 $hostname = $parsed['host'];
682                         }
683
684                         if (x($parsed, 'port')) {
685                                 $hostname .= ':' . $parsed['port'];
686                         }
687                         if (x($parsed, 'path')) {
688                                 $this->urlpath = trim($parsed['path'], '\\/');
689                         }
690
691                         if (file_exists($this->basepath . DIRECTORY_SEPARATOR . '.htpreconfig.php')) {
692                                 include $this->basepath . DIRECTORY_SEPARATOR . '.htpreconfig.php';
693                         }
694
695                         if (Config::get('config', 'hostname') != '') {
696                                 $this->hostname = Config::get('config', 'hostname');
697                         }
698
699                         if (!isset($this->hostname) || ($this->hostname == '')) {
700                                 $this->hostname = $hostname;
701                         }
702                 }
703         }
704
705         public function get_hostname()
706         {
707                 if (Config::get('config', 'hostname') != '') {
708                         $this->hostname = Config::get('config', 'hostname');
709                 }
710
711                 return $this->hostname;
712         }
713
714         public function get_path()
715         {
716                 return $this->urlpath;
717         }
718
719         public function set_pager_total($n)
720         {
721                 $this->pager['total'] = intval($n);
722         }
723
724         public function set_pager_itemspage($n)
725         {
726                 $this->pager['itemspage'] = ((intval($n) > 0) ? intval($n) : 0);
727                 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
728         }
729
730         public function set_pager_page($n)
731         {
732                 $this->pager['page'] = $n;
733                 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
734         }
735
736         public function init_pagehead()
737         {
738                 $interval = ((local_user()) ? PConfig::get(local_user(), 'system', 'update_interval') : 40000);
739
740                 // If the update is 'deactivated' set it to the highest integer number (~24 days)
741                 if ($interval < 0) {
742                         $interval = 2147483647;
743                 }
744
745                 if ($interval < 10000) {
746                         $interval = 40000;
747                 }
748
749                 // compose the page title from the sitename and the
750                 // current module called
751                 if (!$this->module == '') {
752                         $this->page['title'] = $this->config['sitename'] . ' (' . $this->module . ')';
753                 } else {
754                         $this->page['title'] = $this->config['sitename'];
755                 }
756
757                 /* put the head template at the beginning of page['htmlhead']
758                  * since the code added by the modules frequently depends on it
759                  * being first
760                  */
761                 if (!isset($this->page['htmlhead'])) {
762                         $this->page['htmlhead'] = '';
763                 }
764
765                 // If we're using Smarty, then doing replace_macros() will replace
766                 // any unrecognized variables with a blank string. Since we delay
767                 // replacing $stylesheet until later, we need to replace it now
768                 // with another variable name
769                 if ($this->theme['template_engine'] === 'smarty3') {
770                         $stylesheet = $this->get_template_ldelim('smarty3') . '$stylesheet' . $this->get_template_rdelim('smarty3');
771                 } else {
772                         $stylesheet = '$stylesheet';
773                 }
774
775                 $shortcut_icon = Config::get('system', 'shortcut_icon');
776                 if ($shortcut_icon == '') {
777                         $shortcut_icon = 'images/friendica-32.png';
778                 }
779
780                 $touch_icon = Config::get('system', 'touch_icon');
781                 if ($touch_icon == '') {
782                         $touch_icon = 'images/friendica-128.png';
783                 }
784
785                 // get data wich is needed for infinite scroll on the network page
786                 $invinite_scroll = infinite_scroll_data($this->module);
787
788                 $tpl = get_markup_template('head.tpl');
789                 $this->page['htmlhead'] = replace_macros($tpl, [
790                         '$baseurl'         => $this->get_baseurl(),
791                         '$local_user'      => local_user(),
792                         '$generator'       => 'Friendica' . ' ' . FRIENDICA_VERSION,
793                         '$delitem'         => L10n::t('Delete this item?'),
794                         '$showmore'        => L10n::t('show more'),
795                         '$showfewer'       => L10n::t('show fewer'),
796                         '$update_interval' => $interval,
797                         '$shortcut_icon'   => $shortcut_icon,
798                         '$touch_icon'      => $touch_icon,
799                         '$stylesheet'      => $stylesheet,
800                         '$infinite_scroll' => $invinite_scroll,
801                         '$block_public'    => intval(Config::get('system', 'block_public')),
802                 ]) . $this->page['htmlhead'];
803         }
804
805         public function init_page_end()
806         {
807                 if (!isset($this->page['end'])) {
808                         $this->page['end'] = '';
809                 }
810                 $tpl = get_markup_template('end.tpl');
811                 $this->page['end'] = replace_macros($tpl, [
812                         '$baseurl' => $this->get_baseurl()
813                 ]) . $this->page['end'];
814         }
815
816         public function set_curl_code($code)
817         {
818                 $this->curl_code = $code;
819         }
820
821         public function get_curl_code()
822         {
823                 return $this->curl_code;
824         }
825
826         public function set_curl_content_type($content_type)
827         {
828                 $this->curl_content_type = $content_type;
829         }
830
831         public function get_curl_content_type()
832         {
833                 return $this->curl_content_type;
834         }
835
836         public function set_curl_headers($headers)
837         {
838                 $this->curl_headers = $headers;
839         }
840
841         public function get_curl_headers()
842         {
843                 return $this->curl_headers;
844         }
845
846         /**
847          * @brief Removes the base url from an url. This avoids some mixed content problems.
848          *
849          * @param string $orig_url
850          *
851          * @return string The cleaned url
852          */
853         public function remove_baseurl($orig_url)
854         {
855                 // Remove the hostname from the url if it is an internal link
856                 $nurl = normalise_link($orig_url);
857                 $base = normalise_link($this->get_baseurl());
858                 $url = str_replace($base . '/', '', $nurl);
859
860                 // if it is an external link return the orignal value
861                 if ($url == normalise_link($orig_url)) {
862                         return $orig_url;
863                 } else {
864                         return $url;
865                 }
866         }
867
868         /**
869          * @brief Register template engine class
870          *
871          * @param string $class
872          */
873         private function register_template_engine($class)
874         {
875                 $v = get_class_vars($class);
876                 if (x($v, 'name')) {
877                         $name = $v['name'];
878                         $this->template_engines[$name] = $class;
879                 } else {
880                         echo "template engine <tt>$class</tt> cannot be registered without a name.\n";
881                         die();
882                 }
883         }
884
885         /**
886          * @brief Return template engine instance.
887          *
888          * If $name is not defined, return engine defined by theme,
889          * or default
890          *
891          * @return object Template Engine instance
892          */
893         public function template_engine()
894         {
895                 $template_engine = 'smarty3';
896                 if (x($this->theme, 'template_engine')) {
897                         $template_engine = $this->theme['template_engine'];
898                 }
899
900                 if (isset($this->template_engines[$template_engine])) {
901                         if (isset($this->template_engine_instance[$template_engine])) {
902                                 return $this->template_engine_instance[$template_engine];
903                         } else {
904                                 $class = $this->template_engines[$template_engine];
905                                 $obj = new $class;
906                                 $this->template_engine_instance[$template_engine] = $obj;
907                                 return $obj;
908                         }
909                 }
910
911                 echo "template engine <tt>$template_engine</tt> is not registered!\n";
912                 killme();
913         }
914
915         /**
916          * @brief Returns the active template engine.
917          *
918          * @return string
919          */
920         public function get_template_engine()
921         {
922                 return $this->theme['template_engine'];
923         }
924
925         public function set_template_engine($engine = 'smarty3')
926         {
927                 $this->theme['template_engine'] = $engine;
928         }
929
930         public function get_template_ldelim($engine = 'smarty3')
931         {
932                 return $this->ldelim[$engine];
933         }
934
935         public function get_template_rdelim($engine = 'smarty3')
936         {
937                 return $this->rdelim[$engine];
938         }
939
940         public function save_timestamp($stamp, $value)
941         {
942                 if (!isset($this->config['system']['profiler']) || !$this->config['system']['profiler']) {
943                         return;
944                 }
945
946                 $duration = (float) (microtime(true) - $stamp);
947
948                 if (!isset($this->performance[$value])) {
949                         // Prevent ugly E_NOTICE
950                         $this->performance[$value] = 0;
951                 }
952
953                 $this->performance[$value] += (float) $duration;
954                 $this->performance['marktime'] += (float) $duration;
955
956                 $callstack = System::callstack();
957
958                 if (!isset($this->callstack[$value][$callstack])) {
959                         // Prevent ugly E_NOTICE
960                         $this->callstack[$value][$callstack] = 0;
961                 }
962
963                 $this->callstack[$value][$callstack] += (float) $duration;
964         }
965
966         public function get_useragent()
967         {
968                 return
969                         FRIENDICA_PLATFORM . " '" .
970                         FRIENDICA_CODENAME . "' " .
971                         FRIENDICA_VERSION . '-' .
972                         DB_UPDATE_VERSION . '; ' .
973                         $this->get_baseurl();
974         }
975
976         public function is_friendica_app()
977         {
978                 return $this->is_friendica_app;
979         }
980
981         /**
982          * @brief Checks if the site is called via a backend process
983          *
984          * This isn't a perfect solution. But we need this check very early.
985          * So we cannot wait until the modules are loaded.
986          *
987          * @return bool Is it a known backend?
988          */
989         public function is_backend()
990         {
991                 static $backends = [
992                         '_well_known',
993                         'api',
994                         'dfrn_notify',
995                         'fetch',
996                         'hcard',
997                         'hostxrd',
998                         'nodeinfo',
999                         'noscrape',
1000                         'p',
1001                         'poco',
1002                         'post',
1003                         'proxy',
1004                         'pubsub',
1005                         'pubsubhubbub',
1006                         'receive',
1007                         'rsd_xml',
1008                         'salmon',
1009                         'statistics_json',
1010                         'xrd',
1011                 ];
1012
1013                 // Check if current module is in backend or backend flag is set
1014                 return (in_array($this->module, $backends) || $this->backend);
1015         }
1016
1017         /**
1018          * @brief Checks if the maximum number of database processes is reached
1019          *
1020          * @return bool Is the limit reached?
1021          */
1022         public function isMaxProcessesReached()
1023         {
1024                 // Deactivated, needs more investigating if this check really makes sense
1025                 return false;
1026
1027                 /*
1028                  * Commented out to suppress static analyzer issues
1029                  *
1030                 if ($this->is_backend()) {
1031                         $process = 'backend';
1032                         $max_processes = Config::get('system', 'max_processes_backend');
1033                         if (intval($max_processes) == 0) {
1034                                 $max_processes = 5;
1035                         }
1036                 } else {
1037                         $process = 'frontend';
1038                         $max_processes = Config::get('system', 'max_processes_frontend');
1039                         if (intval($max_processes) == 0) {
1040                                 $max_processes = 20;
1041                         }
1042                 }
1043
1044                 $processlist = DBA::processlist();
1045                 if ($processlist['list'] != '') {
1046                         logger('Processcheck: Processes: ' . $processlist['amount'] . ' - Processlist: ' . $processlist['list'], LOGGER_DEBUG);
1047
1048                         if ($processlist['amount'] > $max_processes) {
1049                                 logger('Processcheck: Maximum number of processes for ' . $process . ' tasks (' . $max_processes . ') reached.', LOGGER_DEBUG);
1050                                 return true;
1051                         }
1052                 }
1053                 return false;
1054                  */
1055         }
1056
1057         /**
1058          * @brief Checks if the minimal memory is reached
1059          *
1060          * @return bool Is the memory limit reached?
1061          */
1062         public function min_memory_reached()
1063         {
1064                 $min_memory = Config::get('system', 'min_memory', 0);
1065                 if ($min_memory == 0) {
1066                         return false;
1067                 }
1068
1069                 if (!is_readable('/proc/meminfo')) {
1070                         return false;
1071                 }
1072
1073                 $memdata = explode("\n", file_get_contents('/proc/meminfo'));
1074
1075                 $meminfo = [];
1076                 foreach ($memdata as $line) {
1077                         $data = explode(':', $line);
1078                         if (count($data) != 2) {
1079                                 continue;
1080                         }
1081                         list($key, $val) = $data;
1082                         $meminfo[$key] = (int) trim(str_replace('kB', '', $val));
1083                         $meminfo[$key] = (int) ($meminfo[$key] / 1024);
1084                 }
1085
1086                 if (!isset($meminfo['MemAvailable']) || !isset($meminfo['MemFree'])) {
1087                         return false;
1088                 }
1089
1090                 $free = $meminfo['MemAvailable'] + $meminfo['MemFree'];
1091
1092                 $reached = ($free < $min_memory);
1093
1094                 if ($reached) {
1095                         logger('Minimal memory reached: ' . $free . '/' . $meminfo['MemTotal'] . ' - limit ' . $min_memory, LOGGER_DEBUG);
1096                 }
1097
1098                 return $reached;
1099         }
1100
1101         /**
1102          * @brief Checks if the maximum load is reached
1103          *
1104          * @return bool Is the load reached?
1105          */
1106         public function isMaxLoadReached()
1107         {
1108                 if ($this->is_backend()) {
1109                         $process = 'backend';
1110                         $maxsysload = intval(Config::get('system', 'maxloadavg'));
1111                         if ($maxsysload < 1) {
1112                                 $maxsysload = 50;
1113                         }
1114                 } else {
1115                         $process = 'frontend';
1116                         $maxsysload = intval(Config::get('system', 'maxloadavg_frontend'));
1117                         if ($maxsysload < 1) {
1118                                 $maxsysload = 50;
1119                         }
1120                 }
1121
1122                 $load = current_load();
1123                 if ($load) {
1124                         if (intval($load) > $maxsysload) {
1125                                 logger('system: load ' . $load . ' for ' . $process . ' tasks (' . $maxsysload . ') too high.');
1126                                 return true;
1127                         }
1128                 }
1129                 return false;
1130         }
1131
1132         /**
1133          * Executes a child process with 'proc_open'
1134          *
1135          * @param string $command The command to execute
1136          * @param array  $args    Arguments to pass to the command ( [ 'key' => value, 'key2' => value2, ... ]
1137          */
1138         public function proc_run($command, $args)
1139         {
1140                 if (!function_exists('proc_open')) {
1141                         return;
1142                 }
1143
1144                 $cmdline = $this->getConfigValue('config', 'php_path', 'php') . ' ' . escapeshellarg($command);
1145
1146                 foreach ($args as $key => $value) {
1147                         if (!is_null($value) && is_bool($value) && !$value) {
1148                                 continue;
1149                         }
1150
1151                         $cmdline .= ' --' . $key;
1152                         if (!is_null($value) && !is_bool($value)) {
1153                                 $cmdline .= ' ' . $value;
1154                         }
1155                 }
1156
1157                 if ($this->min_memory_reached()) {
1158                         return;
1159                 }
1160
1161                 if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
1162                         $resource = proc_open('cmd /c start /b ' . $cmdline, [], $foo, $this->get_basepath());
1163                 } else {
1164                         $resource = proc_open($cmdline . ' &', [], $foo, $this->get_basepath());
1165                 }
1166                 if (!is_resource($resource)) {
1167                         logger('We got no resource for command ' . $cmdline, LOGGER_DEBUG);
1168                         return;
1169                 }
1170                 proc_close($resource);
1171         }
1172
1173         /**
1174          * @brief Returns the system user that is executing the script
1175          *
1176          * This mostly returns something like "www-data".
1177          *
1178          * @return string system username
1179          */
1180         private static function systemuser()
1181         {
1182                 if (!function_exists('posix_getpwuid') || !function_exists('posix_geteuid')) {
1183                         return '';
1184                 }
1185
1186                 $processUser = posix_getpwuid(posix_geteuid());
1187                 return $processUser['name'];
1188         }
1189
1190         /**
1191          * @brief Checks if a given directory is usable for the system
1192          *
1193          * @return boolean the directory is usable
1194          */
1195         public static function directory_usable($directory, $check_writable = true)
1196         {
1197                 if ($directory == '') {
1198                         logger('Directory is empty. This shouldn\'t happen.', LOGGER_DEBUG);
1199                         return false;
1200                 }
1201
1202                 if (!file_exists($directory)) {
1203                         logger('Path "' . $directory . '" does not exist for user ' . self::systemuser(), LOGGER_DEBUG);
1204                         return false;
1205                 }
1206
1207                 if (is_file($directory)) {
1208                         logger('Path "' . $directory . '" is a file for user ' . self::systemuser(), LOGGER_DEBUG);
1209                         return false;
1210                 }
1211
1212                 if (!is_dir($directory)) {
1213                         logger('Path "' . $directory . '" is not a directory for user ' . self::systemuser(), LOGGER_DEBUG);
1214                         return false;
1215                 }
1216
1217                 if ($check_writable && !is_writable($directory)) {
1218                         logger('Path "' . $directory . '" is not writable for user ' . self::systemuser(), LOGGER_DEBUG);
1219                         return false;
1220                 }
1221
1222                 return true;
1223         }
1224
1225         /**
1226          * @param string $cat     Config category
1227          * @param string $k       Config key
1228          * @param mixed  $default Default value if it isn't set
1229          */
1230         public function getConfigValue($cat, $k, $default = null)
1231         {
1232                 $return = $default;
1233
1234                 if ($cat === 'config') {
1235                         if (isset($this->config[$k])) {
1236                                 $return = $this->config[$k];
1237                         }
1238                 } else {
1239                         if (isset($this->config[$cat][$k])) {
1240                                 $return = $this->config[$cat][$k];
1241                         }
1242                 }
1243
1244                 return $return;
1245         }
1246
1247         /**
1248          * Sets a value in the config cache. Accepts raw output from the config table
1249          *
1250          * @param string $cat Config category
1251          * @param string $k   Config key
1252          * @param mixed  $v   Value to set
1253          */
1254         public function setConfigValue($cat, $k, $v)
1255         {
1256                 // Only arrays are serialized in database, so we have to unserialize sparingly
1257                 $value = is_string($v) && preg_match("|^a:[0-9]+:{.*}$|s", $v) ? unserialize($v) : $v;
1258
1259                 if ($cat === 'config') {
1260                         $this->config[$k] = $value;
1261                 } else {
1262                         if (!isset($this->config[$cat])) {
1263                                 $this->config[$cat] = [];
1264                         }
1265
1266                         $this->config[$cat][$k] = $value;
1267                 }
1268         }
1269
1270         /**
1271          * Deletes a value from the config cache
1272          *
1273          * @param string $cat Config category
1274          * @param string $k   Config key
1275          */
1276         public function deleteConfigValue($cat, $k)
1277         {
1278                 if ($cat === 'config') {
1279                         if (isset($this->config[$k])) {
1280                                 unset($this->config[$k]);
1281                         }
1282                 } else {
1283                         if (isset($this->config[$cat][$k])) {
1284                                 unset($this->config[$cat][$k]);
1285                         }
1286                 }
1287         }
1288
1289
1290         /**
1291          * Retrieves a value from the user config cache
1292          *
1293          * @param int    $uid     User Id
1294          * @param string $cat     Config category
1295          * @param string $k       Config key
1296          * @param mixed  $default Default value if key isn't set
1297          */
1298         public function getPConfigValue($uid, $cat, $k, $default = null)
1299         {
1300                 $return = $default;
1301
1302                 if (isset($this->config[$uid][$cat][$k])) {
1303                         $return = $this->config[$uid][$cat][$k];
1304                 }
1305
1306                 return $return;
1307         }
1308
1309         /**
1310          * Sets a value in the user config cache
1311          *
1312          * Accepts raw output from the pconfig table
1313          *
1314          * @param int    $uid User Id
1315          * @param string $cat Config category
1316          * @param string $k   Config key
1317          * @param mixed  $v   Value to set
1318          */
1319         public function setPConfigValue($uid, $cat, $k, $v)
1320         {
1321                 // Only arrays are serialized in database, so we have to unserialize sparingly
1322                 $value = is_string($v) && preg_match("|^a:[0-9]+:{.*}$|s", $v) ? unserialize($v) : $v;
1323
1324                 if (!isset($this->config[$uid]) || !is_array($this->config[$uid])) {
1325                         $this->config[$uid] = [];
1326                 }
1327
1328                 if (!isset($this->config[$uid][$cat]) || !is_array($this->config[$uid][$cat])) {
1329                         $this->config[$uid][$cat] = [];
1330                 }
1331
1332                 $this->config[$uid][$cat][$k] = $value;
1333         }
1334
1335         /**
1336          * Deletes a value from the user config cache
1337          *
1338          * @param int    $uid User Id
1339          * @param string $cat Config category
1340          * @param string $k   Config key
1341          */
1342         public function deletePConfigValue($uid, $cat, $k)
1343         {
1344                 if (isset($this->config[$uid][$cat][$k])) {
1345                         unset($this->config[$uid][$cat][$k]);
1346                 }
1347         }
1348
1349         /**
1350          * Generates the site's default sender email address
1351          *
1352          * @return string
1353          */
1354         public function getSenderEmailAddress()
1355         {
1356                 $sender_email = Config::get('config', 'sender_email');
1357                 if (empty($sender_email)) {
1358                         $hostname = $this->get_hostname();
1359                         if (strpos($hostname, ':')) {
1360                                 $hostname = substr($hostname, 0, strpos($hostname, ':'));
1361                         }
1362
1363                         $sender_email = 'noreply@' . $hostname;
1364                 }
1365
1366                 return $sender_email;
1367         }
1368
1369         /**
1370          * Returns the current theme name.
1371          *
1372          * @return string
1373          */
1374         public function getCurrentTheme()
1375         {
1376                 if ($this->isInstallMode()) {
1377                         return '';
1378                 }
1379
1380                 //// @TODO Compute the current theme only once (this behavior has
1381                 /// already been implemented, but it didn't work well -
1382                 /// https://github.com/friendica/friendica/issues/5092)
1383                 $this->computeCurrentTheme();
1384
1385                 return $this->current_theme;
1386         }
1387
1388         /**
1389          * Computes the current theme name based on the node settings, the user settings and the device type
1390          *
1391          * @throws Exception
1392          */
1393         private function computeCurrentTheme()
1394         {
1395                 $system_theme = Config::get('system', 'theme');
1396                 if (!$system_theme) {
1397                         throw new Exception(L10n::t('No system theme config value set.'));
1398                 }
1399
1400                 // Sane default
1401                 $this->current_theme = $system_theme;
1402
1403                 $allowed_themes = explode(',', Config::get('system', 'allowed_themes', $system_theme));
1404
1405                 $page_theme = null;
1406                 // Find the theme that belongs to the user whose stuff we are looking at
1407                 if ($this->profile_uid && ($this->profile_uid != local_user())) {
1408                         // Allow folks to override user themes and always use their own on their own site.
1409                         // This works only if the user is on the same server
1410                         $user = DBA::selectFirst('user', ['theme'], ['uid' => $this->profile_uid]);
1411                         if (DBA::isResult($user) && !PConfig::get(local_user(), 'system', 'always_my_theme')) {
1412                                 $page_theme = $user['theme'];
1413                         }
1414                 }
1415
1416                 $user_theme = Core\Session::get('theme', $system_theme);
1417
1418                 // Specific mobile theme override
1419                 if (($this->is_mobile || $this->is_tablet) && Core\Session::get('show-mobile', true)) {
1420                         $system_mobile_theme = Config::get('system', 'mobile-theme');
1421                         $user_mobile_theme = Core\Session::get('mobile-theme', $system_mobile_theme);
1422
1423                         // --- means same mobile theme as desktop
1424                         if (!empty($user_mobile_theme) && $user_mobile_theme !== '---') {
1425                                 $user_theme = $user_mobile_theme;
1426                         }
1427                 }
1428
1429                 if ($page_theme) {
1430                         $theme_name = $page_theme;
1431                 } else {
1432                         $theme_name = $user_theme;
1433                 }
1434
1435                 if ($theme_name
1436                         && in_array($theme_name, $allowed_themes)
1437                         && (file_exists('view/theme/' . $theme_name . '/style.css')
1438                         || file_exists('view/theme/' . $theme_name . '/style.php'))
1439                 ) {
1440                         $this->current_theme = $theme_name;
1441                 }
1442         }
1443
1444         /**
1445          * @brief Return full URL to theme which is currently in effect.
1446          *
1447          * Provide a sane default if nothing is chosen or the specified theme does not exist.
1448          *
1449          * @return string
1450          */
1451         public function getCurrentThemeStylesheetPath()
1452         {
1453                 return Core\Theme::getStylesheetPath($this->getCurrentTheme());
1454         }
1455 }