public function request($request_type = 'post', $url = '', $data = array(), $headers = array())
 {
     $options = $this->_options;
     $res = ['status' => -1, 'res' => []];
     try {
         switch ($request_type) {
             case 'post':
                 $response = Requests::post($url, $headers, $data, $options);
                 break;
             case 'get':
                 $response = Requests::request($url, $headers, $data, Requests::GET, $options);
                 break;
             default:
                 $response = Requests::post($url, $headers, $data, $options);
                 break;
         }
         if ($response->status_code == 200) {
             $res = ['status' => 0, 'msg' => 'success', 'res' => trim($response->body)];
         } else {
             $res = ['status' => -1, 'msg' => 'fail', 'res' => trim($response->body)];
         }
     } catch (Exception $e) {
         $res = ['status' => -1, 'msg' => $e->getMessage(), 'res' => ''];
     }
     return $res;
 }
 /**
  * Process Netki API request and response
  *
  * @param string $partnerId
  * @param string $apiKey
  * @param string $apiURL
  * @param string $method
  * @param array $data
  * @return array|mixed
  * @throws \Exception
  */
 public function process_request($partnerId, $apiKey, $apiURL, $method, $data)
 {
     $supportedMethods = array('GET', 'PUT', 'POST', 'DELETE');
     $successCodes = array(200, 201, 202, 204);
     if (!in_array($method, $supportedMethods)) {
         throw new \Exception('Unsupported method: ' . $method);
     }
     $headers = array('content-type' => 'application/json', 'X-Partner-ID' => $partnerId, 'Authorization' => $apiKey);
     $postData = !empty($data) ? json_encode($data) : null;
     $response = \Requests::request($apiURL, $headers, $postData, $method);
     if ($method == 'DELETE' && $response->status_code == 204) {
         return array();
     }
     $responseData = json_decode($response->body);
     if (empty($responseData)) {
         throw new \Exception('Error parsing JSON Data');
     }
     if (!$responseData->success || !in_array($response->status_code, $successCodes)) {
         $errorMessage = $responseData->message;
         if (isset($responseData->failures)) {
             $errorMessage .= ' [FAILURES: ';
             $failures = array();
             foreach ($responseData->failures as $failure) {
                 array_push($failures, $failure->message);
             }
             $errorMessage .= join(', ', $failures) . ']';
         }
         throw new \Exception('Request Failed: ' . $errorMessage);
     }
     return $responseData;
 }
Exemple #3
0
 public function testGETWithDataAndQuery()
 {
     $data = array('test2' => 'test');
     $request = Requests::request('http://httpbin.org/get?test=true', array(), $data, Requests::GET, $this->getOptions());
     $this->assertEquals(200, $request->status_code);
     $result = json_decode($request->body, true);
     $this->assertEquals('http://httpbin.org/get?test=true&test2=test', $result['url']);
     $this->assertEquals(array('test' => 'true', 'test2' => 'test'), $result['args']);
 }
 public function request($method, $url, $data = null)
 {
     $url = Api::$baseUrl . $url;
     if ($data === null) {
         $data = array();
     }
     $options = array('auth' => array(Api::$key, Api::$secret));
     $response = \Requests::request($url, self::$headers, $data, $method, $options);
     $this->checkErrors($response);
     return json_decode($response->body, true);
 }
Exemple #5
0
 /**
  * @inheritdoc
  */
 public function request($url, $args, $method, Options $options)
 {
     $headers = $options->get('headers', array());
     $method = Filter::up($method);
     $args = 'GET' !== $method ? $args : array();
     $httpResult = \Requests::request($url, $headers, $args, $method, $this->_getClientOptions($options));
     if ($options->isExceptions() && $httpResult->status_code >= 400) {
         throw new Exception($httpResult->body, $httpResult->status_code);
     }
     return array($httpResult->status_code, $httpResult->headers->getAll(), $httpResult->body);
 }
Exemple #6
0
 /**
  * @inheritDoc
  */
 public function load(IApiRequest $request)
 {
     $req = $request->getRequestDetail();
     try {
         $response = \Requests::request($req->getUrl(), $this->_buildHeaders($req), $this->_buildData($req), $req->getMethod(), $req->getOptions());
         $result = $this->_getResult($response);
         $request->setRawResult($result);
         return $request;
     } catch (\Exception $e) {
         $this->_handleException($e);
     }
 }
 /**
  * Send a request
  *
  * @param string $url
  * @param string $method
  * @param array $data
  * @param array $headers
  * @param array $options
  */
 public function send($url, $method = self::GET, $data = array(), $headers = array(), $options = array())
 {
     if (isset($this->_auth)) {
         $options['auth'] = $this->_auth;
     }
     try {
         $response = \Requests::request($url, $headers, $data, $method, $options);
         return new Response($response);
     } catch (Exception $e) {
         throw new Exception($e->getMessage(), $e->getCode());
     }
 }
 /**
  * @expectedException Requests_Exception
  */
 public function testInvalidProtocol()
 {
     $request = Requests::request('ftp://128.0.0.1/');
 }
Exemple #9
0
 /**
  * Main interface for HTTP requests
  *
  * This method initiates a request and sends it via a transport before
  * parsing.
  *
  * @see Requests::request()
  *
  * @throws Requests_Exception On invalid URLs (`nonhttp`)
  *
  * @param string $url URL to request
  * @param array $headers Extra headers to send with the request
  * @param array|null $data Data to send either as a query string for GET/HEAD requests, or in the body for POST requests
  * @param string $type HTTP request type (use Requests constants)
  * @param array $options Options for the request (see {@see Requests::request})
  * @return Requests_Response
  */
 public function request($url, $headers = array(), $data = array(), $type = Requests::GET, $options = array())
 {
     $request = $this->merge_request(compact('url', 'headers', 'data', 'options'));
     return Requests::request($request['url'], $request['headers'], $request['data'], $type, $request['options']);
 }
 /**
  * Send an HTTP request to a URI.
  *
  * Please note: The only URI that are supported in the HTTP Transport implementation
  * are the HTTP and HTTPS protocols.
  *
  * @access public
  * @since 2.7.0
  *
  * @param string       $url  The request URL.
  * @param string|array $args {
  *     Optional. Array or string of HTTP request arguments.
  *
  *     @type string       $method              Request method. Accepts 'GET', 'POST', 'HEAD', or 'PUT'.
  *                                             Some transports technically allow others, but should not be
  *                                             assumed. Default 'GET'.
  *     @type int          $timeout             How long the connection should stay open in seconds. Default 5.
  *     @type int          $redirection         Number of allowed redirects. Not supported by all transports
  *                                             Default 5.
  *     @type string       $httpversion         Version of the HTTP protocol to use. Accepts '1.0' and '1.1'.
  *                                             Default '1.0'.
  *     @type string       $user-agent          User-agent value sent.
  *                                             Default WordPress/' . get_bloginfo( 'version' ) . '; ' . get_bloginfo( 'url' ).
  *     @type bool         $reject_unsafe_urls  Whether to pass URLs through wp_http_validate_url().
  *                                             Default false.
  *     @type bool         $blocking            Whether the calling code requires the result of the request.
  *                                             If set to false, the request will be sent to the remote server,
  *                                             and processing returned to the calling code immediately, the caller
  *                                             will know if the request succeeded or failed, but will not receive
  *                                             any response from the remote server. Default true.
  *     @type string|array $headers             Array or string of headers to send with the request.
  *                                             Default empty array.
  *     @type array        $cookies             List of cookies to send with the request. Default empty array.
  *     @type string|array $body                Body to send with the request. Default null.
  *     @type bool         $compress            Whether to compress the $body when sending the request.
  *                                             Default false.
  *     @type bool         $decompress          Whether to decompress a compressed response. If set to false and
  *                                             compressed content is returned in the response anyway, it will
  *                                             need to be separately decompressed. Default true.
  *     @type bool         $sslverify           Whether to verify SSL for the request. Default true.
  *     @type string       sslcertificates      Absolute path to an SSL certificate .crt file.
  *                                             Default ABSPATH . WPINC . '/certificates/ca-bundle.crt'.
  *     @type bool         $stream              Whether to stream to a file. If set to true and no filename was
  *                                             given, it will be droped it in the WP temp dir and its name will
  *                                             be set using the basename of the URL. Default false.
  *     @type string       $filename            Filename of the file to write to when streaming. $stream must be
  *                                             set to true. Default null.
  *     @type int          $limit_response_size Size in bytes to limit the response to. Default null.
  *
  * }
  * @return array|WP_Error Array containing 'headers', 'body', 'response', 'cookies', 'filename'.
  *                        A WP_Error instance upon error.
  */
 public function request($url, $args = array())
 {
     $defaults = array('method' => 'GET', 'timeout' => apply_filters('http_request_timeout', 5), 'redirection' => apply_filters('http_request_redirection_count', 5), 'httpversion' => apply_filters('http_request_version', '1.0'), 'user-agent' => apply_filters('http_headers_useragent', 'WordPress/' . get_bloginfo('version') . '; ' . get_bloginfo('url')), 'reject_unsafe_urls' => apply_filters('http_request_reject_unsafe_urls', false), 'blocking' => true, 'headers' => array(), 'cookies' => array(), 'body' => null, 'compress' => false, 'decompress' => true, 'sslverify' => true, 'sslcertificates' => ABSPATH . WPINC . '/certificates/ca-bundle.crt', 'stream' => false, 'filename' => null, 'limit_response_size' => null);
     // Pre-parse for the HEAD checks.
     $args = wp_parse_args($args);
     // By default, Head requests do not cause redirections.
     if (isset($args['method']) && 'HEAD' == $args['method']) {
         $defaults['redirection'] = 0;
     }
     $r = wp_parse_args($args, $defaults);
     /**
      * Filters the arguments used in an HTTP request.
      *
      * @since 2.7.0
      *
      * @param array  $r   An array of HTTP request arguments.
      * @param string $url The request URL.
      */
     $r = apply_filters('http_request_args', $r, $url);
     // The transports decrement this, store a copy of the original value for loop purposes.
     if (!isset($r['_redirection'])) {
         $r['_redirection'] = $r['redirection'];
     }
     /**
      * Filters whether to preempt an HTTP request's return value.
      *
      * Returning a non-false value from the filter will short-circuit the HTTP request and return
      * early with that value. A filter should return either:
      *
      *  - An array containing 'headers', 'body', 'response', 'cookies', and 'filename' elements
      *  - A WP_Error instance
      *  - boolean false (to avoid short-circuiting the response)
      *
      * Returning any other value may result in unexpected behaviour.
      *
      * @since 2.9.0
      *
      * @param false|array|WP_Error $preempt Whether to preempt an HTTP request's return value. Default false.
      * @param array               $r        HTTP request arguments.
      * @param string              $url      The request URL.
      */
     $pre = apply_filters('pre_http_request', false, $r, $url);
     if (false !== $pre) {
         return $pre;
     }
     if (function_exists('wp_kses_bad_protocol')) {
         if ($r['reject_unsafe_urls']) {
             $url = wp_http_validate_url($url);
         }
         if ($url) {
             $url = wp_kses_bad_protocol($url, array('http', 'https', 'ssl'));
         }
     }
     $arrURL = @parse_url($url);
     if (empty($url) || empty($arrURL['scheme'])) {
         return new WP_Error('http_request_failed', __('A valid URL was not provided.'));
     }
     if ($this->block_request($url)) {
         return new WP_Error('http_request_failed', __('User has blocked requests through HTTP.'));
     }
     // If we are streaming to a file but no filename was given drop it in the WP temp dir
     // and pick its name using the basename of the $url
     if ($r['stream']) {
         if (empty($r['filename'])) {
             $r['filename'] = get_temp_dir() . basename($url);
         }
         // Force some settings if we are streaming to a file and check for existence and perms of destination directory
         $r['blocking'] = true;
         if (!wp_is_writable(dirname($r['filename']))) {
             return new WP_Error('http_request_failed', __('Destination directory for file streaming does not exist or is not writable.'));
         }
     }
     if (is_null($r['headers'])) {
         $r['headers'] = array();
     }
     // WP allows passing in headers as a string, weirdly.
     if (!is_array($r['headers'])) {
         $processedHeaders = WP_Http::processHeaders($r['headers']);
         $r['headers'] = $processedHeaders['headers'];
     }
     // Setup arguments
     $headers = $r['headers'];
     $data = $r['body'];
     $type = $r['method'];
     $options = array('timeout' => $r['timeout'], 'useragent' => $r['user-agent'], 'blocking' => $r['blocking'], 'hooks' => new WP_HTTP_Requests_Hooks($url, $r));
     // Ensure redirects follow browser behaviour.
     $options['hooks']->register('requests.before_redirect', array(get_class(), 'browser_redirect_compatibility'));
     if ($r['stream']) {
         $options['filename'] = $r['filename'];
     }
     if (empty($r['redirection'])) {
         $options['follow_redirects'] = false;
     } else {
         $options['redirects'] = $r['redirection'];
     }
     // Use byte limit, if we can
     if (isset($r['limit_response_size'])) {
         $options['max_bytes'] = $r['limit_response_size'];
     }
     // If we've got cookies, use and convert them to Requests_Cookie.
     if (!empty($r['cookies'])) {
         $options['cookies'] = WP_Http::normalize_cookies($r['cookies']);
     }
     // SSL certificate handling
     if (!$r['sslverify']) {
         $options['verify'] = false;
         $options['verifyname'] = false;
     } else {
         $options['verify'] = $r['sslcertificates'];
     }
     // All non-GET/HEAD requests should put the arguments in the form body.
     if ('HEAD' !== $type && 'GET' !== $type) {
         $options['data_format'] = 'body';
     }
     /**
      * Filters whether SSL should be verified for non-local requests.
      *
      * @since 2.8.0
      *
      * @param bool $ssl_verify Whether to verify the SSL connection. Default true.
      */
     $options['verify'] = apply_filters('https_ssl_verify', $options['verify']);
     // Check for proxies.
     $proxy = new WP_HTTP_Proxy();
     if ($proxy->is_enabled() && $proxy->send_through_proxy($url)) {
         $options['proxy'] = new Requests_Proxy_HTTP($proxy->host() . ':' . $proxy->port());
         if ($proxy->use_authentication()) {
             $options['proxy']->use_authentication = true;
             $options['proxy']->user = $proxy->username();
             $options['proxy']->pass = $proxy->password();
         }
     }
     // Avoid issues where mbstring.func_overload is enabled
     mbstring_binary_safe_encoding();
     try {
         $requests_response = Requests::request($url, $headers, $data, $type, $options);
         // Convert the response into an array
         $http_response = new WP_HTTP_Requests_Response($requests_response, $r['filename']);
         $response = $http_response->to_array();
         // Add the original object to the array.
         $response['http_response'] = $http_response;
     } catch (Requests_Exception $e) {
         $response = new WP_Error('http_request_failed', $e->getMessage());
     }
     reset_mbstring_encoding();
     /**
      * Fires after an HTTP API response is received and before the response is returned.
      *
      * @since 2.8.0
      *
      * @param array|WP_Error $response HTTP response or WP_Error object.
      * @param string         $context  Context under which the hook is fired.
      * @param string         $class    HTTP transport used.
      * @param array          $args     HTTP request arguments.
      * @param string         $url      The request URL.
      */
     do_action('http_api_debug', $response, 'response', 'Requests', $r, $url);
     if (is_wp_error($response)) {
         return $response;
     }
     if (!$r['blocking']) {
         return array('headers' => array(), 'body' => '', 'response' => array('code' => false, 'message' => false), 'cookies' => array(), 'http_response' => null);
     }
     /**
      * Filters the HTTP API response immediately before the response is returned.
      *
      * @since 2.9.0
      *
      * @param array  $response HTTP response.
      * @param array  $r        HTTP request arguments.
      * @param string $url      The request URL.
      */
     return apply_filters('http_response', $response, $r, $url);
 }
Exemple #11
0
 /**
  * Return remote file's content via HTTP
  *
  * @param string $url The address of the target file
  * @param string $body HTTP request body
  * @param int $timeout Connection timeout
  * @param string $method GET/POST
  * @param string $content_type Content type header of HTTP request
  * @param string[] $headers Headers key value array.
  * @param string[] $cookies Cookies key value array.
  * @param string $post_data Request arguments array for POST method
  * @return string If success, the content of the target file. Otherwise: none
  */
 public static function getRemoteResource($url, $body = null, $timeout = 3, $method = 'GET', $content_type = null, $headers = array(), $cookies = array(), $post_data = array(), $request_config = array())
 {
     try {
         $host = parse_url($url, PHP_URL_HOST);
         $request_headers = array();
         $request_cookies = array();
         $request_options = array('timeout' => $timeout);
         foreach ($headers as $key => $val) {
             $request_headers[$key] = $val;
         }
         if (isset($cookies[$host]) && is_array($cookies[$host])) {
             foreach ($cookies[$host] as $key => $val) {
                 $request_cookies[] = rawurlencode($key) . '=' . rawurlencode($val);
             }
         }
         if (count($request_cookies)) {
             $request_headers['Cookie'] = implode('; ', $request_cookies);
         }
         foreach ($request_config as $key => $val) {
             $request_options[$key] = $val;
         }
         if ($content_type) {
             $request_headers['Content-Type'] = $content_type;
         }
         if (defined('__PROXY_SERVER__')) {
             $proxy = parse_url(__PROXY_SERVER__);
             if ($proxy["host"]) {
                 $request_options['proxy'] = array($proxy['host'] . ($proxy['port'] ? ':' . $proxy['port'] : ''));
                 if ($proxy['user'] && $proxy['pass']) {
                     $request_options['proxy'][] = $proxy['user'];
                     $request_options['proxy'][] = $proxy['pass'];
                 }
             }
         }
         $url = str_replace('&', '&', $url);
         $start_time = microtime(true);
         $response = Requests::request($url, $request_headers, $body ?: $post_data, $method, $request_options);
         $elapsed_time = microtime(true) - $start_time;
         $GLOBALS['__remote_request_elapsed__'] += $elapsed_time;
         $log = array();
         $log['url'] = $url;
         $log['status'] = $response ? $response->status_code : 0;
         $log['elapsed_time'] = $elapsed_time;
         if (config('debug.enabled') && in_array('slow_remote_requests', config('debug.display_content'))) {
             $bt = debug_backtrace(\DEBUG_BACKTRACE_IGNORE_ARGS);
             foreach ($bt as $no => $call) {
                 if (strncasecmp($call['function'], 'getRemote', 9) === 0) {
                     $call_no = $no + 1;
                     $log['called_file'] = $bt[$call_no]['file'];
                     $log['called_line'] = $bt[$call_no]['line'];
                     $call_no++;
                     $log['called_method'] = $bt[$call_no]['class'] . $bt[$call_no]['type'] . $bt[$call_no]['function'];
                     $log['backtrace'] = array_slice($bt, $call_no, 1);
                     break;
                 }
             }
         } else {
             $log['called_file'] = $log['called_line'] = $log['called_method'] = null;
             $log['backtrace'] = array();
         }
         Rhymix\Framework\Debug::addRemoteRequest($log);
         if (count($response->cookies)) {
             foreach ($response->cookies as $cookie) {
                 $cookies[$host][$cookie->name] = $cookie->value;
             }
         }
         if ($response->success) {
             if (isset($request_config['filename'])) {
                 return true;
             } else {
                 return $response->body;
             }
         } else {
             return NULL;
         }
     } catch (Exception $e) {
         return NULL;
     }
 }
Exemple #12
0
/**
 * Perform a HTTP request, return response object
 *
 * @since 1.7
 * @param string $type HTTP request type (GET, POST)
 * @param string $url URL to request
 * @param array $headers Extra headers to send with the request
 * @param array $data Data to send either as a query string for GET requests, or in the body for POST requests
 * @param array $options Options for the request (see /includes/Requests/Requests.php:request())
 * @return object Requests_Response object
 */
function yourls_http_request($type, $url, $headers, $data, $options)
{
    yourls_http_load_library();
    $options = array_merge(yourls_http_default_options(), $options);
    if (yourls_http_proxy_is_defined() && !yourls_send_through_proxy($url)) {
        unset($options['proxy']);
    }
    try {
        $result = Requests::request($url, $headers, $data, $type, $options);
    } catch (Requests_Exception $e) {
        $result = yourls_debug_log($e->getMessage() . ' (' . $type . ' on ' . $url . ')');
    }
    return $result;
}
Exemple #13
0
 public function testLOCKWithData()
 {
     $data = array('test' => 'true', 'test2' => 'test');
     $request = Requests::request(httpbin('/lock'), array(), $data, 'LOCK', $this->getOptions());
     $this->assertEquals(200, $request->status_code);
     $result = json_decode($request->body, true);
     $this->assertEquals(array('test' => 'true', 'test2' => 'test'), $result['form']);
 }
Exemple #14
0
/**
 * Perform a HTTP request, return response object
 *
 * @since 1.7
 * @param string $type HTTP request type (GET, POST)
 * @param string $url URL to request
 * @param array $headers Extra headers to send with the request
 * @param array $data Data to send either as a query string for GET requests, or in the body for POST requests
 * @param array $options Options for the request (see /includes/Requests/Requests.php:request())
 * @return object Requests_Response object
 */
function yourls_http_request($type, $url, $headers, $data, $options)
{
    // Allow plugins to short-circuit the whole function
    $pre = yourls_apply_filter('shunt_yourls_http_request', null, $type, $url, $headers, $data, $options);
    if (null !== $pre) {
        return $pre;
    }
    yourls_http_load_library();
    $options = array_merge(yourls_http_default_options(), $options);
    if (yourls_http_get_proxy() && !yourls_send_through_proxy($url)) {
        unset($options['proxy']);
    }
    try {
        $result = Requests::request($url, $headers, $data, $type, $options);
    } catch (Requests_Exception $e) {
        $result = yourls_debug_log($e->getMessage() . ' (' . $type . ' on ' . $url . ')');
    }
    return $result;
}
Exemple #15
0
/**
 * Make a HTTP request to a remote URL
 *
 * @param string $method
 * @param string $url
 * @param array $headers
 * @param array $options
 * @return object
 */
function http_request($method, $url, $data = null, $headers = array(), $options = array())
{
    $pem_copied = false;
    // cURL can't read Phar archives
    if (0 === strpos(WP_CLI_ROOT, 'phar://')) {
        $options['verify'] = sys_get_temp_dir() . '/wp-cli-cacert.pem';
        copy(WP_CLI_ROOT . '/vendor/rmccue/requests/library/Requests/Transport/cacert.pem', $options['verify']);
        $pem_copied = true;
    }
    try {
        $request = \Requests::request($url, $headers, $data, $method, $options);
        if ($pem_copied) {
            unlink($options['verify']);
        }
        return $request;
    } catch (\Requests_Exception $ex) {
        // Handle SSL certificate issues gracefully
        \WP_CLI::warning($ex->getMessage());
        if ($pem_copied) {
            unlink($options['verify']);
        }
        $options['verify'] = false;
        try {
            return \Requests::request($url, $headers, $data, $method, $options);
        } catch (\Requests_Exception $ex) {
            \WP_CLI::error($ex->getMessage());
        }
    }
}
Exemple #16
0
 public function testDELETEWithData()
 {
     $data = array('test' => 'true', 'test2' => 'test');
     $request = Requests::request(httpbin('/delete'), array(), $data, Requests::DELETE, $this->getOptions());
     $this->assertEquals(200, $request->status_code);
     $result = json_decode($request->body, true);
     $this->assertEquals(httpbin('/delete?test=true&test2=test'), $result['url']);
     $this->assertEquals(array('test' => 'true', 'test2' => 'test'), $result['args']);
 }
Exemple #17
0
 /**
  * Return remote file's content via HTTP
  *
  * @param string $url The address of the target file
  * @param string $body HTTP request body
  * @param int $timeout Connection timeout
  * @param string $method GET/POST
  * @param string $content_type Content type header of HTTP request
  * @param string[] $headers Headers key value array.
  * @param string[] $cookies Cookies key value array.
  * @param string $post_data Request arguments array for POST method
  * @return string If success, the content of the target file. Otherwise: none
  */
 public static function getRemoteResource($url, $body = null, $timeout = 3, $method = 'GET', $content_type = null, $headers = array(), $cookies = array(), $post_data = array(), $request_config = array())
 {
     try {
         $request_headers = array();
         $request_cookies = array();
         $request_options = array('timeout' => $timeout);
         foreach ($headers as $key => $val) {
             $request_headers[$key] = $val;
         }
         if (isset($cookies[$host]) && is_array($cookies[$host])) {
             foreach ($cookies[$host] as $key => $val) {
                 $request_cookies[] = rawurlencode($key) . '=' . rawurlencode($val);
             }
         }
         if (count($request_cookies)) {
             $request_headers['Cookie'] = implode('; ', $request_cookies);
         }
         foreach ($request_config as $key => $val) {
             $request_options[$key] = $val;
         }
         if ($content_type) {
             $request_headers['Content-Type'] = $content_type;
         }
         $proxy = parse_url(__PROXY_SERVER__);
         if ($proxy["host"]) {
             $request_options['proxy'] = array($proxy['host'] . ($proxy['port'] ? ':' . $proxy['port'] : ''));
             if ($proxy['user'] && $proxy['pass']) {
                 $request_options['proxy'][] = $proxy['user'];
                 $request_options['proxy'][] = $proxy['pass'];
             }
         }
         $response = Requests::request($url, $request_headers, $body ?: $post_data, $method, $request_options);
         if (count($response->cookies)) {
             foreach ($response->cookies as $cookie) {
                 $cookies[$host][$cookie->name] = $cookie->value;
             }
         }
         if ($response->success) {
             return $response->body;
         } else {
             return NULL;
         }
     } catch (Exception $e) {
         return NULL;
     }
 }
Exemple #18
0
/**
 * Make a HTTP request to a remote URL.
 *
 * Wraps the Requests HTTP library to ensure every request includes a cert.
 *
 * ```
 * # `wp core download` verifies the hash for a downloaded WordPress archive
 *
 * $md5_response = Utils\http_request( 'GET', $download_url . '.md5' );
 * if ( 20 != substr( $md5_response->status_code, 0, 2 ) ) {
 *      WP_CLI::error( "Couldn't access md5 hash for release (HTTP code {$response->status_code})" );
 * }
 * ```
 *
 * @access public
 *
 * @param string $method    HTTP method (GET, POST, DELETE, etc.)
 * @param string $url       URL to make the HTTP request to.
 * @param array $headers    Add specific headers to the request.
 * @param array $options
 * @return object
 */
function http_request($method, $url, $data = null, $headers = array(), $options = array())
{
    $cert_path = '/rmccue/requests/library/Requests/Transport/cacert.pem';
    if (inside_phar()) {
        // cURL can't read Phar archives
        $options['verify'] = extract_from_phar(WP_CLI_ROOT . '/vendor' . $cert_path);
    } else {
        foreach (get_vendor_paths() as $vendor_path) {
            if (file_exists($vendor_path . $cert_path)) {
                $options['verify'] = $vendor_path . $cert_path;
                break;
            }
        }
        if (empty($options['verify'])) {
            WP_CLI::error_log("Cannot find SSL certificate.");
        }
    }
    try {
        $request = \Requests::request($url, $headers, $data, $method, $options);
        return $request;
    } catch (\Requests_Exception $ex) {
        // Handle SSL certificate issues gracefully
        \WP_CLI::warning($ex->getMessage());
        $options['verify'] = false;
        try {
            return \Requests::request($url, $headers, $data, $method, $options);
        } catch (\Requests_Exception $ex) {
            \WP_CLI::error($ex->getMessage());
        }
    }
}
Exemple #19
0
 /**
  * Send a HTTP request
  */
 public function request($endpoint, $headers = array(), $data = array(), $type = Requests::GET, $options = array())
 {
     $url = $this->base . $endpoint;
     $options = array_merge($this->getDefaultOptions(), $options);
     return Requests::request($url, $headers, $data, $type, $options);
 }