<?php
/*
 本软件是开源代码，免费使用
 原作者: 看海
 修改者：程威（wiwiboy）
 郑州大学西亚斯国际学院网络信息技术专业
 电话：13733804908
 邮箱：wiwiboy@126.com
 QQ号：158839753
*/
error_reporting(E_ERROR | E_WARNING | E_PARSE);	

new RestoreTool;

class RestoreTool
{
    var $logged_in = 0;
    var $maximum_time = 0;

    function RestoreTool() {
        global $HTTP_GET_VARS, $HTTP_COOKIE_VARS, $password;

        $this->timestamp = time();

        if (!$this->maximum_time) 
        {
            //set_time_limit(0);
        	$this->maximum_time = ini_get('max_execution_time');
        }

        if ($HTTP_GET_VARS['act'] == 'login') 
        {
        	$this->do_login();
        }
        elseif ($password && $password != $HTTP_COOKIE_VARS['mysqltool']) 
        {
        	$this->login();        	
        }
        else 
        {
            if ($password) 
            {
            	$this->logged_in = 1;
            }

            switch ($HTTP_GET_VARS['act']) 
            {
                case 'logout':	
                    $this->logout();
                break;

                case 'change_db':
                    $this->read_db_details();
                    $this->set_database('如果你要变更当前连接的数据库，请在下面设置数据库信息:');
                break;

                case 'set_database':	
                    $this->do_set_database();
                break;

                case 'backup':	
                    $this->backup();
                break;

                case 'do_backup':	
                    $this->do_backup();
                break;

                case 'restore':	
                    $this->restore();
                break;

                case 'do_restore':
                    $this->do_restore();
                break;

                default:
                    
                    $this->main();
            }        	
        }

        if ($this->link) 
        {
        	mysql_close($this->link);
        }

        $this->output();
    }

    function timeout() {
        if (!$this->maximum_time)
        {
        	return false;
        }
        elseif ((time() - $this->timestamp) > ($this->maximum_time - 5)) 
        {
        	return true;
        }
        else 
        {
        	return false;
        }
    }

    function output() {
        if ($this->logged_in) 
        {
        	//$logout_text = ' <a href="mysql_tool.php?act=logout"><font style=\"color:#fff;font-weight:bold;\">[ 退出 ]</font></a>';
        }
        else 
        {
        	$logout_text = '';
        }

        if ($this->title) 
        {
        	$title = $this->title;
        }
        else 
        {
        	$title = 'PHPStat数据库备份恢复工具';
        }

        print '<?xml version="1.0" encoding="gb2312"?>';
        print <<<HTML

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<link href="../../style.css" rel="stylesheet" type="text/css">
<title>$title</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
{$this->meta}

<style type="text/css">
  
  BODY                            { font: 12px Verdana,宋体;  background-image: url(../../html/images/backgd2.gif); padding: 0; margin: 0 }
  a:link, a:visited, a:active     { color: #006699;text-decoration: none; }
  a:hover                         { color: #006699; text-decoration: none; }
  FORM                            { padding: 0; margin: 0 }

  .textbox                        { border: 1px solid black; padding: 1px; width: 100% }
  .headertable                    { background-color: #FFFFFF; border: 1px solid black; padding: 2px }
  .title                          { font-size: 12px; font-weight: bold; line-height: 150%; color: #FFFFFF; height: 26px; background-image: url(./tile_back.gif) }
  .table1                         { background-color: #FFFFFF; width: 100%; align: center; }
  .tablewrap                      { border: 1px dashed #777777; background-color: #F5F9FD; vertical-align: middle; }
  .tdrow1                         { background-color: #EEF2F7; padding: 3px }
  .tdrow2                         { background-color: #F5F9FD; padding: 3px }
  .tdtop                          { font-weight: bold; height: 24px; line-height: 150%; color: #FFFFFF; background-image: url(./tile_back.gif) }
  .note                           { margin: 10px; padding: 5px; border: 1px dashed #555555; background-color: #FFFFFF }
</style>
</head>

<body>
<br />
$this->output
<br />
<div align="center">
     <a href="mysql_tool.php"><font style="color:#000;font-weight:bold;">[ 返回 ]</font></a>  $logout_text <br /><br />
     <font style="color:#000;font-weight:bold;"> Copyright @ 2006-2007 phpstat.net   Power by phpstat.net phpstat inside </font>
</div>
</body>
</html>
HTML;
    }

    function error($error) {
        $this->output = <<<HTML
    <form method="post" action="mysql_tool.php?act=login">
      <table align="center" class="tablewrap" cellpadding="0" cellspacing="3" width="350">
        <tr>
          <td align="center" class="title">出现错误</td>
        </tr>
        <tr>
          <td>
            <table class="table1" align="center" width="100%">
              <tr>
                <td class="tdrow2" colspan="2"><div align="center">$error</div></td>
              </tr>
            </table>
          </td>
        </tr>
      </table>
    </form>
HTML;
    }

    function login() {
        $this->output = <<<HTML
    <form method="post" action="mysql_tool.php?act=login">
      <table align="center" class="tablewrap" cellpadding="0" cellspacing="3" width="350">
        <tr>
          <td align="center" class="title">PCS数据库备份恢复工具:: 请登陆</td>
        </tr>
        <tr>
          <td>
            <table class="table1" align="center" width="100%">
              <tr>
                <td width="100" class="tdrow1">输入密码</td>
                <td width="250" class="tdrow2"><input type="password" class="textbox" name="password"></td>
              </tr>
              <tr>
                <td class="tdrow2" colspan="2"><div align="center"><input type="submit" value="确定" class=pagebutton></div></td>
              </tr>
            </table>
          </td>
        </tr>
      </table>
    </form>
HTML;
    }

    function do_login() {
        global $HTTP_POST_VARS, $password;

        if ($HTTP_POST_VARS['password'] = "321") 
        {
            @setcookie ('mysqltool',$password,time()+3600*24*365);
            $this->logged_in = 1;
            $this->main();
        }
        else 
        {
        	$this->error('无效密码');
        }
    }

    function logout() {
        @setcookie ('mysqltool','',0);
        $this->logged_in = 0;
        $this->login();
    }

    function connect($return_errors = 0) {
        if (!$this->db['port']) 
        {
        	$this->db['port'] = '3306';
        }
        
        $error_text = '';

        $this->link = @mysql_connect ($this->db['host'] . ':' . $this->db['port'], $this->db['user'], $this->db['pass']); 

        if ($this->link)
        {
            if(!@mysql_select_db($this->db['name'],$this->link))
            {
                $error_text = '<strong>Failed selecting database "'.$this->db['name'].'"</strong><br /><br />'.@mysql_error($this->link);
            }
        }
        else
        {
            $error_text = '<strong>连接MYSQL数据库失败，请确认你的MYSQL用户名和密码</strong><br /><br />'.@mysql_error();
        }

        if ($return_errors) 
        {
        	return $error_text;
        }
        else 
        {
            if ($error_text) 
            {
                $this->error($error_text);
                return false;            	
            }
            else 
            {
            	return true;
            }
        }

    }

    function read_db_details() {
        if (file_exists('tool_settings.php')) 
        {
        	// Lets borrow IPB's settings
            include 'tool_settings.php';

            $this->db = $data;
        }
        elseif (file_exists('conf_global.php')) 
        {
        	// Lets borrow IPB's settings
            include 'conf_global.php';

            $this->db = array(
                'port'      =>      $INFO['sql_port'],
                'host'      =>      $INFO['sql_host'],
                'name'      =>      $INFO['sql_database'],
                'user'      =>      $INFO['sql_user'],
                'pass'      =>      $INFO['sql_pass'],
                'prefix'    =>      $INFO['sql_tbl_prefix']
            );
        }
        else 
        {
        	return false;
        }

        return true;
    }

    function do_set_database() {
        global $HTTP_POST_VARS;

        $this->db = array(
            'port'      =>      $HTTP_POST_VARS['port'],
            'host'      =>      $HTTP_POST_VARS['host'],
            'name'      =>      $HTTP_POST_VARS['name'],
            'user'      =>      $HTTP_POST_VARS['user'],
            'pass'      =>      $HTTP_POST_VARS['pass']
        );

        if (!$this->connect()) 
        {
        	return;
        }

        // Connection details are fine, let's continue

        $file_data = "<?php

\$data = array(
    'port'      =>      '{$HTTP_POST_VARS['port']}',
    'host'      =>      '{$HTTP_POST_VARS['host']}',
    'name'      =>      '{$HTTP_POST_VARS['name']}',
    'user'      =>      '{$HTTP_POST_VARS['user']}',
    'pass'      =>      '{$HTTP_POST_VARS['pass']}'
);

?".'>';
    
        $file_data = str_replace("\r\n","\n",$file_data);
        

        // Mkay, lets write the details
        if ($fp = fopen('tool_settings.php','w'))
        {
        	fwrite($fp,$file_data);
            fclose($fp);
        }
        else 
        {
        	$this->error('
            <strong>错误：无法写入 tool_settings.php</strong><br /><br />
            请设置文件夹为可写属性，UNIX主机设置为777，WINDOWS主机设置为666.Please CHMOD this file so it is writable. If this is not possible please create a file named "tool_settings.php" with the contents of the text box below:<br /><br />
            <div align="center">
            <textarea rows="10" cols="40">'.htmlentities($file_data).'</textarea>
            </div>');

            return false;
        }

        // Funky, lets roll
        $this->main();

        return true;
    }

    function set_database($error = false) {
        if (!$error) 
        {
        	$text = '无法找到数据库信息。如果你是第一次使用本系统，请在下面设置你的数据库信息:';
        }
        else 
        {
        	$text = $error;
        }

        $host = isset($this->db['host']) ? $this->db['host'] : 'localhost';
        $port = isset($this->db['port']) ? $this->db['port'] : '';
        $user = isset($this->db['user']) ? $this->db['user'] : '';
        $name = isset($this->db['name']) ? $this->db['name'] : '';

        $this->output = <<<HTML
    <form method="post" action="mysql_tool.php?act=set_database">
      <table align="center" class="tablewrap" cellpadding="0" cellspacing="3" width="450">
        <tr>
          <td align="center" class="line_title">数据库设置</td>
        </tr>
        <tr>
          <td>
            <div class="note">$text</div>
            <table class="table1" align="center" width="100%">
              <tr>
                <td width="100" class="tdrow1"><strong>服务器</strong><br /><em>(不确定请保持默认)</em></td>
                <td width="350" class="tdrow2"><input type="text" class="textbox" name="host" value="$host"></td>
              </tr>
              <tr>
                <td class="tdrow1"><strong>端口</strong><br /><em>(不知道请留空)</em></td>
                <td class="tdrow2"><input type="text" class="textbox" name="port" value="$port"></td>
              </tr>
              <tr>
                <td class="tdrow1"><strong>数据库名称</strong></td>
                <td class="tdrow2"><input type="text" name="name" class="textbox" value="$name"></td>
              </tr>
              <tr>
                <td class="tdrow1"><strong>数据库用户名</strong></td>
                <td class="tdrow2"><input type="text" name="user" class="textbox" value="$user"></td>
              </tr>
              <tr>
                <td class="tdrow1"><strong>数据库密码</strong></td>
                <td class="tdrow2"><input type="text" name="pass" class="textbox"></td>
              </tr>
              <tr>
                <td class="tdrow2" colspan="2"><div align="center"><input type="submit" value="Connect" class=pagebutton></div></td>
              </tr>
            </table>
          </td>
        </tr>
      </table>
    </form>
HTML;
    }

    function backup() {
        global $HTTP_POST_VARS;

        $this->read_db_details();
        $this->connect();

        $filename       = $HTTP_POST_VARS['filename'];
        $tables         = $HTTP_POST_VARS['tables'];
        $table_select   = $HTTP_POST_VARS['table_select'];
        $prefix         = $this->db['prefix'];

        switch ($tables) 
        {
            case 'all':
                $tables = mysql_list_tables($this->db['name']);
                while (list($table_name) = mysql_fetch_array($tables)) 
                {
                   $options[ $table_name ] = 0;
                }
            break;

        	case 'prefix':
                $tables = mysql_list_tables($this->db['name']);
                while (list($table_name) = mysql_fetch_array($tables)) 
                {
                    if (substr($table_name,0,strlen($prefix)) == $prefix) 
                    {
                    	$options[ $table_name ] = 0;
                    }
                }
            break;

            case 'selected':
                foreach ($table_select as $table_name) 
                {
                	$options[ $table_name ] = 0;
                }
        }

        if (!count($options)) 
        {
        	$this->error('No tables selected');
        }


        $data = base64_encode(serialize($options));

        $header = <<<DATA
-- SQL Dump
-- Backup script written by Mark Wraith 。
DATA;

        if (!$fp = fopen($filename, 'wb')) 
        {
        	return $this->error('无法写入数据,请设置文件夹属性为可写,UNIX主机设置为777.Unable to write to backup file. Please CHMod the current directory so it is writable');
        }
        fwrite($fp,$header);
        fclose($fp);

        $url = 'mysql_tool.php?act=do_backup&amp;file='.urlencode($filename).'&amp;data='.$data;

        $this->meta = '<meta http-equiv="refresh" content="1; url='.$url.'" />';
        $this->output = <<<HTML
      <table align="center" class="tablewrap" cellpadding="0" cellspacing="3" width="350">
        <tr>
          <td align="center" class="title">备份数据中...</td>
        </tr>
        <tr>
          <td>
            <table class="table1" align="center" width="100%">
              <tr>
                <td class="tdrow2" colspan="2">
                    <div align="center">数据开始备份<br /><br /><a href="$url">暂停备份请点这里</a></div>
                </td>
              </tr>
            </table>
          </td>
        </tr>
      </table>
HTML;
        
    }

    function do_backup() {
        global $HTTP_GET_VARS;

        $this->read_db_details();
        $this->connect();

        $data = unserialize(base64_decode($HTTP_GET_VARS['data']));
        $filename = $HTTP_GET_VARS['file'];

        $timedout = 0;
        $dump = '';

        foreach ($data as $table => $line) 
        {
            if (!$this->timeout()) 
            {
            	$returned = $this->backup_table($table, $line);

                if (is_array($returned)) 
                {
                	$timedout = 1;
                    $dump .= $returned[0];
                    $data[ $table ] = $returned[1];
                }
                else 
                {
                    $dump .= $returned;
                	unset($data[ $table ]);
                }
            }
            else 
            {
            	$timedout = 1;
            }
        }

        if (!$fp = fopen($filename, 'ab')) 
        {
        	return $this->error('无法写入数据,请设置当前文件夹属性为可写,UNIX主机设置为777.Unable to write to backup file. Please CHMod the current directory so it is writable');
        }
        fwrite($fp,$dump);
        fclose($fp);

        if ($timedout) 
        {
            $data = base64_encode(serialize($data));
            $url = 'mysql_tool.php?act=do_backup&amp;file='.urlencode($filename).'&amp;data='.$data;
            $this->meta = '<meta http-equiv="refresh" content="1; url='.$url.'" />';

            $this->output = <<<HTML
      <table align="center" class="tablewrap" cellpadding="0" cellspacing="3" width="350">
        <tr>
          <td align="center" class="title">备份中...</td>
        </tr>
        <tr>
          <td>
            <table class="table1" align="center" width="100%">
              <tr>
                <td class="tdrow2">
                    <div align="center">数据正在备份<br /><br /><a href="$url">如果你想终止备份请点这里</a></div>
                </td>
              </tr>
            </table>
          </td>
        </tr>
      </table>
HTML;
        }
        else 
        {
            $this->output = <<<HTML
      <table align="center" class="tablewrap" cellpadding="0" cellspacing="3" width="350">
        <tr>
          <td align="center" class="line_title">备份完成</td>
        </tr>
        <tr>
          <td>
            <table class="table1" align="center" width="100%">
              <tr>
                <td class="tdrow2">
                    数据备份已经完成,文件保存为:"$filename".<br /><br />
                    <a href="$filename"><font style="color:#000;font-weight:bold;">[ 点击这里下载备份文件 ]</font></a>
                </td>
              </tr>
            </table>
          </td>
        </tr>
      </table>
HTML;
        }

    }

    function backup_table($table,$start) {
        $dump = '';

        if (!$start) 
        {
            $result = mysql_query('SHOW CREATE TABLE '.$table);
            $row = mysql_fetch_assoc($result);

            $dump .= "\n\n--\n";
            $dump .= "-- Table structure for table '$table'\n";
            $dump .= "--\n\n";
            $dump .= str_replace( "`", "", $row['Create Table'] );
            $dump .= ";\n\n";

            $dump .= "\n\n--\n";
            $dump .= "-- Dumping data for table '$table'\n";
            $dump .= "--\n\n";     	
        }


        //
        // Records
        //

        $done = $start;
        $result = mysql_query('SELECT * FROM '.$table.' LIMIT '.$start.'');

        while ($row = mysql_fetch_row($result)) 
        {
            if ($this->timeout()) 
            {
             	return array($dump,$done);
            }

            $done++;

            foreach ($row as $id => $value) 
            {
                $value = str_replace('"','\\"',$value);
                $row[$id] = '"'.$value.'"';

            }

        	$dump .= 'INSERT INTO ' . $table . ' VALUES (' . implode(',',$row) . ");\n";
        }

        return $dump;
    }


    function main() {
        if (!$this->link) 
        {
            if (!$this->read_db_details()) 
            {
                return $this->set_database();
            }

            if ($error_text = $this->connect(1)) 
            {
                return $this->set_database($error_text);            	
            }        
        }


        $tables_to_backup = '';

        if ($this->db['prefix']) 
        {
        	$tables_to_backup .= '<input type="radio" name="tables" value="prefix" checked="checked" />IPB Tables Only <br />';
        	$tables_to_backup .= '<input type="radio" name="tables" value="all" />All<br />';
        }
        else 
        {
        	$tables_to_backup .= '<input type="radio" name="tables" value="all" checked="checked" id="all" /><label for="all">全部数据 / All</label><br />';        	
        }

        $tables = mysql_list_tables($this->db['name']);

        $options = '';
        while (list($table_name) = mysql_fetch_array($tables)) 
        {
           $options .= '<option value="'.$table_name.'">'.$table_name.'</option>';
        }

        $tables_to_backup .= <<<HTML
<input type="radio" name="tables" value="selected" id="table"/><label for="table">选择数据表 / Selected tables:</label><br />
<div style="margin-left: 40px">
    <select name="table_select[]" class="textbox" size="5" style="width: 250px" multiple="multiple">
$options
    </select>
</div>
HTML;


        $options = '';
        if ($dir = @opendir('./')) 
        {
            while ($file = readdir($dir)) 
            {
                $temp = strtolower($file);

                if ($file != '.' && $file != '..' && strpos($temp, '.sql')) 
                {
                    $options .= '<option value="'.$file.'">'.$file.'</option>';
                } 
            }  
            closedir($dir);
        }
        $restore_files = '<select name="filename" class="textbox">'.$options.'</select>';

        $restore_files .= '<br /><br /><u>或</u> 地址:<br /><br /><input type="text" name="relfilename" class="textbox" />';

        $this->output = <<<HTML
    <form method="post" action="mysql_tool.php?act=login">
      <table align="center" class="tablewrap" cellpadding="0" cellspacing="3" width="450">
        <tr>
          <td align="center" class="line_title">目前连接数据库信息</td>
        </tr>
        <tr>
          <td>
            <table class="table1" align="center" width="100%">
              <tr>
                <td width="150" class="tdrow1"><strong>主机 / 端口：</strong></td>
                <td width="300" class="tdrow2">{$this->db['host']}:{$this->db['port']}</td>
              </tr>
              <tr>
                <td class="tdrow1"><strong>数据库名：</strong></td>
                <td class="tdrow2">{$this->db['name']}</td>
              </tr>
              <tr>
                <td class="tdrow1"><strong>用户名：</strong></td>
                <td class="tdrow2">{$this->db['user']}</td>
              </tr>
              <tr>
                <td class="tdrow2" colspan="2"><div align="center"><a href="mysql_tool.php?act=change_db"><font style="color:#000;font-weight:bold;">[ 变更当前连接的数据库 ]</font></a></div></td>
              </tr>
            </table>
          </td>
        </tr>
      </table>
    </form>
<br /><br />
    <form method="post" action="mysql_tool.php?act=backup">
      <table align="center" class="tablewrap" cellpadding="0" cellspacing="3" width="450">
        <tr>
          <td align="center" class="line_title">备份设置/Backup Options</td>
        </tr>
        <tr>
          <td>
            <table class="table1" align="center" width="100%">
              <tr>
                <td width="150" class="tdrow1" valign="top"><strong>数据备份/Tables to backup:</strong></td>
                <td width="300" class="tdrow2">$tables_to_backup</td>
              </tr>
              <tr>
                <td class="tdrow1"><strong>文件名/Filename</strong><br><small>(备份文件将保存在mysql_tool.php同一目录下)</small></td>
                <td class="tdrow2"><input type="text" name="filename" class="textbox" value="sql_backup.sql"></td>
              </tr>
              <tr>
                <td colspan="2"><div align="center"><input type="submit" value="开始备份/Backup" class=pagebutton></div></td>
              </tr>
            </table>
          </td>
        </tr>
      </table>
    </form>
        <br /><br />
    <form method="post" action="mysql_tool.php?act=restore">
      <table align="center" class="tablewrap" cellpadding="0" cellspacing="3" width="450">
        <tr>
          <td align="center" class="line_title">数据恢复设置/Restore Options</td>
        </tr>
        <tr>
          <td>
            <table class="table1" align="center" width="100%">
              <tr>
                <td width="150" class="tdrow1" valign="top"><strong>选择需要导入的数据/SQL File to restore:</strong></td>
                <td width="300" class="tdrow2">$restore_files</td>
              </tr>
              <tr>
                <td class="tdrow2" colspan="2"><div align="center"><input type="submit" value="开始导入/Restore" class=pagebutton></div></td>
              </tr>
            </table>
          </td>
        </tr>
      </table>
    </form>
HTML;
    }

    function restore() {
        global $HTTP_POST_VARS;

        $this->read_db_details();
        $filename = $HTTP_POST_VARS['filename'];
        $relfilename = $HTTP_POST_VARS['relfilename'];

        if ($relfilename) 
        {
        	$filename = $relfilename;
        }

        $url = 'mysql_tool.php?act=do_restore&filename='.urlencode($filename);

            $this->output = <<<HTML
      <table align="center" class="tablewrap" cellpadding="0" cellspacing="3" width="350">
        <tr>
          <td align="center" class="line_title">确认恢复数据</td>
        </tr>
        <tr>
          <td>
            <table class="table1" align="center" width="100%">
              <tr>
                <td class="tdrow2">
                    <strong>你确定要恢复该数据文件?</strong><br /><br />
                    <a href="$url"><font style="color:#000;font-weight:bold;">[点击这里确定导入 "$filename" to "{$this->db['name']}"]</font></a>
                    <br /><br /><strong>注意:如果导入数据中包含的表/table,MYSQL数据库中已经存在,程序将提示出错</strong>

                </td>
              </tr>
            </table>
          </td>
        </tr>
      </table>
HTML;
    }

    function do_restore() {
        global $HTTP_GET_VARS;

        $filename = $HTTP_GET_VARS['filename'];
        $this->read_db_details();
        $this->connect();

        $filesize       = filesize($filename);
        $file_position  = isset($HTTP_GET_VARS['pos']) ? $HTTP_GET_VARS['pos'] : 0;
        $errors         = isset($HTTP_GET_VARS['ignore_errors']) ? 0 : 1;

        if (!$fp = fopen($filename,'rb')) 
        {
        	return $this->error('无法打开文件 "'.$filename.'"');
        }

        $buffer = '';
        $inside_quote = 0;
        $quote_inside = '';
        $started_query = 0;

        $data_buffer = '';

        $last_char = "\n";

        // Sets file position indicator
        fseek($fp,$file_position);

        while ((!feof($fp) || strlen($buffer)) && !$this->timeout()) 
        {
            do 
            {
                // Deals with the length of the buffer
                if (!strlen($buffer)) 
                {
                    $buffer .= fread ($fp,1024);
                }

                // Fiddle around with the buffers
                $current_char = $buffer[0];
                $buffer = substr($buffer, 1);


                if ($started_query)
                {
                    $data_buffer .= $current_char;
                } 
                elseif (preg_match("/[A-Za-z]/i",$current_char) && $last_char == "\n") 
                {
                    $started_query = 1;
                    $data_buffer = $current_char;
                } 
                else 
                {
                    $last_char = $current_char;
                }
            } while (!$started_query && (!feof($fp) || strlen($buffer)));


            if ($inside_quote && $current_char == $quote_inside && $last_char != '\\') 
            {
                // We were inside a quote but now we aren't so reset the flag and carry on
                $inside_quote = 0;
            } 
            elseif ($current_char == '\\' && $last_char == '\\')
            {
                $current_char = '';	
            } 
            elseif (!$inside_quote && ($current_char == '"' || $current_char == '`' || $current_char == '\''))
            {
                // We have just entered a new quote
                $inside_quote = 1;
                $quote_inside = $current_char;
            } 
            elseif (!$inside_quote && $current_char == ';') 
            {
                // End of query so execute query, clear data buffer and advance counter
                mysql_query($data_buffer);

                if ($errors && mysql_errno())
                {
                    $new_position = ftell($fp) - strlen($buffer);
                    return $this->restore_error($data_buffer, $new_position);
                }


                $data_buffer = '';
                $last_char = "\n";
                $started_query = 0;
            }

            $last_char = $current_char;
        }


        $new_position = ftell($fp) - strlen($buffer) - strlen($data_buffer);

        if (feof($fp)) 
        {
            $this->output = <<<HTML
      <table align="center" class="tablewrap" cellpadding="0" cellspacing="3" width="350">
        <tr>
          <td align="center" class="title">恢复数据完成</td>
        </tr>
        <tr>
          <td>
            <table class="table1" align="center" width="100%">
              <tr>
                <td class="tdrow2">
                    恢复数据已经完成.
                </td>
              </tr>
            </table>
          </td>
        </tr>
      </table>
HTML;
        }
        else 
        {
            $url = 'mysql_tool.php?act=do_restore&amp;filename='.urlencode($filename).'&amp;pos='.$new_position;

            if (!$errors) 
            {
            	$url .= '&ignore_errors=1';
            }

            $process = floor(($new_position / $filesize) * 100);

            $this->meta = '<meta http-equiv="refresh" content="5; url='.$url.'" />';
            $this->title = $process.'% Complete';
            $this->output = <<<HTML
      <table align="center" class="tablewrap" cellpadding="0" cellspacing="3" width="350">
        <tr>
          <td align="center" class="title">数据恢复中...</td>
        </tr>
        <tr>
          <td>
            <table class="table1" align="center" width="100%">
              <tr>
                <td class="tdrow2">
                    <div align="center">
                        <strong>恢复进度:已经有 <b>$process%</b> 完成.</strong>
                        <br /><br />
                        数据恢复中,请耐心等待.
                        <br /><br />
                        <a href="$url">点击这里暂停导入</a>
                    </div>
                </td>
              </tr>
            </table>
          </td>
        </tr>
      </table>
HTML;
        }

        fclose($fp);
       
    }

    function restore_error($query, $position) {
        global $HTTP_GET_VARS;

        $filename = $HTTP_GET_VARS['filename'];

        $url = 'mysql_tool.php?act=do_restore&filename='.urlencode($filename).'&pos='.$position;

        $mysql_error = mysql_error();

        $this->output = <<<HTML
      <table align="center" class="tablewrap" cellpadding="0" cellspacing="3" width="600">
        <tr>
          <td align="center" class="line_title">导入失败</td>
        </tr>
        <tr>
          <td>
            <table class="table1" align="center" width="100%">
              <tr>
                <td class="tdrow2">
                    <div align="center">
                        <strong>An error occurred due to an invalid query</strong>
                        <br /><br />
                        Query Executed: $query
                        <br />
                        MySQL Returned: $mysql_error
                        <br /><br />
                        <a href="$url"><font style="color:#000;font-weight:bold;">[跳过此错误继续恢复]</font></a><br /><br />
                        <a href="{$url}&ignore_errors=1"><font style="color:#000;font-weight:bold;">[跳过可能发生的所有错误继续导入]</font></a><br />
                    </div>
                </td>
              </tr>
            </table>
          </td>
        </tr>
      </table>
HTML;
    }
    
}


?>