<?php
if(!defined('MOD'))  die("access die");
purviewCheck('database', 'plugin');
$action = $_GET['action'] ? $_GET['action'] : 'manage';
qbase::checkAction( $action);

switch($action){
	case 'manage':
		$data = qdb::fetchAll("select * from ".TABLEPRE."banned order by id asc");
		foreach($data as $key=>$val){
			$data[$key]['exptime'] = $val['dateline']+ ($val['lasttime'] ? ceil($val['lasttime']/24) * 86400 : 86400 * 365 * 10);
			$data[$key]['status'] = $_SERVER['REQUEST_TIME'] > $data[$key]['exptime'] ? false : true;
		}
	break;

	case 'add':
		checkAdminReferer();
		if($_POST['myFormAc'] == 'update'){
			$type = intval($_POST['type']);
			if($type == 0){ // 单个ip
				if(false === ($ip = check_ip($_POST['ip0']))) qbase::showmsg("输入的ip非法");
				$start = $end = $ip;
			}elseif($type == 1){ // 连续ip
				if(false === ($ip_start = check_ip($_POST['ip1_start'])) || false === ($ip_end = check_ip($_POST['ip1_end']))) qbase::showmsg("输入的ip非法");
				$start = min($ip_start, $ip_end);
				$end = max($ip_start, $ip_end);
			}else{
				qbase::showmsg("bad request");
			}
			qbase::get_object('banned')->add($start, $end, intval($_POST['lasttime']));
			die(qbase::xmlPrint(qbase::jsonencode(array('status'=>200, 'message'=>"Submit success"))));
		}
	break;

	case 'edit':
		checkAdminReferer();
		$id = intval($_GET['id']);
		$item = qdb::queryFirst("select * from ".TABLEPRE."banned where id = '{$id}' ");
		if(empty($item)) qbase::showmsg("bad request");
		if($_POST['myFormAc'] == 'update'){
			if(false === ($ip_start = check_ip($_POST['ip_start'])) || false === ($ip_end = check_ip($_POST['ip_end'])))  die(qbase::xmlPrint("输入的ip非法"));
			$start = min($ip_start, $ip_end);
			$end = max($ip_start, $ip_end);
			$lasttime = intval($_POST['lasttime']);
			if($start != $item['start'] || $end != $item['end'] || $lasttime != $item['lasttime']){
				qdb::query("update ".TABLEPRE."banned set start = '{$start}', end = '{$end}', lasttime = '{$lasttime}', dateline = '{$_SERVER['REQUEST_TIME']}'  where id='{$id}' ");
				qbase::get_object('banned')->cache();
			}
			die(qbase::xmlPrint(qbase::jsonencode(array('status'=>200, 'message'=>"Submit success"))));
		}else{
			$ip_start = explode('.', long2ip($item['start']));
			$ip_end = explode('.', long2ip($item['end']));
		}
	break;

	case 'delete':
		checkAdminReferer();
		$id = intval($_GET['id']);
		qdb::query("delete from ".TABLEPRE."banned where id = '{$id}' ");
		qbase::get_object('banned')->cache();
		qbase::showmsg("操作成功", "default", $_SERVER['HTTP_REFERER']);
	break;
}

include qbase::template($path . 'plugin/banned');

function check_ip($arr){
	if(count($arr) != 4) return false;
	foreach($arr as $key=>$num){
		if(strlen(trim($num)) == 0) return false;
		$num = intval($num);
		if($num < 0 || $num > 255) return false;
		$arr[$key] = $num;
	}
	return sprintf("%u", ip2long(implode('.', $arr)));
}
?>
