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'] = [];
194 $this->query_string = '';
196 $this->process_id = System::processID('log');
200 // This has to be quite large to deal with embedded private photos
201 ini_set('pcre.backtrack_limit', 500000);
203 $this->scheme = 'http';
205 if ((x($_SERVER, 'HTTPS') && $_SERVER['HTTPS']) ||
206 (x($_SERVER, 'HTTP_FORWARDED') && preg_match('/proto=https/', $_SERVER['HTTP_FORWARDED'])) ||
207 (x($_SERVER, 'HTTP_X_FORWARDED_PROTO') && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') ||
208 (x($_SERVER, 'HTTP_X_FORWARDED_SSL') && $_SERVER['HTTP_X_FORWARDED_SSL'] == 'on') ||
209 (x($_SERVER, 'FRONT_END_HTTPS') && $_SERVER['FRONT_END_HTTPS'] == 'on') ||
210 (x($_SERVER, 'SERVER_PORT') && (intval($_SERVER['SERVER_PORT']) == 443)) // XXX: reasonable assumption, but isn't this hardcoding too much?
212 $this->scheme = 'https';
215 if (x($_SERVER, 'SERVER_NAME')) {
216 $this->hostname = $_SERVER['SERVER_NAME'];
218 if (x($_SERVER, 'SERVER_PORT') && $_SERVER['SERVER_PORT'] != 80 && $_SERVER['SERVER_PORT'] != 443) {
219 $this->hostname .= ':' . $_SERVER['SERVER_PORT'];
222 * Figure out if we are running at the top of a domain
223 * or in a sub-directory and adjust accordingly
226 /// @TODO This kind of escaping breaks syntax-highlightning on CoolEdit (Midnight Commander)
227 $path = trim(dirname($_SERVER['SCRIPT_NAME']), '/\\');
228 if (isset($path) && strlen($path) && ($path != $this->path)) {
234 get_include_path() . PATH_SEPARATOR
235 . $this->basepath . DIRECTORY_SEPARATOR . 'include' . PATH_SEPARATOR
236 . $this->basepath . DIRECTORY_SEPARATOR . 'library' . PATH_SEPARATOR
239 if ((x($_SERVER, 'QUERY_STRING')) && substr($_SERVER['QUERY_STRING'], 0, 9) === 'pagename=') {
240 $this->query_string = substr($_SERVER['QUERY_STRING'], 9);
242 // removing trailing / - maybe a nginx problem
243 $this->query_string = ltrim($this->query_string, '/');
244 } elseif ((x($_SERVER, 'QUERY_STRING')) && substr($_SERVER['QUERY_STRING'], 0, 2) === 'q=') {
245 $this->query_string = substr($_SERVER['QUERY_STRING'], 2);
247 // removing trailing / - maybe a nginx problem
248 $this->query_string = ltrim($this->query_string, '/');
251 if (x($_GET, 'pagename')) {
252 $this->cmd = trim($_GET['pagename'], '/\\');
253 } elseif (x($_GET, 'q')) {
254 $this->cmd = trim($_GET['q'], '/\\');
258 $this->query_string = str_replace($this->cmd . '&', $this->cmd . '?', $this->query_string);
260 // unix style "homedir"
261 if (substr($this->cmd, 0, 1) === '~') {
262 $this->cmd = 'profile/' . substr($this->cmd, 1);
265 // Diaspora style profile url
266 if (substr($this->cmd, 0, 2) === 'u/') {
267 $this->cmd = 'profile/' . substr($this->cmd, 2);
271 * Break the URL path into C style argc/argv style arguments for our
272 * modules. Given "http://example.com/module/arg1/arg2", $this->argc
273 * will be 3 (integer) and $this->argv will contain:
279 * There will always be one argument. If provided a naked domain
280 * URL, $this->argv[0] is set to "home".
283 $this->argv = explode('/', $this->cmd);
284 $this->argc = count($this->argv);
285 if ((array_key_exists('0', $this->argv)) && strlen($this->argv[0])) {
286 $this->module = str_replace('.', '_', $this->argv[0]);
287 $this->module = str_replace('-', '_', $this->module);
290 $this->argv = ['home'];
291 $this->module = 'home';
294 // See if there is any page number information, and initialise pagination
295 $this->pager['page'] = ((x($_GET, 'page') && intval($_GET['page']) > 0) ? intval($_GET['page']) : 1);
296 $this->pager['itemspage'] = 50;
297 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
299 if ($this->pager['start'] < 0) {
300 $this->pager['start'] = 0;
302 $this->pager['total'] = 0;
304 // Detect mobile devices
305 $mobile_detect = new MobileDetect();
306 $this->is_mobile = $mobile_detect->isMobile();
307 $this->is_tablet = $mobile_detect->isTablet();
310 $this->is_friendica_app = isset($_SERVER['HTTP_USER_AGENT']) && $_SERVER['HTTP_USER_AGENT'] == 'Apache-HttpClient/UNAVAILABLE (java 1.4)';
312 // Register template engines
313 $this->register_template_engine('Friendica\Render\FriendicaSmartyEngine');
316 * Load the configuration file which contains our DB credentials.
317 * Ignore errors. If the file doesn't exist or is empty, we are running in
318 * installation mode. *
320 $this->mode = ((file_exists('.htconfig.php') && filesize('.htconfig.php')) ? App::MODE_NORMAL : App::MODE_INSTALL);
327 * @brief Returns the base filesystem path of the App
329 * It first checks for the internal variable, then for DOCUMENT_ROOT and
334 public function get_basepath()
336 $basepath = $this->basepath;
339 $basepath = Config::get('system', 'basepath');
342 if (!$basepath && x($_SERVER, 'DOCUMENT_ROOT')) {
343 $basepath = $_SERVER['DOCUMENT_ROOT'];
346 if (!$basepath && x($_SERVER, 'PWD')) {
347 $basepath = $_SERVER['PWD'];
350 return self::realpath($basepath);
354 * @brief Returns a normalized file path
356 * This is a wrapper for the "realpath" function.
357 * That function cannot detect the real path when some folders aren't readable.
358 * Since this could happen with some hosters we need to handle this.
360 * @param string $path The path that is about to be normalized
361 * @return string normalized path - when possible
363 public static function realpath($path)
365 $normalized = realpath($path);
367 if (!is_bool($normalized)) {
374 public function get_scheme()
376 return $this->scheme;
380 * @brief Retrieves the Friendica instance base URL
382 * This function assembles the base URL from multiple parts:
383 * - Protocol is determined either by the request or a combination of
384 * system.ssl_policy and the $ssl parameter.
385 * - Host name is determined either by system.hostname or inferred from request
386 * - Path is inferred from SCRIPT_NAME
388 * Note: $ssl parameter value doesn't directly correlate with the resulting protocol
390 * @param bool $ssl Whether to append http or https under SSL_POLICY_SELFSIGN
391 * @return string Friendica server base URL
393 public function get_baseurl($ssl = false)
395 $scheme = $this->scheme;
397 if (Config::get('system', 'ssl_policy') == SSL_POLICY_FULL) {
401 // Basically, we have $ssl = true on any links which can only be seen by a logged in user
402 // (and also the login link). Anything seen by an outsider will have it turned off.
404 if (Config::get('system', 'ssl_policy') == SSL_POLICY_SELFSIGN) {
412 if (Config::get('config', 'hostname') != '') {
413 $this->hostname = Config::get('config', 'hostname');
416 return $scheme . '://' . $this->hostname . ((isset($this->path) && strlen($this->path)) ? '/' . $this->path : '' );
420 * @brief Initializes the baseurl components
422 * Clears the baseurl cache to prevent inconsistencies
426 public function set_baseurl($url)
428 $parsed = @parse_url($url);
432 if (!empty($parsed['scheme'])) {
433 $this->scheme = $parsed['scheme'];
436 if (!empty($parsed['host'])) {
437 $hostname = $parsed['host'];
440 if (x($parsed, 'port')) {
441 $hostname .= ':' . $parsed['port'];
443 if (x($parsed, 'path')) {
444 $this->path = trim($parsed['path'], '\\/');
447 if (file_exists($this->basepath . DIRECTORY_SEPARATOR . '.htpreconfig.php')) {
448 include $this->basepath . DIRECTORY_SEPARATOR . '.htpreconfig.php';
451 if (Config::get('config', 'hostname') != '') {
452 $this->hostname = Config::get('config', 'hostname');
455 if (!isset($this->hostname) || ($this->hostname == '')) {
456 $this->hostname = $hostname;
461 public function get_hostname()
463 if (Config::get('config', 'hostname') != '') {
464 $this->hostname = Config::get('config', 'hostname');
467 return $this->hostname;
470 public function get_path()
475 public function set_pager_total($n)
477 $this->pager['total'] = intval($n);
480 public function set_pager_itemspage($n)
482 $this->pager['itemspage'] = ((intval($n) > 0) ? intval($n) : 0);
483 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
486 public function set_pager_page($n)
488 $this->pager['page'] = $n;
489 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
492 public function init_pagehead()
494 $interval = ((local_user()) ? PConfig::get(local_user(), 'system', 'update_interval') : 40000);
496 // If the update is 'deactivated' set it to the highest integer number (~24 days)
498 $interval = 2147483647;
501 if ($interval < 10000) {
505 // compose the page title from the sitename and the
506 // current module called
507 if (!$this->module == '') {
508 $this->page['title'] = $this->config['sitename'] . ' (' . $this->module . ')';
510 $this->page['title'] = $this->config['sitename'];
513 /* put the head template at the beginning of page['htmlhead']
514 * since the code added by the modules frequently depends on it
517 if (!isset($this->page['htmlhead'])) {
518 $this->page['htmlhead'] = '';
521 // If we're using Smarty, then doing replace_macros() will replace
522 // any unrecognized variables with a blank string. Since we delay
523 // replacing $stylesheet until later, we need to replace it now
524 // with another variable name
525 if ($this->theme['template_engine'] === 'smarty3') {
526 $stylesheet = $this->get_template_ldelim('smarty3') . '$stylesheet' . $this->get_template_rdelim('smarty3');
528 $stylesheet = '$stylesheet';
531 $shortcut_icon = Config::get('system', 'shortcut_icon');
532 if ($shortcut_icon == '') {
533 $shortcut_icon = 'images/friendica-32.png';
536 $touch_icon = Config::get('system', 'touch_icon');
537 if ($touch_icon == '') {
538 $touch_icon = 'images/friendica-128.png';
541 // get data wich is needed for infinite scroll on the network page
542 $invinite_scroll = infinite_scroll_data($this->module);
544 $tpl = get_markup_template('head.tpl');
545 $this->page['htmlhead'] = replace_macros($tpl, [
546 '$baseurl' => $this->get_baseurl(),
547 '$local_user' => local_user(),
548 '$generator' => 'Friendica' . ' ' . FRIENDICA_VERSION,
549 '$delitem' => L10n::t('Delete this item?'),
550 '$showmore' => L10n::t('show more'),
551 '$showfewer' => L10n::t('show fewer'),
552 '$update_interval' => $interval,
553 '$shortcut_icon' => $shortcut_icon,
554 '$touch_icon' => $touch_icon,
555 '$stylesheet' => $stylesheet,
556 '$infinite_scroll' => $invinite_scroll,
557 '$block_public' => intval(Config::get('system', 'block_public')),
558 ]) . $this->page['htmlhead'];
561 public function init_page_end()
563 if (!isset($this->page['end'])) {
564 $this->page['end'] = '';
566 $tpl = get_markup_template('end.tpl');
567 $this->page['end'] = replace_macros($tpl, [
568 '$baseurl' => $this->get_baseurl()
569 ]) . $this->page['end'];
572 public function set_curl_code($code)
574 $this->curl_code = $code;
577 public function get_curl_code()
579 return $this->curl_code;
582 public function set_curl_content_type($content_type)
584 $this->curl_content_type = $content_type;
587 public function get_curl_content_type()
589 return $this->curl_content_type;
592 public function set_curl_headers($headers)
594 $this->curl_headers = $headers;
597 public function get_curl_headers()
599 return $this->curl_headers;
603 * @brief Removes the base url from an url. This avoids some mixed content problems.
605 * @param string $orig_url
607 * @return string The cleaned url
609 public function remove_baseurl($orig_url)
611 // Remove the hostname from the url if it is an internal link
612 $nurl = normalise_link($orig_url);
613 $base = normalise_link($this->get_baseurl());
614 $url = str_replace($base . '/', '', $nurl);
616 // if it is an external link return the orignal value
617 if ($url == normalise_link($orig_url)) {
625 * @brief Register template engine class
627 * @param string $class
629 private function register_template_engine($class)
631 $v = get_class_vars($class);
634 $this->template_engines[$name] = $class;
636 echo "template engine <tt>$class</tt> cannot be registered without a name.\n";
642 * @brief Return template engine instance.
644 * If $name is not defined, return engine defined by theme,
647 * @return object Template Engine instance
649 public function template_engine()
651 $template_engine = 'smarty3';
652 if (x($this->theme, 'template_engine')) {
653 $template_engine = $this->theme['template_engine'];
656 if (isset($this->template_engines[$template_engine])) {
657 if (isset($this->template_engine_instance[$template_engine])) {
658 return $this->template_engine_instance[$template_engine];
660 $class = $this->template_engines[$template_engine];
662 $this->template_engine_instance[$template_engine] = $obj;
667 echo "template engine <tt>$template_engine</tt> is not registered!\n";
672 * @brief Returns the active template engine.
676 public function get_template_engine()
678 return $this->theme['template_engine'];
681 public function set_template_engine($engine = 'smarty3')
683 $this->theme['template_engine'] = $engine;
686 public function get_template_ldelim($engine = 'smarty3')
688 return $this->ldelim[$engine];
691 public function get_template_rdelim($engine = 'smarty3')
693 return $this->rdelim[$engine];
696 public function save_timestamp($stamp, $value)
698 if (!isset($this->config['system']['profiler']) || !$this->config['system']['profiler']) {
702 $duration = (float) (microtime(true) - $stamp);
704 if (!isset($this->performance[$value])) {
705 // Prevent ugly E_NOTICE
706 $this->performance[$value] = 0;
709 $this->performance[$value] += (float) $duration;
710 $this->performance['marktime'] += (float) $duration;
712 $callstack = System::callstack();
714 if (!isset($this->callstack[$value][$callstack])) {
715 // Prevent ugly E_NOTICE
716 $this->callstack[$value][$callstack] = 0;
719 $this->callstack[$value][$callstack] += (float) $duration;
722 public function get_useragent()
725 FRIENDICA_PLATFORM . " '" .
726 FRIENDICA_CODENAME . "' " .
727 FRIENDICA_VERSION . '-' .
728 DB_UPDATE_VERSION . '; ' .
729 $this->get_baseurl();
732 public function is_friendica_app()
734 return $this->is_friendica_app;
738 * @brief Checks if the site is called via a backend process
740 * This isn't a perfect solution. But we need this check very early.
741 * So we cannot wait until the modules are loaded.
743 * @return bool Is it a known backend?
745 public function is_backend()
769 // Check if current module is in backend or backend flag is set
770 return (in_array($this->module, $backends) || $this->backend);
774 * @brief Checks if the maximum number of database processes is reached
776 * @return bool Is the limit reached?
778 public function max_processes_reached()
780 // Deactivated, needs more investigating if this check really makes sense
784 * Commented out to suppress static analyzer issues
786 if ($this->is_backend()) {
787 $process = 'backend';
788 $max_processes = Config::get('system', 'max_processes_backend');
789 if (intval($max_processes) == 0) {
793 $process = 'frontend';
794 $max_processes = Config::get('system', 'max_processes_frontend');
795 if (intval($max_processes) == 0) {
800 $processlist = DBM::processlist();
801 if ($processlist['list'] != '') {
802 logger('Processcheck: Processes: ' . $processlist['amount'] . ' - Processlist: ' . $processlist['list'], LOGGER_DEBUG);
804 if ($processlist['amount'] > $max_processes) {
805 logger('Processcheck: Maximum number of processes for ' . $process . ' tasks (' . $max_processes . ') reached.', LOGGER_DEBUG);
814 * @brief Checks if the minimal memory is reached
816 * @return bool Is the memory limit reached?
818 public function min_memory_reached()
820 $min_memory = Config::get('system', 'min_memory', 0);
821 if ($min_memory == 0) {
825 if (!is_readable('/proc/meminfo')) {
829 $memdata = explode("\n", file_get_contents('/proc/meminfo'));
832 foreach ($memdata as $line) {
833 list($key, $val) = explode(':', $line);
834 $meminfo[$key] = (int) trim(str_replace('kB', '', $val));
835 $meminfo[$key] = (int) ($meminfo[$key] / 1024);
838 if (!isset($meminfo['MemAvailable']) || !isset($meminfo['MemFree'])) {
842 $free = $meminfo['MemAvailable'] + $meminfo['MemFree'];
844 $reached = ($free < $min_memory);
847 logger('Minimal memory reached: ' . $free . '/' . $meminfo['MemTotal'] . ' - limit ' . $min_memory, LOGGER_DEBUG);
854 * @brief Checks if the maximum load is reached
856 * @return bool Is the load reached?
858 public function maxload_reached()
860 if ($this->is_backend()) {
861 $process = 'backend';
862 $maxsysload = intval(Config::get('system', 'maxloadavg'));
863 if ($maxsysload < 1) {
867 $process = 'frontend';
868 $maxsysload = intval(Config::get('system', 'maxloadavg_frontend'));
869 if ($maxsysload < 1) {
874 $load = current_load();
876 if (intval($load) > $maxsysload) {
877 logger('system: load ' . $load . ' for ' . $process . ' tasks (' . $maxsysload . ') too high.');
884 public function proc_run($args)
886 if (!function_exists('proc_open')) {
890 array_unshift($args, $this->getConfigValue('config', 'php_path', 'php'));
892 for ($x = 0; $x < count($args); $x ++) {
893 $args[$x] = escapeshellarg($args[$x]);
896 $cmdline = implode(' ', $args);
898 if ($this->min_memory_reached()) {
902 if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
903 $resource = proc_open('cmd /c start /b ' . $cmdline, [], $foo, $this->get_basepath());
905 $resource = proc_open($cmdline . ' &', [], $foo, $this->get_basepath());
907 if (!is_resource($resource)) {
908 logger('We got no resource for command ' . $cmdline, LOGGER_DEBUG);
911 proc_close($resource);
915 * @brief Returns the system user that is executing the script
917 * This mostly returns something like "www-data".
919 * @return string system username
921 private static function systemuser()
923 if (!function_exists('posix_getpwuid') || !function_exists('posix_geteuid')) {
927 $processUser = posix_getpwuid(posix_geteuid());
928 return $processUser['name'];
932 * @brief Checks if a given directory is usable for the system
934 * @return boolean the directory is usable
936 public static function directory_usable($directory, $check_writable = true)
938 if ($directory == '') {
939 logger('Directory is empty. This shouldn\'t happen.', LOGGER_DEBUG);
943 if (!file_exists($directory)) {
944 logger('Path "' . $directory . '" does not exist for user ' . self::systemuser(), LOGGER_DEBUG);
948 if (is_file($directory)) {
949 logger('Path "' . $directory . '" is a file for user ' . self::systemuser(), LOGGER_DEBUG);
953 if (!is_dir($directory)) {
954 logger('Path "' . $directory . '" is not a directory for user ' . self::systemuser(), LOGGER_DEBUG);
958 if ($check_writable && !is_writable($directory)) {
959 logger('Path "' . $directory . '" is not writable for user ' . self::systemuser(), LOGGER_DEBUG);
967 * @param string $cat Config category
968 * @param string $k Config key
969 * @param mixed $default Default value if it isn't set
971 public function getConfigValue($cat, $k, $default = null)
975 if ($cat === 'config') {
976 if (isset($this->config[$k])) {
977 $return = $this->config[$k];
980 if (isset($this->config[$cat][$k])) {
981 $return = $this->config[$cat][$k];
989 * Sets a value in the config cache. Accepts raw output from the config table
991 * @param string $cat Config category
992 * @param string $k Config key
993 * @param mixed $v Value to set
995 public function setConfigValue($cat, $k, $v)
997 // Only arrays are serialized in database, so we have to unserialize sparingly
998 $value = is_string($v) && preg_match("|^a:[0-9]+:{.*}$|s", $v) ? unserialize($v) : $v;
1000 if ($cat === 'config') {
1001 $this->config[$k] = $value;
1003 if (!isset($this->config[$cat])) {
1004 $this->config[$cat] = [];
1007 $this->config[$cat][$k] = $value;
1012 * Deletes a value from the config cache
1014 * @param string $cat Config category
1015 * @param string $k Config key
1017 public function deleteConfigValue($cat, $k)
1019 if ($cat === 'config') {
1020 if (isset($this->config[$k])) {
1021 unset($this->config[$k]);
1024 if (isset($this->config[$cat][$k])) {
1025 unset($this->config[$cat][$k]);
1032 * Retrieves a value from the user config cache
1034 * @param int $uid User Id
1035 * @param string $cat Config category
1036 * @param string $k Config key
1037 * @param mixed $default Default value if key isn't set
1039 public function getPConfigValue($uid, $cat, $k, $default = null)
1043 if (isset($this->config[$uid][$cat][$k])) {
1044 $return = $this->config[$uid][$cat][$k];
1051 * Sets a value in the user config cache
1053 * Accepts raw output from the pconfig table
1055 * @param int $uid User Id
1056 * @param string $cat Config category
1057 * @param string $k Config key
1058 * @param mixed $v Value to set
1060 public function setPConfigValue($uid, $cat, $k, $v)
1062 // Only arrays are serialized in database, so we have to unserialize sparingly
1063 $value = is_string($v) && preg_match("|^a:[0-9]+:{.*}$|s", $v) ? unserialize($v) : $v;
1065 if (!isset($this->config[$uid])) {
1066 $this->config[$uid] = [];
1069 if (!isset($this->config[$uid][$cat])) {
1070 $this->config[$uid][$cat] = [];
1073 $this->config[$uid][$cat][$k] = $value;
1077 * Deletes a value from the user config cache
1079 * @param int $uid User Id
1080 * @param string $cat Config category
1081 * @param string $k Config key
1083 public function deletePConfigValue($uid, $cat, $k)
1085 if (isset($this->config[$uid][$cat][$k])) {
1086 unset($this->config[$uid][$cat][$k]);
1091 * Generates the site's default sender email address
1095 public function getSenderEmailAddress()
1097 $sender_email = Config::get('config', 'sender_email');
1098 if (empty($sender_email)) {
1099 $hostname = $this->get_hostname();
1100 if (strpos($hostname, ':')) {
1101 $hostname = substr($hostname, 0, strpos($hostname, ':'));
1104 $sender_email = 'noreply@' . $hostname;
1107 return $sender_email;
1111 * @note Checks, if the App is in the Maintenance-Mode
1115 public function checkMaintenanceMode()
1117 if (Config::get('system', 'maintenance')) {
1118 $this->mode = App::MODE_MAINTENANCE;
1126 * Returns the current theme name.
1130 public function getCurrentTheme()
1132 if ($this->mode == App::MODE_INSTALL) {
1136 //// @TODO Compute the current theme only once (this behavior has
1137 /// already been implemented, but it didn't work well -
1138 /// https://github.com/friendica/friendica/issues/5092)
1139 $this->computeCurrentTheme();
1141 return $this->current_theme;
1145 * Computes the current theme name based on the node settings, the user settings and the device type
1149 private function computeCurrentTheme()
1151 $system_theme = Config::get('system', 'theme');
1152 if (!$system_theme) {
1153 throw new Exception(L10n::t('No system theme config value set.'));
1157 $this->current_theme = $system_theme;
1159 $allowed_themes = explode(',', Config::get('system', 'allowed_themes', $system_theme));
1162 // Find the theme that belongs to the user whose stuff we are looking at
1163 if ($this->profile_uid && ($this->profile_uid != local_user())) {
1164 // Allow folks to override user themes and always use their own on their own site.
1165 // This works only if the user is on the same server
1166 $user = dba::selectFirst('user', ['theme'], ['uid' => $this->profile_uid]);
1167 if (DBM::is_result($user) && !PConfig::get(local_user(), 'system', 'always_my_theme')) {
1168 $page_theme = $user['theme'];
1172 if (!empty($_SESSION)) {
1173 $user_theme = defaults($_SESSION, 'theme', $system_theme);
1175 $user_theme = $system_theme;
1178 // Specific mobile theme override
1179 if (($this->is_mobile || $this->is_tablet) && defaults($_SESSION, 'show-mobile', true)) {
1180 $system_mobile_theme = Config::get('system', 'mobile-theme');
1181 $user_mobile_theme = defaults($_SESSION, 'mobile-theme', $system_mobile_theme);
1183 // --- means same mobile theme as desktop
1184 if (!empty($user_mobile_theme) && $user_mobile_theme !== '---') {
1185 $user_theme = $user_mobile_theme;
1190 $theme_name = $page_theme;
1192 $theme_name = $user_theme;
1196 && in_array($theme_name, $allowed_themes)
1197 && (file_exists('view/theme/' . $theme_name . '/style.css')
1198 || file_exists('view/theme/' . $theme_name . '/style.php'))
1200 $this->current_theme = $theme_name;
1205 * @brief Return full URL to theme which is currently in effect.
1207 * Provide a sane default if nothing is chosen or the specified theme does not exist.
1211 public function getCurrentThemeStylesheetPath()
1213 return Core\Theme::getStylesheetPath($this->getCurrentTheme());