<?php
if (!defined('R_P')) exit("access Die");
define('E_P', R_P . '/event/');
class event{
	var $files = array();
	var $config;
	function event($event, $param, $mod = false){
		$this->config = C_P . '/config/event_config.php';
		if(!is_file($this->config)){
			$this->_init_config();
		}
		require_once($this->config);
		$this->files = $event_config;
		$this->_proc($event, $param);
		if($mod) $this->_proc('common', $param);
	}
	
	function _proc($event, $param){
		$files = is_array($this->files[$event]) ? $this->files[$event] : array() ;
		foreach($files as $e){
			$file = E_P . $event . "/class" . $e . ".php";
			if(!is_file) continue;
			$object = "event_" . $event ."_". $e;
			if(!class_exists($object)) require_once($file);
			if(!class_exists($object)) continue;
			$obj = new $object;
			if(!method_exists($obj, 'init')) continue;
			$obj->init($param);
		}	
	}
	
	function _get_element($type){
		$dir = E_P . $type . '/';
		if (!is_dir($dir)) return array();
		$handle = @opendir($dir);
		$temp = array();
		while (false !== ($filename = @readdir($handle)))
		{
			if (false !== ($php = $this->_is_php_file($dir , $filename))){
				$temp[] = $php;
			}
		}
		@closedir($handle);
		return $temp;
	}
	
	function _init_config(){
		$dir = $this->_get_dir();
		$data = array();
		foreach($dir as $val){
			$data[$val] = $this->_get_element($val);
		}
		$s = "<?php\n\$event_config = ". var_export($data, true) .";\n?>";
		qbase::writetofile($this->config, $s);
		return $data;
	}

	function _get_dir(){
		$dir = E_P;
		$handle = @opendir($dir);
		$temp = array();
		while (false !== ($filename = @readdir($handle)))
		{
			if($filename == '.' || $filename == '..') continue;
			if (is_dir($dir . $filename)){
				if(!preg_match("/[^0-9a-zA-Z_\-]/i", $filename)){
					$temp[] = $filename;
				}
			}
		}
		@closedir($handle);
		return $temp;
	}

	function _is_php_file($dir, $file){
		if(!is_file($dir . $file)) return false;
		$r = preg_match("/class\.([a-zA-Z_][a-zA-Z0-9_]{0,63})\.php/", $file, $data);
		if($r) return $data[1];
		else return false;
	}	
}
?>