<?php
function commonCache() {
	global $_SET;
	qbase::deletedir(C_P . "/acategory/");
	qbase::deletedir(C_P . "/channel/");
	cache::delete("menu_list");
	$_MODULEs = array();
	$_MODULE_result = qdb::fetchAll("select id,pid,name,table_name,appname,admin_php,user_list_php,user_list_last_php,user_content_php,is_showpage from ".TABLEPRE."module where `is_lock`=0");
	foreach($_MODULE_result as $_MODULE){
		$temp  = qdb::fetchAll("select eid, ext, type from ".TABLEPRE."extend where id = '{$_MODULE['id']}' order by ordering desc");
		$_MODULE['extend'] = array();
		foreach($temp as $val){
			$_MODULE['extend'][$val['eid']] = $val;
		}
		foreach($_MODULE['extend'] as $key=>$val){
			$_MODULE['extend'][$key]['type'] = $_MODULE['extend'][$key]['type'] == 'checkbox' ? 1 : 0;
		}
		$_MODULEs[$_MODULE['id']] = $_MODULE;
	}
	$cache['module'] = "\$_MODULE=" . var_export($_MODULEs, true) . ";";
	$channel_result = qdb::fetchAll("select * from ".TABLEPRE."channel where link=0 order by displayorder ASC");
	foreach($channel_result as $channel) {
		if ($channel['is_link'] == 0) {
			$channels[$channel['channelid']] = $channel;
		} 
	} 
	$cache['channels'] = "\$channel=" . var_export($channels, true) . ";";
	$string = str_replace(array(" ", "\n"), "", implode("", $cache));
	qbase::writetofile(R_P . "/cache/config/common.php", "<?php\n" . $string . "\n?>");
	clearstatcache();
	qbase::get_object('event', 'cache', array());
} 
function getPicModCache($channelid){
	if($channelid > 0){
		return qdb::fetchAll("select * from ".TABLEPRE."pic_setting where channelid = '{$channelid}' order by id asc ");
	}else{
		$temp = qdb::fetchAll("select * from ".TABLEPRE."pic_setting ");
		$data = array();
		foreach($temp as $val){
			$data[$val['channelid']][] = array(
				'w'=>$val['w'],
				'h'=>$val['h'],
				'name'=>$val['name'],
				'type'=>$val['type']
			);
		}
		return $data;
	}
}
function servercache() {
	return qbase::get_object('server')->cache();
} 
function memebrmanage($channelid) {
	$strall = "";
	$menus = qbase::get_object('category', $channelid)->get();
	foreach($menus as $cat) {
		$strall .= "<tr class='item' onclick=\"var mo=this.getElementsByTagName('input');mo[mo.length-1].checked=mo[mo.length-1].checked?false:true;\" rel='{$cat['cupid']}' onmouseout=\"removeClassName(this,'item-hover');\" onmouseover=\"addClassName(this,'item-hover');\"><td align=center class='tablerowl'>" . $cat['cid'] . "</td><td style='padding-left:12px;'>" . $cat['str']. $cat['title'] . "</td><td>{$cat['description']}</td><td align='center'><input type=\"checkbox\" value=\"{$cat[cid]}-{$cat[arrchildids]}\" id=\"ids_{$cat[cid]}\" name=\"manage{$channelid}[]\" onclick=\"try{event.cancelBubble=true;}catch(e){event.stopPropagation();}\" /></td>";
	} 
	$strall = str_replace("\"", "\\\"", $strall);
	$js = qbase::readfromfile("images/js/purview.js");
	$js = str_replace("{strall}", $strall, $js);
	echo "<script type='text/javascript'>" . $js . "</script>";
} 
function TemplateSelect() {
	global $templatefile, $templatefiles;
	$data = opendir(R_P . "/templates/");
	while ($templatefile = readdir($data)) {
		if ($templatefile != '.' && $templatefile != '..' && is_dir(R_P . "/templates/" . $templatefile)) {
			$templatefiles[] = $templatefile;
		} 
	} 
	closedir($data);
} 

function GetTimeOff() {
	global $_SET;
	$file = R_P . "/config/timeoff.txt";
	$fp = @fopen($file, 'r') ;
	$str = fread($fp, filesize($file));
	fclose($fp);
	$timeset = explode("\n", $str);
	while (list($key, $val) = each($timeset)) {
		$str = explode("\t", $val);
		if ($str[0] == $_SET['timeoff']) $str[2] = " selected" ;
		$timeoff[] = $str;
	} 
	return $timeoff;
} 

function getStatus($status) {
	switch ($status) {
		case 1 :
			return '草稿';
			break;
		case 2 :
			return '退稿';
			break;
		case 3 :
			return '<font color=green>待审核</font>';
			break;
		case 4 :
			return '通过审核';
			break;
	} 
} 

function groupCheck($name, $disabled = '', $group = '') {
	global $usergroup;
	if(empty($usergroup)){
		if(false === ($usergroup = cache::get('sys_usergroup'))){
			$usergroup = qbase::get_object("group")->cache();
		}
	}
	if ($group) {
		if (is_array($usergroup)) {
			$groups = @explode(',', $group);
			$index = 0;
			foreach($usergroup as $key => $val) {
				if ($index == 0) $id = " id=$name";
				if (is_array($disabled) && in_array($key, $disabled)) continue;
				if (in_array($key, $groups)) {
					echo "<li><input id='{$name}-box-{$key}'  type=checkbox name={$name}[] {$id} value={$key} checked><label for='{$name}-box-{$key}' style='margin-right:15px;'>" . $val['gname'] . "</label></li>";
				} else {
					echo "<li><input id='{$name}-box-{$key}'  type=checkbox name={$name}[] {$id} value={$key}><label for='{$name}-box-{$key}' style='margin-right:15px;'>" . $val['gname'] . "</label></li>";
				} 
				$id = '';
				$index++;
			} 
		} 
	} else {
		if (is_array($usergroup)) {
			$index = 0;
			foreach($usergroup as $key => $val) {
				if ($index == 0) $id = " id=$name";
				if (is_array($disabled) && in_array($key, $disabled)) continue;
				echo "<li><input  id='{$name}-box-{$key}' type=checkbox name={$name}[] {$id} value={$key}><label for='{$name}-box-{$key}' style='margin-right:15px;'>" . $val['gname'] . "</label></li>";
				$id = '';
				$index++;
			} 
		} 
	} 
} 

function makeAuthorLink($type, $num = 8){
	$temp = qdb::queryAlone("select v from ".TABLEPRE."config where g = 'author' and k = '{$type}' ");
	$data = explode("\n", $temp);
	$index = 1;
	foreach($data as $val){
		$val = trim($val);
		if(empty($val)) continue;
		echo "<a href='javascript:void(0);' onclick=\"$('{$type}').value=this.innerHTML;\">{$val}</a>";
		$index++;
		if($index >= $num+1) break;
	}
	echo "<a href='javascript:void(0);' onclick=\"qmeCms.dialogView.get('更多','system.php?sys=author&action=get&type={$type}');\">更多</a>";
}

function makeFilterBox($data, $type = 'checkbox'){
	if(!is_array($data)) $data = array();
	global $filterData;
	$html = '';
	if($type == 'checkbox'){
		foreach($filterData as $key=>$val){
			$index = $key + 1;
			$html .= "<input ".( in_array($index, $data) ? 'checked' : '' )." type=\"checkbox\" name=\"filter[]\" id=\"filter_{$index}\" value=\"{$index}\" /><label for=\"filter_{$index}\">{$val}</label>";
		}
	}else{
		$html .= '<option value="0">过滤条件</option>';
		foreach($filterData as $key=>$val){
			$index = $key + 1;
			$html .= "<option ".( in_array($index, $data) ? 'selected' : '' )." value=\"{$index}\">{$val}</option>";
		}
	}
	return $html;
}

function cachePurview() {
	global $tablepre, $admin_info;
	if($admin_info['groupid'] < 3) return;
	$lists = array();
	if ($admin_info['uid'] > 0) {
		$purview = qdb::queryFirst("select uid, groupid,manage_channel,manage_acc_channel,manage_category,manage_other from ".TABLEPRE."admin where uid='$admin_info[uid]' limit 1");
		switch ($purview['groupid']) {
			case 1:
			case 2:
			break;
			case 3:
			case 4:
				if ($purview['manage_category']) {
					$result = qdb::fetchAll("select arrchildids, channelid from ".TABLEPRE."acategory where cid IN (" . $purview['manage_category'] . ")");
					foreach($result as $list) {
						if ($list['arrchildids']) {
							$arr = explode(",", $list['arrchildids']);
							foreach($arr as $val) {
								$lists[$list['channelid']][] = $val;
							} 
						} 
					} 
					$keys = array_keys($lists);
					foreach($keys as $key => $val) {
						$manage_category_string .= "{$val}=>array(" . implode(',', $lists[$val]) . "),";
					} 
				} 
				$p_c_s = "\$manage_channel  = array( {$purview['manage_channel']} );" ;
				$p_acc_s = "\$manage_acc_channel  = array( {$purview['manage_acc_channel']} );" ;
				$p_a_s = "\$manage_category = array( $manage_category_string );" ;
				$p_p_s = "\$manage_other    = ". var_export(explode(',', $purview['manage_other']), true) .";" ;
				$data = "<?php\n " . $p_c_s . "\n" . $p_acc_s . "\n" . $p_a_s . "\n" . $p_p_s . "\n?>";
				qbase::writetofile(C_P . "/config/admin/" . $admin_info['uid'] . ".php", $data);
				clearstatcache();
			break;
			default:
			break;
		} 
	} 
} 

function purviewCheck($check_id, $type, $return = true) {
	global $manage_channel, $manage_acc_channel, $manage_category, $manage_other , $admin_info;
	if(!is_file(C_P . "/config/admin/" . $admin_info['uid'] . ".php")) cachePurview();
	$checkString = "manage_" . $type;
	switch ($admin_info['groupid']) {
		case 1:
		case 2:
			return true;
			break;
		case 3:
			require_once(C_P . "/config/admin/" . $admin_info['uid'] . ".php");
			if ($type == 'acc_channel') { // 是否能够进入该频道
				if (in_array($check_id, $manage_acc_channel)) {
					return true;
				} else {
					return $return ? qbase::purviewCheckDie() : false;
				} 
			} else if ($type == 'channel') { // 是否是该频道的管理员
				if (in_array($check_id, $manage_channel)) {
					return true;
				} else {
					return $return ? qbase::purviewCheckDie() : false;
				} 
			} else if ($type == 'category') { // 是否是该栏目的管理员
				$channelid = qdb::QueryAlone("select channelid from ".TABLEPRE."acategory where cid='$check_id' limit 1");
				if ($channelid > 0) {
					if (in_array($channelid, $manage_channel)) { // 载该栏目上具有频道管理员权限
						return true;
					} else {
						if (in_array($check_id, $manage_category[$channelid])) { // 在该栏目有栏目管理员权限
							return true;
						} else {
							return $return ? qbase::purviewCheckDie() : false;
						} 
					} 
				} else {
					return $return ? qbase::purviewCheckDie() : false;
				} 
			} else if ($type == 'plugin'){
				if(in_array($check_id, $manage_other)){
					return true;
				}else{
					return $return ? qbase::purviewCheckDie() : false;
				}
			}
			return true;
			break;
		case 4:
			require_once(C_P . "/config/admin/" . $admin_info['uid'] . ".php");
			if ($type == 'category') {
				if (in_array($check_id, $manage_category[$GLOBALS['channelid']])) {
					return true;
				} else {
					return $return ? qbase::purviewCheckDie() : false;
				} 
			} else if ($type == 'channel') {
				return $return ? qbase::purviewCheckDie() : false;
			} else if ($type == 'plugin'){
				if(in_array($check_id, $manage_other)){
					return true;
				}else{
					return $return ? qbase::purviewCheckDie() : false;
				}
			}
			break;
		default:
			return $return ? qbase::purviewCheckDie() : false;
			break;
	} 
} 
function adminGetCookie() {
	global $admin_info, $_SET;
	parse_str(qbase::authcode(trim($_COOKIE['admin_auth']) ? trim($_COOKIE['admin_auth']) : trim(urldecode($_POST['adminSession'])), "DECODE"), $admin_info);
	if(isset($admin_info['u']) && isset($admin_info['s'])){
		$admin_info['uid'] = intval($admin_info['u']);
		$admin_info['adminsession'] = urldecode($admin_info['s']);
	}else{
		$admin_info['uid'] = 0;
	}
} 

function adminOut(){
	global $admin_info;
	$uid = intval($admin_info['uid']);
	qbase::phpsetcookie("admin_auth", "", 0 - 3600 * 24 * 365);
	qdb::query("update ".TABLEPRE."admin set checkstring  = ''  where uid = '{$uid}' ");
}
function adminCheck() {
	global $admin_info, $manage_channel, $manage_category, $manage_other, $_SET;
	if (strlen($admin_info['adminsession']) == 32) {
		$user = qdb::QueryFirst("select checkstring, username, groupid, active_time from ".TABLEPRE."admin where uid='$admin_info[uid]' and `session`='$admin_info[adminsession]' limit 1");
		if (!empty($user)) {
			$ip = qbase::get_ip();
			$session = md5($user['checkstring'] . $ip . $user['groupid']);
			if ($session != $admin_info['adminsession'] || $_SERVER['REQUEST_TIME'] - $user['active_time'] > 3600 * 5) {
				adminOut();
				qbase::showmsg("请重新登录", "default", "login.php?action=login");
			}else{
				$admin_info['groupid'] = $user['groupid'];
				$admin_info['username'] = $user['username'];
				$admin_info['groupname'] = $admin_group[$user['groupid']];
				if($_SERVER['REQUEST_TIME'] - $user['active_time'] > 60 * 10){
					qdb::query("update ".TABLEPRE."admin set active_time = '{$_SERVER['REQUEST_TIME']}' where  uid='{$admin_info['uid']}' ");
				}
			}
		} else {
			adminOut();
			qbase::showmsg("您没有权限进入后台", "default", "login.php?action=login");
		} 
	} else {
		adminOut();
		qbase::showmsg("您没有权限进入后台", "default", "login.php?action=login");
	} 
} 

function Html2Text($str) {
	$str = preg_replace("/<sty(.*)\\/style>|<scr(.*)\\/script>|<!--(.*)-->/isU", "", $str);
	$alltext = "";
	$start = 1;
	for($i = 0;$i < strlen($str);$i++) {
		if ($start == 0 && $str[$i] == ">") $start = 1;
		else if ($start == 1) {
			if ($str[$i] == "<") {
				$start = 0;
				$alltext .= " ";
			} else if (ord($str[$i]) > 32) $alltext .= $str[$i];
		} 
	} 
	$alltext = str_replace("　", "", $alltext);
	$alltext = preg_replace("/&([^;&]*)(;|&)/", "", $alltext);
	$alltext = preg_replace("/[ ]+/s", " ", $alltext);
	return $alltext;
} 
// +--------------------------------
// |	取得内容的关键字
// +--------------------------------
function keyword($body, $title = '', $num=5) {
	global $sp;
	if(!isset($sp)) $sp = new SplitWord();
	$titleindexs = explode(" ", trim($sp -> GetIndexText($sp -> SplitRMM($title), true, true)));
	$allindexs = explode(" ", trim($sp -> GetIndexText($sp -> SplitRMM(Html2Text($body), true, true), 200)));
	$temp = array();
	if (is_array($allindexs) && is_array($titleindexs)) {
		foreach($titleindexs as $k) {
			$k = trim($k);
			if($k) $temp[] = $k;
		} 
		foreach($allindexs as $k) {
			$k = trim($k);
			if($k) $temp[] = $k;
		} 
	} 
	if (empty($temp)) return array();
	$temp = array_unique($temp);
	$keyword = array();
	foreach($temp as $key => $val) {
		$r = $sp -> GetRank($val);
		if($r > 20000) continue;
		$keyword[$key]['name'] = $val;
		$keyword[$key]['rank'] = $r;
	} 
	return array_slice($keyword, 0, $num);
} 

function adminLog($msg) {
	global $admin_info, $_SET;
	if ($admin_info['groupid'] < 3 || !$_SET['log']) return true;
	$php = basename(addslashes(urldecode($_SERVER['REQUEST_URI'])));
	$username = addslashes($admin_info['username']);
	$dateline = $_SERVER['REQUEST_TIME'];
	$ip = qbase::get_ip();
	$msg = addslashes($msg);
	qdb::Query("insert into ".TABLEPRE."admin_log (php,username,dateline,ip, msg) values ('{$php}','{$username}','{$dateline}','{$ip}', '{$msg}')");
} 

function AjaxEcho($str) {
	$data = "[" . str_replace('|', ',', $str) . "]";
	echo  qbase::xmlPrint($data);
	exit();
} 

function get_pugin(){
	$dir = 'plugin/';
	if(!is_dir($dir)) return array();
	$handle = @opendir($dir);
	$temp = array();
	while (false !== ($filename = @readdir($handle)))
	{
		if($filename == '.' || $filename == '..') continue;
		if(!is_dir($dir . $filename . '/') || !is_file($dir . $filename . '/config.ini')) continue;
		$tp = @parse_ini_file($dir . $filename . '/config.ini');
		if($tp === false) continue;
		foreach($tp as &$v){
			$v = urldecode($v);
		}
		$temp[] = array('name'=>$filename, 'data'=>$tp);
	}
	@closedir($handle);
	return $temp;
}
function formatFileName($filename){
	$filename = trim($filename);
	$temp = array();
	if(!$filename) return '';
	$len = strlen($filename);
	for($i=0; $i<$len; $i++){
		if(!ereg("([0-9_a-zA-Z\-\.,]+)", $filename[$i])) continue;
		$temp[] = $filename[$i];
	}
	return implode('', str_replace(" ", "", $temp));
}
function getIpArea($ip){
	$ex = explode(".", trim($ip));
	if(count($ex)!=4) return false;
	list($a, $b, $c, $d) = $ex;
	if($a != '*') $aa['max'] = $aa['min'] = $a*16777216;
	else{
		$aa['max'] = 255*16777216;
		$aa['min'] = 0;
	}
	if($b != '*') $bb['max'] = $bb['min'] = $b*65536;
	else{
		$bb['max'] = 255*65536;
		$bb['min'] = 0;
	}
	if($c != '*') $cc['max'] = $cc['min'] = $c*256;
	else{
		$cc['max'] = 255*256;
		$cc['min'] = 0;
	}
	if($d != '*') $dd['max'] = $dd['min'] = $d;
	else{
		$dd['max'] = 255;
		$dd['min'] = 0;
	}
	return array(
		'max'=>$aa['max']+$bb['max']+$cc['max']+$dd['max'],
		'min'=>$aa['min']+$bb['min']+$cc['min']+$dd['min']
	);
}

function checkAdminReferer(){
	global $_SET;
	$r = $_SERVER['HTTP_REFERER'];
	if(empty($r)) qbase::purviewCheckDie("error request");
	$info = parse_url($r);
	if(empty($info) || $info['host'] != $_SERVER['HTTP_HOST'] || strpos($info['path'], $_SET['webpath'] . $_SET['admin_path']) !== 0) qbase::purviewCheckDie("error request");
	return true;
}
?>