<?php
 /**
 * Magic CMS 数据库导入
 * ============================================================================
 * Copyright 2014 大秦科技，并保留所有权利。
 * 网站地址: http://www.qintech.net；
 * ----------------------------------------------------------------------------
 * 未获商业授权之前，不得将Magic CMS用于商业用途（包括但不限于企业网站、经营性网站
 * 以营利为目的或实现盈利的网站）未经官方许可，禁止在Magic CMS的整体或任何部分基础
 * 上以发展任何派生版本、修改版本或第三方版本用于重新分发。如果您未能遵守本协议的
 * 条款，您的授权将被终止，所被许可的权利将被收回，并承担相应法律责任。
 * ============================================================================
 * Date:2014/12/31
**/
class ImportModule extends CommonModule{

	public function __construct(){
		$this->backdir = 'Data/Backup/';
	}
	public function index(){
		$list = Files::getfile($this->backdir,'zip',2);
		$this->assign('list',$list);
		$this->assign('step','index');
		$this->display('Database/import');
	}
	
	public function download(){
		$filename = Q('get.file');
		Http::download($this->backdir.$filename,$filename);
	}
	
	public function del(){
		$filename = Q('get.file');
		$table    = Q('get.table');
		if (@unlink($this->backdir.$filename)) {
			$this->success('删除成功','?r=database-import&table='.$table);
		}else{
			$this->error('删除失败');
		}
	}

	public function start(){
		set_time_limit(0);
		$step     = Q('get.step',1);
		$filename = Q('get.file',0);
		$pathinfo = pathinfo($filename);
		$schedule = 0;

		if ($step==1) {
			if (empty($filename)) {
				$this->alert('参数错误');
				exit;
			}
			$this->assign('msg','<p>即将解压备份文件</p>');
			echo '<meta http-equiv="refresh" content="1; url=?r=database-import-start&step=2&file='.$filename.'">';

		}elseif($step==2){

			if (!is_dir ($tempdir)) {
				mkdir ($tempdir, 0777, true);
			}
			
			//解压临时文件夹
			$tempdir = $this->backdir.'temp_'.$pathinfo['filename'];

			$zip = new Zip();

			$decompress = $zip->zipDecompress($this->backdir.$filename,$tempdir);

			if ($decompress) {
				$this->assign('msg','<p>解压完成，即将导入备份文件</p>');
				echo '<meta http-equiv="refresh" content="1; url=?r=database-import-start&step=3&file='.$tempdir.'">';
			}else{
				Files::delDFlies($tempdir);
				$this->assign('msg','<p style="color:#f00">解压文件失败！</p>');
			}
		}elseif($step==3){
			$v = Q('get.v',0);
		
			//读取所有文件
			$files = Files::getfile($filename,'sql',2);
	
			if(!empty($files)) {
				if (!empty($files[$v]['fullpath'])) {
					if (file_exists($files[$v]['fullpath'])) {
						$fh = fopen ($files[$v]['fullpath'], "rb" );
					
						if ($fh) {
							while (!feof($fh)) {
								$sql = stream_get_line($fh,10000000, "--MagicCMS;");
							
								//去除注释
								$sql = preg_replace("/--.*\n/iU","",$sql);
								//去除多余的空格换行
								$sql = preg_replace("/((\s)*(\n)+(\s)*)/i","",$sql);
								
								if (!empty($sql)) {
									M()->exe($sql);
								}
								$sql = '';
							}
						}
					
						fclose ($fh);

						//计算进度
						$schedule = round(($v/count($files))*100);

						$this->assign('msg','<p>正在导入'.$files[$v]['name'].'</p><p style="font-size:15px">请不要关闭浏览器，否则将导致导入失败</p>');
						echo '<script>function jump(){window.location.href="?r=database-import-start&step=3&file='.$filename.'&v='.($v+1).'";};setTimeout("jump()",100);</script>';
					}
				}else{
					$schedule = 100;
					if (Files::delDFlies($filename)) {
						$this->assign('msg','<p>全部数据导入完成</p>');
						echo '<script>function jump(){parent.location.href="?r=database";};setTimeout("jump()",2000);</script>';
					}else{
						$this->assign('msg','<p>全部数据导入完成，但临时文件删除失败，请手动删除</p>');
					}
				}
			}else{
				
				$this->assign('msg','<p style="color:#f00">未发现备份文件！</p>');
			}	
		}
		$this->assign('schedule',$schedule);
		$this->assign('step','start');
		$this->display('Database/import');
	}
}