Subversion Repositories general

Compare Revisions

Ignore whitespace Rev 1285 → Rev 1286

/FileXch/branches/php-impl/lib/file.php
0,0 → 1,178
<?php
class File
{
public $name;
public $size;
}
 
class FileManager
{
private $endOfLife;
private $root;
private $umask;
 
function __construct($root, $umask)
{
$this->endOfLife = false;
$this->root = $root;
$this->umask = $umask;
 
umask($this->umask);
}
 
function endTheLife()
{
$this->checkLiveCycle();
 
$this->endOfLife = true;
}
 
function checkLiveCycle()
{
if($this->endOfLife) {
throw new Exception("I'm die");
}
}
 
function checkFileName($name)
{
if(!$name) {
throw new Exception("Empty name");
}
 
if(strpos($name, '/') !== false) {
throw new Exception("Name contains slash");
}
 
if(substr($s, 0, 1) == '.') {
throw new Exception("Name starts with dot");
}
}
 
function createDir($name)
{
$this->checkLiveCycle();
$this->checkFileName($name);
 
$fullName = "$this->root/$name";
if(!@mkdir($fullName, 0777, true)) {
if(!is_dir($fullName)) { // already exists?
throw new Exception("Cannot create dir");
}
}
}
 
function removeDir($name)
{
$this->checkLiveCycle();
$this->checkFileName($name);
 
$fullName = "$this->root/$name";
if(!@rmdir($fullName)) {
if(file_exists($fullName)) { // already removed?
throw new Exception("Cannot remove dir");
}
}
}
 
static function cmpFiles($a, $b)
{
if($a->name == $b->name) {
return 0;
}
else {
return ($a->name < $b->name ? -1 : 1);
}
}
 
function listDir($name)
{
$this->checkLiveCycle();
$this->checkFileName($name);
 
$res = array();
$fullName = "$this->root/$name";
$d = dir($fullName);
 
while(false !== ($e = $d->read())) {
if($e == '.' || $e == '..') continue;
$s = stat("$fullName/$e");
 
$f = new File();
$f->name = $e;
$f->size = $s[7];
 
array_push($res, $f);
}
 
$d->close();
 
usort($res, "FileManager::cmpFiles");
 
return $res;
}
 
function removeFile($dir, $name)
{
$this->checkLiveCycle();
$this->checkFileName($dir);
$this->checkFileName($name);
 
if(!unlink("$this->root/$dir/$name")) {
throw new Exception("Cannot remove file");
}
}
 
function removeDirWithFiles($dir)
{
$this->checkLiveCycle();
$this->checkFileName($dir);
 
$fullName = "$this->root/$dir";
$d = dir($fullName);
 
while(false !== ($e = $d->read())) {
if($e == '.' || $e == '..') continue;
 
if(!unlink("$fullName/$e")) {
throw new Exception("Cannot remove file");
}
}
 
if(!@rmdir($fullName)) {
throw new Exception("Cannot remove dir");
}
}
 
function moveFile($tmpName, $dir, $name)
{
$this->checkLiveCycle();
$this->checkFileName($dir);
$this->checkFileName($name);
 
$uniqueName = $name;
$counter = 0;
for(;;) {
$fullName = "$this->root/$dir/$uniqueName";
if(!file_exists($fullName)) {
break;
}
 
$uniqueName = $this->generateUniqueName($name, ++$counter);
}
 
move_uploaded_file($tmpName, $fullName);
}
 
function generateUniqueName($name, $counter)
{
$pos = strrpos($name, '.');
if($pos > 0) {
return substr($name, 0, $pos) . "($counter)" . substr($name, $pos);
}
else {
return "$name($counter)";
}
}
}
?>