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