<?php

/**
 *--------------------------------------
 * Ban IP
 *--------------------------------------
 * @project		: loga
 * @author		: cblee
 * @created		: 2016-07-06
 * @copyright	: (c)2016 AsThis
 *--------------------------------------
 */
defined('PFA_PATH') or exit('Access Denied');

class BanIpModl extends Modl {
	public function get_ipList() {
		$_BIL = F('_bil');
		if(empty($_BIL)) {
			$_BIL = $this->order('`bi_add_time` DESC')->limit(100)->select();
			F('_bil', $_BIL);
		}
		return $_BIL;
	}

	public function get_ipInfo($banIpId) {
		$_BII = $this->where(array('ban_ip_id' => array('EQ', $banIpId)))->find();
		return $_BII;
	}

	public function add_ip($data) {
		$result = array('data' => '', 'error' => '');

		unset($data['ban_ip_id']);
		$_t_id = $this->insert($data);
		if(false === $_t_id) {
			$result['error'] = L('ADD_FAILED');
			return $result;
		}
		$result['data'] = $_t_id;

		F('_bil', null);
		return $result;
	}

	public function edit_ip($data) {
		$result = array('data' => '', 'error' => '');

		if(false === $this->update($data)) {
			$result['error'] = L('EDIT_FAILED');
			return $result;
		}

		F('_bil', null);
		return $result;
	}

	public function delete_ip($banIpId) {
		$result = array('data' => '', 'error' => '');

		if(false === $this->delete($banIpId)) {
			$result['error'] = L('DELETE_FAILED');
			return $result;
		}

		F('_bil', null);
		return $result;
	}

	public function clear_expiredIp() {
		$result = array('data' => '', 'error' => '');

		if(false === $this->where(array('bi_expire_time' => array(array('NEQ', 0), array('LT', NOW_TIME))))->delete()) {
			$result['error'] = L('CLEAR_FAILED');
			return $result;
		}

		F('_bil', null);
		return $result;
	}

	/* check ban ip */
	public function is_banIp() {
		$_BIL = $this->get_ipList();
		if(empty($_BIL)) {
			return false;
		}
		$uip =  CLIENT_IP;
		foreach($_BIL as $ip) {
			if($ip['bi_expire_time'] and $ip['bi_expire_time'] < NOW_TIME) {
				continue;
			}
			if($ip['bi_ip'] == $uip) {
				return true;
			}
			if(preg_match("/^".str_replace('*', '[0-9]{1,3}', $ip['bi_ip'])."$/", $uip)) {
				return true;
			}
		}
		return false;
	}

}

?>