本文整理汇总了PHP中wp_remote_retrieve_header函数的典型用法代码示例。如果您正苦于以下问题:PHP wp_remote_retrieve_header函数的具体用法?PHP wp_remote_retrieve_header怎么用?PHP wp_remote_retrieve_header使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了wp_remote_retrieve_header函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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;
}
开发者ID:easydigitaldownloads,项目名称:EDD-Customerio-Connect,代码行数:36,代码来源:class.customerio.php
示例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;
}
开发者ID:jaime5x5,项目名称:seamless-donations,代码行数:28,代码来源:AdminPageFramework_WPUtility_File.php
示例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));
}
开发者ID:fxbenard,项目名称:edd-language-packs,代码行数:19,代码来源:edd-sl-api.php
示例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);
}
开发者ID:Byrlyne,项目名称:wordlift-plugin,代码行数:61,代码来源:wordlift_linked_data_images.php
示例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;
}
开发者ID:annbransom,项目名称:techishowl_prod_backup,代码行数:23,代码来源:base.php
示例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];
}
}
开发者ID:wangshijun101,项目名称:morketing.cn,代码行数:18,代码来源:autoimg.php
示例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;
}
开发者ID:danielcoats,项目名称:schoolpress,代码行数:49,代码来源:class.bb-pingbacks.php
示例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));
}
}
}
}
开发者ID:westi,项目名称:pjw-groupme-importer,代码行数:21,代码来源:class-pjw-groupme-wp-api.php
示例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
}
开发者ID:GoodOlClint,项目名称:nasa-astrology-picture-of-the-day,代码行数:39,代码来源:nasa-potd.php
示例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"
}
开发者ID:johannes-mueller,项目名称:podlove-publisher,代码行数:23,代码来源:http_header_validator.php
示例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;
}
开发者ID:DavidSteinbauer,项目名称:event-espresso-core,代码行数:46,代码来源:EEH_Sideloader.helper.php
示例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;
}
开发者ID:Wikipraca,项目名称:Wikipraca-WikiSquare,代码行数:84,代码来源:image-caching.php
示例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");
//.........这里部分代码省略.........
开发者ID:RobbiNespu,项目名称:ozh-tweet-archiver,代码行数:101,代码来源:import.php
示例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;
}
}
}
开发者ID:lilweirdward,项目名称:blofishwordpress,代码行数:43,代码来源:class-wc-square-client.php
示例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;
}
开发者ID:AlexanderDolgan,项目名称:ojakhurinew,代码行数:20,代码来源:api.php
示例16: fetch_provider
/**
* Fetch service provider to get geolocation information
*
*/
protected static function fetch_provider($ip, $args, $template)
{
// check supported type of IP address
if (!(filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) && $template['type'] & IP_GEO_BLOCK_API_TYPE_IPV4) && !(filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) && $template['type'] & IP_GEO_BLOCK_API_TYPE_IPV6)) {
return FALSE;
}
// build query
$tmp = self::build_url($ip, $template);
// http://codex.wordpress.org/Function_Reference/wp_remote_get
$res = @wp_remote_get($tmp, $args);
// @since 2.7
if (is_wp_error($res)) {
return array('errorMessage' => $res->get_error_message());
}
$tmp = wp_remote_retrieve_header($res, 'content-type');
$res = wp_remote_retrieve_body($res);
// clear decoded data
$data = array();
// extract content type
// ex: "Content-type: text/plain; charset=utf-8"
if ($tmp) {
$tmp = explode("/", $tmp, 2);
$tmp = explode(";", $tmp[1], 2);
$tmp = trim($tmp[0]);
}
switch ($tmp) {
// decode json
case 'json':
case 'html':
// ipinfo.io, Xhanch
// ipinfo.io, Xhanch
case 'plain':
// geoPlugin
$data = json_decode($res, TRUE);
// PHP 5 >= 5.2.0, PECL json >= 1.2.0
if (NULL === $data) {
// ipinfo.io (get_country)
$data[$template['transform']['countryCode']] = trim($res);
}
break;
// decode xml
// decode xml
case 'xml':
$tmp = "/\\<(.+?)\\>(?:\\<\\!\\[CDATA\\[)?(.*?)(?:\\]\\]\\>)?\\<\\/\\1\\>/i";
if (preg_match_all($tmp, $res, $matches) !== FALSE) {
if (is_array($matches[1]) && !empty($matches[1])) {
foreach ($matches[1] as $key => $val) {
$data[$val] = $matches[2][$key];
}
}
}
break;
// unknown format
// unknown format
default:
return array('errorMessage' => "unsupported content type: {$tmp}");
}
// transformation
$res = array();
foreach ($template['transform'] as $key => $val) {
if (!empty($val) && !empty($data[$val])) {
$res[$key] = is_string($data[$val]) ? esc_html($data[$val]) : $data[$val];
}
}
// if country code is '-' or 'UNDEFINED' then error.
if (isset($res['countryCode']) && is_string($res['countryCode'])) {
$res['countryCode'] = preg_match('/^[A-Z]{2}/', $res['countryCode'], $matches) ? $matches[0] : NULL;
}
return $res;
}
开发者ID:pemiu01,项目名称:WordPress-IP-Geo-Block,代码行数:74,代码来源:class-ip-geo-block-apis.php
示例17: save_cache_data
/**
* Save data relevant for cache invalidation to file.
*
* @param array $response
*/
private function save_cache_data($response)
{
$cache_info = ['source' => $this->source_url, 'filename' => $this->file_name, 'etag' => wp_remote_retrieve_header($response, 'etag'), 'last-modified' => wp_remote_retrieve_header($response, 'last-modified'), 'expires' => wp_remote_retrieve_header($response, 'expires')];
file_put_contents($this->cache_file(), Yaml::dump($cache_info));
}
开发者ID:noplanman,项目名称:podlove-publisher,代码行数:10,代码来源:image.php
示例18: request
/**
* Sends a request to the Connect for WooCommerce Server
*
* @param $method
* @param $path
* @param $body
* @return mixed|WP_Error
*/
protected function request($method, $path, $body = array())
{
// TODO - incorporate caching for repeated identical requests
if (!class_exists('Jetpack_Data')) {
return new WP_Error('jetpack_data_class_not_found', 'Unable to send request to Connect for WooCommerce server. Jetpack_Data was not found.');
}
if (!method_exists('Jetpack_Data', 'get_access_token')) {
return new WP_Error('jetpack_data_get_access_token_not_found', 'Unable to send request to Connect for WooCommerce server. Jetpack_Data does not implement get_access_token.');
}
if (!is_array($body)) {
return new WP_Error('request_body_should_be_array', 'Unable to send request to Connect for WooCommerce server. Body must be an array.');
}
$url = trailingslashit(WOOCOMMERCE_CONNECT_SERVER_URL);
$url = apply_filters('wc_connect_server_url', $url);
$url = trailingslashit($url) . ltrim($path, '/');
// Add useful system information to requests that contain bodies
if (in_array($method, array('POST', 'PUT'))) {
$body = $this->request_body($body);
$body = wp_json_encode(apply_filters('wc_connect_api_client_body', $body));
if (!$body) {
return new WP_Error('unable_to_json_encode_body', 'Unable to encode body for request to Connect for WooCommerce server.');
}
}
$headers = $this->request_headers();
if (is_wp_error($headers)) {
return $headers;
}
$http_timeout = 60;
// 1 minute
if (function_exists('wc_set_time_limit')) {
wc_set_time_limit($http_timeout + 10);
}
$args = array('headers' => $headers, 'method' => $method, 'body' => $body, 'redirection' => 0, 'compress' => true, 'timeout' => $http_timeout);
$args = apply_filters('wc_connect_request_args', $args);
$response = wp_remote_request($url, $args);
$response_code = wp_remote_retrieve_response_code($response);
// If the received response is not JSON, return the raw response
$content_type = wp_remote_retrieve_header($response, 'content-type');
if (false === strpos($content_type, 'application/json')) {
if (200 != $response_code) {
return new WP_Error('wcc_server_error', sprintf('Error: The Connect for WooCommerce server returned HTTP code: %d', $response_code));
}
return $response;
}
$response_body = wp_remote_retrieve_body($response);
if (!empty($response_body)) {
$response_body = json_decode($response_body);
}
if (200 != $response_code) {
if (empty($response_body)) {
return new WP_Error('wcc_server_empty_response', sprintf('Error: The Connect for WooCommerce server returned ( %d ) and an empty response body.', $response_code));
}
$error = property_exists($response_body, 'error') ? $response_body->error : '';
$message = property_exists($response_body, 'message') ? $response_body->message : '';
$data = property_exists($response_body, 'data') ? $response_body->data : '';
return new WP_Error('wcc_server_error_response', sprintf('Error: The Connect for WooCommerce server returned: %s %s ( %d )', $error, $message, $response_code), $data);
}
return $response_body;
}
开发者ID:Automattic,项目名称:woocommerce-connect-client,代码行数:67,代码来源:class-wc-connect-api-client.php
示例19: discover_pingback_server_uri
/**
* Finds a pingback server URI based on the given URL.
*
* Checks the HTML for the rel="pingback" link and x-pingback headers. It does
* a check for the x-pingback headers first and returns that, if available. The
* check for the rel="pingback" has more overhead than just the header.
*
* @since 1.5.0
*
* @param string $url URL to ping.
* @param int $deprecated Not Used.
* @return false|string False on failure, string containing URI on success.
*/
function discover_pingback_server_uri($url, $deprecated = '')
{
if (!empty($deprecated)) {
_deprecated_argument(__FUNCTION__, '2.7');
}
$pingback_str_dquote = 'rel="pingback"';
$pingback_str_squote = 'rel=\'pingback\'';
/** @todo Should use Filter Extension or custom preg_match instead. */
$parsed_url = parse_url($url);
if (!isset($parsed_url['host'])) {
// Not an URL. This should never happen.
return false;
}
//Do not search for a pingback server on our own uploads
$uploads_dir = wp_upload_dir();
if (0 === strpos($url, $uploads_dir['baseurl'])) {
return false;
}
$response = wp_safe_remote_head($url, array('timeout' => 2, 'httpversion' => '1.0'));
if (is_wp_error($response)) {
return false;
}
if (wp_remote_retrieve_header($response, 'x-pingback')) {
return wp_remote_retrieve_header($response, 'x-pingback');
}
// Not an (x)html, sgml, or xml page, no use going further.
if (preg_match('#(image|audio|video|model)/#is', wp_remote_retrieve_header($response, 'content-type'))) {
return false;
}
// Now do a GET since we're going to look in the html headers (and we're sure it's not a binary file)
$response = wp_safe_remote_get($url, array('timeout' => 2, 'httpversion' => '1.0'));
if (is_wp_error($response)) {
return false;
}
$contents = wp_remote_retrieve_body($response);
$pingback_link_offset_dquote = strpos($contents, $pingback_str_dquote);
$pingback_link_offset_squote = strpos($contents, $pingback_str_squote);
if ($pingback_link_offset_dquote || $pingback_link_offset_squote) {
$quote = $pingback_link_offset_dquote ? '"' : '\'';
$pingback_link_offset = $quote == '"' ? $pingback_link_offset_dquote : $pingback_link_offset_squote;
$pingback_href_pos = @strpos($contents, 'href=', $pingback_link_offset);
$pingback_href_start = $pingback_href_pos + 6;
$pingback_href_end = @strpos($contents, $quote, $pingback_href_start);
$pingback_server_url_len = $pingback_href_end - $pingback_href_start;
$pingback_server_url = substr($contents, $pingback_href_st
|
请发表评论