<?php
if (!defined('IN_CONTEXT')) die('access violation error!');
class ModTemplate extends Module {
    protected $_filters = array(
        'check_admin' => ''
    );
    
    /**
     * 模板展示
     */
    public function admin_list() {
    	$read_cache_flag = false;
        $this->_layout = 'content';
        
        if (!$this->_requireAdmin()) {
            return '_error';
        }
        
        $page_count = 16;//show 16 templates' shortcut
        $page_number =& ParamHolder::get('_p', 1);//page number
        $category_number =& ParamHolder::get('_cates', '_all'); 
        
        if(!is_numeric($page_number)) $page_number = 1;
        $page_number = floor($page_number);//对输入页码的类型判断
        
        $template_owns = array();
//        if ( IS_INSTALL ) {
		if($category_number == '_all')
		{
        	$handle  = opendir(ROOT.'/template');
			while($file = readdir($handle)){
			 	$newpath=ROOT.'/template/'.$file;
			 	if(is_dir($newpath) && $file != "." && $file != ".." && $file != ".svn") {
			 		if(file_exists(ROOT.DS.'template'.DS.$file.DS.'conf.php') && file_exists(ROOT.DS.'template'.DS.$file.DS.'template_info.php'))
			 		{
			 			include  ROOT.DS.'template'.DS.$file.DS.'conf.php';
			 			if(!empty($template_name))
			 			{
					 		$template_owns[] = $file;
					 		$template_owns_name[] = $template_name;
			 			}
			 		}
			 	}
			}
    	}
			$installed_templates = $template_owns;
//        } else {
        	$cat_sw =& ParamHolder::get('cat_sw', '-');
	        // Now using "My Templates" as default category
	        if ($cat_sw == '-') $cat_sw = '1';
	        
	        //---------------templates cache strategy[start]----------------------
//	        if(extension_loaded('soap'))
//	        {
		        $now = time();
		        $set_expired_time = 24;
		        if(!file_exists('../cache/templates_cache.cache'))
		        {
		        	!@chmod('../cache', 0755 );
		        	$read_cache_flag = false;
		        }
		        else
		        {
		        	$arr = file_get_contents('../cache/templates_cache.cache');
		        	$arr = unserialize($arr);
		        	$set_time = $arr['set_time'];
		        	$expired_time = $arr['expired_time'];
		        	
		        	$read_cache_flag = ($set_time + $expired_time * 3600 >= $now) ? true : false;//estimate cache file's valid
		        }
		        
		        if($read_cache_flag)
		        {
	//	        	$tmp = unserialize($arr['templates_data']);
					$tmp = $arr['templates_data'];
					$tmp_category = $arr['templates_category'];
		        }
		        else
		        {
//		        	if(extension_loaded('soap'))
//		        	{
		        		$tmp =& Template::allRemoteTemplates($cat_sw);
		        		$tmp_category = & Template::allRemoteTemplatesCategories();
//		        	}
	//	        	$ser_data = serialize($tmp);
		        	if(file_exists('../cache/templates_cache.cache'))
		        	{
		        		@unlink('../cache/templates_cache.cache');
		        	}
					$cache_string = array('set_time' => $now,'expired_time' => $set_expired_time,'templates_data' => $tmp,'templates_category' => $tmp_category);
					$cache_string = serialize($cache_string);
		        	file_put_contents('../cache/templates_cache.cache',$cache_string);
		        }
//	        }
	        //---------------templates cache strategy[end]----------------------
	        if($category_number == '_all')
	        {
	        	$template_categories1 = $tmp;
	        }
	        else
	        {
		        $template_categories1 = array();//某类型下的模板
		        if(empty($tmp)) $tmp = array();
		        foreach($tmp as $k => $v)
		        {
		        	if($category_number == $v['ezsite_template_category_id'])
		        	{
		        		$template_categories1[] = $v;
		        	}
		        }
	        }
	        
	        
	        
	        $list = array();
	        if(empty($template_categories1)) $template_categories1 = array();
	        foreach($template_categories1 as $k => $v)
	        {
	        	$str = substr($v['archive'],0,-4);
	        	if(in_array($str,$installed_templates))
	        	{
	        		$list[$str] = $v['demourl'];
	        		continue;
	        	}
	        	$template_owns[] = $v;
	        }
//        }
			
	        
			if(empty($list)) $list = array();
			foreach($list as $k => $v)
			{
				foreach($template_owns as $k1 => $v1)
				{
					if(is_array($v1))
					{
						continue;
					}
					else
					{
						if($k == $v1)
						{
							$template_owns[$k1] .= '#$'.$v;
						}
					}
				}
			}
			
	    //------------------------分页处理[start]---------------------- 
	    $sum_template = count($template_owns);
	    $page_sum_page = intval($sum_template / $page_count);//page_sum_page总页数
	    if($sum_template % $page_count > 0) $page_sum_page++;
	    
	    $output_array = array();
	    $output_array_name = array();
	    if($page_number == $page_sum_page)
	    {
	    	for($i = ($page_number - 1) * $page_count; $i <= $sum_template; $i++)
	    	{
	    		if(!empty($template_owns[$i]))
	    		{
	    			$output_array[] = $template_owns[$i];
	    			if(!empty($template_owns_name[$i])) $output_array_name[] = $template_owns_name[$i];
	    		}
	    	}
	    }
	    elseif(($page_number < $page_sum_page) && ($page_number > 0))
	    {
	    	for($i = ($page_number - 1) * $page_count; $i <= $page_number * 16 -1; $i++)
	    	{
	    		$output_array[] = $template_owns[$i];
	    		if(!empty($template_owns_name[$i])) $output_array_name[] = $template_owns_name[$i];
	    	}
	    }
	    //------------------------分页处理[end]----------------------
	    $this->assign('last_page',$page_sum_page);//最后一页
	    $this->assign('page_number',$page_number);//当前页码
	    $this->assign('output_array', $output_array);//每页信息
	    $this->assign('output_array_name', $output_array_name);
        $this->assign('template_owns', $template_owns);//总模板信息
        $this->assign('template_owns_name', $template_owns_name);
        $this->assign('tmplate_category',$tmp_category);//模板分类信息
        $this->assign('category_number',$category_number);//模板类型
    }
    
    public function admin_upload() {
        $this->_layout = 'content';
        
        if (!$this->_requireAdmin()) {
            return '_error';
        }
    }
    
    public function admin_create() {
        if (!$this->_requireAdmin()) {
            return '_result';
        }

        include_once(P_LIB.'/zip.php');//加载zip功能代码
        
        $file_info =& ParamHolder::get('tpl_file', array(), PS_FILES);
        $file_name = ToolKit::get_filename($file_info["name"]);
        if (empty($file_info)) {
            Notice::set('mod_template/msg', __('Invalid post file data!'));
            Content::redirect(Html::uriquery('mod_template', 'admin_upload'));
        }
        
        if(is_dir(ROOT.'/template/'.$file_name)) {
            Notice::set('mod_template/msg',__('Template with the same name exists!'));
            Content::redirect(Html::uriquery('mod_template', 'admin_list'));
        }
        
        if (!$this->_savetplFile($file_info)) {
            Notice::set('mod_template/msg', __('Uploading template file failed!'));
            Content::redirect(Html::uriquery('mod_template', 'admin_upload'));
        }
        
        if(extension_loaded('zip'))
        {
	        $tpl_zip = new ZipArchive(); 
	        $tpl_zip->open(ROOT.'/template/'.$file_info["name"]); 
	        $tpl_zip->extractTo(ROOT."/template/".$file_name); 
	        $tpl_zip->close();
        }
        else
        {
	        if(!file_exists(ROOT."/template/".$file_name))
	        {
	        	mkdir(ROOT."/template/".$file_name,0755);
	        }
	        $z = new zipper();
	        $z->ExtractTotally(ROOT.'/template/'.$file_info["name"],ROOT."/template/".$file_name);
        }
        
        @unlink(ROOT.'/template/'.$file_info["name"]);
        
        if (!file_exists(ROOT.'/template/'.$file_name.'/conf.php') || !file_exists(ROOT.'/template/'.$file_name.'/template_info.php')) {
            Notice::set('mod_template/msg', __('The file conf.php and(or) template_info.php does not exist'));
            Toolkit::rmdir_template($file_name);
            Content::redirect(Html::uriquery('mod_template', 'admin_upload'));
        }
        
        Notice::set('mod_template/msg', __('Uploading language file succeeded!'));
        Content::redirect(Html::uriquery('mod_template', 'admin_list'));
    }
    
    /**
     * 安装模板
     */
    public function admin_make_default($curr_tpl_id,$is_remote_tpl) {
        
        $template = '';
        $tpl_path = ROOT.DS.'template';
//        $curr_tpl_id = trim(ParamHolder::get('tpl_id', '0'));
//        $is_remote_tpl = trim(ParamHolder::get('is_remote', '0'));
        if (intval($curr_tpl_id) == 0) {
            return false;
        }
        if (intval($is_remote_tpl) == 1) {
            $template = $this->_downloadRemote($curr_tpl_id);
            if (!$template) {
                return false;
            }
        } else {
            try {
                $curr_template = new Template($curr_tpl_id);
                $template = $curr_template->template;
            } catch (Exception $ex) {
                return false;
            }
        }
        try {
			include_once(ROOT.'/template/'.DEFAULT_TPL.'/template_info.php');
        } catch (Exception $ex) {
            return false;
        }
        
        return true;
    }
	
    /**
     * 设为默认模板时触发,切模板
     */
    public function admin_make_owntpl($curr_tpl_id) {
        
        if(!file_exists(ROOT.'/template/'.$curr_tpl_id.'/template_info.php')) return false;
        
        try {
            $o_param = new Parameter();
            $tpl_param =& $o_param->find("`key`='DEFAULT_TPL'");
            $tpl_param->val = $curr_tpl_id;
            $tpl_param->save();
            
            $tpl_default_id =& $o_param->find("`key`='DEFAULT_TPL_ID'");
            $tpl_default_id->val = '0';
            $tpl_default_id->save();
			
			//2010-6-12 zhangjc two => three
			include_once(ROOT.'/template/'.DEFAULT_TPL.'/template_info.php');
			if(in_array("center",TplInfo::$positions)){
				$o_block = new ModuleBlock();
				$modules = $o_block->findAll("`s_pos`='right' and `module`='mod_product'");
				if(sizeof($modules) > 0){
					foreach($modules as $module){
						$module_info['s_pos'] = "center";
						$o_module = new ModuleBlock($module->id);
						$o_module->set($module_info);
						$o_module->save();
					}
				}
			}

			
        } catch (Exception $ex) {
            return false;
        }
        
        return true;
    }

    public function admin_delete() {
        if (!$this->_requireAdmin()) {
            return '_result';
        }
        
        $curr_tpl_id = trim(ParamHolder::get('tpl_id', '0'));
        if (intval($curr_tpl_id) == 0) {
            $this->assign('json', Toolkit::jsonERR(__('Invalid ID!')));
            return '_result';
        }
        try {
            $curr_tpl = new Template($curr_tpl_id);
            if ($curr_tpl->template == DEFAULT_TPL) {
                $this->assign('json', Toolkit::jsonERR(__('Cannot delete default template!')));
                return '_result';
            } else {
                if(!file_exists(ROOT.'/template/'.$curr_tpl->template)){
                    $this->assign('json',ToolKit::jsonERR(__('File does not exist!')));
                    return '_result';
                }
                if (!Toolkit::rmdir_template($curr_tpl->template)) {
                    $this->assign('json', Toolkit::jsonERR(__('Delete template failed!')));
                    return '_result';
                }
                $curr_tpl->delete();
            }
        } catch (Exception $ex) {
            $this->assign('json', Toolkit::jsonERR($ex->getMessage()));
            return ('_result');
        }
        
        $this->assign('json', Toolkit::jsonOK());
        return '_result';
    }
    
    /**
     * 重置模板数据
     */
    public function reset_tpl_data($tpl_name = DEFAULT_TPL,$flag = 1) {
		if (!$this->_requireAdmin()) {
            return '_result';
        }
		if($this->downloadsql($tpl_name)){
			//先删除原来数据
			Template::ResetTplData();
			//更新数据库
			include ROOT.'/include/fun_install.php';
			create_table(Config::$db_name,Config::$tbl_prefix,ROOT."/template/".$tpl_name."/".$tpl_name.'_2_sample.sql');
			
			//upload文件操作
			$this->delDir(ROOT."/upload");
			uploadcopy(ROOT."/template/".$tpl_name."/".$tpl_name."_2_upload/image",ROOT."/upload/image");
			uploadcopy(ROOT."/template/".$tpl_name."/".$tpl_name."_2_upload/flash",ROOT."/upload/flash");
			uploadcopy(ROOT."/template/".$tpl_name."/".$tpl_name."_2_upload/file",ROOT."/upload/file");
			uploadcopy(ROOT."/template/".$tpl_name."/".$tpl_name."_2_upload/media",ROOT."/upload/media");
			
			@unlink(ROOT."/template/".$tpl_name."/".$tpl_name.'_2_sample.sql');
			$res1 = $this->full_rmdir(ROOT."/template/".$tpl_name."/".$tpl_name."_2_upload");
        	
			if($flag == 1)	
			{
				$str6 = <<<HTML
<script language="JavaScript">   
    updateProgress("模板重置成功", 390);
    top.location.reload();   
</script>
HTML;
//				$this->assign('json', Toolkit::jsonOK());
				echo $str6;
				flush();
				die;
			}
			else
			{
				$str6 = <<<HTML
<script language="JavaScript">   
    updateProgress("模板安装成功", 390);   
</script>
HTML;
				echo $str6;
				flush();
				return true;
			}
		} else {
			if($flag == 1)
			{
				$this->assign('json', Toolkit::jsonERR(__('Install Error!')));
			}
			else
			{
				return false;
			}
		}
		
        if($flag == 1)	return '_result';
	}
	
	/**
     * 安装模板流程
     */
    public function admin_install_template()
    {
    	try{
    	if (!$this->_requireAdmin()) {
			die(__('No Permission!'));
        }
        $curr_tpl_id = trim(ParamHolder::get('tpl_id', '0'));
        $is_remote_tpl1 = trim(ParamHolder::get('is_remote', '0'));
        $has_data = trim(ParamHolder::get('has_data', '0'));//新参数
        $tpl_name1 = trim(ParamHolder::get('tpl_name', '0'));
        if (intval($is_remote_tpl1) == 1)//模板文件远程下载安装
        {
        	if(!file_exists(ROOT.'/template/'.$tpl_name1))
        	{
	        	$res_bool = $this->admin_make_default($curr_tpl_id,$is_remote_tpl1);//取模板文件
	        	if(!$res_bool)
	        	{
					die(__('Install Error!'));
	        	}
        	}
        	
        	if($has_data == 1)//安装新数据替换旧数据（upload&sql）
        	{
        		$res = $this->reset_tpl_data($tpl_name1,2);
        		if(!$res)
        		{
					die(__('Install Error!'));
        		}
        	}
        	
        	$res_bool = $this->admin_make_owntpl($tpl_name1);
        	if(!$res_bool)
        	{
				die(__('Install Error!'));
        	}
        	
        	if($has_data == 1)
        	{
				$str7 = <<<HTML
<script type="text/javascript">
alert("模板安装成功！");	
top.location.reload();
</script>
HTML;
				echo $str7;
				flush();
        	}
        }
        else//模板文件本地已存在
        {
        	if($has_data == 1)//安装新数据替换旧数据（upload&sql）
        	{
  				$res = $this->reset_tpl_data($tpl_name1,2);  	
        		if(!$res)
        		{
					die(__('Install Error!'));
        		}	
        	}
        	
        	$res_bool = $this->admin_make_owntpl($tpl_name1);
        	if(!$res_bool)
        	{
				die(__('Install Error!'));
        	}
        	if($has_data == 1)
        	{
				$str7 = <<<HTML
<script type="text/javascript">	
top.location.reload();
</script>
HTML;
				echo $str7;
				flush();
        	}
        }
        
		  die(__('Installation Completed'));
    	}
    	catch(Exception $ex)
    	{
    		$res_bool = $this->admin_make_owntpl($tpl_name1);
        	if(!$res_bool)
        	{
				die(__('Install Error!'));
        	}
    	}    	
    }
    
    /**
     * 模板在本地安装时安装界面
     */
    public function template_local()
    {
    	$tpl_name = trim(ParamHolder::get('tpl_name', '0'));
    	$this->_layout = 'template';
    	
    	$this->assign('tpl_name',$tpl_name);
    	return 'template_local';
    }
    
    /**
     * 模板远程下载模式
     */
    public function template_remote()
    {
    	$tpl_id = trim(ParamHolder::get('tpl_id', '0'));
    	$remote_tpl = trim(ParamHolder::get('is_remote', '0'));
    	$tpl_name = trim(ParamHolder::get('tpl_name', '0'));
    	$this->_layout = 'template';
    	
    	$this->assign('tpl_id',$tpl_id);
    	$this->assign('remote_tpl',$remote_tpl);
    	$this->assign('tpl_name',$tpl_name);
    	return 'template_remote';
    } 
    
    public function show_reset_data()
    {
    	$this->_layout = 'blank';
    	return 'reset_tpl_data';
    }
    
    private function _requireAdmin() {
        if (!ACL::requireRoles(array('admin'))) {
            $this->assign('json', Toolkit::jsonERR(__('No Permission!')));
            return false;
        }
        return true;
    }
    
    private function _savetplFile($struct_file) {
        return move_uploaded_file($struct_file['tmp_name'], ROOT.'/template/'.$struct_file['name']);
    }
	
    /**
     * 
     * @param $tplid
     * @return unknown_type
     */
    private function _downloadRemote($tplid) {
    	include_once(P_LIB.'/zip.php');//加载zip功能代码
    	ini_set('max_execution_time', 600);//把php脚本运行超期时间设为10分钟
        $tpl_path = ROOT.DS.'template';
        
        // Get template info first
        /*
        $client =& Toolkit::initSoapClient();
        $tpl_info = unserialize($client->getTplInfo(EZSITE_UID, $tplid));
        */
        $ezsite_uid = EZSITE_UID;
        $tpl_info = file_get_contents(SVC_TPL."getTplInfo.php?ezsite_uid=$ezsite_uid&tplid=$tplid");
        $tpl_info = unserialize($tpl_info);
        
        if (!$tpl_info) {
            return false;
        }
        
        // Check whether the target download dir is writable
        if (!is_writable($tpl_path)) {
            return false;
        }
        
        // Check whether there is a template with the same name
        $folder_name = ToolKit::get_filename($tpl_info['archive']);
        if(file_exists($tpl_path.DS.$folder_name)) {
            Toolkit::removeDir($tpl_path.DS.$folder_name);
        }
         
        // Try to download the file
//        $remote_file = fopen($tpl_info['package_url'].'&uid='.EZSITE_UID, 'r');
		$remote_file = fopen(SVC_TPL."../sitestar100901/{$tpl_info['archive']}",'r');
        if (!$remote_file) {
            return false;
        }
        $local_file = fopen($tpl_path.DS.$tpl_info['archive'], 'w');
        while (!feof($remote_file)) {
            fwrite($local_file, 
                fread($remote_file, 4096), 
                4096);
        }
        fclose($local_file);
        fclose($remote_file);
        
        // Download finished. Now extract.
        if(extension_loaded('zip'))
        {
	        $tpl_zip = new ZipArchive(); 
	        $tpl_zip->open($tpl_path.DS.$tpl_info['archive']); 
	        $tpl_zip->extractTo($tpl_path.DS.$folder_name); 
	        $tpl_zip->close();
        }
        else
        {
	        if(!file_exists($tpl_path.DS.$folder_name))
	        {
	        	mkdir($tpl_path.DS.$folder_name,0755);
	        }
	        $zipper = new zipper();
	        $zipper->ExtractTotally($tpl_path.DS.$tpl_info['archive'],$tpl_path.DS.$folder_name);
        }
        
        @unlink($tpl_path.DS.$tpl_info['archive']);
        
        if (!file_exists($tpl_path.DS.$folder_name.DS.'conf.php') || 
            !file_exists($tpl_path.DS.$folder_name.DS.'template_info.php')) {
            Toolkit::rmdir_template($folder_name);
            return false;
        }
        
        if(file_exists($tpl_path.DS.$folder_name.DS.'conf.php'))
        {
        	include $tpl_path.DS.$folder_name.DS.'conf.php';
        }
        else
        {
        	die(__('Install Error!'));
        }
        
        
    	
        return $tpl_name;
    }
    
 	/**
 	 * 下载sql和upload时触发
 	 * @return 成功返回模板名，失败返回false
 	 */
    private function downloadsql($tpl_name)
    {
    	include_once(P_LIB.'/zip.php');
		//判断文件是否存在
		if(file_exists(ROOT.'/template/'.$tpl_name.'/'.$tpl_name.'_2_sample.sql') && file_exists(ROOT.'/template/'.$tpl_name.'/'.$tpl_name.'_2_upload')){
			return true;
		}
    	//download sql file
        
        //为了应对模板容量巨大的情况
        try{
        ini_set('max_execution_time', 600);//把php脚本运行超期时间设为10分钟
		ini_set('memory_limit', '60M');//允许php获取60的内存大小
		
		if(file_exists("../template/{$tpl_name}_upload.zip"))
		{
			@unlink("../template/{$tpl_name}_upload.zip");
		}
		
//		$remote_file = fopen(SVC_TPL."download_upload.php?tpl_name={$tpl_name}",'r');
		$remote_file = fopen(SVC_TPL."../sql_upload/{$tpl_name}.zip",'r');
		
		$local_file = fopen("../template/{$tpl_name}_upload.zip",'w');
		/*
		$soap1 = new SoapClient(SVC_TPL.'MysqlUploadOutput.wsdl');
		$file_size = $soap1->uploadOutput($tpl_name);
		*/
		$file_size = file_get_contents(SVC_TPL."uploadOutput.php?tpl_name=$tpl_name");
		$count = 0;
		$width = 390;
		$width1 = $width + 2;
		$progress = 0;
		$str1 = <<<HTML
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/transitional.dtd">   
<html>   
<head>   
    <title>下载模板</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
    
    <style>   
    body, div input { font-family: Tahoma; font-size: 9pt }   
    </style>   
    <script language="JavaScript">   
    <!--   
    function updateProgress(sMsg, iWidth)  
    {     
        document.getElementById("status").innerHTML = sMsg;   
        document.getElementById("progress").style.width = iWidth + "px";   
        document.getElementById("percent").innerHTML = parseInt(iWidth /$width * 100) + "%";   
     }   
    //-->   
    </script>        
</head>
<body>   
<div style="margin: 4px; margin-left:40px;margin-top:45px;*margin-top:15px;;padding: 8px; border: 1px solid gray; background: #EAEAEA; width: {$width1}px">   
    <div><font color="gray"></font></div>   
    <div style="padding: 0; background-color: white; border: 1px solid navy; width: {$width}px">   
    <div id="progress" style="padding: 0; background-color: #FFCC66; border: 0; width: 0px; text-align: center;   height: 16px"></div>               
    </div>   
    <div id="status"> </div>   
    <div id="percent" style="position: relative; top: -30px; text-align: center; font-weight: bold; font-size: 8pt">0%</div>   
</div>
HTML;
		echo $str1;
		flush();
		while(!feof($remote_file))
		{
			$tmp = fwrite($local_file,fread($remote_file,4096),4096);
			$count += $tmp;
			$progress = $count*$width/$file_size;
			$ptx = min($width-20,intval($progress));
$str2 = <<<HTML
<script language="JavaScript">   
    updateProgress("正在下载模板....", $ptx);   
</script>
HTML;
			echo $str2;
			flush();
		}
$width2 = $width - 19;	
$str3 = <<<HTML
<script language="JavaScript">   
    updateProgress("模板下载成功,正在安装模板...", $width2);   
</script>
HTML;
		echo $str3;
		flush();
		
		
		
		fclose($local_file);
		fclose($remote_file);
		@chmod( $tpl_path.DS.$folder_name, 0755 ); 
		if(extension_loaded('zip'))
		{
			$tpl_zip = new ZipArchive(); 
	        $tpl_zip->open("../template/{$tpl_name}_upload.zip"); 
	        $tpl_zip->extractTo("../template/{$tpl_name}"); 
	        $tpl_zip->close();
		}
		else
		{
			if(!file_exists("../template/{$tpl_name}"))
			{
				mkdir("../template/{$tpl_name}",0755);
			}
			$z = new zipper();
			$z->ExtractTotally("../template/{$tpl_name}_upload.zip","../template/{$tpl_name}");
		}
		
        @unlink("../template/{$tpl_name}_upload.zip");
        
        
    	} catch(Exception $ex) {
    		return false;
    	}
    	
    	return $tpl_name;
    } 
    
    /**
     * 文件拷贝
     * @param $source  拷贝$source下的文件
     * @param $destination 黏贴到目标文件
     * @param $child 拷贝目标包括子目录 1:包括 0:不包括 
     * @return bool
     */
    private function xCopy($source, $destination, $child){
    	if(!is_dir($source)){
    		return false;
    	}
    	if(!is_dir($destination)){
    		@mkdir($destination,0777);
    	}

    	$handle=dir($source);
    	while($entry=$handle->read()) {
    		if(($entry!=".")&&($entry!="..")){
    			if(is_dir($source."/".$entry)){
    				if($child)
    				$this->xCopy($source."/".$entry,$destination."/".$entry,$child);
    			}
    			else{
    				@copy($source."/".$entry,$destination."/".$entry);
    			}

    		}
    	}

    	return true;
    }
    
	private function full_rmdir( $dir )
   	{
       if ( !is_writable( $dir ) )
       {
           if ( !@chmod( $dir, 0777 ) )
           {
               return FALSE;
           }
       }
       
       $d = @dir( $dir );
       while ( FALSE !== ( $entry = $d->read() ) )
       {
           if ( $entry == '.' || $entry == '..' )
           {
               continue;
           }
           $entry = $dir . '/' . $entry;
           if ( is_dir( $entry ) )
           {
               if ( !$this->full_rmdir( $entry ) )
               {
                   return FALSE;
               }
               continue;
           }
           if ( !@unlink( $entry ) )
           {
               $d->close();
               return FALSE;
           }
       }
       
       $d->close();
       
       @rmdir( $dir );
       
       return TRUE;
   }
   
   private function delDir($path)
   {
   		if(!(strpos($path,'.svn') === false)) return 1;
	   	if (is_dir($path))
	   	{
	   		if ($dh = opendir($path))
	   		{
	   			while (($file = readdir($dh)) !== false)
	   			{
	   				if($file!=".."&&$file!=".")
	   				{
	   					if(is_dir($path."/".$file))
	   					{
	   						if(!$this->delDir($path."/".$file))
	   						{
	   							return 0;
	   						}
	   					}
	   					else
	   					{
	   						if(!@unlink($path."/".$file))
	   						{
	   							return 0;
	   						}
	   					}
	   				}
	   			}
	   			closedir($dh);
	   		}
	   		return 1;//rmdir($path);
	   	}
   }
}
?>
