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