<?php

class Akismet {

    var $_blog        = "http://blog.phpdeveloper.org";
    var $_user_ip    = "";
    var $_user_agent= "";
    var $_wp_key    = "";
    var $_server    = "";

    public function Akismet(){
        $this->_user_ip        = $_SERVER['REMOTE_ADDR'];
        $this->_user_agent    = $_SERVER['HTTP_USER_AGENT'];
        $this->_referer        = $_SERVER['HTTP_REFERER'];
    }
    //---------------------
    private function _makeRequest($host,$path,$request,$port=80){
        $return="";
        $msg=sprintf("POST %s HTTP/1.0\r
            Host: %s\r
            Content-type: application/x-www-form-urlencoded; charset=utf-8\r
            Content-length: %s\r
            User-Agent: %s\r
            \r
            %s
        ",$path,$host,strlen($request),$this->_user_agent,$request);

        $msg=str_replace("\t","",$msg); //echo $msg;
        $fp=fsockopen($host,$port,$errno,$errstr,3);
        if($fp){
            fwrite($fp,$msg);
            while(!feof($fp)){ $return.=fgets($fp,1024); }
            fclose($fp);
        }
        return explode("\r\n\r\n",$return);
    }
    private function _encodeRequest($arr){
        $request='';
        foreach($arr as $key => $value){
            $request.=$key."=".urlencode(stripslashes($value))."&";
        }
        return substr($request,0,strlen($request)-1);
    }
    //---------------------
    // At least comment_content and comment_author need to be set to get anythink good
    public function checkSpam($content_arr){
        $this->_server    =$this->_wp_key.".rest.akismet.com";
        $this->_path    = "/1.1/comment-check";

        $request_arr=array(
            "blog"             =>$this->_blog,
            "user_ip"         =>$this->_user_ip,
            "user_agent"     =>$this->_user_agent,
            "referrer"         =>$this->_referer,
            "comment_type"     =>"comment"
        );
        $request_arr=array_merge($request_arr,$content_arr);

        $request= $this->_encodeRequest($request_arr); //echo $request."\n";
        $return    = $this->_makeRequest($this->_server,$this->_path,$request);
        if(isset($return[1]) && $return[1]=="true"){
            return true;
        }else{ return false; }
    }
    public function checkKey(){
        $this->_server    ="rest.akismet.com";
        $this->_path    = "/1.1/verify-key";

        $request_arr=array(
            "key"=>$this->_wp_key,
            "blog"=>$this->_blog
        );
        $request=$this->_encodeRequest($request_arr);

        $response=$this->_makeRequest($this->_server,$this->_path,$request);
        if(!empty($response[1]) && $response[1]=="valid"){
            return true;
        }else{ return false; }
    }
    public function submitSpam(){
    }
    public function submitHam(){
    }

}