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 // The order of the following calls is important to ensure proper initialization
147 $this->loadConfigFiles();
149 $this->loadDatabase();
151 $this->determineMode();
153 $this->determineUrlPath();
155 if ($this->mode === self::MODE_NORMAL) {
156 Core\Addon::loadHooks();
158 $this->loadAddonConfig();
161 $this->loadDefaultTimezone();
163 $this->performance['start'] = microtime(true);
164 $this->performance['database'] = 0;
165 $this->performance['database_write'] = 0;
166 $this->performance['cache'] = 0;
167 $this->performance['cache_write'] = 0;
168 $this->performance['network'] = 0;
169 $this->performance['file'] = 0;
170 $this->performance['rendering'] = 0;
171 $this->performance['parser'] = 0;
172 $this->performance['marktime'] = 0;
173 $this->performance['markstart'] = microtime(true);
175 $this->callstack['database'] = [];
176 $this->callstack['database_write'] = [];
177 $this->callstack['cache'] = [];
178 $this->callstack['cache_write'] = [];
179 $this->callstack['network'] = [];
180 $this->callstack['file'] = [];
181 $this->callstack['rendering'] = [];
182 $this->callstack['parser'] = [];
198 $this->process_id = System::processID('log');
202 // This has to be quite large to deal with embedded private photos
203 ini_set('pcre.backtrack_limit', 500000);
205 $this->scheme = 'http';
207 if ((x($_SERVER, 'HTTPS') && $_SERVER['HTTPS']) ||
208 (x($_SERVER, 'HTTP_FORWARDED') && preg_match('/proto=https/', $_SERVER['HTTP_FORWARDED'])) ||
209 (x($_SERVER, 'HTTP_X_FORWARDED_PROTO') && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') ||
210 (x($_SERVER, 'HTTP_X_FORWARDED_SSL') && $_SERVER['HTTP_X_FORWARDED_SSL'] == 'on') ||
211 (x($_SERVER, 'FRONT_END_HTTPS') && $_SERVER['FRONT_END_HTTPS'] == 'on') ||
212 (x($_SERVER, 'SERVER_PORT') && (intval($_SERVER['SERVER_PORT']) == 443)) // XXX: reasonable assumption, but isn't this hardcoding too much?
214 $this->scheme = 'https';
217 if (x($_SERVER, 'SERVER_NAME')) {
218 $this->hostname = $_SERVER['SERVER_NAME'];
220 if (x($_SERVER, 'SERVER_PORT') && $_SERVER['SERVER_PORT'] != 80 && $_SERVER['SERVER_PORT'] != 443) {
221 $this->hostname .= ':' . $_SERVER['SERVER_PORT'];
226 get_include_path() . PATH_SEPARATOR
227 . $this->basepath . DIRECTORY_SEPARATOR . 'include' . PATH_SEPARATOR
228 . $this->basepath . DIRECTORY_SEPARATOR . 'library' . PATH_SEPARATOR
231 if ((x($_SERVER, 'QUERY_STRING')) && substr($_SERVER['QUERY_STRING'], 0, 9) === 'pagename=') {
232 $this->query_string = substr($_SERVER['QUERY_STRING'], 9);
233 } elseif ((x($_SERVER, 'QUERY_STRING')) && substr($_SERVER['QUERY_STRING'], 0, 2) === 'q=') {
234 $this->query_string = substr($_SERVER['QUERY_STRING'], 2);
237 // removing trailing / - maybe a nginx problem
238 $this->query_string = ltrim($this->query_string, '/');
240 if (!empty($_GET['pagename'])) {
241 $this->cmd = trim($_GET['pagename'], '/\\');
242 } elseif (!empty($_GET['q'])) {
243 $this->cmd = trim($_GET['q'], '/\\');
247 $this->query_string = str_replace($this->cmd . '&', $this->cmd . '?', $this->query_string);
249 // unix style "homedir"
250 if (substr($this->cmd, 0, 1) === '~') {
251 $this->cmd = 'profile/' . substr($this->cmd, 1);
254 // Diaspora style profile url
255 if (substr($this->cmd, 0, 2) === 'u/') {
256 $this->cmd = 'profile/' . substr($this->cmd, 2);
260 * Break the URL path into C style argc/argv style arguments for our
261 * modules. Given "http://example.com/module/arg1/arg2", $this->argc
262 * will be 3 (integer) and $this->argv will contain:
268 * There will always be one argument. If provided a naked domain
269 * URL, $this->argv[0] is set to "home".
272 $this->argv = explode('/', $this->cmd);
273 $this->argc = count($this->argv);
274 if ((array_key_exists('0', $this->argv)) && strlen($this->argv[0])) {
275 $this->module = str_replace('.', '_', $this->argv[0]);
276 $this->module = str_replace('-', '_', $this->module);
279 $this->argv = ['home'];
280 $this->module = 'home';
283 // See if there is any page number information, and initialise pagination
284 $this->pager['page'] = ((x($_GET, 'page') && intval($_GET['page']) > 0) ? intval($_GET['page']) : 1);
285 $this->pager['itemspage'] = 50;
286 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
288 if ($this->pager['start'] < 0) {
289 $this->pager['start'] = 0;
291 $this->pager['total'] = 0;
293 // Detect mobile devices
294 $mobile_detect = new MobileDetect();
295 $this->is_mobile = $mobile_detect->isMobile();
296 $this->is_tablet = $mobile_detect->isTablet();
299 $this->is_friendica_app = isset($_SERVER['HTTP_USER_AGENT']) && $_SERVER['HTTP_USER_AGENT'] == 'Apache-HttpClient/UNAVAILABLE (java 1.4)';
301 // Register template engines
302 $this->register_template_engine('Friendica\Render\FriendicaSmartyEngine');
306 * Load the configuration files
308 * First loads the default value for all the configuration keys, then the legacy configuration files, then the
309 * expected local.ini.php
311 private function loadConfigFiles()
313 $this->loadConfigFile($this->basepath . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'defaults.ini.php');
315 // Legacy .htconfig.php support
316 if (file_exists($this->basepath . DIRECTORY_SEPARATOR . '.htpreconfig.php')) {
318 include $this->basepath . DIRECTORY_SEPARATOR . '.htpreconfig.php';
321 // Legacy .htconfig.php support
322 if (file_exists($this->basepath . DIRECTORY_SEPARATOR . '.htconfig.php')) {
325 include $this->basepath . DIRECTORY_SEPARATOR . '.htconfig.php';
326 unset($db_host, $db_user, $db_pass, $db_data);
328 if (isset($default_timezone)) {
329 $this->setConfigValue('system', 'default_timezone', $default_timezone);
330 unset($default_timezone);
333 if (isset($pidfile)) {
334 $this->setConfigValue('system', 'pidfile', $pidfile);
339 if (file_exists($this->basepath . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'local.ini.php')) {
340 $this->loadConfigFile($this->basepath . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'local.ini.php');
345 * Tries to load the specified configuration file into the App->config array.
346 * Overwrites previously set values.
348 * The config format is INI and the template for configuration files is the following:
350 * <?php return <<<INI
358 * @param type $filepath
361 public function loadConfigFile($filepath)
363 if (!file_exists($filepath)) {
364 throw new Exception('Error parsing non-existent config file ' . $filepath);
367 $contents = include($filepath);
369 $config = parse_ini_string($contents, true, INI_SCANNER_TYPED);
371 if ($config === false) {
372 throw new Exception('Error parsing config file ' . $filepath);
375 foreach($config as $category => $values) {
376 foreach($values as $key => $value) {
377 $this->setConfigValue($category, $key, $value);
383 * Loads addons configuration files
385 * First loads all activated addons default configuration throught the load_config hook, then load the local.ini.php
386 * again to overwrite potential local addon configuration.
388 private function loadAddonConfig()
390 // Loads addons default config
391 Core\Addon::callHooks('load_config');
393 // Load the local config file again in case there are overwritten addon config
394 if (file_exists($this->basepath . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'local.ini.php')) {
395 $this->loadConfigFile($this->basepath . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'local.ini.php');
400 * Loads the default timezone
402 * Include support for legacy $default_timezone
404 * @global string $default_timezone
406 private function loadDefaultTimezone()
408 if ($this->getConfigValue('system', 'default_timezone')) {
409 $this->timezone = $this->getConfigValue('system', 'default_timezone');
411 global $default_timezone;
412 $this->timezone = !empty($default_timezone) ? $default_timezone : 'UTC';
415 if ($this->timezone) {
416 date_default_timezone_set($this->timezone);
421 * Figure out if we are running at the top of a domain or in a sub-directory and adjust accordingly
423 private function determineUrlPath()
425 $this->urlpath = $this->getConfigValue('system', 'urlpath');
427 /* SCRIPT_URL gives /path/to/friendica/module/parameter
428 * QUERY_STRING gives pagename=module/parameter
430 * To get /path/to/friendica we perform dirname() for as many levels as there are slashes in the QUERY_STRING
432 if (!empty($_SERVER['SCRIPT_URL']) && !empty($_SERVER['QUERY_STRING'])) {
433 $path = trim(dirname($_SERVER['SCRIPT_URL'], substr_count(trim($_SERVER['QUERY_STRING'], '/'), '/') + 1), '/');
435 if ($path && $path != $this->urlpath) {
436 $this->urlpath = $path;
444 * - App::MODE_INSTALL : Either the database connection can't be established or the config table doesn't exist
445 * - App::MODE_MAINTENANCE: The maintenance mode has been set
446 * - App::MODE_NORMAL : Normal run with all features enabled
450 private function determineMode()
452 $this->mode = App::MODE_INSTALL;
454 // Missing local config files: MODE_INSTALL
455 if (!file_exists($this->basepath . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'local.ini.php')
456 && !file_exists($this->basepath . DIRECTORY_SEPARATOR . '.htconfig.php')) {
460 // Missing DB connection: ERROR
461 if (!\dba::connected()) {
462 System::unavailable();
465 // Working DB connection, missing tables: MODE_INSTALL
466 if (\dba::fetch_first("SHOW TABLES LIKE 'config'") === false) {
470 // Maintenance mode check
471 if (Config::get('system', 'maintenance')) {
472 $this->mode = App::MODE_MAINTENANCE;
474 $this->mode = App::MODE_NORMAL;
478 public function loadDatabase()
480 if (\dba::connected()) {
484 $db_host = $this->getConfigValue('database', 'hostname');
485 $db_user = $this->getConfigValue('database', 'username');
486 $db_pass = $this->getConfigValue('database', 'password');
487 $db_data = $this->getConfigValue('database', 'database');
488 $charset = $this->getConfigValue('database', 'charset');
490 // Use environment variables for mysql if they are set beforehand
491 if (!empty(getenv('MYSQL_HOST'))
492 && !empty(getenv('MYSQL_PORT'))
493 && (!empty(getenv('MYSQL_USERNAME')) || !empty(getenv('MYSQL_USER')))
494 && !empty(getenv('MYSQL_PASSWORD'))
495 && !empty(getenv('MYSQL_DATABASE')))
497 $db_host = getenv('MYSQL_HOST') . ':' . getenv('MYSQL_PORT');
499 if (!empty(getenv('MYSQL_USERNAME'))) {
500 $db_user = getenv('MYSQL_USERNAME');
501 } elseif (!empty(getenv('MYSQL_USER'))) {
502 $db_user = getenv('MYSQL_USER');
505 $db_pass = getenv('MYSQL_PASSWORD');
506 $db_data = getenv('MYSQL_DATABASE');
507 }elseif (file_exists($this->basepath . DIRECTORY_SEPARATOR . '.htconfig.php')) {
508 $a = new \stdClass();
509 include $this->basepath . DIRECTORY_SEPARATOR . '.htconfig.php';
510 $charset = isset($a->config["system"]["db_charset"]) ? $a->config["system"]["db_charset"] : $charset;
515 $stamp1 = microtime(true);
517 \dba::connect($db_host, $db_user, $db_pass, $db_data, $charset);
518 unset($db_host, $db_user, $db_pass, $db_data, $charset);
520 $this->save_timestamp($stamp1, "network");
524 * @brief Returns the base filesystem path of the App
526 * It first checks for the internal variable, then for DOCUMENT_ROOT and
531 public function get_basepath()
533 $basepath = $this->basepath;
536 $basepath = Config::get('system', 'basepath');
539 if (!$basepath && x($_SERVER, 'DOCUMENT_ROOT')) {
540 $basepath = $_SERVER['DOCUMENT_ROOT'];
543 if (!$basepath && x($_SERVER, 'PWD')) {
544 $basepath = $_SERVER['PWD'];
547 return self::realpath($basepath);
551 * @brief Returns a normalized file path
553 * This is a wrapper for the "realpath" function.
554 * That function cannot detect the real path when some folders aren't readable.
555 * Since this could happen with some hosters we need to handle this.
557 * @param string $path The path that is about to be normalized
558 * @return string normalized path - when possible
560 public static function realpath($path)
562 $normalized = realpath($path);
564 if (!is_bool($normalized)) {
571 public function get_scheme()
573 return $this->scheme;
577 * @brief Retrieves the Friendica instance base URL
579 * This function assembles the base URL from multiple parts:
580 * - Protocol is determined either by the request or a combination of
581 * system.ssl_policy and the $ssl parameter.
582 * - Host name is determined either by system.hostname or inferred from request
583 * - Path is inferred from SCRIPT_NAME
585 * Note: $ssl parameter value doesn't directly correlate with the resulting protocol
587 * @param bool $ssl Whether to append http or https under SSL_POLICY_SELFSIGN
588 * @return string Friendica server base URL
590 public function get_baseurl($ssl = false)
592 $scheme = $this->scheme;
594 if (Config::get('system', 'ssl_policy') == SSL_POLICY_FULL) {
598 // Basically, we have $ssl = true on any links which can only be seen by a logged in user
599 // (and also the login link). Anything seen by an outsider will have it turned off.
601 if (Config::get('system', 'ssl_policy') == SSL_POLICY_SELFSIGN) {
609 if (Config::get('config', 'hostname') != '') {
610 $this->hostname = Config::get('config', 'hostname');
613 return $scheme . '://' . $this->hostname . (!empty($this->urlpath) ? '/' . $this->urlpath : '' );
617 * @brief Initializes the baseurl components
619 * Clears the baseurl cache to prevent inconsistencies
623 public function set_baseurl($url)
625 $parsed = @parse_url($url);
629 if (!empty($parsed['scheme'])) {
630 $this->scheme = $parsed['scheme'];
633 if (!empty($parsed['host'])) {
634 $hostname = $parsed['host'];
637 if (x($parsed, 'port')) {
638 $hostname .= ':' . $parsed['port'];
640 if (x($parsed, 'path')) {
641 $this->urlpath = trim($parsed['path'], '\\/');
644 if (file_exists($this->basepath . DIRECTORY_SEPARATOR . '.htpreconfig.php')) {
645 include $this->basepath . DIRECTORY_SEPARATOR . '.htpreconfig.php';
648 if (Config::get('config', 'hostname') != '') {
649 $this->hostname = Config::get('config', 'hostname');
652 if (!isset($this->hostname) || ($this->hostname == '')) {
653 $this->hostname = $hostname;
658 public function get_hostname()
660 if (Config::get('config', 'hostname') != '') {
661 $this->hostname = Config::get('config', 'hostname');
664 return $this->hostname;
667 public function get_path()
669 return $this->urlpath;
672 public function set_pager_total($n)
674 $this->pager['total'] = intval($n);
677 public function set_pager_itemspage($n)
679 $this->pager['itemspage'] = ((intval($n) > 0) ? intval($n) : 0);
680 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
683 public function set_pager_page($n)
685 $this->pager['page'] = $n;
686 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
689 public function init_pagehead()
691 $interval = ((local_user()) ? PConfig::get(local_user(), 'system', 'update_interval') : 40000);
693 // If the update is 'deactivated' set it to the highest integer number (~24 days)
695 $interval = 2147483647;
698 if ($interval < 10000) {
702 // compose the page title from the sitename and the
703 // current module called
704 if (!$this->module == '') {
705 $this->page['title'] = $this->config['sitename'] . ' (' . $this->module . ')';
707 $this->page['title'] = $this->config['sitename'];
710 /* put the head template at the beginning of page['htmlhead']
711 * since the code added by the modules frequently depends on it
714 if (!isset($this->page['htmlhead'])) {
715 $this->page['htmlhead'] = '';
718 // If we're using Smarty, then doing replace_macros() will replace
719 // any unrecognized variables with a blank string. Since we delay
720 // replacing $stylesheet until later, we need to replace it now
721 // with another variable name
722 if ($this->theme['template_engine'] === 'smarty3') {
723 $stylesheet = $this->get_template_ldelim('smarty3') . '$stylesheet' . $this->get_template_rdelim('smarty3');
725 $stylesheet = '$stylesheet';
728 $shortcut_icon = Config::get('system', 'shortcut_icon');
729 if ($shortcut_icon == '') {
730 $shortcut_icon = 'images/friendica-32.png';
733 $touch_icon = Config::get('system', 'touch_icon');
734 if ($touch_icon == '') {
735 $touch_icon = 'images/friendica-128.png';
738 // get data wich is needed for infinite scroll on the network page
739 $invinite_scroll = infinite_scroll_data($this->module);
741 $tpl = get_markup_template('head.tpl');
742 $this->page['htmlhead'] = replace_macros($tpl, [
743 '$baseurl' => $this->get_baseurl(),
744 '$local_user' => local_user(),
745 '$generator' => 'Friendica' . ' ' . FRIENDICA_VERSION,
746 '$delitem' => L10n::t('Delete this item?'),
747 '$showmore' => L10n::t('show more'),
748 '$showfewer' => L10n::t('show fewer'),
749 '$update_interval' => $interval,
750 '$shortcut_icon' => $shortcut_icon,
751 '$touch_icon' => $touch_icon,
752 '$stylesheet' => $stylesheet,
753 '$infinite_scroll' => $invinite_scroll,
754 '$block_public' => intval(Config::get('system', 'block_public')),
755 ]) . $this->page['htmlhead'];
758 public function init_page_end()
760 if (!isset($this->page['end'])) {
761 $this->page['end'] = '';
763 $tpl = get_markup_template('end.tpl');
764 $this->page['end'] = replace_macros($tpl, [
765 '$baseurl' => $this->get_baseurl()
766 ]) . $this->page['end'];
769 public function set_curl_code($code)
771 $this->curl_code = $code;
774 public function get_curl_code()
776 return $this->curl_code;
779 public function set_curl_content_type($content_type)
781 $this->curl_content_type = $content_type;
784 public function get_curl_content_type()
786 return $this->curl_content_type;
789 public function set_curl_headers($headers)
791 $this->curl_headers = $headers;
794 public function get_curl_headers()
796 return $this->curl_headers;
800 * @brief Removes the base url from an url. This avoids some mixed content problems.
802 * @param string $orig_url
804 * @return string The cleaned url
806 public function remove_baseurl($orig_url)
808 // Remove the hostname from the url if it is an internal link
809 $nurl = normalise_link($orig_url);
810 $base = normalise_link($this->get_baseurl());
811 $url = str_replace($base . '/', '', $nurl);
813 // if it is an external link return the orignal value
814 if ($url == normalise_link($orig_url)) {
822 * @brief Register template engine class
824 * @param string $class
826 private function register_template_engine($class)
828 $v = get_class_vars($class);
831 $this->template_engines[$name] = $class;
833 echo "template engine <tt>$class</tt> cannot be registered without a name.\n";
839 * @brief Return template engine instance.
841 * If $name is not defined, return engine defined by theme,
844 * @return object Template Engine instance
846 public function template_engine()
848 $template_engine = 'smarty3';
849 if (x($this->theme, 'template_engine')) {
850 $template_engine = $this->theme['template_engine'];
853 if (isset($this->template_engines[$template_engine])) {
854 if (isset($this->template_engine_instance[$template_engine])) {
855 return $this->template_engine_instance[$template_engine];
857 $class = $this->template_engines[$template_engine];
859 $this->template_engine_instance[$template_engine] = $obj;
864 echo "template engine <tt>$template_engine</tt> is not registered!\n";
869 * @brief Returns the active template engine.
873 public function get_template_engine()
875 return $this->theme['template_engine'];
878 public function set_template_engine($engine = 'smarty3')
880 $this->theme['template_engine'] = $engine;
883 public function get_template_ldelim($engine = 'smarty3')
885 return $this->ldelim[$engine];
888 public function get_template_rdelim($engine = 'smarty3')
890 return $this->rdelim[$engine];
893 public function save_timestamp($stamp, $value)
895 if (!isset($this->config['system']['profiler']) || !$this->config['system']['profiler']) {
899 $duration = (float) (microtime(true) - $stamp);
901 if (!isset($this->performance[$value])) {
902 // Prevent ugly E_NOTICE
903 $this->performance[$value] = 0;
906 $this->performance[$value] += (float) $duration;
907 $this->performance['marktime'] += (float) $duration;
909 $callstack = System::callstack();
911 if (!isset($this->callstack[$value][$callstack])) {
912 // Prevent ugly E_NOTICE
913 $this->callstack[$value][$callstack] = 0;
916 $this->callstack[$value][$callstack] += (float) $duration;
919 public function get_useragent()
922 FRIENDICA_PLATFORM . " '" .
923 FRIENDICA_CODENAME . "' " .
924 FRIENDICA_VERSION . '-' .
925 DB_UPDATE_VERSION . '; ' .
926 $this->get_baseurl();
929 public function is_friendica_app()
931 return $this->is_friendica_app;
935 * @brief Checks if the site is called via a backend process
937 * This isn't a perfect solution. But we need this check very early.
938 * So we cannot wait until the modules are loaded.
940 * @return bool Is it a known backend?
942 public function is_backend()
966 // Check if current module is in backend or backend flag is set
967 return (in_array($this->module, $backends) || $this->backend);
971 * @brief Checks if the maximum number of database processes is reached
973 * @return bool Is the limit reached?
975 public function isMaxProcessesReached()
977 // Deactivated, needs more investigating if this check really makes sense
981 * Commented out to suppress static analyzer issues
983 if ($this->is_backend()) {
984 $process = 'backend';
985 $max_processes = Config::get('system', 'max_processes_backend');
986 if (intval($max_processes) == 0) {
990 $process = 'frontend';
991 $max_processes = Config::get('system', 'max_processes_frontend');
992 if (intval($max_processes) == 0) {
997 $processlist = DBM::processlist();
998 if ($processlist['list'] != '') {
999 logger('Processcheck: Processes: ' . $processlist['amount'] . ' - Processlist: ' . $processlist['list'], LOGGER_DEBUG);
1001 if ($processlist['amount'] > $max_processes) {
1002 logger('Processcheck: Maximum number of processes for ' . $process . ' tasks (' . $max_processes . ') reached.', LOGGER_DEBUG);
1011 * @brief Checks if the minimal memory is reached
1013 * @return bool Is the memory limit reached?
1015 public function min_memory_reached()
1017 $min_memory = Config::get('system', 'min_memory', 0);
1018 if ($min_memory == 0) {
1022 if (!is_readable('/proc/meminfo')) {
1026 $memdata = explode("\n", file_get_contents('/proc/meminfo'));
1029 foreach ($memdata as $line) {
1030 list($key, $val) = explode(':', $line);
1031 $meminfo[$key] = (int) trim(str_replace('kB', '', $val));
1032 $meminfo[$key] = (int) ($meminfo[$key] / 1024);
1035 if (!isset($meminfo['MemAvailable']) || !isset($meminfo['MemFree'])) {
1039 $free = $meminfo['MemAvailable'] + $meminfo['MemFree'];
1041 $reached = ($free < $min_memory);
1044 logger('Minimal memory reached: ' . $free . '/' . $meminfo['MemTotal'] . ' - limit ' . $min_memory, LOGGER_DEBUG);
1051 * @brief Checks if the maximum load is reached
1053 * @return bool Is the load reached?
1055 public function isMaxLoadReached()
1057 if ($this->is_backend()) {
1058 $process = 'backend';
1059 $maxsysload = intval(Config::get('system', 'maxloadavg'));
1060 if ($maxsysload < 1) {
1064 $process = 'frontend';
1065 $maxsysload = intval(Config::get('system', 'maxloadavg_frontend'));
1066 if ($maxsysload < 1) {
1071 $load = current_load();
1073 if (intval($load) > $maxsysload) {
1074 logger('system: load ' . $load . ' for ' . $process . ' tasks (' . $maxsysload . ') too high.');
1081 public function proc_run($args)
1083 if (!function_exists('proc_open')) {
1087 array_unshift($args, $this->getConfigValue('config', 'php_path', 'php'));
1089 for ($x = 0; $x < count($args); $x ++) {
1090 $args[$x] = escapeshellarg($args[$x]);
1093 $cmdline = implode(' ', $args);
1095 if ($this->min_memory_reached()) {
1099 if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
1100 $resource = proc_open('cmd /c start /b ' . $cmdline, [], $foo, $this->get_basepath());
1102 $resource = proc_open($cmdline . ' &', [], $foo, $this->get_basepath());
1104 if (!is_resource($resource)) {
1105 logger('We got no resource for command ' . $cmdline, LOGGER_DEBUG);
1108 proc_close($resource);
1112 * @brief Returns the system user that is executing the script
1114 * This mostly returns something like "www-data".
1116 * @return string system username
1118 private static function systemuser()
1120 if (!function_exists('posix_getpwuid') || !function_exists('posix_geteuid')) {
1124 $processUser = posix_getpwuid(posix_geteuid());
1125 return $processUser['name'];
1129 * @brief Checks if a given directory is usable for the system
1131 * @return boolean the directory is usable
1133 public static function directory_usable($directory, $check_writable = true)
1135 if ($directory == '') {
1136 logger('Directory is empty. This shouldn\'t happen.', LOGGER_DEBUG);
1140 if (!file_exists($directory)) {
1141 logger('Path "' . $directory . '" does not exist for user ' . self::systemuser(), LOGGER_DEBUG);
1145 if (is_file($directory)) {
1146 logger('Path "' . $directory . '" is a file for user ' . self::systemuser(), LOGGER_DEBUG);
1150 if (!is_dir($directory)) {
1151 logger('Path "' . $directory . '" is not a directory for user ' . self::systemuser(), LOGGER_DEBUG);
1155 if ($check_writable && !is_writable($directory)) {
1156 logger('Path "' . $directory . '" is not writable for user ' . self::systemuser(), LOGGER_DEBUG);
1164 * @param string $cat Config category
1165 * @param string $k Config key
1166 * @param mixed $default Default value if it isn't set
1168 public function getConfigValue($cat, $k, $default = null)
1172 if ($cat === 'config') {
1173 if (isset($this->config[$k])) {
1174 $return = $this->config[$k];
1177 if (isset($this->config[$cat][$k])) {
1178 $return = $this->config[$cat][$k];
1186 * Sets a value in the config cache. Accepts raw output from the config table
1188 * @param string $cat Config category
1189 * @param string $k Config key
1190 * @param mixed $v Value to set
1192 public function setConfigValue($cat, $k, $v)
1194 // Only arrays are serialized in database, so we have to unserialize sparingly
1195 $value = is_string($v) && preg_match("|^a:[0-9]+:{.*}$|s", $v) ? unserialize($v) : $v;
1197 if ($cat === 'config') {
1198 $this->config[$k] = $value;
1200 if (!isset($this->config[$cat])) {
1201 $this->config[$cat] = [];
1204 $this->config[$cat][$k] = $value;
1209 * Deletes a value from the config cache
1211 * @param string $cat Config category
1212 * @param string $k Config key
1214 public function deleteConfigValue($cat, $k)
1216 if ($cat === 'config') {
1217 if (isset($this->config[$k])) {
1218 unset($this->config[$k]);
1221 if (isset($this->config[$cat][$k])) {
1222 unset($this->config[$cat][$k]);
1229 * Retrieves a value from the user config cache
1231 * @param int $uid User Id
1232 * @param string $cat Config category
1233 * @param string $k Config key
1234 * @param mixed $default Default value if key isn't set
1236 public function getPConfigValue($uid, $cat, $k, $default = null)
1240 if (isset($this->config[$uid][$cat][$k])) {
1241 $return = $this->config[$uid][$cat][$k];
1248 * Sets a value in the user config cache
1250 * Accepts raw output from the pconfig table
1252 * @param int $uid User Id
1253 * @param string $cat Config category
1254 * @param string $k Config key
1255 * @param mixed $v Value to set
1257 public function setPConfigValue($uid, $cat, $k, $v)
1259 // Only arrays are serialized in database, so we have to unserialize sparingly
1260 $value = is_string($v) && preg_match("|^a:[0-9]+:{.*}$|s", $v) ? unserialize($v) : $v;
1262 if (!isset($this->config[$uid])) {
1263 $this->config[$uid] = [];
1266 if (!isset($this->config[$uid][$cat])) {
1267 $this->config[$uid][$cat] = [];
1270 $this->config[$uid][$cat][$k] = $value;
1274 * Deletes a value from the user config cache
1276 * @param int $uid User Id
1277 * @param string $cat Config category
1278 * @param string $k Config key
1280 public function deletePConfigValue($uid, $cat, $k)
1282 if (isset($this->config[$uid][$cat][$k])) {
1283 unset($this->config[$uid][$cat][$k]);
1288 * Generates the site's default sender email address
1292 public function getSenderEmailAddress()
1294 $sender_email = Config::get('config', 'sender_email');
1295 if (empty($sender_email)) {
1296 $hostname = $this->get_hostname();
1297 if (strpos($hostname, ':')) {
1298 $hostname = substr($hostname, 0, strpos($hostname, ':'));
1301 $sender_email = 'noreply@' . $hostname;
1304 return $sender_email;
1308 * Returns the current theme name.
1312 public function getCurrentTheme()
1314 if ($this->mode == App::MODE_INSTALL) {
1318 //// @TODO Compute the current theme only once (this behavior has
1319 /// already been implemented, but it didn't work well -
1320 /// https://github.com/friendica/friendica/issues/5092)
1321 $this->computeCurrentTheme();
1323 return $this->current_theme;
1327 * Computes the current theme name based on the node settings, the user settings and the device type
1331 private function computeCurrentTheme()
1333 $system_theme = Config::get('system', 'theme');
1334 if (!$system_theme) {
1335 throw new Exception(L10n::t('No system theme config value set.'));
1339 $this->current_theme = $system_theme;
1341 $allowed_themes = explode(',', Config::get('system', 'allowed_themes', $system_theme));
1344 // Find the theme that belongs to the user whose stuff we are looking at
1345 if ($this->profile_uid && ($this->profile_uid != local_user())) {
1346 // Allow folks to override user themes and always use their own on their own site.
1347 // This works only if the user is on the same server
1348 $user = dba::selectFirst('user', ['theme'], ['uid' => $this->profile_uid]);
1349 if (DBM::is_result($user) && !PConfig::get(local_user(), 'system', 'always_my_theme')) {
1350 $page_theme = $user['theme'];
1354 if (!empty($_SESSION)) {
1355 $user_theme = defaults($_SESSION, 'theme', $system_theme);
1357 $user_theme = $system_theme;
1360 // Specific mobile theme override
1361 if (($this->is_mobile || $this->is_tablet) && defaults($_SESSION, 'show-mobile', true)) {
1362 $system_mobile_theme = Config::get('system', 'mobile-theme');
1363 $user_mobile_theme = defaults($_SESSION, 'mobile-theme', $system_mobile_theme);
1365 // --- means same mobile theme as desktop
1366 if (!empty($user_mobile_theme) && $user_mobile_theme !== '---') {
1367 $user_theme = $user_mobile_theme;
1372 $theme_name = $page_theme;
1374 $theme_name = $user_theme;
1378 && in_array($theme_name, $allowed_themes)
1379 && (file_exists('view/theme/' . $theme_name . '/style.css')
1380 || file_exists('view/theme/' . $theme_name . '/style.php'))
1382 $this->current_theme = $theme_name;
1387 * @brief Return full URL to theme which is currently in effect.
1389 * Provide a sane default if nothing is chosen or the specified theme does not exist.
1393 public function getCurrentThemeStylesheetPath()
1395 return Core\Theme::getStylesheetPath($this->getCurrentTheme());