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