本文整理汇总了PHP中wp_remote_retrieve_header函数的典型用法代码示例。如果您正苦于以下问题:PHP wp_remote_retrieve_header函数的具体用法?PHP wp_remote_retrieve_header怎么用?PHP wp_remote_retrieve_header使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了wp_remote_retrieve_header函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: call
/**
* Execute an API call
*
* @access public
* @since 1.0.0
* @param int $customer_id The customer ID
* @param array $body The body of the API call
* @param string $method The type of call to make
* @param string $endpoint The endpoint to call
* @return mixed int $response If API call succeeded, false otherwise
*/
public function call($customer_id = 0, $body = array(), $method = 'PUT', $endpoint = false)
{
// Bail if no ID or body passed
if (!$customer_id || empty($body)) {
return false;
}
$args = array('headers' => array('Authorization' => 'Basic ' . base64_encode($this->site_id . ':' . $this->api_key)), 'method' => $method, 'body' => $body);
$url = $this->api_url . $customer_id;
if ($endpoint) {
$url .= '/' . $endpoint;
}
try {
$response = wp_remote_request($url, $args);
} catch (Exception $e) {
edd_record_gateway_error(__('EDD Customer.io Connect Error', 'edd-customerio-connect'), print_r($e->getMessage(), true));
return false;
}
$status = wp_remote_retrieve_header($response, 'status');
if ($status != '200 OK') {
$body = json_decode(wp_remote_retrieve_body($response));
edd_record_gateway_error(__('EDD Customer.io Connect Error', 'edd-customerio-connect'), $status . ': ' . $body->meta->error);
return false;
}
return $response;
}
示例2: download
public static function download($sURL, $iTimeOut = 300)
{
if (false === filter_var($sURL, FILTER_VALIDATE_URL)) {
return false;
}
$_sTmpFileName = self::setTempPath(self::getBaseNameOfURL($sURL));
if (!$_sTmpFileName) {
return false;
}
$_aoResponse = wp_safe_remote_get($sURL, array('timeout' => $iTimeOut, 'stream' => true, 'filename' => $_sTmpFileName));
if (is_wp_error($_aoResponse)) {
unlink($_sTmpFileName);
return false;
}
if (200 != wp_remote_retrieve_response_code($_aoResponse)) {
unlink($_sTmpFileName);
return false;
}
$_sContent_md5 = wp_remote_retrieve_header($_aoResponse, 'content-md5');
if ($_sContent_md5) {
$_boIsMD5 = verify_file_md5($_sTmpFileName, $_sContent_md5);
if (is_wp_error($_boIsMD5)) {
unlink($_sTmpFileName);
return false;
}
}
return $_sTmpFileName;
}
示例3: edd_lp_get_last_modified
/**
* Fetch the last modified date for the language pack url
*
* @param string $package_url Translate pack zip URL
*
* @return string Last modified date in `Y-m-d H:i:s` format
*
* @since 0.1.0
*/
function edd_lp_get_last_modified($package_url)
{
$response = wp_remote_get($package_url);
$last_modified = wp_remote_retrieve_header($response, 'last-modified');
if (!$last_modified) {
error_log($package_url . ': ' . print_r($response['response'], true));
return false;
}
return date('Y-m-d H:i:s', strtotime($last_modified));
}
示例4: wl_save_image
/**
* Save the image with the specified URL locally. To the local filename a uniqe serial is appended to ensure its uniqueness.
*
* @param string $url The image remote URL.
*
* @return array An array with information about the saved image (*path*: the local path to the image, *url*: the local
* url, *content_type*: the image content type)
*/
function wl_save_image($url)
{
$parts = parse_url($url);
$path = $parts['path'];
// Get the bare filename (filename w/o the extension).
// Sanitize filename before saving the current image as attachment
// See https://codex.wordpress.org/Function_Reference/sanitize_file_name
$basename = sanitize_file_name(pathinfo($path, PATHINFO_FILENAME) . '-' . uniqid(date('YmdH-')));
// Chunk the bare name to get a subpath.
$chunks = chunk_split(strtolower($basename), 3, DIRECTORY_SEPARATOR);
// Get the base dir.
$wp_upload_dir = wp_upload_dir();
$base_dir = $wp_upload_dir['basedir'];
$base_url = $wp_upload_dir['baseurl'];
// Get the full path to the local filename.
$image_path = '/' . $chunks;
$image_full_path = $base_dir . $image_path;
$image_full_url = $base_url . $image_path;
// Create the folders.
if (!(file_exists($image_full_path) && is_dir($image_full_path))) {
if (false === mkdir($image_full_path, 0777, true)) {
wl_write_log("wl_save_image : failed creating dir [ image full path :: {$image_full_path} ]\n");
}
}
// Request the remote file.
$response = wp_remote_get($url);
$content_type = wp_remote_retrieve_header($response, 'content-type');
switch ($content_type) {
case 'image/jpeg':
case 'image/jpg':
$extension = ".jpg";
break;
case 'image/svg+xml':
$extension = ".svg";
break;
case 'image/gif':
$extension = ".gif";
break;
case 'image/png':
$extension = ".png";
break;
default:
$extension = '';
}
// Complete the local filename.
$image_full_path .= $basename . $extension;
$image_full_url .= $basename . $extension;
// Store the data locally.
file_put_contents($image_full_path, wp_remote_retrieve_body($response));
// wl_write_log( "wl_save_image [ url :: $url ][ content type :: $content_type ][ image full path :: $image_full_path ][ image full url :: $image_full_url ]\n" );
// Return the path.
return array('path' => $image_full_path, 'url' => $image_full_url, 'content_type' => $content_type);
}
示例5: call
/**
* Generic GitHub API interface and response handler
*
* @param string $method HTTP method.
* @param string $endpoint API endpoint.
* @param array $body Request body.
*
* @return stdClass|WP_Error
*/
protected function call($method, $endpoint, $body = array())
{
if (is_wp_error($error = $this->can_call())) {
return $error;
}
$args = array('method' => $method, 'headers' => array('Authorization' => 'token ' . $this->oauth_token()), 'body' => function_exists('wp_json_encode') ? wp_json_encode($body) : json_encode($body));
$response = wp_remote_request($endpoint, $args);
$status = wp_remote_retrieve_header($response, 'status');
$body = json_decode(wp_remote_retrieve_body($response));
if ('2' !== substr($status, 0, 1) && '3' !== substr($status, 0, 1)) {
return new WP_Error(strtolower(str_replace(' ', '_', $status)), sprintf(__('Method %s to endpoint %s failed with error: %s', 'wordpress-github-sync'), $method, $endpoint, $body && $body->message ? $body->message : 'Unknown error'));
}
return $body;
}
示例6: upload
public function upload()
{
foreach ($this->imgoldurl as $v) {
$pkwall = array('user-agent' => 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:17.0) Gecko/20100101 Firefox/17.0');
if (!preg_match('/^([^\'"]+)(\\.[a-z]{3,4})$\\b/i', $v)) {
$v .= '.png';
}
$get = wp_remote_get($v, $pkwall);
$type = wp_remote_retrieve_header($get, 'content-type');
$mirror = wp_upload_bits(rawurldecode(basename($v)), '', wp_remote_retrieve_body($get));
$attachment = array('post_title' => basename($v), 'post_mime_type' => $type);
$attach_id = wp_insert_attachment($attachment, $mirror['file'], $this->pid);
$attach_data = wp_generate_attachment_metadata($attach_id, $v);
wp_update_attachment_metadata($attach_id, $attach_data);
set_post_thumbnail($this - pid, $attach_id);
$this->imgnewurl[] = $mirror[url];
}
}
示例7: get_endpoint_uri
/**
* Gets the Pingback endpoint URI provided by a web page specified by URL
*
* @return string|boolean Returns the Pingback endpoint URI if found or false
*/
function get_endpoint_uri($url)
{
// First check for an X-pingback header
if (!($response = wp_remote_head($url))) {
return false;
}
if (!($content_type = wp_remote_retrieve_header($response, 'content-type'))) {
return false;
}
if (preg_match('#(image|audio|video|model)/#is', $content_type)) {
return false;
}
if ($x_pingback = wp_remote_retrieve_header($response, 'x-pingback')) {
return trim($x_pingback);
}
// Fall back to extracting it from the HTML link
if (!($response = wp_remote_get($url))) {
return false;
}
if (200 !== wp_remote_retrieve_response_code($response)) {
return false;
}
if ('' === ($response_body = wp_remote_retrieve_body($response))) {
return false;
}
if (!preg_match_all('@<link([^>]+)>@im', $response_body, $response_links)) {
return false;
}
foreach ($response_links[1] as $response_link_attributes) {
$_link = array('rel' => false, 'href' => false);
$response_link_attributes = preg_split('@\\s+@im', $response_link_attributes, -1, PREG_SPLIT_NO_EMPTY);
foreach ($response_link_attributes as $response_link_attribute) {
if ($_link['rel'] == 'pingback' && $_link['href']) {
return $_link['href'];
}
if (strpos($response_link_attribute, '=', 1) !== false) {
list($_key, $_value) = explode('=', $response_link_attribute, 2);
$_link[strtolower($_key)] = trim($_value, "'\"");
}
}
}
// Fail
return false;
}
示例8: sideload_attachment
private function sideload_attachment($attachment, $_to_post_id, $date)
{
if ('image' === $attachment->type) {
$response = wp_remote_head($attachment->url);
if (200 == wp_remote_retrieve_response_code($response)) {
$_mimes = array_flip(wp_get_mime_types());
$_content_type = wp_remote_retrieve_header($response, 'content-type');
if (isset($_mimes[$_content_type])) {
$_ext = strtok($_mimes[$_content_type], '|');
$_temp_file = download_url($attachment->url);
// TODO check for WP_Error
$_new_file = str_replace('.tmp', '.' . $_ext, $_temp_file);
rename($_temp_file, $_new_file);
$file_array = array();
$file_array['name'] = basename($_new_file);
$file_array['tmp_name'] = $_new_file;
$attachment_id = media_handle_sideload($file_array, $_to_post_id, '', array('post_date' => $date, 'post_date_gmt' => $date));
}
}
}
}
示例9: get_potd
function get_potd()
{
$api_key = get_option('apod_api_key');
$default_status = get_option('apod_default_status');
$post_as = get_option('apod_post_as');
$response = wp_remote_get('https://api.data.gov/nasa/planetary/apod?api_key=' . $api_key . '&format=JSON');
$body = json_decode($response['body']);
if (is_null($post_as) or $post_as == "") {
$user_id = get_user_by('login', $post_as);
} else {
$user_id = '1';
}
if (!is_numeric($user_id)) {
$user_id = '1';
}
$pGUID = 'apod-' . $body->date;
if (getIDfromGUID($pGUID) > 0) {
return;
}
$post_data = array('post_content' => $body->explanation, 'post_title' => $body->title, 'post_name' => create_slug($body->title), 'post_excerpt' => $body->explanation, 'post_status' => $default_status, 'post_author' => $user_id, 'guid' => $pGUID);
$post_id = wp_insert_post($post_data);
//insert the post, return the new post_id
$imgGet = wp_remote_get($body->url);
//grab our image
$imgType = wp_remote_retrieve_header($imgGet, 'content-type');
//get our image type
$imgMirror = wp_upload_bits(rawurldecode(basename($body->url)), '', wp_remote_retrieve_body($imgGet));
//upload image to wordpress
$attachment = array('post_title' => preg_replace('/\\.[^.]+$/', '', basename($body->url)), 'post_mime_type' => $imgType, 'post_content' => '', 'post_status' => 'inherit', 'guid' => basename($body->url), 'post_author' => $user_id, 'post_type' => 'attachment');
require_once ABSPATH . 'wp-admin/includes/image.php';
$attach_id = wp_insert_attachment($attachment, $imgMirror['url'], $post_id);
//insert the attachment and get the ID
$attach_data = wp_generate_attachment_metadata($attach_id, $imgMirror['file']);
//generate the meta-data for the image
wp_update_attachment_metadata($attach_id, $attach_data);
//update the images meta-data
set_post_thumbnail($post_id, $attach_id);
//set the image as featured for the new post
}
示例10: validate
public function validate()
{
$response = wp_remote_head($this->url);
// Might just be unavailable right now, so ignore.
// It would be great to track this over time and create conflicts.
if (is_wp_error($response)) {
return;
}
$remote_etag = wp_remote_retrieve_header($response, 'etag');
$remote_last_modified = wp_remote_retrieve_header($response, 'last-modified');
if ($this->etag || $remote_etag) {
if ($this->etag != $remote_etag) {
$this->has_changed = true;
}
}
if ($this->last_modified || $remote_last_modified) {
if ($this->last_modified != $remote_last_modified) {
$this->has_changed = true;
}
}
// @fixme: what to do if both etag and last_modified are missing?
// right now those cases never count as "changed"
}
示例11: sideload
public function sideload()
{
//setup temp dir
$temp_file = wp_tempnam($this->_upload_from);
if (!$temp_file) {
EE_Error::add_error(__('Something went wrong with the upload. Unable to create a tmp file for the uploaded file on the server', 'event_espresso'), __FILE__, __FUNCTION__, __LINE__);
return false;
}
do_action('AHEE__EEH_Sideloader__sideload__before', $this, $temp_file);
$wp_remote_args = apply_filters('FHEE__EEH_Sideloader__sideload__wp_remote_args', array('timeout' => 500, 'stream' => true, 'filename' => $temp_file), $this, $temp_file);
$response = wp_safe_remote_get($this->_upload_from, $wp_remote_args);
if (is_wp_error($response) || 200 != wp_remote_retrieve_response_code($response)) {
unlink($temp_file);
if (defined('WP_DEBUG') && WP_DEBUG) {
EE_Error::add_error(sprintf(__('Unable to upload the file. Either the path given to upload from is incorrect, or something else happened. Here is the response returned:<br />%s<br />Here is the path given: %s', 'event_espresso'), var_export($response, true), $this->_upload_from), __FILE__, __FUNCTION__, __LINE__);
}
return false;
}
//possible md5 check
$content_md5 = wp_remote_retrieve_header($response, 'content-md5');
if ($content_md5) {
$md5_check = verify_file_md5($temp_file, $content_md5);
if (is_wp_error($md5_check)) {
unlink($temp_file);
EE_Error::add_error($md5_check->get_error_message(), __FILE__, __FUNCTION__, __LINE__);
return false;
}
}
$file = $temp_file;
//now we have the file, let's get it in the right directory with the right name.
$path = apply_filters('FHEE__EEH_Sideloader__sideload__new_path', $this->_upload_to . $this->_new_file_name, $this);
//move file in
if (false === @rename($file, $path)) {
unlink($temp_file);
EE_Error::add_error(sprintf(__('Unable to move the file to new location (possible permissions errors). This is the path the class attempted to move the file to: %s', 'event_espresso'), $path), __FILE__, __FUNCTION__, __LINE__);
return false;
}
//set permissions
$permissions = apply_filters('FHEE__EEH_Sideloader__sideload__permissions_applied', $this->_permissions, $this);
chmod($path, $permissions);
//that's it. let's allow for actions after file uploaded.
do_action('AHEE__EE_Sideloader__sideload_after', $this, $path);
//unlink tempfile
@unlink($temp_file);
return true;
}
示例12: download_image
/**
* Downloads a resource identified by the parameters.
*
* If only the first parameter is passed, and it is an instance of a cache
* file, downloads the resource described by it.
* If it is a URL, the request timeout and target path will be computed by this instance.
* Otherwise, they will be overridden by the specified values, respectively.
*
* If the 'content-md5' header is present in the responce, MD5 checksum
* verification will take place.
*
* @since 4.7.3
* @see get_download_request_timeout()
* @see WPRSS_Image_Cache_Image::get_download_request_timeout()
* @see get_unique_filename()
* @see WPRSS_Image_Cache_Image::get_current_path()
* @see get_tmp_dir()
* @see wp_mkdir_p()
* @see wp_safe_remote_get()
* @see verify_file_md5()
* @param WPRSS_Image_Cache_Image|string $image An instance of a cache file, or the URL to download.
* @param int|null $request_timeout The timeout for the download request.
* @param string|null $target_path The relative path to the target file.
* @return string| The absolute local path to the downloaded file,
* or false if checksum verification failed.
* @throws Exception If the URL is invalid, or the destination path is not writable,
* or the file download library cannot be read, or any other error happens during download.
*/
public function download_image($image, $request_timeout = null, $target_path = null)
{
if ($image instanceof WPRSS_Image_Cache_Image) {
$url = $image->get_url();
$timeout = $image->get_download_request_timeout();
$path = $image->get_current_path();
} else {
$url = $image;
$timeout = $this->get_download_request_timeout();
$path = $this->get_unique_filename($url);
}
if (!$url) {
throw new Exception(sprintf(__('Invalid URL provided: "%1$s"'), $url));
}
if (!is_null($target_path)) {
$path = $target_path;
}
if (is_null($request_timeout)) {
$timeout = $request_timeout;
}
// Absolute path to the cache file
$tmpfname = $image instanceof WPRSS_Image_Cache_Image ? $image->get_tmp_dir($path) : $this->get_tmp_dir($path);
//WARNING: The file is not automatically deleted, The script must unlink() the file.
$dirname = dirname($tmpfname);
if (!wp_mkdir_p($dirname)) {
throw new Exception(sprintf(__('Could not create directory: "%1$s". Filename: "%2$s"'), $dirname, $tmpfname));
}
// Getting file download lib
$file_lib_path = ABSPATH . 'wp-admin/includes/file.php';
if (!is_readable($file_lib_path)) {
throw new Exception(sprintf(__('The file library cannot be read from %1$s'), $file_lib_path));
}
require_once $file_lib_path;
// Retrieving the remote resource
$response = wp_safe_remote_get($url, array('timeout' => $timeout, 'stream' => true, 'filename' => $tmpfname));
// Could not retrieve
if (is_wp_error($response)) {
@unlink($tmpfname);
throw new Exception($response->get_error_message());
}
// Retrieved, but remote server served error instead of resource
if (200 != wp_remote_retrieve_response_code($response)) {
@unlink($tmpfname);
throw new Exception(trim(wp_remote_retrieve_response_message($response)));
}
// Checksum verification
$content_md5 = wp_remote_retrieve_header($response, 'content-md5');
if ($content_md5) {
$md5_check = verify_file_md5($tmpfname, $content_md5);
if (is_wp_error($md5_check)) {
unlink($tmpfname);
return $md5_check;
}
}
return $tmpfname;
}
示例13: ozh_ta_get_tweets
/**
* Poll Twitter API and get tweets
*
* @param bool $echo True to output results and redirect page (ie called from option page)
* @return bool false if error while polling Twitter, true otherwise
*/
function ozh_ta_get_tweets($echo = false)
{
global $ozh_ta;
if (!ozh_ta_is_configured()) {
ozh_ta_debug('Config incomplete, cannot import tweets');
return false;
}
$api = add_query_arg(array('count' => OZH_TA_BATCH, 'page' => $ozh_ta['api_page'], 'screen_name' => urlencode($ozh_ta['screen_name']), 'since_id' => $ozh_ta['last_tweet_id_inserted']), OZH_TA_API);
ozh_ta_debug("Polling {$api}");
$headers = array('Authorization' => 'Bearer ' . $ozh_ta['access_token']);
ozh_ta_debug("Headers: " . json_encode($headers));
$response = wp_remote_get($api, array('headers' => $headers, 'timeout' => 10));
$tweets = wp_remote_retrieve_body($response);
$ratelimit = wp_remote_retrieve_header($response, 'x-rate-limit-limit');
$ratelimit_r = wp_remote_retrieve_header($response, 'x-rate-limit-remaining');
$status = wp_remote_retrieve_response_code($response);
ozh_ta_debug("API status: {$status}");
ozh_ta_debug("API rate: {$ratelimit_r}/{$ratelimit}");
/**
* Something to check when Twitter update their API :
*
* Currently, when you try to retrieve more tweets than available (either you already have fetched 3200, or you
* have fetched them all), the API returns no particular error: status 200, just an empty body.
* In the future, check if they change this and return a particular message or status code
*/
// Fail Whale or other error
if (!$tweets or $status != 200) {
// 401 : Unauthorized
if ($status == 401) {
ozh_ta_debug('Could not fetch tweets: unauthorized access.');
if ($echo) {
wp_die('<p>Twitter returned an "Unauthorized" error. Check your consumer key and secret!</p>');
} else {
// TODO: what to do in such a case? Better not to silently die and do nothing.
// Email blog admin ?
return false;
}
}
// 419 : Rate limit exceeded
// 5xx : Fail whale
ozh_ta_debug('Twitter fail, retry in ' . OZH_TA_NEXT_FAIL);
// Context: from option page
if ($echo) {
$url = wp_nonce_url(admin_url('options-general.php?page=ozh_ta&action=import_all&time=' . time()), 'ozh_ta-import_all');
ozh_ta_reload($url, OZH_TA_NEXT_FAIL);
wp_die('<p>Twitter is over capacity. This page will refresh in ' . OZH_TA_NEXT_FAIL . ' seconds. Please wait this delay to avoid a ban.</p>');
// Context: from cron
} else {
// schedule same operation later
ozh_ta_schedule_next(OZH_TA_NEXT_FAIL);
return false;
}
}
// No Fail Whale, let's import
// Legacy note:
// We used to have to fix integers in the JSON response to have them handled as strings and not integers,
// to avoid having tweet ID 438400650846928897 interpreted as 4.34343e15
// $tweets = preg_replace( '/"\s*:\s*([\d]+)\s*([,}{])/', '": "$1"$2', $tweets );
// This isn't needed anymore since, smartly, Twitter's API returns both an id and an id_str. Nice, Twitter :)
$tweets = array_reverse((array) json_decode($tweets));
// Tweets found, let's archive
if ($tweets) {
if (ozh_ta_is_debug()) {
$overall = new ozh_ta_query_count();
}
$results = ozh_ta_insert_tweets($tweets, true);
// array( inserted, skipped, tagged, num_tags, (array)$user );
// Increment api_page and update user info
$ozh_ta['twitter_stats'] = array_merge($ozh_ta['twitter_stats'], $results['user']);
$ozh_ta['api_page']++;
update_option('ozh_ta', $ozh_ta);
ozh_ta_debug("Twitter OK, imported {$results['inserted']}, skipped {$results['skipped']}, tagged {$results['tagged']} with {$results['num_tags']} tags, next in " . OZH_TA_NEXT_SUCCESS);
if (ozh_ta_is_debug()) {
ozh_ta_debug('Total queries: ' . $overall->stop());
}
// Context: option page
if ($echo) {
echo "<p>Tweets inserted: <strong>{$results['inserted']}</strong></p>";
$url = wp_nonce_url(admin_url('options-general.php?page=ozh_ta&action=import_all&time=' . time()), 'ozh_ta-import_all');
ozh_ta_reload($url, OZH_TA_NEXT_SUCCESS);
// Context: from cron
} else {
// schedule next operation soon
ozh_ta_schedule_next(OZH_TA_NEXT_SUCCESS);
}
// No tweets found
} else {
global $wpdb;
// Schedule next operation
ozh_ta_schedule_next($ozh_ta['refresh_interval']);
ozh_ta_debug("Twitter finished, next in {$ozh_ta['refresh_interval']}");
// Update last_tweet_id_inserted, stats, & reset API paging
$ozh_ta['api_page'] = 1;
$ozh_ta['last_tweet_id_inserted'] = $wpdb->get_var("SELECT `meta_value` FROM `{$wpdb->postmeta}` WHERE `meta_key` = 'ozh_ta_id' ORDER BY ABS(`meta_value`) DESC LIMIT 1");
//.........这里部分代码省略.........
示例14: request
/**
* Wrapper around http_request() that handles pagination for List endpoints.
*
* @param string $debug_label Description of the request, for logging.
* @param string $path API endpoint path to hit. E.g. /items/
* @param string $method HTTP method to use. Defaults to 'GET'.
* @param mixed $body Optional. Request payload - will be JSON encoded if non-scalar.
*
* @return bool|object|WP_Error
*/
public function request($debug_label, $path, $method = 'GET', $body = null)
{
// The access token is required for all requests
$access_token = $this->get_access_token();
if (empty($access_token)) {
return false;
}
$request_url = $this->get_request_url($path);
$return_data = array();
while (true) {
$response = $this->http_request($debug_label, $request_url, $method, $body);
if (!$response) {
return $response;
}
$response_data = json_decode(wp_remote_retrieve_body($response));
// A paged list result will be an array, so let's merge if we're already returning an array
if ('GET' === $method && is_array($return_data) && is_array($response_data)) {
$return_data = array_merge($return_data, $response_data);
} else {
$return_data = $response_data;
}
// Look for the next page, if specified
$link_header = wp_remote_retrieve_header($response, 'Link');
$rel_link_matches = array();
// Set up the next page URL for the following loop
if ('GET' === $method && preg_match("|^<(.+)>;rel='next'\$|", $link_header, $rel_link_matches)) {
$request_url = $rel_link_matches[1];
$body = null;
} else {
return $return_data;
}
}
}
示例15: call
/**
* Generic GitHub API interface and response handler
*
* @param string $method
* @param string $endpoint
* @param array $body
*
* @return mixed
*/
public function call($method, $endpoint, $body = array())
{
$args = array('method' => $method, 'headers' => array('Authorization' => 'token ' . $this->oauth_token()), 'body' => function_exists('wp_json_encode') ? wp_json_encode($body) : json_encode($body));
$response = wp_remote_request($endpoint, $args);
$status = wp_remote_retrieve_header($response, 'status');
$body = json_decode(wp_remote_retrieve_body($response));
if ('2' !== substr($status, 0, 1) && '3' !== substr($status, 0, 1)) {
return new WP_Error($status, $body ? $body->message : 'Unknown error');
}
return $body;
}