<?php
/*
 * 中间件solr
 * Fisher 2014-5-5
*/
class Solr_class
{
    private $api_url = "";  //应用接口地址

    private $show_field_str   = "*"; //显示字段
    private $query_field_str  = "&q=";  //检索字段
    private $filter_field_str = "";  //过滤字段
    private $order_field_str  = "";  //排序字段
    private $start_num        = "&s=0";  //位移量
    private $rows_num         = "&r=1";  //查询条数
    private $count_num        = "&fn=1000"; //统计分组获取条数
    private $count_field_str  = "";  //统计分组

    private $mc = "nomc";//MC对象    
    
    //构造方法
    public function __construct($arr)
    {
        $this->api_url = $arr['api_url'];
    }
    
    //设置MC对象
    public function setMc($mc)
    {
        $this->mc = is_object($mc) ? $mc : "nomc";
    }
    
    //查询数据
    public function query($query_type = 'normal')
    {
        //normal：普通模式  countgroup：统计分组模式
        $url = $query_type == 'normal' ? $this->api_url.$this->show_field_str.$this->query_field_str.$this->filter_field_str.$this->order_field_str.$this->start_num.$this->rows_num : $this->api_url.$this->count_field_str.$this->query_field_str.$this->filter_field_str.$this->count_num;
        //echo $url."<br /><br />";
        //是否启用MC
        if("nomc" == $this->mc)
        {
            $str = $this->curl_get_contents($url);
        }
        else
        {
            $memkey = md5($url);
            $cache = $this->mc->get($memkey);
            if($cache['isok'] == 1)
            {
                $str = $cache['data'];
            }
            else
            {
                $str = $this->curl_get_contents($url);
                $this->mc->add($memkey, array('isok'=>1, 'data'=>$str), false, 5);
            }
        }
        
        $sss = json_decode($str);
        $arr = $this->obj2arr(json_decode($str));

		return $arr;
    }
    
    //CURL
    public function curl_get_contents($url,$t_url="")
	{
		$ch = curl_init();
        $t_url = $t_url ? $t_url : "http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_REFERER, $t_url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

        $str = curl_exec($ch);
        curl_close($ch);

        return $str;
	}

    //设置显示字段
    public function setShowField($show_field_arr = array())
    {
        $show_field_str = "";
        if(is_array($show_field_arr) && !empty($show_field_arr))
        {
            foreach($show_field_arr as $value)
            {
                $show_field_str .= "&sf1=$value";
            }
        }

        $this->show_field_str = $show_field_str;
    }

    //设置检索字段
    public function setQueryField($query_field_arr = array())
    {
        $query_field_str = "";
        if(is_array($query_field_arr) && !empty($query_field_arr))
        {
            $field_str = "";
            foreach($query_field_arr as $key=>$value)
            {
                $field_str .= $field_str == '' ? "$key%3A".urlencode($this->gbk2utf($value)) : "+OR+$key%3A".urlencode($this->gbk2utf($value));
            }
            
            $query_field_str = "&q=".$field_str;
        }
        else
        {
            $query_field_str = "&q=";
        }
        
        $this->query_field_str = $query_field_str;
    }

    //设置过滤字段
    public function setFilterField($filter_field_arr = array())
    {
        $filter_field_str = "";
        
        if(is_array($filter_field_arr) && !empty($filter_field_arr))
        {
            $field_str = "";

            foreach($filter_field_arr as $key=>$value)
            {
                
                $f_str = "";

                switch($value["inneroper"])
                { 
                    case "TO":  
                                $f_str = $value["oper"]."+".$value["field"];
                                $f_str .= "%3A[".intval($value["value"][0])."+TO+".intval($value["value"][1])."]";
                                break;
                    case "OR":  
                    case "AND": 
                                $f_str = $value["oper"]."+(";
                                $fs = "";
                                foreach((array)$value["value"] as $val)
                                {
                                    $fs .= $fs == '' ? $value["field"]."%3A".$val : "+".$value["inneroper"]."+".$value["field"]."%3A".$val;
                                }
                                $f_str .= $fs.")";
                                break;
                    default:    
                                $f_str = $value["oper"]."+".$value["field"];
                                $f_str .= "%3A".urlencode($this->gbk2utf($value["value"]));
                                break;
                }

                $field_str .= $field_str == '' ? $f_str : "+".$f_str;
            }

            $filter_field_str = "&fq=".$field_str;
        }

        $this->filter_field_str = $filter_field_str;
    }

    //设置排序字段
    public function setOrderField($order_field_arr = array())
    {
        $order_field_str = "";
        if(is_array($order_field_arr) && !empty($order_field_arr))
        {   
            $order_field_str .= "&of=";
            $order_str = "";
            foreach($order_field_arr as $key=>$value)
            {
                $order_str .= $order_str == "" ? $key."+".$value : "%2C".$key."+".$value;
            }
            $order_field_str .= $order_str;
        }
        $this->order_field_str = $order_field_str;
    }

    //设置统计分组
    public function setCountField($count_field_arr = array())
    {

        $count_field_str = "";
        if(is_array($count_field_arr) && !empty($count_field_arr))
        {
            $count_field_str .= "&ft=";
            $count_str = "";
            foreach($count_field_arr as $key=>$value)
            {
                $count_str .= $count_str == "" ? $value : "%2C".$value;
            }
            $count_field_str .= $count_str;
        }
        $this->count_field_str = $count_field_str;
    }
    
    //设置位移量
    public function setStartNum($start_num)
    {
        $start_num = intval($start_num);
        $this->start_num = "&s=".$start_num;
    }
        
    //设置查询条数
    public function setRowsNum($rows_num)
    {
        $rows_num = intval($rows_num);
        $this->rows_num = "&r=".$rows_num;
    }

    //设置查询条数
    public function setCountNum($count_num)
    {
        $count_num = intval($count_num);
        $this->count_num = "&fn=".$count_num;
    }

    //GBK转UTF8编码
    public function gbk2utf($strInput)
    {
        return $this->is_gbk($strInput) ? $this->strIconv($strInput, "gbk", "utf-8") : $strInput;
    }

    //UTF8转GBK编码
    public function utf2gbk($strInput)
    {
        return $this->is_utf8($strInput) ? $this->strIconv($strInput, "utf-8", "gbk") : $strInput;
    }

    //是否UTF8格式编码
    public function is_utf8($strInput)
    {
        return $strInput === iconv("gbk", "utf-8", iconv("utf-8", "gbk", $strInput));
    }

    //是否gbk格式编码
    public function is_gbk($strInput)
    {
        return $strInput === iconv("utf-8", "gbk", iconv("gbk", "utf-8", $strInput));
    }

    //替换数组编码
    public function strIconv($strInput,$inChar="",$outChar="")
    {
        $strOutput = iconv($inChar, $outChar, $strInput);
        return $strOutput !== false ? $strOutput : $strInput;
    }

    //JSON格式数据递归转化为ARRAY
    public function obj2arr($obj){
        $ret = array();
        if(gettype($obj) == 'array' || gettype($obj) == 'object')
        {
            foreach($obj as $key =>$value){
                if(gettype($value) == 'array' || gettype($value) == 'object'){
                    $ret[$key] = $this->obj2arr($value);
                }
                else{
                    $ret[$key] = $value;
                }
            }    
        }
        
        return $ret;
    }
}