<?php
require_once(dirname(__FILE__)."/admin_inc.php");
/*******************************************************************************************
' Software name: DJCMS Content Management System
' Version:3.0
' Web: http://www.djcms.net
' Author: 心情(qq:1130731)
' Copyright (C) 2009-2010 DJCMS官方 版权所有
' 法律申明：DJCMS程序所有代码100%原创、未引入任何网上代码,对一切抄袭行为、坚决严肃追究法律责任
'*******************************************************************************************/
viewHead("备份、压缩、还原数据库"."-" .$menuList[4][0]);
@set_time_limit(0);
$action = getForm("action", "get");
switch ($action) {
	case "delete" : delete();break;
	case "bakup" : bakUp();break;
	case "repair" : repair();break;
	case "repairtable" : repairtable();break;
	case "restore" : restore();break;
	case "changecharset" : changecharset();break;
	case "import" : import();break;
	case "down" : down();break;
	default : main();break;
}
viewFoot();

function main() {
	global $menuList;
	$djcms = array();
	$other = array();
	$query = DB::query("SHOW TABLE STATUS FROM `".databaseName."`");
    while($table = DB::fetch($query)) {
		$name = $table['Name'];
		$row = array('name'=>$name,'rows'=>$table['Rows'],'size'=>$table['Data_length']+$table['Index_length']);
		if (strpos($name, 'm_') === 0)
			$djcms[] = $row;
		else
			$other[] = $row;
	}
	$alltables = array('djcmstables'=>$djcms, 'othertables'=>$other)
?>
<div id="append_parent"></div>
<div class="container" id="cpcontainer">
<!--当前导航-->
<script type="text/JavaScript">if(parent.$('admincpnav')) parent.$('admincpnav').innerHTML='后台首页&nbsp;&raquo;&nbsp;<?php echo $menuList[4][0];?>&nbsp;&raquo;&nbsp; 数据库备份';</script>
<?php
		foreach ($alltables as $name => $tables) if ($tables) {
	?>
    <table class="tb"> 
    <tr class="thead">
      <td height="30" class="td_title" colspan="8">&nbsp;数据库备份</b></td>
    </tr>
		<form method="post" name="myform" id="myform" action="?action=bakup&tabletype=<?=$name?>">
		<tr>
			<th width="15%">选择</th>
			<th>数据库表</th>
			<th width="10%">记录条数</th>
			<th width="15%">使用空间</th>
		</tr>
		<?php
		if (is_array($tables)) foreach ($tables as $k => $tableinfo) {
		?>
	 	<tr>
		    <td class="align_c"><input type="checkbox" value="<?=$tableinfo['name']?>" name="tables[]"  checked  class="checkbox" /></td>
		    <td class="align_l"><?=$tableinfo['name']?></td>
		    <td class="align_c"><?=$tableinfo['rows']?></td>
			<td class="align_l"><?php echo sizecount($tableinfo['size']);?></td>
		</tr>
		<?php
		}
		?>
	  	<tr>
	    	<td colspan=4>分卷备份设置</th>
	  	</tr>
	  	<tr>
		    <td>每个分卷文件大小：</td>
		    <td colspan=3><input type=text name="sizelimit" value="2048" size=5> K</td>
	  	</tr>
	   	<tr>
		    <td>建表语句格式：</td>
		    <td colspan=3><input type="radio" name="sqlcompat" value="" checked class="checkbox"> 默认 &nbsp; <input type="radio" name="sqlcompat" value="MYSQL40" class="checkbox"> MySQL 3.23/4.0.x &nbsp; <input type="radio" name="sqlcompat" value="MYSQL41" class="checkbox"> MySQL 4.1.x/5.x &nbsp;</td>
	  	</tr>
	   	<tr>
		    <td>强制字符集：</td>
		    <td colspan=3><input type="radio" name="sqlcharset" value="" checked class="checkbox"> 默认 &nbsp; <input type="radio" name="sqlcharset" value="latin1" class="checkbox"> LATIN1 &nbsp; <input type="radio" name="sqlcharset" value='utf8' class="checkbox"> UTF-8</option></td>
	  	</tr>
	  	<tr>
		    <td></td>
		    <tr><td  colspan="6"><label>全选<input type="checkbox" name="chkall" id="chkall" class="checkbox" onclick="checkAll(this.checked,'input','tables[]')" /></label><label>反选<input type="checkbox" name="chkothers" id="chkothers" class="checkbox" onclick="checkOthers('input','tables[]')" /></label>&nbsp;&nbsp; <input type="submit" name="dosubmit" value=" 开始备份数据 " class="btn"></td>
	  	</tr>
		</form>
	</table>
	<?php
		}
	?>
<?php
}
function restore() {
	global $action,$menuList;
	$others = array();
	$sqlfiles = glob(DJ_ROOT.'inc/data/databasebak/*.sql');
	if (is_array($sqlfiles)) {
		$prepre = '';
		$info = $infos = $other = $others = array();
		foreach ($sqlfiles as $id => $sqlfile) {
			if(preg_match("/(djcmstables_[0-9]{8}_[0-9a-z]{4}_)([0-9]+)\.sql/i",basename($sqlfile),$num)) {
				$info['filename'] = basename($sqlfile);
				$info['filesize'] = round(filesize($sqlfile)/(1024*1024), 2);
				$info['maketime'] = date('Y-m-d H:i:s', filemtime($sqlfile));
				$info['pre'] = $num[1];
				$info['number'] = $num[2];
				if (!$id) $prebgcolor = '#CFEFFF';
				if ($info['pre'] == $prepre){
					$info['bgcolor'] = $prebgcolor;
				} else {
					$info['bgcolor'] = $prebgcolor == '#CFEFFF' ? '#F1F3F5' : '#CFEFFF';
				}
			    $prebgcolor = $info['bgcolor'];
				$prepre = $info['pre'];
				$infos[] = $info;
			} else {
				$other['filename'] = basename($sqlfile);
				$other['filesize'] = round(filesize($sqlfile)/(1024*1024),2);
				$other['maketime'] = date('Y-m-d H:i:s',filemtime($sqlfile));
				$others[] = $other;
			}
		}
	}
?>
<div id="append_parent"></div>
<div class="container" id="cpcontainer">
<!--当前导航-->
<script type="text/JavaScript">if(parent.$('admincpnav')) parent.$('admincpnav').innerHTML='后台首页&nbsp;&raquo;&nbsp;<?php echo $menuList[4][0];?>&nbsp;&raquo;&nbsp;数据库还原';</script>
<form method="post" id="myform" name="myform" >
<table class="tb">
<tr class="thead"><th colspan="7">备份的SQL文件管理</th></tr>
	<tr>
		<th width="8%">选中</th>
		<th>文件名</th>
		<th width="10%">文件大小</th>
		<th width="20%">备份时间</th>
		<th width="10%">卷号</th>
		<th width="15%">操作</th>
	</tr>
<?php
if (is_array($infos)) {
	foreach ($infos as $id => $info) {
$id++;
?>
  <tr bgcolor="<?=$info['bgcolor']?>" >
    <td class="align_c"><input type="checkbox" value="<?=$info['filename']?>" name="filenames[]"   class="checkbox" /></td>
    <td><a href="?action=down&filename=<?=$info['filename']?>"><?=$info['filename']?></a></td>
    <td class="align_c"><?=$info['filesize']?> M</td>
	<td class="align_c"><?=$info['maketime']?></td>
    <td class="align_c"><?=$info['number']?></td>
    <td class="align_c">
	<a href="?action=import&pre=<?=$info['pre']?>&dosubmit=1">导入</a> |
	<a href="?action=down&filename=<?=$info['filename']?>">下载</a>
	</td>
</tr>
<?php
	}
}
?>
 <tr><td  colspan="6"><label>全选<input type="checkbox" name="chkall" id="chkall" class="checkbox" onclick="checkAll(this.checked,'input','filenames[]')" /></label><label>反选<input type="checkbox" name="chkothers" id="chkothers" class="checkbox" onclick="checkOthers('input','filenames[]')" /></label><select name="tocharset">
	<option value="">不进行字符集转换</option>
	<option value="gbk2utf-8">GBK 转 UTF-8</option>
	<option value="utf-82gbk">UTF-8 转 GBK</option>
	<option value="big52utf-8">BIG5 转 UTF-8</option>
	<option value="utf-82big5">UTF-8 转 BIG5</option>
	</select>
<input type="submit"  style="width:90px" value="字符集转换"  class="btn" onclick="if($('tocharset').value==''){alert('请选择字符集转换');return false;};myform.action='?action=changecharset'" />&nbsp;&nbsp;<input type="submit" value="删除选中的备份" onclick="if(confirm('确定要删除吗')){myform.action='?action=delete';}else{return false}" class="btn"  />&nbsp;&nbsp; </td></tr>
</form>
</table>

<table class="tb">
<tr class="thead"><th colspan="7">非djcms备份的SQL文件</th></tr>
<form method="post" name="myform1" id="myform1" action="?action=delete">
	<tr>
	<th>选中</th>
	<th>ID</th>
	<th>文件名</th>
	<th>文件大小</th>
	<th>备份时间</th>
	<th>操作</th>
	</tr>
<?php
if (is_array($others)) {
	foreach ($others as $id => $other) {
$id++;
?>
  <tr>
    <td class="align_c">
    <input type="checkbox" value="<?=$other['filename']?>" name="filenames1[]"   class="checkbox" />
	</td>
    <td><?=$id?></td>
    <td><a href="?action=down&filename=<?=$other['filename']?>"><?=$other['filename']?></a></td>
    <td><?=$other['filesize']?> M</td>
	<td><?=$other['maketime']?></td>
    <td class="align_c">
	<a href="?action=import&filename=<?=$other['filename']?>">导入</a> |
	<a href="?action=down&filename=<?=$other['filename']?>">下载</a>
	</td>
</tr>
<?php
	}
}
?>
 <tr><td  colspan="6"><label>全选<input type="checkbox" name="chkall" id="chkall" class="checkbox" onclick="checkAll(this.checked,'input','filenames1[]')" /></label><label>反选<input type="checkbox" name="chkothers" id="chkothers" class="checkbox" onclick="checkOthers('input','filenames1[]')" /></label><select name="tocharset">
	<option value="">不进行字符集转换</option>
	<option value="gbk2utf-8">GBK 转 UTF-8</option>
	<option value="utf-82gbk">UTF-8 转 GBK</option>
	<option value="big52utf-8">BIG5 转 UTF-8</option>
	<option value="utf-82big5">UTF-8 转 BIG5</option>
	</select>
<input type="submit"  style="width:90px" value="字符集转换"  class="btn" onclick="if($('tocharset').value==''){alert('请选择字符集转换');return false;};myform1.action='?action=changecharset'" />&nbsp;&nbsp;<input type="submit" value="删除选中的备份" onclick="if(confirm('确定要删除吗')){myform1.action='?action=delete';}else{return false}" class="btn"  />&nbsp;&nbsp; </td></tr>
 </form>
</table>
<?php
}
function repair() {
	global $menuList;
	$tables = array();
	$query = DB::query("SHOW TABLES FROM `".databaseName."`");
	while ($r = mysql_fetch_row($query)) {
		$tables[] = $r[0];
	}
?>
<div id="append_parent"></div>
<div class="container" id="cpcontainer">
<!--当前导航-->
<script type="text/JavaScript">if(parent.$('admincpnav')) parent.$('admincpnav').innerHTML='后台首页&nbsp;&raquo;&nbsp;<?php echo $menuList[4][0];?>&nbsp;&raquo;&nbsp;数据库优化';</script>
<form method="post" name="myform" id="myform" action="?action=repairtable">
<table class="tb">
<tr class="thead"><th colspan="7">数据表优化和修复</th></tr>
	<tr>
	<th>选中</th>
	<th>数据表名</th>
	</tr>
<?php
if (is_array($tables)) {
	foreach ($tables as $table) {
?>
  <tr>
    <td><input type="checkbox" value="<?=$table?>" name="tables[]"   class="checkbox" /></td>
    <td><?=$table?></td>
</tr>
<?php
	}
}
?>
 <tr><td  colspan="2"><label>全选<input type="checkbox" name="chkall" id="chkall" class="checkbox" onclick="checkAll(this.checked,'input','tables[]')" /></label><label>反选<input type="checkbox" name="chkothers" id="chkothers" class="checkbox" onclick="checkOthers('input','tables[]')" />&nbsp;&nbsp;<input type="radio" name="operation" value="repair"  class="checkbox">修复表&nbsp;&nbsp;
      <input type="radio" name="operation" value="optimize" checked  class="checkbox">优化表&nbsp;&nbsp;
	  <input type="submit" name="dosubmit" value=" 提交 "  class="btn">&nbsp;&nbsp; </td></tr>
 </form>
</table>
<?php
}

function changecharset() {
	$tocharset = getForm("tocharset","post");$filenames = getForm("filenames","post");
	if (empty($tocharset)) { alertMsg("请选择字符集转换类型！","");last();}
	$charsets = explode('2',$tocharset);
	$from = $charsets[0];
	$to = $charsets[1];
	if ($filenames) {
		if(is_array($filenames)) {
			foreach ($filenames as $filename) {
				if (fileext($filename) == 'sql') {
					$str = file_get_contents(DJ_ROOT.'inc/data/databasebak/'.$filename);
					$str = str_charset($from, $to, $str);
					file_put_contents(DJ_ROOT.'inc/data/databasebak/'.$to.$filename, $str);
					@chmod(DJ_ROOT.'inc/data/databasebak/'.$to.$filename, 0777);
				}
			}
		} else {
			if (fileext($filenames) == 'sql') {
				$str = file_get_contents(DJ_ROOT.'inc/data/databasebak/'.$filenames);
				$str = str_charset($from, $to, $str);
				file_put_contents(DJ_ROOT.'inc/data/databasebak/'.$to.$filenames, $str);
				@chmod(DJ_ROOT.'inc/data/databasebak/'.$to.$filenames, 0777);
			}
		}
		alertMsg("操作成功！","?action=restore");
	}
	else
	   alertMsg("请选择字符集转换类型！","?action=restore");
}
	
function repairtable() {
	$tables = getForm("tables","post");$operation = getForm("operation","post");
	if (empty($tables)) {
		alertMsg("请选择要修复优化的表","");last();
	}
	$tables = is_array($tables) ? implode(',',$tables) : $tables;
	if ($tables && in_array($operation,array('repair','optimize'))) {
		DB::query("$operation TABLE $tables");
		alertMsg("操作成功！","?action=repair");
	} else {
		alertMsg("操作成功！","?action=repair");
	}
}
	
function import() {
	$fileid = getForm("fileid");$pre = getForm("pre");
	if($pre && fileext($pre) == 'sql') {
	    $filepath = DJ_ROOT.'inc/data/databasebak/'.$pre;
	    if(!file_exists($filepath)) { alertMsg("对不起,".$filepath."文件不存在","");last();}
	    $sql = file_get_contents($filepath);
	    sql_execute($sql);
	    alertMsg("".$pre."中的数据已经成功导入到数据库！","");
	} else {
		$fileid = $fileid ? $fileid : 1;
		$filename = $pre.$fileid.'.sql';
		$filepath = DJ_ROOT.'inc/data/databasebak/'.$filename;
		if (file_exists($filepath)) {
			$sql = file_get_contents($filepath);
			sql_execute($sql);
			$fileid++;
			echo "<br/>数据文件".$filename."导入成功！</font><br/></div>";
			echo "<script language=\"javascript\">setTimeout(\"makeNextPage();\",1000);function makeNextPage(){location.href='?action=import&pre=$pre&fileid=$fileid';}</script>";
			//alertMsg("数据文件".$filename."导入成功！","?action=import&pre=".$pre."&fileid=".$fileid."");
		} else {
			alertMsg("数据库恢复成功！","?action=restore");
		}
	}
}
	
function bakUp() {
	    global $db;
		$tables = getForm("tables","post");$tableid = getForm("tableid");$fileid = getForm("fileid");$tabletype = getForm("tabletype");
		$sqlcompat = getForm("sqlcompat","post");$sqlcharset = getForm("sqlcharset");$sizelimit = getForm("sizelimit");$random = getForm("random");$startfrom = getForm("startfrom");
		$dumpcharset = $sqlcharset ? $sqlcharset : str_replace('-', '', 'gbk');
		$fileid = isset($fileid) ? $fileid : 1;
		if ($fileid==1 && $tables) {
			if (!isset($tables) || !is_array($tables)){ alertMsg("请选择要备份的数据表！","");last();}
			$random = mt_rand(1000, 9999);
			cache_write('bakup_tables.php', $tables);
		} else {
			if(!$tables = cache_read('bakup_tables.php')){ alertMsg("请选择要备份的数据表！","");last();}
		}
		if ($db->version() > '4.1') {
			if ($sqlcharset) {
				DB::query("SET NAMES '".$sqlcharset."';\n\n");
			}
			if($sqlcompat == 'MYSQL40') {
				DB::query("SET SQL_MODE='MYSQL40'");
			} else if ($sqlcompat == 'MYSQL41') {
				DB::query("SET SQL_MODE=''");
			}
		}
		$tabledump = '';
		$tableid = isset($tableid) ? $tableid - 1 : 0;
		$startfrom = isset($startfrom) ? intval($startfrom) : 0;
		for ($i = $tableid; $i < count($tables) && strlen($tabledump) < $sizelimit * 1000; $i++) {
			global $startrow;
			$offset = 100;
			if (!$startfrom) {
				$tabledump .= "DROP TABLE IF EXISTS `$tables[$i]`;\n";
				$createtable = DB::query("SHOW CREATE TABLE `$tables[$i]` ");
				$create = mysql_fetch_row($createtable);
				$tabledump .= $create[1].";\n\n";
				if ($sqlcompat == 'MYSQL41' && $db->version() < '4.1') {
					$tabledump = preg_replace("/TYPE\=([a-zA-Z0-9]+)/", "ENGINE=\\1 DEFAULT CHARSET=".$dumpcharset, $tabledump);
				}
				if ($db->version() > '4.1' && $sqlcharset) {
					$tabledump = preg_replace("/(DEFAULT)*\s*CHARSET=[a-zA-Z0-9]+/", "DEFAULT CHARSET=".$sqlcharset, $tabledump);
				}
			}
			$numrows = $offset;
			while (strlen($tabledump) < $sizelimit * 1000 && $numrows == $offset) {
				$rows = DB::query("SELECT * FROM `$tables[$i]` LIMIT $startfrom, $offset");
				$numfields = mysql_num_fields($rows);
				$numrows = mysql_num_rows($rows);
				while ($row = mysql_fetch_row($rows)) {
					$comma = "";
					$tabledump .= "INSERT INTO `$tables[$i]` VALUES(";
					for ($j = 0; $j < $numfields; $j++) {
						$tabledump .= $comma."'".mysql_escape_string($row[$j])."'";
						$comma = ",";
					}
					$tabledump .= ");\n";
				}
				//db::free_result($rows);
				$startfrom += $offset;
			}
			$tabledump .= "\n";
			$startrow = $startfrom;
			$startfrom = 0;
		}

		if (trim($tabledump)) {
			$tabledump = "# djcms bakfile\n# version:".$cfg_version."\n# time:".date('Y-m-d H:i:s')."\n# type:djcms\n# djcms:http://www.djcms.net\n# --------------------------------------------------------\n\n\n".$tabledump;
			$tableid = $i;
			$filename = $tabletype.'_'.date('Ymd').'_'.$random.'_'.$fileid.'.sql';
			$altid = $fileid;
			$fileid++;
			$bakfile = DJ_ROOT.'inc/data/databasebak/'.$filename;
			if (!is_writable(DJ_ROOT.'inc/data/databasebak/')) { alertMsg("数据无法备份到服务器！请检查 ./data/bakup 目录是否可写。","");last();}
			file_put_contents($bakfile, $tabledump);
			@chmod($bakfile, 0777);
			//$filename = '分卷：'.$altid.'#';
			echo "<br/>备份文件"." $filename "."写入成功！</font><br/></div>";
			echo "<script language=\"javascript\">setTimeout(\"makeNextPage();\",1000);function makeNextPage(){location.href='?action=$action&sizelimit=$sizelimit&sqlcompat=$sqlcompat&sqlcharset=$sqlcharset&tableid=$tableid&fileid=$fileid&startfrom=$startrow&random=$random&dosubmit=1&tabletype=$tabletype';}</script>";
			//alertMsg("备份文件"." $filename "."写入成功！",'?action='.$action.'&sizelimit='.$sizelimit.'&sqlcompat='.$sqlcompat.'&sqlcharset='.$sqlcharset.'&tableid='.$tableid.'&fileid='.$fileid.'&startfrom='.$startrow.'&random='.$random.'&dosubmit=1&tabletype='.$tabletype.'&allow='.$allow);
		} else {
		   cache_delete('bakup_tables.php');
		   alertMsg("数据库备份完毕！","admin_database.php");
		}
}

function delete() {
	global $action;
	$filenames = getForm("filenames","post");$filenames1 = getForm("filenames1","post");
	if (empty($filenames)) $filenames = $filenames1;
	if ($filenames) {
		if (is_array($filenames)) {
			foreach ($filenames as $filename) {
				if(fileext($filename) == 'sql') {
					@unlink(DJ_ROOT.'inc/data/databasebak/'.$filename);
				}
			}
			alertMsg("操作成功！","?action=restore");
		} else {
			if (fileext($filenames) == 'sql') {
				@unlink(DJ_ROOT.'inc/data/databasebak/'.$filenames);
				alertMsg("操作成功！","?action=restore");
			}
		}
	}
	else
	alertMsg("请选择要删除的文件！","?action=restore");
}
	
function down() {
	$filename = getForm("filename","get");
	$fileext = fileext($filename);
	if ($fileext != 'sql') {
		alertMsg("对不起，只允许下载sql格式的文件！","?action=restore");
	}
	file_down(DJ_ROOT.'inc/data/databasebak/'.$filename);

}

function file_down($filepath, $filename = '') {
	if (!$filename) $filename = basename($filepath);
	if (is_ie()) $filename = rawurlencode($filename);
	$filetype = fileext($filename);
	$filesize = sprintf("%u", filesize($filepath));
	if (ob_get_length() !== false) @ob_end_clean();
	header('Pragma: public');
	header('Last-Modified: '.gmdate('D, d M Y H:i:s') . ' GMT');
	header('Cache-Control: no-store, no-cache, must-revalidate');
	header('Cache-Control: pre-check=0, post-check=0, max-age=0');
	header('Content-Transfer-Encoding: binary');
	header('Content-Encoding: none');
	header('Content-type: '.$filetype);
	header('Content-Disposition: attachment; filename="'.$filename.'"');
	header('Content-length: '.$filesize);
	readfile($filepath);
	exit;
}

function sql_execute($sql) {
    $sqls = sql_split($sql);
	if (is_array($sqls)) {
		foreach ($sqls as $sql) {
			if (trim($sql) != '') {
				DB::query($sql);
			}
		}
	} else {
		DB::query($sqls);
	}
	return true;
}

function sql_split($sql) {
	global $db;
	if ($db->version() > '4.1') {
		$sql = preg_replace("/TYPE=(InnoDB|MyISAM|MEMORY)( DEFAULT CHARSET=[^; ]+)?/", "TYPE=\\1 DEFAULT CHARSET='gbk'",$sql);
	}
	$sql = str_replace("\r", "\n", $sql);
	$ret = array();
	$num = 0;
	$queriesarray = explode(";\n", trim($sql));
	unset($sql);
	foreach ($queriesarray as $query) {
		$ret[$num] = '';
		$queries = explode("\n", trim($query));
		$queries = array_filter($queries);
		foreach ($queries as $query) {
			$str1 = substr($query, 0, 1);
			if ($str1 != '#' && $str1 != '-') $ret[$num] .= $query;
		}
		$num++;
	}
	return($ret);
}

function is_ie() {
	$useragent = strtolower($_SERVER['HTTP_USER_AGENT']);
	if ((strpos($useragent, 'opera') !== false) || (strpos($useragent, 'konqueror') !== false)) return false;
	if (strpos($useragent, 'msie ') !== false) return true;
	return false;
}	

function fileext($filename) {
	return strtolower(trim(substr(strrchr($filename, '.'), 1, 10)));
}

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

function cache_read($file, $path = '', $iscachevar = 0) {
	if(!$path) $path = DJ_ROOT.'/cache/';
	$cachefile = $path.$file;
	if ($iscachevar) {
		global $TEMP;
		$key = 'cache_'.substr($file, 0, -4);
		return isset($TEMP[$key]) ? $TEMP[$key] : $TEMP[$key] = @include $cachefile;
	}
	return @include $cachefile;
}

function cache_write($file, $array, $path = '') {
	if(!is_array($array)) return false;
	$array = "<?php\nreturn ".var_export($array, true).";\n?>";
	$cachefile = ($path ? $path : DJ_ROOT.'/cache/').$file;
	$strlen = file_put_contents($cachefile, $array);
	@chmod($cachefile, 0777);
	return $strlen;
}

function cache_delete($file, $path = '') {
	$cachefile = ($path ? $path : DJ_ROOT.'/cache/').$file;
	return @unlink($cachefile);
}
?>
