<?php

	class IpRestrictModel {
		protected $iRestriction = 10;

		public function hasRestriction( $ip ) {
			$query = sprintf( "select faults from ip_restricts where ipaddress='%s' and expires_tstamp>now()" , FNTH_db_addslashes( $ip ) );
			return FNTH_db_get_field( $query , "faults" );
		}

		public function hasHardRestriction( $ip ) {
			$restrict = $this->hasRestriction( $ip );
			return ($restrict>=$this->iRestriction);
		}

		public function clearRestriction( $ip ) {
			FNTH_db_free_result( FNTH_db_query( sprintf( "delete from ip_restricts where ipaddress='%s'" , FNTH_db_addslashes( $ip ) ) ) );
		}

		public function garbageCollect() {
			FNTH_db_free_result( FNTH_db_query( "delete from ip_restricts where expires_tstamp<now()" ) );
		}

		public function addUpdateRestriction( $ip , $tstamp = null ) {
			if (!isset( $tstamp )) $tstamp = fo3_time()+IP_TIMEOUT_RESTRICTION;
			$this->garbageCollect();
			$query = sprintf( "select ip_restrict_id from ip_restricts where ipaddress='%s'" , FNTH_db_addslashes( $ip ) );
			$ip_restrict_id = FNTH_db_get_field( $query , "ip_restrict_id" );
			$q = "";
			$d = array();
			$d["ipaddress"]=sprintf( "'%s'" , FNTH_db_addslashes( $ip ) );
			if ($ip_restrict_id) {
				$d["faults"]="faults+1";
				$q = FNTH_db_generate_update_query( "ip_restricts" , $d ,sprintf( "ip_restrict_id=%d" , $ip_restrict_id ) );
			} else {
				$d["expires_tstamp"]=sprintf( "'%s'" , fo3_date( "Y-m-d H:i:s" , $tstamp ) );
				$q = FNTH_db_generate_insert_query( "ip_restricts" , $d );
			}
			FNTH_db_free_result( FNTH_db_query( $q ) );
		}
	}
?>
