<?php
/*
* 后台控制函数库
* @author: moufer<moufer@163.com>
* @package: modoer
* @version: 1.0.0
* @copyright: www.modoer.com
* @Date: 2007-10-11 v1.0.0
*/
(!defined('IN_ADMIN') || !defined('IN_MUDDER')) && exit('Access Denied');

@set_time_limit(0);

// 获得模板文件的路径并解析
function cpheader() {
	global $charset, $_config;
	print <<< EOT
<!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>
<meta http-equiv="Content-Type" content="text/html; charset=$charset">
<link rel="stylesheet" type="text/css" id="css" href="{$_config[siteurl]}images/admin/admin.css">
<link rel="stylesheet" type="text/css" id="css" href="{$_config[siteurl]}images/jquery/ui.css">
<script src="{$_config[siteurl]}include/javascript/jquery.js" type="text/javascript"></script>
<script src="{$_config[siteurl]}include/javascript/common.js" type="text/javascript"></script>
<script src="{$_config[siteurl]}include/javascript/jquery-ui.js" type="text/javascript"></script>
</head>
<body>

EOT;

}

// 获取页面调试信息
function cpfooter() {
    global $db, $mudder_starttime, $_config, $_VERSION;
    $mtime = explode(' ', microtime());
    $totaltime = number_format(($mtime[1] + $mtime[0] - $mudder_starttime), 6);
    $gzip = $_config['gzipcompress'] ? 'enabled' : 'disabled';
    $sitedebug = 'Processed in '.$totaltime.' second(s), '.$db->query_num.' queries, Gzip '.$gzip;
	print <<< EOT

<div id="footer">
<small>Powered by <a href="http://www.modoer.com" target="_blank">Modoer $_VERSION[version]</a> &copy; 2007 - 2008, <a href="http://www.modoer.com" target="_blank">Moufer Studio</a></small><br />
<small>$sitedebug</small>
</div>
</body>
</html>
EOT;

}

function cptpl($file, $tpldir = '') {
    if($tpldir) {
        return $tpldir.$file.'.tpl.php';
    } else {
	    return MUDDER_ROOT.'./admin/templates/'.$file.'.tpl.php';
    }
}

function cpmsg($message, $url_forward = '', $msgtype = 'message') {
    global $action,$file;

    if($msgtype == 'message') {
		$message = html_special_chars($message);
    }
    if($url_forward && $url_forward != 'stop') {
        if(strposex($url_forward, '?') || strposex(strtolower($url_forward), 'javascript')) {
            $url_forward = $url_forward;
        } else {
            $url_forward .= $action ? '?action='.$action : '';
        }
    } elseif($url_forward != 'stop') {
        if(strposex($message, '请返回')) {
            $url_forward = 'javascript:history.go(-1);';
        } else {
            $url_forward = 'admincp.php'.($action ? '?action='.$action.'&file='.$file : '');
        }
    } else {
        $url_forward = null;
    }
    include cptpl('msg');
    cpfooter();
    cpoutput();
}

function cploginmsg($message, $url_forward='', $msgtype = 'message') {
    extract($GLOBALS, EXTR_SKIP);
    $url_forward = trim($url_forward);
    if($msgtype == 'message') {
		$message = html_special_chars($message);
    } else {
        $extra = isset($action) && $ction != 'logout' ? '?'.$_SERVER['QUERY_STRING'] : (in_array($action, array('header','menu','logout')) ? '' : '?'.$_SERVER['QUERY_STRING']);
    }
    include_once cptpl('loginmsg');
    cpoutput();
}

// 页面输出
function cpoutput() {
    global $_config;
    $output = ob_get_contents();
    ob_end_clean();
    $_config['gzipcompress'] ? ob_start('ob_gzhandler') : ob_start();
    echo $output;
    exit;
}

function istpldir($dir, $rootdir='./templates/main') {
	return is_dir(MUDDER_ROOT.'./'.$dir) && !in_array(substr($dir, -1, 1), array('/', '\\')) &&
		 strpos(realpath(MUDDER_ROOT.'./'.$dir), realpath(MUDDER_ROOT.$rootdir)) === 0;
}

function sqldumptable($table, $startfrom = 0, $currsize = 0) {
	global $db, $sizelimit, $startrow, $extendins, $sqlcompat, $dumpcharset;

	$offset = 300;
	$tabledump = '';

	if(!$startfrom) {
		$tabledump = "DROP TABLE IF EXISTS $table;\n";
		$createtable = $db->query("SHOW CREATE TABLE $table");
		$create = $db->fetch_row($createtable);
		$tabledump .= $create[1];

		if($sqlcompat == 'MYSQL41' && $db->version() < '4.1') {
			$tabledump = preg_replace("/TYPE\=(.+)/", "ENGINE=\\1 DEFAULT CHARSET=".$dumpcharset, $tabledump);
		}
		if($db->version() > '4.1' && $dumpcharset) {
			$tabledump = preg_replace("/(DEFAULT)*\s*CHARSET=.+/", "DEFAULT CHARSET=".$dumpcharset, $tabledump);
		}

		$query = $db->query("SHOW TABLE STATUS LIKE '$table'");
		$tablestatus = $db->fetch_array($query);
		$tabledump .= ($tablestatus['Auto_increment'] ? " AUTO_INCREMENT=$tablestatus[Auto_increment]" : '').";\n\n";
		if($sqlcompat == 'MYSQL40' && $db->version() >= '4.1') {
			if($tablestatus['Auto_increment'] <> '') {
				$temppos = strpos($tabledump, ',');
				$tabledump = substr($tabledump, 0, $temppos).' auto_increment'.substr($tabledump, $temppos);
			}
		}
	}

	$tabledumped = 0;
	$numrows = $offset;
	if($extendins == '0') {
		while($currsize + strlen($tabledump) < $sizelimit * 1000 && $numrows == $offset) {
			$tabledumped = 1;
			$rows = $db->query("SELECT * FROM $table LIMIT $startfrom, $offset");
			$numfields = $db->num_fields($rows);
			$numrows = $db->num_rows($rows);
			while($row = $db->fetch_row($rows)) {
				$comma = '';
				$tabledump .= "INSERT INTO $table VALUES (";
				for($i = 0; $i < $numfields; $i++) {
					$tabledump .= $comma.'\''.mysql_escape_string($row[$i]).'\'';
					$comma = ',';
				}
				$tabledump .= ");\n";
			}
			$startfrom += $offset;
		}
	} else {
		while($currsize + strlen($tabledump) < $sizelimit * 1000 && $numrows == $offset) {
			$tabledumped = 1;
			$rows = $db->query("SELECT * FROM $table LIMIT $startfrom, $offset");
			$numfields = $db->num_fields($rows);
			if($numrows = $db->num_rows($rows)) {
				$tabledump .= "INSERT INTO $table VALUES";
				$commas = '';
				while($row = $db->fetch_row($rows)) {
					$comma = '';
					$tabledump .= $commas." (";
					for($i = 0; $i < $numfields; $i++) {
						$tabledump .= $comma.'\''.mysql_escape_string($row[$i]).'\'';
						$comma = ',';
					}
					$tabledump .= ')';
					$commas = ',';
				}
				$tabledump .= ";\n";
			}
			$startfrom += $offset;
		}
	}

	$startrow = $startfrom;
	$tabledump .= "\n";
	return $tabledump;
}

function sizeunit($filesize) {
	if($filesize >= 1073741824) {
		$filesize = round($filesize / 1073741824 * 100) / 100 . ' GB';
	} elseif($filesize >= 1048576) {
		$filesize = round($filesize / 1048576 * 100) / 100 . ' MB';
	} elseif($filesize >= 1024) {
		$filesize = round($filesize / 1024 * 100) / 100 . ' KB';
	} else {
		$filesize = $filesize . ' bytes';
	}
	return $filesize;
}

function splitsql($sql) {
	$sql = str_replace("\r", "\n", $sql);
	$ret = array();
	$num = 0;
	$queriesarray = explode(";\n", trim($sql));
	unset($sql);
	foreach($queriesarray as $query) {
		$queries = explode("\n", trim($query));
		foreach($queries as $query) {
			$ret[$num] .= $query[0] == "#" ? NULL : $query;
		}
		$num++;
	}
	return($ret);
}

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_get_server_info() > '4.1' ? " ENGINE=$type DEFAULT CHARSET=$dbcharset" : " TYPE=$type");
}

function runQuery($sql) {
	global $dbcharset, $dbpre, $db; //$tablenum, $create_text;

	$sql = str_replace("\r", "\n", str_replace(' modoer_', ' '.$dbpre, $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;
		}
		$num++;
	}
	unset($sql);

	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);
				//$create_text .= '创建表 '.$name.' ... <font color="#0000EE">成功</font><br />';
				$db->query(createTable($query, $dbcharset));
				//$tablenum++;
			} else {
				$db->query($query);
			}
		}
	}
}

function removeDir($path) {
   if(substr($path, -1, 1) != "/") {
       $path .= "/";
   }
   $normal_files = glob($path . "*");
   $hidden_files = glob($path . "\.?*");
   $all_files = array_merge($normal_files, $hidden_files);

   foreach ($all_files as $file) {
       if(preg_match("/(\.|\.\.)$/", $file)) continue;
       if(is_file($file) === TRUE) unlink($file);
       elseif (is_dir($file) === TRUE) removeDir($file);
   }
   if(is_dir($path) === TRUE) rmdir($path);
}

function getModulekeys() {
    global $_modules;

    $result = array();
    if(is_array($_modules)) {
        foreach($_modules as $key => $val) {
            if(in_array($key,array('modoer','space'))) continue;
            $result[] = $key;
        }
    }
    return $result;
}

function getPluginkeys() {
    global $_plugins;

    $result = array();

    if(is_array($_plugins)) foreach($_plugins as $plugin) {
        $pmenu = array();
        $pmenu['title'] = $plugin['name'];
        $pmenu['module'] = $plugin['module'];
        if($plugin['menu']) foreach($plugin['menu'] as $_key => $_val) {
           $result[] = $_key;
        }
    }
    return $result;
}

function createDatacall($post, $type, $callid=0) {
    global $db,$dbpre;

    $post['calltype'] = $type;
    if($type == 'sql') {
        $post['fun'] = 'sql';
        foreach($post['expression'] as $key => $val) {
            $post['expression'][$key] = str_replace("\'","'",$val);
        }
    } elseif($type == 'fun') {
        $params = explode("\r\n", preg_replace("/\s*(\r\n|\n\r|\n|\r)\s*/", "\r\n", $post['expression']['params']));
        foreach($params as $val) {
            list($key,$value) = explode('=', $val);
            $post['expression'][$key] = str_replace("\'","'",$value);
        }
        unset($params, $post['expression']['params']);
        $post['hash'] = cacheIdentifier($post['expression']);
    } else {
        return;
    }
    $post['expression'] = addslashes(serialize($post['expression']));
    $post['hash'] = cacheIdentifier($post['expression']);

    if($callid > 0) {
        $post['callid'] = $callid;
        $db->update_new($dbpre.'datacall', "", $post, 1);
        // 删除过期/无效的缓存
        deleteDatacallCache($callid);
    } else {
        $db->insert_new($dbpre.'datacall', $post);
        $callid = $db->insert_id();
    }
    return $callid;
}

function deleteDatacallCache($callids, $force=0) {
    global $_config;

    if(!is_array($callids) && !is_numeric($callids)) return;
    $directory = MUDDER_ROOT.$_config['datacall_dir'].DIRECTORY_SEPARATOR;
    //echo 'aaa';
    if(@$handle = opendir($directory)) {
        $deletefiles = array();
        while (false !== ($file = readdir($handle))) {
            if($file == "." || $file == "..") continue;
            if($force) {
                $deletefiles[] = $file;
            } elseif(is_array($callids)) {
                foreach($callids as $callid) {
					if(empty($callid)) continue;	
                    $pattern = "cache_".$callid."_[0-9a-z]+\\.php";
                    if(preg_match('/^'.$pattern.'$/i', $file)) {
                        $deletefiles[] = $file;
                    }
                }
            } else if(preg_match("/^cache_".$callids."_[0-9a-z]+\\.php$/i", $file)) {
                    $deletefiles[] = $file;
            }
        }
        closedir($handle);
    }
    //echo 'bbb';
    if($deletefiles) {
        foreach($deletefiles as $file) {
            //pr($directory.$file);
            @unlink($directory.$file);
        }
    }
}

function deleteTemplateCache($dir) {
    $files = array();
    $cachedir = MUDDER_ROOT.'data/'.$dir;
    if ($handle = @opendir($cachedir)) {
        while (false !== ($file = @readdir($handle))) {
            if (preg_match('/^.+\.tpl\.php$/i', $file)) {
                $files[] = $file;
            }
        }
        closedir($handle);
    }
    
    if($files) foreach($files as $filename) {
        @unlink($cachedir.'/'.$filename);
    }
}
?>