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 = uniqid('log', true);
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 ]) . $this->page['htmlhead'];
560 public function init_page_end()
562 if (!isset($this->page['end'])) {
563 $this->page['end'] = '';
565 $tpl = get_markup_template('end.tpl');
566 $this->page['end'] = replace_macros($tpl, [
567 '$baseurl' => $this->get_baseurl()
568 ]) . $this->page['end'];
571 public function set_curl_code($code)
573 $this->curl_code = $code;
576 public function get_curl_code()
578 return $this->curl_code;
581 public function set_curl_content_type($content_type)
583 $this->curl_content_type = $content_type;
586 public function get_curl_content_type()
588 return $this->curl_content_type;
591 public function set_curl_headers($headers)
593 $this->curl_headers = $headers;
596 public function get_curl_headers()
598 return $this->curl_headers;
602 * @brief Removes the base url from an url. This avoids some mixed content problems.
604 * @param string $orig_url
606 * @return string The cleaned url
608 public function remove_baseurl($orig_url)
610 // Remove the hostname from the url if it is an internal link
611 $nurl = normalise_link($orig_url);
612 $base = normalise_link($this->get_baseurl());
613 $url = str_replace($base . '/', '', $nurl);
615 // if it is an external link return the orignal value
616 if ($url == normalise_link($orig_url)) {
624 * @brief Register template engine class
626 * @param string $class
628 private function register_template_engine($class)
630 $v = get_class_vars($class);
633 $this->template_engines[$name] = $class;
635 echo "template engine <tt>$class</tt> cannot be registered without a name.\n";
641 * @brief Return template engine instance.
643 * If $name is not defined, return engine defined by theme,
646 * @return object Template Engine instance
648 public function template_engine()
650 $template_engine = 'smarty3';
651 if (x($this->theme, 'template_engine')) {
652 $template_engine = $this->theme['template_engine'];
655 if (isset($this->template_engines[$template_engine])) {
656 if (isset($this->template_engine_instance[$template_engine])) {
657 return $this->template_engine_instance[$template_engine];
659 $class = $this->template_engines[$template_engine];
661 $this->template_engine_instance[$template_engine] = $obj;
666 echo "template engine <tt>$template_engine</tt> is not registered!\n";
671 * @brief Returns the active template engine.
675 public function get_template_engine()
677 return $this->theme['template_engine'];
680 public function set_template_engine($engine = 'smarty3')
682 $this->theme['template_engine'] = $engine;
685 public function get_template_ldelim($engine = 'smarty3')
687 return $this->ldelim[$engine];
690 public function get_template_rdelim($engine = 'smarty3')
692 return $this->rdelim[$engine];
695 public function save_timestamp($stamp, $value)
697 if (!isset($this->config['system']['profiler']) || !$this->config['system']['profiler']) {
701 $duration = (float) (microtime(true) - $stamp);
703 if (!isset($this->performance[$value])) {
704 // Prevent ugly E_NOTICE
705 $this->performance[$value] = 0;
708 $this->performance[$value] += (float) $duration;
709 $this->performance['marktime'] += (float) $duration;
711 $callstack = System::callstack();
713 if (!isset($this->callstack[$value][$callstack])) {
714 // Prevent ugly E_NOTICE
715 $this->callstack[$value][$callstack] = 0;
718 $this->callstack[$value][$callstack] += (float) $duration;
721 public function get_useragent()
724 FRIENDICA_PLATFORM . " '" .
725 FRIENDICA_CODENAME . "' " .
726 FRIENDICA_VERSION . '-' .
727 DB_UPDATE_VERSION . '; ' .
728 $this->get_baseurl();
731 public function is_friendica_app()
733 return $this->is_friendica_app;
737 * @brief Checks if the site is called via a backend process
739 * This isn't a perfect solution. But we need this check very early.
740 * So we cannot wait until the modules are loaded.
742 * @return bool Is it a known backend?
744 public function is_backend()
768 // Check if current module is in backend or backend flag is set
769 return (in_array($this->module, $backends) || $this->backend);
773 * @brief Checks if the maximum number of database processes is reached
775 * @return bool Is the limit reached?
777 public function max_processes_reached()
779 // Deactivated, needs more investigating if this check really makes sense
783 * Commented out to suppress static analyzer issues
785 if ($this->is_backend()) {
786 $process = 'backend';
787 $max_processes = Config::get('system', 'max_processes_backend');
788 if (intval($max_processes) == 0) {
792 $process = 'frontend';
793 $max_processes = Config::get('system', 'max_processes_frontend');
794 if (intval($max_processes) == 0) {
799 $processlist = DBM::processlist();
800 if ($processlist['list'] != '') {
801 logger('Processcheck: Processes: ' . $processlist['amount'] . ' - Processlist: ' . $processlist['list'], LOGGER_DEBUG);
803 if ($processlist['amount'] > $max_processes) {
804 logger('Processcheck: Maximum number of processes for ' . $process . ' tasks (' . $max_processes . ') reached.', LOGGER_DEBUG);
813 * @brief Checks if the minimal memory is reached
815 * @return bool Is the memory limit reached?
817 public function min_memory_reached()
819 $min_memory = Config::get('system', 'min_memory', 0);
820 if ($min_memory == 0) {
824 if (!is_readable('/proc/meminfo')) {
828 $memdata = explode("\n", file_get_contents('/proc/meminfo'));
831 foreach ($memdata as $line) {
832 list($key, $val) = explode(':', $line);
833 $meminfo[$key] = (int) trim(str_replace('kB', '', $val));
834 $meminfo[$key] = (int) ($meminfo[$key] / 1024);
837 if (!isset($meminfo['MemAvailable']) || !isset($meminfo['MemFree'])) {
841 $free = $meminfo['MemAvailable'] + $meminfo['MemFree'];
843 $reached = ($free < $min_memory);
846 logger('Minimal memory reached: ' . $free . '/' . $meminfo['MemTotal'] . ' - limit ' . $min_memory, LOGGER_DEBUG);
853 * @brief Checks if the maximum load is reached
855 * @return bool Is the load reached?
857 public function maxload_reached()
859 if ($this->is_backend()) {
860 $process = 'backend';
861 $maxsysload = intval(Config::get('system', 'maxloadavg'));
862 if ($maxsysload < 1) {
866 $process = 'frontend';
867 $maxsysload = intval(Config::get('system', 'maxloadavg_frontend'));
868 if ($maxsysload < 1) {
873 $load = current_load();
875 if (intval($load) > $maxsysload) {
876 logger('system: load ' . $load . ' for ' . $process . ' tasks (' . $maxsysload . ') too high.');
883 public function proc_run($args)
885 if (!function_exists('proc_open')) {
889 array_unshift($args, $this->getConfigValue('config', 'php_path', 'php'));
891 for ($x = 0; $x < count($args); $x ++) {
892 $args[$x] = escapeshellarg($args[$x]);
895 $cmdline = implode(' ', $args);
897 if ($this->min_memory_reached()) {
901 if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
902 $resource = proc_open('cmd /c start /b ' . $cmdline, [], $foo, $this->get_basepath());
904 $resource = proc_open($cmdline . ' &', [], $foo, $this->get_basepath());
906 if (!is_resource($resource)) {
907 logger('We got no resource for command ' . $cmdline, LOGGER_DEBUG);
910 proc_close($resource);
914 * @brief Returns the system user that is executing the script
916 * This mostly returns something like "www-data".
918 * @return string system username
920 private static function systemuser()
922 if (!function_exists('posix_getpwuid') || !function_exists('posix_geteuid')) {
926 $processUser = posix_getpwuid(posix_geteuid());
927 return $processUser['name'];
931 * @brief Checks if a given directory is usable for the system
933 * @return boolean the directory is usable
935 public static function directory_usable($directory, $check_writable = true)
937 if ($directory == '') {
938 logger('Directory is empty. This shouldn\'t happen.', LOGGER_DEBUG);
942 if (!file_exists($directory)) {
943 logger('Path "' . $directory . '" does not exist for user ' . self::systemuser(), LOGGER_DEBUG);
947 if (is_file($directory)) {
948 logger('Path "' . $directory . '" is a file for user ' . self::systemuser(), LOGGER_DEBUG);
952 if (!is_dir($directory)) {
953 logger('Path "' . $directory . '" is not a directory for user ' . self::systemuser(), LOGGER_DEBUG);
957 if ($check_writable && !is_writable($directory)) {
958 logger('Path "' . $directory . '" is not writable for user ' . self::systemuser(), LOGGER_DEBUG);
966 * @param string $cat Config category
967 * @param string $k Config key
968 * @param mixed $default Default value if it isn't set
970 public function getConfigValue($cat, $k, $default = null)
974 if ($cat === 'config') {
975 if (isset($this->config[$k])) {
976 $return = $this->config[$k];
979 if (isset($this->config[$cat][$k])) {
980 $return = $this->config[$cat][$k];
988 * Sets a value in the config cache. Accepts raw output from the config table
990 * @param string $cat Config category
991 * @param string $k Config key
992 * @param mixed $v Value to set
994 public function setConfigValue($cat, $k, $v)
996 // Only arrays are serialized in database, so we have to unserialize sparingly
997 $value = is_string($v) && preg_match("|^a:[0-9]+:{.*}$|s", $v) ? unserialize($v) : $v;
999 if ($cat === 'config') {
1000 $this->config[$k] = $value;
1002 if (!isset($this->config[$cat])) {
1003 $this->config[$cat] = [];
1006 $this->config[$cat][$k] = $value;
1011 * Deletes a value from the config cache
1013 * @param string $cat Config category
1014 * @param string $k Config key
1016 public function deleteConfigValue($cat, $k)
1018 if ($cat === 'config') {
1019 if (isset($this->config[$k])) {
1020 unset($this->config[$k]);
1023 if (isset($this->config[$cat][$k])) {
1024 unset($this->config[$cat][$k]);
1031 * Retrieves a value from the user config cache
1033 * @param int $uid User Id
1034 * @param string $cat Config category
1035 * @param string $k Config key
1036 * @param mixed $default Default value if key isn't set
1038 public function getPConfigValue($uid, $cat, $k, $default = null)
1042 if (isset($this->config[$uid][$cat][$k])) {
1043 $return = $this->config[$uid][$cat][$k];
1050 * Sets a value in the user config cache
1052 * Accepts raw output from the pconfig table
1054 * @param int $uid User Id
1055 * @param string $cat Config category
1056 * @param string $k Config key
1057 * @param mixed $v Value to set
1059 public function setPConfigValue($uid, $cat, $k, $v)
1061 // Only arrays are serialized in database, so we have to unserialize sparingly
1062 $value = is_string($v) && preg_match("|^a:[0-9]+:{.*}$|s", $v) ? unserialize($v) : $v;
1064 if (!isset($this->config[$uid])) {
1065 $this->config[$uid] = [];
1068 if (!isset($this->config[$uid][$cat])) {
1069 $this->config[$uid][$cat] = [];
1072 $this->config[$uid][$cat][$k] = $value;
1076 * Deletes a value from the user config cache
1078 * @param int $uid User Id
1079 * @param string $cat Config category
1080 * @param string $k Config key
1082 public function deletePConfigValue($uid, $cat, $k)
1084 if (isset($this->config[$uid][$cat][$k])) {
1085 unset($this->config[$uid][$cat][$k]);
1090 * Generates the site's default sender email address
1094 public function getSenderEmailAddress()
1096 $sender_email = Config::get('config', 'sender_email');
1097 if (empty($sender_email)) {
1098 $hostname = $this->get_hostname();
1099 if (strpos($hostname, ':')) {
1100 $hostname = substr($hostname, 0, strpos($hostname, ':'));
1103 $sender_email = 'noreply@' . $hostname;
1106 return $sender_email;
1110 * @note Checks, if the App is in the Maintenance-Mode
1114 public function checkMaintenanceMode()
1116 if (Config::get('system', 'maintenance')) {
1117 $this->mode = App::MODE_MAINTENANCE;
1125 * Returns the current theme name.
1129 public function getCurrentTheme()
1131 if ($this->mode == App::MODE_INSTALL) {
1135 //// @TODO Compute the current theme only once (this behavior has
1136 /// already been implemented, but it didn't work well -
1137 /// https://github.com/friendica/friendica/issues/5092)
1138 $this->computeCurrentTheme();
1140 return $this->current_theme;
1144 * Computes the current theme name based on the node settings, the user settings and the device type
1148 private function computeCurrentTheme()
1150 $system_theme = Config::get('system', 'theme');
1151 if (!$system_theme) {
1152 throw new Exception(L10n::t('No system theme config value set.'));
1156 $this->current_theme = $system_theme;
1158 $allowed_themes = explode(',', Config::get('system', 'allowed_themes', $system_theme));
1161 // Find the theme that belongs to the user whose stuff we are looking at
1162 if ($this->profile_uid && ($this->profile_uid != local_user())) {
1163 // Allow folks to override user themes and always use their own on their own site.
1164 // This works only if the user is on the same server
1165 $user = dba::selectFirst('user', ['theme'], ['uid' => $this->profile_uid]);
1166 if (DBM::is_result($user) && !PConfig::get(local_user(), 'system', 'always_my_theme')) {
1167 $page_theme = $user['theme'];
1171 if (!empty($_SESSION)) {
1172 $user_theme = defaults($_SESSION, 'theme', $system_theme);
1174 $user_theme = $system_theme;
1177 // Specific mobile theme override
1178 if (($this->is_mobile || $this->is_tablet) && defaults($_SESSION, 'show-mobile', true)) {
1179 $system_mobile_theme = Config::get('system', 'mobile-theme');
1180 $user_mobile_theme = defaults($_SESSION, 'mobile-theme', $system_mobile_theme);
1182 // --- means same mobile theme as desktop
1183 if (!empty($user_mobile_theme) && $user_mobile_theme !== '---') {
1184 $user_theme = $user_mobile_theme;
1189 $theme_name = $page_theme;
1191 $theme_name = $user_theme;
1195 && in_array($theme_name, $allowed_themes)
1196 && (file_exists('view/theme/' . $theme_name . '/style.css')
1197 || file_exists('view/theme/' . $theme_name . '/style.php'))
1199 $this->current_theme = $theme_name;
1204 * @brief Return full URL to theme which is currently in effect.
1206 * Provide a sane default if nothing is chosen or the specified theme does not exist.
1210 public function getCurrentThemeStylesheetPath()
1212 return Core\Theme::getStylesheetPath($this->getCurrentTheme());