<?php

/*
*	Copyright VeryIDE,2007-2010
*	http://www.veryide.com/
*
*	SQL 执行函数包
*
*	$Id: sql.php,v2.0 14:01 2009-03-31 Leilei $
*/

//读取数据
if(!function_exists('file_put_contents')) {
	function file_put_contents($filename, $s) {
		$fp = @fopen($filename, 'w');
		@fwrite($fp, $s);
		@fclose($fp);
		return TRUE;
	}
}

//创建表
function createtable($sql, $dbcharset) {
	$type = strtoupper(preg_replace("/^\s*CREATE TABLE\s+.+\s+\(.+?\).*(ENGINE|TYPE)\s*=\s*([a-z]+?).*$/isU", "\\2", $sql));
	$type = in_array($type, array('MYISAM', 'HEAP')) ? $type : 'MYISAM';
	return preg_replace("/^\s*(CREATE TABLE\s+.+\s+\(.+?\)).*$/isU", "\\1", $sql);
}

//查询MySQL
function runquery($mysql , $sql) {
	global $lang, $dbcharset, $tablepre, $db;

	//前辍
	$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);
	
	//用户
	$sql = str_replace("{TableAdmin}",$_SESSION["Manager"]["account"]?$_SESSION["Manager"]["account"]:'admin',$sql);

	$sql = str_replace("\r", "\n", $sql);
	
	$ret = array();
	$num = 0;
	foreach(explode(";\n", trim($sql)) as $query) {
		$queries = explode("\n", trim($query));
		foreach($queries as $query) {
			$ret[$num] .= $query[0] == '#' || $query[0].$query[1] == '--' ? '' : $query;
		}
		$num++;
	}
	unset($sql);
	
	$succ = array();	//成功
	$fail = array();	//失败
	
	$ERR = 0;
	$MID = 0;

	foreach($ret as $query) {
		$query = trim($query);
		if($query) {
		
			if(substr($query, 0, 12) == 'CREATE TABLE') {
				$name = preg_replace("/CREATE TABLE ([a-z0-9_]+) .*/is", "\\1", $query);
				
				mysql_query(createtable($query, $dbcharset),$mysql);
				
				if(mysql_errno()){
					//$state .= '<h4>创建数据表出错</h4><p class="error">'.mysql_error().'</p>';
					
					array_push($fail,array('message'=>'创建数据表出错','query'=>$query,'error'=>mysql_error()));
					
					$ERR++;
				}else{
					//$state .= '<h4>成功创建数据表</h4><p class="note">'.$query.'</p>';
					
					array_push($succ,array('message'=>'成功创建数据表','query'=>$query));
				}

			} else {
				
				/*
				if($state && !$space){
					$state .= '<hr />';
					$space = true;
				}
				*/
			
				//菜单ID
				if(substr($query, 0, 11) == 'INSERT INTO' && stripos($query,"{TableMenu}") === false) {
					mysql_query($query,$mysql);
					$MID = mysql_insert_id();
				}else{
					$query = str_replace("{TableMenu}",$MID,$query);
					mysql_query($query,$mysql);
				}
				
				if(mysql_errno()){
					//$state .= '<h4>写入数据出错</h4><p class="error">'.mysql_error().'</p>';
					array_push($fail,array('message'=>'执行查询出错','query'=>$query,'error'=>mysql_error()));
					$ERR++;
				}else{
					//$state .= '<h4>成功写入数据</h4><p class="note">'.$query.'</p>';
					array_push($succ,array('message'=>'成功执行查询','query'=>$query));
				}
			}

		}
	}
	
	return array('err'=>$ERR,'succ'=>$succ,'fail'=>$fail);
}

//////////////////////////

//保存配置
function saveconfig( $file, $mysql_host, $mysql_port, $mysql_db, $mysql_user, $mysql_password, $mysql_manpre ,$mysql_modpre ) {

	$success = false;
	
	if( !$file ) return false;
	
	if($content = file_get_contents($file)) {
		$content = trim($content);
		
		$content = insertconfig($content, "/define\('VI_BASE',\s*'.*?'\);/i", "define('VI_BASE', '".dirname($_SERVER["REQUEST_URI"])."/"."');");

		//VeryIDE 所在 URL
		$http = uripath(true);		

		$content = insertconfig($content, "/define\('VI_HOST',\s*'.*?'\);/i", "define('VI_HOST', '$http');");		
		
		$content = insertconfig($content, "/define\('VI_START',\s*'.*?'\);/i", "define('VI_START', '".time()."');");
		
		$content = insertconfig($content, "/define\('VI_DBHOST',\s*'.*?'\);/i", "define('VI_DBHOST', '$mysql_host');");
		$content = insertconfig($content, "/define\('VI_DBPORT',\s*'.*?'\);/i", "define('VI_DBPORT', '$mysql_port');");
		$content = insertconfig($content, "/define\('VI_DBNAME',\s*'.*?'\);/i", "define('VI_DBNAME', '$mysql_db');");
		$content = insertconfig($content, "/define\('VI_DBUSER',\s*'.*?'\);/i", "define('VI_DBUSER', '$mysql_user');");
		$content = insertconfig($content, "/define\('VI_DBPASS',\s*'.*?'\);/i", "define('VI_DBPASS', '$mysql_password');");
		
		$content = insertconfig($content, "/define\('VI_DBMANPRE',\s*'.*?'\);/i", "define('VI_DBMANPRE', '$mysql_manpre');");
		$content = insertconfig($content, "/define\('VI_DBMODPRE',\s*'.*?'\);/i", "define('VI_DBMODPRE', '$mysql_modpre');");

		if(@file_put_contents($file, $content)) {
			$success = true;
		}
	}

	return $success;
}

//写入配置
function insertconfig($s, $find, $replace) {
	if(preg_match($find, $s)) {
		$s = preg_replace($find, $replace, $s);
	} else {
		// 插入到最后一行
		$s .= "\r\n".$replace;
	}
	return $s;
}

//////////////////////////


?>