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->scheme = 'http';
188 if ((x($_SERVER, 'HTTPS') && $_SERVER['HTTPS']) ||
189 (x($_SERVER, 'HTTP_FORWARDED') && preg_match('/proto=https/', $_SERVER['HTTP_FORWARDED'])) ||
190 (x($_SERVER, 'HTTP_X_FORWARDED_PROTO') && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') ||
191 (x($_SERVER, 'HTTP_X_FORWARDED_SSL') && $_SERVER['HTTP_X_FORWARDED_SSL'] == 'on') ||
192 (x($_SERVER, 'FRONT_END_HTTPS') && $_SERVER['FRONT_END_HTTPS'] == 'on') ||
193 (x($_SERVER, 'SERVER_PORT') && (intval($_SERVER['SERVER_PORT']) == 443)) // XXX: reasonable assumption, but isn't this hardcoding too much?
195 $this->scheme = 'https';
198 if (x($_SERVER, 'SERVER_NAME')) {
199 $this->hostname = $_SERVER['SERVER_NAME'];
201 if (x($_SERVER, 'SERVER_PORT') && $_SERVER['SERVER_PORT'] != 80 && $_SERVER['SERVER_PORT'] != 443) {
202 $this->hostname .= ':' . $_SERVER['SERVER_PORT'];
205 * Figure out if we are running at the top of a domain
206 * or in a sub-directory and adjust accordingly
209 /// @TODO This kind of escaping breaks syntax-highlightning on CoolEdit (Midnight Commander)
210 $path = trim(dirname($_SERVER['SCRIPT_NAME']), '/\\');
211 if (isset($path) && strlen($path) && ($path != $this->path)) {
217 get_include_path() . PATH_SEPARATOR
218 . $this->basepath . DIRECTORY_SEPARATOR . 'include' . PATH_SEPARATOR
219 . $this->basepath . DIRECTORY_SEPARATOR . 'library' . PATH_SEPARATOR
222 if ((x($_SERVER, 'QUERY_STRING')) && substr($_SERVER['QUERY_STRING'], 0, 9) === 'pagename=') {
223 $this->query_string = substr($_SERVER['QUERY_STRING'], 9);
225 // removing trailing / - maybe a nginx problem
226 $this->query_string = ltrim($this->query_string, '/');
227 } elseif ((x($_SERVER, 'QUERY_STRING')) && substr($_SERVER['QUERY_STRING'], 0, 2) === 'q=') {
228 $this->query_string = substr($_SERVER['QUERY_STRING'], 2);
230 // removing trailing / - maybe a nginx problem
231 $this->query_string = ltrim($this->query_string, '/');
234 if (x($_GET, 'pagename')) {
235 $this->cmd = trim($_GET['pagename'], '/\\');
236 } elseif (x($_GET, 'q')) {
237 $this->cmd = trim($_GET['q'], '/\\');
241 $this->query_string = str_replace($this->cmd . '&', $this->cmd . '?', $this->query_string);
243 // unix style "homedir"
244 if (substr($this->cmd, 0, 1) === '~') {
245 $this->cmd = 'profile/' . substr($this->cmd, 1);
248 // Diaspora style profile url
249 if (substr($this->cmd, 0, 2) === 'u/') {
250 $this->cmd = 'profile/' . substr($this->cmd, 2);
254 * Break the URL path into C style argc/argv style arguments for our
255 * modules. Given "http://example.com/module/arg1/arg2", $this->argc
256 * will be 3 (integer) and $this->argv will contain:
262 * There will always be one argument. If provided a naked domain
263 * URL, $this->argv[0] is set to "home".
266 $this->argv = explode('/', $this->cmd);
267 $this->argc = count($this->argv);
268 if ((array_key_exists('0', $this->argv)) && strlen($this->argv[0])) {
269 $this->module = str_replace('.', '_', $this->argv[0]);
270 $this->module = str_replace('-', '_', $this->module);
273 $this->argv = ['home'];
274 $this->module = 'home';
277 // See if there is any page number information, and initialise pagination
278 $this->pager['page'] = ((x($_GET, 'page') && intval($_GET['page']) > 0) ? intval($_GET['page']) : 1);
279 $this->pager['itemspage'] = 50;
280 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
282 if ($this->pager['start'] < 0) {
283 $this->pager['start'] = 0;
285 $this->pager['total'] = 0;
287 // Detect mobile devices
288 $mobile_detect = new MobileDetect();
289 $this->is_mobile = $mobile_detect->isMobile();
290 $this->is_tablet = $mobile_detect->isTablet();
293 $this->is_friendica_app = ($_SERVER['HTTP_USER_AGENT'] == 'Apache-HttpClient/UNAVAILABLE (java 1.4)');
295 // Register template engines
296 $this->register_template_engine('Friendica\Render\FriendicaSmartyEngine');
299 * Load the configuration file which contains our DB credentials.
300 * Ignore errors. If the file doesn't exist or is empty, we are running in
301 * installation mode. *
303 $this->mode = ((file_exists('.htconfig.php') && filesize('.htconfig.php')) ? App::MODE_NORMAL : App::MODE_INSTALL);
310 * @brief Returns the base filesystem path of the App
312 * It first checks for the internal variable, then for DOCUMENT_ROOT and
317 public function get_basepath()
319 $basepath = $this->basepath;
322 $basepath = Config::get('system', 'basepath');
325 if (!$basepath && x($_SERVER, 'DOCUMENT_ROOT')) {
326 $basepath = $_SERVER['DOCUMENT_ROOT'];
329 if (!$basepath && x($_SERVER, 'PWD')) {
330 $basepath = $_SERVER['PWD'];
333 return self::realpath($basepath);
337 * @brief Returns a normalized file path
339 * This is a wrapper for the "realpath" function.
340 * That function cannot detect the real path when some folders aren't readable.
341 * Since this could happen with some hosters we need to handle this.
343 * @param string $path The path that is about to be normalized
344 * @return string normalized path - when possible
346 public static function realpath($path)
348 $normalized = realpath($path);
350 if (!is_bool($normalized)) {
357 public function get_scheme()
359 return $this->scheme;
363 * @brief Retrieves the Friendica instance base URL
365 * This function assembles the base URL from multiple parts:
366 * - Protocol is determined either by the request or a combination of
367 * system.ssl_policy and the $ssl parameter.
368 * - Host name is determined either by system.hostname or inferred from request
369 * - Path is inferred from SCRIPT_NAME
371 * Note: $ssl parameter value doesn't directly correlate with the resulting protocol
373 * @param bool $ssl Whether to append http or https under SSL_POLICY_SELFSIGN
374 * @return string Friendica server base URL
376 public function get_baseurl($ssl = false)
378 $scheme = $this->scheme;
380 if (Config::get('system', 'ssl_policy') == SSL_POLICY_FULL) {
384 // Basically, we have $ssl = true on any links which can only be seen by a logged in user
385 // (and also the login link). Anything seen by an outsider will have it turned off.
387 if (Config::get('system', 'ssl_policy') == SSL_POLICY_SELFSIGN) {
395 if (Config::get('config', 'hostname') != '') {
396 $this->hostname = Config::get('config', 'hostname');
399 return $scheme . '://' . $this->hostname . ((isset($this->path) && strlen($this->path)) ? '/' . $this->path : '' );
403 * @brief Initializes the baseurl components
405 * Clears the baseurl cache to prevent inconsistencies
409 public function set_baseurl($url)
411 $parsed = @parse_url($url);
414 $this->scheme = $parsed['scheme'];
416 $hostname = $parsed['host'];
417 if (x($parsed, 'port')) {
418 $hostname .= ':' . $parsed['port'];
420 if (x($parsed, 'path')) {
421 $this->path = trim($parsed['path'], '\\/');
424 if (file_exists($this->basepath . DIRECTORY_SEPARATOR . '.htpreconfig.php')) {
425 include $this->basepath . DIRECTORY_SEPARATOR . '.htpreconfig.php';
428 if (Config::get('config', 'hostname') != '') {
429 $this->hostname = Config::get('config', 'hostname');
432 if (!isset($this->hostname) || ( $this->hostname == '')) {
433 $this->hostname = $hostname;
438 public function get_hostname()
440 if (Config::get('config', 'hostname') != '') {
441 $this->hostname = Config::get('config', 'hostname');
444 return $this->hostname;
447 public function get_path()
452 public function set_pager_total($n)
454 $this->pager['total'] = intval($n);
457 public function set_pager_itemspage($n)
459 $this->pager['itemspage'] = ((intval($n) > 0) ? intval($n) : 0);
460 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
463 public function set_pager_page($n)
465 $this->pager['page'] = $n;
466 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
469 public function init_pagehead()
471 $interval = ((local_user()) ? PConfig::get(local_user(), 'system', 'update_interval') : 40000);
473 // If the update is 'deactivated' set it to the highest integer number (~24 days)
475 $interval = 2147483647;
478 if ($interval < 10000) {
482 // compose the page title from the sitename and the
483 // current module called
484 if (!$this->module == '') {
485 $this->page['title'] = $this->config['sitename'] . ' (' . $this->module . ')';
487 $this->page['title'] = $this->config['sitename'];
490 /* put the head template at the beginning of page['htmlhead']
491 * since the code added by the modules frequently depends on it
494 if (!isset($this->page['htmlhead'])) {
495 $this->page['htmlhead'] = '';
498 // If we're using Smarty, then doing replace_macros() will replace
499 // any unrecognized variables with a blank string. Since we delay
500 // replacing $stylesheet until later, we need to replace it now
501 // with another variable name
502 if ($this->theme['template_engine'] === 'smarty3') {
503 $stylesheet = $this->get_template_ldelim('smarty3') . '$stylesheet' . $this->get_template_rdelim('smarty3');
505 $stylesheet = '$stylesheet';
508 $shortcut_icon = Config::get('system', 'shortcut_icon');
509 if ($shortcut_icon == '') {
510 $shortcut_icon = 'images/friendica-32.png';
513 $touch_icon = Config::get('system', 'touch_icon');
514 if ($touch_icon == '') {
515 $touch_icon = 'images/friendica-128.png';
518 // get data wich is needed for infinite scroll on the network page
519 $invinite_scroll = infinite_scroll_data($this->module);
521 $tpl = get_markup_template('head.tpl');
522 $this->page['htmlhead'] = replace_macros($tpl, [
523 '$baseurl' => $this->get_baseurl(),
524 '$local_user' => local_user(),
525 '$generator' => 'Friendica' . ' ' . FRIENDICA_VERSION,
526 '$delitem' => L10n::t('Delete this item?'),
527 '$showmore' => L10n::t('show more'),
528 '$showfewer' => L10n::t('show fewer'),
529 '$update_interval' => $interval,
530 '$shortcut_icon' => $shortcut_icon,
531 '$touch_icon' => $touch_icon,
532 '$stylesheet' => $stylesheet,
533 '$infinite_scroll' => $invinite_scroll,
534 ]) . $this->page['htmlhead'];
537 public function init_page_end()
539 if (!isset($this->page['end'])) {
540 $this->page['end'] = '';
542 $tpl = get_markup_template('end.tpl');
543 $this->page['end'] = replace_macros($tpl, [
544 '$baseurl' => $this->get_baseurl()
545 ]) . $this->page['end'];
548 public function set_curl_code($code)
550 $this->curl_code = $code;
553 public function get_curl_code()
555 return $this->curl_code;
558 public function set_curl_content_type($content_type)
560 $this->curl_content_type = $content_type;
563 public function get_curl_content_type()
565 return $this->curl_content_type;
568 public function set_curl_headers($headers)
570 $this->curl_headers = $headers;
573 public function get_curl_headers()
575 return $this->curl_headers;
579 * @brief Removes the base url from an url. This avoids some mixed content problems.
581 * @param string $orig_url
583 * @return string The cleaned url
585 public function remove_baseurl($orig_url)
587 // Remove the hostname from the url if it is an internal link
588 $nurl = normalise_link($orig_url);
589 $base = normalise_link($this->get_baseurl());
590 $url = str_replace($base . '/', '', $nurl);
592 // if it is an external link return the orignal value
593 if ($url == normalise_link($orig_url)) {
601 * @brief Register template engine class
603 * @param string $class
605 private function register_template_engine($class)
607 $v = get_class_vars($class);
610 $this->template_engines[$name] = $class;
612 echo "template engine <tt>$class</tt> cannot be registered without a name.\n";
618 * @brief Return template engine instance.
620 * If $name is not defined, return engine defined by theme,
623 * @return object Template Engine instance
625 public function template_engine()
627 $template_engine = 'smarty3';
628 if (x($this->theme, 'template_engine')) {
629 $template_engine = $this->theme['template_engine'];
632 if (isset($this->template_engines[$template_engine])) {
633 if (isset($this->template_engine_instance[$template_engine])) {
634 return $this->template_engine_instance[$template_engine];
636 $class = $this->template_engines[$template_engine];
638 $this->template_engine_instance[$template_engine] = $obj;
643 echo "template engine <tt>$template_engine</tt> is not registered!\n";
648 * @brief Returns the active template engine.
652 public function get_template_engine()
654 return $this->theme['template_engine'];
657 public function set_template_engine($engine = 'smarty3')
659 $this->theme['template_engine'] = $engine;
662 public function get_template_ldelim($engine = 'smarty3')
664 return $this->ldelim[$engine];
667 public function get_template_rdelim($engine = 'smarty3')
669 return $this->rdelim[$engine];
672 public function save_timestamp($stamp, $value)
674 if (!isset($this->config['system']['profiler']) || !$this->config['system']['profiler']) {
678 $duration = (float) (microtime(true) - $stamp);
680 if (!isset($this->performance[$value])) {
681 // Prevent ugly E_NOTICE
682 $this->performance[$value] = 0;
685 $this->performance[$value] += (float) $duration;
686 $this->performance['marktime'] += (float) $duration;
688 $callstack = System::callstack();
690 if (!isset($this->callstack[$value][$callstack])) {
691 // Prevent ugly E_NOTICE
692 $this->callstack[$value][$callstack] = 0;
695 $this->callstack[$value][$callstack] += (float) $duration;
698 public function get_useragent()
701 FRIENDICA_PLATFORM . " '" .
702 FRIENDICA_CODENAME . "' " .
703 FRIENDICA_VERSION . '-' .
704 DB_UPDATE_VERSION . '; ' .
705 $this->get_baseurl();
708 public function is_friendica_app()
710 return $this->is_friendica_app;
714 * @brief Checks if the site is called via a backend process
716 * This isn't a perfect solution. But we need this check very early.
717 * So we cannot wait until the modules are loaded.
719 * @return bool Is it a known backend?
721 public function is_backend()
745 // Check if current module is in backend or backend flag is set
746 return (in_array($this->module, $backends) || $this->backend);
750 * @brief Checks if the maximum number of database processes is reached
752 * @return bool Is the limit reached?
754 public function max_processes_reached()
756 // Deactivated, needs more investigating if this check really makes sense
760 * Commented out to suppress static analyzer issues
762 if ($this->is_backend()) {
763 $process = 'backend';
764 $max_processes = Config::get('system', 'max_processes_backend');
765 if (intval($max_processes) == 0) {
769 $process = 'frontend';
770 $max_processes = Config::get('system', 'max_processes_frontend');
771 if (intval($max_processes) == 0) {
776 $processlist = DBM::processlist();
777 if ($processlist['list'] != '') {
778 logger('Processcheck: Processes: ' . $processlist['amount'] . ' - Processlist: ' . $processlist['list'], LOGGER_DEBUG);
780 if ($processlist['amount'] > $max_processes) {
781 logger('Processcheck: Maximum number of processes for ' . $process . ' tasks (' . $max_processes . ') reached.', LOGGER_DEBUG);
790 * @brief Checks if the minimal memory is reached
792 * @return bool Is the memory limit reached?
794 public function min_memory_reached()
796 $min_memory = Config::get('system', 'min_memory', 0);
797 if ($min_memory == 0) {
801 if (!is_readable('/proc/meminfo')) {
805 $memdata = explode("\n", file_get_contents('/proc/meminfo'));
808 foreach ($memdata as $line) {
809 list($key, $val) = explode(':', $line);
810 $meminfo[$key] = (int) trim(str_replace('kB', '', $val));
811 $meminfo[$key] = (int) ($meminfo[$key] / 1024);
814 if (!isset($meminfo['MemAvailable']) || !isset($meminfo['MemFree'])) {
818 $free = $meminfo['MemAvailable'] + $meminfo['MemFree'];
820 $reached = ($free < $min_memory);
823 logger('Minimal memory reached: ' . $free . '/' . $meminfo['MemTotal'] . ' - limit ' . $min_memory, LOGGER_DEBUG);
830 * @brief Checks if the maximum load is reached
832 * @return bool Is the load reached?
834 public function maxload_reached()
836 if ($this->is_backend()) {
837 $process = 'backend';
838 $maxsysload = intval(Config::get('system', 'maxloadavg'));
839 if ($maxsysload < 1) {
843 $process = 'frontend';
844 $maxsysload = intval(Config::get('system', 'maxloadavg_frontend'));
845 if ($maxsysload < 1) {
850 $load = current_load();
852 if (intval($load) > $maxsysload) {
853 logger('system: load ' . $load . ' for ' . $process . ' tasks (' . $maxsysload . ') too high.');
860 public function proc_run($args)
862 if (!function_exists('proc_open')) {
866 array_unshift($args, ((x($this->config, 'php_path')) && (strlen($this->config['php_path'])) ? $this->config['php_path'] : 'php'));
868 for ($x = 0; $x < count($args); $x ++) {
869 $args[$x] = escapeshellarg($args[$x]);
872 $cmdline = implode(' ', $args);
874 if ($this->min_memory_reached()) {
878 if (Config::get('system', 'proc_windows')) {
879 $resource = proc_open('cmd /c start /b ' . $cmdline, [], $foo, $this->get_basepath());
881 $resource = proc_open($cmdline . ' &', [], $foo, $this->get_basepath());
883 if (!is_resource($resource)) {
884 logger('We got no resource for command ' . $cmdline, LOGGER_DEBUG);
887 proc_close($resource);
891 * @brief Returns the system user that is executing the script
893 * This mostly returns something like "www-data".
895 * @return string system username
897 private static function systemuser()
899 if (!function_exists('posix_getpwuid') || !function_exists('posix_geteuid')) {
903 $processUser = posix_getpwuid(posix_geteuid());
904 return $processUser['name'];
908 * @brief Checks if a given directory is usable for the system
910 * @return boolean the directory is usable
912 public static function directory_usable($directory, $check_writable = true)
914 if ($directory == '') {
915 logger('Directory is empty. This shouldn\'t happen.', LOGGER_DEBUG);
919 if (!file_exists($directory)) {
920 logger('Path "' . $directory . '" does not exist for user ' . self::systemuser(), LOGGER_DEBUG);
924 if (is_file($directory)) {
925 logger('Path "' . $directory . '" is a file for user ' . self::systemuser(), LOGGER_DEBUG);
929 if (!is_dir($directory)) {
930 logger('Path "' . $directory . '" is not a directory for user ' . self::systemuser(), LOGGER_DEBUG);
934 if ($check_writable && !is_writable($directory)) {
935 logger('Path "' . $directory . '" is not writable for user ' . self::systemuser(), LOGGER_DEBUG);
943 * @param string $cat Config category
944 * @param string $k Config key
945 * @param mixed $default Default value if it isn't set
947 public function getConfigValue($cat, $k, $default = null)
951 if ($cat === 'config') {
952 if (isset($this->config[$k])) {
953 $return = $this->config[$k];
956 if (isset($this->config[$cat][$k])) {
957 $return = $this->config[$cat][$k];
965 * Sets a value in the config cache. Accepts raw output from the config table
967 * @param string $cat Config category
968 * @param string $k Config key
969 * @param mixed $v Value to set
971 public function setConfigValue($cat, $k, $v)
973 // Only arrays are serialized in database, so we have to unserialize sparingly
974 $value = is_string($v) && preg_match("|^a:[0-9]+:{.*}$|s", $v) ? unserialize($v) : $v;
976 if ($cat === 'config') {
977 $this->config[$k] = $value;
979 $this->config[$cat][$k] = $value;
984 * Deletes a value from the config cache
986 * @param string $cat Config category
987 * @param string $k Config key
989 public function deleteConfigValue($cat, $k)
991 if ($cat === 'config') {
992 if (isset($this->config[$k])) {
993 unset($this->config[$k]);
996 if (isset($this->config[$cat][$k])) {
997 unset($this->config[$cat][$k]);
1004 * Retrieves a value from the user config cache
1006 * @param int $uid User Id
1007 * @param string $cat Config category
1008 * @param string $k Config key
1009 * @param mixed $default Default value if key isn't set
1011 public function getPConfigValue($uid, $cat, $k, $default = null)
1015 if (isset($this->config[$uid][$cat][$k])) {
1016 $return = $this->config[$uid][$cat][$k];
1023 * Sets a value in the user config cache
1025 * Accepts raw output from the pconfig table
1027 * @param int $uid User Id
1028 * @param string $cat Config category
1029 * @param string $k Config key
1030 * @param mixed $v Value to set
1032 public function setPConfigValue($uid, $cat, $k, $v)
1034 // Only arrays are serialized in database, so we have to unserialize sparingly
1035 $value = is_string($v) && preg_match("|^a:[0-9]+:{.*}$|s", $v) ? unserialize($v) : $v;
1037 $this->config[$uid][$cat][$k] = $value;
1041 * Deletes a value from the user config cache
1043 * @param int $uid User Id
1044 * @param string $cat Config category
1045 * @param string $k Config key
1047 public function deletePConfigValue($uid, $cat, $k)
1049 if (isset($this->config[$uid][$cat][$k])) {
1050 unset($this->config[$uid][$cat][$k]);
1055 * Generates the site's default sender email address
1059 public function getSenderEmailAddress()
1061 $sender_email = Config::get('config', 'sender_email');
1062 if (empty($sender_email)) {
1063 $hostname = $this->get_hostname();
1064 if (strpos($hostname, ':')) {
1065 $hostname = substr($hostname, 0, strpos($hostname, ':'));
1068 $sender_email = 'noreply@' . $hostname;
1071 return $sender_email;
1075 * @note Checks, if the App is in the Maintenance-Mode
1079 public function checkMaintenanceMode()
1081 if (Config::get('system', 'maintenance')) {
1082 $this->mode = App::MODE_MAINTENANCE;
1090 * Returns the current theme name.
1094 public function getCurrentTheme()
1096 if ($this->mode == App::MODE_INSTALL) {
1100 //// @TODO Compute the current theme only once (this behavior has
1101 /// already been implemented, but it didn't work well -
1102 /// https://github.com/friendica/friendica/issues/5092)
1103 $this->computeCurrentTheme();
1105 return $this->current_theme;
1109 * Computes the current theme name based on the node settings, the user settings and the device type
1113 private function computeCurrentTheme()
1115 $system_theme = Config::get('system', 'theme');
1116 if (!$system_theme) {
1117 throw new Exception(L10n::t('No system theme config value set.'));
1121 $this->current_theme = $system_theme;
1123 $allowed_themes = explode(',', Config::get('system', 'allowed_themes', $system_theme));
1126 // Find the theme that belongs to the user whose stuff we are looking at
1127 if ($this->profile_uid && ($this->profile_uid != local_user())) {
1128 // Allow folks to override user themes and always use their own on their own site.
1129 // This works only if the user is on the same server
1130 $user = dba::selectFirst('user', ['theme'], ['uid' => $this->profile_uid]);
1131 if (DBM::is_result($user) && !PConfig::get(local_user(), 'system', 'always_my_theme')) {
1132 $page_theme = $user['theme'];
1136 $user_theme = defaults($_SESSION, 'theme', $system_theme);
1137 // Specific mobile theme override
1138 if (($this->is_mobile || $this->is_tablet) && defaults($_SESSION, 'show-mobile', true)) {
1139 $system_mobile_theme = Config::get('system', 'mobile-theme');
1140 $user_mobile_theme = defaults($_SESSION, 'mobile-theme', $system_mobile_theme);
1142 // --- means same mobile theme as desktop
1143 if (!empty($user_mobile_theme) && $user_mobile_theme !== '---') {
1144 $user_theme = $user_mobile_theme;
1149 $theme_name = $page_theme;
1151 $theme_name = $user_theme;
1155 && in_array($theme_name, $allowed_themes)
1156 && (file_exists('view/theme/' . $theme_name . '/style.css')
1157 || file_exists('view/theme/' . $theme_name . '/style.php'))
1159 $this->current_theme = $theme_name;
1164 * @brief Return full URL to theme which is currently in effect.
1166 * Provide a sane default if nothing is chosen or the specified theme does not exist.
1170 public function getCurrentThemeStylesheetPath()
1172 return Core\Theme::getStylesheetPath($this->getCurrentTheme());