function __construct($url, $timeout = 10, $redirects = 5, $headers = null, $useragent = null, $force_fsockopen = false) { $this->url = $url; $this->timeout = $timeout; $this->redirects = $redirects; $this->headers = $headers; $this->useragent = $useragent; $this->method = SIMPLEPIE_FILE_SOURCE_REMOTE; if (preg_match('/^http(s)?:\\/\\//i', $url)) { $args = array('timeout' => $this->timeout, 'redirection' => $this->redirects); if (!empty($this->headers)) { $args['headers'] = $this->headers; } if (SIMPLEPIE_USERAGENT != $this->useragent) { //Use default WP user agent unless custom has been specified $args['user-agent'] = $this->useragent; } $res = wp_safe_remote_request($url, $args); if (is_wp_error($res)) { $this->error = 'WP HTTP Error: ' . $res->get_error_message(); $this->success = false; } else { $this->headers = wp_remote_retrieve_headers($res); $this->body = wp_remote_retrieve_body($res); $this->status_code = wp_remote_retrieve_response_code($res); } } else { $this->error = ''; $this->success = false; } }
public function __construct($sURL, $iTimeout = 10, $iRedirects = 5, $aHeaders = null, $sUserAgent = null, $bForceFsockOpen = false) { $this->timeout = $iTimeout; $this->redirects = $iRedirects; $this->headers = $sUserAgent; $this->useragent = $sUserAgent; $this->url = $sURL; // If the scheme is not http or https. if (!preg_match('/^http(s)?:\\/\\//i', $sURL)) { $this->error = ''; $this->success = false; return; } // Arguments $aArgs = array('timeout' => $this->timeout, 'redirection' => $this->redirects, true, 'sslverify' => false); if (!empty($this->headers)) { $aArgs['headers'] = $this->headers; } if (SIMPLEPIE_USERAGENT != $this->useragent) { $aArgs['user-agent'] = $this->useragent; } // Request $res = function_exists('wp_safe_remote_request') ? wp_safe_remote_request($sURL, $aArgs) : wp_remote_get($sURL, $aArgs); if (is_wp_error($res)) { $this->error = 'WP HTTP Error: ' . $res->get_error_message(); $this->success = false; return; } $this->headers = wp_remote_retrieve_headers($res); $this->body = wp_remote_retrieve_body($res); $this->status_code = wp_remote_retrieve_response_code($res); }
/** * Internal callback, after OAuth */ public function oauth2callback() { if (empty($_GET['code'])) { $error = array('provider' => self::PROVIDER_NAME, 'code' => 'oauth2callback_error', 'message' => 'No authorization code received', 'raw' => $_GET); $this->errorCallback($error); return; } $code = $_GET['code']; $url = self::TOKEN_ENDPOINT; $args = array('method' => 'POST', 'headers' => array('Authorization' => 'Basic ' . base64_encode($this->strategy['client_id'] . ':' . $this->strategy['client_secret'])), 'body' => array('code' => $code, 'redirect_uri' => $this->strategy['redirect_uri'], 'grant_type' => 'authorization_code')); $response = wp_safe_remote_request($url, $args); if (is_wp_error($response)) { $error = array('provider' => self::PROVIDER_NAME, 'code' => 'remote_request_error', 'raw' => $response->get_error_message()); $this->errorCallback($error); return; } $responseHeaders = wp_remote_retrieve_body($response); $results = json_decode($response['body']); if (!empty($results) && !empty($results->access_token) && !empty($results->xoauth_yahoo_guid)) { $user_info = $this->userinfo($results->access_token, $results->xoauth_yahoo_guid); $email = $this->user_email($user_info); if (!$email) { $error = array('provider' => self::PROVIDER_NAME, 'code' => 'no_email_error', 'message' => 'No email in the user profile', 'raw' => array('response' => $response, 'headers' => $responseHeaders)); $this->errorCallback($error); return; } $this->auth = array('uid' => $user_info->profile->guid, 'info' => array('nickname' => $user_info->profile->nickname, 'first_name' => $user_info->profile->givenName, 'last_name' => $user_info->profile->familyName, 'location' => $user_info->profile->location, 'image' => $user_info->profile->image->imageUrl, 'profileUrl' => $user_info->profile->profileUrl, 'email' => $email), 'credentials' => array('token' => $results->access_token, 'expires' => date('c', time() + $results->expires_in)), 'raw' => $user_info); $this->callback(); } else { $error = array('provider' => self::PROVIDER_NAME, 'code' => 'access_token_error', 'message' => 'Failed when attempting to obtain access token', 'raw' => array('response' => $response, 'headers' => $responseHeaders)); $this->errorCallback($error); } }
protected function request($url, $fields = '', $args = array()) { $defaults = array('follow' => true, 'method' => 'GET', 'ssl_verify' => false, 'body' => '', 'httpversion' => '1.1', 'timeout' => 60); $args = array_merge($defaults, $args); $args['body'] = $fields; $response = wp_safe_remote_request($url, $args); if (is_wp_error($response)) { throw new PHP_Merchant_Exception(PHPME_HTTP_REQUEST_FAILED, $response->get_error_message()); } return $response['body']; }
function yp_remote_request($url) { if (empty($url)) { return false; } $args = array('headers' => array('Accept-Encoding' => ''), 'timeout' => 30, 'user-agent' => 'Yellow Pencil Updater'); $request = wp_safe_remote_request($url, $args); if ($request['response']['code'] == 200) { return $request['body']; } return false; }
/** * GET URL * * @param string $url * @param string $username * @param string $password * @param bool $head * @return array */ public function get_page($url, $username = '', $password = '', $head = false) { // Increase the timeout add_filter('http_request_timeout', array($this, 'bump_request_timeout')); $headers = array(); $args = array(); if (true === $head) { $args['method'] = 'HEAD'; } if (!empty($username) && !empty($password)) { $headers['Authorization'] = 'Basic ' . base64_encode("{$username}:{$password}"); } $args['headers'] = $headers; return wp_safe_remote_request($url, $args); }
/** * Performs HTTP Request * * @since 1.0 * @see wp_safe_remote_request() * @param string $method HTTP method to use for request * @throws Exception for Blank/invalid endpoint or HTTP method, WP HTTP API error */ private function http_request($method) { // Check for blank endpoint or method if (!$this->endpoint || !$method) { throw new Exception(__('Endpoint and / or HTTP Method is blank.', WC_Twilio_SMS::TEXT_DOMAIN)); } // Check that method is a valid http method if (!in_array($method, array('GET', 'POST', 'PUT', 'DELETE'))) { throw new Exception(__('Requested HTTP Method is invalid.', WC_Twilio_SMS::TEXT_DOMAIN)); } // set the method $this->wp_remote_http_args['method'] = $method; // perform HTTP request with endpoint / args $this->response = wp_safe_remote_request(esc_url_raw($this->endpoint), $this->wp_remote_http_args); // WP HTTP API error like network timeout, etc if (is_wp_error($this->response)) { throw new Exception($this->response->get_error_message()); } // Check for proper response / body if (!isset($this->response['response'])) { throw new Exception(__('Empty Response', WC_Twilio_SMS::TEXT_DOMAIN)); } if (!isset($this->response['body'])) { throw new Exception(__('Empty Body', WC_Twilio_SMS::TEXT_DOMAIN)); } }
/** * Helper function to query the marketplace API via wp_remote_request. * * @param string The url to access. * @return object The results of the wp_remote_request request. * * @access private * @since 1.0 */ protected function remote_request($url) { if (empty($url)) { return false; } $args = array('headers' => array('Accept-Encoding' => '', 'Authorization' => sprintf('Bearer %s', $this->personal_token)), 'timeout' => 30, 'user-agent' => 'Toolkit/1.7.3'); $request = wp_safe_remote_request($url, $args); if (is_wp_error($request)) { echo $request->get_error_message(); return false; } $data = json_decode($request['body']); if ($request['response']['code'] == 200) { return $data; } else { $this->set_error('http_code', $request['response']['code']); } if (isset($data->error)) { $this->set_error('api_error', $data->error); } return false; }
/** * Simple server-side HTTP request with file_get_contents * Provides basic HTTP calls. * See serverGet() and serverPost() for wrapper functions of httpRequest() * * Notes: * Reluctant to use any more advanced transport like cURL for the time being to not * having to set cURL as being a requirement. * Strategy is to provide own HTTP transport handler if requiring more advanced support. * * @param string $url Full URL to load * @param array $options Stream context options (http://php.net/stream-context-create) * @param string $responseHeaders Response headers after HTTP call. Useful for error debugging. * @return string Content resulted from request, without headers */ public static function httpRequest($url, $options = null, &$responseHeaders = null) { $wp_http_args = array('method' => !empty($options['http']['method']) ? $options['http']['method'] : 'GET', 'timeout' => MINUTE_IN_SECONDS, 'redirection' => 0, 'httpversion' => '1.0', 'sslverify' => true, 'blocking' => true, 'body' => !empty($options['http']['content']) ? $options['http']['content'] : '', 'headers' => !empty($options['http']['header']) ? $options['http']['header'] : array(), 'cookies' => array()); // perform request $response = wp_safe_remote_request($url, $wp_http_args); // immediately get response headers $responseHeaders = wp_remote_retrieve_body($response); if (is_wp_error($response)) { // network timeout, etc $content = $response->get_error_message(); } else { $content = wp_remote_retrieve_body($response); } return $content; }
/** * Sends a DELETE request for the given article and bundles. * * @param string $url * @return mixed * @since 0.2.0 */ public function delete($url) { // Build the delete request args $args = array('headers' => array('Authorization' => $this->sign($url, 'DELETE')), 'method' => 'DELETE'); // Allow filtering and merge with the default args $args = apply_filters('apple_news_delete_args', wp_parse_args($args, $this->default_args)); // Perform the delete $response = wp_safe_remote_request(esc_url_raw($url), $args); // NULL is a valid response for DELETE if (is_null($response)) { return null; } // Parse and return the response return $this->parse_response($response); }
public static function request($url, $params = null, $args = array()) { if (!empty($params)) { $url = add_query_arg($params, $url); } $defaults = array('method' => 'GET'); $args = wp_parse_args($args, $defaults); if (strpos($url, 'http') !== 0) { $url = Sputnik::API_BASE . $url; } $args['timeout'] = 25; $args['headers']['user-agent'] = 'WP eCommerce Marketplace: ' . WPSC_VERSION; $args['headers']['X-WP-Domain'] = self::domain(); $request = wp_safe_remote_request(esc_url_raw($url), $args); if (is_wp_error($request)) { throw new Exception($request->get_error_message()); } if ($request['response']['code'] != 200) { throw new Exception($request['body'], $request['response']['code']); } $result = json_decode($request['body']); if ($result === null) { throw new Exception($request['body'], $request['response']['code']); } $request['body'] = $result; return $request; }
protected function http($url, $method, $postfields = NULL) { $args = array('method' => $method, 'user-agent' => 'WP eCommerce Marketplace: ' . WPSC_VERSION); switch ($method) { case 'POST': if (!empty($postfields)) { $args['body'] = $postfields; } break; } $args['headers'] = array('X-WP-Domain' => Sputnik_API::domain()); $response = wp_safe_remote_request($url, $args); if (is_wp_error($response)) { throw new Exception($response->get_error_message()); } if ($response['response']['code'] != 200) { throw new Exception($response['body']); } return $response['body']; }
private function request($url, $method, $parameters) { $request = OAuthRequest::from_consumer_and_token($this->consumer, $this->token, $method, $url, $parameters); $request->sign_request($this->sha1_method, $this->consumer, $this->token); $args = array('sslverify' => false, 'method' => $method, 'timeout' => 15); switch ($method) { case 'GET': $url = $request->to_url(); $response = wp_safe_remote_get($url, $args); break; default: $url = $request->get_normalized_http_url(); $args = wp_parse_args(array('body' => $request->to_postdata()), $args); $response = wp_safe_remote_request($url, $args); break; } $this->response_code = wp_remote_retrieve_response_code($response); $this->response_headers = wp_remote_retrieve_headers($response); /* Check if we have a valid response */ if (200 == $this->response_code) { if ($response_body = wp_remote_retrieve_body($response)) { /* Decode the response body */ $result = json_decode(trim($response_body), true); /* Check if we failed to decode the response, or the response contains errors */ if (is_null($result) || isset($result['errors'])) { $this->response_errors = isset($result['errors']) ? $result['errors'] : null; return false; } return $result; } } return false; }
/** * Make an HTTP request * * @internal Adapted for WP_Http * @return API results */ function http($url, $method, $postfields = NULL) { $this->http_info = null; // this is never used $options = array('method' => $method, 'timeout' => $this->timeout, 'user-agent' => $this->useragent, 'sslverify' => $this->ssl_verifypeer); switch ($method) { case 'POST': if (!empty($postfields)) { $options['body'] = $postfields; } break; case 'DELETE': if (!empty($postfields)) { $url = "{$url}?{$postfields}"; } } $response = wp_safe_remote_request($url, $options); if (is_wp_error($response)) { $this->http_code = null; $this->http_header = array(); return false; } $this->http_code = $response['response']['code']; $this->http_header = $response['headers']; return $response['body']; }
/** * Simple wrapper for wp_remote_request() so child classes can override this * and provide their own transport mechanism if needed, e.g. a custom * cURL implementation * * @since 2.2.0 * @param string $request_uri * @param string $request_args * @return array|WP_Error */ protected function do_remote_request($request_uri, $request_args) { return wp_safe_remote_request($request_uri, $request_args); }
/** * Helper function to query the marketplace API via wp_remote_request. * * @param string The url to access. * @return object The results of the wp_remote_request request. * * @access private * @since 1.0 */ protected function remote_request($url) { if (empty($url)) { return false; } $args = array('headers' => array('Accept-Encoding' => ''), 'timeout' => 30, 'user-agent' => 'Toolkit/1.7.3'); $options = get_option(EWPT_PLUGIN_SLUG); if (isset($options['deactivate_sslverify'])) { $args['sslverify'] = false; } $request = wp_safe_remote_request($url, $args); if (is_wp_error($request)) { echo $request->get_error_message(); return false; } $data = json_decode($request['body']); if ($request['response']['code'] == 200) { return $data; } else { $this->set_error('http_code', $request['response']['code']); } if (isset($data->error)) { $this->set_error('api_error', $data->error); } return false; }
/** * Retrieve URL headers and content using WP HTTP Request API. * * @since 1.5.0 * @package External * @subpackage MagpieRSS * * @param string $url URL to retrieve * @param array $headers Optional. Headers to send to the URL. * @return Snoopy style response */ function _fetch_remote_file($url, $headers = "") { $resp = wp_safe_remote_request($url, array('headers' => $headers, 'timeout' => MAGPIE_FETCH_TIME_OUT)); if (is_wp_error($resp)) { $error = array_shift($resp->errors); $resp = new stdClass(); $resp->status = 500; $resp->response_code = 500; $resp->error = $error[0] . "\n"; //\n = Snoopy compatibility return $resp; } // Snoopy returns headers unprocessed. // Also note, WP_HTTP lowercases all keys, Snoopy did not. $return_headers = array(); foreach (wp_remote_retrieve_headers($resp) as $key => $value) { if (!is_array($value)) { $return_headers[] = "{$key}: {$value}"; } else { foreach ($value as $v) { $return_headers[] = "{$key}: {$v}"; } } } $response = new stdClass(); $response->status = wp_remote_retrieve_response_code($resp); $response->response_code = wp_remote_retrieve_response_code($resp); $response->headers = $return_headers; $response->results = wp_remote_retrieve_body($resp); return $response; }
/** * Prüfung auf DNSBL Spam * * @since 2.4.5 * @change 2.4.5 * * @param string $ip IP-Adresse * @return boolean TRUE bei gemeldeter IP */ private static function _is_dnsbl_spam($ip) { /* Start request */ $response = wp_safe_remote_request(esc_url_raw(sprintf('http://www.stopforumspam.com/api?ip=%s&f=json', $ip), 'http')); /* Response error? */ if (is_wp_error($response)) { return false; } /* Get JSON */ $json = wp_remote_retrieve_body($response); /* Decode JSON */ $result = json_decode($json); /* Empty data */ if (empty($result->success)) { return false; } /* Return status */ return (bool) $result->ip->appears; }
/** * Deliver the webhook payload using wp_safe_remote_request() * * @since 2.2 * @param mixed $arg first hook argument */ public function deliver($arg) { $payload = $this->build_payload($arg); // setup request args $http_args = array('method' => 'POST', 'timeout' => MINUTE_IN_SECONDS, 'redirection' => 0, 'httpversion' => '1.0', 'blocking' => true, 'user-agent' => sprintf('WooCommerce/%s Hookshot (WordPress/%s)', WC_VERSION, $GLOBALS['wp_version']), 'body' => trim(json_encode($payload)), 'headers' => array('Content-Type' => 'application/json'), 'cookies' => array()); $http_args = apply_filters('woocommerce_webhook_http_args', $http_args, $arg, $this->id); // add custom headers $http_args['headers']['X-WC-Webhook-Topic'] = $this->get_topic(); $http_args['headers']['X-WC-Webhook-Resource'] = $this->get_resource(); $http_args['headers']['X-WC-Webhook-Event'] = $this->get_event(); $http_args['headers']['X-WC-Webhook-Signature'] = $this->generate_signature($http_args['body']); $http_args['headers']['X-WC-Webhook-ID'] = $this->id; $http_args['headers']['X-WC-Webhook-Delivery-ID'] = $delivery_id = $this->get_new_delivery_id(); $start_time = microtime(true); // webhook away! $response = wp_safe_remote_request($this->get_delivery_url(), $http_args); $duration = round(microtime(true) - $start_time, 5); $this->log_delivery($delivery_id, $http_args, $response, $duration); do_action('woocommerce_webhook_delivery', $http_args, $response, $duration, $arg, $this->id); }
/** * Search for records * * @param array $query * * @return mixed Response body on success, or FALSE on failure */ private function search($query = array()) { if (!$this->is_connected()) { return false; } $defaults = array('sort' => array(array('created' => array('order' => 'asc')))); $last = get_option('wp_stream_last_migrated'); if ($last) { $defaults['filter'] = array('and' => array(array('range' => array('created' => array('gt' => $last))))); } $body['sites'] = array($this->site_uuid); $body['query'] = array_merge($defaults, (array) $query); $args = array('headers' => array('Stream-Site-API-Key' => $this->api_key, 'Content-Type' => 'application/json'), 'method' => 'POST', 'body' => wp_stream_json_encode($body), 'sslverify' => true); $response = wp_safe_remote_request('https://api.wp-stream.com/search', $args); if (is_wp_error($response)) { return false; } return json_decode(wp_remote_retrieve_body($response)); }
/** * Perform a HTTP HEAD or GET request. * * If $file_path is a writable filename, this will do a GET request and write * the file to that path. * * @since 2.5.0 * * @param string $url URL to fetch. * @param string|bool $file_path Optional. File path to write request to. Default false. * @param int $red Optional. The number of Redirects followed, Upon 5 being hit, * returns false. Default 1. * @return bool|string False on failure and string of headers if HEAD request. */ function wp_get_http($url, $file_path = false, $red = 1) { @set_time_limit(60); if ($red > 5) { return false; } $options = array(); $options['redirection'] = 5; if (false == $file_path) { $options['method'] = 'HEAD'; } else { $options['method'] = 'GET'; } $response = wp_safe_remote_request($url, $options); if (is_wp_error($response)) { return false; } $headers = wp_remote_retrieve_headers($response); $headers['response'] = wp_remote_retrieve_response_code($response); // WP_HTTP no longer follows redirects for HEAD requests. if ('HEAD' == $options['method'] && in_array($headers['response'], array(301, 302)) && isset($headers['location'])) { return wp_get_http($headers['location'], $file_path, ++$red); } if (false == $file_path) { return $headers; } // GET request - write it to the supplied filename $out_fp = fopen($file_path, 'w'); if (!$out_fp) { return $headers; } fwrite($out_fp, wp_remote_retrieve_body($response)); fclose($out_fp); clearstatcache(); return $headers; }
function parser_s_cb($attr) { extract(shortcode_atts(array('url' => 'https://m.avito.ru/tyumen/kommercheskaya_nedvizhimost', 'user_agent' => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:20.0) Gecko/20100101 Firefox/20.0'), $atts)); $args = array('method' => 'GET', 'timeout' => 5, 'redirection' => 5, 'httpversion' => '1.0', 'user-agent' => $user_agent, 'blocking' => true, 'headers' => array(), 'cookies' => array(), 'body' => null, 'compress' => false, 'decompress' => true, 'sslverify' => false, 'stream' => false, 'filename' => null); // Указываем прокси, если сайт блокирует доступ define('WP_PROXY_HOST', '188.127.237.141'); define('WP_PROXY_PORT', '1890'); $result = wp_safe_remote_request($url, $args); ob_start(); ?> <div> Запрос данных по адресу: <pre><?php echo $url; ?> </pre> <h1>Ответ</h1> <pre><?php var_dump($result['response']); ?> </pre> <h1>Заголовок</h1> <pre><?php var_dump(wp_remote_retrieve_headers($result)); ?> </pre> <h1>Результат</h1> <ul> <?php //Подключаем парсер DOM дерева http://simplehtmldom.sourceforge.net/manual.htm include_once 'inc/simplehtmldom/simple_html_dom.php'; $body = new simple_html_dom(); $body->load($result['body']); //Получаем список элементов для обработку в список $list = $body->find('.b-content-main .b-item'); ?> <?php foreach ($list as $element) { ?> <li> <?php //получаем ИД атрибут элемента //$id = $element->id; //echo $id; ?> <br/> <?php //Находим внутри элемента заголовок с ссылкой и выдергиваем текст ссылки $title = $element->find('.header-text', 0); echo $title->plaintext; ?> <br/> <?php //Находим внутри элемента ссылку $title = $element->find('h1.entry-title a', 0); echo $title->href; ?> <hr> </li> <?php } ?> </ul> </div> <?php $html = ob_get_contents(); ob_get_clean(); return $html; }