<?php


// +----------------------------------------------------------------------
// | 桌子工作室 [Http协议] V0.12015014  Released
// +----------------------------------------------------------------------
// | Copyright (c) 2015-2016 ，MrTable All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: Mr Table <admin@hjf.pw>
// +----------------------------------------------------------------------
declare (strict_types=1);
namespace library\utils;

 class Http{
    private static $boundary = '';

    public static $cookie = [];
    /**
     * get获取
     * @param string $url 
     * @param type $params 数组类型
     * @return type
     */
    public static function get($url, $params = '',$cookie = [])
    {
        if(is_array($params)) $url = $url . '?' . http_build_query($params);
        return self::https($url, 'GET',null,[],$cookie);
    }
    
    /**
     * post传递
     * @param type $url
     * @param type $params post数组
     * @param type $files 文件数据
     * @return type
     */
    public static function post($url, $params, $files = array(),$headers = array(),$cookie = [])
    {
        if (!$files) {
            $body = http_build_query($params);
        } else {
            $body = self::build_http_query_multi($params, $files);
            $headers[] = "Content-Type: multipart/form-data; boundary=" . self::$boundary;
        }
        return self::https($url, 'POST', $body, $headers,$cookie);
    }

     /**
      * 获取文件数据
      * @param type $durl
      * @return type
      */
     static function file_get_contents($durl) {
         $ch = curl_init();
         curl_setopt($ch, CURLOPT_URL, $durl);
         curl_setopt($ch, CURLOPT_TIMEOUT, 5);
         //  curl_setopt($ch, CURLOPT_USERAGENT, _USERAGENT_);
         //  curl_setopt($ch, CURLOPT_REFERER, _REFERER_);
         curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
         $r = curl_exec($ch);
         curl_close($ch);
         return $r;
     }
    
    
        /**
     * 传递json值
     * @param $url
     * @param $json
     */
    public static function Json($url,$json){
        $jsonStr = $json;
        $headers = array(
            'Content-Type: application/json; charset=utf-8',
            'Content-Length: ' . strlen($jsonStr)
        );

        return self::https($url, 'json', $jsonStr, $headers);

    }

     static function join_cookie($cookie) {
         foreach( $cookie as $k=> $v){
             $d[] =$k."=".$v;
        }
        $data = implode(";",$d);
        return $data;
    }


    private static function https($url, $method, $postfields = NULL, $headers = array(),$cookie = [])
    {
        $ci = curl_init();
        /* Curl settings */
        curl_setopt($ci, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
        curl_setopt($ci, CURLOPT_USERAGENT, 'X-YZ-Client 2.0.0 - PHP');
        curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, 30);
        curl_setopt($ci, CURLOPT_TIMEOUT, 30);
        curl_setopt($ci, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($ci, CURLOPT_ENCODING, "");
        curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ci, CURLOPT_SSL_VERIFYHOST, 2);
        curl_setopt($ci, CURLOPT_HEADER, FALSE);

        switch ($method) {
            case 'POST':
                curl_setopt($ci, CURLOPT_POST, TRUE);
                if (!empty($postfields)) {
                    curl_setopt($ci, CURLOPT_POSTFIELDS, $postfields);
                }
                break;
                
           case 'json':
                curl_setopt($ci, CURLOPT_POST, TRUE);
                curl_setopt($ci, CURLOPT_POSTFIELDS, $postfields);
                break;     
        }

        if(count($cookie) > 0) {
            curl_setopt($ci, CURLOPT_COOKIE, self::join_cookie($cookie));
        }
        curl_setopt($ci, CURLOPT_URL, $url);
        curl_setopt($ci, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ci, CURLINFO_HEADER_OUT, TRUE);

        $response = curl_exec($ci);
        $httpCode = curl_getinfo($ci, CURLINFO_HTTP_CODE);
        $httpInfo = curl_getinfo($ci);
        curl_close($ci);
        return $response;
    }

    private static function build_http_query_multi($params, $files)
    {
        if (!$params) return '';

        $pairs = array();

        self::$boundary = $boundary = uniqid('------------------');
        $MPboundary = '--' . $boundary;
        $endMPboundary = $MPboundary . '--';
        $multipartbody = '';

        foreach ($params as $key => $value) {
            $multipartbody .= $MPboundary . "\r\n";
            $multipartbody .= 'content-disposition: form-data; name="' . $key . "\"\r\n\r\n";
            $multipartbody .= $value . "\r\n";
        }
        foreach ($files as $key => $value) {
            if (!$value) {
                continue;
            }
            
            if (is_array($value)) {
                $url = $value['url'];
                if (isset($value['name'])) {
                    $filename = $value['name'];
                } else {
                    $parts = explode('?', basename($value['url']));
                    $filename = $parts[0];
                }
                $field = isset($value['field']) ? $value['field'] : $key;
            } else {
                $url = $value;
                $parts = explode('?', basename($url));
                $filename = $parts[0];
                $field = $key;
            }
            
            $content = file_get_contents($url);
            
            $multipartbody .= $MPboundary . "\r\n";
            $multipartbody .= 'Content-Disposition: form-data; name="' . $field . '"; filename="' . $filename . '"' . "\r\n";
            $multipartbody .= "Content-Type: image/unknown\r\n\r\n";
            $multipartbody .= $content . "\r\n";
        }

        $multipartbody .= $endMPboundary;
        return $multipartbody;
    }
}