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

		$this->display('Database/export');
	}

	public function start(){
		set_time_limit(0);
		$option = Q('get.');

		$get_table = $option['table'];

		$nowpage = Q('get.page','1');

		$limit     = $option['export-volume-num'];
		$vpage     = 1;

		//备份目录
		$backdir = 'Data/Backup/';

		//临时目录
		$tempdir = $backdir.'temp_'.Date('Ymd').session_id().'/';

		$tables = M()->getAllTableInfo(true);


		if(empty($get_table) || is_numeric($get_table)) {
			foreach ($tables['table']  as $value) {
				$tables_arr[] = $value;
				$isPage = round($value['rows']/$limit);
				$isPage = $isPage==0 ? 1 : $isPage;
				$totalPage +=$isPage;
			}

			$table = $tables_arr[$get_table];
			$backname = 'all';
		}else{
			$table = $tables['table'][$get_table];
			$backname = $table['tablename'];
		}

        $base_sql .= '-- MySQL Database Dump'.PHP_EOL;
        $base_sql .= '-- Created by Magic CMS, Power By QinTech Network. '.PHP_EOL;
        $base_sql .= '-- http://www.qintech.net '.PHP_EOL;
        $base_sql .= '--'.PHP_EOL ;
        $base_sql .= '-- 主机: '.C('DB_HOST').PHP_EOL;
        $base_sql .= '-- 生成日期: ' . date ( 'Y 年 m 月 d 日 ' ) . date ( 'H:i' ).PHP_EOL;
        $base_sql .= '-- MySQL版本: ' . mysql_get_server_info ().PHP_EOL;
        $base_sql .= '-- PHP 版本: ' . phpversion ().PHP_EOL;
        $base_sql .= '-- 数据库: `' . C('DB_DATABASE') . '`'.PHP_EOL;
        $base_sql .= '--'.PHP_EOL ;
        $base_sql .= '-- -------------------------------------------------------'.PHP_EOL ;

		if (!empty($table)) {
			if (!is_dir($tempdir)) {
				mkdir($tempdir,0777);
			}



			//创建表
			if ($option['export-strdata']=='structure' || $option['export-strdata']=='strdata') {

				$create_arr = M()->showCreate($table['tablename'],true);
				$create_sql .= PHP_EOL.PHP_EOL."--".PHP_EOL."-- 表的结构 `".$table['tablename']."` ".PHP_EOL."--".PHP_EOL.PHP_EOL;

				if ($option['export-drop-table']==1) {
					$create_sql .= "DROP TABLE IF EXISTS `".$table['tablename']."`--MagicCMS;".PHP_EOL;
				}

				if ($option['export-notexists-table']==1) {
					$create_sql .= str_ireplace("CREATE TABLE","CREATE TABLE IF NOT EXISTS",$create_arr['create']);
				}else{
					$create_sql .= $create_arr['create'];
				}

				$create_sql .= '--MagicCMS;'.PHP_EOL.PHP_EOL.'-- -------------------------------------------------------'.PHP_EOL ;
			}

			if ($option['export-strdata']=='data' || $option['export-strdata']=='strdata') {

				$page  = new Page($table['rows'],$limit);

				$data = M($table['tablename'],true)->limit($page->limit())->all();

				if (!empty($data)) {
						$i=0;
						$sql .= PHP_EOL.PHP_EOL."--".PHP_EOL."-- 转存表中的数据 `".$table['tablename']."` ".PHP_EOL."--".PHP_EOL.PHP_EOL;

						if ($option['export-type']=='UPDATE') {

						}else{
							$exe_sql = $option['export-type']." INTO `" . $table['tablename'] ."` ";
							foreach ($data  as $key=>$values) {
								foreach ($values  as $rkey=>$value) {
									if ($key==0) {
										$field[] = $rkey;
									}

									$value = str_replace(PHP_EOL,'\r\n',addslashes($value));
									if (is_numeric($value)) {
										$value_arr[$rkey] = $value;
									}else{
										$value_arr[$rkey] = "'".$value."'";
									}
								}

								if ($key==0) {
									$field_sql .= '(`'.implode('`,`',$field).'`) VALUES'.PHP_EOL;
								}

								if ($key%100!=0) {
									$value_arr_in[$i-1][$key] = "(".implode(",",$value_arr).")";
								}else{
									$value_arr_in[$i][$key] = "(".implode(",",$value_arr).")";
									$i++;
								}

							}
							foreach ($value_arr_in  as $field) {
								$sql .= $exe_sql.$field_sql.implode(','.PHP_EOL,$field)."--MagicCMS;".PHP_EOL;
							}

						}

						if ($nowpage<=1) {
							$value_sql .= $create_sql.$sql;
						}

						//分卷
						if ($option['export-volume']=='volume') {
							if($page->totalPage>$vpage && $nowpage>1){
								if($nowpage%$vpage==0){
									$backname  .= '_'.$table['tablename'].'_v'.$nowpage;
									$value_sql .=  $base_sql.$sql;
								}
							}
						}else{
							$value_sql .= $base_sql.$sql;
						}

				}else{
					$value_sql .= $create_sql;
				}
			}

			if ($nowpage< $page->totalPage) {
				$nowpage ++;
			}else{
				$get_table ++;
				$nowpage = 1;
			}

			//创建进度
			if(empty($get_table) || is_numeric($get_table)) {
				$get_st    = Q('get.st',1);
				$schedule = round(($get_st/$totalPage)*100);

			}else{
				$schedule = round(($nowpage/$page->totalPage)*100);
			}

			Files::writeFiles($tempdir.'Mac_'.$backname.'.sql',$value_sql,"a");
			$msg = '<p>正在导出：<b>'.$table['tablename'].'</b>表</p><p style="font-size:15px">不要关闭浏览器，请耐心等待......</p>';

			$uri['r'] = 'database-export-start';
			$uri['table'] = $get_table;
			$uri['export-type'] = $option['export-type'];
			$uri['export-volume'] = $option['export-volume'];
			$uri['export-volume-num'] = $option['export-volume-num'];
			$uri['export-strdata'] = $option['export-strdata'];
			$uri['export-drop-table'] = $option['export-drop-table'];
			$uri['export-notexists-table'] = $option['export-notexists-table'];
			$uri['page'] = $nowpage;
			$uri['st']   = $get_st+1;
			echo '<script>function jump(){window.location.href="?'.http_build_query($uri).'";};setTimeout("jump()",100);</script>';
		}else{
			//压缩存放
			$zip = new Zip();
			$compress = $zip->zipCompress($backdir.'Mac_'.rand_str(30).'.zip',$tempdir,$tempdir);
			Files::delDFlies($tempdir);
			$schedule = 100;
			if ($compress) {
				$msg = '<p>全部数据导出完成</p>';
				echo '<script>function jump(){location.href="?r=database-import";};setTimeout("jump()",2000);</script>';
			}else{
				$msg = '<p style="color:#f00">数据导出完成，但压缩存放失败！</p>';
			}
		}
		$this->assign('msg',$msg);
		$this->assign('step','start');
		$this->assign('schedule',$schedule);
		$this->display('Database/export');
	}
}