Beispiel #1
2
 function jws_fetchUrl($url)
 {
     //Can we use cURL?
     if (is_callable('curl_init')) {
         $ch = curl_init();
         curl_setopt($ch, CURLOPT_URL, $url);
         curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
         curl_setopt($ch, CURLOPT_TIMEOUT, 20);
         curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
         $feedData = curl_exec($ch);
         curl_close($ch);
         //If not then use file_get_contents
     } elseif (ini_get('allow_url_fopen') == 1 || ini_get('allow_url_fopen') === TRUE) {
         $feedData = @file_get_contents($url);
         //Or else use the WP HTTP API
     } else {
         if (!class_exists('WP_Http')) {
             include_once ABSPATH . WPINC . '/class-http.php';
         }
         $request = new WP_Http();
         $result = $request->request($url);
         $feedData = $result['body'];
     }
     /*    echo $feedData;
     		exit;*/
     return $feedData;
 }
function post_to_third_party($entry, $form)
{
    $post_url = 'http://thirdparty.com';
    $body = array('first_name' => rgar($entry, '1.3'), 'last_name' => rgar($entry, '1.6'), 'message' => rgar($entry, '3'));
    $request = new WP_Http();
    $response = $request->post($post_url, array('body' => $body));
}
 /**
  * @param string $url
  * @param array  $params
  * @param string $method
  * @param bool   $has_return_value
  *
  * @throws RuntimeException
  *
  * @return null|string
  */
 private function call_remote_api($url, $params, $method, $has_return_value = true)
 {
     $context = $this->filter_request_params($params, $method);
     $response = $this->http->request($url, $context);
     if ($has_return_value && (bool) $response === false || is_wp_error($response) || isset($response['response']['code']) && $response['response']['code'] > 400) {
         throw new RuntimeException("Cannot communicate with the remote service params: " . serialize($context) . ' response: ' . serialize($response));
     }
     return $response;
 }
 /**
  * Makes a http request to the url this points at and checks if the requests
  * returns the correct validation result.
  *
  * @return bool
  */
 public function is_valid()
 {
     $url_glue = false === strpos($this->url, '?') ? '?' : '&';
     $url = trailingslashit($this->url) . ($this->language_code ? '/' . $this->language_code . '/' : '') . $url_glue . '____icl_validate_domain=1';
     $response = $this->http->request($url, 'timeout=15');
     return !is_wp_error($response) && $response['response']['code'] == '200' && ($response['body'] === '<!--' . untrailingslashit($this->wp_api->get_home_url()) . '-->' || $response['body'] === '<!--' . untrailingslashit($this->wp_api->get_site_url()) . '-->');
 }
 function do_request($url, $oauth_header, $body_params = '')
 {
     $request = new WP_Http();
     $params = array();
     if ($body_params) {
         foreach ($body_params as $key => $value) {
             $body_params[$key] = $value;
         }
         $params['body'] = $body_params;
     }
     $params['method'] = 'POST';
     $params['headers'] = array('Authorization' => $oauth_header);
     $result = $request->request($url, $params);
     if (!is_wp_error($result)) {
         $this->response_code = $result['response']['code'];
         if ($result['response']['code'] == '200') {
             return $result['body'];
         } else {
             switch ($result['response']['code']) {
                 case 403:
                     $this->duplicate_tweet = true;
                     break;
             }
             $error_message_found = preg_match('#<error>(.*)</error>#i', $result['body'], $matches);
             if ($error_message_found) {
                 $this->error_message = $matches[1];
             }
         }
     }
     return false;
 }
 /**
  * Gets an instagram feed
  *
  * @param string $username Username
  * @param integer $limit Number of images to return
  * @return array
  */
 protected function getFeed($username = null, $limit = 5)
 {
     if (empty($username)) {
         return array();
     }
     $results = get_transient('InstagramWidget::getFeed');
     if ($results === false) {
         $request = new WP_Http();
         $response = $request->get("http://ink361.com/feed/user/{$username}");
         $results = array();
         if (!is_a($response, 'WP_Error')) {
             try {
                 $resultsXml = new SimpleXMLElement($response['body']);
                 foreach ($resultsXml->channel[0]->item as $node) {
                     // ink361 sends <a href="ink361.com"><img src="image.jpg"></a>
                     try {
                         $imageNode = new DOMDocument();
                         $imageNode->loadHTML($node->description);
                         $img = $imageNode->getElementsByTagName('img');
                         $results[] = $img->item(0)->getAttribute('src');
                         if (count($results) == $limit) {
                             break;
                         }
                     } catch (Exception $e) {
                     }
                 }
                 set_transient('InstagramWidget::getFeed', $results, HOUR_IN_SECONDS);
             } catch (Exception $e) {
             }
         }
     }
     return $results;
 }
Beispiel #7
0
function cff_fetchUrl($url)
{
    //Can we use cURL?
    if (is_callable('curl_init')) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT, 20);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_ENCODING, 'gzip,deflate,sdch');
        $feedData = curl_exec($ch);
        curl_close($ch);
        //If not then use file_get_contents
    } elseif (ini_get('allow_url_fopen') == 1 || ini_get('allow_url_fopen') === TRUE) {
        $feedData = @file_get_contents($url);
        //Or else use the WP HTTP API
    } else {
        $request = new WP_Http();
        $response = $request->request($urls, array('timeout' => 60, 'sslverify' => false));
        if (is_wp_error($response)) {
            //Don't display an error, just use the Server config Error Reference message
            echo '';
        } else {
            $feedData = wp_remote_retrieve_body($response);
        }
    }
    return $feedData;
}
 /**
  * Send an authenticated request to the Urban Airship API. The request is
  * authenticated with the key and secret.
  *
  * @param string  $method      REST method for request
  * @param mixed   $body        Body of request, optional
  * @param string  $uri         URI for this request
  * @param string  $contentType Content type for the request, optional
  * @param int     $version     version # for API, optional, default is 3
  * @param mixed   $request     Request object for this operation (PushRequest, etc)
  *   optional
  * @return \Httpful\associative|string
  * @throws AirshipException
  */
 public function request($method, $body, $uri, $contentType = null, $version = 3, $request = null)
 {
     // As a result of replacing Httpful/Request with WP HTTP,
     // We need to map WP_HTTP response object to Httpful/Request properties as a shim,
     // Action is not necessary but looks a bit cleaner
     add_action('http_api_debug', array($this, 'set_mock_response_object'), 10, 5);
     $headers = array('Authorization' => 'Basic ' . base64_encode("{$this->key}:{$this->secret}"), "Accept" => sprintf(self::VERSION_STRING, $version));
     if (!is_null($contentType)) {
         $headers["Content-type"] = $contentType;
     }
     $request = new \WP_Http();
     /**
      * Logger is disabled in production, so this won't do nothing unless WP_DEBUG is enabled
      *
      * @var [type]
      */
     $logger = UALog::getLogger();
     $logger->debug("Making request", array("method" => $method, "uri" => $uri, "headers" => $headers, "body" => $body));
     // Make a request (fires http_api_debug action that sets object property $mock_response)
     $response = $request->request($uri, array('method' => $method, 'body' => $body, 'headers' => $headers));
     // Check the response for wp_error (that's what WP HTTP throws when there was an issue with request)
     if (is_wp_error($response)) {
         return $response;
     }
     // Check for "successful" WP HTTP request and see if UA returns any non-2xx response code
     if (300 <= $response['response']['code']) {
         throw AirshipException::fromResponse($this->mock_response);
     }
     $logger->debug("Received response", array("status" => $this->mock_response->code, "headers" => $this->mock_response->raw_headers, "body" => $this->mock_response->raw_body));
     // Return mock response object for any components of UA library that make requests
     return $this->mock_response;
 }
function kpg_read_file($f, $method = 'GET')
{
    // try this using Wp_Http
    if (!class_exists('WP_Http')) {
        include_once ABSPATH . WPINC . '/class-http.php';
    }
    $request = new WP_Http();
    $parms = array();
    $parms['timeout'] = 10;
    // bump timeout a little we are timing out in google
    $parms['method'] = $method;
    $result = $request->request($f, $parms);
    // see if there is anything there
    if (empty($result)) {
        return '';
    }
    if (is_array($result)) {
        $ansa = $result['body'];
        return $ansa;
    }
    if (is_object($result)) {
        $ansa = 'ERR: ' . $result->get_error_message();
        return $ansa;
        // return $ansa when debugging
        //return '';
    }
    return '';
}
Beispiel #10
0
 /**
  * Method responsible for making Rest API calls @ Return $response from rest api.
  *
  * @return $response
  */
 public function rest_api_call()
 {
     try {
         if (!class_exists('WP_Http')) {
             include_once ABSPATH . WPINC . '/class-http.php';
         }
         $request = new WP_Http();
         $postfields = $this->getPostfields();
         $header = $this->getHeaders();
         $url = $this->getApiUrl();
         $options = array('headers' => $header, 'method' => $this->method, 'timeout' => ConfigSDK::TIMEOUT);
         if (!is_null($postfields)) {
             $options['body'] = $postfields;
         }
         //SSL PROBLEMS
         $options['sslverify'] = false;
         $result = $request->request($url, $options);
         if (!is_wp_error($result)) {
             $json = $result['body'];
             $response = json_decode($json, true);
             $response_status = $result['response']['code'];
             $this->setLastStatusCode($response_status);
         } else {
             $this->setLastStatusCode(0);
         }
         if ($this->authorization->is_preauthorized_request) {
             $this->authorization->setAccessParams($response);
         }
         return $response;
     } catch (Exception $e) {
         throw new Exception('Failed to send Data in rest_api_call: ' . $e);
     }
 }
function socialdiscuss_http_post($link, $body)
{
    if (!$link) {
        return array(500, 'Invalid Link');
    }
    require_once ABSPATH . WPINC . '/class-snoopy.php';
    $snoop = new Snoopy();
    if ($snoop->submit($link, $body)) {
        if (strpos($snoop->response_code, '200')) {
            $response = $snoop->results;
            return array(200, $response);
        }
    }
    if (!class_exists('WP_Http')) {
        include_once ABSPATH . WPINC . '/class-http.php';
    }
    if (!class_exists('WP_Http')) {
        return array(500, $snoop->response_code);
    }
    $request = new WP_Http();
    $response_full = $request->request($link, array('method' => 'POST', 'body' => $body, 'headers' => $headers));
    if (isset($response_full->errors)) {
        return array(500, 'Unknown Error');
    }
    $response_code = $response_full['response']['code'];
    if ($response_code === 200) {
        $response = $response_full['body'];
        return array($response_code, $response);
    }
    $response_msg = $response_full['response']['message'];
    return array($response_code, $response_msg);
}
/**
 * Gets content from GitHub Gist
 * 
 * @param int $id GitHub Gist ID
 * @param int $ttl How long to cache (in seconds)
 * @param string $bump Bump value to force cache expirey.
 * @param string $file Name of file
 */
function embed_github_gist($id, $ttl = null, $bump = null, $file = null)
{
    $gist = '';
    if (!class_exists('WP_Http')) {
        require_once ABSPATH . WPINC . '/class-http.php';
    }
    $key = embed_github_gist_build_cache_key($id, $bump);
    if (embed_github_gist_bypass_cache() or false === ($gist = get_transient($key))) {
        $http = new WP_Http();
        if (embed_github_gist_prefer_inline_html() and function_exists('json_decode')) {
            $result = $http->request('https://gist.github.com/' . $id . '.json');
            $json = json_decode($result['body']);
            $gist = $json->div;
        } else {
            if (!$file) {
                $file = 'file';
            }
            $result = $http->request('https://gist.github.com/raw/' . $id . '/' . $file);
            $gist = '<script src="https://gist.github.com/' . $id . '.js?file=' . $file . '%5B345%5D" type="text/javascript"></script>';
            $gist .= '<noscript><div class="embed-github-gist-source"><code><pre>';
            $gist .= htmlentities($result['body']);
            $gist .= '</pre></code></div></noscript>';
        }
        unset($result, $http);
        if (!embed_github_gist_bypass_cache()) {
            if (!$ttl) {
                $ttl = EMBED_GISTHUB_DEFAULT_TTL;
            }
            set_transient($key, $gist, $ttl);
        }
    }
    return $gist;
}
function genesis_purchase_themes_admin()
{
    ?>
	
<div class="wrap purchase-themes">
	<?php 
    screen_icon('themes');
    ?>
	<h2><?php 
    echo 'Genesis ';
    _e('- Purchase Themes', 'genesis');
    ?>
</h2>
	
	<?php 
    $store = get_transient('genesis-remote-store');
    if (!$store) {
        $request = new WP_Http();
        $store = $request->request('http://www.studiopress.com/store.php');
        set_transient('genesis-remote-store', $store, 60 * 60 * 12);
        // store for 12 hours
    }
    echo $store['body'];
    ?>
	
</div>
<?php 
}
 /**
  * @param string|array $address
  */
 public function provide_coordinates_for_address($address)
 {
     if (is_array($address)) {
         $address = implode(', ', array_filter(array_map('trim', $address)));
     }
     $address = trim($address);
     if ($location = $this->get_resolved($address)) {
         return $location;
     }
     $base_request_url = trailingslashit($this->get_google_api_base()) . $this->get_google_api_json_format();
     $url = esc_url(add_query_arg(array('address' => $address), $base_request_url));
     $response = $this->http->get($url);
     if (is_wp_error($response)) {
         return false;
     }
     $decoded = json_decode($response['body'], true);
     if (empty($decoded['status']) || 'OK' !== $decoded['status']) {
         return false;
     }
     if (empty($decoded['results'][0]['place_id']) || empty($decoded['results'][0]['geometry']['location']['lat']) || empty($decoded['results'][0]['geometry']['location']['lng'])) {
         return false;
     }
     $location = $decoded['results'][0]['geometry']['location'];
     $updated_transient = array_merge($this->get_transient(), array($address => $location));
     set_transient(self::$transient_name, $updated_transient);
     $this->transient = $updated_transient;
     return $location;
 }
Beispiel #15
0
function ml_send_notification($alert, $sound = true, $badge = NULL, $custom_properties = NULL, $tags = NULL, $remote_identifier = NULL)
{
    global $ml_api_key, $ml_secret_key;
    //push notification only when api key is set
    if (($ml_api_key == NULL || strlen($ml_api_key) < 5) && ($ml_secret_key == NULL || strlen($ml_secret_key) < 5)) {
        return false;
    }
    $notification = array('alert' => $alert);
    if ($sound) {
        $notification['sound'] = $sound;
    }
    if ($badge) {
        $notification['badge'] = $badge;
    }
    if ($custom_properties) {
        $notification['custom_properties'] = $custom_properties;
    }
    if ($tags) {
        $notification['tags'] = $tags;
    }
    $parameters = array('api_key' => $ml_api_key, 'secret_key' => $ml_secret_key, 'notification' => $notification);
    //postID
    if ($remote_identifier) {
        $parameters['remote_identifier'] = "{$remote_identifier}";
    }
    $request = new WP_Http();
    $result = $request->request(MOBILOUD_PUSH_API_PUBLISH_URL, array('method' => 'POST', 'timeout' => 10, 'body' => $parameters));
    return false;
}
Beispiel #16
0
 /**
  * Load IPN IP List
  * @since 1.1
  * @version 1.0
  */
 public function load_ipn_ips()
 {
     $request = new WP_Http();
     $data = $request->request('http://www.zombaio.com/ip_list.txt');
     $data = explode('|', $data['body']);
     return $data;
 }
Beispiel #17
0
function prli_get_main_message($message = '', $expiration = 1800)
{
    global $prli_update;
    // Set the default message
    if (empty($message)) {
        $message = __("Get started by <a href=\"?page=pretty-link&action=new\">" . "adding a URL</a> that you want to turn into a pretty link.<br/>" . "Come back to see how many times it was clicked.", 'pretty-link');
    }
    $messages = get_site_transient('_prli_messages');
    // if the messages array has expired go back to the mothership
    if (!$messages) {
        $remote_controller = $prli_update->pro_is_installed_and_authorized() ? 'prlipro' : 'prli';
        $message_mothership = "http://prettylinkpro.com/index.php?controller={$remote_controller}&action=json_messages";
        if (!class_exists('WP_Http')) {
            include_once ABSPATH . WPINC . '/class-http.php';
        }
        $http = new WP_Http();
        $response = $http->request($message_mothership);
        if (isset($response) and is_array($response) and isset($response['body']) and !empty($response['body'])) {
            $messages = json_decode($response['body']);
        } else {
            $messages = array($message);
        }
        set_site_transient("_prli_messages", $messages, $expiration);
    }
    if (empty($messages) or !$messages or !is_array($messages)) {
        return $message;
    } else {
        return $messages[array_rand($messages)];
    }
}
 /**
  * rpc_call function.
  * 
  * @access public
  * @param string $method. (default: '')
  * @param array $params. (default: array())
  * @return void
  */
 function rpc_call($method = '', $params = array())
 {
     $request = new WP_Http();
     if (function_exists('xmlrpc_encode_request')) {
         $params = xmlrpc_encode_request($method, $params);
     }
     return $request->request($this->getServiceUrl(), array('method' => 'POST', 'body' => $params));
 }
Beispiel #19
0
 /**
  * {@inheritdoc}
  */
 protected function _request($url, $args, Data $options)
 {
     $httpClient = new \WP_Http();
     $apiResponse = $httpClient->request($url, array('body' => $args, 'method' => $options->get('method'), 'headers' => $options->get('headers'), 'timeout' => $options->get('timeout'), 'user-agent' => $options->get('user_agent'), 'sslverify' => $options->get('ssl_verify'), 'redirection' => 20));
     if ($options->get('debug') && $apiResponse instanceof \WP_Error) {
         $apiResponse = array('body' => implode($apiResponse->get_error_messages()));
     }
     return $apiResponse;
 }
function wp2android_display_charts()
{
    global $ml_api_key, $ml_secret_key;
    $parameters = array('api_key' => $ml_api_key, 'secret_key' => $ml_secret_key);
    //SUBSCRIPTIONS
    $request = new WP_Http();
    $ml_host = "https://api.wp2android.wps.edu.vn";
    $url_subscriptions = "{$ml_host}/product/stats/devices/count";
    $result_subscriptions = $request->request($url_subscriptions, array('method' => 'POST', 'timeout' => 10, 'body' => $parameters));
    if ($result_subscriptions) {
        $json_subscriptions = $result_subscriptions['body'];
    }
    //MODELS
    $request = new WP_Http();
    $url_models = "{$ml_host}/product/stats/devices/models";
    $result_models = $request->request($url_models, array('method' => 'POST', 'timeout' => 10, 'body' => $parameters));
    if ($result_models) {
        $json_models = $result_models['body'];
    }
    //SESSIONS
    $request = new WP_Http();
    $url_sessions = "{$ml_host}/product/stats/events/sessions";
    $result_sessions = $request->request($url_sessions, array('method' => 'POST', 'timeout' => 10, 'body' => $parameters));
    if ($result_sessions) {
        $json_sessions = $result_sessions['body'];
    }
    ?>
	
	<script type="text/javascript" src="<?php 
    echo $ml_host;
    ?>
/assets/highcharts.js"></script> 
	<div id="wp2android_analytics_title" style="margin-top:20px;">
		<h1>wp2android Analytics</h1>
		<div style="clear:both;">
	</div>
	<table width="100%">
		<tr>
			<td align="center">
				<div id="wp2android_subscriptions_chart" style="width: 400px; height: 400px;margin-top:50px;margin-left:50px;"></div>
			</td>
			<td align="center">
				<div id="wp2android_sessions_chart" style="width: 400px; height: 400px;margin-top:50px;margin-left:50px;"></div>
			</td>
		</tr>
		<tr>
			<td align="center" colspan=2>
				<div id="wp2android_models_chart" style="width: 700px; height: 400px;margin-top:50px;"></div>
			</td>
		</tr>
	</table>
	



	<?php 
}
function post_to_third_party($entry, $form)
{
    //echo '<pre>';print_r($entry);echo '</pre>';
    $post_url = 'http://dmtrk.net/signup.ashx';
    $body = array('Email' => $entry['1'], 'addressbookid' => '2619899', 'userid' => '88348', 'cd_FIRSTNAME' => $entry['2.3'], 'cd_LASTNAME' => $entry['2.6'], 'cd_FULLNAME' => $entry['2.3'] . ' ' . $entry['2.6']);
    // echo '<pre>';print_r($body);echo '</pre>';
    $request = new WP_Http();
    $response = $request->post($post_url, array('body' => $body));
}
 public function request($url, $args = array())
 {
     $http = new WP_Http();
     if (isset($args['data'])) {
         $args['body'] = $args['data'];
         unset($args['data']);
     }
     return $http->request($url, $args);
 }
function perform_post_payment_duties($order_id)
{
    //create box folder
    $folderName = $order_id;
    $parentFolder = '1169288163';
    $urltopost = 'http://www.paratus.com.au/wp-content/themes/goodchoice/includes/paratus-box-api/boxapi/example.php';
    $body = array('action' => 'create_folder', 'folder_name' => $folderName, 'parent_folder' => $parentFolder);
    $request = new WP_Http();
    $response = $request->post($urltopost, array('body' => $body, 'blocking' => false));
}
 public function validate_domain_networking($posted_url, $code = false)
 {
     $string_valid = $this->validate_url_string($posted_url);
     if ($string_valid === true) {
         $url_glue = false === strpos($posted_url, '?') ? '?' : '&';
         $url = trailingslashit($posted_url) . ($code ? '/' . $code . '/' : '') . $url_glue . '____icl_validate_domain=1';
         $client = new WP_Http();
         $response = $client->request($url, 'timeout=15');
     }
     return isset($response) && !is_wp_error($response) && $response['response']['code'] == '200' && ($response['body'] === '<!--' . untrailingslashit(get_home_url()) . '-->' || $response['body'] === '<!--' . untrailingslashit(get_site_url()) . '-->') ? 1 : 0;
 }
 private function from_remote()
 {
     $data = array();
     $url = 'https://api.wpengine.com/1.2/?method=disk-usage&account_name=' . PWP_NAME . '&wpe_apikey=' . WPE_APIKEY . '&blog_id=all';
     $http = new WP_Http();
     $msg = $http->get($url);
     if (!is_a($msg, 'WP_Error') && isset($msg['body'])) {
         $data = json_decode($msg['body'], TRUE);
     }
     return $data;
 }
function ml_configuration_connection_test_callback()
{
    global $ml_server_host;
    $request = new WP_Http();
    $url = "{$ml_server_host}";
    $result = $request->request($url, array('method' => 'GET', 'timeout' => 10));
    if ($result) {
        print_r($result);
    } else {
        echo "Request returned NULL";
    }
    die;
}
Beispiel #27
0
 function googl_shortlink($url)
 {
     $http = new WP_Http();
     $headers = array('Content-Type' => 'application/json');
     $result = $http->request('https://www.googleapis.com/urlshortener/v1/url', array('method' => 'POST', 'body' => '{"longUrl": "' . $url . '"}', 'headers' => $headers));
     $result = json_decode($result['body']);
     $shortlink = $result->id;
     if ($shortlink) {
         add_post_meta($post_id, '_googl_shortlink', $shortlink, true);
         return $shortlink;
     } else {
         return $url;
     }
 }
Beispiel #28
0
 function import_wordpress_comments(&$wxr, $timestamp, $eof = true)
 {
     $http = new WP_Http();
     $response = $http->request(DISQUS_IMPORTER_URL . 'api/import-wordpress-comments/', array('method' => 'POST', 'timeout' => 60, 'body' => array('forum_url' => $this->short_name, 'forum_api_key' => $this->forum_api_key, 'response_type' => 'php', 'wxr' => $wxr, 'timestamp' => $timestamp, 'eof' => (int) $eof)));
     if ($response['response']['code'] !== 200) {
         // hack
         $this->api->last_error = $response->errors;
         return -1;
     }
     $data = unserialize($response['body']);
     if (!$data || $data['stat'] == 'fail') {
         return -1;
     }
     return $data;
 }
 /**
  * @param string $path
  * @param string $method
  * @param array $data
  * @param string $contentType
  *
  * @return array
  * @throws CommunicationError
  * @throws Exception\InvalidResponseError
  * @throws Exception\LaunchKeyEngineError
  * @throws Exception\NoPairedDevicesError
  * @throws Exception\NoSuchUserError
  * @throws Exception\RateLimitExceededError
  * @throws ExpiredAuthRequestError
  * @throws InvalidCredentialsError
  * @throws InvalidRequestError
  */
 private function sendRequest($path, $method, array $data = array(), array $parameters = array(), $contentType = 'application/x-www-form-urlencoded')
 {
     $headers = array('Accept' => 'application/json', 'Connection' => 'close');
     if (!empty($data)) {
         $headers['Content-Type'] = $contentType;
         if ($contentType === 'application/x-www-form-urlencoded') {
             $body = http_build_query($data);
         } elseif ($contentType === 'application/json') {
             $body = json_encode($data);
             $parameters['signature'] = $this->cryptService->sign($body);
         }
     } else {
         $body = null;
     }
     if (!empty($parameters)) {
         $path .= '?' . http_build_query($parameters);
     }
     $this->debugLog("Sending request", array('path' => $path, 'method' => $method, 'headers' => $headers, 'body' => $body));
     $response = $this->http->request($this->getUrl($path), array('method' => $method, 'timeout' => $this->requestTimeout, 'redirection' => 0, 'httpversion' => '1.1', 'sslverify' => $this->sslVerify, 'body' => $body, 'headers' => $headers));
     if ($response instanceof \WP_Error) {
         $msg = implode(' => ', $response->get_error_messages());
         throw new CommunicationError($msg);
     } else {
         $this->debugLog("Response received", array($response));
         $data = $this->jsonDecodeData($response['body']);
         if (!in_array($response['response']['code'], array(200, 201))) {
             $this->throwExceptionForErrorResponse($data);
         }
     }
     return $data;
 }
 function pre_http_request($pre, $args, $url)
 {
     $this->args = wp_parse_args($args, array('authentication' => NULL, 'username' => NULL, 'password' => NULL));
     // Ruh roh...
     if (!is_null($this->args['authentication'])) {
         switch ($this->args['authentication']) {
             case '-':
                 // No HTTP Auth method. Remove this stuff.
                 $this->args['authentication'] = NULL;
                 $this->args['username'] = NULL;
                 $this->args['password'] = NULL;
                 break;
             case 'basic':
                 if ($this->have_curl($args, $url)) {
                     // Don't need to do anything. http_api_curl hook takes care
                     // of it.
                     break;
                 } elseif ($this->have_streams($args, $url)) {
                     // curl has a nice native way to jam in the username and
                     // passwd but streams and fsockopen do not. So we have to
                     // make a recursive call with the credentials in the URL.
                     // Wee ha!
                     $method = $this->args['authentication'];
                     $credentials = $this->args['username'];
                     if (!is_null($this->args['password'])) {
                         $credentials .= ':' . $args['password'];
                     }
                     // Remove these so we don't recurse all the way down
                     unset($this->args['authentication']);
                     unset($this->args['username']);
                     unset($this->args['password']);
                     $url = preg_replace('!(https?://)!', '$1' . $credentials . '@', $url);
                     // Subsidiary request
                     $pre = wp_remote_request($url, $this->args);
                     break;
                 }
             case 'digest':
                 if ($this->have_curl($args, $url)) {
                     // Don't need to do anything. http_api_curl hook takes care
                     // of it.
                     break;
                 }
             default:
                 if (is_callable('WP_Http', '_get_first_available_transport')) {
                     $trans = WP_Http::_get_first_available_transport($args, $url);
                     if (!$trans) {
                         $trans = WP_Http::_get_first_available_transport(array(), $url);
                     }
                 } elseif (is_callable('WP_Http', '_getTransport')) {
                     $transports = WP_Http::_getTransport($args);
                     $trans = get_class(reset($transports));
                 } else {
                     $trans = 'HTTP';
                 }
                 $pre = new WP_Error('http_request_failed', sprintf(__('%s cannot use %s authentication with the %s transport.'), __CLASS__, $args['authentication'], $trans));
         }
     }
     return $pre;
 }