<?php
/*
 * This file is part of the easy-CMS project.
 * easy-CMS is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 * 
 * easy-CMS is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with easy-CMS; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */


include_once('classes/system/Node.class.php');
include_once('classes/system/File.class.php');

/**
 * Dir Class
 *
 * @author  cedseven
 * @package System
 */
class Dir extends Node {
	/**
	 * Constructor
	 *
	 * @param string $name
	 * @param string $path
	 * @param boolean $create
	 */
	function Dir($name, $path='', $create=false, $doCheck=true) {
		parent::Node($name, $path);
		$dirName = $this->getNodeFullName();
		if($create){
      if(!is_dir($dirName)) {
        if(!$doCheck || $this->isValidFileName()) {
          mkdir($dirName, 0755);
        }
        else {
          trigger_error("Directory constructor, warning : not a valid directory name for '$dirName'.", E_USER_ERROR);
        }
      }
      else {
        trigger_error("Directory constructor, warning : directory '$dirName' already  exist.", E_USER_ERROR);
      }
		}
    else if(!is_dir($dirName)) {
      trigger_error("Directory constructor, warning : directory '$dirName' does not exist.", E_USER_ERROR);
    }
	}

	/**
	 * Gets node type
	 */
	function getNodeType() {
		return DIR_NODE;
	}

	/**
	 * checks if a filename is valid
	 *
	 * @static
	 * @return boolean
	 */
	function isValidFileName() {
		return parent::isValidFileName($this->getName());
	}

	function remove() {
		$fileName = $this->getNodeFullName();
  	if(!rmdir($fileName)) {
			return -1;
		}
		return 1;
	}

	/**
	 * Gets directory listing
	 *
	 * @return array
	 */
	function &getListing() {
		$dirName = $this->getNodeFullName();
		if(($dir = opendir($dirName)) === false) {
      return null;
		}
		$i = 0;
		$j = 0;		
		$listDirs = array();
		$listFiles = array();		
	  while ($file = readdir($dir)) {
			if ($file != '.' && $file != '..') {
				if (is_dir($dirName.'/'.$file)) {
					$listDirs[$i] = new Dir($file, $dirName);
					$listDirs[$i]->setParentNode($this);
					++$i;					
				}
				else{
					$listFiles[$j] = new File($file, $dirName);
					$listFiles[$j]->setParentNode($this);
					++$j;
				}
			}
	  }
    closedir($dir);

		usort($listDirs, array("Node","compare"));
		usort($listFiles, array("Node","compare"));

		return array_merge($listDirs, $listFiles);
	}
}
?>
