From 6685b908eeeed8c78c4b86b6f6443463bf1a87fe Mon Sep 17 00:00:00 2001 From: Nicolas Boisselier Date: Wed, 31 Aug 2016 02:07:42 +0100 Subject: [PATCH] user_infos --- lib/php/nb.php | 79 +++++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 75 insertions(+), 4 deletions(-) diff --git a/lib/php/nb.php b/lib/php/nb.php index 76703ca2..8a13dae9 100644 --- a/lib/php/nb.php +++ b/lib/php/nb.php @@ -597,13 +597,84 @@ class NB { } public static function untilde($path) { - if (!function_exists('posix_getuid')) return $path; - return preg_replace_callback('/^(~)(\w+)?/',function($m){ + #if (!function_exists('posix_getuid')) return $path; + return preg_replace_callback('/^(~)([\w_-]+)?/',function($m){ - if (!empty($m[2])) return str_replace($m[1].$m[2],posix_getpwnam($m[2])['dir'],$m[0]); + $user = empty($m[2]) ? '' : $m[2]; + $infos = self::user_infos($user); - return str_replace($m[1],posix_getpwuid(posix_getuid())['dir'],$m[0]); + if (empty($infos)) return $path; + + return preg_replace("/^~".($user ? $infos['name'] : '')."/",$infos['dir'],$m[0]); },$path); } + + public static function user_infos($user=null,$key=''){ + + if ($user === null) $user = ''; + if ($key === null) $key = ''; + $infos = []; + + # Linux standard + if (function_exists('posix_getuid')) { + if ($user==='') $user = posix_getuid(); + if (preg_match('/^\d+$/',$user)) $infos = posix_getpwuid($user); + else $infos = posix_getpwnam($user); + } + + # /etc/passwd + if (!$infos + and $user !== '' + and self::osname()!='darwin' + and is_readable('/etc/passwd') + and $handle = fopen("/etc/passwd", "r") + ) { + $i = preg_match('/^\d+$/',$user) ? 2 : 0; # uid or name + + while (($line = fgets($handle)) !== false) { + // process the line read. + $line = explode(':',$line); + if ($user != $line[$i]) continue; + $infos = [ + 'name' => $line[0], + 'uid' => $line[2], + 'gid' => $line[3], + 'dir' => $line[5], + ]; + break; + #if ($user == (int)$user) + } + fclose($handle); + } + + # Command + if (!$infos) { + $cmd = $user === '' ? 'id' : sprintf('id %s',$user); + $line = []; exec(escapeshellcmd($user === '' ? 'id' : 'id '.escapeshellarg($user)).' 2>/dev/null',$line); + if ($line and preg_match('/uid=(\d+)\((\S+)\) gid=(\d+)\((\S+)\)/',$line[0],$infos)) { + array_shift($infos); + $infos = [ + 'name' => $infos[1], + 'uid' => $infos[0], + 'gid' => $infos[2], + '_group' => $infos[3], + ]; + } + } + + if ((!$key or $key == 'dir') and empty($infos['dir']) and !empty($infos['name'])) { + $line = []; exec("echo ~".($infos['name']),$line); + $infos['dir'] = $line[0]; + #debug ( `echo ~$cmd` ); + } + + if ($key) return (empty($infos[$key]) ? '' : $infos[$key] ); + return $infos; + } + + public static function osname(){ + return strtolower(php_uname('s')); + return strtolower(preg_replace('/\s+.*$/','', php_uname())); + } } # < Class ?> -- 2.47.3