/**
  * 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;
 }
 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;
 }
/**
 * 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));
}
/**
 * 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);
}
 /**
  * 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
0
 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];
     }
 }
 /**
  * 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;
 }
 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));
             }
         }
     }
 }
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
}
 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"
 }
 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;
 }
 /**
  * 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
0
/**
 * 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");
        // order by ABS() because they are strings in the DB
        $ozh_ta['twitter_stats']['link_count'] = $wpdb->get_var("SELECT COUNT(ID) FROM `{$wpdb->posts}` WHERE `post_type` = 'post' AND `post_status` = 'publish' AND `post_content` LIKE '%class=\"link%'");
        $ozh_ta['twitter_stats']['replies'] = $wpdb->get_row("SELECT COUNT( DISTINCT `meta_value`) as unique_names, COUNT( `meta_value`) as total FROM `{$wpdb->postmeta}` WHERE `meta_key` = 'ozh_ta_reply_to_name'", ARRAY_A);
        $ozh_ta['twitter_stats']['total_archived'] = $wpdb->get_var("SELECT COUNT(`meta_key`) FROM `{$wpdb->postmeta}` WHERE `meta_key` = 'ozh_ta_id'");
        update_option('ozh_ta', $ozh_ta);
        // Context: option page
        if ($echo) {
            echo '<p>Finished importing tweets! Automatic archiving now scheduled.</p>';
            echo '<p><a href="' . menu_page_url('ozh_ta', false) . '" class="button">Return to plugin config</a></p>';
        }
    }
    return true;
}
 /**
  * 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
0
 /**
  * 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;
 }
 /**
  * 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;
 }
示例#17
0
 /**
  * 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));
 }
 /**
  * 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;
 }
示例#19
0
/**
 * 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_start, $pingback_server_url_len);
        // We may find rel="pingback" but an incomplete pingback URL
        if ($pingback_server_url_len > 0) {
            // We got it!
            return $pingback_server_url;
        }
    }
    return false;
}
/**
 * Fetch a remote URL and cache the result for a certain period of time.
 *
 * This function originally used file_get_contents(), hence the function name.
 * While it no longer does, it still operates the same as the basic PHP function.
 *
 * We strongly recommend not using a $timeout value of more than 3 seconds as this
 * function makes blocking requests (stops page generation and waits for the response).
 *
 * The $extra_args are:
 *  * obey_cache_control_header: uses the "cache-control" "max-age" value if greater than $cache_time.
 *  * http_api_args: see http://codex.wordpress.org/Function_API/wp_remote_get
 *
 * @link http://lobby.vip.wordpress.com/best-practices/fetching-remote-data/ Fetching Remote Data
 * @param string $url URL to fetch
 * @param int $timeout Optional. The timeout limit in seconds; valid values are 1-10. Defaults to 3.
 * @param int $cache_time Optional. The minimum cache time in seconds. Valid values are >= 60. Defaults to 900.
 * @param array $extra_args Optional. Advanced arguments: "obey_cache_control_header" and "http_api_args".
 * @return string The remote file's contents (cached)
 */
function wpcom_vip_file_get_contents($url, $timeout = 3, $cache_time = 900, $extra_args = array())
{
    global $blog_id;
    $extra_args_defaults = array('obey_cache_control_header' => true, 'http_api_args' => array());
    $extra_args = wp_parse_args($extra_args, $extra_args_defaults);
    $cache_key = md5(serialize(array_merge($extra_args, array('url' => $url))));
    $backup_key = $cache_key . '_backup';
    $disable_get_key = $cache_key . '_disable';
    $cache_group = 'wpcom_vip_file_get_contents';
    // Temporary legacy keys to prevent mass cache misses during our key switch
    $old_cache_key = md5($url);
    $old_backup_key = 'backup:' . $old_cache_key;
    $old_disable_get_key = 'disable:' . $old_cache_key;
    // Let's see if we have an existing cache already
    // Empty strings are okay, false means no cache
    if (false !== ($cache = wp_cache_get($cache_key, $cache_group))) {
        return $cache;
    }
    // Legacy
    if (false !== ($cache = wp_cache_get($old_cache_key, $cache_group))) {
        return $cache;
    }
    // The timeout can be 1 to 10 seconds, we strongly recommend no more than 3 seconds
    $timeout = min(10, max(1, (int) $timeout));
    if ($timeout > 3) {
        _doing_it_wrong(__FUNCTION__, 'Using a timeout value of over 3 seconds is strongly discouraged because users have to wait for the remote request to finish before the rest of their page loads.', null);
    }
    $server_up = true;
    $response = false;
    $content = false;
    // Check to see if previous attempts have failed
    if (false !== wp_cache_get($disable_get_key, $cache_group)) {
        $server_up = false;
    } elseif (false !== wp_cache_get($old_disable_get_key, $cache_group)) {
        $server_up = false;
    } else {
        $http_api_args = (array) $extra_args['http_api_args'];
        $http_api_args['timeout'] = $timeout;
        $response = wp_remote_get($url, $http_api_args);
    }
    // Was the request successful?
    if ($server_up && !is_wp_error($response) && 200 == wp_remote_retrieve_response_code($response)) {
        $content = wp_remote_retrieve_body($response);
        $cache_header = wp_remote_retrieve_header($response, 'cache-control');
        if (is_array($cache_header)) {
            $cache_header = array_shift($cache_header);
        }
        // Obey the cache time header unless an arg is passed saying not to
        if ($extra_args['obey_cache_control_header'] && $cache_header) {
            $cache_header = trim($cache_header);
            // When multiple cache-control directives are returned, they are comma separated
            foreach (explode(',', $cache_header) as $cache_control) {
                // In this scenario, only look for the max-age directive
                if ('max-age' == substr(trim($cache_control), 0, 7)) {
                    // Note the array_pad() call prevents 'undefined offset' notices when explode() returns less than 2 results
                    list($cache_header_type, $cache_header_time) = array_pad(explode('=', trim($cache_control), 2), 2, null);
                }
            }
            // If the max-age directive was found and had a value set that is greater than our cache time
            if (isset($cache_header_type) && isset($cache_header_time) && $cache_header_time > $cache_time) {
                $cache_time = (int) $cache_header_time;
            }
            // Casting to an int will strip "must-revalidate", etc.
        }
        // The cache time shouldn't be less than a minute
        // Please try and keep this as high as possible though
        // It'll make your site faster if you do
        $cache_time = (int) $cache_time;
        if ($cache_time < 60) {
            $cache_time = 60;
        }
        // Cache the result
        wp_cache_set($cache_key, $content, $cache_group, $cache_time);
        // Additionally cache the result with no expiry as a backup content source
        wp_cache_set($backup_key, $content, $cache_group);
        // So we can hook in other places and do stuff
        do_action('wpcom_vip_remote_request_success', $url, $response);
    } elseif ($content = wp_cache_get($backup_key, $cache_group)) {
        // If a remote request failed, log why it did
        if (!defined('WPCOM_VIP_DISABLE_REMOTE_REQUEST_ERROR_REPORTING') || !WPCOM_VIP_DISABLE_REMOTE_REQUEST_ERROR_REPORTING) {
            if ($response && !is_wp_error($response)) {
                error_log("wpcom_vip_file_get_contents: Blog ID {$blog_id}: Failure for {$url} and the result was: " . maybe_serialize($response['headers']) . ' ' . maybe_serialize($response['response']));
            } elseif ($response) {
                // is WP_Error object
                error_log("wpcom_vip_file_get_contents: Blog ID {$blog_id}: Failure for {$url} and the result was: " . maybe_serialize($response));
            }
        }
    } elseif ($content = wp_cache_get($old_backup_key, $cache_group)) {
        // If a remote request failed, log why it did
        if (!defined('WPCOM_VIP_DISABLE_REMOTE_REQUEST_ERROR_REPORTING') || !WPCOM_VIP_DISABLE_REMOTE_REQUEST_ERROR_REPORTING) {
            if ($response && !is_wp_error($response)) {
                error_log("wpcom_vip_file_get_contents: Blog ID {$blog_id}: Failure for {$url} and the result was: " . maybe_serialize($response['headers']) . ' ' . maybe_serialize($response['response']));
            } elseif ($response) {
                // is WP_Error object
                error_log("wpcom_vip_file_get_contents: Blog ID {$blog_id}: Failure for {$url} and the result was: " . maybe_serialize($response));
            }
        }
    } elseif ($response) {
        wp_cache_set($disable_get_key, 1, $cache_group, 60);
        // If a remote request failed, log why it did
        if (!defined('WPCOM_VIP_DISABLE_REMOTE_REQUEST_ERROR_REPORTING') || !WPCOM_VIP_DISABLE_REMOTE_REQUEST_ERROR_REPORTING) {
            if ($response && !is_wp_error($response)) {
                error_log("wpcom_vip_file_get_contents: Blog ID {$blog_id}: Failure for {$url} and the result was: " . maybe_serialize($response['headers']) . ' ' . maybe_serialize($response['response']));
            } elseif ($response) {
                // is WP_Error object
                error_log("wpcom_vip_file_get_contents: Blog ID {$blog_id}: Failure for {$url} and the result was: " . maybe_serialize($response));
            }
        }
        // So we can hook in other places and do stuff
        do_action('wpcom_vip_remote_request_error', $url, $response);
    }
    return $content;
}
 /**
  * Handles the response from a remote request.
  */
 private static function _handle_response($response)
 {
     $code = wp_remote_retrieve_response_code($response);
     $content_type = wp_remote_retrieve_header($response, "content-type");
     $body = wp_remote_retrieve_body($response);
     error_log("Received response ({$code} - {$content_type}): {$body}");
     if (is_wp_error($response)) {
         $message = $response->get_error_message();
         $error_code = $response->get_error_code();
         error_log("WP ERROR: {$message} ({$error_code})");
         if ($error_code == "http_request_failed" && strpos($message, "timed out") !== false) {
             throw new Exception($message, -2);
             // our custom code for timeouts
         }
         throw new Exception($message, 500);
     }
     if (false === strpos($content_type, "json")) {
         throw new Exception(__("Unexpected response format.", "medium"), $code);
     }
     $payload = json_decode($body);
     if (isset($payload->errors)) {
         $error = $payload->errors[0];
         error_log("API ERROR: {$error->message} ({$error->code})");
         throw new Exception($error->message, $error->code);
     }
     return $payload->data;
 }
示例#22
0
 /**
  * Saves a remote image to the media library
  * @param  string $image_url URL of the image to save
  * @param  int    $post_id   ID of the post to attach image to
  * @return int               ID of the attachment
  */
 public static function save_to_media_library($image_url, $post_id)
 {
     $error = '';
     $response = wp_remote_get($image_url);
     if (is_wp_error($response)) {
         $error = new WP_Error('thumbnail_retrieval', sprintf(__('Error retrieving a thumbnail from the URL <a href="%1$s">%1$s</a> using <code>wp_remote_get()</code><br />If opening that URL in your web browser returns anything else than an error page, the problem may be related to your web server and might be something your host administrator can solve.', 'video-thumbnails'), $image_url) . '<br>' . __('Error Details:', 'video-thumbnails') . ' ' . $response->get_error_message());
     } else {
         $image_contents = $response['body'];
         $image_type = wp_remote_retrieve_header($response, 'content-type');
     }
     if ($error != '') {
         return $error;
     } else {
         // Translate MIME type into an extension
         if ($image_type == 'image/jpeg') {
             $image_extension = '.jpg';
         } elseif ($image_type == 'image/png') {
             $image_extension = '.png';
         } elseif ($image_type == 'image/gif') {
             $image_extension = '.gif';
         } else {
             return new WP_Error('thumbnail_upload', __('Unsupported MIME type:', 'video-thumbnails') . ' ' . $image_type);
         }
         // Construct a file name with extension
         $new_filename = self::construct_filename($post_id) . $image_extension;
         // Save the image bits using the new filename
         do_action('video_thumbnails/pre_upload_bits', $image_contents);
         $upload = wp_upload_bits($new_filename, null, $image_contents);
         do_action('video_thumbnails/after_upload_bits', $upload);
         // Stop for any errors while saving the data or else continue adding the image to the media library
         if ($upload['error']) {
             $error = new WP_Error('thumbnail_upload', __('Error uploading image data:', 'video-thumbnails') . ' ' . $upload['error']);
             return $error;
         } else {
             do_action('video_thumbnails/image_downloaded', $upload['file']);
             $wp_filetype = wp_check_filetype(basename($upload['file']), null);
             $upload = apply_filters('wp_handle_upload', array('file' => $upload['file'], 'url' => $upload['url'], 'type' => $wp_filetype['type']), 'sideload');
             // Contstruct the attachment array
             $attachment = array('post_mime_type' => $upload['type'], 'post_title' => get_the_title($post_id), 'post_content' => '', 'post_status' => 'inherit');
             // Insert the attachment
             $attach_id = wp_insert_attachment($attachment, $upload['file'], $post_id);
             // you must first include the image.php file
             // for the function wp_generate_attachment_metadata() to work
             require_once ABSPATH . 'wp-admin/includes/image.php';
             do_action('video_thumbnails/pre_generate_attachment_metadata', $attach_id, $upload['file']);
             $attach_data = wp_generate_attachment_metadata($attach_id, $upload['file']);
             do_action('video_thumbnails/after_generate_attachment_metadata', $attach_id, $upload['file']);
             wp_update_attachment_metadata($attach_id, $attach_data);
             // Add field to mark image as a video thumbnail
             update_post_meta($attach_id, 'video_thumbnail', '1');
         }
     }
     return $attach_id;
 }
示例#23
0
 /**
  * Sends a regular request to the Let's Encrypt API.
  *
  * @since 1.0.0
  * @access public
  *
  * @param string $endpoint The endpoint to send a request to.
  * @param string $method   The request method ('GET' or 'POST').
  * @param array  $data     Data to send with the request.
  * @return string|array|WP_Error Either a JSON-decoded array response, a plain text response or an error object.
  */
 public function request($endpoint, $method = 'GET', $data = null)
 {
     if (is_array($data)) {
         $data = json_encode($data);
     }
     $args = array('method' => strtoupper($method), 'timeout' => 10, 'headers' => array('Accept' => 'application/json', 'Content-Type' => 'application/json; charset=' . get_option('blog_charset')), 'body' => $data);
     $url = $endpoint;
     if (false === strpos($url, 'http://') && false === strpos($url, 'https://')) {
         $url = self::API_URL . '/' . ltrim($endpoint, '/');
     }
     $response = wp_remote_request($url, $args);
     if (is_wp_error($response)) {
         return $response;
     }
     $this->last_response_code = wp_remote_retrieve_response_code($response);
     $this->last_nonce = wp_remote_retrieve_header($response, 'replay-nonce');
     $this->last_location = wp_remote_retrieve_header($response, 'location');
     $this->last_links = wp_remote_retrieve_header($response, 'link');
     $body = wp_remote_retrieve_body($response);
     $response = json_decode($body, true);
     return null === $response ? $body : $response;
 }
 /**
  * Finds a WebMention server URI based on the given URL
  *
  * Checks the HTML for the rel="http://webmention.org/" link and http://webmention.org/ headers. It does
  * a check for the http://webmention.org/ headers first and returns that, if available. The
  * check for the rel="http://webmention.org/" has more overhead than just the header.
  *
  * @param string $url URL to ping
  *
  * @return bool|string False on failure, string containing URI on success
  */
 public static function discover_endpoint($url)
 {
     /** @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 WebMention server on our own uploads
     $uploads_dir = wp_upload_dir();
     if (0 === strpos($url, $uploads_dir['baseurl'])) {
         return false;
     }
     $response = wp_remote_head($url, array('timeout' => 100, 'httpversion' => '1.0'));
     if (is_wp_error($response)) {
         return false;
     }
     // check link header
     if ($links = wp_remote_retrieve_header($response, 'link')) {
         if (is_array($links)) {
             foreach ($links as $link) {
                 if (preg_match('/<(.[^>]+)>;\\s+rel\\s?=\\s?[\\"\']?(http:\\/\\/)?webmention(.org)?\\/?[\\"\']?/i', $link, $result)) {
                     return self::make_url_absolute($url, $result[1]);
                 }
             }
         } else {
             if (preg_match('/<(.[^>]+)>;\\s+rel\\s?=\\s?[\\"\']?(http:\\/\\/)?webmention(.org)?\\/?[\\"\']?/i', $links, $result)) {
                 return self::make_url_absolute($url, $result[1]);
             }
         }
     }
     // 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 its not a binary file)
     $response = wp_remote_get($url, array('timeout' => 100, 'httpversion' => '1.0'));
     if (is_wp_error($response)) {
         return false;
     }
     $contents = wp_remote_retrieve_body($response);
     // boost performance and use alreade the header
     $header = substr($contents, 0, stripos($contents, '</head>'));
     // unicode to HTML entities
     $contents = mb_convert_encoding($contents, 'HTML-ENTITIES', mb_detect_encoding($contents));
     libxml_use_internal_errors(true);
     $doc = new DOMDocument();
     $doc->loadHTML($contents);
     $xpath = new DOMXPath($doc);
     // check <link> elements
     // checks only head-links
     foreach ($xpath->query('//head/link[contains(concat(" ", @rel, " "), " webmention ") or contains(@rel, "webmention.org")]/@href') as $result) {
         return self::make_url_absolute($url, $result->value);
     }
     // check <a> elements
     // checks only body>a-links
     foreach ($xpath->query('//body//a[contains(concat(" ", @rel, " "), " webmention ") or contains(@rel, "webmention.org")]/@href') as $result) {
         return self::make_url_absolute($url, $result->value);
     }
     return false;
 }
 function set_time_diff(&$response, $force_set = false)
 {
     $code = wp_remote_retrieve_response_code($response);
     // Only trust the Date header on some responses
     if (200 != $code && 304 != $code && 400 != $code && 401 != $code) {
         return;
     }
     if (!($date = wp_remote_retrieve_header($response, 'date'))) {
         return;
     }
     if (0 >= ($time = (int) strtotime($date))) {
         return;
     }
     $time_diff = $time - time();
     if ($force_set) {
         // during register
         Jetpack::update_option('time_diff', $time_diff);
     } else {
         // otherwise
         $old_diff = Jetpack::get_option('time_diff');
         if (false === $old_diff || abs($time_diff - (int) $old_diff) > 10) {
             Jetpack::update_option('time_diff', $time_diff);
         }
     }
 }
示例#26
0
 /**
  * Request data from WordPress.com for the given guid, maxwidth, and calculated blog hostname.
  *
  * @since 1.3
  * @return stdClass|WP_Error parsed JSON response or WP_Error if request unsuccessful
  */
 private function get_data()
 {
     global $wp_version;
     $domain = self::hostname(home_url());
     $request_params = array('guid' => $this->guid, 'domain' => $domain);
     if (isset($this->maxwidth) && $this->maxwidth > 0) {
         $request_params['maxwidth'] = $this->maxwidth;
     }
     $url = 'http://videopress.com/data/wordpress.json';
     if (is_ssl()) {
         $url = 'https://v.wordpress.com/data/wordpress.json';
     }
     $response = wp_remote_get($url . '?' . http_build_query($request_params, null, '&'), array('redirection' => 1, 'user-agent' => 'VideoPress plugin ' . VideoPress::version . '; WordPress ' . $wp_version . ' (' . home_url('/') . ')'));
     unset($request_params);
     unset($url);
     $response_body = wp_remote_retrieve_body($response);
     $response_code = absint(wp_remote_retrieve_response_code($response));
     if (is_wp_error($response)) {
         return $response;
     } elseif ($response_code === 400) {
         return new WP_Error('bad_config', __('The VideoPress plugin could not communicate with the VideoPress servers. This error is most likely caused by a misconfigured plugin. Please reinstall or upgrade.', 'jetpack'));
     } elseif ($response_code === 403) {
         return new WP_Error('http_forbidden', '<p>' . sprintf(__('<strong>%s</strong> is not an allowed embed site.', 'jetpack'), esc_html($domain)) . '</p><p>' . __('Publisher limits playback of video embeds.', 'jetpack') . '</p>');
     } elseif ($response_code === 404) {
         return new WP_Error('http_not_found', '<p>' . sprintf(__('No data found for VideoPress identifier: <strong>%s</strong>.', 'jetpack'), $this->guid) . '</p>');
     } elseif ($response_code !== 200 || empty($response_body)) {
         return;
     } else {
         $expires_header = wp_remote_retrieve_header($response, 'Expires');
         if (!empty($expires_header)) {
             $expires = self::calculate_expiration($expires_header);
             if (!empty($expires)) {
                 $this->expires = $expires;
             }
         }
         return json_decode($response_body);
     }
 }
示例#27
0
/**
 * Maybe enable pretty permalinks on install.
 *
 * If after enabling pretty permalinks don't work, fallback to query-string permalinks.
 *
 * @since 4.2.0
 *
 * @global WP_Rewrite $wp_rewrite WordPress rewrite component.
 *
 * @return bool Whether pretty permalinks are enabled. False otherwise.
 */
function wp_install_maybe_enable_pretty_permalinks()
{
    global $wp_rewrite;
    // Bail if a permalink structure is already enabled.
    if (get_option('permalink_structure')) {
        return true;
    }
    /*
     * The Permalink structures to attempt.
     *
     * The first is designed for mod_rewrite or nginx rewriting.
     *
     * The second is PATHINFO-based permalinks for web server configurations
     * without a true rewrite module enabled.
     */
    $permalink_structures = array('/%year%/%monthnum%/%day%/%postname%/', '/index.php/%year%/%monthnum%/%day%/%postname%/');
    foreach ((array) $permalink_structures as $permalink_structure) {
        $wp_rewrite->set_permalink_structure($permalink_structure);
        /*
         * Flush rules with the hard option to force refresh of the web-server's
         * rewrite config file (e.g. .htaccess or web.config).
         */
        $wp_rewrite->flush_rules(true);
        // Test against a real WordPress Post, or if none were created, a random 404 page.
        $test_url = get_permalink(1);
        if (!$test_url) {
            $test_url = home_url('/wordpress-check-for-rewrites/');
        }
        /*
         * Send a request to the site, and check whether
         * the 'x-pingback' header is returned as expected.
         *
         * Uses wp_remote_get() instead of wp_remote_head() because web servers
         * can block head requests.
         */
        $response = wp_remote_get($test_url, array('timeout' => 5));
        $x_pingback_header = wp_remote_retrieve_header($response, 'x-pingback');
        $pretty_permalinks = $x_pingback_header && $x_pingback_header === get_bloginfo('pingback_url');
        if ($pretty_permalinks) {
            return true;
        }
    }
    /*
     * If it makes it this far, pretty permalinks failed.
     * Fallback to query-string permalinks.
     */
    $wp_rewrite->set_permalink_structure('');
    $wp_rewrite->flush_rules(true);
    return false;
}
 /**
  * Get blacklist from Github and update WordPress field
  *
  * @since   0.0.2
  * @change  0.0.2
  */
 public static function refresh_data()
 {
     /* Plugin options */
     $options = get_site_option('blacklist_updater');
     /* Etag header */
     if (!empty($options['etag'])) {
         $args = array('headers' => array('If-None-Match' => $options['etag']));
     } else {
         $args = array();
     }
     /* Output debug infos */
     if (defined('WP_DEBUG_LOG') && WP_DEBUG_LOG) {
         error_log('Comment Blacklist requested from GitHub');
     }
     /* Start request */
     $response = wp_remote_get('https://raw.githubusercontent.com/splorp/wordpress-comment-blacklist/master/blacklist.txt', $args);
     /* Exit on error */
     if (is_wp_error($response)) {
         if (defined('WP_DEBUG_LOG') && WP_DEBUG_LOG) {
             error_log('Comment Blacklist response error: ' . $response->get_error_message());
         }
         return;
     }
     /* Check response code */
     if (wp_remote_retrieve_response_code($response) !== 200) {
         if (defined('WP_DEBUG_LOG') && WP_DEBUG_LOG) {
             error_log('Comment Blacklist is up to date');
         }
         return;
     }
     /* Output debug infos */
     if (defined('WP_DEBUG_LOG') && WP_DEBUG_LOG) {
         error_log('Comment Blacklist successfully downloaded');
     }
     /* Update blacklist */
     update_option('blacklist_keys', wp_remote_retrieve_body($response));
     /* Output debug infos */
     if (defined('WP_DEBUG_LOG') && WP_DEBUG_LOG) {
         error_log('Comment Blacklist successfully updated');
     }
     /* Get & validate Etag */
     $etag = preg_replace('/^[a-f0-9"]$/', '', wp_remote_retrieve_header($response, 'etag'));
     /* Update options */
     update_site_option('blacklist_updater', array('etag' => $etag));
 }
示例#29
0
/**
 * Downloads a url to a local temporary file using the WordPress HTTP Class.
 * Please note, That the calling function must unlink() the file.
 *
 * @since 2.5.0
 *
 * @param string $url the URL of the file to download
 * @param int $timeout The timeout for the request to download the file default 300 seconds
 * @return mixed WP_Error on failure, string Filename on success.
 */
function download_url( $url, $timeout = 300 ) {
	//WARNING: The file is not automatically deleted, The script must unlink() the file.
	if ( ! $url )
		return new WP_Error('http_no_url', __('Invalid URL Provided.'));

	$tmpfname = wp_tempnam($url);
	if ( ! $tmpfname )
		return new WP_Error('http_no_file', __('Could not create Temporary file.'));

	$response = wp_safe_remote_get( $url, array( 'timeout' => $timeout, 'stream' => true, 'filename' => $tmpfname ) );

	if ( is_wp_error( $response ) ) {
		unlink( $tmpfname );
		return $response;
	}

	if ( 200 != wp_remote_retrieve_response_code( $response ) ){
		unlink( $tmpfname );
		return new WP_Error( 'http_404', trim( wp_remote_retrieve_response_message( $response ) ) );
	}

	$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;
}
示例#30
0
 /**
  * Parse an HTTP response.
  *
  * @since 1.0.0
  *
  * @param  string    $response        HTTP response.
  * @param  int|array $expected_status Optional. Expected status code. Defaults to 200.
  * @return mixed
  */
 public function parse_response($response, $expected_status = 200)
 {
     if (is_wp_error($response)) {
         return $response;
     }
     $content = wp_remote_retrieve_body($response);
     $status = wp_remote_retrieve_response_code($response);
     $content_type = wp_remote_retrieve_header($response, 'content-type');
     #if ( 'application/json' === $content_type ) {
     // @todo Consider a strict mode to return JSON decoding errors.
     $content = $this->maybe_decode_json($content);
     #}
     if (isset($content->error) && isset($content->error_description)) {
         $data = isset($content->data) ? (array) $content->data : '';
         return new WP_Error($content->error, $content->error_description, $data);
     }
     if (!is_array($expected_status)) {
         $expected_status = array($expected_status);
     }
     if (!in_array($status, $expected_status)) {
         $this->log('error', 'Unexpected response code: {status}. Expected status: {expected_status}. Response: {response}', array('expected_status' => $expected_status, 'response' => $content, 'status' => $status));
         $message = sprintf(esc_html__('An unexpected status code was returned by the remote server. Status: %d', 'audiotheme-agent'), $status);
         return new WP_Error('unexpected_status', $message, array('body' => $content, 'status' => $status));
     }
     return $content;
 }