<?php
class ModelAction extends AdminAction{
    private $name;
    public function _initialize() {
        parent::_initialize();
    }
 
    public function index(){
        $this->display();
    }

    public function submit(){
		$action = D($this->_name);
		$ModelSource=IVEARS_PATH."/Lib/ModelSource";
		$ModelSource_themepath=IVEARS_PATH."/Tpl/Admin/".C('DEFAULT_THEME');
		$ModelSource_actionpath=IVEARS_PATH."/Lib/Action/";
		$TagLib_actionpath=IVEARS_PATH."/Lib/TagLib/";
        $ary_post = $this->_post();
		
		if($ary_post['modelname']){
			$ary_post['modelname']=ucfirst($ary_post['modelname']);//大写第一人字母
			//复制后台模型
			$actionSource=file_get_contents($ModelSource."/action/Action.class.php");
			$actionSource=str_replace('_ACTIONNAME_',$ary_post['modelname'],$actionSource);
			@file_put_contents($ModelSource_actionpath.'Admin/'.$ary_post['modelname']."Action.class.php",$actionSource);
			//复制前台模型
			$HomeactionSource=file_get_contents($ModelSource."/action/HomeAction.class.php");
			$HomeactionSource=str_replace('_ACTIONNAME_',$ary_post['modelname'],$HomeactionSource);
			@file_put_contents($ModelSource_actionpath."Home/".$ary_post['modelname']."Action.class.php",$HomeactionSource);	
			
			//复制模板标签
			$TagLibActionSource=file_get_contents($ModelSource."/action/TagLibAction.class.php");
			$TagLibActionSource=str_replace('Tagname__',$ary_post['modelname'],$TagLibActionSource);
			@file_put_contents($TagLib_actionpath."TagLib".$ary_post['modelname'].".class.php",$HomeactionSource);				
					
			
			//执行模行sql文件添加表
			$actionSqlSource=file_get_contents($ModelSource."/sql/action.sql");
			$actionSqlSource=str_replace('_DB_PREFIX_',C('DB_PREFIX'),$actionSqlSource);
			$actionSqlSource=str_replace('ACTIONNAME',strtolower($ary_post['modelname']),$actionSqlSource);
			$action->execute($actionSqlSource);
			//复制模板文件
			$this->recurse_copy($ModelSource."/templates",$ModelSource_themepath.'/'.$ary_post['modelname']);
			$this->success("操作成功");
			
		}
    }
	
	public function recurse_copy($src,$dst) {  // 原目录，复制到的目录
		$dir = opendir($src);
		@mkdir($dst);
		while(false !== ( $file = readdir($dir)) ) {
			if (( $file != '.' ) && ( $file != '..' )) {
				if ( is_dir($src . '/' . $file) ) {
					recurse_copy($src . '/' . $file,$dst . '/' . $file);
				}
				else {
					copy($src . '/' . $file,$dst . '/' . $file);
				}
			}
		}
		closedir($dir);
	}	
	
}
