<?php
/**
 * $Source: /home/cvs/nukescripts/kernel/nukesentinel.php,v $
 * $Revision: 1.1.0a $
 * $Author: cyril $
 * $Date: 2006/08/29 19:47:16 $
 *
 */
/********************************************************/
/* NukeSentinel(tm) Special Ultra Version Maximus       */
/* By: Maximus Team (dev@php-maximus.org)               */
/********************************************************/
/* NukeSentinel(tm)                                     */
/* By: NukeScripts Network (webmaster@nukescripts.net)  */
/* http://www.nukescripts.net                           */
/* Copyright © 2000-2005 by NukeScripts Network         */
/********************************************************/
/* CLIKE, UNION, & Email elements from HackAlert        */
/* HTTPAuth element                                     */
/* By: Raven PHP Scripts                                */
/* http://www.ravenphpscripts.com                       */
/* Copyright © 2004 by Raven PHP Scripts                */
/********************************************************/
/* Scripting Blocker elements                           */
/* By: ChatServ                                         */
/* http://www.nukeresources.com                         */
/* Copyright © 2004 by Nuke Resources                   */
/********************************************************/
/* Flood Blocker elements                               */
/* Written specificly for NukeSentinel(tm)              */
/* By: Manuel                                           */
/* http://www.ultradigital.it                           */
/* Copyright © 2005                                     */
/********************************************************/
defined('MAXIMUS') or die ('Access denied sentinel MAXIMUS directly...');
define('NUKESENTINEL_IS_LOADED', TRUE);

if(!isset($admin_file)) { $admin_file = "admin"; }
// Load required configs
global $remote, $nsnst_const, $admin_file, $user, $admin, $lang_dir, $op, $name, $aid, $c2c, $nukeurl, $max_time, $config, $blocker_array;

$ab_config                          = abget_configs();
$nsnst_const['server_ip']           = get_server_ip();
$nsnst_const['client_ip']           = get_client_ip();
$nsnst_const['forward_ip']          = get_x_forwarded();
$nsnst_const['remote_addr']         = get_remote_addr();
$nsnst_const['remote_ip']           = get_ip();
$nsnst_const['remote_port']         = get_remote_port();
$nsnst_const['request_method']      = get_request_method();
$nsnst_const['script_name']         = get_script_name();
$nsnst_const['http_host']           = get_http_host();
$nsnst_const['query_string']        = st_clean_string(get_query_string());
$nsnst_const['get_string']          = st_clean_string(get_get_string());
$nsnst_const['post_string']         = st_clean_string(get_post_string());
$nsnst_const['query_string_base64'] = st_clean_string(base64_decode($nsnst_const['query_string']));
$nsnst_const['get_string_base64']   = st_clean_string(base64_decode($nsnst_const['get_string']));
$nsnst_const['post_string_base64']  = st_clean_string(base64_decode($nsnst_const['post_string']));
$nsnst_const['user_agent']          = get_user_agent();
$nsnst_const['referer']             = get_referer();
$nsnst_const['script_name']         = get_script_name();
$nsnst_const['ban_time']            = $max_time;
$nsnst_const['ban_ip']              = "";
if(is_array($user)) {
  $user = implode(":", $user);
  $user = base64_encode($user);
}
$uinfo = getusrinfo($user);
if ($uinfo['user_id'] > 1 && !empty($uinfo['username'])) {
  $nsnst_const['ban_user_id'] = $uinfo['user_id'];
  $nsnst_const['ban_username'] = $uinfo['username'];
} else {
  $nsnst_const['ban_user_id'] = 1;
  $nsnst_const['ban_username'] = $anonymous;
}
// Load required lang file
if (defined('LANG_SENTINEL')) {
if(!isset($lang)) { $lang = $language; }
if (!stristr("$lang", ".") AND file_exists($lang_dir."language/nukesentinel/lang-$lang.php")) {
if (is_file($lang_dir."language/nukesentinel/lang-$lang.php")) {
  include_once($lang_dir."language/nukesentinel/lang-$lang.php");}
} else {
if (is_file($lang_dir."language/nukesentinel/lang-french.php")) {
  include_once($lang_dir."language/nukesentinel/lang-french.php");}
}
}
// Load Blocker Arrays
$result   = $GLOBALS['db']->sql_query("SELECT `blocker`, `block_name` FROM `".TABLE_NSNST_BLOCKERS."` ORDER BY `blocker`");
$num_rows = $GLOBALS['db']->sql_numrows($result);
for ($i = 0; $i < $num_rows; $i++) { $blocker_array[$i] = $GLOBALS['db']->sql_fetchrow($result); }
$GLOBALS['db']->sql_freeresult($result);

// Check for Flood Attack
// CAUTION: This function sometimes can slow a little your sites load time
$blocker_row = $blocker_array[11];
if($blocker_row['activate'] > 0 AND $nsnst_const['server_ip'] != $nsnst_const['remote_ip']/* AND !is_admin($admin)*/) {
  if(($ab_config['flood_delay_post'] + $ab_config['flood_delay_get']) > 0 AND (count($_POST) + count($_GET)) > 0) {
    if($nsnst_const['ban_username'] == $anonymous) {
      $checkrow = $GLOBALS['db']->sql_query("SELECT `lastpost` FROM `".TABLE_NSNST_FLOOD."` WHERE `ip` = `".$nsnst_const['remote_ip']."`");
      if( $GLOBALS['db']->sql_numrows($checkrow) == 1 ) {
        $res = $GLOBALS['db']->sql_fetchrow($checkrow);
        $tl = $max_time - $GLOBALS['db']->XMFnum($res['lastpost']);
        if(count($_POST) > 0) if($tl < $ab_config['flood_delay_post']) block_ip($blocker_row);
        if(count($_GET) > 0) if($tl < $ab_config['flood_delay_get']) block_ip($blocker_row);
        $GLOBALS['db']->sql_query("UPDATE `".TABLE_NSNST_FLOOD." SET `lastpost` = `".$max_time."` WHERE `ip` = `".$nsnst_const['remote_ip']."`");
      } else {
        $GLOBALS['db']->sql_query("INSERT INTO `".TABLE_NSNST_FLOOD." (`ip`, `lastpost`) VALUES (`".$nsnst_const['remote_ip']."`, `".$max_time."`)");
        $lpdelete = $max_time - 600;
        $GLOBALS['db']->sql_query("DELETE FROM `".TABLE_NSNST_FLOOD."` ORDER BY `lastpost` LIMIT ".$ab_config['flood_del']." ");
        $GLOBALS['db']->sql_query("OPTIMIZE TABLE `".TABLE_NSNST_FLOOD."` ");
      }
    } else {
      // let's make a brand new cookie
      $lp = intval($HTTP_COOKIE_VARS['nsnst_flood_lastreq']);
      if($lp > 0) if(($max_time - $lp) < $ab_config['flood_delay_post']) block_ip($blocker_row);
      @setcookie('nsnst_flood_lastreq', $max_time, $max_time + 2592000);
      if($lp > 0) if(($max_time - $lp) < $ab_config['flood_delay_get']) block_ip($blocker_row);
      @setcookie('nsnst_flood_lastreq', $max_time, $max_time + 2592000);
    }
  }
}

// Invalid admin check
if($aid AND (!isset($admin) OR empty($admin)) AND $op!='login') { die(_AB_FALSEADMIN); }

// Stop Santy Worm
// If you have problems with forums remove ,highlight from the string below
if($ab_config['santy_protection'] == 1) {
  $bad_uri_content=array("rush","highlight=%","perl","chr(","pillar","visualcoder","sess_");
  while(list($stid,$uri_content)=each($bad_uri_content)) { if(stristr($_SERVER['REQUEST_URI'], $uri_content)) { die(_AB_SANTY); } }
}

// Invalid ip check
//if($nsnst_const['remote_ip']=="none") { die(_AB_INVALIDIP); }

// Invalid request method check
if(strtolower($nsnst_const['request_method'])!="get" AND strtolower($nsnst_const['request_method'])!="head" AND strtolower($nsnst_const['request_method'])!="post" AND strtolower($nsnst_const['request_method'])!="put") { die(_AB_INVALIDMETHOD); }

// DOS Attack Blocker
if($ab_config['prevent_dos'] == 1 AND !stristr($_SERVER['PHP_SELF'], "backend.php") AND !stristr($_SERVER['PHP_SELF'], "backend2.php") AND !stristr($_SERVER['PHP_SELF'], "backend3.php") AND !stristr($_SERVER['PHP_SELF'], "backendforums.php") AND !stristr($_SERVER['PHP_SELF'], "backend2forums.php") AND !stristr($nukeurl, $_SERVER['SERVER_NAME'])) {
  if (empty($nsnst_const['user_agent']) || $nsnst_const['user_agent'] == "-" || !isset($nsnst_const['user_agent'])) { die(_AB_GETOUT); }
}

// Site Switch Check
if($ab_config['site_switch'] == 1 AND !stristr($_SERVER['PHP_SELF'], "".$admin_file.".php") AND !defined('ADMIN_ALLOW')) {
include_once($lang_dir."language/nukesentinel/lang-$lang.php");
  $display_page = abget_template($ab_config['site_reason']);
  $display_page = eregi_replace("</body>", "<hr noshade />\n<div align='right'>"._AB_NUKESENTINEL." ".$ab_config['version_number']." "._AB_BYNSN."</div>\n</body>", $display_page);
  die($display_page);
}

// Clearing of expired blocks
// CAUTION: This function can slow your sites load time
if($ab_config['self_expire'] == 1) {
  $expiretime = $max_time;
  $clearresult = $GLOBALS['db']->sql_query("SELECT `ip_addr` FROM `".TABLE_NSNST_BLOCKED_IPS."` WHERE (`expires`<'$expiretime' AND `expires`!='0')");
  while($clearblock = $GLOBALS['db']->sql_fetchrow($clearresult)) {
    $GLOBALS['db']->sql_query("DELETE FROM `".TABLE_NSNST_BLOCKED_IPS."` WHERE `ip_addr`='".$clearblock['ip_addr']."'");
    $GLOBALS['db']->sql_query("OPTIMIZE TABLE `".TABLE_NSNST_BLOCKED_IPS."`");
    if(!empty($ab_config['htaccess_path'])) {
      $ipfile = file($ab_config['htaccess_path']);
      $ipfile = implode("", $ipfile);
      $i = 1;
      while ($i <= 3) {
        $tip = substr($clearblock['ip_addr'], -2);
        if ($tip == ".*") { $clearblock['ip_addr'] = substr($clearblock['ip_addr'], 0, -2); }
        $i++;
      }
      $testip = "deny from ".$clearblock['ip_addr']."\n";
      $ipfile = str_replace($testip, "", $ipfile);
      $doit = @fopen($ab_config['htaccess_path'], "w");
      @fwrite($doit, $ipfile);
      @fclose($doit);
    }
  }
  $clearresult = $GLOBALS['db']->sql_query("SELECT `ip_lo`, `ip_hi` FROM `".TABLE_NSNST_BLOCKED_RANGES."` WHERE (`expires`<'$expiretime' AND `expires`!='0')");
  while($clearblock = $GLOBALS['db']->sql_fetchrow($clearresult)) {
    $old_masscidr = ABGetCIDRs($clearblock['ip_lo'], $clearblock['ip_hi']);
    if (!empty($ab_config['htaccess_path'])) {
      $old_masscidr = explode("||", $old_masscidr);
      for ($i=0; $i < sizeof($old_masscidr); $i++) {
        if (!empty($old_masscidr[$i])) {
          $old_masscidr[$i] = "deny from ".$old_masscidr[$i]."\n";
        }
      }
      $ipfile = file($ab_config['htaccess_path']);
      $ipfile = implode("", $ipfile);
      $ipfile = str_replace($old_masscidr, "", $ipfile);
      $ipfile = $ipfile;
      $doit = @fopen($ab_config['htaccess_path'], "w");
      @fwrite($doit, $ipfile);
      @fclose($doit);
    }
    $GLOBALS['db']->sql_query("DELETE FROM `".TABLE_NSNST_BLOCKED_RANGES."` WHERE `ip_lo`='".$clearblock['ip_lo']."' AND `ip_hi`='".$clearblock['ip_hi']."'");
    $GLOBALS['db']->sql_query("OPTIMIZE TABLE `".TABLE_NSNST_BLOCKED_RANGES."`");
  }
}

// Proxy Blocker
if($ab_config['proxy_switch'] == 1) {
  $proxy0 = $nsnst_const['remote_ip'];
  $proxy1 = $nsnst_const['client_ip'];
  $proxy2 = $nsnst_const['forward_ip'];
  $proxy_host = @getHostByAddr($proxy0);
  //Lite:
  if($ab_config['proxy_switch'] == 1 AND ($proxy1 != "none" OR $proxy2 != "none")) {
    $display_page = abget_template($ab_config['proxy_reason']);
    $display_page = eregi_replace("</body>", "<hr noshade />\n<div align='right'>"._AB_NUKESENTINEL." ".$ab_config['version_number']." "._AB_BYNSN."</div>\n</body>", $display_page);
    die($display_page);
  }
  //Mild:
  if($ab_config['proxy_switch'] == 2 AND ($proxy1 != "none" OR $proxy2 != "none" OR stristr($proxy_host,"proxy"))) {
    $display_page = abget_template($ab_config['proxy_reason']);
    $display_page = eregi_replace("</body>", "<hr noshade>\n<div align='right'>"._AB_NUKESENTINEL." ".$ab_config['version_number']." "._AB_BYNSN."</div>\n</body>", $display_page);
    die($display_page);
  }
  //Strong:
  if($ab_config['proxy_switch'] == 3 AND ($proxy1 != "none" OR $proxy2 != "none" OR stristr($proxy_host,"proxy") OR $proxy0 == $proxy_host)) {
    $display_page = abget_template($ab_config['proxy_reason']);
    $display_page = eregi_replace("</body>", "<hr noshade>\n<div align='right'>"._AB_NUKESENTINEL." ".$ab_config['version_number']." "._AB_BYNSN."</div>\n</body>", $display_page);
    die($display_page);
  }
}

// Check if ip is blocked
$blocked_row = abget_blocked($nsnst_const['remote_ip']);
if($blocked_row) { blocked($blocked_row); }

// Check if range is blocked
$blockedrange_row = abget_blockedrange($nsnst_const['remote_ip']);
if($blockedrange_row) { blockedrange($blockedrange_row); }

// AUTHOR Protection
$blocker_row = $blocker_array[5];
if($blocker_row['activate'] > 0) {
  if(($op=="mod_authors" OR $op=="modifyadmin" OR $op=="UpdateAuthor" OR $op=="AddAuthor" OR $op=="deladmin2" OR $op=="deladmin" OR $op=="assignstories" OR $op=="deladminconf") AND !is_god($admin)) {
    block_ip($blocker_row);
  }
}

// ADMIN protection
$blocker_row = $blocker_array[10];
if($blocker_row['activate'] > 0) {
  if(stristr($_SERVER['PHP_SELF'],"".$admin_file.".php") AND ($op!="login" AND $op!="adminMain" AND $op!="gfx" AND isset($op)) AND !defined('ADMIN_ALLOW')) {
    block_ip($blocker_row);
  }
}

// Check for UNION attack
// Copyright 2004(c) Raven PHP Scripts
// Copyright 2006(c) Maximus
$blocker_row = $blocker_array[1];
if($blocker_row['activate'] > 0) {
  $ct_rules = array( '*/from/*', '*/insert/*', '+into+', '%20into%20', '*/into/*', ' into ', 'into', '*/limit/*', 'not123exists*', '*/radminsuper/*', '*/select/*', '+select+', '%20select%20', ' select ',  '+union+', '%20union%20', '*/union/*', ' union ', '*/update/*', '*/where/*' );
  $check    = str_replace($ct_rules, '*', $nsnst_const['query_string']);
  if( $nsnst_const['query_string'] != $check ) {
    block_ip($blocker_row);
  }
  $check    = str_replace($ct_rules, '*', $nsnst_const['query_string_base64']);
  if( $nsnst_const['query_string_base64'] != $check ) {
    block_ip($blocker_row);
  }
}
unset($loc);
$loc = rawurldecode($_SERVER["QUERY_STRING"]);
if (preg_match("/([OdWo5NIbpuU4V2iJT0n]{5}) /", $loc)) {
	block_ip($blocker_array[1]);
}
// Check for CLIKE attack
// Copyright 2004(c) Raven PHP Scripts
// Copyright 2006(c) Maximus
$blocker_row = $blocker_array[2];
if($blocker_row['activate'] > 0) {
  $ct_rules = array( '/*', 'c2nyaxb0', 'http://', '/*' );
  $check    = str_replace($ct_rules, '*', $nsnst_const['query_string']);
  if( $nsnst_const['query_string'] != $check ) {
    block_ip($blocker_row);
  }
  $check    = str_replace($ct_rules, '*', $nsnst_const['query_string_base64']);
  if( $nsnst_const['query_string_base64'] != $check ) {
    block_ip($blocker_row);
  }

}
if (strstr($loc,"*")) {
	block_ip($blocker_array[2]);
}
// Check Filters
$blocker_row = $blocker_array[7];
if($blocker_row['activate'] > 0) {
  // Check for Forum attack
  // Copyright 2004(c) GanjaUK & ChatServ
  if (!stristr($nsnst_const['query_string'],'&file=nickpage') AND stristr($nsnst_const['query_string'],'&user=') AND ($name=="Private_Messages" || $name=="Forums" || $name=="Members_List")) {
    block_ip($blocker_row);
  }
  // Check for News attack
  // Copyright 2004(c) ChatServ
  if (stristr($nsnst_const['query_string'],'%25') AND ($name=="News" || $name=="Reviews")) {
    block_ip($blocker_row);
  }
  // Check for XSS attack
  // Copyright 2006(c) Maximus
  $ct_rules = array( 'http\:\/\/', 'cmd=', '&cmd', 'exec', 'execu', 'concat', '../' );
  $check    = str_replace($ct_rules, '*', $nsnst_const['query_string']);
  if( $nsnst_const['query_string'] != $check ) {
    block_ip($blocker_row);
  }

}

if(!defined('ADMIN_ALLOW')) {
  // Check for SCRIPTING attack
  // Copyright 2004(c) ChatServ
  // Copyright 2006(c) Maximus
  $blocker_row = $blocker_array[4];
  if($blocker_row['activate'] > 0) {

if ( !empty($_GET) ) {
    foreach ($_GET as $sec_key => $secvalue) {
      $secvalue = strtolower($secvalue);
      str_replace("%3c", "<", $secvalue);
      str_replace("%3e", ">", $secvalue);
if (
(stristr($secvalue,"<[^>]script.*\"?[^>]*>")) ||
(stristr($secvalue,".*[[:space:]](or|and)[[:space:]].*(=|like).*")) ||
(stristr($secvalue,"<[^>]*object.*\"?[^>]*>")) ||
(stristr($secvalue,"<[^>]*iframe.*\"?[^>]*>")) ||
(stristr($secvalue,"<[^>]*applet.*\"?[^>]*>")) ||
(stristr($secvalue,"<[^>]*meta.*\"?[^>]*>")) ||
(stristr($secvalue,"<[^>]style.*\"?[^>]*>")) ||
(stristr($secvalue,"<[^>]*form.*\"?[^>]*>")) ||
(stristr($secvalue,"<[^>]*window.*\"?[^>]*>")) ||
(stristr($secvalue,"<[^>]*alert.*\"?[^>]*>")) ||
(stristr($secvalue,"<[^>]*cookie.*\"?[^>]*>")) ||
(stristr($secvalue,"<[^>]*img.*\"?[^>]*>")) ||
(stristr($secvalue,"<[^>]*onmouseover*\"?[^>]*>")) ||
(stristr($secvalue,"<[^>]*body*\"?[^>]*>")) ||
(stristr($secvalue,"\([^>]p0hh*\"?[^)]*\)")) ||
(stristr($secvalue,"\([^>]*\"?[^)]*\)")) ||
(stristr($secvalue,"\"")) ||
(stristr($secvalue,"forum_admin")) ||
(stristr($secvalue,"inside_mod"))
) {
        block_ip($blocker_row);
      }
    }
  }

if ( !empty($HTTP_GET_VARS) ) {
    foreach ($HTTP_GET_VARS as $sec_key => $secvalue) {
      $secvalue = strtolower($secvalue);
      str_replace("%3c", "<", $secvalue);
      str_replace("%3e", ">", $secvalue);
if (
(stristr($secvalue,"<[^>]script.*\"?[^>]*>")) ||
(stristr($secvalue,".*[[:space:]](or|and)[[:space:]].*(=|like).*")) ||
(stristr($secvalue,"<[^>]*object.*\"?[^>]*>")) ||
(stristr($secvalue,"<[^>]*iframe.*\"?[^>]*>")) ||
(stristr($secvalue,"<[^>]*applet.*\"?[^>]*>")) ||
(stristr($secvalue,"<[^>]*meta.*\"?[^>]*>")) ||
(stristr($secvalue,"<[^>]style.*\"?[^>]*>")) ||
(stristr($secvalue,"<[^>]*form.*\"?[^>]*>")) ||
(stristr($secvalue,"<[^>]*window.*\"?[^>]*>")) ||
(stristr($secvalue,"<[^>]*alert.*\"?[^>]*>")) ||
(stristr($secvalue,"<[^>]*cookie.*\"?[^>]*>")) ||
(stristr($secvalue,"<[^>]*img.*\"?[^>]*>")) ||
(stristr($secvalue,"<[^>]*onmouseover*\"?[^>]*>")) ||
(stristr($secvalue,"<[^>]*body*\"?[^>]*>")) ||
(stristr($secvalue,"\([^>]p0hh*\"?[^)]*\)")) ||
(stristr($secvalue,"\([^>]*\"?[^)]*\)")) ||
(stristr($secvalue,"\"")) ||
(stristr($secvalue,"forum_admin")) ||
(stristr($secvalue,"inside_mod"))
) {
        block_ip($blocker_row);
      }
    }
  }
// Copyright 2006(c) Maximus
if ( !empty($_POST) ) {
    foreach ($_POST as $secvalue) {
      $secvalue = strtolower($secvalue);
      str_replace("%3c", "<", $secvalue);
      str_replace("%3e", ">", $secvalue);
      if (
(stristr($secvalue,"<[^>]script.*\"?[^>]*>")) ||
(stristr($secvalue,".*[[:space:]](or|and)[[:space:]].*(=|like).*")) ||
(stristr($secvalue,"<[^>]*object.*\"?[^>]*>")) ||
(stristr($secvalue,"<[^>]*iframe.*\"?[^>]*>")) ||
(stristr($secvalue,"<[^>]*applet.*\"?[^>]*>")) ||
(stristr($secvalue,"<[^>]*meta.*\"?[^>]*>")) ||
(stristr($secvalue,"<[^>]style.*\"?[^>]*>")) ||
(stristr($secvalue,"<[^>]*form.*\"?[^>]*>")) ||
(stristr($secvalue,"<[^>]*window.*\"?[^>]*>")) ||
(stristr($secvalue,"<[^>]*alert.*\"?[^>]*>")) ||
(stristr($secvalue,"<[^>]*cookie.*\"?[^>]*>")) ||
(stristr($secvalue,"<[^>]*img.*\"?[^>]*>")) ||
(stristr($secvalue,"<[^>]*onmouseover*\"?[^>]*>")) ||
(stristr($secvalue,"<[^>]*body*\"?[^>]*>")) ||
(stristr($secvalue,"\([^>]p0hh*\"?[^)]*\)")) ||
(stristr($secvalue,"\([^>]*\"?[^)]*\)"))
) {
        block_ip($blocker_row);
      }
    }
  }

if ( !empty($HTTP_POST_VARS) ) {
    foreach ($HTTP_POST_VARS as $secvalue) {
      $secvalue = strtolower($secvalue);
      str_replace("%3c", "<", $secvalue);
      str_replace("%3e", ">", $secvalue);
      if (
(stristr($secvalue,"<[^>]script.*\"?[^>]*>")) ||
(stristr($secvalue,".*[[:space:]](or|and)[[:space:]].*(=|like).*")) ||
(stristr($secvalue,"<[^>]*object.*\"?[^>]*>")) ||
(stristr($secvalue,"<[^>]*iframe.*\"?[^>]*>")) ||
(stristr($secvalue,"<[^>]*applet.*\"?[^>]*>")) ||
(stristr($secvalue,"<[^>]*meta.*\"?[^>]*>")) ||
(stristr($secvalue,"<[^>]style.*\"?[^>]*>")) ||
(stristr($secvalue,"<[^>]*form.*\"?[^>]*>")) ||
(stristr($secvalue,"<[^>]*window.*\"?[^>]*>")) ||
(stristr($secvalue,"<[^>]*alert.*\"?[^>]*>")) ||
(stristr($secvalue,"<[^>]*cookie.*\"?[^>]*>")) ||
(stristr($secvalue,"<[^>]*img.*\"?[^>]*>")) ||
(stristr($secvalue,"<[^>]*onmouseover*\"?[^>]*>")) ||
(stristr($secvalue,"<[^>]*body*\"?[^>]*>")) ||
(stristr($secvalue,"\([^>]p0hh*\"?[^)]*\)")) ||
(stristr($secvalue,"\([^>]*\"?[^)]*\)"))
) {
        block_ip($blocker_row);
      }
    }
  }
// Lets now sanitize the COOKIE vars
// Copyright 2006(c) Maximus
if ( !empty($_COOKIE) ) {
foreach ($_COOKIE as $secvalue) {
if (!is_array($secvalue)) {
if (
(stristr($secvalue,"<[^>]script.*\"?[^>]*>")) ||
(stristr($secvalue,".*[[:space:]](or|and)[[:space:]].*(=|like).*")) ||
(stristr($secvalue,"<[^>]*object.*\"?[^>]*>")) ||
(stristr($secvalue,"<[^>]*iframe.*\"?[^>]*>")) ||
(stristr($secvalue,"<[^>]*applet.*\"?[^>]*>")) ||
(stristr($secvalue,"<[^>]*meta.*\"?[^>]*>")) ||
(stristr($secvalue,"<[^>]*style.*\"?[^>]*>")) ||
(stristr($secvalue,"<[^>]*form.*\"?[^>]*>")) ||
(stristr($secvalue,"<[^>]*window.*\"?[^>]*>")) ||
(stristr($secvalue,"<[^>]*alert.*\"?[^>]*>")) ||
(stristr($secvalue,"<[^>]*cookie.*\"?[^>]*>")) ||
(stristr($secvalue,"<[^>]*img.*\"?[^>]*>"))
) {
        block_ip($blocker_row);
      }
    }
  }
}


// Lets now sanitize the COOKIE vars
// Copyright 2006(c) Maximus
if ( !empty($HTTP_COOKIE_VARS) ) {
foreach ($HTTP_COOKIE_VARS as $secvalue) {
if (!is_array($secvalue)) {
if (
(stristr($secvalue,"<[^>]script.*\"?[^>]*>")) ||
(stristr($secvalue,".*[[:space:]](or|and)[[:space:]].*(=|like).*")) ||
(stristr($secvalue,"<[^>]*object.*\"?[^>]*>")) ||
(stristr($secvalue,"<[^>]*iframe.*\"?[^>]*>")) ||
(stristr($secvalue,"<[^>]*applet.*\"?[^>]*>")) ||
(stristr($secvalue,"<[^>]*meta.*\"?[^>]*>")) ||
(stristr($secvalue,"<[^>]*style.*\"?[^>]*>")) ||
(stristr($secvalue,"<[^>]*form.*\"?[^>]*>")) ||
(stristr($secvalue,"<[^>]*window.*\"?[^>]*>")) ||
(stristr($secvalue,"<[^>]*alert.*\"?[^>]*>")) ||
(stristr($secvalue,"<[^>]*cookie.*\"?[^>]*>")) ||
(stristr($secvalue,"<[^>]*img.*\"?[^>]*>"))
) {
        block_ip($blocker_row);
      }
    }
  }
}

// Lets now sanitize the $_SERVER and $_ENV vars
// Copyright 2006(c) Maximus
    if (!empty($_SERVER)) {
       extract($_SERVER, EXTR_OVERWRITE);
    } else if (!empty($HTTP_SERVER_VARS)) {
       extract($HTTP_SERVER_VARS, EXTR_OVERWRITE);
    }

    if (!empty($_ENV)) {
       extract($_ENV, EXTR_OVERWRITE);
    } else if (!empty($HTTP_ENV_VARS)) {
       extract($HTTP_ENV_VARS, EXTR_OVERWRITE);
    }

// Lets now sanitize the $_ENV vars
// Copyright 2006(c) Maximus
if ( !empty($_ENV)) {
foreach ($_ENV as $secvalue) {
if (!is_array($secvalue)) {
if (
(stristr($secvalue,"<[^>]script.*\"?[^>]*>")) ||
(stristr($secvalue,".*[[:space:]](or|and)[[:space:]].*(=|like).*")) ||
(stristr($secvalue,"<[^>]*object.*\"?[^>]*>")) ||
(stristr($secvalue,"<[^>]*iframe.*\"?[^>]*>")) ||
(stristr($secvalue,"<[^>]*applet.*\"?[^>]*>")) ||
(stristr($secvalue,"<[^>]*meta.*\"?[^>]*>")) ||
(stristr($secvalue,"<[^>]*style.*\"?[^>]*>")) ||
(stristr($secvalue,"<[^>]*form.*\"?[^>]*>")) ||
(stristr($secvalue,"<[^>]*window.*\"?[^>]*>")) ||
(stristr($secvalue,"<[^>]*alert.*\"?[^>]*>")) ||
(stristr($secvalue,"<[^>]*cookie.*\"?[^>]*>")) ||
(stristr($secvalue,"<[^>]*img.*\"?[^>]*>"))
) {
        block_ip($blocker_row);
      }
    }
  }
}

if ( !empty($HTTP_ENV_VARS)) {
foreach ($HTTP_ENV_VARS as $secvalue) {
if (!is_array($secvalue)) {
if (
(stristr($secvalue,"<[^>]script.*\"?[^>]*>")) ||
(stristr($secvalue,".*[[:space:]](or|and)[[:space:]].*(=|like).*")) ||
(stristr($secvalue,"<[^>]*object.*\"?[^>]*>")) ||
(stristr($secvalue,"<[^>]*iframe.*\"?[^>]*>")) ||
(stristr($secvalue,"<[^>]*applet.*\"?[^>]*>")) ||
(stristr($secvalue,"<[^>]*meta.*\"?[^>]*>")) ||
(stristr($secvalue,"<[^>]*style.*\"?[^>]*>")) ||
(stristr($secvalue,"<[^>]*form.*\"?[^>]*>")) ||
(stristr($secvalue,"<[^>]*window.*\"?[^>]*>")) ||
(stristr($secvalue,"<[^>]*alert.*\"?[^>]*>")) ||
(stristr($secvalue,"<[^>]*cookie.*\"?[^>]*>")) ||
(stristr($secvalue,"<[^>]*img.*\"?[^>]*>"))
) {
        block_ip($blocker_row);
      }
    }
  }
}
// Lets now sanitize the $_SERVER vars
// Copyright 2006(c) Maximus
if ( !empty($_SERVER) ) {
foreach ($_SERVER as $secvalue) {
if (!is_array($secvalue)) {
if (
(stristr($secvalue,"<[^>]script.*\"?[^>]*>")) ||
(stristr($secvalue,".*[[:space:]](or|and)[[:space:]].*(=|like).*")) ||
(stristr($secvalue,"<[^>]*object.*\"?[^>]*>")) ||
(stristr($secvalue,"<[^>]*iframe.*\"?[^>]*>")) ||
(stristr($secvalue,"<[^>]*applet.*\"?[^>]*>")) ||
(stristr($secvalue,"<[^>]*meta.*\"?[^>]*>")) ||
(stristr($secvalue,"<[^>]*style.*\"?[^>]*>")) ||
(stristr($secvalue,"<[^>]*form.*\"?[^>]*>")) ||
(stristr($secvalue,"<[^>]*window.*\"?[^>]*>")) ||
(stristr($secvalue,"<[^>]*alert.*\"?[^>]*>")) ||
(stristr($secvalue,"<[^>]*cookie.*\"?[^>]*>")) ||
(stristr($secvalue,"<[^>]*img.*\"?[^>]*>"))
) {
        block_ip($blocker_row);
      }
    }
  }
}

if ( !empty($HTTP_SERVER_VARS) ) {
foreach ($HTTP_SERVER_VARS as $secvalue) {
if (!is_array($secvalue)) {
if (
(stristr($secvalue,"<[^>]script.*\"?[^>]*>")) ||
(stristr($secvalue,".*[[:space:]](or|and)[[:space:]].*(=|like).*")) ||
(stristr($secvalue,"<[^>]*object.*\"?[^>]*>")) ||
(stristr($secvalue,"<[^>]*iframe.*\"?[^>]*>")) ||
(stristr($secvalue,"<[^>]*applet.*\"?[^>]*>")) ||
(stristr($secvalue,"<[^>]*meta.*\"?[^>]*>")) ||
(stristr($secvalue,"<[^>]*style.*\"?[^>]*>")) ||
(stristr($secvalue,"<[^>]*form.*\"?[^>]*>")) ||
(stristr($secvalue,"<[^>]*window.*\"?[^>]*>")) ||
(stristr($secvalue,"<[^>]*alert.*\"?[^>]*>")) ||
(stristr($secvalue,"<[^>]*cookie.*\"?[^>]*>")) ||
(stristr($secvalue,"<[^>]*img.*\"?[^>]*>"))
) {
        block_ip($blocker_row);
      }
    }
  }
}

// Lets now sanitize the $_FILES vars
// Copyright 2006(c) Maximus
if ( !empty($_FILES)) {
foreach ($_FILES as $secvalue) {
if (!is_array($secvalue)) {
if (
(stristr($secvalue,"<[^>]script.*\"?[^>]*>")) ||
(stristr($secvalue,".*[[:space:]](or|and)[[:space:]].*(=|like).*")) ||
(stristr($secvalue,"<[^>]*object.*\"?[^>]*>")) ||
(stristr($secvalue,"<[^>]*iframe.*\"?[^>]*>")) ||
(stristr($secvalue,"<[^>]*applet.*\"?[^>]*>")) ||
(stristr($secvalue,"<[^>]*meta.*\"?[^>]*>")) ||
(stristr($secvalue,"<[^>]*style.*\"?[^>]*>")) ||
(stristr($secvalue,"<[^>]*form.*\"?[^>]*>")) ||
(stristr($secvalue,"<[^>]*window.*\"?[^>]*>")) ||
(stristr($secvalue,"<[^>]*alert.*\"?[^>]*>")) ||
(stristr($secvalue,"<[^>]*cookie.*\"?[^>]*>")) ||
(stristr($secvalue,"<[^>]*img.*\"?[^>]*>"))
) {
        block_ip($blocker_row);
      }
    }
  }
}

// Lets now sanitize the $_FILES vars
// Copyright 2006(c) PHP Maximus CMS
if ( !empty($HTTP_POST_FILES)) {
foreach ($HTTP_POST_FILES as $secvalue) {
if (!is_array($secvalue)) {
if (
(stristr($secvalue,"<[^>]script.*\"?[^>]*>")) ||
(stristr($secvalue,".*[[:space:]](or|and)[[:space:]].*(=|like).*")) ||
(stristr($secvalue,"<[^>]*object.*\"?[^>]*>")) ||
(stristr($secvalue,"<[^>]*iframe.*\"?[^>]*>")) ||
(stristr($secvalue,"<[^>]*applet.*\"?[^>]*>")) ||
(stristr($secvalue,"<[^>]*meta.*\"?[^>]*>")) ||
(stristr($secvalue,"<[^>]*style.*\"?[^>]*>")) ||
(stristr($secvalue,"<[^>]*form.*\"?[^>]*>")) ||
(stristr($secvalue,"<[^>]*window.*\"?[^>]*>")) ||
(stristr($secvalue,"<[^>]*alert.*\"?[^>]*>")) ||
(stristr($secvalue,"<[^>]*cookie.*\"?[^>]*>")) ||
(stristr($secvalue,"<[^>]*img.*\"?[^>]*>"))
) {
        block_ip($blocker_row);
      }
    }
  }
}


  }
}


// Check for Referer
$blocker_row = $blocker_array[6];
if($blocker_row['activate'] > 0) {
  if($blocker_row['list'] > "") {
    $RefererList = explode("\r\n",$blocker_row['list']);
    for ($i=0; $i < count($RefererList); $i++) {
      $refered = $RefererList[$i];
      if (stristr($nsnst_const['referer'], $refered) AND !empty($refered)) {
        block_ip($blocker_row, $refered);
      }
    }
  }
}

// Check for Harvester
$blocker_row = $blocker_array[3];
if($blocker_row['activate'] > 0) {
  if($blocker_row['list'] > "") {
    $HarvestList = explode("\r\n",$blocker_row['list']);
    for ($i=0; $i < count($HarvestList); $i++) {
      $harvest = $HarvestList[$i];
      if (stristr($nsnst_const['user_agent'], $harvest) AND !empty($harvest)) {
        block_ip($blocker_row, $harvest);
      }
    }
  }
}

// Check for Strings
$blocker_row = $blocker_array[9];
if($blocker_row['activate'] > 0) {
  if($blocker_row['list'] > "") {
    $StringList = explode("\r\n",$blocker_row['list']);
    for ($i=0; $i < count($StringList); $i++) {
      $stringl = $StringList[$i];
      if (stristr($nsnst_const['query_string'], $stringl) AND !empty($stringl)) {
        block_ip($blocker_row, $stringl);
      }
    }
  }
}

// Check for Request
$blocker_row = $blocker_array[8];
if($blocker_row['activate'] > 0) {
  if($blocker_row['list'] > "") {
    $RequestList = explode("\r\n",$blocker_row['list']);
    for ($i=0; $i < count($RequestList); $i++) {
      $request = $RequestList[$i];
      if (stristr($nsnst_const['request_method'], $request) AND !empty($request)) {
        block_ip($blocker_row, $request);
      }
    }
  }
}

// Force to NUKEURL
if($ab_config['force_nukeurl'] == 1 AND !stristr($_SERVER['PHP_SELF'], "backend.php")) {
  $servtemp1 = strtolower(str_replace("http://", "", $nukeurl));
  if(substr($servtemp1, -1) == "/") { $servtemp1 = substr($servtemp1, 0, strlen($servtemp1)-1); }
  $servrqst1 = strtolower($_SERVER['HTTP_HOST']);
  if ($servrqst1 != $servtemp1 AND (!stristr($_SERVER['REQUEST_URI'], "modules/Forums/admin/") AND !stristr($_SERVER['REQUEST_URI'], "abuse/"))) {
    $rphp1 = $_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
    $rphp2 = str_replace($servrqst1, $servtemp1, $rphp1);
    $rphp2 = "http://".$rphp2;
    header("Location: $rphp2");
  }
}

// IP Tracking
// CAUTION: This function can slow your sites load time
if($ab_config['track_active'] == 1 AND !is_excluded($nsnst_const['remote_ip'])) {
if (is_file('kernel/Sentinel/track_active.php')) {
include_once('kernel/Sentinel/track_active.php');}
}

/*******************************/
/* BEGIN FUNCTIONS             */
/*******************************/

function get_remote_port() {
  if (isset($_SERVER["REMOTE_PORT"])) {
    return $_SERVER["REMOTE_PORT"];
  } elseif (isset($HTTP_SERVER_VARS["REMOTE_PORT"])) {
    return $HTTP_SERVER_VARS["REMOTE_PORT"];
  } elseif (getenv("REMOTE_PORT")) {
    return getenv("REMOTE_PORT");
  } else {
    return "none";
  }
}

function get_request_method() {
  if (isset($_SERVER['REQUEST_METHOD'])) {
    return $_SERVER['REQUEST_METHOD'];
  } elseif (isset($HTTP_SERVER_VARS['REQUEST_METHOD'])) {
    return $HTTP_SERVER_VARS['REQUEST_METHOD'];
  } elseif (getenv('REQUEST_METHOD')) {
    return getenv('REQUEST_METHOD');
  } else {
    return 'none';
  }
}

function get_script_name() {
  if (isset($_SERVER['SCRIPT_NAME'])) {
    return $_SERVER['SCRIPT_NAME'];
  } elseif (isset($HTTP_SERVER_VARS['SCRIPT_NAME'])) {
    return $HTTP_SERVER_VARS['SCRIPT_NAME'];
  } elseif (getenv('SCRIPT_NAME')) {
    return getenv('SCRIPT_NAME');
  } else {
    return 'none';
  }
}

function get_http_host() {
  if (isset($_SERVER['HTTP_HOST'])) {
    return $_SERVER['HTTP_HOST'];
  } elseif (isset($HTTP_SERVER_VARS['HTTP_HOST'])) {
    return $HTTP_SERVER_VARS['HTTP_HOST'];
  } elseif (getenv('HTTP_HOST')) {
    return getenv('HTTP_HOST');
  } else {
    return 'none';
  }
}

function st_clean_string($cleanstring) {
  $st_fr1 = array("%00", "%01", "%02", "%03", "%04", "%05", "%06", "%07", "%08", "%09", "%10", "%11", "%12", "%13", "%14", "%15", "%16", "%17", "%18", "%19", "%20", "%21", "%22", "%23", "%24", "%25", "%26", "%27", "%28", "%29", "%30", "%31", "%32", "%33", "%34", "%35", "%36", "%37", "%38", "%39", "%40", "%41", "%42", "%43", "%44", "%45", "%46", "%47", "%48", "%49", "%50", "%51", "%52", "%53", "%54", "%55", "%56", "%57", "%58", "%59", "%60", "%61", "%62", "%63", "%64", "%65", "%66", "%67", "%68", "%69", "%70", "%71", "%72", "%73", "%74", "%75", "%76", "%77", "%78", "%79");
  $st_to1 = array("", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", " ", "!", "\"", "#", "$", "%", "&", "'", "(", ")", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "@", "A", "B", "C", "D", "E", "F", "G", "H", "I", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "`", "a", "b", "c", "d", "e", "f", "g", "h", "i", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y");
  $st_fr2 = array("%0A", "%0B", "%0C", "%0D", "%0E", "%0F", "%1A", "%1B", "%1C", "%1D", "%1E", "%1F", "%2A", "%2B", "%2C", "%2D", "%2E", "%2F", "%3A", "%3B", "%3C", "%3D", "%3E", "%3F", "%4A", "%4B", "%4C", "%4D", "%4E", "%4F", "%5A", "%5B", "%5C", "%5D", "%5E", "%5F", "%6A", "%6B", "%6C", "%6D", "%6E", "%6F", "%7A", "%7B", "%7C", "%7D", "%7E", "%7F", "%0a", "%0b", "%0c", "%0d", "%0e", "%0f", "%1a", "%1b", "%1c", "%1d", "%1e", "%1f", "%2a", "%2b", "%2c", "%2d", "%2e", "%2f", "%3a", "%3b", "%3c", "%3d", "%3e", "%3f", "%4a", "%4b", "%4c", "%4d", "%4e", "%4f", "%5a", "%5b", "%5c", "%5d", "%5e", "%5f", "%6a", "%6b", "%6c", "%6d", "%6e", "%6f", "%7a", "%7b", "%7c", "%7d", "%7e", "%7f");
  $st_to2 = array("", "", "", "", "", "", "", "", "", "", "", "", "*", "+", ",", "-", ".", "/", ":", ";", "<", "=", ">", "?", "J", "K", "L", "M", "N", "O", "Z", "[", "\\", "]", "^", "_", "j", "k", "l", "m", "n", "o", "z", "{", "|", "}", "~", "", "", "", "", "", "", "", "", "", "", "", "", "", "*", "+", ",", "-", ".", "/", ":", ";", "<", "=", ">", "?", "J", "K", "L", "M", "N", "O", "Z", "[", "\\", "]", "^", "_", "j", "k", "l", "m", "n", "o", "z", "{", "|", "}", "~", "");
  $cleanstring = str_replace($st_fr1, $st_to1, $cleanstring);
  $cleanstring = str_replace($st_fr2, $st_to2, $cleanstring);
  return $cleanstring;
}

function get_query_string() {
  if (isset($_SERVER["QUERY_STRING"])) {
    return str_replace("%09", "%20", $_SERVER["QUERY_STRING"]);
  } elseif (isset($HTTP_SERVER_VARS["QUERY_STRING"])) {
    return str_replace("%09", "%20", $HTTP_SERVER_VARS["QUERY_STRING"]);
  } elseif (getenv("QUERY_STRING")) {
    return str_replace("%09", "%20", getenv("QUERY_STRING"));
  } else {
    return "none";
  }
}

function get_get_string() {
  $getstring = "";
  if (isset($_GET)) {
    $ST_GET = $_GET;
  } elseif (isset($HTTP_GET_VARS)) {
    $ST_GET = $HTTP_GET_VARS;
  } elseif (getenv("GET")) {
    $ST_GET = getenv("GET");
  } else {
    $ST_GET = "";
  }
  foreach ($ST_GET as $getkey => $getvalue) {
    if (!empty($getstring)) {
      $getstring .= "&".$getkey."=".$getvalue;
    } else {
      $getstring .= $getkey."=".$getvalue;
    }
  }
  return str_replace("%09", "%20", $getstring);
}

function get_post_string() {
  $poststring = "";
  if (isset($_POST)) {
    $ST_POST = $_POST;
  } elseif (isset($HTTP_POST_VARS)) {
    $ST_POST = $HTTP_POST_VARS;
  } elseif (getenv("POST")) {
    $ST_POST = getenv("POST");
  } else {
    $ST_POST = "";
  }
  foreach ($ST_POST as $postkey => $postvalue) {
    if (!empty($poststring)) {
      $poststring .= "&".$postkey."=".$postvalue;
    } else {
      $poststring .= $postkey."=".$postvalue;
    }
  }
  return str_replace("%09", "%20", $poststring);
}

function get_user_agent() {
  if (isset($_SERVER["HTTP_USER_AGENT"])) {
    return $_SERVER["HTTP_USER_AGENT"];
  } elseif (isset($HTTP_SERVER_VARS["HTTP_USER_AGENT"])) {
    return $HTTP_SERVER_VARS["HTTP_USER_AGENT"];
  } elseif (getenv("HTTP_USER_AGENT")) {
    return getenv("HTTP_USER_AGENT");
  } else {
    return "none";
  }
}

function get_referer() {
  if (isset($_SERVER["HTTP_REFERER"])) {
    return $_SERVER["HTTP_REFERER"];
  } elseif (isset($HTTP_SERVER_VARS["HTTP_REFERER"])) {
    return $HTTP_SERVER_VARS["HTTP_REFERER"];
  } elseif (getenv("HTTP_REFERER")) {
    return getenv("HTTP_REFERER");
  } else {
    return "none";
  }
}

function get_ip() {
  global $nsnst_const;
  if (strpos($nsnst_const['client_ip'], ', ') AND isset($nsnst_const['client_ip'])) {
    $client_ips = explode(', ', $nsnst_const['client_ip']);
    if($client_ips[0] != 'unknown' AND $client_ips[0] != 'none' AND !empty($client_ips[0]) AND !is_reserved($client_ips[0])) {
      $nsnst_const['client_ip'] = $client_ips[0];
    } else {
      $nsnst_const['client_ip'] = $client_ips[1];
    }
  }
  if (strpos($nsnst_const['forward_ip'], ', ') AND isset($nsnst_const['forward_ip'])) {
    $x_forwardeds = explode(', ', $nsnst_const['forward_ip']);
    if($x_forwardeds[0] != 'unknown' AND $x_forwardeds[0] != 'none' AND !empty($x_forwardeds[0]) AND !is_reserved($x_forwardeds[0])) {
      $nsnst_const['forward_ip'] = $x_forwardeds[0];
    } else {
      $nsnst_const['forward_ip'] = $x_forwardeds[1];
    }
  }
  if (strpos($nsnst_const['remote_addr'], ', ') AND isset($nsnst_const['remote_addr'])) {
    $remote_addrs = explode(', ', $nsnst_const['remote_addr']);
    if($remote_addrs[0] != 'unknown' AND $remote_addrs[0] != 'none' AND !empty($remote_addrs[0]) AND !is_reserved($remote_addrs[0])) {
      $nsnst_const['remote_addr'] = $remote_addrs[0];
    } else {
      $nsnst_const['remote_addr'] = $remote_addrs[1];
    }
  }
  if (isset($nsnst_const['client_ip']) && !stristr($nsnst_const['client_ip'], "none") && !stristr($nsnst_const['client_ip'], "unknown") AND !is_reserved($nsnst_const['client_ip'])) {
    return $nsnst_const['client_ip'];
  } elseif (isset($nsnst_const['forward_ip']) && !stristr($nsnst_const['forward_ip'], "none") && !stristr($nsnst_const['forward_ip'], "unknown") AND !is_reserved($nsnst_const['forward_ip'])) {
    return $nsnst_const['forward_ip'];
  } elseif (isset($nsnst_const['remote_addr']) && !stristr($nsnst_const['remote_addr'], "none") && !stristr($nsnst_const['remote_addr'], "unknown") AND !is_reserved($nsnst_const['remote_addr'])) {
    return $nsnst_const['remote_addr'];
  } else {
    return "none";
  }
}

function get_server_ip () {
  if(isset($_SERVER["SERVER_ADDR"])) {
    return $_SERVER["SERVER_ADDR"];
  } elseif (isset($HTTP_SERVER_VARS["SERVER_ADDR"])) {
    return $HTTP_SERVER_VARS["SERVER_ADDR"];
  } elseif (getenv("SERVER_ADDR")) {
    return getenv("SERVER_ADDR");
  } else {
    return "none";
  }
}

function get_client_ip () {
  if(isset($_SERVER["HTTP_CLIENT_IP"])) {
    return $_SERVER["HTTP_CLIENT_IP"];
  } elseif (isset($HTTP_SERVER_VARS["HTTP_CLIENT_IP"])) {
    return $HTTP_SERVER_VARS["HTTP_CLIENT_IP"];
  } elseif (getenv("HTTP_CLIENT_IP")) {
    return getenv("HTTP_CLIENT_IP");
  } else {
    return "none";
  }
}

function get_x_forwarded () {
  if(isset($_SERVER["HTTP_X_FORWARDED_FOR"])) {
    return $_SERVER["HTTP_X_FORWARDED_FOR"];
  } elseif (isset($HTTP_SERVER_VARS["HTTP_X_FORWARDED_FOR"])) {
    return $HTTP_SERVER_VARS["HTTP_X_FORWARDED_FOR"];
  } elseif (getenv("HTTP_X_FORWARDED_FOR")) {
    return getenv("HTTP_X_FORWARDED_FOR");
  } else {
    return "none";
  }
}

function get_remote_addr () {
  if(isset($_SERVER["REMOTE_ADDR"])) {
    return $_SERVER["REMOTE_ADDR"];
  } elseif (isset($HTTP_SERVER_VARS["REMOTE_ADDR"])) {
    return $HTTP_SERVER_VARS["REMOTE_ADDR"];
  } elseif (getenv("REMOTE_ADDR")) {
    return getenv("REMOTE_ADDR");
  } else {
    return "none";
  }
}

function is_excluded($rangeip){
  $longip = sprintf("%u", ip2long($rangeip));
  $excludenum = $GLOBALS['db']->sql_fetchrow($GLOBALS['db']->sql_query("SELECT `ip_lo` FROM `".TABLE_NSNST_EXCLUDED_RANGES."` WHERE `ip_lo`<='$longip' AND `ip_hi`>='$longip'"));
  if($excludenum > 0) { return 1; } else { return 0; }
  return 0;
}

function is_protected($rangeip){
  $longip = sprintf("%u", ip2long($rangeip));
  $protectnum = $GLOBALS['db']->sql_fetchrow($GLOBALS['db']->sql_query("SELECT `ip_lo` FROM `".TABLE_NSNST_PROTECTED_RANGES."` WHERE `ip_lo`<='$longip' AND `ip_hi`>='$longip'"));
  if($protectnum > 0) { return 1; } else { return 0; }
  return 0;
}

function is_reserved($rangeip) {
  $rangelong = sprintf("%u", ip2long($rangeip));
  $rangenum = $GLOBALS['db']->sql_numrows($GLOBALS['db']->sql_query("SELECT `ip_lo` FROM `".TABLE_NSNST_RESERVED_RANGES."` WHERE `ip_lo`<='$rangelong' AND `ip_hi`>='$rangelong'"));
  if($rangenum > 0) { return 1; } else { return 0; }
  return 0;
}

function abget_blocked($remoteip){
  $ip = explode(".", $remoteip);
  $testip1 = "$ip[0].*.*.*";
  $testip2 = "$ip[0].$ip[1].*.*";
  $testip3 = "$ip[0].$ip[1].$ip[2].*";
  $testip4 = "$ip[0].$ip[1].$ip[2].$ip[3]";
  $blocked_result = $GLOBALS['db']->sql_query("SELECT `ip_addr`, `user_id`, `user_name` FROM `".TABLE_NSNST_BLOCKED_IPS."` WHERE `ip_addr` = '$testip1' OR `ip_addr` = '$testip2' OR `ip_addr` = '$testip3' OR `ip_addr` = '$testip4'");
  $blocked_row = $GLOBALS['db']->sql_fetchrow($blocked_result);
  return $blocked_row;
}

function abget_blockedrange($remoteip){
  $longip = sprintf("%u", ip2long($remoteip));
  $blockedrange_result = $GLOBALS['db']->sql_query("SELECT `ip_lo`, `ip_hi`, `date`, `reason`, `expires` FROM `".TABLE_NSNST_BLOCKED_RANGES."` WHERE `ip_lo`<='$longip' AND `ip_hi`>='$longip'");
  $blockedrange_row = $GLOBALS['db']->sql_fetchrow($blockedrange_result);
  return $blockedrange_row;
}

function abget_blocker($blocker_name){
  $blockerresult = $GLOBALS['db']->sql_query("SELECT `blocker`, `block_name`, `activate`, `block_type`, `email_lookup`, `forward`, `reason`, `template`, `duration`, `htaccess`, `list` FROM `".TABLE_NSNST_BLOCKERS."` WHERE `block_name`='$blocker_name'");
  $blocker_row = $GLOBALS['db']->sql_fetchrow($blockerresult);
  return $blocker_row;
}

function abget_blockerrow($reason){
  $blockerresult = $GLOBALS['db']->sql_query("SELECT `blocker`, `block_name`, `activate`, `block_type`, `email_lookup`, `forward`, `reason`, `template`, `duration`, `htaccess`, `list` FROM `".TABLE_NSNST_BLOCKERS."` WHERE `blocker`='$reason'");
  $blocker_row = $GLOBALS['db']->sql_fetchrow($blockerresult);
  return $blocker_row;
}

function abget_admin($author){
  $adminresult = $GLOBALS['db']->sql_query("SELECT * FROM `".TABLE_NSNST_ADMINS."` WHERE `aid`='$author'");
  $admin_row   = $GLOBALS['db']->sql_fetchrow($adminresult);
  return $admin_row;
}

function abget_config($config_name){
  $configresult = $GLOBALS['db']->sql_query("SELECT `config_value` FROM `".TABLE_NSNST_CONFIG."` WHERE `config_name`='$config_name'");
  $row = $GLOBALS['db']->sql_fetchrow($reasonresult);
  $config_value = stripslashes($row['config_value']);
  return $config_value;
}

function abget_configs(){
  $configresult = $GLOBALS['db']->sql_query("SELECT `config_name`, `config_value` FROM `".TABLE_NSNST_CONFIG."`");
    while ($raw = $GLOBALS['db']->sql_fetchrow($configresult)) {
    $config_name  = stripslashes($raw['config_name']);
    $config_value = stripslashes($raw['config_value']);
    $config[$config_name] = $config_value;
  }
  return $config;
}

function abget_reason($reason_id){
  $reasonresult = $GLOBALS['db']->sql_query("SELECT `reason` FROM `".TABLE_NSNST_BLOCKERS."` WHERE `blocker`='$reason_id'");
  $row          = $GLOBALS['db']->sql_fetchrow($reasonresult);
  $reason_value = stripslashes($row['reason']);
  return $reason_value;
}


function block_ip($blocker_row, $abmatch="") {
  global $ab_config, $nsnst_const;
  if(!is_protected($nsnst_const['remote_ip'])) {
    $ip = explode(".", $nsnst_const['remote_ip']);
    include_once('kernel/Sentinel/clear_session.php');
    clear_session();
    $nsnst_const['ban_ip'] = "$ip[0].$ip[1].$ip[2].$ip[3]";
    $testip1 = "$ip[0].*.*.*";
    $testip1p = "deny from $ip[0]\n";
    $resultag1 = $GLOBALS['db']->sql_query("SELECT * FROM `".TABLE_NSNST_BLOCKED_IPS."` WHERE `ip_addr`='$testip1'");
    $numag1 = $GLOBALS['db']->sql_numrows($resultag1);
    if ($numag1 == 0 AND $blocker_row['block_type'] == 3) {
    include_once('kernel/Sentinel/write_mail.php');
    include_once('kernel/Sentinel/write_ban.php');
      write_mail($testip1, $blocker_row, $abmatch);
      write_ban($testip1, $testip1p, $blocker_row);
      $nsnst_const['ban_ip'] = $testip1;
    } elseif ($numag1 == 0 AND $blocker_row['block_type'] < 3) {
      $testip2 = "$ip[0].$ip[1].*.*";
      $testip2p = "deny from $ip[0].$ip[1]\n";
      $resultag2 = $GLOBALS['db']->sql_query("SELECT * FROM `".TABLE_NSNST_BLOCKED_IPS."` WHERE `ip_addr`='$testip2'");
      $numag2 = $GLOBALS['db']->sql_numrows($resultag2);
      if ($numag2 == 0 AND $blocker_row['block_type'] == 2) {
      include_once('kernel/Sentinel/write_mail.php');
      include_once('kernel/Sentinel/write_ban.php');
        write_mail($testip2, $blocker_row, $abmatch);
        write_ban($testip2, $testip2p, $blocker_row);
        $nsnst_const['ban_ip'] = $testip2;
      } elseif ($numag2 == 0 AND $blocker_row['block_type'] < 2) {
        $testip3 = "$ip[0].$ip[1].$ip[2].*";
        $testip3p = "deny from $ip[0].$ip[1].$ip[2]\n";
        $resultag3 = $GLOBALS['db']->sql_query("SELECT * FROM `".TABLE_NSNST_BLOCKED_IPS."` WHERE `ip_addr`='$testip3'");
        $numag3 = $GLOBALS['db']->sql_numrows($resultag3);
        if ($numag3 == 0 AND $blocker_row['block_type'] == 1) {
        include_once('kernel/Sentinel/write_mail.php');
        include_once('kernel/Sentinel/write_ban.php');
          write_mail($testip3, $blocker_row, $abmatch);
          write_ban($testip3, $testip3p, $blocker_row);
          $nsnst_const['ban_ip'] = $testip3;
        } elseif ($numag3 == 0 AND $blocker_row['block_type'] < 1) {
          $testip4 = "$ip[0].$ip[1].$ip[2].$ip[3]";
          $testip4p = "deny from $ip[0].$ip[1].$ip[2].$ip[3]\n";
          $resultag4 = $GLOBALS['db']->sql_query("SELECT * FROM `".TABLE_NSNST_BLOCKED_IPS."` WHERE `ip_addr`='$testip4'");
          $numag4 = $GLOBALS['db']->sql_numrows($resultag4);
          if ($numag4 == 0 AND $blocker_row['block_type'] == 0) {
          include_once('kernel/Sentinel/write_mail.php');
          include_once('kernel/Sentinel/write_ban.php');
            write_mail($testip4, $blocker_row, $abmatch);
            write_ban($testip4, $testip4p, $blocker_row);
            $nsnst_const['ban_ip'] = $testip4;
          }
        }
      }
    }
    $blocked_row = abget_blocked($nsnst_const['ban_ip']);
    blocked($blocked_row, $blocker_row);
    die();
  } else {
    return;
  }
}

if (!function_exists("file_get_contents")) {
  function file_get_contents($filename, $use_include_path = 0) {
    $file = @fopen($filename, "rb", $use_include_path);
    if ($file) {
      while (!feof($file)) $data .= fread($file, 1024);
      @fclose($file);
    }
    return $data;
  }
}

function abget_template($template="") {
  global $ab_config, $nsnst_const, $ip, $adminmail, $sitename;
  if(empty($template)) { $template = "abuse_default.tpl"; }
  $adminmail = str_replace("@", "(at)", $adminmail);
  $adminmail = str_replace(".", "(dot)", $adminmail);
  $adminmail2 = urlencode($adminmail);
  $querystring = get_query_string();
  $filename = "abuse/".$template;
  if(!file_exists($filename)) { $filename = "abuse/abuse_default.tpl"; }
  $handle = @fopen($filename, "r");
  $display_page = fread($handle, filesize($filename));
  @fclose($handle);
  $display_page = str_replace("__SITENAME__", $sitename, $display_page);
  $display_page = str_replace("__ADMINMAIL1__", $adminmail, $display_page);
  $display_page = str_replace("__ADMINMAIL2__", $adminmail2, $display_page);
  $display_page = str_replace("__REMOTEPORT__", $nsnst_const['remote_port'], $display_page);
  $display_page = str_replace("__REQUESTMETHOD__", $nsnst_const['request_method'], $display_page);
  $display_page = str_replace("__SCRIPTNAME__", $nsnst_const['script_name'], $display_page);
  $display_page = str_replace("__HTTPHOST__", $nsnst_const['http_host'], $display_page);
  $display_page = str_replace("__USERAGENT__", $nsnst_const['user_agent'], $display_page);
  $display_page = str_replace("__CLIENTIP__", $nsnst_const['client_ip'], $display_page);
  $display_page = str_replace("__FORWARDEDFOR__", $nsnst_const['forward_ip'], $display_page);
  $display_page = str_replace("__REMOTEADDR__", $nsnst_const['remote_addr'], $display_page);
  return $display_page;
}

function blocked($blocked_row="", $blocker_row="") {
  global $ab_config, $nsnst_const, $max_time;
  $ip = explode(".", $nsnst_const['remote_ip']);
  if (is_file('includes/counter.php')) {
  include('includes/counter.php');}
  if(!$nsnst_const['ban_time'] OR empty($nsnst_const['ban_time'])) { $nsnst_const['ban_time'] = $max_time; }
  if(empty($blocked_row)) { $blocked_row = abget_blocked($ip); }
  if(empty($blocked_row)) { $blocked_row['reason'] = 0; $blocked_row['date'] = $max_time; }
  if(empty($blocker_row)) { $blocker_row = abget_blockerrow($blocked_row['reason']); }
  if(($blocker_row['activate'] == 2 OR $blocker_row['activate'] == 4 OR $blocker_row['activate'] == 6) AND !empty($blocker_row['forward'])) {
    header("Location: ".$blocker_row['forward']);
    die();
  } elseif($blocker_row['activate'] == 3 OR $blocker_row['activate'] == 5 OR $blocker_row['activate'] == 7) {
    $display_page = abget_template($blocker_row['template']);
    $display_page = str_replace("__TIMEDATE__", date("Y-m-d \@ H:i:s T \G\M\T O", $blocked_row['date']), $display_page);
    if($blocked_row['expires']>0) {
      $display_page = str_replace("__DATEEXPIRES__", date("Y-m-d \@ H:i:s T \G\M\T O", $blocked_row['expires']), $display_page);
    } elseif(isset($blocked_row['expires'])) {
      $display_page = str_replace("__DATEEXPIRES__", _AB_PERMENANT, $display_page);
    } else {
      $display_page = str_replace("__DATEEXPIRES__", _AB_UNKNOWN, $display_page);
    }
    $display_page = eregi_replace("</body>", "<hr noshade>\n<div align='right'>"._AB_NUKESENTINEL." ".$ab_config['version_number']." "._AB_BYNSN."</div>\n</body>", $display_page);
    die($display_page);
  } else {
    $display_page = abget_template();
    $display_page = str_replace("__TIMEDATE__", date("Y-m-d \@ H:i:s T \G\M\T O", $max_time), $display_page);
    if($blocked_row['expires']>0) {
      $display_page = str_replace("__DATEEXPIRES__", date("Y-m-d \@ H:i:s T \G\M\T O", $blocked_row['expires']), $display_page);
    } else {
      $display_page = str_replace("__DATEEXPIRES__", _AB_PERMENANT, $display_page);
    }
    $display_page = eregi_replace("</body>", "<hr noshade>\n<div align='right'>"._AB_NUKESENTINEL." ".$ab_config['version_number']." "._AB_BYNSN."</div>\n</body>", $display_page);
    die($display_page);
  }
}

function blockedrange($blockedrange_row="") {
  global $ab_config, $nsnst_const, $max_time;
  $ip = explode(".", $nsnst_const['remote_ip']);
  if (is_file('includes/counter.php')) {
  include('includes/counter.php');}
  if(!$nsnst_const['ban_time'] OR empty($nsnst_const['ban_time'])) { $nsnst_const['ban_time'] = $max_time; }
  if(empty($blockedrange_row)) { $blockedrange_row = abget_blockedrange($remote); }
  if(empty($blockedrange_row)) { $blockedrange_row['reason'] = 0; $blockedrange_row['date'] = $max_time; }
  if(empty($blocker_row)) { $blocker_row = abget_blockerrow($blockedrange_row['reason']); }
  if(($blocker_row['activate'] == 2 OR $blocker_row['activate'] == 4 OR $blocker_row['activate'] == 6) AND !empty($blocker_row['forward'])) {
    header("Location: ".$blocker_row['forward']);
    die();
  } elseif($blocker_row['activate'] == 3 OR $blocker_row['activate'] == 5 OR $blocker_row['activate'] == 7) {
    $display_page = abget_template($blocker_row['template']);
    $display_page = str_replace("__TIMEDATE__", date("Y-m-d \@ H:i:s T \G\M\T O", $blockedrange_row['date']), $display_page);
    if($blockedrange_row['expires']>0) {
      $display_page = str_replace("__DATEEXPIRES__", date("Y-m-d \@ H:i:s T \G\M\T O", $blockedrange_row['expires']), $display_page);
    } elseif(isset($blockedrange_row['expires'])) {
      $display_page = str_replace("__DATEEXPIRES__", _AB_PERMENANT, $display_page);
    } else {
      $display_page = str_replace("__DATEEXPIRES__", _AB_UNKNOWN, $display_page);
    }
    $display_page = eregi_replace("</body>", "<hr noshade>\n<div align='right'>"._AB_NUKESENTINEL." ".$ab_config['version_number']." "._AB_BYNSN."</div>\n</body>", $display_page);
    die($display_page);
  } else {
    $display_page = abget_template();
    $display_page = str_replace("__TIMEDATE__", date("Y-m-d \@ H:i:s T \G\M\T O", $max_time), $display_page);
    if($blockedrange_row['expires']>0) {
      $display_page = str_replace("__DATEEXPIRES__", date("Y-m-d \@ H:i:s T \G\M\T O", $blockedrange_row['expires']), $display_page);
    } else {
      $display_page = str_replace("__DATEEXPIRES__", _AB_PERMENANT, $display_page);
    }
    $display_page = eregi_replace("</body>", "<hr noshade>\n<div align='right'>"._AB_NUKESENTINEL." ".$ab_config['version_number']." "._AB_BYNSN."</div>\n</body>", $display_page);
    die($display_page);
  }
}

function ABGetCIDRs($long_lo, $long_hi) {
  global $masscidr;
  $chosts = ($long_hi - $long_lo) + 1;
  $testrst = $GLOBALS['db']->sql_query("SELECT * FROM `".TABLE_NSNST_CIDRS."` ORDER BY `hosts` DESC");
  $cidrs = $hosts = $masks = "";
  while($test = $GLOBALS['db']->sql_fetchrow($testrst)) {
    if($chosts >= $test['hosts']) {
      $cidrs = $test['cidr']."||".$cidrs;
      $hosts = $test['hosts']."||".$hosts;
      $masks = $test['mask']."||".$masks;
      $chosts = $chosts - $test['hosts'];
    }
  }
  $cidrs = rtrim($cidrs, "||");
  $hosts = rtrim($hosts, "||");
  $masks = rtrim($masks, "||");
  $cidrsary = explode("||", $cidrs);
  $hostsary = explode("||", $hosts);
  $masksary = explode("||", $masks);
  $masscidr = "";
  $nextcidr = $long_lo;
  for($i=0; $i<count($cidrsary); $i++) {
    $tempcidr = long2ip($nextcidr)."/".$cidrsary[$i];
    $masscidr = $masscidr.$tempcidr."||";
    $nextcidr = $nextcidr + $hostsary[$i];
  }
  $masscidr = rtrim($masscidr, "||");
  return $masscidr;
}