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