/** * {@inheritdoc} */ protected function failureDescription($other) { if (!is_string($other)) { if (is_object($other)) { $type = sprintf('%s#%s', get_class($other), method_exists($other, '__toString') ? $other->__toString() : ''); } elseif (null === $other) { $type = 'null'; } else { $type = gettype($other) . '#' . $other; } return $type . ' ' . $this->toString(); } if (!file_exists($other)) { return 'not file or directory#' . $other . ' ' . $this->toString(); } if (is_link($other)) { $type = 'link'; $perms = lstat($other); $perms = $perms['mode']; } else { $type = is_file($other) ? 'file' : (is_dir($other) ? 'directory' : 'other'); $perms = fileperms($other); } return sprintf('%s#%s %o %s %o', $type, $other, $perms, $this->toString(), $this->mask); }
public function getRuntimeDir($strict = true) { if ($runtimeDir = getenv('XDG_RUNTIME_DIR')) { return $runtimeDir; } if ($strict) { throw new \RuntimeException('XDG_RUNTIME_DIR was not set'); } $fallback = sys_get_temp_dir() . DIRECTORY_SEPARATOR . self::RUNTIME_DIR_FALLBACK . getenv('USER'); $create = false; if (!is_dir($fallback)) { mkdir($fallback, 0700, true); } $st = lstat($fallback); # The fallback must be a directory if (!$st['mode'] & self::S_IFDIR) { rmdir($fallback); $create = true; } elseif ($st['uid'] != getmyuid() || $st['mode'] & (self::S_IRWXG | self::S_IRWXO)) { rmdir($fallback); $create = true; } if ($create) { mkdir($fallback, 0700, true); } return $fallback; }
public function __construct() { parent::__construct('filePermissions', function ($string) { if (is_string($string)) { if (ctype_digit($string)) { $permissions = octdec($string); } elseif (is_link($string)) { $permissions = lstat($string)['mode']; } elseif (file_exists($string)) { $permissions = fileperms($string); } else { throw new \Twig_Error_Runtime(sprintf('Cannot determine permissions for "%s".', $string)); } } else { $permissions = octdec($string); } if (($permissions & 0xc000) === 0xc000) { // Socket $info = 's'; } elseif (($permissions & 0xa000) === 0xa000) { // Symbolic Link $info = 'l'; } elseif (($permissions & 0x8000) === 0x8000) { // Regular $info = '-'; } elseif (($permissions & 0x6000) === 0x6000) { // Block special $info = 'b'; } elseif (($permissions & 0x4000) === 0x4000) { // Directory $info = 'd'; } elseif (($permissions & 0x2000) === 0x2000) { // Character special $info = 'c'; } elseif (($permissions & 0x1000) === 0x1000) { // FIFO pipe $info = 'p'; } else { // Unknown $info = 'u'; } // Owner $info .= $permissions & 0x100 ? 'r' : '-'; $info .= $permissions & 0x80 ? 'w' : '-'; $info .= $permissions & 0x40 ? $permissions & 0x800 ? 's' : 'x' : ($permissions & 0x800 ? 'S' : '-'); // Group $info .= $permissions & 0x20 ? 'r' : '-'; $info .= $permissions & 0x10 ? 'w' : '-'; $info .= $permissions & 0x8 ? $permissions & 0x400 ? 's' : 'x' : ($permissions & 0x400 ? 'S' : '-'); // World $info .= $permissions & 0x4 ? 'r' : '-'; $info .= $permissions & 0x2 ? 'w' : '-'; $info .= $permissions & 0x1 ? $permissions & 0x200 ? 't' : 'x' : ($permissions & 0x200 ? 'T' : '-'); return $info; }); }
function buildDirModel($dir, $model, $rootname, $user_id, $db) { ##Remove from $dir to output the part until s3db root; $dirFiles = scandir($dir); #echo '<pre>';print_r($dirFiles);exit; #foreach ($dirFiles as $ind) for ($i = 0; $i < count($dirFiles); $i++) { $ind = $dirFiles[$i]; if (is_file($dir . '/' . $ind) && !ereg('^(s3id|config.inc.php|treeitem.*.js|.*.tmp|.*[0-9]{8}$)', $ind)) { $fstat = lstat($dir . '/' . $ind); $lastModified = date('Y-m-d H:i:s', $fstat['mtime']); $path = str_replace($rootname, '', $dir); $path = $path == '' ? $ind : substr($path, 1, strlen($path)) . '/' . $ind; $path = addslashes($path); ### #Is there an item with this path value on path rule? #$item_id = findFileItemId($path,$user_id,$db); ### #Find the statement_id of this file on the local s3db $allFileIds = @file_get_contents('fileIds.tmp'); $allFileIds = @unserialize($allFileIds); $file_id = @array_search($path, $allFileIds); if ($file_id == '') { echo "Finding ID of file " . $path . chr(10); $sql = "select statement_id from s3db_statement where rule_id = '" . $GLOBALS['update_project']['file']['rule_id'] . "' and file_name = '" . $path . "' order by created_on desc limit 1"; $db->query($sql, __LINE__, __FILE__); if ($db->next_record()) { $file_id = $db->f('statement_id'); $allFileIds[$file_id] = $path; } } if ($file_id == '') { $updated = fileUpdate($path, $user_id, $db); $file_id = $updated; } if ($file_id != '') { file_put_contents('fileIds.tmp', serialize($allFileIds)); echo "writting item " . $path . " " . $file_id . chr(10); $subjResources = new Resource($GLOBALS['s3db_info']['deployment']['URI'] . 's3dbfiles.php?file_id=' . $file_id); $statement = new Statement($subjResources, new Resource('http://purl.org/dc/elements/1.1/date'), new Literal($lastModified)); $path = new Statement($subjResources, new Resource('http://s3db.org/scripts'), new Literal($path)); $model->add($statement); $model->add($path); } else { @file_put_contents('update_error_log.txt', "Could not find a file_id for " . $path . chr(10)); } } elseif (is_dir($dir . '/' . $ind) && !ereg('^(.|..|extras)$', $ind)) { $newDir = $dir . '/' . $ind; $submodel = ModelFactory::getDefaultModel(); $submodel = buildDirModel($newDir, $submodel, $rootname, $user_id, $db); $model->addModel($submodel); } } return $model; }
/** * @param $real_path * @param $new_path * @return bool */ protected function writeHeader($real_path, $new_path) { if (strlen($new_path) > 99) { $this->writeLongHeader($new_path); } $v_info = lstat($real_path); $v_uid = sprintf("%6s ", DecOct($v_info[4])); $v_gid = sprintf("%6s ", DecOct($v_info[5])); $v_perms = sprintf("%6s ", DecOct($v_info['mode'])); $v_mtime = sprintf("%11s", DecOct($v_info['mtime'])); $v_linkname = ''; if (@is_link($real_path)) { $v_typeflag = '2'; $v_linkname = readlink($real_path); $v_size = sprintf("%11s ", DecOct(0)); } elseif (@is_dir($real_path)) { $v_typeflag = "5"; $v_size = sprintf("%11s ", DecOct(0)); } else { $v_typeflag = ''; clearstatcache(TRUE, $real_path); $v_size = sprintf("%11s ", DecOct($v_info['size'])); } $v_magic = ''; $v_version = ''; $v_uname = ''; $v_gname = ''; $v_devmajor = ''; $v_devminor = ''; $v_prefix = ''; $v_binary_data_first = pack("a100a8a8a8a12A12", $new_path, $v_perms, $v_uid, $v_gid, $v_size, $v_mtime); $v_binary_data_last = pack("a1a100a6a2a32a32a8a8a155a12", $v_typeflag, $v_linkname, $v_magic, $v_version, $v_uname, $v_gname, $v_devmajor, $v_devminor, $v_prefix, ''); // ----- Calculate the checksum $v_checksum = 0; // ..... First part of the header for ($i = 0; $i < 148; $i++) { $v_checksum += ord(substr($v_binary_data_first, $i, 1)); } // ..... Ignore the checksum value and replace it by ' ' (space) for ($i = 148; $i < 156; $i++) { $v_checksum += ord(' '); } // ..... Last part of the header for ($i = 156, $j = 0; $i < 512; $i++, $j++) { $v_checksum += ord(substr($v_binary_data_last, $j, 1)); } // ----- Write the first 148 bytes of the header in the archive $this->archive->write($v_binary_data_first, 148); // ----- Write the calculated checksum $v_checksum = sprintf("%6s ", DecOct($v_checksum)); $v_binary_data = pack("a8", $v_checksum); $this->archive->write($v_binary_data, 8); // ----- Write the last 356 bytes of the header in the archive $this->archive->write($v_binary_data_last, 356); }
/** * {@inheritdoc} */ public function lstat($path) { if ($stat = @\lstat($path)) { $stat["isfile"] = (bool) \is_file($path); $stat["isdir"] = empty($stat["isfile"]); \clearstatcache(true, $path); } else { $stat = null; } return new Success($stat); }
/** * Manage log file. * * @param string $filePath * @param string $callStart * @param string $resource * @param string $duration */ protected function writeLog($filePath, $callStart, $resource, $duration) { $log = fopen($filePath, "a+"); clearstatcache(); $fileStats = lstat($filePath); if ($fileStats && 0 === $fileStats['size']) { fwrite($log, "datetime;soap_call_resource;duration (s)\n"); } fwrite($log, sprintf("%s;%s;%s\n", $callStart, $resource, $duration)); fclose($log); }
function httpfs_getattr($data) { $path = explode("", $data, 2)[0]; $s = lstat($path); if ($s) { dump_ok(); echo pack('NNNNNNNNNNNNN', $s['dev'], $s['ino'], $s['mode'], $s['nlink'], $s['uid'], $s['gid'], $s['rdev'], $s['size'], $s['atime'], $s['mtime'], $s['ctime'], $s['blksize'], $s['blocks']); } else { dump_error(ENTRY_NOT_FOUND); } }
/** * This function retrieves the path to a directory where temporary files can be saved. * * @return string Path to a temporary directory, without a trailing directory separator. * @throws \SimpleSAML_Error_Exception If the temporary directory cannot be created or it exists and does not belong * to the current user. * * @author Andreas Solberg, UNINETT AS <*****@*****.**> * @author Olav Morken, UNINETT AS <*****@*****.**> * @author Jaime Perez, UNINETT AS <*****@*****.**> */ public static function getTempDir() { $globalConfig = \SimpleSAML_Configuration::getInstance(); $tempDir = rtrim($globalConfig->getString('tempdir', sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'simplesaml'), DIRECTORY_SEPARATOR); if (!is_dir($tempDir)) { if (!mkdir($tempDir, 0700, true)) { $error = error_get_last(); throw new \SimpleSAML_Error_Exception('Error creating temporary directory "' . $tempDir . '": ' . $error['message']); } } elseif (function_exists('posix_getuid')) { // check that the owner of the temp directory is the current user $stat = lstat($tempDir); if ($stat['uid'] !== posix_getuid()) { throw new \SimpleSAML_Error_Exception('Temporary directory "' . $tempDir . '" does not belong to the current user.'); } } return $tempDir; }
/** * Gives information about a file * * Stat from regular file (stat()) and symbolic link (lstat()) * * @param string $findkey Find a key from stat value as 'dev' * @return array|string */ public function getStatRaw($findkey = '') { if (is_link($this->source)) { if ($findkey !== '') { $stat = lstat($this->source); return $stat[$findkey]; } if ($findkey === '') { return lstat($this->source); } else { $stat = lstat($this->source); if ($stat) { foreach (array_keys($stat) as $key) { if (is_string($key)) { $statResponse[$key] = $stat[$key]; } } return $statResponse; } return $stat; } } if (file_exists($this->source) || is_dir($this->source)) { if ($findkey !== '') { $stat = stat($this->source); return $stat[$findkey]; } if ($findkey === '') { return stat($this->source); } else { $stat = stat($this->source); if ($stat) { foreach (array_keys($stat) as $key) { if (is_string($key)) { $statResponse[$key] = $stat[$key]; } } return $statResponse; } return $stat; } } return false; }
/** * Print report header * * @param array $targets List of target directories * @param array $argv Command line arguments */ public function header($targets, $argv) { $header = !empty($this->format) ? $this->getRowFormatHeader($this->format) : $this->getRowHeader(); echo "date: " . date('r (U)') . "\n"; echo "getenv(TZ): " . getenv('TZ') . "\n"; echo "date_default_timezone_get: " . date_default_timezone_get() . "\n"; if (defined('DIRSCAN_VERSION')) { echo "dirscan version: " . DIRSCAN_VERSION . "\n"; } echo "php version: " . phpversion() . "\n"; echo "uname: " . php_uname() . "\n"; echo "cwd: " . getcwd() . "\n"; echo "settings: " . json_encode($this->settings) . "\n"; echo "argv: " . json_encode($argv) . "\n"; echo "target" . (count($targets) > 1 ? "s" : "") . ": " . "\n"; foreach ($targets as $key => $target) { $targetStat = lstat($target); $targetStat['realpath'] = realpath($target); echo sprintf(" - %s (realpath: %s, device: %s)\n", $target, $targetStat['realpath'], $targetStat['dev']); } echo "=====================================\n"; echo implode("\t", $header) . "\n"; }
public function cached() { // Check for non-existant cache file if (!file_exists('data/cache/language_registry')) { return false; } // Get directory modification date clearstatcache(); $dir_modified = array_element(lstat('./locale/'), 9); // Get cache modification date clearstatcache(); $cache_modified = array_element(lstat('data/cache/language_registry'), 9); // If the cache is older than the directory if ($cache_modified < $dir_modified) { //print "rebuild<br/>\n"; // Rebuild cache return false; } else { // Otherwise cache is up to date //print "fine<br/>\n"; return true; } }
function getdirfiles($dir, $exts) { $path = $_SERVER['DOCUMENT_ROOT']; $path = PathBckSlash($path); $result = array(); if (is_dir($path . $dir)) { $dp = dir($path . $dir); while (($file = $dp->read()) !== false) { if ($file != '.' && $file != '..') { if (!is_dir($path . $dir . "/" . $file)) { if (in_array(strtolower(pathinfo($file, PATHINFO_EXTENSION)), $exts)) { $fpropert = lstat($path . $dir . "/" . $file); if ($fpropert) { $result[] = array("fname" => $file, "url" => $dir . "/" . $file, "ctime" => date("Y-m-d H:i:s", $fpropert[10]), "size" => round($fpropert[7] / 1024) . "k"); } } } } } $dp->close(); } return $result; }
function buildDirModel($dir, $model, $rootname) { ##Remove from $dir to output the part until s3db root; $dirFiles = scandir($dir); foreach ($dirFiles as $ind) { if (is_file($dir . '/' . $ind) && !ereg('^(s3id|config.inc.php|treeitem.*.js)', $ind)) { $fstat = lstat($dir . '/' . $ind); $lastModified = date('Y-m-d H:i:s', $fstat['mtime']); $path = str_replace($rootname, '', $dir); $path = $path == '' ? $ind : substr($path, 1, strlen($path)) . '/' . $ind; $subjResources = new Resource('http://www.s3db.org/central/s3dbfiles.php?file=' . $path); $statement = new Statement($subjResources, new Resource('http://purl.org/dc/elements/1.1/date'), new Literal($lastModified)); $path = new Statement($subjResources, new Resource('http://s3db.org/scripts'), new Literal($path)); $model->add($statement); $model->add($path); } elseif (is_dir($dir . '/' . $ind) && !ereg('^(.|..|extras)$', $ind)) { $newDir = $dir . '/' . $ind; $submodel = ModelFactory::getDefaultModel(); $submodel = buildDirModel($newDir, $submodel, $rootname); $model->addModel($submodel); } } return $model; }
/** * Return stat for given path. * Stat contains following fields: * - (int) size file size in b. required * - (int) ts file modification time in unix time. required * - (string) mime mimetype. required for folders, others - optionally * - (bool) read read permissions. required * - (bool) write write permissions. required * - (bool) locked is object locked. optionally * - (bool) hidden is object hidden. optionally * - (string) alias for symlinks - link target path relative to root path. optionally * - (string) target for symlinks - link target path. optionally * * If file does not exists - returns empty array or false. * * @param string $path file path * @return array|false * @author Dmitry (dio) Levashov **/ protected function _stat($path) { $stat = array(); if (!file_exists($path)) { return $stat; } //Verifies the given path is the root or is inside the root. Prevents directory traveral. if (!$this->aroot) { // for Inheritance class ( not calling parent::configure() ) $this->aroot = realpath($this->root); } if (!$this->_inpath($path, $this->aroot)) { return $stat; } if ($path != $this->root && is_link($path)) { if (($target = $this->readlink($path)) == false || $target == $path) { $stat['mime'] = 'symlink-broken'; $stat['read'] = false; $stat['write'] = false; $stat['size'] = 0; return $stat; } $stat['alias'] = $this->_path($target); $stat['target'] = $target; $path = $target; $lstat = lstat($path); $size = $lstat['size']; } else { $size = @filesize($path); } $dir = is_dir($path); $stat['mime'] = $dir ? 'directory' : $this->mimetype($path); $stat['ts'] = filemtime($path); $stat['read'] = is_readable($path); $stat['write'] = is_writable($path); if ($stat['read']) { $stat['size'] = $dir ? 0 : $size; } return $stat; }
/** * Return stat for given path. * Stat contains following fields: * - (int) size file size in b. required * - (int) ts file modification time in unix time. required * - (string) mime mimetype. required for folders, others - optionally * - (bool) read read permissions. required * - (bool) write write permissions. required * - (bool) locked is object locked. optionally * - (bool) hidden is object hidden. optionally * - (string) alias for symlinks - link target path relative to root path. optionally * - (string) target for symlinks - link target path. optionally * * If file does not exists - returns empty array or false. * * @param string $path file path * @return array|false * @author Dmitry (dio) Levashov **/ protected function _stat($path) { $stat = array(); if (!file_exists($path)) { return $stat; } if ($path != $this->root && is_link($path)) { if (($target = $this->readlink($path)) == false || $target == $path) { $stat['mime'] = 'symlink-broken'; $stat['read'] = false; $stat['write'] = false; $stat['size'] = 0; return $stat; } $stat['alias'] = $this->_path($target); $stat['target'] = $target; $path = $target; $lstat = lstat($path); $size = $lstat['size']; } else { $size = @filesize($path); } $dir = is_dir($path); $stat['mime'] = $dir ? 'directory' : $this->mimetype($path); $stat['ts'] = filemtime($path); $stat['read'] = is_readable($path); $stat['write'] = is_writable($path); if ($stat['read']) { $stat['size'] = $dir ? 0 : $size; } return $stat; }
/** * Tests Fs_Node->getAttribute() getting posix info * this test is not so good because owner of the symlink is the same as the owner of the file */ public function testGetAttribute_lstat_Posix() { $stat = lstat($this->file); $userinfo = extension_loaded('posix') && ($info = posix_getpwuid($stat['uid'])) ? $info['name'] : $stat['uid']; $groupinfo = extension_loaded('posix') && ($info = posix_getgrgid($stat['gid'])) ? $info['name'] : $stat['gid']; $this->assertEquals($userinfo, $this->Fs_Node->getAttribute('owner', Fs::NO_DEREFERENCE), 'owner'); $this->assertEquals($groupinfo, $this->Fs_Node->getAttribute('group', Fs::NO_DEREFERENCE), 'group'); }
public function getURLLastModified($url, $symlink, $bucket) { $this->clearstatcache(); if (!$this->fileExists($symlink)) { return array('time' => 0, 'revalidate' => true, 'cache_age' => 0); } $symlinkAbs = $this->absolutize($symlink); $stat = lstat($symlinkAbs); $now = time(); if (readlink($symlinkAbs) == '/dev/null') { $failed_time = $now - $stat['mtime']; if ($failed_time > binarypool_config::getBadUrlExpiry()) { unlink($symlinkAbs); return array('time' => 0, 'revalidate' => true, 'cache_age' => $failed_time); } $failed_nextfetch = $stat['mtime'] + binarypool_config::getBadUrlExpiry() - $now; throw new binarypool_exception(122, 400, "File download failed {$failed_time} seconds ago. Re-fetching allowed in next time in {$failed_nextfetch} seconds: {$url}"); } $cache_age = $now - $stat['mtime']; $revalidate = false; if ($cache_age > binarypool_config::getCacheRevalidate($bucket)) { $revalidate = true; } return array('time' => filemtime($symlinkAbs), 'revalidate' => $revalidate, 'cache_age' => $cache_age); }
protected function _lstat($vd6fe1d0be6347b8ef2427fa629c04485) { return lstat($vd6fe1d0be6347b8ef2427fa629c04485); }
function _writeHeader($p_filename, $p_stored_filename) { if ($p_stored_filename == '') { $p_stored_filename = $p_filename; } $v_reduce_filename = $this->_pathReduction($p_stored_filename); if (strlen($v_reduce_filename) > 99) { if (!$this->_writeLongHeader($v_reduce_filename)) { return false; } } $v_info = lstat($p_filename); $v_uid = sprintf("%07s", DecOct($v_info[4])); $v_gid = sprintf("%07s", DecOct($v_info[5])); $v_perms = sprintf("%07s", DecOct($v_info['mode'] & 0777)); $v_mtime = sprintf("%011s", DecOct($v_info['mtime'])); $v_linkname = ''; if (@is_link($p_filename)) { $v_typeflag = '2'; $v_linkname = readlink($p_filename); $v_size = sprintf("%011s", DecOct(0)); } elseif (@is_dir($p_filename)) { $v_typeflag = "5"; $v_size = sprintf("%011s", DecOct(0)); } else { $v_typeflag = '0'; clearstatcache(); $v_size = sprintf("%011s", DecOct($v_info['size'])); } $v_magic = 'ustar '; $v_version = ' '; if (function_exists('posix_getpwuid')) { $userinfo = posix_getpwuid($v_info[4]); $groupinfo = posix_getgrgid($v_info[5]); $v_uname = $userinfo['name']; $v_gname = $groupinfo['name']; } else { $v_uname = ''; $v_gname = ''; } $v_devmajor = ''; $v_devminor = ''; $v_prefix = ''; $v_binary_data_first = pack("a100a8a8a8a12a12", $v_reduce_filename, $v_perms, $v_uid, $v_gid, $v_size, $v_mtime); $v_binary_data_last = pack("a1a100a6a2a32a32a8a8a155a12", $v_typeflag, $v_linkname, $v_magic, $v_version, $v_uname, $v_gname, $v_devmajor, $v_devminor, $v_prefix, ''); // ----- Calculate the checksum $v_checksum = 0; // ..... First part of the header for ($i = 0; $i < 148; $i++) { $v_checksum += ord(substr($v_binary_data_first, $i, 1)); } // ..... Ignore the checksum value and replace it by ' ' (space) for ($i = 148; $i < 156; $i++) { $v_checksum += ord(' '); } // ..... Last part of the header for ($i = 156, $j = 0; $i < 512; $i++, $j++) { $v_checksum += ord(substr($v_binary_data_last, $j, 1)); } // ----- Write the first 148 bytes of the header in the archive $this->_writeBlock($v_binary_data_first, 148); // ----- Write the calculated checksum $v_checksum = sprintf("%06s ", DecOct($v_checksum)); $v_binary_data = pack("a8", $v_checksum); $this->_writeBlock($v_binary_data, 8); // ----- Write the last 356 bytes of the header in the archive $this->_writeBlock($v_binary_data_last, 356); return true; }
/** * Returns size and creation time of the given file. * * @param array $file The file. * * @return mixed size and ctime of the file if file is valid, null else; */ public static function getInfosFromFile($file) { if (self::_isValidFileHash($file['md5'])) { $stat = lstat(self::_absoluteFilePathFromHash($file['md5'])); return array("size" => $stat['size'], "ctime" => $stat['ctime']); } return null; }
/** * Get temp directory path. * * This function retrieves the path to a directory where * temporary files can be saved. * * @return string Path to temp directory, without a trailing '/'. */ public static function getTempDir() { $globalConfig = SimpleSAML_Configuration::getInstance(); $tempDir = $globalConfig->getString('tempdir', '/tmp/simplesaml'); while (substr($tempDir, -1) === '/') { $tempDir = substr($tempDir, 0, -1); } if (!is_dir($tempDir)) { $ret = mkdir($tempDir, 0700, TRUE); if (!$ret) { throw new SimpleSAML_Error_Exception('Error creating temp dir ' . var_export($tempDir, TRUE) . ': ' . SimpleSAML_Utilities::getLastError()); } } elseif (function_exists('posix_getuid')) { /* Check that the owner of the temp diretory is the current user. */ $stat = lstat($tempDir); if ($stat['uid'] !== posix_getuid()) { throw new SimpleSAML_Error_Exception('Temp directory (' . var_export($tempDir, TRUE) . ') not owned by current user.'); } } return $tempDir; }
function saveCacheFile($file, $contents) { $len = strlen($contents); $cachefile_fp = @fopen($file, 'xb'); // x is the O_CREAT|O_EXCL mode if ($cachefile_fp !== false) { // create file if (fwrite($cachefile_fp, $contents, $len) < $len) { fclose($cachefile_fp); return PEAR::raiseError("Could not write {$file}."); } } else { // update file $cachefile_lstat = lstat($file); $cachefile_fp = @fopen($file, 'wb'); if (!$cachefile_fp) { return PEAR::raiseError("Could not open {$file} for writing."); } $cachefile_fstat = fstat($cachefile_fp); if ($cachefile_lstat['mode'] == $cachefile_fstat['mode'] && $cachefile_lstat['ino'] == $cachefile_fstat['ino'] && $cachefile_lstat['dev'] == $cachefile_fstat['dev'] && $cachefile_fstat['nlink'] === 1) { if (fwrite($cachefile_fp, $contents, $len) < $len) { fclose($cachefile_fp); return PEAR::raiseError("Could not write {$file}."); } } else { fclose($cachefile_fp); $link = function_exists('readlink') ? readlink($file) : $file; return PEAR::raiseError('SECURITY ERROR: Will not write to ' . $file . ' as it is symlinked to ' . $link . ' - Possible symlink attack'); } } fclose($cachefile_fp); return true; }
/** * @depends testOpensStreams */ public function testDoesNotRaiseErrorForMissingFile() { self::log('Testing invalid file'); $this->assertFalse(is_file('s3://ewfwefwfeweff/' . uniqid('foo'))); $this->assertFalse(is_link('s3://ewfwefwfeweff/' . uniqid('foo'))); try { lstat('s3://ewfwefwfeweff/' . uniqid('foo')); $this->fail('Did not trigger a warning'); } catch (\PHPUnit_Framework_Error_Warning $e) { } }
################################################################################## if (is_readable(getcwd())) { if ($h = opendir(getcwd())) { $arr = array(); while (false !== ($f = readdir($h))) { array_push($arr, $f); } closedir($h); } } else { die("<center>" . b(font('red', 'FUNCTION LIST PERMISSION DENIED', 6)) . "</center>"); } sort($arr); echo '<table width=800 bgcolor=#DFD6C8 cellspacing=0 cellpadding=0 border=1>'; foreach ($arr as $f) { $l = @lstat($f); print is_readable($f) && is_writeable($f) ? "<tr><td>" . w(1) . b("R" . w(1) . font('red', 'RW', 3)) . w(1) : (is_readable($f) ? "<tr><td>" . w(1) . b("R") . w(4) : "") . (is_writable($f) ? "<tr><td>" . w(1) . b(font('red', 'RW', 3)) : ""); $r = sprintf("%o", @fileperms($f) & 0777); $ow = posix_getpwuid($l[4]); $gr = posix_getgrgid($l[5]); $fow = ($ow["name"] ? $ow["name"] : fileowner($f)) . "/" . ($gr["name"] ? $gr["name"] : filegroup($f)); if (!is_readable($f) && !is_writeable($f)) { echo "<tr><td>" . w(12); } echo "</td><td>{$r}</td><td>{$fow}</td>"; if (!is_dir($f)) { if (!is_link($f)) { echo w(2) . "<td><i>" . $l[7] . "</i></td>"; } else { echo "</td><td>link</td>"; }
function ls($curpath) { global $_lang; global $excludes, $editablefiles, $inlineviewablefiles, $viewablefiles, $enablefileunzip, $enablefiledownload, $uploadablefiles, $folders, $files, $filesizes, $len, $dirs_array, $files_array, $webstart_path, $manager_theme, $modx; $dircounter = 0; $filecounter = 0; $curpath = str_replace('//', '/', $curpath . '/'); if (!is_dir($curpath)) { echo 'Invalid path "', $curpath, '"<br />'; return; } $dir = dir($curpath); // first, get info while ($file = $dir->read()) { if (!in_array($file, $excludes)) { $newpath = $curpath . $file; if (is_dir($newpath)) { $dirs_array[$dircounter]['dir'] = $newpath; $dirs_array[$dircounter]['stats'] = lstat($newpath); $dirs_array[$dircounter]['text'] = '<img src="media/style/' . $manager_theme . 'images/tree/folder.gif" border="0" align="absmiddle" alt="" /> <a href="index.php?a=31&mode=drill&path=' . urlencode($newpath) . '"><b>' . $file . '</b></a>'; $dirs_array[$dircounter]['delete'] = is_writable($curpath) ? '<span style="width:20px"><a href="javascript: deleteFolder(\'' . urlencode($curpath) . '\', \'' . urlencode($newpath) . '\');"><img src="media/style/' . $manager_theme . 'images/icons/delete.gif" alt="' . $_lang['file_delete_folder'] . '" title="' . $_lang['file_delete_folder'] . '" /></a></span>' : ''; // increment the counter $dircounter++; } else { $type = getExtension($newpath); $files_array[$filecounter]['file'] = $newpath; $files_array[$filecounter]['stats'] = lstat($newpath); $files_array[$filecounter]['text'] = '<img src="media/style/' . $manager_theme . 'images/tree/page-html.gif" border="0" align="absmiddle" alt="" />' . $file; $files_array[$filecounter]['view'] = in_array($type, $viewablefiles) ? '<span style="cursor:pointer; width:20px;" onclick="viewfile(\'' . $webstart_path . substr($newpath, $len, strlen($newpath)) . '\');"><img src="media/style/' . $manager_theme . 'images/icons/context_view.gif" border="0" align="absmiddle" alt="' . $_lang['files_viewfile'] . '" title="' . $_lang['files_viewfile'] . '" /></span>' : ($enablefiledownload && in_array($type, $uploadablefiles) ? '<a href="' . $webstart_path . implode('/', array_map('rawurlencode', explode('/', substr($newpath, $len, strlen($newpath))))) . '" style="cursor:pointer; width:20px;"><img src="media/style/' . $manager_theme . 'images/misc/ed_save.gif" border="0" align="absmiddle" alt="' . $_lang['file_download_file'] . '" title="' . $_lang['file_download_file'] . '" /></a>' : '<span class="disabledImage"><img src="media/style/' . $manager_theme . 'images/icons/context_view.gif" border="0" align="absmiddle" alt="' . $_lang['files_viewfile'] . '" title="' . $_lang['files_viewfile'] . '" /></span>'); $files_array[$filecounter]['view'] = in_array($type, $inlineviewablefiles) ? '<span style="width:20px;"><a href="index.php?a=31&mode=view&path=' . urlencode($newpath) . '"><img src="media/style/' . $manager_theme . 'images/icons/context_view.gif" border="0" align="absmiddle" alt="' . $_lang['files_viewfile'] . '" title="' . $_lang['files_viewfile'] . '" /></a></span>' : $files_array[$filecounter]['view']; $files_array[$filecounter]['unzip'] = $enablefileunzip && $type == '.zip' ? '<span style="width:20px;"><a href="index.php?a=31&mode=unzip&path=' . $curpath . '&file=' . urlencode($file) . '" onclick="return confirmUnzip();"><img src="media/style/' . $manager_theme . 'images/icons/unzip.gif" border="0" align="absmiddle" alt="' . $_lang['file_download_unzip'] . '" title="' . $_lang['file_download_unzip'] . '" /></a></span>' : ''; $files_array[$filecounter]['edit'] = in_array($type, $editablefiles) && is_writable($curpath) && is_writable($newpath) ? '<span style="width:20px;"><a href="index.php?a=31&mode=edit&path=' . urlencode($newpath) . '#file_editfile"><img src="media/style/' . $manager_theme . 'images/icons/save.png" border="0" align="absmiddle" alt="' . $_lang['files_editfile'] . '" title="' . $_lang['files_editfile'] . '" /></a></span>' : '<span class="disabledImage"><img src="media/style/' . $manager_theme . 'images/icons/save.png" border="0" align="absmiddle" alt="' . $_lang['files_editfile'] . '" title="' . $_lang['files_editfile'] . '" /></span>'; $files_array[$filecounter]['delete'] = is_writable($curpath) && is_writable($newpath) ? '<span style="width:20px;"><a href="javascript:deleteFile(\'' . urlencode($newpath) . '\');"><img src="media/style/' . $manager_theme . 'images/icons/delete.gif" border="0" align="absmiddle" alt="' . $_lang['file_delete_file'] . '" title="' . $_lang['file_delete_file'] . '" /></a></span>' : '<span class="disabledImage"><img src="media/style/' . $manager_theme . 'images/icons/delete.gif" border="0" align="absmiddle" alt="' . $_lang['file_delete_file'] . '" title="' . $_lang['file_delete_file'] . '" /></span>'; // increment the counter $filecounter++; } } } $dir->close(); // dump array entries for directories $folders = count($dirs_array); sort($dirs_array); // sorting the array alphabetically (Thanks pxl8r!) for ($i = 0; $i < $folders; $i++) { $filesizes += $dirs_array[$i]['stats']['7']; echo '<tr style="cursor:default;" onmouseout="setColor(this,0)" onmouseover="setColor(this,1)">'; echo '<td>', $dirs_array[$i]['text'], '</td>'; echo '<td>', $modx->toDateFormat($dirs_array[$i]['stats']['9']), '</td>'; echo '<td dir="ltr">', ufilesize($dirs_array[$i]['stats']['7']), '</td>'; echo '<td>'; echo $dirs_array[$i]['delete']; echo '</td>'; echo '</tr>'; } // dump array entries for files $files = count($files_array); sort($files_array); // sorting the array alphabetically (Thanks pxl8r!) for ($i = 0; $i < $files; $i++) { $filesizes += $files_array[$i]['stats']['7']; echo '<tr onmouseout="setColor(this,0)" onmouseover="setColor(this,1)">'; echo '<td>', $files_array[$i]['text'], '</td>'; echo '<td>', $modx->toDateFormat($files_array[$i]['stats']['9']), '</td>'; echo '<td dir="ltr">', ufilesize($files_array[$i]['stats']['7']), '</td>'; echo '<td>'; echo $files_array[$i]['unzip']; echo $files_array[$i]['view']; echo $files_array[$i]['edit']; echo $files_array[$i]['delete']; echo '</td>'; echo '</tr>'; } return; }
/** * Gets information about a file referenced by filename. * @param string file name * @param int STREAM_URL_STAT_LINK, STREAM_URL_STAT_QUIET * @return array */ public function url_stat($path, $flags) { // This is not thread safe $path = substr($path, strlen(self::PROTOCOL) + 3); return $flags & STREAM_URL_STAT_LINK ? @lstat($path) : @stat($path); // intentionally @ }
/** * Return file/folder info * * @param string $path file path * @return array **/ protected function _info($path) { $type = filetype($path); $stat = $type == 'link' ? lstat($path) : stat($path); if ($stat['mtime'] > $this->_today) { $d = 'Today ' . date('H:i', $stat['mtime']); } elseif ($stat['mtime'] > $this->_yesterday) { $d = 'Yesterday ' . date('H:i', $stat['mtime']); } else { $d = date($this->_options['dateFormat'], $stat['mtime']); } $info = array('name' => htmlspecialchars(basename($path)), 'hash' => $this->_hash($path), 'mime' => $type == 'dir' ? 'directory' : $this->_mimetype($path), 'date' => $d, 'size' => $type == 'dir' ? $this->_dirSize($path) : $stat['size'], 'read' => $this->_isAllowed($path, 'read'), 'write' => $this->_isAllowed($path, 'write'), 'rm' => $this->_isAllowed($path, 'rm')); if ($type == 'link') { if (false == ($lpath = $this->_readlink($path))) { $info['mime'] = 'symlink-broken'; return $info; } if (is_dir($lpath)) { $info['mime'] = 'directory'; } else { $info['parent'] = $this->_hash(dirname($lpath)); $info['mime'] = $this->_mimetype($lpath); } $info['link'] = $this->_hash($lpath); $info['linkTo'] = ($this->_options['rootAlias'] ? $this->_options['rootAlias'] : basename($this->_options['root'])) . substr($lpath, strlen($this->_options['root'])); $info['read'] = $this->_isAllowed($lpath, 'read'); $info['write'] = $this->_isAllowed($lpath, 'write'); $info['rm'] = $this->_isAllowed($lpath, 'rm'); } else { $lpath = ''; } if ($info['mime'] != 'directory') { if ($this->_options['fileURL'] && $info['read']) { $info['url'] = $this->_path2url($lpath ? $lpath : $path); } if (0 === ($p = strpos($info['mime'], 'image'))) { if (false != ($s = getimagesize($path))) { $info['dim'] = $s[0] . 'x' . $s[1]; } if ($info['read']) { $info['resize'] = isset($info['dim']) && $this->_canCreateTmb($info['mime']); $tmb = $this->_tmbPath($path); if (file_exists($tmb)) { $info['tmb'] = $this->_path2url($tmb); } elseif ($info['resize']) { $this->_result['tmb'] = true; } } } } return $info; }
function getlist ($directory) { global $delim, $win; if ($d = @opendir($directory)) { while (($filename = @readdir($d)) !== false) { $path = $directory . $filename; if ($stat = @lstat($path)) { $file = array( 'filename' => $filename, 'path' => $path, 'is_file' => @is_file($path), 'is_dir' => @is_dir($path), 'is_link' => @is_link($path), 'is_readable' => @is_readable($path), 'is_writable' => @is_writable($path), 'size' => $stat['size'], 'permission' => $stat['mode'], 'owner' => $stat['uid'], 'group' => $stat['gid'], 'mtime' => @filemtime($path), 'atime' => @fileatime($path), 'ctime' => @filectime($path) ); if ($file['is_dir']) { $file['is_executable'] = @file_exists($path . $delim . '.'); } else { if (!$win) { $file['is_executable'] = @is_executable($path); } else { $file['is_executable'] = true; } } if ($file['is_link']) $file['target'] = @readlink($path); if (function_exists('posix_getpwuid')) $file['owner_name'] = @reset(posix_getpwuid($file['owner'])); if (function_exists('posix_getgrgid')) $file['group_name'] = @reset(posix_getgrgid($file['group'])); $files[] = $file; } } return $files; } else { return false; } }
function lxfile_dstat($dir, $duflag) { $dir = expand_real_root($dir); $list = lscandir_without_dot($dir); $ret = null; foreach ($list as $l) { $stat = lstat("{$dir}/{$l}"); get_file_type("{$dir}/{$l}", $stat); remove_unnecessary_stat($stat); if ($duflag && is_dir("{$dir}/{$l}") || $l === ".trash") { $stat['size'] = lxfile_dirsize("{$dir}/{$l}", true); } else { $stat['size'] = lxfile_size("{$dir}/{$l}"); } $stat['name'] = "{$dir}/{$l}"; $ret[] = $stat; } //dprintr($ret); return $ret; }