5 use Friendica\Core\Config;
6 use Friendica\Core\PConfig;
12 use Detection\MobileDetect;
20 * @brief Our main application structure for the life of this page.
22 * Primarily deals with the URL that got us here
23 * and tries to make some sense of it, and
24 * stores our page contents and config storage
25 * and anything else that might need to be passed around
26 * before we spit the page out.
31 public $module_loaded = false;
43 public $data = array();
44 public $error = false;
55 public $interactive = true;
57 public $apps = array();
59 public $is_mobile = false;
60 public $is_tablet = false;
61 public $is_friendica_app;
62 public $performance = array();
63 public $callstack = array();
64 public $theme_info = array();
65 public $backend = true;
68 // Allow themes to control internal parameters
69 // by changing App values in theme.php
71 public $sourcename = '';
72 public $videowidth = 425;
73 public $videoheight = 350;
74 public $force_max_items = 0;
75 public $theme_thread_allow = true;
76 public $theme_events_in_profile = true;
79 * @brief An array for all theme-controllable parameters
81 * Mostly unimplemented yet. Only options 'template_engine' and
84 public $theme = array(
88 'force_max_items' => 0,
89 'thread_allow' => true,
91 'template_engine' => 'smarty3',
95 * @brief An array of registered template engines ('name'=>'class name')
97 public $template_engines = array();
100 * @brief An array of instanced template engines ('name'=>'instance')
102 public $template_engine_instance = array();
105 private $ldelim = array(
109 private $rdelim = array(
117 private $curl_content_type;
118 private $curl_headers;
119 private $cached_profile_image;
120 private $cached_profile_picdate;
124 * @brief App constructor.
126 * @param string $basepath Path to the app base folder
128 function __construct($basepath) {
130 global $default_timezone;
134 if (file_exists('.htpreconfig.php')) {
135 include '.htpreconfig.php';
138 $this->timezone = ((x($default_timezone)) ? $default_timezone : 'UTC');
140 date_default_timezone_set($this->timezone);
142 $this->performance['start'] = microtime(true);
143 $this->performance['database'] = 0;
144 $this->performance['database_write'] = 0;
145 $this->performance['network'] = 0;
146 $this->performance['file'] = 0;
147 $this->performance['rendering'] = 0;
148 $this->performance['parser'] = 0;
149 $this->performance['marktime'] = 0;
150 $this->performance['markstart'] = microtime(true);
152 $this->callstack['database'] = array();
153 $this->callstack['database_write'] = array();
154 $this->callstack['network'] = array();
155 $this->callstack['file'] = array();
156 $this->callstack['rendering'] = array();
157 $this->callstack['parser'] = array();
159 $this->config = array();
160 $this->page = array();
161 $this->pager = array();
163 $this->query_string = '';
165 $this->process_id = uniqid('log', true);
169 $this->scheme = 'http';
171 if ((x($_SERVER, 'HTTPS') && $_SERVER['HTTPS']) ||
172 (x($_SERVER, 'HTTP_FORWARDED') && preg_match('/proto=https/', $_SERVER['HTTP_FORWARDED'])) ||
173 (x($_SERVER, 'HTTP_X_FORWARDED_PROTO') && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') ||
174 (x($_SERVER, 'HTTP_X_FORWARDED_SSL') && $_SERVER['HTTP_X_FORWARDED_SSL'] == 'on') ||
175 (x($_SERVER, 'FRONT_END_HTTPS') && $_SERVER['FRONT_END_HTTPS'] == 'on') ||
176 (x($_SERVER, 'SERVER_PORT') && (intval($_SERVER['SERVER_PORT']) == 443)) // XXX: reasonable assumption, but isn't this hardcoding too much?
178 $this->scheme = 'https';
181 if (x($_SERVER, 'SERVER_NAME')) {
182 $this->hostname = $_SERVER['SERVER_NAME'];
184 if (x($_SERVER, 'SERVER_PORT') && $_SERVER['SERVER_PORT'] != 80 && $_SERVER['SERVER_PORT'] != 443) {
185 $this->hostname .= ':' . $_SERVER['SERVER_PORT'];
188 * Figure out if we are running at the top of a domain
189 * or in a sub-directory and adjust accordingly
192 /// @TODO This kind of escaping breaks syntax-highlightning on CoolEdit (Midnight Commander)
193 $path = trim(dirname($_SERVER['SCRIPT_NAME']), '/\\');
194 if (isset($path) && strlen($path) && ($path != $this->path)) {
199 if ($hostname != '') {
200 $this->hostname = $hostname;
203 if (! static::directory_usable($basepath, false)) {
204 throw new Exception('Basepath ' . $basepath . ' isn\'t usable.');
207 $this->basepath = rtrim($basepath, DIRECTORY_SEPARATOR);
210 get_include_path() . PATH_SEPARATOR
211 . $this->basepath . DIRECTORY_SEPARATOR . 'include' . PATH_SEPARATOR
212 . $this->basepath . DIRECTORY_SEPARATOR . 'library' . PATH_SEPARATOR
213 . $this->basepath . DIRECTORY_SEPARATOR . 'library/langdet' . PATH_SEPARATOR
217 if (is_array($_SERVER['argv']) && $_SERVER['argc'] > 1 && substr(end($_SERVER['argv']), 0, 4) == 'http') {
218 $this->set_baseurl(array_pop($_SERVER['argv']));
222 if ((x($_SERVER, 'QUERY_STRING')) && substr($_SERVER['QUERY_STRING'], 0, 9) === 'pagename=') {
223 $this->query_string = substr($_SERVER['QUERY_STRING'], 9);
225 // removing trailing / - maybe a nginx problem
226 $this->query_string = ltrim($this->query_string, '/');
227 } elseif ((x($_SERVER, 'QUERY_STRING')) && substr($_SERVER['QUERY_STRING'], 0, 2) === 'q=') {
228 $this->query_string = substr($_SERVER['QUERY_STRING'], 2);
230 // removing trailing / - maybe a nginx problem
231 $this->query_string = ltrim($this->query_string, '/');
234 if (x($_GET, 'pagename')) {
235 $this->cmd = trim($_GET['pagename'], '/\\');
236 } elseif (x($_GET, 'q')) {
237 $this->cmd = trim($_GET['q'], '/\\');
241 $this->query_string = str_replace($this->cmd . '&', $this->cmd . '?', $this->query_string);
243 // unix style "homedir"
244 if (substr($this->cmd, 0, 1) === '~') {
245 $this->cmd = 'profile/' . substr($this->cmd, 1);
248 // Diaspora style profile url
249 if (substr($this->cmd, 0, 2) === 'u/') {
250 $this->cmd = 'profile/' . substr($this->cmd, 2);
254 * Break the URL path into C style argc/argv style arguments for our
255 * modules. Given "http://example.com/module/arg1/arg2", $this->argc
256 * will be 3 (integer) and $this->argv will contain:
262 * There will always be one argument. If provided a naked domain
263 * URL, $this->argv[0] is set to "home".
266 $this->argv = explode('/', $this->cmd);
267 $this->argc = count($this->argv);
268 if ((array_key_exists('0', $this->argv)) && strlen($this->argv[0])) {
269 $this->module = str_replace('.', '_', $this->argv[0]);
270 $this->module = str_replace('-', '_', $this->module);
273 $this->argv = array('home');
274 $this->module = 'home';
277 // See if there is any page number information, and initialise pagination
278 $this->pager['page'] = ((x($_GET, 'page') && intval($_GET['page']) > 0) ? intval($_GET['page']) : 1);
279 $this->pager['itemspage'] = 50;
280 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
282 if ($this->pager['start'] < 0) {
283 $this->pager['start'] = 0;
285 $this->pager['total'] = 0;
287 // Detect mobile devices
288 $mobile_detect = new MobileDetect();
289 $this->is_mobile = $mobile_detect->isMobile();
290 $this->is_tablet = $mobile_detect->isTablet();
293 $this->is_friendica_app = ($_SERVER['HTTP_USER_AGENT'] == 'Apache-HttpClient/UNAVAILABLE (java 1.4)');
295 // Register template engines
296 $dc = get_declared_classes();
297 foreach ($dc as $k) {
298 if (in_array('ITemplateEngine', class_implements($k))) {
299 $this->register_template_engine($k);
307 * @brief Returns the base filesystem path of the App
309 * It first checks for the internal variable, then for DOCUMENT_ROOT and
314 public static function get_basepath() {
316 $basepath = $this->basepath;
320 $basepath = Config::get('system', 'basepath');
323 if (! $basepath && x($_SERVER, 'DOCUMENT_ROOT')) {
324 $basepath = $_SERVER['DOCUMENT_ROOT'];
327 if (! $basepath && x($_SERVER, 'PWD')) {
328 $basepath = $_SERVER['PWD'];
331 return self::realpath($basepath);
335 * @brief Returns a normalized file path
337 * This is a wrapper for the "realpath" function.
338 * That function cannot detect the real path when some folders aren't readable.
339 * Since this could happen with some hosters we need to handle this.
341 * @param string $path The path that is about to be normalized
342 * @return string normalized path - when possible
344 public static function realpath($path) {
345 $normalized = realpath($path);
347 if (!is_bool($normalized)) {
354 function get_scheme() {
355 return $this->scheme;
359 * @brief Retrieves the Friendica instance base URL
361 * This function assembles the base URL from multiple parts:
362 * - Protocol is determined either by the request or a combination of
363 * system.ssl_policy and the $ssl parameter.
364 * - Host name is determined either by system.hostname or inferred from request
365 * - Path is inferred from SCRIPT_NAME
367 * Note: $ssl parameter value doesn't directly correlate with the resulting protocol
369 * @param bool $ssl Whether to append http or https under SSL_POLICY_SELFSIGN
370 * @return string Friendica server base URL
372 function get_baseurl($ssl = false) {
373 // Is the function called statically?
374 if (!(isset($this) && get_class($this) == __CLASS__)) {
375 return self::$a->get_baseurl($ssl);
378 $scheme = $this->scheme;
380 if (Config::get('system', 'ssl_policy') == SSL_POLICY_FULL) {
384 // Basically, we have $ssl = true on any links which can only be seen by a logged in user
385 // (and also the login link). Anything seen by an outsider will have it turned off.
387 if (Config::get('system', 'ssl_policy') == SSL_POLICY_SELFSIGN) {
395 if (Config::get('config', 'hostname') != '') {
396 $this->hostname = Config::get('config', 'hostname');
399 return $scheme . '://' . $this->hostname . ((isset($this->path) && strlen($this->path)) ? '/' . $this->path : '' );
403 * @brief Initializes the baseurl components
405 * Clears the baseurl cache to prevent inconstistencies
409 function set_baseurl($url) {
410 $parsed = @parse_url($url);
413 $this->scheme = $parsed['scheme'];
415 $hostname = $parsed['host'];
416 if (x($parsed, 'port')) {
417 $hostname .= ':' . $parsed['port'];
419 if (x($parsed, 'path')) {
420 $this->path = trim($parsed['path'], '\\/');
423 if (file_exists('.htpreconfig.php')) {
424 include '.htpreconfig.php';
427 if (Config::get('config', 'hostname') != '') {
428 $this->hostname = Config::get('config', 'hostname');
431 if (!isset($this->hostname) || ( $this->hostname == '')) {
432 $this->hostname = $hostname;
437 function get_hostname() {
438 if (Config::get('config', 'hostname') != '') {
439 $this->hostname = Config::get('config', 'hostname');
442 return $this->hostname;
445 function set_hostname($h) {
446 $this->hostname = $h;
449 function set_path($p) {
450 $this->path = trim(trim($p), '/');
453 function get_path() {
457 function set_pager_total($n) {
458 $this->pager['total'] = intval($n);
461 function set_pager_itemspage($n) {
462 $this->pager['itemspage'] = ((intval($n) > 0) ? intval($n) : 0);
463 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
466 function set_pager_page($n) {
467 $this->pager['page'] = $n;
468 $this->pager['start'] = ($this->pager['page'] * $this->pager['itemspage']) - $this->pager['itemspage'];
471 function init_pagehead() {
472 $interval = ((local_user()) ? PConfig::get(local_user(), 'system', 'update_interval') : 40000);
474 // If the update is 'deactivated' set it to the highest integer number (~24 days)
476 $interval = 2147483647;
479 if ($interval < 10000) {
483 // compose the page title from the sitename and the
484 // current module called
485 if (!$this->module == '') {
486 $this->page['title'] = $this->config['sitename'] . ' (' . $this->module . ')';
488 $this->page['title'] = $this->config['sitename'];
491 /* put the head template at the beginning of page['htmlhead']
492 * since the code added by the modules frequently depends on it
495 if (!isset($this->page['htmlhead'])) {
496 $this->page['htmlhead'] = '';
499 // If we're using Smarty, then doing replace_macros() will replace
500 // any unrecognized variables with a blank string. Since we delay
501 // replacing $stylesheet until later, we need to replace it now
502 // with another variable name
503 if ($this->theme['template_engine'] === 'smarty3') {
504 $stylesheet = $this->get_template_ldelim('smarty3') . '$stylesheet' . $this->get_template_rdelim('smarty3');
506 $stylesheet = '$stylesheet';
509 $shortcut_icon = Config::get('system', 'shortcut_icon');
510 if ($shortcut_icon == '') {
511 $shortcut_icon = 'images/friendica-32.png';
514 $touch_icon = Config::get('system', 'touch_icon');
515 if ($touch_icon == '') {
516 $touch_icon = 'images/friendica-128.png';
519 // get data wich is needed for infinite scroll on the network page
520 $invinite_scroll = infinite_scroll_data($this->module);
522 $tpl = get_markup_template('head.tpl');
523 $this->page['htmlhead'] = replace_macros($tpl, array(
524 '$baseurl' => $this->get_baseurl(), // FIXME for z_path!!!!
525 '$local_user' => local_user(),
526 '$generator' => 'Friendica' . ' ' . FRIENDICA_VERSION,
527 '$delitem' => t('Delete this item?'),
528 '$showmore' => t('show more'),
529 '$showfewer' => t('show fewer'),
530 '$update_interval' => $interval,
531 '$shortcut_icon' => $shortcut_icon,
532 '$touch_icon' => $touch_icon,
533 '$stylesheet' => $stylesheet,
534 '$infinite_scroll' => $invinite_scroll,
535 )) . $this->page['htmlhead'];
538 function init_page_end() {
539 if (!isset($this->page['end'])) {
540 $this->page['end'] = '';
542 $tpl = get_markup_template('end.tpl');
543 $this->page['end'] = replace_macros($tpl, array(
544 '$baseurl' => $this->get_baseurl() // FIXME for z_path!!!!
545 )) . $this->page['end'];
548 function set_curl_code($code) {
549 $this->curl_code = $code;
552 function get_curl_code() {
553 return $this->curl_code;
556 function set_curl_content_type($content_type) {
557 $this->curl_content_type = $content_type;
560 function get_curl_content_type() {
561 return $this->curl_content_type;
564 function set_curl_headers($headers) {
565 $this->curl_headers = $headers;
568 function get_curl_headers() {
569 return $this->curl_headers;
572 function get_cached_avatar_image($avatar_image) {
573 return $avatar_image;
577 * @brief Removes the baseurl from an url. This avoids some mixed content problems.
579 * @param string $orig_url
581 * @return string The cleaned url
583 function remove_baseurl($orig_url) {
585 // Is the function called statically?
586 if (!(isset($this) && get_class($this) == __CLASS__)) {
587 return self::$a->remove_baseurl($orig_url);
590 // Remove the hostname from the url if it is an internal link
591 $nurl = normalise_link($orig_url);
592 $base = normalise_link($this->get_baseurl());
593 $url = str_replace($base . '/', '', $nurl);
595 // if it is an external link return the orignal value
596 if ($url == normalise_link($orig_url)) {
604 * @brief Register template engine class
606 * If $name is '', is used class static property $class::$name
608 * @param string $class
609 * @param string $name
611 function register_template_engine($class, $name = '') {
612 /// @TODO Really === and not just == ?
614 $v = get_class_vars($class);
619 echo "template engine <tt>$class</tt> cannot be registered without a name.\n";
622 $this->template_engines[$name] = $class;
626 * @brief Return template engine instance.
628 * If $name is not defined, return engine defined by theme,
631 * @param strin $name Template engine name
632 * @return object Template Engine instance
634 function template_engine($name = '') {
635 /// @TODO really type-check included?
637 $template_engine = $name;
639 $template_engine = 'smarty3';
640 if (x($this->theme, 'template_engine')) {
641 $template_engine = $this->theme['template_engine'];
645 if (isset($this->template_engines[$template_engine])) {
646 if (isset($this->template_engine_instance[$template_engine])) {
647 return $this->template_engine_instance[$template_engine];
649 $class = $this->template_engines[$template_engine];
651 $this->template_engine_instance[$template_engine] = $obj;
656 echo "template engine <tt>$template_engine</tt> is not registered!\n";
661 * @brief Returns the active template engine.
665 function get_template_engine() {
666 return $this->theme['template_engine'];
669 function set_template_engine($engine = 'smarty3') {
670 $this->theme['template_engine'] = $engine;
673 function get_template_ldelim($engine = 'smarty3') {
674 return $this->ldelim[$engine];
677 function get_template_rdelim($engine = 'smarty3') {
678 return $this->rdelim[$engine];
681 function save_timestamp($stamp, $value) {
682 if (!isset($this->config['system']['profiler']) || !$this->config['system']['profiler']) {
686 $duration = (float) (microtime(true) - $stamp);
688 if (!isset($this->performance[$value])) {
689 // Prevent ugly E_NOTICE
690 $this->performance[$value] = 0;
693 $this->performance[$value] += (float) $duration;
694 $this->performance['marktime'] += (float) $duration;
696 $callstack = $this->callstack();
698 if (!isset($this->callstack[$value][$callstack])) {
699 // Prevent ugly E_NOTICE
700 $this->callstack[$value][$callstack] = 0;
703 $this->callstack[$value][$callstack] += (float) $duration;
707 * @brief Log active processes into the "process" table
709 function start_process() {
710 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 1);
712 $command = basename($trace[0]['file']);
714 $this->remove_inactive_processes();
718 $r = q('SELECT `pid` FROM `process` WHERE `pid` = %d', intval(getmypid()));
719 if (!dbm::is_result($r)) {
720 dba::insert('process', array('pid' => getmypid(), 'command' => $command, 'created' => datetime_convert()));
726 * @brief Remove inactive processes
728 function remove_inactive_processes() {
731 $r = q('SELECT `pid` FROM `process`');
732 if (dbm::is_result($r)) {
733 foreach ($r AS $process) {
734 if (!posix_kill($process['pid'], 0)) {
735 q('DELETE FROM `process` WHERE `pid` = %d', intval($process['pid']));
743 * @brief Remove the active process from the "process" table
745 function end_process() {
746 q('DELETE FROM `process` WHERE `pid` = %d', intval(getmypid()));
750 * @brief Returns a string with a callstack. Can be used for logging.
754 function callstack($depth = 4) {
755 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, $depth + 2);
757 // We remove the first two items from the list since they contain data that we don't need.
761 $callstack = array();
762 foreach ($trace AS $func) {
763 $callstack[] = $func['function'];
766 return implode(', ', $callstack);
769 function get_useragent() {
771 FRIENDICA_PLATFORM . " '" .
772 FRIENDICA_CODENAME . "' " .
773 FRIENDICA_VERSION . '-' .
774 DB_UPDATE_VERSION . '; ' .
775 $this->get_baseurl();
778 function is_friendica_app() {
779 return $this->is_friendica_app;
783 * @brief Checks if the site is called via a backend process
785 * This isn't a perfect solution. But we need this check very early.
786 * So we cannot wait until the modules are loaded.
788 * @return bool Is it a known backend?
790 function is_backend() {
791 static $backends = array();
792 $backends[] = '_well_known';
794 $backends[] = 'dfrn_notify';
795 $backends[] = 'fetch';
796 $backends[] = 'hcard';
797 $backends[] = 'hostxrd';
798 $backends[] = 'nodeinfo';
799 $backends[] = 'noscrape';
801 $backends[] = 'poco';
802 $backends[] = 'post';
803 $backends[] = 'proxy';
804 $backends[] = 'pubsub';
805 $backends[] = 'pubsubhubbub';
806 $backends[] = 'receive';
807 $backends[] = 'rsd_xml';
808 $backends[] = 'salmon';
809 $backends[] = 'statistics_json';
812 // Check if current module is in backend or backend flag is set
813 return (in_array($this->module, $backends) || $this->backend);
817 * @brief Checks if the maximum number of database processes is reached
819 * @return bool Is the limit reached?
821 function max_processes_reached() {
822 // Deactivated, needs more investigating if this check really makes sense
825 if ($this->is_backend()) {
826 $process = 'backend';
827 $max_processes = Config::get('system', 'max_processes_backend');
828 if (intval($max_processes) == 0) {
832 $process = 'frontend';
833 $max_processes = Config::get('system', 'max_processes_frontend');
834 if (intval($max_processes) == 0) {
839 $processlist = dbm::processlist();
840 if ($processlist['list'] != '') {
841 logger('Processcheck: Processes: ' . $processlist['amount'] . ' - Processlist: ' . $processlist['list'], LOGGER_DEBUG);
843 if ($processlist['amount'] > $max_processes) {
844 logger('Processcheck: Maximum number of processes for ' . $process . ' tasks (' . $max_processes . ') reached.', LOGGER_DEBUG);
852 * @brief Checks if the minimal memory is reached
854 * @return bool Is the memory limit reached?
856 public function min_memory_reached() {
857 $min_memory = Config::get('system', 'min_memory', 0);
858 if ($min_memory == 0) {
862 if (!is_readable('/proc/meminfo')) {
866 $memdata = explode("\n", file_get_contents('/proc/meminfo'));
869 foreach ($memdata as $line) {
870 list($key, $val) = explode(':', $line);
871 $meminfo[$key] = (int) trim(str_replace('kB', '', $val));
872 $meminfo[$key] = (int) ($meminfo[$key] / 1024);
875 if (!isset($meminfo['MemAvailable']) || ! isset($meminfo['MemFree'])) {
879 $free = $meminfo['MemAvailable'] + $meminfo['MemFree'];
881 $reached = ($free < $min_memory);
884 logger('Minimal memory reached: ' . $free . '/' . $meminfo['MemTotal'] . ' - limit ' . $min_memory, LOGGER_DEBUG);
891 * @brief Checks if the maximum load is reached
893 * @return bool Is the load reached?
895 function maxload_reached() {
897 if ($this->is_backend()) {
898 $process = 'backend';
899 $maxsysload = intval(Config::get('system', 'maxloadavg'));
900 if ($maxsysload < 1) {
904 $process = 'frontend';
905 $maxsysload = intval(Config::get('system', 'maxloadavg_frontend'));
906 if ($maxsysload < 1) {
911 $load = current_load();
913 if (intval($load) > $maxsysload) {
914 logger('system: load ' . $load . ' for ' . $process . ' tasks (' . $maxsysload . ') too high.');
921 function proc_run($args) {
923 if (!function_exists('proc_open')) {
927 // If the last worker fork was less than 2 seconds before then don't fork another one.
928 // This should prevent the forking of masses of workers.
929 $cachekey = 'app:proc_run:started';
930 $result = Cache::get($cachekey);
932 if (!is_null($result) && ( time() - $result) < 2) {
936 // Set the timestamp of the last proc_run
937 Cache::set($cachekey, time(), CACHE_MINUTE);
939 array_unshift($args, ((x($this->config, 'php_path')) && (strlen($this->config['php_path'])) ? $this->config['php_path'] : 'php'));
941 // add baseurl to args. cli scripts can't construct it
942 $args[] = $this->get_baseurl();
944 for ($x = 0; $x < count($args); $x ++) {
945 $args[$x] = escapeshellarg($args[$x]);
948 $cmdline = implode($args, ' ');
950 if ($this->min_memory_reached()) {
954 if (Config::get('system', 'proc_windows')) {
955 $resource = proc_open('cmd /c start /b ' . $cmdline, array(), $foo, $this->get_basepath());
957 $resource = proc_open($cmdline . ' &', array(), $foo, $this->get_basepath());
959 if (!is_resource($resource)) {
960 logger('We got no resource for command ' . $cmdline, LOGGER_DEBUG);
963 proc_close($resource);
967 * @brief Returns the system user that is executing the script
969 * This mostly returns something like "www-data".
971 * @return string system username
973 static function systemuser() {
974 if (!function_exists('posix_getpwuid') || ! function_exists('posix_geteuid')) {
978 $processUser = posix_getpwuid(posix_geteuid());
979 return $processUser['name'];
983 * @brief Checks if a given directory is usable for the system
985 * @return boolean the directory is usable
987 static function directory_usable($directory, $check_writable = true) {
988 if ($directory == '') {
989 logger('Directory is empty. This shouldn\'t happen.', LOGGER_DEBUG);
993 if (!file_exists($directory)) {
994 logger('Path "' . $directory . '" does not exist for user ' . self::systemuser(), LOGGER_DEBUG);
997 if (is_file($directory)) {
998 logger('Path "' . $directory . '" is a file for user ' . self::systemuser(), LOGGER_DEBUG);
1001 if (!is_dir($directory)) {
1002 logger('Path "' . $directory . '" is not a directory for user ' . self::systemuser(), LOGGER_DEBUG);
1005 if ($check_writable && !is_writable($directory)) {
1006 logger('Path "' . $directory . '" is not writable for user ' . self::systemuser(), LOGGER_DEBUG);