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