7 use Friendica\Core\Config;
8 use Friendica\Core\L10n;
9 use Friendica\Core\PConfig;
10 use Friendica\Core\System;
11 use Friendica\Database\DBM;
14 use Detection\MobileDetect;
18 require_once 'boot.php';
19 require_once 'include/dba.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;
43 public $query_string = '';
57 public $error = false;
62 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;
132 * @brief App constructor.
134 * @param string $basepath Path to the app base folder
136 public function __construct($basepath)
138 if (!static::directory_usable($basepath, false)) {
139 throw new Exception('Basepath ' . $basepath . ' isn\'t usable.');
142 $this->basepath = rtrim($basepath, DIRECTORY_SEPARATOR);
144 $this->determineUrlPath();
146 $this->loadConfigFiles();
148 $this->loadDatabase();
150 $this->determineMode();
152 $this->loadDefaultTimezone();
154 $this->performance['start'] = microtime(true);
155 $this->performance['database'] = 0;
156 $this->performance['database_write'] = 0;
157 $this->performance['cache'] = 0;
158 $this->performance['cache_write'] = 0;
159 $this->performance['network'] = 0;
160 $this->performance['file'] = 0;
161 $this->performance['rendering'] = 0;
162 $this->performance['parser'] = 0;
163 $this->performance['marktime'] = 0;
164 $this->performance['markstart'] = microtime(true);
166 $this->callstack['database'] = [];
167 $this->callstack['database_write'] = [];
168 $this->callstack['cache'] = [];
169 $this->callstack['cache_write'] = [];
170 $this->callstack['network'] = [];
171 $this->callstack['file'] = [];
172 $this->callstack['rendering'] = [];
173 $this->callstack['parser'] = [];
189 $this->process_id = System::processID('log');
193 // This has to be quite large to deal with embedded private photos
194 ini_set('pcre.backtrack_limit', 500000);
196 $this->scheme = 'http';
198 if ((x($_SERVER, 'HTTPS') && $_SERVER['HTTPS']) ||
199 (x($_SERVER, 'HTTP_FORWARDED') && preg_match('/proto=https/', $_SERVER['HTTP_FORWARDED'])) ||
200 (x($_SERVER, 'HTTP_X_FORWARDED_PROTO') && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') ||
201 (x($_SERVER, 'HTTP_X_FORWARDED_SSL') && $_SERVER['HTTP_X_FORWARDED_SSL'] == 'on') ||
202 (x($_SERVER, 'FRONT_END_HTTPS') && $_SERVER['FRONT_END_HTTPS'] == 'on') ||
203 (x($_SERVER, 'SERVER_PORT') && (intval($_SERVER['SERVER_PORT']) == 443)) // XXX: reasonable assumption, but isn't this hardcoding too much?
205 $this->scheme = 'https';
208 if (x($_SERVER, 'SERVER_NAME')) {
209 $this->hostname = $_SERVER['SERVER_NAME'];
211 if (x($_SERVER, 'SERVER_PORT') && $_SERVER['SERVER_PORT'] != 80 && $_SERVER['SERVER_PORT'] != 443) {
212 $this->hostname .= ':' . $_SERVER['SERVER_PORT'];
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);
224 } elseif ((x($_SERVER, 'QUERY_STRING')) && substr($_SERVER['QUERY_STRING'], 0, 2) === 'q=') {
225 $this->query_string = substr($_SERVER['QUERY_STRING'], 2);
228 // removing trailing / - maybe a nginx problem
229 $this->query_string = ltrim($this->query_string, '/');
231 if (!empty($_GET['pagename'])) {
232 $this->cmd = trim($_GET['pagename'], '/\\');
233 } elseif (!empty($_GET['q'])) {
234 $this->cmd = trim($_GET['q'], '/\\');
238 $this->query_string = str_replace($this->cmd . '&', $this->cmd . '?', $this->query_string);
240 // unix style "homedir"
241 if (substr($this->cmd, 0, 1) === '~') {
242 $this->cmd = 'profile/' . substr($this->cmd, 1);
245 // Diaspora style profile url
246 if (substr($this->cmd, 0, 2) === 'u/') {
247 $this->cmd = 'profile/' . substr($this->cmd, 2);
251 * Break the URL path into C style argc/argv style arguments for our
252 * modules. Given "http://example.com/module/arg1/arg2", $this->argc
253 * will be 3 (integer) and $this->argv will contain:
259 * There will always be one argument. If provided a naked domain
260 * URL, $this->argv[0] is set to "home".
263 $this->argv = explode('/', $this->cmd);
264 $this->argc = count($this->argv);
265 if ((array_key_exists('0', $this->argv)) && strlen($this->argv[0])) {
266 $this->module = str_replace('.', '_', $this->argv[0]);
267 $this->module = str_replace('-', '_', $this->module);
270 $this->argv = ['home'];
271 $this->module = 'home';
274 // See if there is any page number information, and initialise pagination
275 $this->pager['page'] = ((x($_GET, 'page') && intval($_GET['page']) > 0) ? intval($_GET['page']) : 1);
276 $this->pager['itemspage'] = 50;
277 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
279 if ($this->pager['start'] < 0) {
280 $this->pager['start'] = 0;
282 $this->pager['total'] = 0;
284 // Detect mobile devices
285 $mobile_detect = new MobileDetect();
286 $this->is_mobile = $mobile_detect->isMobile();
287 $this->is_tablet = $mobile_detect->isTablet();
290 $this->is_friendica_app = isset($_SERVER['HTTP_USER_AGENT']) && $_SERVER['HTTP_USER_AGENT'] == 'Apache-HttpClient/UNAVAILABLE (java 1.4)';
292 // Register template engines
293 $this->register_template_engine('Friendica\Render\FriendicaSmartyEngine');
296 private function loadConfigFiles()
298 $this->loadConfigFile($this->basepath . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'defaults.ini.php');
300 // Legacy .htconfig.php support
301 if (file_exists($this->basepath . DIRECTORY_SEPARATOR . '.htpreconfig.php')) {
303 include $this->basepath . DIRECTORY_SEPARATOR . '.htpreconfig.php';
306 // Legacy .htconfig.php support
307 if (file_exists($this->basepath . DIRECTORY_SEPARATOR . '.htconfig.php')) {
310 include $this->basepath . DIRECTORY_SEPARATOR . '.htconfig.php';
311 unset($db_host, $db_user, $db_pass, $db_data);
313 if (isset($default_timezone)) {
314 $this->setConfigValue('system', 'default_timezone', $default_timezone);
315 unset($default_timezone);
318 if (isset($pidfile)) {
319 $this->setConfigValue('system', 'pidfile', $pidfile);
324 if (file_exists($this->basepath . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'local.ini.php')) {
325 $this->loadConfigFile($this->basepath . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'local.ini.php');
329 public function loadConfigFile($filepath)
331 if (!file_exists($filepath)) {
332 throw new Exception('Error parsing non-existent config file ' . $filepath);
335 $contents = include($filepath);
337 $config = parse_ini_string($contents, true, INI_SCANNER_TYPED);
339 if ($config === false) {
340 throw new Exception('Error parsing config file ' . $filepath);
343 foreach($config as $category => $values) {
344 foreach($values as $key => $value) {
345 $this->setConfigValue($category, $key, $value);
350 private function loadAddonConfig()
352 // Loads addons default config
353 Core\Addon::callHooks('load_config');
355 // Load the local config file again in case there are overwritten addon config
356 if (file_exists($this->basepath . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'local.ini.php')) {
357 $this->loadConfigFile($this->basepath . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'local.ini.php');
361 private function loadDefaultTimezone()
363 if ($this->getConfigValue('system', 'default_timezone')) {
364 $this->timezone = $this->getConfigValue('system', 'default_timezone');
366 global $default_timezone;
367 $this->timezone = !empty($default_timezone) ? $default_timezone : 'UTC';
370 if ($this->timezone) {
371 date_default_timezone_set($this->timezone);
376 * Figure out if we are running at the top of a domain
377 * or in a sub-directory and adjust accordingly
379 private function determineUrlPath()
381 $this->urlpath = $this->getConfigValue('system', 'urlpath');
383 /* SCRIPT_URL gives /path/to/friendica/module/parameter
384 * QUERY_STRING gives pagename=module/parameter
386 * To get /path/to/friendica we perform dirname() for as many levels as there are slashes in the QUERY_STRING
388 if (!empty($_SERVER['SCRIPT_URL']) && !empty($_SERVER['QUERY_STRING'])) {
389 $path = trim(dirname($_SERVER['SCRIPT_URL'], substr_count(trim($_SERVER['QUERY_STRING'], '/'), '/') + 1), '/');
391 if ($path && $path != $this->urlpath) {
392 $this->urlpath = $path;
397 private function determineMode()
399 $this->mode = App::MODE_INSTALL;
401 // Missing DB connection
402 if (!\dba::connected()) {
406 // Working DB connection, missing tables
407 if (\dba::fetch_first("SHOW TABLES LIKE 'config'") === false) {
411 // Maintenance mode check
412 if (Config::get('system', 'maintenance')) {
413 $this->mode = App::MODE_MAINTENANCE;
415 $this->mode = App::MODE_NORMAL;
419 public function loadDatabase()
421 if (\dba::connected()) {
425 $db_host = $this->getConfigValue('database', 'hostname');
426 $db_user = $this->getConfigValue('database', 'username');
427 $db_pass = $this->getConfigValue('database', 'password');
428 $db_data = $this->getConfigValue('database', 'database');
429 $charset = $this->getConfigValue('database', 'charset');
431 // Use environment variables for mysql if they are set beforehand
432 if (!empty(getenv('MYSQL_HOST'))
433 && !empty(getenv('MYSQL_PORT'))
434 && (!empty(getenv('MYSQL_USERNAME')) || !empty(getenv('MYSQL_USER')))
435 && !empty(getenv('MYSQL_PASSWORD'))
436 && !empty(getenv('MYSQL_DATABASE')))
438 $db_host = getenv('MYSQL_HOST') . ':' . getenv('MYSQL_PORT');
440 if (!empty(getenv('MYSQL_USERNAME'))) {
441 $db_user = getenv('MYSQL_USERNAME');
442 } elseif (!empty(getenv('MYSQL_USER'))) {
443 $db_user = getenv('MYSQL_USER');
446 $db_pass = getenv('MYSQL_PASSWORD');
447 $db_data = getenv('MYSQL_DATABASE');
448 }elseif (file_exists($this->basepath . DIRECTORY_SEPARATOR . '.htconfig.php')) {
449 $a = new \stdClass();
450 include $this->basepath . DIRECTORY_SEPARATOR . '.htconfig.php';
451 $charset = isset($a->config["system"]["db_charset"]) ? $a->config["system"]["db_charset"] : $charset;
456 $stamp1 = microtime(true);
458 \dba::connect($db_host, $db_user, $db_pass, $db_data, $charset);
459 unset($db_host, $db_user, $db_pass, $db_data, $charset);
461 $this->save_timestamp($stamp1, "network");
465 * @brief Returns the base filesystem path of the App
467 * It first checks for the internal variable, then for DOCUMENT_ROOT and
472 public function get_basepath()
474 $basepath = $this->basepath;
477 $basepath = Config::get('system', 'basepath');
480 if (!$basepath && x($_SERVER, 'DOCUMENT_ROOT')) {
481 $basepath = $_SERVER['DOCUMENT_ROOT'];
484 if (!$basepath && x($_SERVER, 'PWD')) {
485 $basepath = $_SERVER['PWD'];
488 return self::realpath($basepath);
492 * @brief Returns a normalized file path
494 * This is a wrapper for the "realpath" function.
495 * That function cannot detect the real path when some folders aren't readable.
496 * Since this could happen with some hosters we need to handle this.
498 * @param string $path The path that is about to be normalized
499 * @return string normalized path - when possible
501 public static function realpath($path)
503 $normalized = realpath($path);
505 if (!is_bool($normalized)) {
512 public function get_scheme()
514 return $this->scheme;
518 * @brief Retrieves the Friendica instance base URL
520 * This function assembles the base URL from multiple parts:
521 * - Protocol is determined either by the request or a combination of
522 * system.ssl_policy and the $ssl parameter.
523 * - Host name is determined either by system.hostname or inferred from request
524 * - Path is inferred from SCRIPT_NAME
526 * Note: $ssl parameter value doesn't directly correlate with the resulting protocol
528 * @param bool $ssl Whether to append http or https under SSL_POLICY_SELFSIGN
529 * @return string Friendica server base URL
531 public function get_baseurl($ssl = false)
533 $scheme = $this->scheme;
535 if (Config::get('system', 'ssl_policy') == SSL_POLICY_FULL) {
539 // Basically, we have $ssl = true on any links which can only be seen by a logged in user
540 // (and also the login link). Anything seen by an outsider will have it turned off.
542 if (Config::get('system', 'ssl_policy') == SSL_POLICY_SELFSIGN) {
550 if (Config::get('config', 'hostname') != '') {
551 $this->hostname = Config::get('config', 'hostname');
554 return $scheme . '://' . $this->hostname . (!empty($this->urlpath) ? '/' . $this->urlpath : '' );
558 * @brief Initializes the baseurl components
560 * Clears the baseurl cache to prevent inconsistencies
564 public function set_baseurl($url)
566 $parsed = @parse_url($url);
570 if (!empty($parsed['scheme'])) {
571 $this->scheme = $parsed['scheme'];
574 if (!empty($parsed['host'])) {
575 $hostname = $parsed['host'];
578 if (x($parsed, 'port')) {
579 $hostname .= ':' . $parsed['port'];
581 if (x($parsed, 'path')) {
582 $this->urlpath = trim($parsed['path'], '\\/');
585 if (file_exists($this->basepath . DIRECTORY_SEPARATOR . '.htpreconfig.php')) {
586 include $this->basepath . DIRECTORY_SEPARATOR . '.htpreconfig.php';
589 if (Config::get('config', 'hostname') != '') {
590 $this->hostname = Config::get('config', 'hostname');
593 if (!isset($this->hostname) || ($this->hostname == '')) {
594 $this->hostname = $hostname;
599 public function get_hostname()
601 if (Config::get('config', 'hostname') != '') {
602 $this->hostname = Config::get('config', 'hostname');
605 return $this->hostname;
608 public function get_path()
610 return $this->urlpath;
613 public function set_pager_total($n)
615 $this->pager['total'] = intval($n);
618 public function set_pager_itemspage($n)
620 $this->pager['itemspage'] = ((intval($n) > 0) ? intval($n) : 0);
621 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
624 public function set_pager_page($n)
626 $this->pager['page'] = $n;
627 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
630 public function init_pagehead()
632 $interval = ((local_user()) ? PConfig::get(local_user(), 'system', 'update_interval') : 40000);
634 // If the update is 'deactivated' set it to the highest integer number (~24 days)
636 $interval = 2147483647;
639 if ($interval < 10000) {
643 // compose the page title from the sitename and the
644 // current module called
645 if (!$this->module == '') {
646 $this->page['title'] = $this->config['sitename'] . ' (' . $this->module . ')';
648 $this->page['title'] = $this->config['sitename'];
651 /* put the head template at the beginning of page['htmlhead']
652 * since the code added by the modules frequently depends on it
655 if (!isset($this->page['htmlhead'])) {
656 $this->page['htmlhead'] = '';
659 // If we're using Smarty, then doing replace_macros() will replace
660 // any unrecognized variables with a blank string. Since we delay
661 // replacing $stylesheet until later, we need to replace it now
662 // with another variable name
663 if ($this->theme['template_engine'] === 'smarty3') {
664 $stylesheet = $this->get_template_ldelim('smarty3') . '$stylesheet' . $this->get_template_rdelim('smarty3');
666 $stylesheet = '$stylesheet';
669 $shortcut_icon = Config::get('system', 'shortcut_icon');
670 if ($shortcut_icon == '') {
671 $shortcut_icon = 'images/friendica-32.png';
674 $touch_icon = Config::get('system', 'touch_icon');
675 if ($touch_icon == '') {
676 $touch_icon = 'images/friendica-128.png';
679 // get data wich is needed for infinite scroll on the network page
680 $invinite_scroll = infinite_scroll_data($this->module);
682 $tpl = get_markup_template('head.tpl');
683 $this->page['htmlhead'] = replace_macros($tpl, [
684 '$baseurl' => $this->get_baseurl(),
685 '$local_user' => local_user(),
686 '$generator' => 'Friendica' . ' ' . FRIENDICA_VERSION,
687 '$delitem' => L10n::t('Delete this item?'),
688 '$showmore' => L10n::t('show more'),
689 '$showfewer' => L10n::t('show fewer'),
690 '$update_interval' => $interval,
691 '$shortcut_icon' => $shortcut_icon,
692 '$touch_icon' => $touch_icon,
693 '$stylesheet' => $stylesheet,
694 '$infinite_scroll' => $invinite_scroll,
695 '$block_public' => intval(Config::get('system', 'block_public')),
696 ]) . $this->page['htmlhead'];
699 public function init_page_end()
701 if (!isset($this->page['end'])) {
702 $this->page['end'] = '';
704 $tpl = get_markup_template('end.tpl');
705 $this->page['end'] = replace_macros($tpl, [
706 '$baseurl' => $this->get_baseurl()
707 ]) . $this->page['end'];
710 public function set_curl_code($code)
712 $this->curl_code = $code;
715 public function get_curl_code()
717 return $this->curl_code;
720 public function set_curl_content_type($content_type)
722 $this->curl_content_type = $content_type;
725 public function get_curl_content_type()
727 return $this->curl_content_type;
730 public function set_curl_headers($headers)
732 $this->curl_headers = $headers;
735 public function get_curl_headers()
737 return $this->curl_headers;
741 * @brief Removes the base url from an url. This avoids some mixed content problems.
743 * @param string $orig_url
745 * @return string The cleaned url
747 public function remove_baseurl($orig_url)
749 // Remove the hostname from the url if it is an internal link
750 $nurl = normalise_link($orig_url);
751 $base = normalise_link($this->get_baseurl());
752 $url = str_replace($base . '/', '', $nurl);
754 // if it is an external link return the orignal value
755 if ($url == normalise_link($orig_url)) {
763 * @brief Register template engine class
765 * @param string $class
767 private function register_template_engine($class)
769 $v = get_class_vars($class);
772 $this->template_engines[$name] = $class;
774 echo "template engine <tt>$class</tt> cannot be registered without a name.\n";
780 * @brief Return template engine instance.
782 * If $name is not defined, return engine defined by theme,
785 * @return object Template Engine instance
787 public function template_engine()
789 $template_engine = 'smarty3';
790 if (x($this->theme, 'template_engine')) {
791 $template_engine = $this->theme['template_engine'];
794 if (isset($this->template_engines[$template_engine])) {
795 if (isset($this->template_engine_instance[$template_engine])) {
796 return $this->template_engine_instance[$template_engine];
798 $class = $this->template_engines[$template_engine];
800 $this->template_engine_instance[$template_engine] = $obj;
805 echo "template engine <tt>$template_engine</tt> is not registered!\n";
810 * @brief Returns the active template engine.
814 public function get_template_engine()
816 return $this->theme['template_engine'];
819 public function set_template_engine($engine = 'smarty3')
821 $this->theme['template_engine'] = $engine;
824 public function get_template_ldelim($engine = 'smarty3')
826 return $this->ldelim[$engine];
829 public function get_template_rdelim($engine = 'smarty3')
831 return $this->rdelim[$engine];
834 public function save_timestamp($stamp, $value)
836 if (!isset($this->config['system']['profiler']) || !$this->config['system']['profiler']) {
840 $duration = (float) (microtime(true) - $stamp);
842 if (!isset($this->performance[$value])) {
843 // Prevent ugly E_NOTICE
844 $this->performance[$value] = 0;
847 $this->performance[$value] += (float) $duration;
848 $this->performance['marktime'] += (float) $duration;
850 $callstack = System::callstack();
852 if (!isset($this->callstack[$value][$callstack])) {
853 // Prevent ugly E_NOTICE
854 $this->callstack[$value][$callstack] = 0;
857 $this->callstack[$value][$callstack] += (float) $duration;
860 public function get_useragent()
863 FRIENDICA_PLATFORM . " '" .
864 FRIENDICA_CODENAME . "' " .
865 FRIENDICA_VERSION . '-' .
866 DB_UPDATE_VERSION . '; ' .
867 $this->get_baseurl();
870 public function is_friendica_app()
872 return $this->is_friendica_app;
876 * @brief Checks if the site is called via a backend process
878 * This isn't a perfect solution. But we need this check very early.
879 * So we cannot wait until the modules are loaded.
881 * @return bool Is it a known backend?
883 public function is_backend()
907 // Check if current module is in backend or backend flag is set
908 return (in_array($this->module, $backends) || $this->backend);
912 * @brief Checks if the maximum number of database processes is reached
914 * @return bool Is the limit reached?
916 public function max_processes_reached()
918 // Deactivated, needs more investigating if this check really makes sense
922 * Commented out to suppress static analyzer issues
924 if ($this->is_backend()) {
925 $process = 'backend';
926 $max_processes = Config::get('system', 'max_processes_backend');
927 if (intval($max_processes) == 0) {
931 $process = 'frontend';
932 $max_processes = Config::get('system', 'max_processes_frontend');
933 if (intval($max_processes) == 0) {
938 $processlist = DBM::processlist();
939 if ($processlist['list'] != '') {
940 logger('Processcheck: Processes: ' . $processlist['amount'] . ' - Processlist: ' . $processlist['list'], LOGGER_DEBUG);
942 if ($processlist['amount'] > $max_processes) {
943 logger('Processcheck: Maximum number of processes for ' . $process . ' tasks (' . $max_processes . ') reached.', LOGGER_DEBUG);
952 * @brief Checks if the minimal memory is reached
954 * @return bool Is the memory limit reached?
956 public function min_memory_reached()
958 $min_memory = Config::get('system', 'min_memory', 0);
959 if ($min_memory == 0) {
963 if (!is_readable('/proc/meminfo')) {
967 $memdata = explode("\n", file_get_contents('/proc/meminfo'));
970 foreach ($memdata as $line) {
971 list($key, $val) = explode(':', $line);
972 $meminfo[$key] = (int) trim(str_replace('kB', '', $val));
973 $meminfo[$key] = (int) ($meminfo[$key] / 1024);
976 if (!isset($meminfo['MemAvailable']) || !isset($meminfo['MemFree'])) {
980 $free = $meminfo['MemAvailable'] + $meminfo['MemFree'];
982 $reached = ($free < $min_memory);
985 logger('Minimal memory reached: ' . $free . '/' . $meminfo['MemTotal'] . ' - limit ' . $min_memory, LOGGER_DEBUG);
992 * @brief Checks if the maximum load is reached
994 * @return bool Is the load reached?
996 public function maxload_reached()
998 if ($this->is_backend()) {
999 $process = 'backend';
1000 $maxsysload = intval(Config::get('system', 'maxloadavg'));
1001 if ($maxsysload < 1) {
1005 $process = 'frontend';
1006 $maxsysload = intval(Config::get('system', 'maxloadavg_frontend'));
1007 if ($maxsysload < 1) {
1012 $load = current_load();
1014 if (intval($load) > $maxsysload) {
1015 logger('system: load ' . $load . ' for ' . $process . ' tasks (' . $maxsysload . ') too high.');
1022 public function proc_run($args)
1024 if (!function_exists('proc_open')) {
1028 array_unshift($args, $this->getConfigValue('config', 'php_path', 'php'));
1030 for ($x = 0; $x < count($args); $x ++) {
1031 $args[$x] = escapeshellarg($args[$x]);
1034 $cmdline = implode(' ', $args);
1036 if ($this->min_memory_reached()) {
1040 if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
1041 $resource = proc_open('cmd /c start /b ' . $cmdline, [], $foo, $this->get_basepath());
1043 $resource = proc_open($cmdline . ' &', [], $foo, $this->get_basepath());
1045 if (!is_resource($resource)) {
1046 logger('We got no resource for command ' . $cmdline, LOGGER_DEBUG);
1049 proc_close($resource);
1053 * @brief Returns the system user that is executing the script
1055 * This mostly returns something like "www-data".
1057 * @return string system username
1059 private static function systemuser()
1061 if (!function_exists('posix_getpwuid') || !function_exists('posix_geteuid')) {
1065 $processUser = posix_getpwuid(posix_geteuid());
1066 return $processUser['name'];
1070 * @brief Checks if a given directory is usable for the system
1072 * @return boolean the directory is usable
1074 public static function directory_usable($directory, $check_writable = true)
1076 if ($directory == '') {
1077 logger('Directory is empty. This shouldn\'t happen.', LOGGER_DEBUG);
1081 if (!file_exists($directory)) {
1082 logger('Path "' . $directory . '" does not exist for user ' . self::systemuser(), LOGGER_DEBUG);
1086 if (is_file($directory)) {
1087 logger('Path "' . $directory . '" is a file for user ' . self::systemuser(), LOGGER_DEBUG);
1091 if (!is_dir($directory)) {
1092 logger('Path "' . $directory . '" is not a directory for user ' . self::systemuser(), LOGGER_DEBUG);
1096 if ($check_writable && !is_writable($directory)) {
1097 logger('Path "' . $directory . '" is not writable for user ' . self::systemuser(), LOGGER_DEBUG);
1105 * @param string $cat Config category
1106 * @param string $k Config key
1107 * @param mixed $default Default value if it isn't set
1109 public function getConfigValue($cat, $k, $default = null)
1113 if ($cat === 'config') {
1114 if (isset($this->config[$k])) {
1115 $return = $this->config[$k];
1118 if (isset($this->config[$cat][$k])) {
1119 $return = $this->config[$cat][$k];
1127 * Sets a value in the config cache. Accepts raw output from the config table
1129 * @param string $cat Config category
1130 * @param string $k Config key
1131 * @param mixed $v Value to set
1133 public function setConfigValue($cat, $k, $v)
1135 // Only arrays are serialized in database, so we have to unserialize sparingly
1136 $value = is_string($v) && preg_match("|^a:[0-9]+:{.*}$|s", $v) ? unserialize($v) : $v;
1138 if ($cat === 'config') {
1139 $this->config[$k] = $value;
1141 if (!isset($this->config[$cat])) {
1142 $this->config[$cat] = [];
1145 $this->config[$cat][$k] = $value;
1150 * Deletes a value from the config cache
1152 * @param string $cat Config category
1153 * @param string $k Config key
1155 public function deleteConfigValue($cat, $k)
1157 if ($cat === 'config') {
1158 if (isset($this->config[$k])) {
1159 unset($this->config[$k]);
1162 if (isset($this->config[$cat][$k])) {
1163 unset($this->config[$cat][$k]);
1170 * Retrieves a value from the user config cache
1172 * @param int $uid User Id
1173 * @param string $cat Config category
1174 * @param string $k Config key
1175 * @param mixed $default Default value if key isn't set
1177 public function getPConfigValue($uid, $cat, $k, $default = null)
1181 if (isset($this->config[$uid][$cat][$k])) {
1182 $return = $this->config[$uid][$cat][$k];
1189 * Sets a value in the user config cache
1191 * Accepts raw output from the pconfig table
1193 * @param int $uid User Id
1194 * @param string $cat Config category
1195 * @param string $k Config key
1196 * @param mixed $v Value to set
1198 public function setPConfigValue($uid, $cat, $k, $v)
1200 // Only arrays are serialized in database, so we have to unserialize sparingly
1201 $value = is_string($v) && preg_match("|^a:[0-9]+:{.*}$|s", $v) ? unserialize($v) : $v;
1203 if (!isset($this->config[$uid])) {
1204 $this->config[$uid] = [];
1207 if (!isset($this->config[$uid][$cat])) {
1208 $this->config[$uid][$cat] = [];
1211 $this->config[$uid][$cat][$k] = $value;
1215 * Deletes a value from the user config cache
1217 * @param int $uid User Id
1218 * @param string $cat Config category
1219 * @param string $k Config key
1221 public function deletePConfigValue($uid, $cat, $k)
1223 if (isset($this->config[$uid][$cat][$k])) {
1224 unset($this->config[$uid][$cat][$k]);
1229 * Generates the site's default sender email address
1233 public function getSenderEmailAddress()
1235 $sender_email = Config::get('config', 'sender_email');
1236 if (empty($sender_email)) {
1237 $hostname = $this->get_hostname();
1238 if (strpos($hostname, ':')) {
1239 $hostname = substr($hostname, 0, strpos($hostname, ':'));
1242 $sender_email = 'noreply@' . $hostname;
1245 return $sender_email;
1249 * Returns the current theme name.
1253 public function getCurrentTheme()
1255 if ($this->mode == App::MODE_INSTALL) {
1259 //// @TODO Compute the current theme only once (this behavior has
1260 /// already been implemented, but it didn't work well -
1261 /// https://github.com/friendica/friendica/issues/5092)
1262 $this->computeCurrentTheme();
1264 return $this->current_theme;
1268 * Computes the current theme name based on the node settings, the user settings and the device type
1272 private function computeCurrentTheme()
1274 $system_theme = Config::get('system', 'theme');
1275 if (!$system_theme) {
1276 throw new Exception(L10n::t('No system theme config value set.'));
1280 $this->current_theme = $system_theme;
1282 $allowed_themes = explode(',', Config::get('system', 'allowed_themes', $system_theme));
1285 // Find the theme that belongs to the user whose stuff we are looking at
1286 if ($this->profile_uid && ($this->profile_uid != local_user())) {
1287 // Allow folks to override user themes and always use their own on their own site.
1288 // This works only if the user is on the same server
1289 $user = dba::selectFirst('user', ['theme'], ['uid' => $this->profile_uid]);
1290 if (DBM::is_result($user) && !PConfig::get(local_user(), 'system', 'always_my_theme')) {
1291 $page_theme = $user['theme'];
1295 if (!empty($_SESSION)) {
1296 $user_theme = defaults($_SESSION, 'theme', $system_theme);
1298 $user_theme = $system_theme;
1301 // Specific mobile theme override
1302 if (($this->is_mobile || $this->is_tablet) && defaults($_SESSION, 'show-mobile', true)) {
1303 $system_mobile_theme = Config::get('system', 'mobile-theme');
1304 $user_mobile_theme = defaults($_SESSION, 'mobile-theme', $system_mobile_theme);
1306 // --- means same mobile theme as desktop
1307 if (!empty($user_mobile_theme) && $user_mobile_theme !== '---') {
1308 $user_theme = $user_mobile_theme;
1313 $theme_name = $page_theme;
1315 $theme_name = $user_theme;
1319 && in_array($theme_name, $allowed_themes)
1320 && (file_exists('view/theme/' . $theme_name . '/style.css')
1321 || file_exists('view/theme/' . $theme_name . '/style.php'))
1323 $this->current_theme = $theme_name;
1328 * @brief Return full URL to theme which is currently in effect.
1330 * Provide a sane default if nothing is chosen or the specified theme does not exist.
1334 public function getCurrentThemeStylesheetPath()
1336 return Core\Theme::getStylesheetPath($this->getCurrentTheme());