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