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 if ($this->mode === self::MODE_NORMAL) {
155 Core\Addon::loadHooks();
157 $this->loadAddonConfig();
160 $this->loadDefaultTimezone();
162 $this->performance['start'] = microtime(true);
163 $this->performance['database'] = 0;
164 $this->performance['database_write'] = 0;
165 $this->performance['cache'] = 0;
166 $this->performance['cache_write'] = 0;
167 $this->performance['network'] = 0;
168 $this->performance['file'] = 0;
169 $this->performance['rendering'] = 0;
170 $this->performance['parser'] = 0;
171 $this->performance['marktime'] = 0;
172 $this->performance['markstart'] = microtime(true);
174 $this->callstack['database'] = [];
175 $this->callstack['database_write'] = [];
176 $this->callstack['cache'] = [];
177 $this->callstack['cache_write'] = [];
178 $this->callstack['network'] = [];
179 $this->callstack['file'] = [];
180 $this->callstack['rendering'] = [];
181 $this->callstack['parser'] = [];
197 $this->process_id = System::processID('log');
201 // This has to be quite large to deal with embedded private photos
202 ini_set('pcre.backtrack_limit', 500000);
204 $this->scheme = 'http';
206 if ((x($_SERVER, 'HTTPS') && $_SERVER['HTTPS']) ||
207 (x($_SERVER, 'HTTP_FORWARDED') && preg_match('/proto=https/', $_SERVER['HTTP_FORWARDED'])) ||
208 (x($_SERVER, 'HTTP_X_FORWARDED_PROTO') && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') ||
209 (x($_SERVER, 'HTTP_X_FORWARDED_SSL') && $_SERVER['HTTP_X_FORWARDED_SSL'] == 'on') ||
210 (x($_SERVER, 'FRONT_END_HTTPS') && $_SERVER['FRONT_END_HTTPS'] == 'on') ||
211 (x($_SERVER, 'SERVER_PORT') && (intval($_SERVER['SERVER_PORT']) == 443)) // XXX: reasonable assumption, but isn't this hardcoding too much?
213 $this->scheme = 'https';
216 if (x($_SERVER, 'SERVER_NAME')) {
217 $this->hostname = $_SERVER['SERVER_NAME'];
219 if (x($_SERVER, 'SERVER_PORT') && $_SERVER['SERVER_PORT'] != 80 && $_SERVER['SERVER_PORT'] != 443) {
220 $this->hostname .= ':' . $_SERVER['SERVER_PORT'];
225 get_include_path() . PATH_SEPARATOR
226 . $this->basepath . DIRECTORY_SEPARATOR . 'include' . PATH_SEPARATOR
227 . $this->basepath . DIRECTORY_SEPARATOR . 'library' . PATH_SEPARATOR
230 if ((x($_SERVER, 'QUERY_STRING')) && substr($_SERVER['QUERY_STRING'], 0, 9) === 'pagename=') {
231 $this->query_string = substr($_SERVER['QUERY_STRING'], 9);
232 } elseif ((x($_SERVER, 'QUERY_STRING')) && substr($_SERVER['QUERY_STRING'], 0, 2) === 'q=') {
233 $this->query_string = substr($_SERVER['QUERY_STRING'], 2);
236 // removing trailing / - maybe a nginx problem
237 $this->query_string = ltrim($this->query_string, '/');
239 if (!empty($_GET['pagename'])) {
240 $this->cmd = trim($_GET['pagename'], '/\\');
241 } elseif (!empty($_GET['q'])) {
242 $this->cmd = trim($_GET['q'], '/\\');
246 $this->query_string = str_replace($this->cmd . '&', $this->cmd . '?', $this->query_string);
248 // unix style "homedir"
249 if (substr($this->cmd, 0, 1) === '~') {
250 $this->cmd = 'profile/' . substr($this->cmd, 1);
253 // Diaspora style profile url
254 if (substr($this->cmd, 0, 2) === 'u/') {
255 $this->cmd = 'profile/' . substr($this->cmd, 2);
259 * Break the URL path into C style argc/argv style arguments for our
260 * modules. Given "http://example.com/module/arg1/arg2", $this->argc
261 * will be 3 (integer) and $this->argv will contain:
267 * There will always be one argument. If provided a naked domain
268 * URL, $this->argv[0] is set to "home".
271 $this->argv = explode('/', $this->cmd);
272 $this->argc = count($this->argv);
273 if ((array_key_exists('0', $this->argv)) && strlen($this->argv[0])) {
274 $this->module = str_replace('.', '_', $this->argv[0]);
275 $this->module = str_replace('-', '_', $this->module);
278 $this->argv = ['home'];
279 $this->module = 'home';
282 // See if there is any page number information, and initialise pagination
283 $this->pager['page'] = ((x($_GET, 'page') && intval($_GET['page']) > 0) ? intval($_GET['page']) : 1);
284 $this->pager['itemspage'] = 50;
285 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
287 if ($this->pager['start'] < 0) {
288 $this->pager['start'] = 0;
290 $this->pager['total'] = 0;
292 // Detect mobile devices
293 $mobile_detect = new MobileDetect();
294 $this->is_mobile = $mobile_detect->isMobile();
295 $this->is_tablet = $mobile_detect->isTablet();
298 $this->is_friendica_app = isset($_SERVER['HTTP_USER_AGENT']) && $_SERVER['HTTP_USER_AGENT'] == 'Apache-HttpClient/UNAVAILABLE (java 1.4)';
300 // Register template engines
301 $this->register_template_engine('Friendica\Render\FriendicaSmartyEngine');
305 * Load the configuration files
307 * First loads the default value for all the configuration keys, then the legacy configuration files, then the
308 * expected local.ini.php
310 private function loadConfigFiles()
312 $this->loadConfigFile($this->basepath . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'defaults.ini.php');
314 // Legacy .htconfig.php support
315 if (file_exists($this->basepath . DIRECTORY_SEPARATOR . '.htpreconfig.php')) {
317 include $this->basepath . DIRECTORY_SEPARATOR . '.htpreconfig.php';
320 // Legacy .htconfig.php support
321 if (file_exists($this->basepath . DIRECTORY_SEPARATOR . '.htconfig.php')) {
324 include $this->basepath . DIRECTORY_SEPARATOR . '.htconfig.php';
325 unset($db_host, $db_user, $db_pass, $db_data);
327 if (isset($default_timezone)) {
328 $this->setConfigValue('system', 'default_timezone', $default_timezone);
329 unset($default_timezone);
332 if (isset($pidfile)) {
333 $this->setConfigValue('system', 'pidfile', $pidfile);
338 if (file_exists($this->basepath . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'local.ini.php')) {
339 $this->loadConfigFile($this->basepath . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'local.ini.php');
344 * Tries to load the specified configuration file into the App->config array.
345 * Overwrites previously set values.
347 * The config format is INI and the template for configuration files is the following:
349 * <?php return <<<INI
357 * @param type $filepath
360 public function loadConfigFile($filepath)
362 if (!file_exists($filepath)) {
363 throw new Exception('Error parsing non-existent config file ' . $filepath);
366 $contents = include($filepath);
368 $config = parse_ini_string($contents, true, INI_SCANNER_TYPED);
370 if ($config === false) {
371 throw new Exception('Error parsing config file ' . $filepath);
374 foreach($config as $category => $values) {
375 foreach($values as $key => $value) {
376 $this->setConfigValue($category, $key, $value);
382 * Loads addons configuration files
384 * First loads all activated addons default configuration throught the load_config hook, then load the local.ini.php
385 * again to overwrite potential local addon configuration.
387 private function loadAddonConfig()
389 // Loads addons default config
390 Core\Addon::callHooks('load_config');
392 // Load the local config file again in case there are overwritten addon config
393 if (file_exists($this->basepath . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'local.ini.php')) {
394 $this->loadConfigFile($this->basepath . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'local.ini.php');
399 * Loads the default timezone
401 * Include support for legacy $default_timezone
403 * @global string $default_timezone
405 private function loadDefaultTimezone()
407 if ($this->getConfigValue('system', 'default_timezone')) {
408 $this->timezone = $this->getConfigValue('system', 'default_timezone');
410 global $default_timezone;
411 $this->timezone = !empty($default_timezone) ? $default_timezone : 'UTC';
414 if ($this->timezone) {
415 date_default_timezone_set($this->timezone);
420 * Figure out if we are running at the top of a domain or in a sub-directory and adjust accordingly
422 private function determineUrlPath()
424 $this->urlpath = $this->getConfigValue('system', 'urlpath');
426 /* SCRIPT_URL gives /path/to/friendica/module/parameter
427 * QUERY_STRING gives pagename=module/parameter
429 * To get /path/to/friendica we perform dirname() for as many levels as there are slashes in the QUERY_STRING
431 if (!empty($_SERVER['SCRIPT_URL']) && !empty($_SERVER['QUERY_STRING'])) {
432 $path = trim(dirname($_SERVER['SCRIPT_URL'], substr_count(trim($_SERVER['QUERY_STRING'], '/'), '/') + 1), '/');
434 if ($path && $path != $this->urlpath) {
435 $this->urlpath = $path;
443 * - App::MODE_INSTALL : Either the database connection can't be established or the config table doesn't exist
444 * - App::MODE_MAINTENANCE: The maintenance mode has been set
445 * - App::MODE_NORMAL : Normal run with all features enabled
449 private function determineMode()
451 $this->mode = App::MODE_INSTALL;
453 // Missing local config files: MODE_INSTALL
454 if (!file_exists($this->basepath . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'local.ini.php')
455 && !file_exists($this->basepath . DIRECTORY_SEPARATOR . '.htconfig.php')) {
459 // Missing DB connection: ERROR
460 if (!\dba::connected()) {
461 System::unavailable();
464 // Working DB connection, missing tables: MODE_INSTALL
465 if (\dba::fetch_first("SHOW TABLES LIKE 'config'") === false) {
469 // Maintenance mode check
470 if (Config::get('system', 'maintenance')) {
471 $this->mode = App::MODE_MAINTENANCE;
473 $this->mode = App::MODE_NORMAL;
477 public function loadDatabase()
479 if (\dba::connected()) {
483 $db_host = $this->getConfigValue('database', 'hostname');
484 $db_user = $this->getConfigValue('database', 'username');
485 $db_pass = $this->getConfigValue('database', 'password');
486 $db_data = $this->getConfigValue('database', 'database');
487 $charset = $this->getConfigValue('database', 'charset');
489 // Use environment variables for mysql if they are set beforehand
490 if (!empty(getenv('MYSQL_HOST'))
491 && !empty(getenv('MYSQL_PORT'))
492 && (!empty(getenv('MYSQL_USERNAME')) || !empty(getenv('MYSQL_USER')))
493 && !empty(getenv('MYSQL_PASSWORD'))
494 && !empty(getenv('MYSQL_DATABASE')))
496 $db_host = getenv('MYSQL_HOST') . ':' . getenv('MYSQL_PORT');
498 if (!empty(getenv('MYSQL_USERNAME'))) {
499 $db_user = getenv('MYSQL_USERNAME');
500 } elseif (!empty(getenv('MYSQL_USER'))) {
501 $db_user = getenv('MYSQL_USER');
504 $db_pass = getenv('MYSQL_PASSWORD');
505 $db_data = getenv('MYSQL_DATABASE');
506 }elseif (file_exists($this->basepath . DIRECTORY_SEPARATOR . '.htconfig.php')) {
507 $a = new \stdClass();
508 include $this->basepath . DIRECTORY_SEPARATOR . '.htconfig.php';
509 $charset = isset($a->config["system"]["db_charset"]) ? $a->config["system"]["db_charset"] : $charset;
514 $stamp1 = microtime(true);
516 \dba::connect($db_host, $db_user, $db_pass, $db_data, $charset);
517 unset($db_host, $db_user, $db_pass, $db_data, $charset);
519 $this->save_timestamp($stamp1, "network");
523 * @brief Returns the base filesystem path of the App
525 * It first checks for the internal variable, then for DOCUMENT_ROOT and
530 public function get_basepath()
532 $basepath = $this->basepath;
535 $basepath = Config::get('system', 'basepath');
538 if (!$basepath && x($_SERVER, 'DOCUMENT_ROOT')) {
539 $basepath = $_SERVER['DOCUMENT_ROOT'];
542 if (!$basepath && x($_SERVER, 'PWD')) {
543 $basepath = $_SERVER['PWD'];
546 return self::realpath($basepath);
550 * @brief Returns a normalized file path
552 * This is a wrapper for the "realpath" function.
553 * That function cannot detect the real path when some folders aren't readable.
554 * Since this could happen with some hosters we need to handle this.
556 * @param string $path The path that is about to be normalized
557 * @return string normalized path - when possible
559 public static function realpath($path)
561 $normalized = realpath($path);
563 if (!is_bool($normalized)) {
570 public function get_scheme()
572 return $this->scheme;
576 * @brief Retrieves the Friendica instance base URL
578 * This function assembles the base URL from multiple parts:
579 * - Protocol is determined either by the request or a combination of
580 * system.ssl_policy and the $ssl parameter.
581 * - Host name is determined either by system.hostname or inferred from request
582 * - Path is inferred from SCRIPT_NAME
584 * Note: $ssl parameter value doesn't directly correlate with the resulting protocol
586 * @param bool $ssl Whether to append http or https under SSL_POLICY_SELFSIGN
587 * @return string Friendica server base URL
589 public function get_baseurl($ssl = false)
591 $scheme = $this->scheme;
593 if (Config::get('system', 'ssl_policy') == SSL_POLICY_FULL) {
597 // Basically, we have $ssl = true on any links which can only be seen by a logged in user
598 // (and also the login link). Anything seen by an outsider will have it turned off.
600 if (Config::get('system', 'ssl_policy') == SSL_POLICY_SELFSIGN) {
608 if (Config::get('config', 'hostname') != '') {
609 $this->hostname = Config::get('config', 'hostname');
612 return $scheme . '://' . $this->hostname . (!empty($this->urlpath) ? '/' . $this->urlpath : '' );
616 * @brief Initializes the baseurl components
618 * Clears the baseurl cache to prevent inconsistencies
622 public function set_baseurl($url)
624 $parsed = @parse_url($url);
628 if (!empty($parsed['scheme'])) {
629 $this->scheme = $parsed['scheme'];
632 if (!empty($parsed['host'])) {
633 $hostname = $parsed['host'];
636 if (x($parsed, 'port')) {
637 $hostname .= ':' . $parsed['port'];
639 if (x($parsed, 'path')) {
640 $this->urlpath = trim($parsed['path'], '\\/');
643 if (file_exists($this->basepath . DIRECTORY_SEPARATOR . '.htpreconfig.php')) {
644 include $this->basepath . DIRECTORY_SEPARATOR . '.htpreconfig.php';
647 if (Config::get('config', 'hostname') != '') {
648 $this->hostname = Config::get('config', 'hostname');
651 if (!isset($this->hostname) || ($this->hostname == '')) {
652 $this->hostname = $hostname;
657 public function get_hostname()
659 if (Config::get('config', 'hostname') != '') {
660 $this->hostname = Config::get('config', 'hostname');
663 return $this->hostname;
666 public function get_path()
668 return $this->urlpath;
671 public function set_pager_total($n)
673 $this->pager['total'] = intval($n);
676 public function set_pager_itemspage($n)
678 $this->pager['itemspage'] = ((intval($n) > 0) ? intval($n) : 0);
679 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
682 public function set_pager_page($n)
684 $this->pager['page'] = $n;
685 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
688 public function init_pagehead()
690 $interval = ((local_user()) ? PConfig::get(local_user(), 'system', 'update_interval') : 40000);
692 // If the update is 'deactivated' set it to the highest integer number (~24 days)
694 $interval = 2147483647;
697 if ($interval < 10000) {
701 // compose the page title from the sitename and the
702 // current module called
703 if (!$this->module == '') {
704 $this->page['title'] = $this->config['sitename'] . ' (' . $this->module . ')';
706 $this->page['title'] = $this->config['sitename'];
709 /* put the head template at the beginning of page['htmlhead']
710 * since the code added by the modules frequently depends on it
713 if (!isset($this->page['htmlhead'])) {
714 $this->page['htmlhead'] = '';
717 // If we're using Smarty, then doing replace_macros() will replace
718 // any unrecognized variables with a blank string. Since we delay
719 // replacing $stylesheet until later, we need to replace it now
720 // with another variable name
721 if ($this->theme['template_engine'] === 'smarty3') {
722 $stylesheet = $this->get_template_ldelim('smarty3') . '$stylesheet' . $this->get_template_rdelim('smarty3');
724 $stylesheet = '$stylesheet';
727 $shortcut_icon = Config::get('system', 'shortcut_icon');
728 if ($shortcut_icon == '') {
729 $shortcut_icon = 'images/friendica-32.png';
732 $touch_icon = Config::get('system', 'touch_icon');
733 if ($touch_icon == '') {
734 $touch_icon = 'images/friendica-128.png';
737 // get data wich is needed for infinite scroll on the network page
738 $invinite_scroll = infinite_scroll_data($this->module);
740 $tpl = get_markup_template('head.tpl');
741 $this->page['htmlhead'] = replace_macros($tpl, [
742 '$baseurl' => $this->get_baseurl(),
743 '$local_user' => local_user(),
744 '$generator' => 'Friendica' . ' ' . FRIENDICA_VERSION,
745 '$delitem' => L10n::t('Delete this item?'),
746 '$showmore' => L10n::t('show more'),
747 '$showfewer' => L10n::t('show fewer'),
748 '$update_interval' => $interval,
749 '$shortcut_icon' => $shortcut_icon,
750 '$touch_icon' => $touch_icon,
751 '$stylesheet' => $stylesheet,
752 '$infinite_scroll' => $invinite_scroll,
753 '$block_public' => intval(Config::get('system', 'block_public')),
754 ]) . $this->page['htmlhead'];
757 public function init_page_end()
759 if (!isset($this->page['end'])) {
760 $this->page['end'] = '';
762 $tpl = get_markup_template('end.tpl');
763 $this->page['end'] = replace_macros($tpl, [
764 '$baseurl' => $this->get_baseurl()
765 ]) . $this->page['end'];
768 public function set_curl_code($code)
770 $this->curl_code = $code;
773 public function get_curl_code()
775 return $this->curl_code;
778 public function set_curl_content_type($content_type)
780 $this->curl_content_type = $content_type;
783 public function get_curl_content_type()
785 return $this->curl_content_type;
788 public function set_curl_headers($headers)
790 $this->curl_headers = $headers;
793 public function get_curl_headers()
795 return $this->curl_headers;
799 * @brief Removes the base url from an url. This avoids some mixed content problems.
801 * @param string $orig_url
803 * @return string The cleaned url
805 public function remove_baseurl($orig_url)
807 // Remove the hostname from the url if it is an internal link
808 $nurl = normalise_link($orig_url);
809 $base = normalise_link($this->get_baseurl());
810 $url = str_replace($base . '/', '', $nurl);
812 // if it is an external link return the orignal value
813 if ($url == normalise_link($orig_url)) {
821 * @brief Register template engine class
823 * @param string $class
825 private function register_template_engine($class)
827 $v = get_class_vars($class);
830 $this->template_engines[$name] = $class;
832 echo "template engine <tt>$class</tt> cannot be registered without a name.\n";
838 * @brief Return template engine instance.
840 * If $name is not defined, return engine defined by theme,
843 * @return object Template Engine instance
845 public function template_engine()
847 $template_engine = 'smarty3';
848 if (x($this->theme, 'template_engine')) {
849 $template_engine = $this->theme['template_engine'];
852 if (isset($this->template_engines[$template_engine])) {
853 if (isset($this->template_engine_instance[$template_engine])) {
854 return $this->template_engine_instance[$template_engine];
856 $class = $this->template_engines[$template_engine];
858 $this->template_engine_instance[$template_engine] = $obj;
863 echo "template engine <tt>$template_engine</tt> is not registered!\n";
868 * @brief Returns the active template engine.
872 public function get_template_engine()
874 return $this->theme['template_engine'];
877 public function set_template_engine($engine = 'smarty3')
879 $this->theme['template_engine'] = $engine;
882 public function get_template_ldelim($engine = 'smarty3')
884 return $this->ldelim[$engine];
887 public function get_template_rdelim($engine = 'smarty3')
889 return $this->rdelim[$engine];
892 public function save_timestamp($stamp, $value)
894 if (!isset($this->config['system']['profiler']) || !$this->config['system']['profiler']) {
898 $duration = (float) (microtime(true) - $stamp);
900 if (!isset($this->performance[$value])) {
901 // Prevent ugly E_NOTICE
902 $this->performance[$value] = 0;
905 $this->performance[$value] += (float) $duration;
906 $this->performance['marktime'] += (float) $duration;
908 $callstack = System::callstack();
910 if (!isset($this->callstack[$value][$callstack])) {
911 // Prevent ugly E_NOTICE
912 $this->callstack[$value][$callstack] = 0;
915 $this->callstack[$value][$callstack] += (float) $duration;
918 public function get_useragent()
921 FRIENDICA_PLATFORM . " '" .
922 FRIENDICA_CODENAME . "' " .
923 FRIENDICA_VERSION . '-' .
924 DB_UPDATE_VERSION . '; ' .
925 $this->get_baseurl();
928 public function is_friendica_app()
930 return $this->is_friendica_app;
934 * @brief Checks if the site is called via a backend process
936 * This isn't a perfect solution. But we need this check very early.
937 * So we cannot wait until the modules are loaded.
939 * @return bool Is it a known backend?
941 public function is_backend()
965 // Check if current module is in backend or backend flag is set
966 return (in_array($this->module, $backends) || $this->backend);
970 * @brief Checks if the maximum number of database processes is reached
972 * @return bool Is the limit reached?
974 public function max_processes_reached()
976 // Deactivated, needs more investigating if this check really makes sense
980 * Commented out to suppress static analyzer issues
982 if ($this->is_backend()) {
983 $process = 'backend';
984 $max_processes = Config::get('system', 'max_processes_backend');
985 if (intval($max_processes) == 0) {
989 $process = 'frontend';
990 $max_processes = Config::get('system', 'max_processes_frontend');
991 if (intval($max_processes) == 0) {
996 $processlist = DBM::processlist();
997 if ($processlist['list'] != '') {
998 logger('Processcheck: Processes: ' . $processlist['amount'] . ' - Processlist: ' . $processlist['list'], LOGGER_DEBUG);
1000 if ($processlist['amount'] > $max_processes) {
1001 logger('Processcheck: Maximum number of processes for ' . $process . ' tasks (' . $max_processes . ') reached.', LOGGER_DEBUG);
1010 * @brief Checks if the minimal memory is reached
1012 * @return bool Is the memory limit reached?
1014 public function min_memory_reached()
1016 $min_memory = Config::get('system', 'min_memory', 0);
1017 if ($min_memory == 0) {
1021 if (!is_readable('/proc/meminfo')) {
1025 $memdata = explode("\n", file_get_contents('/proc/meminfo'));
1028 foreach ($memdata as $line) {
1029 list($key, $val) = explode(':', $line);
1030 $meminfo[$key] = (int) trim(str_replace('kB', '', $val));
1031 $meminfo[$key] = (int) ($meminfo[$key] / 1024);
1034 if (!isset($meminfo['MemAvailable']) || !isset($meminfo['MemFree'])) {
1038 $free = $meminfo['MemAvailable'] + $meminfo['MemFree'];
1040 $reached = ($free < $min_memory);
1043 logger('Minimal memory reached: ' . $free . '/' . $meminfo['MemTotal'] . ' - limit ' . $min_memory, LOGGER_DEBUG);
1050 * @brief Checks if the maximum load is reached
1052 * @return bool Is the load reached?
1054 public function maxload_reached()
1056 if ($this->is_backend()) {
1057 $process = 'backend';
1058 $maxsysload = intval(Config::get('system', 'maxloadavg'));
1059 if ($maxsysload < 1) {
1063 $process = 'frontend';
1064 $maxsysload = intval(Config::get('system', 'maxloadavg_frontend'));
1065 if ($maxsysload < 1) {
1070 $load = current_load();
1072 if (intval($load) > $maxsysload) {
1073 logger('system: load ' . $load . ' for ' . $process . ' tasks (' . $maxsysload . ') too high.');
1080 public function proc_run($args)
1082 if (!function_exists('proc_open')) {
1086 array_unshift($args, $this->getConfigValue('config', 'php_path', 'php'));
1088 for ($x = 0; $x < count($args); $x ++) {
1089 $args[$x] = escapeshellarg($args[$x]);
1092 $cmdline = implode(' ', $args);
1094 if ($this->min_memory_reached()) {
1098 if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
1099 $resource = proc_open('cmd /c start /b ' . $cmdline, [], $foo, $this->get_basepath());
1101 $resource = proc_open($cmdline . ' &', [], $foo, $this->get_basepath());
1103 if (!is_resource($resource)) {
1104 logger('We got no resource for command ' . $cmdline, LOGGER_DEBUG);
1107 proc_close($resource);
1111 * @brief Returns the system user that is executing the script
1113 * This mostly returns something like "www-data".
1115 * @return string system username
1117 private static function systemuser()
1119 if (!function_exists('posix_getpwuid') || !function_exists('posix_geteuid')) {
1123 $processUser = posix_getpwuid(posix_geteuid());
1124 return $processUser['name'];
1128 * @brief Checks if a given directory is usable for the system
1130 * @return boolean the directory is usable
1132 public static function directory_usable($directory, $check_writable = true)
1134 if ($directory == '') {
1135 logger('Directory is empty. This shouldn\'t happen.', LOGGER_DEBUG);
1139 if (!file_exists($directory)) {
1140 logger('Path "' . $directory . '" does not exist for user ' . self::systemuser(), LOGGER_DEBUG);
1144 if (is_file($directory)) {
1145 logger('Path "' . $directory . '" is a file for user ' . self::systemuser(), LOGGER_DEBUG);
1149 if (!is_dir($directory)) {
1150 logger('Path "' . $directory . '" is not a directory for user ' . self::systemuser(), LOGGER_DEBUG);
1154 if ($check_writable && !is_writable($directory)) {
1155 logger('Path "' . $directory . '" is not writable for user ' . self::systemuser(), LOGGER_DEBUG);
1163 * @param string $cat Config category
1164 * @param string $k Config key
1165 * @param mixed $default Default value if it isn't set
1167 public function getConfigValue($cat, $k, $default = null)
1171 if ($cat === 'config') {
1172 if (isset($this->config[$k])) {
1173 $return = $this->config[$k];
1176 if (isset($this->config[$cat][$k])) {
1177 $return = $this->config[$cat][$k];
1185 * Sets a value in the config cache. Accepts raw output from the config table
1187 * @param string $cat Config category
1188 * @param string $k Config key
1189 * @param mixed $v Value to set
1191 public function setConfigValue($cat, $k, $v)
1193 // Only arrays are serialized in database, so we have to unserialize sparingly
1194 $value = is_string($v) && preg_match("|^a:[0-9]+:{.*}$|s", $v) ? unserialize($v) : $v;
1196 if ($cat === 'config') {
1197 $this->config[$k] = $value;
1199 if (!isset($this->config[$cat])) {
1200 $this->config[$cat] = [];
1203 $this->config[$cat][$k] = $value;
1208 * Deletes a value from the config cache
1210 * @param string $cat Config category
1211 * @param string $k Config key
1213 public function deleteConfigValue($cat, $k)
1215 if ($cat === 'config') {
1216 if (isset($this->config[$k])) {
1217 unset($this->config[$k]);
1220 if (isset($this->config[$cat][$k])) {
1221 unset($this->config[$cat][$k]);
1228 * Retrieves a value from the user config cache
1230 * @param int $uid User Id
1231 * @param string $cat Config category
1232 * @param string $k Config key
1233 * @param mixed $default Default value if key isn't set
1235 public function getPConfigValue($uid, $cat, $k, $default = null)
1239 if (isset($this->config[$uid][$cat][$k])) {
1240 $return = $this->config[$uid][$cat][$k];
1247 * Sets a value in the user config cache
1249 * Accepts raw output from the pconfig table
1251 * @param int $uid User Id
1252 * @param string $cat Config category
1253 * @param string $k Config key
1254 * @param mixed $v Value to set
1256 public function setPConfigValue($uid, $cat, $k, $v)
1258 // Only arrays are serialized in database, so we have to unserialize sparingly
1259 $value = is_string($v) && preg_match("|^a:[0-9]+:{.*}$|s", $v) ? unserialize($v) : $v;
1261 if (!isset($this->config[$uid])) {
1262 $this->config[$uid] = [];
1265 if (!isset($this->config[$uid][$cat])) {
1266 $this->config[$uid][$cat] = [];
1269 $this->config[$uid][$cat][$k] = $value;
1273 * Deletes a value from the user config cache
1275 * @param int $uid User Id
1276 * @param string $cat Config category
1277 * @param string $k Config key
1279 public function deletePConfigValue($uid, $cat, $k)
1281 if (isset($this->config[$uid][$cat][$k])) {
1282 unset($this->config[$uid][$cat][$k]);
1287 * Generates the site's default sender email address
1291 public function getSenderEmailAddress()
1293 $sender_email = Config::get('config', 'sender_email');
1294 if (empty($sender_email)) {
1295 $hostname = $this->get_hostname();
1296 if (strpos($hostname, ':')) {
1297 $hostname = substr($hostname, 0, strpos($hostname, ':'));
1300 $sender_email = 'noreply@' . $hostname;
1303 return $sender_email;
1307 * Returns the current theme name.
1311 public function getCurrentTheme()
1313 if ($this->mode == App::MODE_INSTALL) {
1317 //// @TODO Compute the current theme only once (this behavior has
1318 /// already been implemented, but it didn't work well -
1319 /// https://github.com/friendica/friendica/issues/5092)
1320 $this->computeCurrentTheme();
1322 return $this->current_theme;
1326 * Computes the current theme name based on the node settings, the user settings and the device type
1330 private function computeCurrentTheme()
1332 $system_theme = Config::get('system', 'theme');
1333 if (!$system_theme) {
1334 throw new Exception(L10n::t('No system theme config value set.'));
1338 $this->current_theme = $system_theme;
1340 $allowed_themes = explode(',', Config::get('system', 'allowed_themes', $system_theme));
1343 // Find the theme that belongs to the user whose stuff we are looking at
1344 if ($this->profile_uid && ($this->profile_uid != local_user())) {
1345 // Allow folks to override user themes and always use their own on their own site.
1346 // This works only if the user is on the same server
1347 $user = dba::selectFirst('user', ['theme'], ['uid' => $this->profile_uid]);
1348 if (DBM::is_result($user) && !PConfig::get(local_user(), 'system', 'always_my_theme')) {
1349 $page_theme = $user['theme'];
1353 if (!empty($_SESSION)) {
1354 $user_theme = defaults($_SESSION, 'theme', $system_theme);
1356 $user_theme = $system_theme;
1359 // Specific mobile theme override
1360 if (($this->is_mobile || $this->is_tablet) && defaults($_SESSION, 'show-mobile', true)) {
1361 $system_mobile_theme = Config::get('system', 'mobile-theme');
1362 $user_mobile_theme = defaults($_SESSION, 'mobile-theme', $system_mobile_theme);
1364 // --- means same mobile theme as desktop
1365 if (!empty($user_mobile_theme) && $user_mobile_theme !== '---') {
1366 $user_theme = $user_mobile_theme;
1371 $theme_name = $page_theme;
1373 $theme_name = $user_theme;
1377 && in_array($theme_name, $allowed_themes)
1378 && (file_exists('view/theme/' . $theme_name . '/style.css')
1379 || file_exists('view/theme/' . $theme_name . '/style.php'))
1381 $this->current_theme = $theme_name;
1386 * @brief Return full URL to theme which is currently in effect.
1388 * Provide a sane default if nothing is chosen or the specified theme does not exist.
1392 public function getCurrentThemeStylesheetPath()
1394 return Core\Theme::getStylesheetPath($this->getCurrentTheme());