<?php
if(file_exists("include/db.php")){
    $admin=isset($admin)?$admin:false;
    $action=isset($action)?$action:false;
    include "db.php";
    if($db_link) {
        mysqli_select_db($db_link,$db) or die(mysqli_error($db_link));
        //cleanup
        $table="ipfilter_log";
        if(isset($_GET['clean']) && ($_GET['clean']=="log") && $admin) {
              $query="drop table if exists $table";
              mysqli_query($db_link,$query) or die(mysqli_error($db_link));
        }
        //create tables
        if(!mysqli_query($db_link,"desc ipfilter")) {
            $query="create table ipfilter (id int not null auto_increment primary key, rule varchar (128) not null default '', type varchar (32) not null default '', expires int not null default 0)";
            mysqli_query($db_link,$query) or die(mysqli_error($db_link));
        }
        if(!mysqli_query($db_link,"desc ipfilter_log")) {
            $query="create table ipfilter_log (id int not null auto_increment primary key, event varchar(16) not null default '', ip varchar(48) not null default '', host varchar(128) not null default '', value varchar (256) not null default '', date int not null default 0)";
            mysqli_query($db_link,$query) or die(mysqli_error($db_link));
        }
        //filter ip
        $table="ipfilter";
        if((!$admin) || ($action !="ipfilter")) {
            //check for expired rules and remove if any.
            $query="delete from $table where expires > 0 and expires <= ".time();
            mysqli_query($db_link,$query) or die(mysqli_error($db_link));
            //check against several rules
            $blockhdr=$_SERVER['SERVER_PROTOCOL']." 403 Forbidden";
            //check user agent
            if ($allow) {
                $query="select * from $table where type='agent'";
                $result=mysqli_query($db_link,$query) or die(mysqli_error($db_link));
                $agent=isset($_SERVER['HTTP_USER_AGENT'])?$_SERVER['HTTP_USER_AGENT']:"";
                if(mysqli_num_rows($result) > 0) {
                    while($arr = mysqli_fetch_assoc($result)){
                        if(strripos($agent, $arr['rule'])!==false) {
                            $allow=false;
                            $warn=false;
                            $type=$arr['type'];
                            $rule=$arr['rule'];
                            $blocktit="Site Access Denied";
                            $blockmsg="Your User Agent (or part of it) has been blacklisted. <b>$rule</b> has been detected in your user agent string.";
                            $warnlist[]="Mozilla";
                            foreach($warnlist as $warnitem) {
                                if(strripos($agent, $warnitem)!==false) {
                                    $warn=true;
                                }
                            }
                            //$ignorelist[]="FINLY";
                            //$ignorelist[]="findlinks";
                            if (isset($ignorelist)) {
                                foreach($ignorelist as $warnitem) {
                                    if(strripos($agent, $warnitem)!==false) {
                                        $warn=false;
                                    }
                                }
                            }
                            if($warn) {
                                $blockmsg.=" It's possible that your user agent was altered by malware. Please clean your computer of viruses, spyware and malware then try again...\n<br>Your User Agent: $agent ";    
                            }
                            //$blockhdr=$_SERVER['SERVER_PROTOCOL']." 400 Bad Request"; 
                        }
                    }
                }
            }
            
            //check url
            if($allow) {
                $query="select * from $table where type='uri'";
                $result=mysqli_query($db_link,$query) or die(mysqli_error($db_link));
                $uri=$_SERVER['REQUEST_URI'];
                if(mysqli_num_rows($result) > 0) {
                    while($arr = mysqli_fetch_assoc($result)){
                        if(strripos($uri, $arr['rule'])!==false) {
                            $allow=false;
                            $type=$arr['type'];
                            $rule=$arr['rule'];
                            $blocktit="Site Access Denied";
                            $blockmsg="The url you typed (or part of it) has been blacklisted. <b>$rule</b> detected in url request.";
                            //$blockhdr=$_SERVER['SERVER_PROTOCOL']." 400 Bad Request"; 
                        }
                    }
                }
            }

            $log=false;
            if (!$allow) {
                switch($type) {
                    case "agent":
                        $event=$type;
                        $data=$agent;
                        $log=true;
                    break;
                    case "uri":
                        $event=$type;
                        $data=$uri;
                        $log=true;
                    break;
                    /*case "error":
                        $event=$type;
                        $log=false;
                    break;*/
                    default:
                        $event="unknown";
                        $log=true;
                    break;
                }
            }
                
            $table="ipfilter_log";
            if($log) {
                $query="select * from $table where event='$event' and ip='$ip' and value='".(isset($data)?mysqli_real_escape_string($db_link,$data):"")."'";
                $result=mysqli_query($db_link,$query);
                $count=mysqli_num_rows($result);
                if($count > 0){
                    $query = "update $table set date='".time()."' where event='$event' and ip='$ip' and value='".(isset($data)?mysqli_real_escape_string($db_link,$data):"")."'";
                mysqli_query($db_link,$query) or die(mysqli_error($db_link));
                $query = "update $table set host='$host' where event='$event' and ip='$ip' and value='".(isset($data)?mysqli_real_escape_string($db_link,$data):"")."'";
                mysqli_query($db_link,$query) or die(mysqli_error($db_link));
                } else {
                    $query="insert into $table (event, ip, host, value, date) values ('$event', '$ip', '$host', '".(isset($data)?mysqli_real_escape_string($db_link,$data):"")."','".time()."')";
                    mysqli_query($db_link,$query) or die(mysqli_error($db_link));
                }
            }
        } else {
            $table="ipfilter_log";
            echo "<h3>IP Filter Log</h3>\n";
            $query="select date, ip, host, event, value from $table order by event, date desc";
            $result=mysqli_query($db_link,$query) or die(mysqli_error($db_link));
            $count=mysqli_num_rows($result);
            if($count > 0) {
                $mylinks[]=Array("Clean IP Filter Log","$PHP_SELF?action=$action&clean=log&lang=$lang");
                $evt="";
                echo <<<EOF
<script>
//call using onclick="toggle('id',this)"
function toggle(obj,link) {
    if(document.getElementById(obj).style.display != 'none'){
        document.getElementById(obj).style.display= 'none';
        link.title='Click to Show';
    } else {
        document.getElementById(obj).style.display = '';
        link.title='Click to Hide';
    }
}
</script>
EOF;
                while($arr=mysqli_fetch_assoc($result)) {
                    if ($evt != $arr['event']) {
                        if($evt != "") echo "</table></div>";
                        switch($arr['event']) {
                            case "agent":
                                $event="Matched User Agents";
                            break;
                            case "uri";
                                $event="Matched URL Requests";
                            break;
                            default:
                                $event="[".$arr['event']." event]";
                            break;
                        }
                        $evt=$arr['event'];
                        echo "<h4><a href=\"javascript:void(0)\" onclick=\"toggle('div_$evt',this)\" title=\"Click to Show\">$event</a></h4><div id=\"div_$evt\" style=\"width: 730px; height:250px; overflow:auto; display:none\"><table width=\"1100\" class=\"form\">\n<tr><th>Date<th>IP<th>Host<th>Value</tr>\n";
                    }
                    echo "<tr><td>".date("Y-m-d H:i:s",$arr['date'])."<td>".$arr['ip']."<td>".$arr['host']."<td>".htmlspecialchars($arr['value'])."</tr>\n";
                }
                echo "</table></div>";
                                unset($evt); //fix navigation bug
            } else {
                echo "No entries found jet.";
            }
        }
        mysqli_close($db_link);
    } else {
        $allow=false;
        $evt="Database Error";
      }
} else $allow=true;
?>