<?php

/*
*	Copyright VeryIDE,2007-2010
*	http://www.veryide.com/
*
*	$Id: veryide_files.php,v2 19:47 2008-2-21 Leilei $
*/

require("../../include/header.php");
require("../../function/sql.php");

html_start("数据备份 - VeryIDE");
?>

<!--body start-->
	<?php

    //延长程序运行时间
    set_time_limit(0);
    
    //loader
    loader_setting("naver.system");
	
	//备份基准目录
    $base = realpath("../../data/backup/")."/";
    
    $action = GetQuery("action");
    $update = GetQuery("update");
    
    if($action){
    
        switch($action){
        
            case "execute":
    
                //检查权限
                $func = "sys-update-exe";
                checker_func($func);
            
                $sqlfile = $base.$update;
                
                //锁文件
                $lock = str_replace(".sql",".lock",$sqlfile);
                
                if(file_exists($lock)){
                    
                    echo '<div id="state" class="failure">抱歉！安装已经存在。更新于早前已经安装，并在使用中：<span class="text-key">'.$update.'</span></div>';
                    
                }else{
                    
                    if(file_exists($sqlfile)){
                    
                        ini_set("memory_limit","100M");
                
                        //mysql open
                        reader_mysql();
                    
                        $sql = file_get_contents($sqlfile);
                        
                        //前置表前辍
                        $sql = str_replace("{TableManPre}",VI_DBMANPRE,$sql);
                        $sql = str_replace("{TableModPre}",VI_DBMODPRE,$sql);
                        
                        //参数
                        $sql = str_replace("{TableNow}",time(),$sql);
                        $sql = str_replace("{TableIP}",GetIP(),$sql);
                    
                        $array = runquery($mysql , $sql);
                        
                        if(!$array[0]){
                        
                            //写入锁
                            create_file( $lock ,date("Y-m-d H:i:s"));
                        
                            echo '<div id="state">恭喜！成功安装更新：'.$update.'，您刚才的操作可能全影响到系统菜单的显示，请刷新查看最新菜单：<input name="submit" onclick=\'parent.location.reload(true)\' type="button" class="submit" value="显示新菜单" /></div>';
                            
                            //搜索模块
                            cache_module();								
                            
                            //缓存系统菜单
                            cache_table('system',$mysql,VI_DBMANPRE."menu",'<option value=\'{table:id}\'>{table:name}</option>'," sort asc ");
                
                            //写入日志
                            event_insert($mysql,$func,time(),time(),"恢复备份：".$update);				
                            
                            ini_set("memory_limit","12M");
                            
                        }else{
                            echo '<div id="state" class="failure">抱歉！安装更新失败。以下是本错误信息详细报告：</div>';
                            
                            trigger_error(str_replace('class="error"','class="text-no"',preg_replace('/<h4>(.*?)<\/h4>/','',$array[1])), E_USER_ERROR);
                        }
                        
                        //mysql close
                        reader_mysql(true);
                        
                    }
                    
                }
                
                //echo $update;
            break;
            
            case "create":
    
                //检查权限
                $func = "sys-update-add";
                checker_func($func);
            
                //mysql open
                reader_mysql();
            
                $name = $_POST["name"];
                
                $action = "";
                
                if (!$name ){
                    
                    reader_redirect($jump,"备份名称不能为空！");
                    
                }elseif ( !preg_match('/^[^\/\\\?!\*]+$/',$name) ){
                    
                    reader_redirect($jump,"备份名称中有非法字符！");
                    
                }else{
                
                    ini_set("memory_limit","100M");
                
                    $i = 0;
                    
                    //缓存名称
                    $text='/*'.chr(13).'	VeryIDE'.chr(13).'	Database: backup'.chr(13).'	Name: '.$name.''.chr(13).'	Date: '.date("Y/m/d H:i:s").''.chr(13).'*/'.chr(13).chr(13);
                    
                    //遍历数据表
                    $q1=mysql_query("show tables",$mysql);
                    
                    while($t=mysql_fetch_array($q1)){
                        $table=$t[0];
                        
                        $q2=mysql_query("show create table `$table`");     
                        $sql=mysql_fetch_array($q2);
                        
                        $text.=$sql['Create Table'].";\r\n\r\n";#DDL     
                        
                        //遍历字段
                        $q3=mysql_query("select * from `$table`");
                        
                        while($data=mysql_fetch_assoc($q3)){     
                            $keys=array_keys($data);     
                            $keys=array_map('addslashes',$keys);     
                            $keys=join('`,`',$keys);     
                            $keys="`".$keys."`";     
                            $vals=array_values($data);     
                            $vals=array_map('addslashes',$vals);     
                            $vals=join("','",$vals);     
                            $vals="'".$vals."'";     
                               
                            $text.="insert into `$table`($keys) values($vals);\r\n";
                            
                             $i++;
                        }     
                        $text.="\r\n";     
                       
                       $i++;
                    }
                    
					//文件名为当天的日期
                    $file = $base.$name.".sql";
                    
                    if( create_file($file,$text) ){
            
                        //写入日志
                        event_insert($mysql,$func,time(),time(),"数据备份：".$file);				
                        
                        echo '<div id="state">恭喜！成功备份数据库，本次备份共记录 '.$i.' 条 SQL 语句。</div>';
                                
                    }else{
                        
                        echo '<div id="state" class="failure">抱歉！备份数据库失败。请确认 backup/ 目录有写权限。</div>';
                    }
                    
                    //mysql close
                    reader_mysql(true);
                    
                    ini_set("memory_limit","12M");
                    
                }
            
            break;
        }

    }
    
    ?>


    <table width="100%" border="0" cellpadding="1" cellspacing="1" class="table">
      <tr class="title">
        <td>ID</td>
        <td>备份文件</td>
        <td>文件大小</td>
        <td>备份时间</td>
        <td width="100">执行操作</td>
      </tr>
    <?php
    
    $item = "";
	
	//echo $base;
    
    if ($handle = opendir($base)) {
        
        $i=1;
        while (false !== ($file = readdir($handle))) {
			
			
			//echo $file;
			
            //SQL文件
            if(stripos($file,".sql")){
            
                //锁文件
                $lock = str_replace(".sql",".lock",$file);
                $val = file_exists($base.$lock);
                
                echo ("<tr class='line'>");
                echo ('<td>'.$i.'</td>');
                echo ('<td class="text-yes">'.$file.'</td>');
                
                echo ("<td>".GetFileSize(filesize($base.$file),"byte")."</td>");
                echo ("<td>".date("Y-m-d H:i:s",filemtime($base.$file))."</td>");
                
                echo '
                <td width="150">
                    <input name="" value="执行" type="button" class="button" onclick="location.href=\'?action=execute&update='.$file.'\';" />
                    <input name="" value="下载" type="button" class="button" onclick="location.href=\''.VI_BASE.'data/backup/'.$file.'\';" />
                </td>';
                
                echo ("</tr>");
                
                $i++;
            }
        }

        closedir($handle);
    }
    
    ?>
</table>
    
	<?php
    if( $Group["sys-backup-add"]=="Y" ){
    ?>
    
    <div id="box">
	    <form action="" method="post" name="from1" mode="edit" verify="true">
        
        <table cellpadding="0" cellspacing="0" class="form">
        
            <tr><td colspan="2" class="section"><strong>创建备份</strong></td></tr>
            
        	<tr>
            	<td width="60"><strong>备份名称：</strong></td>
                <td>
                	<input name="name" type="text" class="text" id="name" size="35" />
                    <a href="#" onclick="Mo('input[name=name]').value(this.innerHTML);void(0);"><?php echo date("Y-m-d");?></a>
                </td>
            </tr>
            <tr class="nobr">
                <td><strong></strong></td>
                <td>
                    <input name="action" type="hidden" id="action" value="create" />
                    <input type="submit" name="Submit" value="创建此备份" class="submit" />
                </td>
            </tr>
        
        </table>
        
        <div id="saving">
       		注意: 将只对数据库进行备份，以 SQL 语句形式存放。
        </div>
        
        </form>
	</div>
    
	<?php
    }
    ?>
	
</div>

<!--body end-->

<?php html_close();?>