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 BaseObject::setApp($this);
144 $this->basepath = rtrim($basepath, DIRECTORY_SEPARATOR);
146 $this->determineUrlPath();
148 $this->loadConfigFiles();
150 $this->loadDatabase();
152 $this->determineMode();
154 $this->loadDefaultTimezone();
156 $this->performance['start'] = microtime(true);
157 $this->performance['database'] = 0;
158 $this->performance['database_write'] = 0;
159 $this->performance['cache'] = 0;
160 $this->performance['cache_write'] = 0;
161 $this->performance['network'] = 0;
162 $this->performance['file'] = 0;
163 $this->performance['rendering'] = 0;
164 $this->performance['parser'] = 0;
165 $this->performance['marktime'] = 0;
166 $this->performance['markstart'] = microtime(true);
168 $this->callstack['database'] = [];
169 $this->callstack['database_write'] = [];
170 $this->callstack['cache'] = [];
171 $this->callstack['cache_write'] = [];
172 $this->callstack['network'] = [];
173 $this->callstack['file'] = [];
174 $this->callstack['rendering'] = [];
175 $this->callstack['parser'] = [];
191 $this->process_id = System::processID('log');
195 // This has to be quite large to deal with embedded private photos
196 ini_set('pcre.backtrack_limit', 500000);
198 $this->scheme = 'http';
200 if ((x($_SERVER, 'HTTPS') && $_SERVER['HTTPS']) ||
201 (x($_SERVER, 'HTTP_FORWARDED') && preg_match('/proto=https/', $_SERVER['HTTP_FORWARDED'])) ||
202 (x($_SERVER, 'HTTP_X_FORWARDED_PROTO') && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') ||
203 (x($_SERVER, 'HTTP_X_FORWARDED_SSL') && $_SERVER['HTTP_X_FORWARDED_SSL'] == 'on') ||
204 (x($_SERVER, 'FRONT_END_HTTPS') && $_SERVER['FRONT_END_HTTPS'] == 'on') ||
205 (x($_SERVER, 'SERVER_PORT') && (intval($_SERVER['SERVER_PORT']) == 443)) // XXX: reasonable assumption, but isn't this hardcoding too much?
207 $this->scheme = 'https';
210 if (x($_SERVER, 'SERVER_NAME')) {
211 $this->hostname = $_SERVER['SERVER_NAME'];
213 if (x($_SERVER, 'SERVER_PORT') && $_SERVER['SERVER_PORT'] != 80 && $_SERVER['SERVER_PORT'] != 443) {
214 $this->hostname .= ':' . $_SERVER['SERVER_PORT'];
219 get_include_path() . PATH_SEPARATOR
220 . $this->basepath . DIRECTORY_SEPARATOR . 'include' . PATH_SEPARATOR
221 . $this->basepath . DIRECTORY_SEPARATOR . 'library' . PATH_SEPARATOR
224 if ((x($_SERVER, 'QUERY_STRING')) && substr($_SERVER['QUERY_STRING'], 0, 9) === 'pagename=') {
225 $this->query_string = substr($_SERVER['QUERY_STRING'], 9);
226 } elseif ((x($_SERVER, 'QUERY_STRING')) && substr($_SERVER['QUERY_STRING'], 0, 2) === 'q=') {
227 $this->query_string = substr($_SERVER['QUERY_STRING'], 2);
230 // removing trailing / - maybe a nginx problem
231 $this->query_string = ltrim($this->query_string, '/');
233 if (!empty($_GET['pagename'])) {
234 $this->cmd = trim($_GET['pagename'], '/\\');
235 } elseif (!empty($_GET['q'])) {
236 $this->cmd = trim($_GET['q'], '/\\');
240 $this->query_string = str_replace($this->cmd . '&', $this->cmd . '?', $this->query_string);
242 // unix style "homedir"
243 if (substr($this->cmd, 0, 1) === '~') {
244 $this->cmd = 'profile/' . substr($this->cmd, 1);
247 // Diaspora style profile url
248 if (substr($this->cmd, 0, 2) === 'u/') {
249 $this->cmd = 'profile/' . substr($this->cmd, 2);
253 * Break the URL path into C style argc/argv style arguments for our
254 * modules. Given "http://example.com/module/arg1/arg2", $this->argc
255 * will be 3 (integer) and $this->argv will contain:
261 * There will always be one argument. If provided a naked domain
262 * URL, $this->argv[0] is set to "home".
265 $this->argv = explode('/', $this->cmd);
266 $this->argc = count($this->argv);
267 if ((array_key_exists('0', $this->argv)) && strlen($this->argv[0])) {
268 $this->module = str_replace('.', '_', $this->argv[0]);
269 $this->module = str_replace('-', '_', $this->module);
272 $this->argv = ['home'];
273 $this->module = 'home';
276 // See if there is any page number information, and initialise pagination
277 $this->pager['page'] = ((x($_GET, 'page') && intval($_GET['page']) > 0) ? intval($_GET['page']) : 1);
278 $this->pager['itemspage'] = 50;
279 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
281 if ($this->pager['start'] < 0) {
282 $this->pager['start'] = 0;
284 $this->pager['total'] = 0;
286 // Detect mobile devices
287 $mobile_detect = new MobileDetect();
288 $this->is_mobile = $mobile_detect->isMobile();
289 $this->is_tablet = $mobile_detect->isTablet();
292 $this->is_friendica_app = isset($_SERVER['HTTP_USER_AGENT']) && $_SERVER['HTTP_USER_AGENT'] == 'Apache-HttpClient/UNAVAILABLE (java 1.4)';
294 // Register template engines
295 $this->register_template_engine('Friendica\Render\FriendicaSmartyEngine');
298 private function loadConfigFiles()
300 $this->loadConfigFile($this->basepath . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'defaults.ini.php');
302 // Legacy .htconfig.php support
303 if (file_exists($this->basepath . DIRECTORY_SEPARATOR . '.htpreconfig.php')) {
305 include $this->basepath . DIRECTORY_SEPARATOR . '.htpreconfig.php';
308 // Legacy .htconfig.php support
309 if (file_exists($this->basepath . DIRECTORY_SEPARATOR . '.htconfig.php')) {
312 include $this->basepath . DIRECTORY_SEPARATOR . '.htconfig.php';
313 unset($db_host, $db_user, $db_pass, $db_data);
315 if (isset($default_timezone)) {
316 $this->setConfigValue('system', 'default_timezone', $default_timezone);
317 unset($default_timezone);
320 if (isset($pidfile)) {
321 $this->setConfigValue('system', 'pidfile', $pidfile);
326 if (file_exists($this->basepath . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'local.ini.php')) {
327 $this->loadConfigFile($this->basepath . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'local.ini.php');
331 public function loadConfigFile($filepath)
333 if (!file_exists($filepath)) {
334 throw new Exception('Error parsing non-existent config file ' . $filepath);
337 $contents = include($filepath);
339 $config = parse_ini_string($contents, true, INI_SCANNER_TYPED);
341 if ($config === false) {
342 throw new Exception('Error parsing config file ' . $filepath);
345 foreach($config as $category => $values) {
346 foreach($values as $key => $value) {
347 $this->setConfigValue($category, $key, $value);
352 private function loadAddonConfig()
354 // Loads addons default config
355 Core\Addon::callHooks('load_config');
357 // Load the local config file again in case there are overwritten addon config
358 if (file_exists($this->basepath . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'local.ini.php')) {
359 $this->loadConfigFile($this->basepath . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'local.ini.php');
363 private function loadDefaultTimezone()
365 if ($this->getConfigValue('system', 'default_timezone')) {
366 $this->timezone = $this->getConfigValue('system', 'default_timezone');
368 global $default_timezone;
369 $this->timezone = !empty($default_timezone) ? $default_timezone : 'UTC';
372 if ($this->timezone) {
373 date_default_timezone_set($this->timezone);
378 * Figure out if we are running at the top of a domain
379 * or in a sub-directory and adjust accordingly
381 private function determineUrlPath()
383 $this->urlpath = $this->getConfigValue('system', 'urlpath');
385 /* SCRIPT_URL gives /path/to/friendica/module/parameter
386 * QUERY_STRING gives pagename=module/parameter
388 * To get /path/to/friendica we perform dirname() for as many levels as there are slashes in the QUERY_STRING
390 if (!empty($_SERVER['SCRIPT_URL']) && !empty($_SERVER['QUERY_STRING'])) {
391 $path = trim(dirname($_SERVER['SCRIPT_URL'], substr_count(trim($_SERVER['QUERY_STRING'], '/'), '/') + 1), '/');
393 if ($path && $path != $this->urlpath) {
394 $this->urlpath = $path;
399 private function determineMode()
401 $this->mode = App::MODE_INSTALL;
403 // Missing DB connection
404 if (!\dba::connected()) {
408 // Working DB connection, missing tables
409 if (\dba::fetch_first("SHOW TABLES LIKE 'config'") === false) {
413 // Maintenance mode check
414 if (Config::get('system', 'maintenance')) {
415 $this->mode = App::MODE_MAINTENANCE;
417 $this->mode = App::MODE_NORMAL;
421 public function loadDatabase()
423 if (\dba::connected()) {
427 $db_host = $this->getConfigValue('database', 'hostname');
428 $db_user = $this->getConfigValue('database', 'username');
429 $db_pass = $this->getConfigValue('database', 'password');
430 $db_data = $this->getConfigValue('database', 'database');
431 $charset = $this->getConfigValue('database', 'charset');
433 // Use environment variables for mysql if they are set beforehand
434 if (!empty(getenv('MYSQL_HOST'))
435 && !empty(getenv('MYSQL_PORT'))
436 && (!empty(getenv('MYSQL_USERNAME')) || !empty(getenv('MYSQL_USER')))
437 && !empty(getenv('MYSQL_PASSWORD'))
438 && !empty(getenv('MYSQL_DATABASE')))
440 $db_host = getenv('MYSQL_HOST') . ':' . getenv('MYSQL_PORT');
442 if (!empty(getenv('MYSQL_USERNAME'))) {
443 $db_user = getenv('MYSQL_USERNAME');
444 } elseif (!empty(getenv('MYSQL_USER'))) {
445 $db_user = getenv('MYSQL_USER');
448 $db_pass = getenv('MYSQL_PASSWORD');
449 $db_data = getenv('MYSQL_DATABASE');
450 }elseif (file_exists($this->basepath . DIRECTORY_SEPARATOR . '.htconfig.php')) {
451 $a = new \stdClass();
452 include $this->basepath . DIRECTORY_SEPARATOR . '.htconfig.php';
453 $charset = isset($a->config["system"]["db_charset"]) ? $a->config["system"]["db_charset"] : $charset;
458 $stamp1 = microtime(true);
460 \dba::connect($db_host, $db_user, $db_pass, $db_data, $charset);
461 unset($db_host, $db_user, $db_pass, $db_data, $charset);
463 $this->save_timestamp($stamp1, "network");
467 * @brief Returns the base filesystem path of the App
469 * It first checks for the internal variable, then for DOCUMENT_ROOT and
474 public function get_basepath()
476 $basepath = $this->basepath;
479 $basepath = Config::get('system', 'basepath');
482 if (!$basepath && x($_SERVER, 'DOCUMENT_ROOT')) {
483 $basepath = $_SERVER['DOCUMENT_ROOT'];
486 if (!$basepath && x($_SERVER, 'PWD')) {
487 $basepath = $_SERVER['PWD'];
490 return self::realpath($basepath);
494 * @brief Returns a normalized file path
496 * This is a wrapper for the "realpath" function.
497 * That function cannot detect the real path when some folders aren't readable.
498 * Since this could happen with some hosters we need to handle this.
500 * @param string $path The path that is about to be normalized
501 * @return string normalized path - when possible
503 public static function realpath($path)
505 $normalized = realpath($path);
507 if (!is_bool($normalized)) {
514 public function get_scheme()
516 return $this->scheme;
520 * @brief Retrieves the Friendica instance base URL
522 * This function assembles the base URL from multiple parts:
523 * - Protocol is determined either by the request or a combination of
524 * system.ssl_policy and the $ssl parameter.
525 * - Host name is determined either by system.hostname or inferred from request
526 * - Path is inferred from SCRIPT_NAME
528 * Note: $ssl parameter value doesn't directly correlate with the resulting protocol
530 * @param bool $ssl Whether to append http or https under SSL_POLICY_SELFSIGN
531 * @return string Friendica server base URL
533 public function get_baseurl($ssl = false)
535 $scheme = $this->scheme;
537 if (Config::get('system', 'ssl_policy') == SSL_POLICY_FULL) {
541 // Basically, we have $ssl = true on any links which can only be seen by a logged in user
542 // (and also the login link). Anything seen by an outsider will have it turned off.
544 if (Config::get('system', 'ssl_policy') == SSL_POLICY_SELFSIGN) {
552 if (Config::get('config', 'hostname') != '') {
553 $this->hostname = Config::get('config', 'hostname');
556 return $scheme . '://' . $this->hostname . (!empty($this->urlpath) ? '/' . $this->urlpath : '' );
560 * @brief Initializes the baseurl components
562 * Clears the baseurl cache to prevent inconsistencies
566 public function set_baseurl($url)
568 $parsed = @parse_url($url);
572 if (!empty($parsed['scheme'])) {
573 $this->scheme = $parsed['scheme'];
576 if (!empty($parsed['host'])) {
577 $hostname = $parsed['host'];
580 if (x($parsed, 'port')) {
581 $hostname .= ':' . $parsed['port'];
583 if (x($parsed, 'path')) {
584 $this->urlpath = trim($parsed['path'], '\\/');
587 if (file_exists($this->basepath . DIRECTORY_SEPARATOR . '.htpreconfig.php')) {
588 include $this->basepath . DIRECTORY_SEPARATOR . '.htpreconfig.php';
591 if (Config::get('config', 'hostname') != '') {
592 $this->hostname = Config::get('config', 'hostname');
595 if (!isset($this->hostname) || ($this->hostname == '')) {
596 $this->hostname = $hostname;
601 public function get_hostname()
603 if (Config::get('config', 'hostname') != '') {
604 $this->hostname = Config::get('config', 'hostname');
607 return $this->hostname;
610 public function get_path()
612 return $this->urlpath;
615 public function set_pager_total($n)
617 $this->pager['total'] = intval($n);
620 public function set_pager_itemspage($n)
622 $this->pager['itemspage'] = ((intval($n) > 0) ? intval($n) : 0);
623 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
626 public function set_pager_page($n)
628 $this->pager['page'] = $n;
629 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
632 public function init_pagehead()
634 $interval = ((local_user()) ? PConfig::get(local_user(), 'system', 'update_interval') : 40000);
636 // If the update is 'deactivated' set it to the highest integer number (~24 days)
638 $interval = 2147483647;
641 if ($interval < 10000) {
645 // compose the page title from the sitename and the
646 // current module called
647 if (!$this->module == '') {
648 $this->page['title'] = $this->config['sitename'] . ' (' . $this->module . ')';
650 $this->page['title'] = $this->config['sitename'];
653 /* put the head template at the beginning of page['htmlhead']
654 * since the code added by the modules frequently depends on it
657 if (!isset($this->page['htmlhead'])) {
658 $this->page['htmlhead'] = '';
661 // If we're using Smarty, then doing replace_macros() will replace
662 // any unrecognized variables with a blank string. Since we delay
663 // replacing $stylesheet until later, we need to replace it now
664 // with another variable name
665 if ($this->theme['template_engine'] === 'smarty3') {
666 $stylesheet = $this->get_template_ldelim('smarty3') . '$stylesheet' . $this->get_template_rdelim('smarty3');
668 $stylesheet = '$stylesheet';
671 $shortcut_icon = Config::get('system', 'shortcut_icon');
672 if ($shortcut_icon == '') {
673 $shortcut_icon = 'images/friendica-32.png';
676 $touch_icon = Config::get('system', 'touch_icon');
677 if ($touch_icon == '') {
678 $touch_icon = 'images/friendica-128.png';
681 // get data wich is needed for infinite scroll on the network page
682 $invinite_scroll = infinite_scroll_data($this->module);
684 $tpl = get_markup_template('head.tpl');
685 $this->page['htmlhead'] = replace_macros($tpl, [
686 '$baseurl' => $this->get_baseurl(),
687 '$local_user' => local_user(),
688 '$generator' => 'Friendica' . ' ' . FRIENDICA_VERSION,
689 '$delitem' => L10n::t('Delete this item?'),
690 '$showmore' => L10n::t('show more'),
691 '$showfewer' => L10n::t('show fewer'),
692 '$update_interval' => $interval,
693 '$shortcut_icon' => $shortcut_icon,
694 '$touch_icon' => $touch_icon,
695 '$stylesheet' => $stylesheet,
696 '$infinite_scroll' => $invinite_scroll,
697 '$block_public' => intval(Config::get('system', 'block_public')),
698 ]) . $this->page['htmlhead'];
701 public function init_page_end()
703 if (!isset($this->page['end'])) {
704 $this->page['end'] = '';
706 $tpl = get_markup_template('end.tpl');
707 $this->page['end'] = replace_macros($tpl, [
708 '$baseurl' => $this->get_baseurl()
709 ]) . $this->page['end'];
712 public function set_curl_code($code)
714 $this->curl_code = $code;
717 public function get_curl_code()
719 return $this->curl_code;
722 public function set_curl_content_type($content_type)
724 $this->curl_content_type = $content_type;
727 public function get_curl_content_type()
729 return $this->curl_content_type;
732 public function set_curl_headers($headers)
734 $this->curl_headers = $headers;
737 public function get_curl_headers()
739 return $this->curl_headers;
743 * @brief Removes the base url from an url. This avoids some mixed content problems.
745 * @param string $orig_url
747 * @return string The cleaned url
749 public function remove_baseurl($orig_url)
751 // Remove the hostname from the url if it is an internal link
752 $nurl = normalise_link($orig_url);
753 $base = normalise_link($this->get_baseurl());
754 $url = str_replace($base . '/', '', $nurl);
756 // if it is an external link return the orignal value
757 if ($url == normalise_link($orig_url)) {
765 * @brief Register template engine class
767 * @param string $class
769 private function register_template_engine($class)
771 $v = get_class_vars($class);
774 $this->template_engines[$name] = $class;
776 echo "template engine <tt>$class</tt> cannot be registered without a name.\n";
782 * @brief Return template engine instance.
784 * If $name is not defined, return engine defined by theme,
787 * @return object Template Engine instance
789 public function template_engine()
791 $template_engine = 'smarty3';
792 if (x($this->theme, 'template_engine')) {
793 $template_engine = $this->theme['template_engine'];
796 if (isset($this->template_engines[$template_engine])) {
797 if (isset($this->template_engine_instance[$template_engine])) {
798 return $this->template_engine_instance[$template_engine];
800 $class = $this->template_engines[$template_engine];
802 $this->template_engine_instance[$template_engine] = $obj;
807 echo "template engine <tt>$template_engine</tt> is not registered!\n";
812 * @brief Returns the active template engine.
816 public function get_template_engine()
818 return $this->theme['template_engine'];
821 public function set_template_engine($engine = 'smarty3')
823 $this->theme['template_engine'] = $engine;
826 public function get_template_ldelim($engine = 'smarty3')
828 return $this->ldelim[$engine];
831 public function get_template_rdelim($engine = 'smarty3')
833 return $this->rdelim[$engine];
836 public function save_timestamp($stamp, $value)
838 if (!isset($this->config['system']['profiler']) || !$this->config['system']['profiler']) {
842 $duration = (float) (microtime(true) - $stamp);
844 if (!isset($this->performance[$value])) {
845 // Prevent ugly E_NOTICE
846 $this->performance[$value] = 0;
849 $this->performance[$value] += (float) $duration;
850 $this->performance['marktime'] += (float) $duration;
852 $callstack = System::callstack();
854 if (!isset($this->callstack[$value][$callstack])) {
855 // Prevent ugly E_NOTICE
856 $this->callstack[$value][$callstack] = 0;
859 $this->callstack[$value][$callstack] += (float) $duration;
862 public function get_useragent()
865 FRIENDICA_PLATFORM . " '" .
866 FRIENDICA_CODENAME . "' " .
867 FRIENDICA_VERSION . '-' .
868 DB_UPDATE_VERSION . '; ' .
869 $this->get_baseurl();
872 public function is_friendica_app()
874 return $this->is_friendica_app;
878 * @brief Checks if the site is called via a backend process
880 * This isn't a perfect solution. But we need this check very early.
881 * So we cannot wait until the modules are loaded.
883 * @return bool Is it a known backend?
885 public function is_backend()
909 // Check if current module is in backend or backend flag is set
910 return (in_array($this->module, $backends) || $this->backend);
914 * @brief Checks if the maximum number of database processes is reached
916 * @return bool Is the limit reached?
918 public function max_processes_reached()
920 // Deactivated, needs more investigating if this check really makes sense
924 * Commented out to suppress static analyzer issues
926 if ($this->is_backend()) {
927 $process = 'backend';
928 $max_processes = Config::get('system', 'max_processes_backend');
929 if (intval($max_processes) == 0) {
933 $process = 'frontend';
934 $max_processes = Config::get('system', 'max_processes_frontend');
935 if (intval($max_processes) == 0) {
940 $processlist = DBM::processlist();
941 if ($processlist['list'] != '') {
942 logger('Processcheck: Processes: ' . $processlist['amount'] . ' - Processlist: ' . $processlist['list'], LOGGER_DEBUG);
944 if ($processlist['amount'] > $max_processes) {
945 logger('Processcheck: Maximum number of processes for ' . $process . ' tasks (' . $max_processes . ') reached.', LOGGER_DEBUG);
954 * @brief Checks if the minimal memory is reached
956 * @return bool Is the memory limit reached?
958 public function min_memory_reached()
960 $min_memory = Config::get('system', 'min_memory', 0);
961 if ($min_memory == 0) {
965 if (!is_readable('/proc/meminfo')) {
969 $memdata = explode("\n", file_get_contents('/proc/meminfo'));
972 foreach ($memdata as $line) {
973 list($key, $val) = explode(':', $line);
974 $meminfo[$key] = (int) trim(str_replace('kB', '', $val));
975 $meminfo[$key] = (int) ($meminfo[$key] / 1024);
978 if (!isset($meminfo['MemAvailable']) || !isset($meminfo['MemFree'])) {
982 $free = $meminfo['MemAvailable'] + $meminfo['MemFree'];
984 $reached = ($free < $min_memory);
987 logger('Minimal memory reached: ' . $free . '/' . $meminfo['MemTotal'] . ' - limit ' . $min_memory, LOGGER_DEBUG);
994 * @brief Checks if the maximum load is reached
996 * @return bool Is the load reached?
998 public function maxload_reached()
1000 if ($this->is_backend()) {
1001 $process = 'backend';
1002 $maxsysload = intval(Config::get('system', 'maxloadavg'));
1003 if ($maxsysload < 1) {
1007 $process = 'frontend';
1008 $maxsysload = intval(Config::get('system', 'maxloadavg_frontend'));
1009 if ($maxsysload < 1) {
1014 $load = current_load();
1016 if (intval($load) > $maxsysload) {
1017 logger('system: load ' . $load . ' for ' . $process . ' tasks (' . $maxsysload . ') too high.');
1024 public function proc_run($args)
1026 if (!function_exists('proc_open')) {
1030 array_unshift($args, $this->getConfigValue('config', 'php_path', 'php'));
1032 for ($x = 0; $x < count($args); $x ++) {
1033 $args[$x] = escapeshellarg($args[$x]);
1036 $cmdline = implode(' ', $args);
1038 if ($this->min_memory_reached()) {
1042 if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
1043 $resource = proc_open('cmd /c start /b ' . $cmdline, [], $foo, $this->get_basepath());
1045 $resource = proc_open($cmdline . ' &', [], $foo, $this->get_basepath());
1047 if (!is_resource($resource)) {
1048 logger('We got no resource for command ' . $cmdline, LOGGER_DEBUG);
1051 proc_close($resource);
1055 * @brief Returns the system user that is executing the script
1057 * This mostly returns something like "www-data".
1059 * @return string system username
1061 private static function systemuser()
1063 if (!function_exists('posix_getpwuid') || !function_exists('posix_geteuid')) {
1067 $processUser = posix_getpwuid(posix_geteuid());
1068 return $processUser['name'];
1072 * @brief Checks if a given directory is usable for the system
1074 * @return boolean the directory is usable
1076 public static function directory_usable($directory, $check_writable = true)
1078 if ($directory == '') {
1079 logger('Directory is empty. This shouldn\'t happen.', LOGGER_DEBUG);
1083 if (!file_exists($directory)) {
1084 logger('Path "' . $directory . '" does not exist for user ' . self::systemuser(), LOGGER_DEBUG);
1088 if (is_file($directory)) {
1089 logger('Path "' . $directory . '" is a file for user ' . self::systemuser(), LOGGER_DEBUG);
1093 if (!is_dir($directory)) {
1094 logger('Path "' . $directory . '" is not a directory for user ' . self::systemuser(), LOGGER_DEBUG);
1098 if ($check_writable && !is_writable($directory)) {
1099 logger('Path "' . $directory . '" is not writable for user ' . self::systemuser(), LOGGER_DEBUG);
1107 * @param string $cat Config category
1108 * @param string $k Config key
1109 * @param mixed $default Default value if it isn't set
1111 public function getConfigValue($cat, $k, $default = null)
1115 if ($cat === 'config') {
1116 if (isset($this->config[$k])) {
1117 $return = $this->config[$k];
1120 if (isset($this->config[$cat][$k])) {
1121 $return = $this->config[$cat][$k];
1129 * Sets a value in the config cache. Accepts raw output from the config table
1131 * @param string $cat Config category
1132 * @param string $k Config key
1133 * @param mixed $v Value to set
1135 public function setConfigValue($cat, $k, $v)
1137 // Only arrays are serialized in database, so we have to unserialize sparingly
1138 $value = is_string($v) && preg_match("|^a:[0-9]+:{.*}$|s", $v) ? unserialize($v) : $v;
1140 if ($cat === 'config') {
1141 $this->config[$k] = $value;
1143 if (!isset($this->config[$cat])) {
1144 $this->config[$cat] = [];
1147 $this->config[$cat][$k] = $value;
1152 * Deletes a value from the config cache
1154 * @param string $cat Config category
1155 * @param string $k Config key
1157 public function deleteConfigValue($cat, $k)
1159 if ($cat === 'config') {
1160 if (isset($this->config[$k])) {
1161 unset($this->config[$k]);
1164 if (isset($this->config[$cat][$k])) {
1165 unset($this->config[$cat][$k]);
1172 * Retrieves a value from the user config cache
1174 * @param int $uid User Id
1175 * @param string $cat Config category
1176 * @param string $k Config key
1177 * @param mixed $default Default value if key isn't set
1179 public function getPConfigValue($uid, $cat, $k, $default = null)
1183 if (isset($this->config[$uid][$cat][$k])) {
1184 $return = $this->config[$uid][$cat][$k];
1191 * Sets a value in the user config cache
1193 * Accepts raw output from the pconfig table
1195 * @param int $uid User Id
1196 * @param string $cat Config category
1197 * @param string $k Config key
1198 * @param mixed $v Value to set
1200 public function setPConfigValue($uid, $cat, $k, $v)
1202 // Only arrays are serialized in database, so we have to unserialize sparingly
1203 $value = is_string($v) && preg_match("|^a:[0-9]+:{.*}$|s", $v) ? unserialize($v) : $v;
1205 if (!isset($this->config[$uid])) {
1206 $this->config[$uid] = [];
1209 if (!isset($this->config[$uid][$cat])) {
1210 $this->config[$uid][$cat] = [];
1213 $this->config[$uid][$cat][$k] = $value;
1217 * Deletes a value from the user config cache
1219 * @param int $uid User Id
1220 * @param string $cat Config category
1221 * @param string $k Config key
1223 public function deletePConfigValue($uid, $cat, $k)
1225 if (isset($this->config[$uid][$cat][$k])) {
1226 unset($this->config[$uid][$cat][$k]);
1231 * Generates the site's default sender email address
1235 public function getSenderEmailAddress()
1237 $sender_email = Config::get('config', 'sender_email');
1238 if (empty($sender_email)) {
1239 $hostname = $this->get_hostname();
1240 if (strpos($hostname, ':')) {
1241 $hostname = substr($hostname, 0, strpos($hostname, ':'));
1244 $sender_email = 'noreply@' . $hostname;
1247 return $sender_email;
1251 * Returns the current theme name.
1255 public function getCurrentTheme()
1257 if ($this->mode == App::MODE_INSTALL) {
1261 //// @TODO Compute the current theme only once (this behavior has
1262 /// already been implemented, but it didn't work well -
1263 /// https://github.com/friendica/friendica/issues/5092)
1264 $this->computeCurrentTheme();
1266 return $this->current_theme;
1270 * Computes the current theme name based on the node settings, the user settings and the device type
1274 private function computeCurrentTheme()
1276 $system_theme = Config::get('system', 'theme');
1277 if (!$system_theme) {
1278 throw new Exception(L10n::t('No system theme config value set.'));
1282 $this->current_theme = $system_theme;
1284 $allowed_themes = explode(',', Config::get('system', 'allowed_themes', $system_theme));
1287 // Find the theme that belongs to the user whose stuff we are looking at
1288 if ($this->profile_uid && ($this->profile_uid != local_user())) {
1289 // Allow folks to override user themes and always use their own on their own site.
1290 // This works only if the user is on the same server
1291 $user = dba::selectFirst('user', ['theme'], ['uid' => $this->profile_uid]);
1292 if (DBM::is_result($user) && !PConfig::get(local_user(), 'system', 'always_my_theme')) {
1293 $page_theme = $user['theme'];
1297 if (!empty($_SESSION)) {
1298 $user_theme = defaults($_SESSION, 'theme', $system_theme);
1300 $user_theme = $system_theme;
1303 // Specific mobile theme override
1304 if (($this->is_mobile || $this->is_tablet) && defaults($_SESSION, 'show-mobile', true)) {
1305 $system_mobile_theme = Config::get('system', 'mobile-theme');
1306 $user_mobile_theme = defaults($_SESSION, 'mobile-theme', $system_mobile_theme);
1308 // --- means same mobile theme as desktop
1309 if (!empty($user_mobile_theme) && $user_mobile_theme !== '---') {
1310 $user_theme = $user_mobile_theme;
1315 $theme_name = $page_theme;
1317 $theme_name = $user_theme;
1321 && in_array($theme_name, $allowed_themes)
1322 && (file_exists('view/theme/' . $theme_name . '/style.css')
1323 || file_exists('view/theme/' . $theme_name . '/style.php'))
1325 $this->current_theme = $theme_name;
1330 * @brief Return full URL to theme which is currently in effect.
1332 * Provide a sane default if nothing is chosen or the specified theme does not exist.
1336 public function getCurrentThemeStylesheetPath()
1338 return Core\Theme::getStylesheetPath($this->getCurrentTheme());