<?php
using('System.Helper.Array');
define('DIRECTORY_REPLACE',';');
/**
 * Dir
 *
 * @date 15.03.2007
 * @name Dir
 * @author Margo Poolak <margo 'dot' poolak 'at' mail 'dot' ee>
 * @copyright Copyright &copy;2006 Margo Poolak. All Rights Reserved.
 * @version 2.0
 * @package System.Library
 * @category 
 * 
 * Directory handler class
 */
class Dir
{
	private $_dir;
	private $_read;
	private $_path;
	private $_array;
	/*
	*
	*/
	public function __construct($dir)
	{
		$this->_path = str_replace(DIRECTORY_REPLACE,DIRECTORY_SEPARATOR,$dir);
		/*
		*
		*/
		if(is_dir($this->_path))
		{
			if(is_readable($this->_path))
			{
				$this->_read = opendir($this->_path); #opens the directory
				if(!$dir)
				{
					trigger_error('The directory is not accessible '.$this->_path,E_USER_ERROR);
				}
				else
				{
					$size = 0;
					while(($file = readdir($this->_read)) !== false)
					{
						if(is_file($this->_path.DIRECTORY_SEPARATOR.$file))
						{
							$size = filesize($this->_path.DIRECTORY_SEPARATOR.$file);
						}
						
						$this->_dir[] = array
						(
							'name'=>$file,
							'size'=>$size
						);
					}
				}
			}
			else
			{
				exit('The directory <b>"'.$this->_path.'"</b> is not readable. <a href="'.$_SERVER['HTTP_REFERER'].'">Go back</a>');
			}
		}
		else
		{
			trigger_error('The path <b>"'.$this->_path.'"</b> is not a directory ',E_USER_ERROR);
		}
	}
	/*
	*
	*/
	public function convertPath($path)
	{
		return str_replace(DIRECTORY_REPLACE,DIRECTORY_SEPARATOR,$path);
	}
	/*
	*
	*/
	public function getRealPath()
	{
		return $this->_path;
	}
	/*
	*
	*/
	public function getPath()
	{
		return str_replace(DIRECTORY_SEPARATOR,DIRECTORY_REPLACE,$this->_path);
	}
	/*
	*
	*/
	public function toArray()
	{
		return $this->_dir;
	}
	/*
	*
	*/
	public function sort($field,$order='asc')
	{
		$array = $this->toArray();
		return $this->_array = array_multi_sort($array,$field,$order);
	}
	/*
	*
	*/
	public function __destruct()
	{
		if(isset($this->_read))
		{
			closedir($this->_read);
		}
	}
}
function move_path_back($path)
{
	$array = explode(DIRECTORY_REPLACE,$path);
	$count = count($array)-1;
	if($count > 1)
	{
		unset($array[$count]);
		return implode(DIRECTORY_REPLACE,$array);
	}
	return DIRECTORY_REPLACE;
}
/**
* Remove one separated end directory
* @parameter string path
* @parameter integer steps to delete
* @returns string new path
*/
function remove_path_end($path,$steps = 1)
{
	$dir = explode(DIRECTORY_SEPARATOR,$path);
	$i = 0;
	$count = count($dir);
	while($i<$steps)
	{
		$k = $count--;
		if(isset($dir[$k]))
		{
			unset($dir[$k]);
		}
		else
		{
			unset($dir[$k-1]);
		}
		++$i;
	}
	return implode(DIRECTORY_SEPARATOR,$dir);
}
?>