7 use Friendica\Core\Cache;
8 use Friendica\Core\Config;
9 use Friendica\Core\L10n;
10 use Friendica\Core\PConfig;
11 use Friendica\Core\System;
12 use Friendica\Database\DBM;
15 use Detection\MobileDetect;
19 require_once 'boot.php';
20 require_once 'include/text.php';
26 * @brief Our main application structure for the life of this page.
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.
37 const MODE_NORMAL = 0;
38 const MODE_INSTALL = 1;
39 const MODE_MAINTENANCE = 2;
41 public $module_loaded = false;
42 public $module_class = null;
56 public $error = false;
61 public $mode = App::MODE_NORMAL;
68 public $interactive = true;
70 public $addons_admin = [];
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;
82 // Allow themes to control internal parameters
83 // by changing App values in theme.php
85 public $sourcename = '';
86 public $videowidth = 425;
87 public $videoheight = 350;
88 public $force_max_items = 0;
89 public $theme_events_in_profile = true;
92 * @brief An array for all theme-controllable parameters
94 * Mostly unimplemented yet. Only options 'template_engine' and
100 'videoheight' => 350,
101 'force_max_items' => 0,
103 'template_engine' => 'smarty3',
107 * @brief An array of registered template engines ('name'=>'class name')
109 public $template_engines = [];
112 * @brief An array of instanced template engines ('name'=>'instance')
114 public $template_engine_instance = [];
128 private $curl_content_type;
129 private $curl_headers;
133 * @brief App constructor.
135 * @param string $basepath Path to the app base folder
137 public function __construct($basepath)
139 global $default_timezone;
141 if (!static::directory_usable($basepath, false)) {
142 throw new Exception('Basepath ' . $basepath . ' isn\'t usable.');
145 $this->basepath = rtrim($basepath, DIRECTORY_SEPARATOR);
147 if (file_exists($this->basepath . DIRECTORY_SEPARATOR . '.htpreconfig.php')) {
148 include $this->basepath . DIRECTORY_SEPARATOR . '.htpreconfig.php';
151 $this->timezone = ((x($default_timezone)) ? $default_timezone : 'UTC');
153 date_default_timezone_set($this->timezone);
155 $this->performance['start'] = microtime(true);
156 $this->performance['database'] = 0;
157 $this->performance['database_write'] = 0;
158 $this->performance['cache'] = 0;
159 $this->performance['cache_write'] = 0;
160 $this->performance['network'] = 0;
161 $this->performance['file'] = 0;
162 $this->performance['rendering'] = 0;
163 $this->performance['parser'] = 0;
164 $this->performance['marktime'] = 0;
165 $this->performance['markstart'] = microtime(true);
167 $this->callstack['database'] = [];
168 $this->callstack['database_write'] = [];
169 $this->callstack['cache'] = [];
170 $this->callstack['cache_write'] = [];
171 $this->callstack['network'] = [];
172 $this->callstack['file'] = [];
173 $this->callstack['rendering'] = [];
174 $this->callstack['parser'] = [];
180 $this->query_string = '';
182 $this->process_id = uniqid('log', true);
186 // This has to be quite large to deal with embedded private photos
187 ini_set('pcre.backtrack_limit', 500000);
189 $this->scheme = 'http';
191 if ((x($_SERVER, 'HTTPS') && $_SERVER['HTTPS']) ||
192 (x($_SERVER, 'HTTP_FORWARDED') && preg_match('/proto=https/', $_SERVER['HTTP_FORWARDED'])) ||
193 (x($_SERVER, 'HTTP_X_FORWARDED_PROTO') && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') ||
194 (x($_SERVER, 'HTTP_X_FORWARDED_SSL') && $_SERVER['HTTP_X_FORWARDED_SSL'] == 'on') ||
195 (x($_SERVER, 'FRONT_END_HTTPS') && $_SERVER['FRONT_END_HTTPS'] == 'on') ||
196 (x($_SERVER, 'SERVER_PORT') && (intval($_SERVER['SERVER_PORT']) == 443)) // XXX: reasonable assumption, but isn't this hardcoding too much?
198 $this->scheme = 'https';
201 if (x($_SERVER, 'SERVER_NAME')) {
202 $this->hostname = $_SERVER['SERVER_NAME'];
204 if (x($_SERVER, 'SERVER_PORT') && $_SERVER['SERVER_PORT'] != 80 && $_SERVER['SERVER_PORT'] != 443) {
205 $this->hostname .= ':' . $_SERVER['SERVER_PORT'];
208 * Figure out if we are running at the top of a domain
209 * or in a sub-directory and adjust accordingly
212 /// @TODO This kind of escaping breaks syntax-highlightning on CoolEdit (Midnight Commander)
213 $path = trim(dirname($_SERVER['SCRIPT_NAME']), '/\\');
214 if (isset($path) && strlen($path) && ($path != $this->path)) {
220 get_include_path() . PATH_SEPARATOR
221 . $this->basepath . DIRECTORY_SEPARATOR . 'include' . PATH_SEPARATOR
222 . $this->basepath . DIRECTORY_SEPARATOR . 'library' . PATH_SEPARATOR
225 if ((x($_SERVER, 'QUERY_STRING')) && substr($_SERVER['QUERY_STRING'], 0, 9) === 'pagename=') {
226 $this->query_string = substr($_SERVER['QUERY_STRING'], 9);
228 // removing trailing / - maybe a nginx problem
229 $this->query_string = ltrim($this->query_string, '/');
230 } elseif ((x($_SERVER, 'QUERY_STRING')) && substr($_SERVER['QUERY_STRING'], 0, 2) === 'q=') {
231 $this->query_string = substr($_SERVER['QUERY_STRING'], 2);
233 // removing trailing / - maybe a nginx problem
234 $this->query_string = ltrim($this->query_string, '/');
237 if (x($_GET, 'pagename')) {
238 $this->cmd = trim($_GET['pagename'], '/\\');
239 } elseif (x($_GET, 'q')) {
240 $this->cmd = trim($_GET['q'], '/\\');
244 $this->query_string = str_replace($this->cmd . '&', $this->cmd . '?', $this->query_string);
246 // unix style "homedir"
247 if (substr($this->cmd, 0, 1) === '~') {
248 $this->cmd = 'profile/' . substr($this->cmd, 1);
251 // Diaspora style profile url
252 if (substr($this->cmd, 0, 2) === 'u/') {
253 $this->cmd = 'profile/' . substr($this->cmd, 2);
257 * Break the URL path into C style argc/argv style arguments for our
258 * modules. Given "http://example.com/module/arg1/arg2", $this->argc
259 * will be 3 (integer) and $this->argv will contain:
265 * There will always be one argument. If provided a naked domain
266 * URL, $this->argv[0] is set to "home".
269 $this->argv = explode('/', $this->cmd);
270 $this->argc = count($this->argv);
271 if ((array_key_exists('0', $this->argv)) && strlen($this->argv[0])) {
272 $this->module = str_replace('.', '_', $this->argv[0]);
273 $this->module = str_replace('-', '_', $this->module);
276 $this->argv = ['home'];
277 $this->module = 'home';
280 // See if there is any page number information, and initialise pagination
281 $this->pager['page'] = ((x($_GET, 'page') && intval($_GET['page']) > 0) ? intval($_GET['page']) : 1);
282 $this->pager['itemspage'] = 50;
283 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
285 if ($this->pager['start'] < 0) {
286 $this->pager['start'] = 0;
288 $this->pager['total'] = 0;
290 // Detect mobile devices
291 $mobile_detect = new MobileDetect();
292 $this->is_mobile = $mobile_detect->isMobile();
293 $this->is_tablet = $mobile_detect->isTablet();
296 $this->is_friendica_app = isset($_SERVER['HTTP_USER_AGENT']) && $_SERVER['HTTP_USER_AGENT'] == 'Apache-HttpClient/UNAVAILABLE (java 1.4)';
298 // Register template engines
299 $this->register_template_engine('Friendica\Render\FriendicaSmartyEngine');
302 * Load the configuration file which contains our DB credentials.
303 * Ignore errors. If the file doesn't exist or is empty, we are running in
304 * installation mode. *
306 $this->mode = ((file_exists('.htconfig.php') && filesize('.htconfig.php')) ? App::MODE_NORMAL : App::MODE_INSTALL);
313 * @brief Returns the base filesystem path of the App
315 * It first checks for the internal variable, then for DOCUMENT_ROOT and
320 public function get_basepath()
322 $basepath = $this->basepath;
325 $basepath = Config::get('system', 'basepath');
328 if (!$basepath && x($_SERVER, 'DOCUMENT_ROOT')) {
329 $basepath = $_SERVER['DOCUMENT_ROOT'];
332 if (!$basepath && x($_SERVER, 'PWD')) {
333 $basepath = $_SERVER['PWD'];
336 return self::realpath($basepath);
340 * @brief Returns a normalized file path
342 * This is a wrapper for the "realpath" function.
343 * That function cannot detect the real path when some folders aren't readable.
344 * Since this could happen with some hosters we need to handle this.
346 * @param string $path The path that is about to be normalized
347 * @return string normalized path - when possible
349 public static function realpath($path)
351 $normalized = realpath($path);
353 if (!is_bool($normalized)) {
360 public function get_scheme()
362 return $this->scheme;
366 * @brief Retrieves the Friendica instance base URL
368 * This function assembles the base URL from multiple parts:
369 * - Protocol is determined either by the request or a combination of
370 * system.ssl_policy and the $ssl parameter.
371 * - Host name is determined either by system.hostname or inferred from request
372 * - Path is inferred from SCRIPT_NAME
374 * Note: $ssl parameter value doesn't directly correlate with the resulting protocol
376 * @param bool $ssl Whether to append http or https under SSL_POLICY_SELFSIGN
377 * @return string Friendica server base URL
379 public function get_baseurl($ssl = false)
381 $scheme = $this->scheme;
383 if (Config::get('system', 'ssl_policy') == SSL_POLICY_FULL) {
387 // Basically, we have $ssl = true on any links which can only be seen by a logged in user
388 // (and also the login link). Anything seen by an outsider will have it turned off.
390 if (Config::get('system', 'ssl_policy') == SSL_POLICY_SELFSIGN) {
398 if (Config::get('config', 'hostname') != '') {
399 $this->hostname = Config::get('config', 'hostname');
402 return $scheme . '://' . $this->hostname . ((isset($this->path) && strlen($this->path)) ? '/' . $this->path : '' );
406 * @brief Initializes the baseurl components
408 * Clears the baseurl cache to prevent inconsistencies
412 public function set_baseurl($url)
414 $parsed = @parse_url($url);
418 if (!empty($parsed['scheme'])) {
419 $this->scheme = $parsed['scheme'];
422 if (!empty($parsed['host'])) {
423 $hostname = $parsed['host'];
426 if (x($parsed, 'port')) {
427 $hostname .= ':' . $parsed['port'];
429 if (x($parsed, 'path')) {
430 $this->path = trim($parsed['path'], '\\/');
433 if (file_exists($this->basepath . DIRECTORY_SEPARATOR . '.htpreconfig.php')) {
434 include $this->basepath . DIRECTORY_SEPARATOR . '.htpreconfig.php';
437 if (Config::get('config', 'hostname') != '') {
438 $this->hostname = Config::get('config', 'hostname');
441 if (!isset($this->hostname) || ($this->hostname == '')) {
442 $this->hostname = $hostname;
447 public function get_hostname()
449 if (Config::get('config', 'hostname') != '') {
450 $this->hostname = Config::get('config', 'hostname');
453 return $this->hostname;
456 public function get_path()
461 public function set_pager_total($n)
463 $this->pager['total'] = intval($n);
466 public function set_pager_itemspage($n)
468 $this->pager['itemspage'] = ((intval($n) > 0) ? intval($n) : 0);
469 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
472 public function set_pager_page($n)
474 $this->pager['page'] = $n;
475 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
478 public function init_pagehead()
480 $interval = ((local_user()) ? PConfig::get(local_user(), 'system', 'update_interval') : 40000);
482 // If the update is 'deactivated' set it to the highest integer number (~24 days)
484 $interval = 2147483647;
487 if ($interval < 10000) {
491 // compose the page title from the sitename and the
492 // current module called
493 if (!$this->module == '') {
494 $this->page['title'] = $this->config['sitename'] . ' (' . $this->module . ')';
496 $this->page['title'] = $this->config['sitename'];
499 /* put the head template at the beginning of page['htmlhead']
500 * since the code added by the modules frequently depends on it
503 if (!isset($this->page['htmlhead'])) {
504 $this->page['htmlhead'] = '';
507 // If we're using Smarty, then doing replace_macros() will replace
508 // any unrecognized variables with a blank string. Since we delay
509 // replacing $stylesheet until later, we need to replace it now
510 // with another variable name
511 if ($this->theme['template_engine'] === 'smarty3') {
512 $stylesheet = $this->get_template_ldelim('smarty3') . '$stylesheet' . $this->get_template_rdelim('smarty3');
514 $stylesheet = '$stylesheet';
517 $shortcut_icon = Config::get('system', 'shortcut_icon');
518 if ($shortcut_icon == '') {
519 $shortcut_icon = 'images/friendica-32.png';
522 $touch_icon = Config::get('system', 'touch_icon');
523 if ($touch_icon == '') {
524 $touch_icon = 'images/friendica-128.png';
527 // get data wich is needed for infinite scroll on the network page
528 $invinite_scroll = infinite_scroll_data($this->module);
530 $tpl = get_markup_template('head.tpl');
531 $this->page['htmlhead'] = replace_macros($tpl, [
532 '$baseurl' => $this->get_baseurl(),
533 '$local_user' => local_user(),
534 '$generator' => 'Friendica' . ' ' . FRIENDICA_VERSION,
535 '$delitem' => L10n::t('Delete this item?'),
536 '$showmore' => L10n::t('show more'),
537 '$showfewer' => L10n::t('show fewer'),
538 '$update_interval' => $interval,
539 '$shortcut_icon' => $shortcut_icon,
540 '$touch_icon' => $touch_icon,
541 '$stylesheet' => $stylesheet,
542 '$infinite_scroll' => $invinite_scroll,
543 ]) . $this->page['htmlhead'];
546 public function init_page_end()
548 if (!isset($this->page['end'])) {
549 $this->page['end'] = '';
551 $tpl = get_markup_template('end.tpl');
552 $this->page['end'] = replace_macros($tpl, [
553 '$baseurl' => $this->get_baseurl()
554 ]) . $this->page['end'];
557 public function set_curl_code($code)
559 $this->curl_code = $code;
562 public function get_curl_code()
564 return $this->curl_code;
567 public function set_curl_content_type($content_type)
569 $this->curl_content_type = $content_type;
572 public function get_curl_content_type()
574 return $this->curl_content_type;
577 public function set_curl_headers($headers)
579 $this->curl_headers = $headers;
582 public function get_curl_headers()
584 return $this->curl_headers;
588 * @brief Removes the base url from an url. This avoids some mixed content problems.
590 * @param string $orig_url
592 * @return string The cleaned url
594 public function remove_baseurl($orig_url)
596 // Remove the hostname from the url if it is an internal link
597 $nurl = normalise_link($orig_url);
598 $base = normalise_link($this->get_baseurl());
599 $url = str_replace($base . '/', '', $nurl);
601 // if it is an external link return the orignal value
602 if ($url == normalise_link($orig_url)) {
610 * @brief Register template engine class
612 * @param string $class
614 private function register_template_engine($class)
616 $v = get_class_vars($class);
619 $this->template_engines[$name] = $class;
621 echo "template engine <tt>$class</tt> cannot be registered without a name.\n";
627 * @brief Return template engine instance.
629 * If $name is not defined, return engine defined by theme,
632 * @return object Template Engine instance
634 public function template_engine()
636 $template_engine = 'smarty3';
637 if (x($this->theme, 'template_engine')) {
638 $template_engine = $this->theme['template_engine'];
641 if (isset($this->template_engines[$template_engine])) {
642 if (isset($this->template_engine_instance[$template_engine])) {
643 return $this->template_engine_instance[$template_engine];
645 $class = $this->template_engines[$template_engine];
647 $this->template_engine_instance[$template_engine] = $obj;
652 echo "template engine <tt>$template_engine</tt> is not registered!\n";
657 * @brief Returns the active template engine.
661 public function get_template_engine()
663 return $this->theme['template_engine'];
666 public function set_template_engine($engine = 'smarty3')
668 $this->theme['template_engine'] = $engine;
671 public function get_template_ldelim($engine = 'smarty3')
673 return $this->ldelim[$engine];
676 public function get_template_rdelim($engine = 'smarty3')
678 return $this->rdelim[$engine];
681 public function save_timestamp($stamp, $value)
683 if (!isset($this->config['system']['profiler']) || !$this->config['system']['profiler']) {
687 $duration = (float) (microtime(true) - $stamp);
689 if (!isset($this->performance[$value])) {
690 // Prevent ugly E_NOTICE
691 $this->performance[$value] = 0;
694 $this->performance[$value] += (float) $duration;
695 $this->performance['marktime'] += (float) $duration;
697 $callstack = System::callstack();
699 if (!isset($this->callstack[$value][$callstack])) {
700 // Prevent ugly E_NOTICE
701 $this->callstack[$value][$callstack] = 0;
704 $this->callstack[$value][$callstack] += (float) $duration;
707 public function get_useragent()
710 FRIENDICA_PLATFORM . " '" .
711 FRIENDICA_CODENAME . "' " .
712 FRIENDICA_VERSION . '-' .
713 DB_UPDATE_VERSION . '; ' .
714 $this->get_baseurl();
717 public function is_friendica_app()
719 return $this->is_friendica_app;
723 * @brief Checks if the site is called via a backend process
725 * This isn't a perfect solution. But we need this check very early.
726 * So we cannot wait until the modules are loaded.
728 * @return bool Is it a known backend?
730 public function is_backend()
754 // Check if current module is in backend or backend flag is set
755 return (in_array($this->module, $backends) || $this->backend);
759 * @brief Checks if the maximum number of database processes is reached
761 * @return bool Is the limit reached?
763 public function max_processes_reached()
765 // Deactivated, needs more investigating if this check really makes sense
769 * Commented out to suppress static analyzer issues
771 if ($this->is_backend()) {
772 $process = 'backend';
773 $max_processes = Config::get('system', 'max_processes_backend');
774 if (intval($max_processes) == 0) {
778 $process = 'frontend';
779 $max_processes = Config::get('system', 'max_processes_frontend');
780 if (intval($max_processes) == 0) {
785 $processlist = DBM::processlist();
786 if ($processlist['list'] != '') {
787 logger('Processcheck: Processes: ' . $processlist['amount'] . ' - Processlist: ' . $processlist['list'], LOGGER_DEBUG);
789 if ($processlist['amount'] > $max_processes) {
790 logger('Processcheck: Maximum number of processes for ' . $process . ' tasks (' . $max_processes . ') reached.', LOGGER_DEBUG);
799 * @brief Checks if the minimal memory is reached
801 * @return bool Is the memory limit reached?
803 public function min_memory_reached()
805 $min_memory = Config::get('system', 'min_memory', 0);
806 if ($min_memory == 0) {
810 if (!is_readable('/proc/meminfo')) {
814 $memdata = explode("\n", file_get_contents('/proc/meminfo'));
817 foreach ($memdata as $line) {
818 list($key, $val) = explode(':', $line);
819 $meminfo[$key] = (int) trim(str_replace('kB', '', $val));
820 $meminfo[$key] = (int) ($meminfo[$key] / 1024);
823 if (!isset($meminfo['MemAvailable']) || !isset($meminfo['MemFree'])) {
827 $free = $meminfo['MemAvailable'] + $meminfo['MemFree'];
829 $reached = ($free < $min_memory);
832 logger('Minimal memory reached: ' . $free . '/' . $meminfo['MemTotal'] . ' - limit ' . $min_memory, LOGGER_DEBUG);
839 * @brief Checks if the maximum load is reached
841 * @return bool Is the load reached?
843 public function maxload_reached()
845 if ($this->is_backend()) {
846 $process = 'backend';
847 $maxsysload = intval(Config::get('system', 'maxloadavg'));
848 if ($maxsysload < 1) {
852 $process = 'frontend';
853 $maxsysload = intval(Config::get('system', 'maxloadavg_frontend'));
854 if ($maxsysload < 1) {
859 $load = current_load();
861 if (intval($load) > $maxsysload) {
862 logger('system: load ' . $load . ' for ' . $process . ' tasks (' . $maxsysload . ') too high.');
869 public function proc_run($args)
871 if (!function_exists('proc_open')) {
875 array_unshift($args, $this->getConfigValue('config', 'php_path', 'php'));
877 for ($x = 0; $x < count($args); $x ++) {
878 $args[$x] = escapeshellarg($args[$x]);
881 $cmdline = implode(' ', $args);
883 if ($this->min_memory_reached()) {
887 if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
888 $resource = proc_open('cmd /c start /b ' . $cmdline, [], $foo, $this->get_basepath());
890 $resource = proc_open($cmdline . ' &', [], $foo, $this->get_basepath());
892 if (!is_resource($resource)) {
893 logger('We got no resource for command ' . $cmdline, LOGGER_DEBUG);
896 proc_close($resource);
900 * @brief Returns the system user that is executing the script
902 * This mostly returns something like "www-data".
904 * @return string system username
906 private static function systemuser()
908 if (!function_exists('posix_getpwuid') || !function_exists('posix_geteuid')) {
912 $processUser = posix_getpwuid(posix_geteuid());
913 return $processUser['name'];
917 * @brief Checks if a given directory is usable for the system
919 * @return boolean the directory is usable
921 public static function directory_usable($directory, $check_writable = true)
923 if ($directory == '') {
924 logger('Directory is empty. This shouldn\'t happen.', LOGGER_DEBUG);
928 if (!file_exists($directory)) {
929 logger('Path "' . $directory . '" does not exist for user ' . self::systemuser(), LOGGER_DEBUG);
933 if (is_file($directory)) {
934 logger('Path "' . $directory . '" is a file for user ' . self::systemuser(), LOGGER_DEBUG);
938 if (!is_dir($directory)) {
939 logger('Path "' . $directory . '" is not a directory for user ' . self::systemuser(), LOGGER_DEBUG);
943 if ($check_writable && !is_writable($directory)) {
944 logger('Path "' . $directory . '" is not writable for user ' . self::systemuser(), LOGGER_DEBUG);
952 * @param string $cat Config category
953 * @param string $k Config key
954 * @param mixed $default Default value if it isn't set
956 public function getConfigValue($cat, $k, $default = null)
960 if ($cat === 'config') {
961 if (isset($this->config[$k])) {
962 $return = $this->config[$k];
965 if (isset($this->config[$cat][$k])) {
966 $return = $this->config[$cat][$k];
974 * Sets a value in the config cache. Accepts raw output from the config table
976 * @param string $cat Config category
977 * @param string $k Config key
978 * @param mixed $v Value to set
980 public function setConfigValue($cat, $k, $v)
982 // Only arrays are serialized in database, so we have to unserialize sparingly
983 $value = is_string($v) && preg_match("|^a:[0-9]+:{.*}$|s", $v) ? unserialize($v) : $v;
985 if ($cat === 'config') {
986 $this->config[$k] = $value;
988 if (!isset($this->config[$cat])) {
989 $this->config[$cat] = [];
992 $this->config[$cat][$k] = $value;
997 * Deletes a value from the config cache
999 * @param string $cat Config category
1000 * @param string $k Config key
1002 public function deleteConfigValue($cat, $k)
1004 if ($cat === 'config') {
1005 if (isset($this->config[$k])) {
1006 unset($this->config[$k]);
1009 if (isset($this->config[$cat][$k])) {
1010 unset($this->config[$cat][$k]);
1017 * Retrieves a value from the user config cache
1019 * @param int $uid User Id
1020 * @param string $cat Config category
1021 * @param string $k Config key
1022 * @param mixed $default Default value if key isn't set
1024 public function getPConfigValue($uid, $cat, $k, $default = null)
1028 if (isset($this->config[$uid][$cat][$k])) {
1029 $return = $this->config[$uid][$cat][$k];
1036 * Sets a value in the user config cache
1038 * Accepts raw output from the pconfig table
1040 * @param int $uid User Id
1041 * @param string $cat Config category
1042 * @param string $k Config key
1043 * @param mixed $v Value to set
1045 public function setPConfigValue($uid, $cat, $k, $v)
1047 // Only arrays are serialized in database, so we have to unserialize sparingly
1048 $value = is_string($v) && preg_match("|^a:[0-9]+:{.*}$|s", $v) ? unserialize($v) : $v;
1050 if (!isset($this->config[$uid])) {
1051 $this->config[$uid] = [];
1054 if (!isset($this->config[$uid][$cat])) {
1055 $this->config[$uid][$cat] = [];
1058 $this->config[$uid][$cat][$k] = $value;
1062 * Deletes a value from the user config cache
1064 * @param int $uid User Id
1065 * @param string $cat Config category
1066 * @param string $k Config key
1068 public function deletePConfigValue($uid, $cat, $k)
1070 if (isset($this->config[$uid][$cat][$k])) {
1071 unset($this->config[$uid][$cat][$k]);
1076 * Generates the site's default sender email address
1080 public function getSenderEmailAddress()
1082 $sender_email = Config::get('config', 'sender_email');
1083 if (empty($sender_email)) {
1084 $hostname = $this->get_hostname();
1085 if (strpos($hostname, ':')) {
1086 $hostname = substr($hostname, 0, strpos($hostname, ':'));
1089 $sender_email = 'noreply@' . $hostname;
1092 return $sender_email;
1096 * @note Checks, if the App is in the Maintenance-Mode
1100 public function checkMaintenanceMode()
1102 if (Config::get('system', 'maintenance')) {
1103 $this->mode = App::MODE_MAINTENANCE;
1111 * Returns the current theme name.
1115 public function getCurrentTheme()
1117 if ($this->mode == App::MODE_INSTALL) {
1121 //// @TODO Compute the current theme only once (this behavior has
1122 /// already been implemented, but it didn't work well -
1123 /// https://github.com/friendica/friendica/issues/5092)
1124 $this->computeCurrentTheme();
1126 return $this->current_theme;
1130 * Computes the current theme name based on the node settings, the user settings and the device type
1134 private function computeCurrentTheme()
1136 $system_theme = Config::get('system', 'theme');
1137 if (!$system_theme) {
1138 throw new Exception(L10n::t('No system theme config value set.'));
1142 $this->current_theme = $system_theme;
1144 $allowed_themes = explode(',', Config::get('system', 'allowed_themes', $system_theme));
1147 // Find the theme that belongs to the user whose stuff we are looking at
1148 if ($this->profile_uid && ($this->profile_uid != local_user())) {
1149 // Allow folks to override user themes and always use their own on their own site.
1150 // This works only if the user is on the same server
1151 $user = dba::selectFirst('user', ['theme'], ['uid' => $this->profile_uid]);
1152 if (DBM::is_result($user) && !PConfig::get(local_user(), 'system', 'always_my_theme')) {
1153 $page_theme = $user['theme'];
1157 $user_theme = defaults($_SESSION, 'theme', $system_theme);
1158 // Specific mobile theme override
1159 if (($this->is_mobile || $this->is_tablet) && defaults($_SESSION, 'show-mobile', true)) {
1160 $system_mobile_theme = Config::get('system', 'mobile-theme');
1161 $user_mobile_theme = defaults($_SESSION, 'mobile-theme', $system_mobile_theme);
1163 // --- means same mobile theme as desktop
1164 if (!empty($user_mobile_theme) && $user_mobile_theme !== '---') {
1165 $user_theme = $user_mobile_theme;
1170 $theme_name = $page_theme;
1172 $theme_name = $user_theme;
1176 && in_array($theme_name, $allowed_themes)
1177 && (file_exists('view/theme/' . $theme_name . '/style.css')
1178 || file_exists('view/theme/' . $theme_name . '/style.php'))
1180 $this->current_theme = $theme_name;
1185 * @brief Return full URL to theme which is currently in effect.
1187 * Provide a sane default if nothing is chosen or the specified theme does not exist.
1191 public function getCurrentThemeStylesheetPath()
1193 return Core\Theme::getStylesheetPath($this->getCurrentTheme());