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 = ($_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);
417 $this->scheme = $parsed['scheme'];
419 $hostname = $parsed['host'];
420 if (x($parsed, 'port')) {
421 $hostname .= ':' . $parsed['port'];
423 if (x($parsed, 'path')) {
424 $this->path = trim($parsed['path'], '\\/');
427 if (file_exists($this->basepath . DIRECTORY_SEPARATOR . '.htpreconfig.php')) {
428 include $this->basepath . DIRECTORY_SEPARATOR . '.htpreconfig.php';
431 if (Config::get('config', 'hostname') != '') {
432 $this->hostname = Config::get('config', 'hostname');
435 if (!isset($this->hostname) || ( $this->hostname == '')) {
436 $this->hostname = $hostname;
441 public function get_hostname()
443 if (Config::get('config', 'hostname') != '') {
444 $this->hostname = Config::get('config', 'hostname');
447 return $this->hostname;
450 public function get_path()
455 public function set_pager_total($n)
457 $this->pager['total'] = intval($n);
460 public function set_pager_itemspage($n)
462 $this->pager['itemspage'] = ((intval($n) > 0) ? intval($n) : 0);
463 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
466 public function set_pager_page($n)
468 $this->pager['page'] = $n;
469 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
472 public function init_pagehead()
474 $interval = ((local_user()) ? PConfig::get(local_user(), 'system', 'update_interval') : 40000);
476 // If the update is 'deactivated' set it to the highest integer number (~24 days)
478 $interval = 2147483647;
481 if ($interval < 10000) {
485 // compose the page title from the sitename and the
486 // current module called
487 if (!$this->module == '') {
488 $this->page['title'] = $this->config['sitename'] . ' (' . $this->module . ')';
490 $this->page['title'] = $this->config['sitename'];
493 /* put the head template at the beginning of page['htmlhead']
494 * since the code added by the modules frequently depends on it
497 if (!isset($this->page['htmlhead'])) {
498 $this->page['htmlhead'] = '';
501 // If we're using Smarty, then doing replace_macros() will replace
502 // any unrecognized variables with a blank string. Since we delay
503 // replacing $stylesheet until later, we need to replace it now
504 // with another variable name
505 if ($this->theme['template_engine'] === 'smarty3') {
506 $stylesheet = $this->get_template_ldelim('smarty3') . '$stylesheet' . $this->get_template_rdelim('smarty3');
508 $stylesheet = '$stylesheet';
511 $shortcut_icon = Config::get('system', 'shortcut_icon');
512 if ($shortcut_icon == '') {
513 $shortcut_icon = 'images/friendica-32.png';
516 $touch_icon = Config::get('system', 'touch_icon');
517 if ($touch_icon == '') {
518 $touch_icon = 'images/friendica-128.png';
521 // get data wich is needed for infinite scroll on the network page
522 $invinite_scroll = infinite_scroll_data($this->module);
524 $tpl = get_markup_template('head.tpl');
525 $this->page['htmlhead'] = replace_macros($tpl, [
526 '$baseurl' => $this->get_baseurl(),
527 '$local_user' => local_user(),
528 '$generator' => 'Friendica' . ' ' . FRIENDICA_VERSION,
529 '$delitem' => L10n::t('Delete this item?'),
530 '$showmore' => L10n::t('show more'),
531 '$showfewer' => L10n::t('show fewer'),
532 '$update_interval' => $interval,
533 '$shortcut_icon' => $shortcut_icon,
534 '$touch_icon' => $touch_icon,
535 '$stylesheet' => $stylesheet,
536 '$infinite_scroll' => $invinite_scroll,
537 ]) . $this->page['htmlhead'];
540 public function init_page_end()
542 if (!isset($this->page['end'])) {
543 $this->page['end'] = '';
545 $tpl = get_markup_template('end.tpl');
546 $this->page['end'] = replace_macros($tpl, [
547 '$baseurl' => $this->get_baseurl()
548 ]) . $this->page['end'];
551 public function set_curl_code($code)
553 $this->curl_code = $code;
556 public function get_curl_code()
558 return $this->curl_code;
561 public function set_curl_content_type($content_type)
563 $this->curl_content_type = $content_type;
566 public function get_curl_content_type()
568 return $this->curl_content_type;
571 public function set_curl_headers($headers)
573 $this->curl_headers = $headers;
576 public function get_curl_headers()
578 return $this->curl_headers;
582 * @brief Removes the base url from an url. This avoids some mixed content problems.
584 * @param string $orig_url
586 * @return string The cleaned url
588 public function remove_baseurl($orig_url)
590 // Remove the hostname from the url if it is an internal link
591 $nurl = normalise_link($orig_url);
592 $base = normalise_link($this->get_baseurl());
593 $url = str_replace($base . '/', '', $nurl);
595 // if it is an external link return the orignal value
596 if ($url == normalise_link($orig_url)) {
604 * @brief Register template engine class
606 * @param string $class
608 private function register_template_engine($class)
610 $v = get_class_vars($class);
613 $this->template_engines[$name] = $class;
615 echo "template engine <tt>$class</tt> cannot be registered without a name.\n";
621 * @brief Return template engine instance.
623 * If $name is not defined, return engine defined by theme,
626 * @return object Template Engine instance
628 public function template_engine()
630 $template_engine = 'smarty3';
631 if (x($this->theme, 'template_engine')) {
632 $template_engine = $this->theme['template_engine'];
635 if (isset($this->template_engines[$template_engine])) {
636 if (isset($this->template_engine_instance[$template_engine])) {
637 return $this->template_engine_instance[$template_engine];
639 $class = $this->template_engines[$template_engine];
641 $this->template_engine_instance[$template_engine] = $obj;
646 echo "template engine <tt>$template_engine</tt> is not registered!\n";
651 * @brief Returns the active template engine.
655 public function get_template_engine()
657 return $this->theme['template_engine'];
660 public function set_template_engine($engine = 'smarty3')
662 $this->theme['template_engine'] = $engine;
665 public function get_template_ldelim($engine = 'smarty3')
667 return $this->ldelim[$engine];
670 public function get_template_rdelim($engine = 'smarty3')
672 return $this->rdelim[$engine];
675 public function save_timestamp($stamp, $value)
677 if (!isset($this->config['system']['profiler']) || !$this->config['system']['profiler']) {
681 $duration = (float) (microtime(true) - $stamp);
683 if (!isset($this->performance[$value])) {
684 // Prevent ugly E_NOTICE
685 $this->performance[$value] = 0;
688 $this->performance[$value] += (float) $duration;
689 $this->performance['marktime'] += (float) $duration;
691 $callstack = System::callstack();
693 if (!isset($this->callstack[$value][$callstack])) {
694 // Prevent ugly E_NOTICE
695 $this->callstack[$value][$callstack] = 0;
698 $this->callstack[$value][$callstack] += (float) $duration;
701 public function get_useragent()
704 FRIENDICA_PLATFORM . " '" .
705 FRIENDICA_CODENAME . "' " .
706 FRIENDICA_VERSION . '-' .
707 DB_UPDATE_VERSION . '; ' .
708 $this->get_baseurl();
711 public function is_friendica_app()
713 return $this->is_friendica_app;
717 * @brief Checks if the site is called via a backend process
719 * This isn't a perfect solution. But we need this check very early.
720 * So we cannot wait until the modules are loaded.
722 * @return bool Is it a known backend?
724 public function is_backend()
748 // Check if current module is in backend or backend flag is set
749 return (in_array($this->module, $backends) || $this->backend);
753 * @brief Checks if the maximum number of database processes is reached
755 * @return bool Is the limit reached?
757 public function max_processes_reached()
759 // Deactivated, needs more investigating if this check really makes sense
763 * Commented out to suppress static analyzer issues
765 if ($this->is_backend()) {
766 $process = 'backend';
767 $max_processes = Config::get('system', 'max_processes_backend');
768 if (intval($max_processes) == 0) {
772 $process = 'frontend';
773 $max_processes = Config::get('system', 'max_processes_frontend');
774 if (intval($max_processes) == 0) {
779 $processlist = DBM::processlist();
780 if ($processlist['list'] != '') {
781 logger('Processcheck: Processes: ' . $processlist['amount'] . ' - Processlist: ' . $processlist['list'], LOGGER_DEBUG);
783 if ($processlist['amount'] > $max_processes) {
784 logger('Processcheck: Maximum number of processes for ' . $process . ' tasks (' . $max_processes . ') reached.', LOGGER_DEBUG);
793 * @brief Checks if the minimal memory is reached
795 * @return bool Is the memory limit reached?
797 public function min_memory_reached()
799 $min_memory = Config::get('system', 'min_memory', 0);
800 if ($min_memory == 0) {
804 if (!is_readable('/proc/meminfo')) {
808 $memdata = explode("\n", file_get_contents('/proc/meminfo'));
811 foreach ($memdata as $line) {
812 list($key, $val) = explode(':', $line);
813 $meminfo[$key] = (int) trim(str_replace('kB', '', $val));
814 $meminfo[$key] = (int) ($meminfo[$key] / 1024);
817 if (!isset($meminfo['MemAvailable']) || !isset($meminfo['MemFree'])) {
821 $free = $meminfo['MemAvailable'] + $meminfo['MemFree'];
823 $reached = ($free < $min_memory);
826 logger('Minimal memory reached: ' . $free . '/' . $meminfo['MemTotal'] . ' - limit ' . $min_memory, LOGGER_DEBUG);
833 * @brief Checks if the maximum load is reached
835 * @return bool Is the load reached?
837 public function maxload_reached()
839 if ($this->is_backend()) {
840 $process = 'backend';
841 $maxsysload = intval(Config::get('system', 'maxloadavg'));
842 if ($maxsysload < 1) {
846 $process = 'frontend';
847 $maxsysload = intval(Config::get('system', 'maxloadavg_frontend'));
848 if ($maxsysload < 1) {
853 $load = current_load();
855 if (intval($load) > $maxsysload) {
856 logger('system: load ' . $load . ' for ' . $process . ' tasks (' . $maxsysload . ') too high.');
863 public function proc_run($args)
865 if (!function_exists('proc_open')) {
869 array_unshift($args, ((x($this->config, 'php_path')) && (strlen($this->config['php_path'])) ? $this->config['php_path'] : 'php'));
871 for ($x = 0; $x < count($args); $x ++) {
872 $args[$x] = escapeshellarg($args[$x]);
875 $cmdline = implode(' ', $args);
877 if ($this->min_memory_reached()) {
881 if (Config::get('system', 'proc_windows')) {
882 $resource = proc_open('cmd /c start /b ' . $cmdline, [], $foo, $this->get_basepath());
884 $resource = proc_open($cmdline . ' &', [], $foo, $this->get_basepath());
886 if (!is_resource($resource)) {
887 logger('We got no resource for command ' . $cmdline, LOGGER_DEBUG);
890 proc_close($resource);
894 * @brief Returns the system user that is executing the script
896 * This mostly returns something like "www-data".
898 * @return string system username
900 private static function systemuser()
902 if (!function_exists('posix_getpwuid') || !function_exists('posix_geteuid')) {
906 $processUser = posix_getpwuid(posix_geteuid());
907 return $processUser['name'];
911 * @brief Checks if a given directory is usable for the system
913 * @return boolean the directory is usable
915 public static function directory_usable($directory, $check_writable = true)
917 if ($directory == '') {
918 logger('Directory is empty. This shouldn\'t happen.', LOGGER_DEBUG);
922 if (!file_exists($directory)) {
923 logger('Path "' . $directory . '" does not exist for user ' . self::systemuser(), LOGGER_DEBUG);
927 if (is_file($directory)) {
928 logger('Path "' . $directory . '" is a file for user ' . self::systemuser(), LOGGER_DEBUG);
932 if (!is_dir($directory)) {
933 logger('Path "' . $directory . '" is not a directory for user ' . self::systemuser(), LOGGER_DEBUG);
937 if ($check_writable && !is_writable($directory)) {
938 logger('Path "' . $directory . '" is not writable for user ' . self::systemuser(), LOGGER_DEBUG);
946 * @param string $cat Config category
947 * @param string $k Config key
948 * @param mixed $default Default value if it isn't set
950 public function getConfigValue($cat, $k, $default = null)
954 if ($cat === 'config') {
955 if (isset($this->config[$k])) {
956 $return = $this->config[$k];
959 if (isset($this->config[$cat][$k])) {
960 $return = $this->config[$cat][$k];
968 * Sets a value in the config cache. Accepts raw output from the config table
970 * @param string $cat Config category
971 * @param string $k Config key
972 * @param mixed $v Value to set
974 public function setConfigValue($cat, $k, $v)
976 // Only arrays are serialized in database, so we have to unserialize sparingly
977 $value = is_string($v) && preg_match("|^a:[0-9]+:{.*}$|s", $v) ? unserialize($v) : $v;
979 if ($cat === 'config') {
980 $this->config[$k] = $value;
982 if (!isset($this->config[$cat])) {
983 $this->config[$cat] = [];
986 $this->config[$cat][$k] = $value;
991 * Deletes a value from the config cache
993 * @param string $cat Config category
994 * @param string $k Config key
996 public function deleteConfigValue($cat, $k)
998 if ($cat === 'config') {
999 if (isset($this->config[$k])) {
1000 unset($this->config[$k]);
1003 if (isset($this->config[$cat][$k])) {
1004 unset($this->config[$cat][$k]);
1011 * Retrieves a value from the user config cache
1013 * @param int $uid User Id
1014 * @param string $cat Config category
1015 * @param string $k Config key
1016 * @param mixed $default Default value if key isn't set
1018 public function getPConfigValue($uid, $cat, $k, $default = null)
1022 if (isset($this->config[$uid][$cat][$k])) {
1023 $return = $this->config[$uid][$cat][$k];
1030 * Sets a value in the user config cache
1032 * Accepts raw output from the pconfig table
1034 * @param int $uid User Id
1035 * @param string $cat Config category
1036 * @param string $k Config key
1037 * @param mixed $v Value to set
1039 public function setPConfigValue($uid, $cat, $k, $v)
1041 // Only arrays are serialized in database, so we have to unserialize sparingly
1042 $value = is_string($v) && preg_match("|^a:[0-9]+:{.*}$|s", $v) ? unserialize($v) : $v;
1044 if (!isset($this->config[$uid])) {
1045 $this->config[$uid] = [];
1048 if (!isset($this->config[$uid][$cat])) {
1049 $this->config[$uid][$cat] = [];
1052 $this->config[$uid][$cat][$k] = $value;
1056 * Deletes a value from the user config cache
1058 * @param int $uid User Id
1059 * @param string $cat Config category
1060 * @param string $k Config key
1062 public function deletePConfigValue($uid, $cat, $k)
1064 if (isset($this->config[$uid][$cat][$k])) {
1065 unset($this->config[$uid][$cat][$k]);
1070 * Generates the site's default sender email address
1074 public function getSenderEmailAddress()
1076 $sender_email = Config::get('config', 'sender_email');
1077 if (empty($sender_email)) {
1078 $hostname = $this->get_hostname();
1079 if (strpos($hostname, ':')) {
1080 $hostname = substr($hostname, 0, strpos($hostname, ':'));
1083 $sender_email = 'noreply@' . $hostname;
1086 return $sender_email;
1090 * @note Checks, if the App is in the Maintenance-Mode
1094 public function checkMaintenanceMode()
1096 if (Config::get('system', 'maintenance')) {
1097 $this->mode = App::MODE_MAINTENANCE;
1105 * Returns the current theme name.
1109 public function getCurrentTheme()
1111 if ($this->mode == App::MODE_INSTALL) {
1115 //// @TODO Compute the current theme only once (this behavior has
1116 /// already been implemented, but it didn't work well -
1117 /// https://github.com/friendica/friendica/issues/5092)
1118 $this->computeCurrentTheme();
1120 return $this->current_theme;
1124 * Computes the current theme name based on the node settings, the user settings and the device type
1128 private function computeCurrentTheme()
1130 $system_theme = Config::get('system', 'theme');
1131 if (!$system_theme) {
1132 throw new Exception(L10n::t('No system theme config value set.'));
1136 $this->current_theme = $system_theme;
1138 $allowed_themes = explode(',', Config::get('system', 'allowed_themes', $system_theme));
1141 // Find the theme that belongs to the user whose stuff we are looking at
1142 if ($this->profile_uid && ($this->profile_uid != local_user())) {
1143 // Allow folks to override user themes and always use their own on their own site.
1144 // This works only if the user is on the same server
1145 $user = dba::selectFirst('user', ['theme'], ['uid' => $this->profile_uid]);
1146 if (DBM::is_result($user) && !PConfig::get(local_user(), 'system', 'always_my_theme')) {
1147 $page_theme = $user['theme'];
1151 $user_theme = defaults($_SESSION, 'theme', $system_theme);
1152 // Specific mobile theme override
1153 if (($this->is_mobile || $this->is_tablet) && defaults($_SESSION, 'show-mobile', true)) {
1154 $system_mobile_theme = Config::get('system', 'mobile-theme');
1155 $user_mobile_theme = defaults($_SESSION, 'mobile-theme', $system_mobile_theme);
1157 // --- means same mobile theme as desktop
1158 if (!empty($user_mobile_theme) && $user_mobile_theme !== '---') {
1159 $user_theme = $user_mobile_theme;
1164 $theme_name = $page_theme;
1166 $theme_name = $user_theme;
1170 && in_array($theme_name, $allowed_themes)
1171 && (file_exists('view/theme/' . $theme_name . '/style.css')
1172 || file_exists('view/theme/' . $theme_name . '/style.php'))
1174 $this->current_theme = $theme_name;
1179 * @brief Return full URL to theme which is currently in effect.
1181 * Provide a sane default if nothing is chosen or the specified theme does not exist.
1185 public function getCurrentThemeStylesheetPath()
1187 return Core\Theme::getStylesheetPath($this->getCurrentTheme());