<?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));
        }
        if (!mysqli_query($db_link,"desc abuseipdb")){
            $query="create table abuseipdb (id int not null auto_increment primary key, ip text not null, lastcheck int not null default 0, result text not null) default charset=utf8mb4 collate=utf8mb4_bin";
            mysqli_query($db_link,$query) or die (mysqli_error($db_link));
        }
        if(!mysqli_query($db_link,"desc bans")){
            $query="create table bans (id int not null auto_increment primary key, ip varchar(48) not null default '', timestamp int not null default 0, expires int not null default 0, exclude int not null default 0, comment text not null) default charset=utf8mb4 collate=utf8mb4_bin";
            mysqli_query($db_link,$query) or die(mysqli_error($db_link));
        }
        if (isset($_SERVER['SERVER_PROTOCOL']))
            $blockhdr=$_SERVER['SERVER_PROTOCOL']." 403 Forbidden";
        $timestamp = time();
        $agent=isset($_SERVER['HTTP_USER_AGENT'])?$_SERVER['HTTP_USER_AGENT']:"";
        $whitelisted = false;
        if ($allow) {
            $table = "abuseipdb";
            $query="select result, lastcheck from $table where ip='$ip'";
            $result=mysqli_query($db_link,$query) or die(mysqli_error($db_link));
            if(mysqli_num_rows($result) > 0) {
                while ($arr=mysqli_fetch_assoc($result)) {
                    $abuseipdb_lastcheck=$arr['lastcheck'];
                    $abuseipdb_result=!empty($arr['result'])?$arr['result']:false;
                    if ($abuseipdb_lastcheck <= $timestamp - 60*60*24) {
                        $abuseipdb_result = abuseipdbcheckip($ip);
                        if ($abuseipdb_result !== false) {
                            mysqli_query($db_link,"update $table set lastcheck='$timestamp', result='".mysqli_real_escape_string($db_link,$abuseipdb_result)."' where ip='$ip'") or die (mysqli_error($db_link));
                        }
                    }
                }
            } else {
                $abuseipdb_result = abuseipdbcheckip($ip);
                if ($abuseipdb_result !== false) {
                    mysqli_query($db_link,"insert into $table (ip, lastcheck, result) values ('$ip','$timestamp','".mysqli_real_escape_string($db_link,$abuseipdb_result)."')") or die (mysqli_error($db_link));
                }
            }
            include "ipwhitelist.php";
            $host_whitelist[]="mj12bot\.com$"; //MJ12bot
            if (isset($whitelist) && in_array($ip, $whitelist))
                $whitelisted = true;
            if (isset($host_whitelist)) {
                foreach ($host_whitelist as $pattern) {
                    if (preg_match("/".$pattern."/i",$host)) {
                        $whitelisted = true;
                        break;
                    }
                }
            }
            $agent_whitelist[]="^Mozilla\/5\.0 \(compatible; MJ12bot\/[^;]+; http:\/\/mj12bot\.com\/\)$";
            if (isset($agent_whitelist)) {
                foreach ($agent_whitelist as $pattern) {
                    if (preg_match("/".$pattern."/i",$agent)) {
                        $whitelisted = true;
                        break;
                    }
                }
            }
            if (!$whitelisted && $abuseipdb_result !== false) {
                $abuseipdb_json = json_decode($abuseipdb_result,true);
                if ($abuseipdb_json !== NULL) {
                    $abuseipdb_data = $abuseipdb_json['data'];
                    $abuseipdb_score = $abuseipdb_data['abuseConfidenceScore'];
                    $abuseipdb_whitelisted = $abuseipdb_data['isWhitelisted'];
                    $abuseipdb_usage = $abuseipdb_data['usageType'];
                    if (isset($abuseipdb_data['domain'])) {
                        $abuseipdb_domain = $abuseipdb_data['domain'];
                        switch ($abuseipdb_domain) {
                            case "facebook.com":
                                $abuseipdb_whitelisted = true;
                            break;
                            case "hetzner.de":
                            case "microsoft.com":
                                if ($abuseipdb_usage == "Search Engine Spider")
                                $abuseipdb_whitelisted = true;
                            break;
                            default: break;
                        }
                    }
                    if (!$abuseipdb_whitelisted && $abuseipdb_score >= 60) {
                        $blocktit = "Banned";
                        $blockmsg = "The abuse ratio of your IP is too high. Ban imminent.";
                        $allow=false;
                        $update = false;
                        $table="bans";
                        if (!isset($evt) || $evt != 403) $evt = 403;
                        if (mysqli_num_rows(mysqli_query($db_link,"select * from $table where ip='$ip'"))>0){ //ip in db
                            $action="AbuseIPDB-Ban (Dupe found)";
                        } else {
                            $action = "AbuseIPDB-Ban";
                            $update = true;
                            mysqli_query($db_link,"insert into $table (ip,timestamp,expires,exclude,comment) values ('$ip','$timestamp.','".($timestamp+60*60*24*2)."','0','')") or die(mysqli_error($db_link));
                        }
                        if ($update) {
                            //read all bans
                            $result=mysqli_query($db_link,"select ip from $table order by ip");
                            $bans="";
                            if (mysqli_num_rows($result) > 0) {
                                while($ban=mysqli_fetch_assoc($result)){
                                    $bans.= "Deny from ".$ban['ip']."\n";
                                }
                            }
                            //update htaccess
                            $out="$htaccess_header\n$errordoc\n$rewrite_rules\n$badbots\nOrder Allow,Deny\nAllow from all\nDeny from env=bad_bot\n$badips\n$bans";
                            $file=fopen(".htaccess","w");
                            fwrite($file, $out);
                            fclose($file);
                        }

                        if (isset($tmp)) unset ($tmp);
                        $log=fopen("logs/bottrap.txt", "a");
                        fwrite($log, "[".date("Y-m-d H:i:s")."] [".$ip.(!empty($host)?(" ".$host):"")."] [$action]\n".(isset($_SERVER['HTTP_USER_AGENT'])?$_SERVER['HTTP_USER_AGENT']:"")."\n\n");
                        fclose($log);
                    }
                }
            }
        }

        //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 <= $timestamp";
            mysqli_query($db_link,$query) or die(mysqli_error($db_link));
            //check against several rules
            //check user agent
            if ($allow) {
                $query="select * from $table where type='agent'";
                $result=mysqli_query($db_link,$query) or die(mysqli_error($db_link));
                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) {
                if (isset($_SERVER['REQUEST_URI'])){
                    $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) {
                if (isset($type)) {
                    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='$timestamp' 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):"")."','$timestamp')";
                    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");
                $event="";
                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 ($event != $arr['event']) {
                        if($event != "") 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;
                        }
                        $event=$arr['event'];
                        echo "<h4><a href=\"javascript:void(0)\" onclick=\"toggle('div_$event',this)\" title=\"Click to Show\">$event</a></h4><div id=\"div_$event\" 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>";
            } else {
                echo "No entries found jet.";
            }
        }
        mysqli_close($db_link);
        unset($timestamp);
    } else {
        $allow=false;
    }
} else $allow=true;
?>