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;
13 use Detection\MobileDetect;
17 require_once 'boot.php';
18 require_once 'include/text.php';
24 * @brief Our main application structure for the life of this page.
26 * Primarily deals with the URL that got us here
27 * and tries to make some sense of it, and
28 * stores our page contents and config storage
29 * and anything else that might need to be passed around
30 * before we spit the page out.
35 const MODE_NORMAL = 0;
36 const MODE_INSTALL = 1;
37 const MODE_MAINTENANCE = 2;
39 public $module_loaded = false;
40 public $module_class = null;
54 public $error = false;
59 public $mode = App::MODE_NORMAL;
66 public $interactive = true;
68 public $addons_admin = [];
71 public $is_mobile = false;
72 public $is_tablet = false;
73 public $is_friendica_app;
74 public $performance = [];
75 public $callstack = [];
76 public $theme_info = [];
77 public $backend = true;
80 // Allow themes to control internal parameters
81 // by changing App values in theme.php
83 public $sourcename = '';
84 public $videowidth = 425;
85 public $videoheight = 350;
86 public $force_max_items = 0;
87 public $theme_events_in_profile = true;
90 * @brief An array for all theme-controllable parameters
92 * Mostly unimplemented yet. Only options 'template_engine' and
99 'force_max_items' => 0,
101 'template_engine' => 'smarty3',
105 * @brief An array of registered template engines ('name'=>'class name')
107 public $template_engines = [];
110 * @brief An array of instanced template engines ('name'=>'instance')
112 public $template_engine_instance = [];
126 private $curl_content_type;
127 private $curl_headers;
131 * @brief App constructor.
133 * @param string $basepath Path to the app base folder
135 public function __construct($basepath)
137 global $default_timezone;
139 if (!static::directory_usable($basepath, false)) {
140 throw new Exception('Basepath ' . $basepath . ' isn\'t usable.');
143 $this->basepath = rtrim($basepath, DIRECTORY_SEPARATOR);
145 if (file_exists($this->basepath . DIRECTORY_SEPARATOR . '.htpreconfig.php')) {
146 include $this->basepath . DIRECTORY_SEPARATOR . '.htpreconfig.php';
149 $this->timezone = ((x($default_timezone)) ? $default_timezone : 'UTC');
151 date_default_timezone_set($this->timezone);
153 $this->performance['start'] = microtime(true);
154 $this->performance['database'] = 0;
155 $this->performance['database_write'] = 0;
156 $this->performance['cache'] = 0;
157 $this->performance['cache_write'] = 0;
158 $this->performance['network'] = 0;
159 $this->performance['file'] = 0;
160 $this->performance['rendering'] = 0;
161 $this->performance['parser'] = 0;
162 $this->performance['marktime'] = 0;
163 $this->performance['markstart'] = microtime(true);
165 $this->callstack['database'] = [];
166 $this->callstack['database_write'] = [];
167 $this->callstack['cache'] = [];
168 $this->callstack['cache_write'] = [];
169 $this->callstack['network'] = [];
170 $this->callstack['file'] = [];
171 $this->callstack['rendering'] = [];
172 $this->callstack['parser'] = [];
178 $this->query_string = '';
180 $this->process_id = uniqid('log', true);
184 $this->scheme = 'http';
186 if ((x($_SERVER, 'HTTPS') && $_SERVER['HTTPS']) ||
187 (x($_SERVER, 'HTTP_FORWARDED') && preg_match('/proto=https/', $_SERVER['HTTP_FORWARDED'])) ||
188 (x($_SERVER, 'HTTP_X_FORWARDED_PROTO') && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') ||
189 (x($_SERVER, 'HTTP_X_FORWARDED_SSL') && $_SERVER['HTTP_X_FORWARDED_SSL'] == 'on') ||
190 (x($_SERVER, 'FRONT_END_HTTPS') && $_SERVER['FRONT_END_HTTPS'] == 'on') ||
191 (x($_SERVER, 'SERVER_PORT') && (intval($_SERVER['SERVER_PORT']) == 443)) // XXX: reasonable assumption, but isn't this hardcoding too much?
193 $this->scheme = 'https';
196 if (x($_SERVER, 'SERVER_NAME')) {
197 $this->hostname = $_SERVER['SERVER_NAME'];
199 if (x($_SERVER, 'SERVER_PORT') && $_SERVER['SERVER_PORT'] != 80 && $_SERVER['SERVER_PORT'] != 443) {
200 $this->hostname .= ':' . $_SERVER['SERVER_PORT'];
203 * Figure out if we are running at the top of a domain
204 * or in a sub-directory and adjust accordingly
207 /// @TODO This kind of escaping breaks syntax-highlightning on CoolEdit (Midnight Commander)
208 $path = trim(dirname($_SERVER['SCRIPT_NAME']), '/\\');
209 if (isset($path) && strlen($path) && ($path != $this->path)) {
215 get_include_path() . PATH_SEPARATOR
216 . $this->basepath . DIRECTORY_SEPARATOR . 'include' . PATH_SEPARATOR
217 . $this->basepath . DIRECTORY_SEPARATOR . 'library' . PATH_SEPARATOR
220 if ((x($_SERVER, 'QUERY_STRING')) && substr($_SERVER['QUERY_STRING'], 0, 9) === 'pagename=') {
221 $this->query_string = substr($_SERVER['QUERY_STRING'], 9);
223 // removing trailing / - maybe a nginx problem
224 $this->query_string = ltrim($this->query_string, '/');
225 } elseif ((x($_SERVER, 'QUERY_STRING')) && substr($_SERVER['QUERY_STRING'], 0, 2) === 'q=') {
226 $this->query_string = substr($_SERVER['QUERY_STRING'], 2);
228 // removing trailing / - maybe a nginx problem
229 $this->query_string = ltrim($this->query_string, '/');
232 if (x($_GET, 'pagename')) {
233 $this->cmd = trim($_GET['pagename'], '/\\');
234 } elseif (x($_GET, 'q')) {
235 $this->cmd = trim($_GET['q'], '/\\');
239 $this->query_string = str_replace($this->cmd . '&', $this->cmd . '?', $this->query_string);
241 // unix style "homedir"
242 if (substr($this->cmd, 0, 1) === '~') {
243 $this->cmd = 'profile/' . substr($this->cmd, 1);
246 // Diaspora style profile url
247 if (substr($this->cmd, 0, 2) === 'u/') {
248 $this->cmd = 'profile/' . substr($this->cmd, 2);
252 * Break the URL path into C style argc/argv style arguments for our
253 * modules. Given "http://example.com/module/arg1/arg2", $this->argc
254 * will be 3 (integer) and $this->argv will contain:
260 * There will always be one argument. If provided a naked domain
261 * URL, $this->argv[0] is set to "home".
264 $this->argv = explode('/', $this->cmd);
265 $this->argc = count($this->argv);
266 if ((array_key_exists('0', $this->argv)) && strlen($this->argv[0])) {
267 $this->module = str_replace('.', '_', $this->argv[0]);
268 $this->module = str_replace('-', '_', $this->module);
271 $this->argv = ['home'];
272 $this->module = 'home';
275 // See if there is any page number information, and initialise pagination
276 $this->pager['page'] = ((x($_GET, 'page') && intval($_GET['page']) > 0) ? intval($_GET['page']) : 1);
277 $this->pager['itemspage'] = 50;
278 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
280 if ($this->pager['start'] < 0) {
281 $this->pager['start'] = 0;
283 $this->pager['total'] = 0;
285 // Detect mobile devices
286 $mobile_detect = new MobileDetect();
287 $this->is_mobile = $mobile_detect->isMobile();
288 $this->is_tablet = $mobile_detect->isTablet();
291 $this->is_friendica_app = ($_SERVER['HTTP_USER_AGENT'] == 'Apache-HttpClient/UNAVAILABLE (java 1.4)');
293 // Register template engines
294 $this->register_template_engine('Friendica\Render\FriendicaSmartyEngine');
297 * Load the configuration file which contains our DB credentials.
298 * Ignore errors. If the file doesn't exist or is empty, we are running in
299 * installation mode. *
301 $this->mode = ((file_exists('.htconfig.php') && filesize('.htconfig.php')) ? App::MODE_NORMAL : App::MODE_INSTALL);
308 * @brief Returns the base filesystem path of the App
310 * It first checks for the internal variable, then for DOCUMENT_ROOT and
315 public function get_basepath()
317 $basepath = $this->basepath;
320 $basepath = Config::get('system', 'basepath');
323 if (!$basepath && x($_SERVER, 'DOCUMENT_ROOT')) {
324 $basepath = $_SERVER['DOCUMENT_ROOT'];
327 if (!$basepath && x($_SERVER, 'PWD')) {
328 $basepath = $_SERVER['PWD'];
331 return self::realpath($basepath);
335 * @brief Returns a normalized file path
337 * This is a wrapper for the "realpath" function.
338 * That function cannot detect the real path when some folders aren't readable.
339 * Since this could happen with some hosters we need to handle this.
341 * @param string $path The path that is about to be normalized
342 * @return string normalized path - when possible
344 public static function realpath($path)
346 $normalized = realpath($path);
348 if (!is_bool($normalized)) {
355 public function get_scheme()
357 return $this->scheme;
361 * @brief Retrieves the Friendica instance base URL
363 * This function assembles the base URL from multiple parts:
364 * - Protocol is determined either by the request or a combination of
365 * system.ssl_policy and the $ssl parameter.
366 * - Host name is determined either by system.hostname or inferred from request
367 * - Path is inferred from SCRIPT_NAME
369 * Note: $ssl parameter value doesn't directly correlate with the resulting protocol
371 * @param bool $ssl Whether to append http or https under SSL_POLICY_SELFSIGN
372 * @return string Friendica server base URL
374 public function get_baseurl($ssl = false)
376 $scheme = $this->scheme;
378 if (Config::get('system', 'ssl_policy') == SSL_POLICY_FULL) {
382 // Basically, we have $ssl = true on any links which can only be seen by a logged in user
383 // (and also the login link). Anything seen by an outsider will have it turned off.
385 if (Config::get('system', 'ssl_policy') == SSL_POLICY_SELFSIGN) {
393 if (Config::get('config', 'hostname') != '') {
394 $this->hostname = Config::get('config', 'hostname');
397 return $scheme . '://' . $this->hostname . ((isset($this->path) && strlen($this->path)) ? '/' . $this->path : '' );
401 * @brief Initializes the baseurl components
403 * Clears the baseurl cache to prevent inconsistencies
407 public function set_baseurl($url)
409 $parsed = @parse_url($url);
412 $this->scheme = $parsed['scheme'];
414 $hostname = $parsed['host'];
415 if (x($parsed, 'port')) {
416 $hostname .= ':' . $parsed['port'];
418 if (x($parsed, 'path')) {
419 $this->path = trim($parsed['path'], '\\/');
422 if (file_exists($this->basepath . DIRECTORY_SEPARATOR . '.htpreconfig.php')) {
423 include $this->basepath . DIRECTORY_SEPARATOR . '.htpreconfig.php';
426 if (Config::get('config', 'hostname') != '') {
427 $this->hostname = Config::get('config', 'hostname');
430 if (!isset($this->hostname) || ( $this->hostname == '')) {
431 $this->hostname = $hostname;
436 public function get_hostname()
438 if (Config::get('config', 'hostname') != '') {
439 $this->hostname = Config::get('config', 'hostname');
442 return $this->hostname;
445 public function get_path()
450 public function set_pager_total($n)
452 $this->pager['total'] = intval($n);
455 public function set_pager_itemspage($n)
457 $this->pager['itemspage'] = ((intval($n) > 0) ? intval($n) : 0);
458 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
461 public function set_pager_page($n)
463 $this->pager['page'] = $n;
464 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
467 public function init_pagehead()
469 $interval = ((local_user()) ? PConfig::get(local_user(), 'system', 'update_interval') : 40000);
471 // If the update is 'deactivated' set it to the highest integer number (~24 days)
473 $interval = 2147483647;
476 if ($interval < 10000) {
480 // compose the page title from the sitename and the
481 // current module called
482 if (!$this->module == '') {
483 $this->page['title'] = $this->config['sitename'] . ' (' . $this->module . ')';
485 $this->page['title'] = $this->config['sitename'];
488 /* put the head template at the beginning of page['htmlhead']
489 * since the code added by the modules frequently depends on it
492 if (!isset($this->page['htmlhead'])) {
493 $this->page['htmlhead'] = '';
496 // If we're using Smarty, then doing replace_macros() will replace
497 // any unrecognized variables with a blank string. Since we delay
498 // replacing $stylesheet until later, we need to replace it now
499 // with another variable name
500 if ($this->theme['template_engine'] === 'smarty3') {
501 $stylesheet = $this->get_template_ldelim('smarty3') . '$stylesheet' . $this->get_template_rdelim('smarty3');
503 $stylesheet = '$stylesheet';
506 $shortcut_icon = Config::get('system', 'shortcut_icon');
507 if ($shortcut_icon == '') {
508 $shortcut_icon = 'images/friendica-32.png';
511 $touch_icon = Config::get('system', 'touch_icon');
512 if ($touch_icon == '') {
513 $touch_icon = 'images/friendica-128.png';
516 // get data wich is needed for infinite scroll on the network page
517 $invinite_scroll = infinite_scroll_data($this->module);
519 $tpl = get_markup_template('head.tpl');
520 $this->page['htmlhead'] = replace_macros($tpl, [
521 '$baseurl' => $this->get_baseurl(),
522 '$local_user' => local_user(),
523 '$generator' => 'Friendica' . ' ' . FRIENDICA_VERSION,
524 '$delitem' => L10n::t('Delete this item?'),
525 '$showmore' => L10n::t('show more'),
526 '$showfewer' => L10n::t('show fewer'),
527 '$update_interval' => $interval,
528 '$shortcut_icon' => $shortcut_icon,
529 '$touch_icon' => $touch_icon,
530 '$stylesheet' => $stylesheet,
531 '$infinite_scroll' => $invinite_scroll,
532 ]) . $this->page['htmlhead'];
535 public function init_page_end()
537 if (!isset($this->page['end'])) {
538 $this->page['end'] = '';
540 $tpl = get_markup_template('end.tpl');
541 $this->page['end'] = replace_macros($tpl, [
542 '$baseurl' => $this->get_baseurl()
543 ]) . $this->page['end'];
546 public function set_curl_code($code)
548 $this->curl_code = $code;
551 public function get_curl_code()
553 return $this->curl_code;
556 public function set_curl_content_type($content_type)
558 $this->curl_content_type = $content_type;
561 public function get_curl_content_type()
563 return $this->curl_content_type;
566 public function set_curl_headers($headers)
568 $this->curl_headers = $headers;
571 public function get_curl_headers()
573 return $this->curl_headers;
577 * @brief Removes the base url from an url. This avoids some mixed content problems.
579 * @param string $orig_url
581 * @return string The cleaned url
583 public function remove_baseurl($orig_url)
585 // Remove the hostname from the url if it is an internal link
586 $nurl = normalise_link($orig_url);
587 $base = normalise_link($this->get_baseurl());
588 $url = str_replace($base . '/', '', $nurl);
590 // if it is an external link return the orignal value
591 if ($url == normalise_link($orig_url)) {
599 * @brief Register template engine class
601 * @param string $class
603 private function register_template_engine($class)
605 $v = get_class_vars($class);
608 $this->template_engines[$name] = $class;
610 echo "template engine <tt>$class</tt> cannot be registered without a name.\n";
616 * @brief Return template engine instance.
618 * If $name is not defined, return engine defined by theme,
621 * @return object Template Engine instance
623 public function template_engine()
625 $template_engine = 'smarty3';
626 if (x($this->theme, 'template_engine')) {
627 $template_engine = $this->theme['template_engine'];
630 if (isset($this->template_engines[$template_engine])) {
631 if (isset($this->template_engine_instance[$template_engine])) {
632 return $this->template_engine_instance[$template_engine];
634 $class = $this->template_engines[$template_engine];
636 $this->template_engine_instance[$template_engine] = $obj;
641 echo "template engine <tt>$template_engine</tt> is not registered!\n";
646 * @brief Returns the active template engine.
650 public function get_template_engine()
652 return $this->theme['template_engine'];
655 public function set_template_engine($engine = 'smarty3')
657 $this->theme['template_engine'] = $engine;
660 public function get_template_ldelim($engine = 'smarty3')
662 return $this->ldelim[$engine];
665 public function get_template_rdelim($engine = 'smarty3')
667 return $this->rdelim[$engine];
670 public function save_timestamp($stamp, $value)
672 if (!isset($this->config['system']['profiler']) || !$this->config['system']['profiler']) {
676 $duration = (float) (microtime(true) - $stamp);
678 if (!isset($this->performance[$value])) {
679 // Prevent ugly E_NOTICE
680 $this->performance[$value] = 0;
683 $this->performance[$value] += (float) $duration;
684 $this->performance['marktime'] += (float) $duration;
686 $callstack = System::callstack();
688 if (!isset($this->callstack[$value][$callstack])) {
689 // Prevent ugly E_NOTICE
690 $this->callstack[$value][$callstack] = 0;
693 $this->callstack[$value][$callstack] += (float) $duration;
696 public function get_useragent()
699 FRIENDICA_PLATFORM . " '" .
700 FRIENDICA_CODENAME . "' " .
701 FRIENDICA_VERSION . '-' .
702 DB_UPDATE_VERSION . '; ' .
703 $this->get_baseurl();
706 public function is_friendica_app()
708 return $this->is_friendica_app;
712 * @brief Checks if the site is called via a backend process
714 * This isn't a perfect solution. But we need this check very early.
715 * So we cannot wait until the modules are loaded.
717 * @return bool Is it a known backend?
719 public function is_backend()
743 // Check if current module is in backend or backend flag is set
744 return (in_array($this->module, $backends) || $this->backend);
748 * @brief Checks if the maximum number of database processes is reached
750 * @return bool Is the limit reached?
752 public function max_processes_reached()
754 // Deactivated, needs more investigating if this check really makes sense
758 * Commented out to suppress static analyzer issues
760 if ($this->is_backend()) {
761 $process = 'backend';
762 $max_processes = Config::get('system', 'max_processes_backend');
763 if (intval($max_processes) == 0) {
767 $process = 'frontend';
768 $max_processes = Config::get('system', 'max_processes_frontend');
769 if (intval($max_processes) == 0) {
774 $processlist = DBM::processlist();
775 if ($processlist['list'] != '') {
776 logger('Processcheck: Processes: ' . $processlist['amount'] . ' - Processlist: ' . $processlist['list'], LOGGER_DEBUG);
778 if ($processlist['amount'] > $max_processes) {
779 logger('Processcheck: Maximum number of processes for ' . $process . ' tasks (' . $max_processes . ') reached.', LOGGER_DEBUG);
788 * @brief Checks if the minimal memory is reached
790 * @return bool Is the memory limit reached?
792 public function min_memory_reached()
794 $min_memory = Config::get('system', 'min_memory', 0);
795 if ($min_memory == 0) {
799 if (!is_readable('/proc/meminfo')) {
803 $memdata = explode("\n", file_get_contents('/proc/meminfo'));
806 foreach ($memdata as $line) {
807 list($key, $val) = explode(':', $line);
808 $meminfo[$key] = (int) trim(str_replace('kB', '', $val));
809 $meminfo[$key] = (int) ($meminfo[$key] / 1024);
812 if (!isset($meminfo['MemAvailable']) || !isset($meminfo['MemFree'])) {
816 $free = $meminfo['MemAvailable'] + $meminfo['MemFree'];
818 $reached = ($free < $min_memory);
821 logger('Minimal memory reached: ' . $free . '/' . $meminfo['MemTotal'] . ' - limit ' . $min_memory, LOGGER_DEBUG);
828 * @brief Checks if the maximum load is reached
830 * @return bool Is the load reached?
832 public function maxload_reached()
834 if ($this->is_backend()) {
835 $process = 'backend';
836 $maxsysload = intval(Config::get('system', 'maxloadavg'));
837 if ($maxsysload < 1) {
841 $process = 'frontend';
842 $maxsysload = intval(Config::get('system', 'maxloadavg_frontend'));
843 if ($maxsysload < 1) {
848 $load = current_load();
850 if (intval($load) > $maxsysload) {
851 logger('system: load ' . $load . ' for ' . $process . ' tasks (' . $maxsysload . ') too high.');
858 public function proc_run($args)
860 if (!function_exists('proc_open')) {
864 // If the last worker fork was less than 2 seconds before then don't fork another one.
865 // This should prevent the forking of masses of workers.
866 $cachekey = 'app:proc_run:started';
867 $result = Cache::get($cachekey);
869 if (!is_null($result) && ( time() - $result) < 2) {
873 // Set the timestamp of the last proc_run
874 Cache::set($cachekey, time(), CACHE_MINUTE);
876 array_unshift($args, ((x($this->config, 'php_path')) && (strlen($this->config['php_path'])) ? $this->config['php_path'] : 'php'));
878 for ($x = 0; $x < count($args); $x ++) {
879 $args[$x] = escapeshellarg($args[$x]);
882 $cmdline = implode(' ', $args);
884 if ($this->min_memory_reached()) {
888 if (Config::get('system', 'proc_windows')) {
889 $resource = proc_open('cmd /c start /b ' . $cmdline, [], $foo, $this->get_basepath());
891 $resource = proc_open($cmdline . ' &', [], $foo, $this->get_basepath());
893 if (!is_resource($resource)) {
894 logger('We got no resource for command ' . $cmdline, LOGGER_DEBUG);
897 proc_close($resource);
901 * @brief Returns the system user that is executing the script
903 * This mostly returns something like "www-data".
905 * @return string system username
907 private static function systemuser()
909 if (!function_exists('posix_getpwuid') || !function_exists('posix_geteuid')) {
913 $processUser = posix_getpwuid(posix_geteuid());
914 return $processUser['name'];
918 * @brief Checks if a given directory is usable for the system
920 * @return boolean the directory is usable
922 public static function directory_usable($directory, $check_writable = true)
924 if ($directory == '') {
925 logger('Directory is empty. This shouldn\'t happen.', LOGGER_DEBUG);
929 if (!file_exists($directory)) {
930 logger('Path "' . $directory . '" does not exist for user ' . self::systemuser(), LOGGER_DEBUG);
934 if (is_file($directory)) {
935 logger('Path "' . $directory . '" is a file for user ' . self::systemuser(), LOGGER_DEBUG);
939 if (!is_dir($directory)) {
940 logger('Path "' . $directory . '" is not a directory for user ' . self::systemuser(), LOGGER_DEBUG);
944 if ($check_writable && !is_writable($directory)) {
945 logger('Path "' . $directory . '" is not writable for user ' . self::systemuser(), LOGGER_DEBUG);
953 * @param string $cat Config category
954 * @param string $k Config key
955 * @param mixed $default Default value if it isn't set
957 public function getConfigValue($cat, $k, $default = null)
961 if ($cat === 'config') {
962 if (isset($this->config[$k])) {
963 $return = $this->config[$k];
966 if (isset($this->config[$cat][$k])) {
967 $return = $this->config[$cat][$k];
975 * Sets a value in the config cache. Accepts raw output from the config table
977 * @param string $cat Config category
978 * @param string $k Config key
979 * @param mixed $v Value to set
981 public function setConfigValue($cat, $k, $v)
983 // Only arrays are serialized in database, so we have to unserialize sparingly
984 $value = is_string($v) && preg_match("|^a:[0-9]+:{.*}$|s", $v) ? unserialize($v) : $v;
986 if ($cat === 'config') {
987 $this->config[$k] = $value;
989 $this->config[$cat][$k] = $value;
994 * Deletes a value from the config cache
996 * @param string $cat Config category
997 * @param string $k Config key
999 public function deleteConfigValue($cat, $k)
1001 if ($cat === 'config') {
1002 if (isset($this->config[$k])) {
1003 unset($this->config[$k]);
1006 if (isset($this->config[$cat][$k])) {
1007 unset($this->config[$cat][$k]);
1014 * Retrieves a value from the user config cache
1016 * @param int $uid User Id
1017 * @param string $cat Config category
1018 * @param string $k Config key
1019 * @param mixed $default Default value if key isn't set
1021 public function getPConfigValue($uid, $cat, $k, $default = null)
1025 if (isset($this->config[$uid][$cat][$k])) {
1026 $return = $this->config[$uid][$cat][$k];
1033 * Sets a value in the user config cache
1035 * Accepts raw output from the pconfig table
1037 * @param int $uid User Id
1038 * @param string $cat Config category
1039 * @param string $k Config key
1040 * @param mixed $v Value to set
1042 public function setPConfigValue($uid, $cat, $k, $v)
1044 // Only arrays are serialized in database, so we have to unserialize sparingly
1045 $value = is_string($v) && preg_match("|^a:[0-9]+:{.*}$|s", $v) ? unserialize($v) : $v;
1047 $this->config[$uid][$cat][$k] = $value;
1051 * Deletes a value from the user config cache
1053 * @param int $uid User Id
1054 * @param string $cat Config category
1055 * @param string $k Config key
1057 public function deletePConfigValue($uid, $cat, $k)
1059 if (isset($this->config[$uid][$cat][$k])) {
1060 unset($this->config[$uid][$cat][$k]);
1065 * Generates the site's default sender email address
1069 public function getSenderEmailAddress()
1071 $sender_email = Config::get('config', 'sender_email');
1072 if (empty($sender_email)) {
1073 $hostname = $this->get_hostname();
1074 if (strpos($hostname, ':')) {
1075 $hostname = substr($hostname, 0, strpos($hostname, ':'));
1078 $sender_email = 'noreply@' . $hostname;
1081 return $sender_email;
1085 * @note Checks, if the App is in the Maintenance-Mode
1089 public function checkMaintenanceMode()
1091 if (Config::get('system', 'maintenance')) {
1092 $this->mode = App::MODE_MAINTENANCE;
1100 * Returns the current theme name.
1104 public function getCurrentTheme()
1106 if (!$this->current_theme) {
1107 $this->computeCurrentTheme();
1110 return $this->current_theme;
1114 * Computes the current theme name based on the node settings, the user settings and the device type
1118 private function computeCurrentTheme()
1120 $system_theme = Config::get('system', 'theme');
1121 if (!$system_theme) {
1122 throw new Exception(L10n::t('No system theme config value set.'));
1126 $this->current_theme = $system_theme;
1128 $allowed_themes = explode(',', Config::get('system', 'allowed_themes', $system_theme));
1131 // Find the theme that belongs to the user whose stuff we are looking at
1132 if ($this->profile_uid && ($this->profile_uid != local_user())) {
1133 // Allow folks to override user themes and always use their own on their own site.
1134 // This works only if the user is on the same server
1135 $user = dba::selectFirst('user', ['theme'], ['uid' => $this->profile_uid]);
1136 if (DBM::is_result($user) && !PConfig::get(local_user(), 'system', 'always_my_theme')) {
1137 $page_theme = $user['theme'];
1141 $user_theme = defaults($_SESSION, 'theme', $system_theme);
1142 // Specific mobile theme override
1143 if (($this->is_mobile || $this->is_tablet) && defaults($_SESSION, 'show-mobile', true)) {
1144 $system_mobile_theme = Config::get('system', 'mobile-theme');
1145 $user_mobile_theme = defaults($_SESSION, 'mobile-theme', $system_mobile_theme);
1147 // --- means same mobile theme as desktop
1148 if (!empty($user_mobile_theme) && $user_mobile_theme !== '---') {
1149 $user_theme = $user_mobile_theme;
1154 $theme_name = $page_theme;
1156 $theme_name = $user_theme;
1160 && in_array($theme_name, $allowed_themes)
1161 && (file_exists('view/theme/' . $theme_name . '/style.css')
1162 || file_exists('view/theme/' . $theme_name . '/style.php'))
1164 $this->current_theme = $theme_name;
1169 * @brief Return full URL to theme which is currently in effect.
1171 * Provide a sane default if nothing is chosen or the specified theme does not exist.
1175 public function getCurrentThemeStylesheetPath()
1177 return Core\Theme::getStylesheetPath($this->getCurrentTheme());