/** * Load the videos from a specified page. Is partly recursive. * * @param $url * * @return array */ public function _retrieve_videos($url) { $body = wp_remote_retrieve_body(wp_safe_remote_get($url)); if ('' === $body) { return false; } $dom = new DOMDocument(); libxml_use_internal_errors(true); $dom->loadHTML($body); libxml_clear_errors(); $finder = new DOMXPath($dom); $videos = $finder->query('//*[contains(@class, "video-list")]/li'); $older_videos = $finder->query('//*[contains(@class, "nav-previous")]/a'); $data = array('videos' => '', 'total_videos' => $videos->length); /** @var $reply \DOMNode */ foreach ($videos as $video) { $img = $finder->query('*[contains(@class, "video-thumbnail")]/img', $video)->item(0)->getAttribute('src'); $a_text = $finder->query('*[contains(@class, "video-description")]/h4/a', $video)->item(0)->nodeValue; $a_href = $finder->query('*[contains(@class, "video-description")]/h4/a', $video)->item(0)->getAttribute('href'); $event = $finder->query('*[contains(@class, "video-description")]/*[contains(@class, "video-events")]/a', $video)->item(0)->nodeValue; $description = $finder->query('*[contains(@class, "video-description")]/*[contains(@class, "video-excerpt")]/p', $video)->item(0)->nodeValue; preg_match('/^((?:\\S+\\s+){2}\\S+).*/', $description, $matches); $description = str_replace('—', '–', $description); $date = new DateTime($matches[1]); $data['videos'][] = array('title' => $a_text, 'date' => $date->format('Y-m-d'), 'url' => $a_href, 'image' => $img, 'event' => $event, 'description' => $description); } if ($older_videos->length) { $more_videos = $this->_retrieve_videos($older_videos->item(0)->getAttribute('href')); $data['videos'] = array_merge($data['videos'], $more_videos['videos']); $data['total_videos'] += $more_videos['total_videos']; } return $data; }
function _wpsc_get_exchange_rate($from, $to) { if ($from == $to) { return 1; } $key = "wpsc_exchange_{$from}_{$to}"; if ($rate = get_transient($key)) { return (double) $rate; } $url = add_query_arg(array('a' => '1', 'from' => $from, 'to' => $to), 'http://www.google.com/finance/converter'); $url = esc_url_raw(apply_filters('_wpsc_get_exchange_rate_service_endpoint', $url, $from, $to)); $response = wp_remote_retrieve_body(wp_safe_remote_get($url, array('timeout' => 10))); if (has_filter('_wpsc_get_exchange_rate')) { return (double) apply_filters('_wpsc_get_exchange_rate', $response, $from, $to); } if (empty($response)) { return $response; } else { $rate = explode('bld>', $response); $rate = explode($to, $rate[1]); $rate = trim($rate[0]); set_transient($key, $rate, DAY_IN_SECONDS); return (double) $rate; } }
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; }
public function import($attachment) { $saved_image = $this->_return_saved_image($attachment); if ($saved_image) { return $saved_image; } // Extract the file name and extension from the url $filename = basename($attachment['url']); if (function_exists('file_get_contents')) { $options = ['http' => ['user_agent' => 'Mozilla/5.0 (X11; Ubuntu; Linux i686 on x86_64; rv:49.0) Gecko/20100101 Firefox/49.0']]; $context = stream_context_create($options); $file_content = file_get_contents($attachment['url'], false, $context); } else { $file_content = wp_remote_retrieve_body(wp_safe_remote_get($attachment['url'])); } if (empty($file_content)) { return false; } $upload = wp_upload_bits($filename, null, $file_content); $post = ['post_title' => $filename, 'guid' => $upload['url']]; $info = wp_check_filetype($upload['file']); if ($info) { $post['post_mime_type'] = $info['type']; } else { // For now just return the origin attachment return $attachment; //return new \WP_Error( 'attachment_processing_error', __( 'Invalid file type', 'elementor' ) ); } $post_id = wp_insert_attachment($post, $upload['file']); wp_update_attachment_metadata($post_id, wp_generate_attachment_metadata($post_id, $upload['file'])); update_post_meta($post_id, '_elementor_source_image_hash', $this->_get_hash_image($attachment['url'])); $new_attachment = ['id' => $post_id, 'url' => $upload['url']]; $this->_replace_image_ids[$attachment['id']] = $new_attachment; return $new_attachment; }
protected function generate_metadata($url) { $response = wp_safe_remote_get($url); if (is_wp_error($response) || 200 !== wp_remote_retrieve_response_code($response)) { return false; } $body = wp_remote_retrieve_body($response); $metadata = sprintf('sha384-%s', base64_encode(hash('sha384', $body, true))); $this->meta->set($url, $metadata); return true; }
function test_get_language_pack_uri() { global $woocommerce_wpml, $woocommerce; //use stable version to test $pack_uri = $woocommerce_wpml->languages_upgrader->get_language_pack_uri('uk_UA', $woocommerce_wpml->get_stable_wc_version()); $response = wp_safe_remote_get($pack_uri, array('timeout' => 60)); $response_result = false; if (!is_wp_error($response) && $response['response']['code'] >= 200 && $response['response']['code'] < 300) { $response_result = true; } $this->assertTrue($response_result); }
/** * Handles output of the reports page in admin. */ public static function output() { if (false === ($addons = get_transient('woocommerce_addons_data'))) { $addons_json = wp_safe_remote_get('http://d3t0oesq8995hv.cloudfront.net/woocommerce-addons.json', array('user-agent' => 'WooCommerce Addons Page')); if (!is_wp_error($addons_json)) { $addons = json_decode(wp_remote_retrieve_body($addons_json)); if ($addons) { set_transient('woocommerce_addons_data', $addons, WEEK_IN_SECONDS); } } } include_once 'views/html-admin-page-addons.php'; }
public function refresh($url) { if (!is_string($url)) { throw new \InvalidArgumentException(sprintf('The url parameter is required to be string, was: %s', gettype($url))); } $r = false; $args = ['blocking' => false, 'headers' => apply_filters(sprintf('%s\\refresh_headers', __NAMESPACE__), ['X-Nginx-Cache-Purge' => '1']), 'sslverify' => apply_filters(sprintf('%s\\sslverify', __NAMESPACE__), true), 'timeout' => 1]; $response = wp_safe_remote_get($url, $args); if (!is_wp_error($response)) { $r = true; } return $r; }
/** * Upload image from URL. * * @since 2.6.0 * @param string $image_url * @return array|WP_Error Attachment data or error message. */ function wc_rest_upload_image_from_url($image_url) { $file_name = basename(current(explode('?', $image_url))); $parsed_url = @parse_url($image_url); // Check parsed URL. if (!$parsed_url || !is_array($parsed_url)) { return new WP_Error('woocommerce_rest_invalid_image_url', sprintf(__('Invalid URL %s.', 'woocommerce'), $image_url), array('status' => 400)); } // Ensure url is valid. $image_url = esc_url_raw($image_url); // Get the file. $response = wp_safe_remote_get($image_url, array('timeout' => 10)); if (is_wp_error($response)) { return new WP_Error('woocommerce_rest_invalid_remote_image_url', sprintf(__('Error getting remote image %s.', 'woocommerce'), $image_url) . ' ' . sprintf(__('Error: %s.', 'woocommerce'), $response->get_error_message()), array('status' => 400)); } elseif (200 !== wp_remote_retrieve_response_code($response)) { return new WP_Error('woocommerce_rest_invalid_remote_image_url', sprintf(__('Error getting remote image %s.', 'woocommerce'), $image_url), array('status' => 400)); } // Ensure we have a file name and type. $wp_filetype = wp_check_filetype($file_name, wc_rest_allowed_image_mime_types()); if (!$wp_filetype['type']) { $headers = wp_remote_retrieve_headers($response); if (isset($headers['content-disposition']) && strstr($headers['content-disposition'], 'filename=')) { $disposition = end(explode('filename=', $headers['content-disposition'])); $disposition = sanitize_file_name($disposition); $file_name = $disposition; } elseif (isset($headers['content-type']) && strstr($headers['content-type'], 'image/')) { $file_name = 'image.' . str_replace('image/', '', $headers['content-type']); } unset($headers); // Recheck filetype $wp_filetype = wp_check_filetype($file_name, wc_rest_allowed_image_mime_types()); if (!$wp_filetype['type']) { return new WP_Error('woocommerce_rest_invalid_image_type', __('Invalid image type.', 'woocommerce'), array('status' => 400)); } } // Upload the file. $upload = wp_upload_bits($file_name, '', wp_remote_retrieve_body($response)); if ($upload['error']) { return new WP_Error('woocommerce_rest_image_upload_error', $upload['error'], array('status' => 400)); } // Get filesize. $filesize = filesize($upload['file']); if (0 == $filesize) { @unlink($upload['file']); unset($upload); return new WP_Error('woocommerce_rest_image_upload_file_error', __('Zero size file downloaded.', 'woocommerce'), array('status' => 400)); } do_action('woocommerce_rest_api_uploaded_image_from_url', $upload, $image_url); return $upload; }
/** * @access protected * * @return bool */ public function _retrieve_data() { $profile = Helper::get_talent_meta($this->post, 'profile'); $url = str_replace('https://secure.gravatar.com/avatar/', 'https://www.gravatar.com/', $profile['avatar']); $url = remove_query_arg(array('s', 'd'), $url) . '.json'; $body = wp_remote_retrieve_body(wp_safe_remote_get($url)); if ('' === $body) { return false; } $body = json_decode($body); if (null === $body) { return false; } if (!isset($body->entry[0])) { return false; } $social = get_post_meta($this->post->ID, 'social', true); if (isset($social[0]) && is_array($social[0])) { foreach ($social[0] as $key => $value) { $social[$key] = $value; } unset($social[0]); } if (isset($body->entry[0]->accounts)) { foreach ($body->entry[0]->accounts as $account) { switch ($account->shortname) { case 'linkedin': $social['linkedin'] = $account->url; break; case 'twitter': case 'facebook': $social[$account->shortname] = $account->username; break; case 'google': $social['google-plus'] = $account->userid; break; case 'wordpress': $social['url'] = $account->url; default: break; } } } if (!empty($body->entry[0]->urls)) { $social['url'] = $body->entry[0]->urls[0]->value; } return (bool) update_post_meta($this->post->ID, 'social', $social); }
private function getJsonData($default_url) { // Setup our header and auth information $args = array('headers' => array('Accept' => 'application/json', 'Authorization' => 'Bearer ' . $this->api_key)); $response = wp_safe_remote_get($default_url, $args); $response['my_url'] = $default_url; $response['my_args'] = $args; if (is_wp_error($response)) { $json = json_encode($return->get_error_message()); } elseif (wp_remote_retrieve_response_code($response) != 200) { $json = json_encode(wp_remote_retrieve_body($response)); } else { $json = wp_remote_retrieve_body($response); } return $json; }
/** * @access protected * * @return bool */ public function _retrieve_data() { $results_url = add_query_arg(array('q' => 'props+' . $this->options['username'], 'noquickjump' => '1', 'changeset' => 'on'), 'https://core.trac.wordpress.org/search'); $results = wp_remote_retrieve_body(wp_safe_remote_get($results_url)); if (is_wp_error($results)) { return false; } $pattern = '/<meta name="totalResults" content="(\\d*)" \\/>/'; preg_match($pattern, $results, $matches); $count = 0; if (isset($matches[1])) { $count = intval($matches[1]); } $data = array('data' => $count, 'expiration' => time() + $this->expiration); update_post_meta($this->post->ID, '_changeset_count', $data); return $data; }
/** * Get section content for the addons screen. * * @param string $section_id * * @return array */ public static function get_section_data($section_id) { $section = self::get_section($section_id); $section_data = ''; if (!empty($section->endpoint)) { if (false === ($section_data = get_transient('wc_addons_section_' . $section_id))) { $raw_section = wp_safe_remote_get(esc_url_raw($section->endpoint), array('user-agent' => 'WooCommerce Addons Page')); if (!is_wp_error($raw_section)) { $section_data = json_decode(wp_remote_retrieve_body($raw_section)); if (!empty($section_data->products)) { set_transient('wc_addons_section_' . $section_id, $section_data, WEEK_IN_SECONDS); } } } } return apply_filters('woocommerce_addons_section_data', $section_data->products, $section_id); }
/** * Send a GET request to the given endpoint. * * @param string $endpoint Appended to $url_root to create the URL. * * @return array * * @throws \InvalidArgumentException When endpoint is not a string. * @throws \RuntimeException When $response is a WP_Error. */ public function get($endpoint) { if (!is_string($endpoint)) { throw new \InvalidArgumentException(sprintf('The endpoint parameter is required to be string, was: %s', gettype($endpoint))); } $endpoint = ltrim($endpoint, '/\\'); $url = sprintf('https://wpvulndb.com/api/v2/%s', $endpoint); $name = 'Soter Security Checker'; $version = '0.3.0'; $soter_url = 'https://github.com/ssnepenthe/soter'; $args = ['user-agent' => sprintf('%s | v%s | %s', $name, $version, $soter_url)]; $response = wp_safe_remote_get($url, $args); if (is_wp_error($response)) { throw new \RuntimeException(sprintf('WP Error: %s', $response->get_error_message())); } return [wp_remote_retrieve_response_code($response), wp_remote_retrieve_headers($response), wp_remote_retrieve_body($response)]; }
/** * @access protected * * @return bool */ public function _retrieve_data() { $results_url = add_query_arg(array('action' => 'query', 'list' => 'users', 'ususers' => $this->options['username'], 'usprop' => 'editcount', 'format' => 'json'), 'https://codex.wordpress.org/api.php'); $results = wp_remote_retrieve_body(wp_safe_remote_get($results_url)); if (is_wp_error($results)) { return false; } $raw = json_decode($results); if (isset($raw->query->users[0]->editcount)) { $count = (int) $raw->query->users[0]->editcount; } else { $count = 0; } $data = array('data' => $count, 'expiration' => time() + $this->expiration); update_post_meta($this->post->ID, '_codex_count', $data); return $data; }
private function produce($url = false) { if (empty($url)) { $url = $this->get('url'); } if (empty($url)) { return $this->error('empty url'); } $url = $this->add_ga_campain($url, 'fetch-data'); $resp = wp_safe_remote_get($url, array('timeout' => 30)); if (is_wp_error($resp)) { /** * if user can manage_options then display a real error message */ if (current_user_can('manage_options')) { return $this->error(false, $resp->get_error_message()); } else { return $this->error('http request failed'); } } if (200 != $resp['response']['code']) { return $this->error('wrong response status'); } $title_temp = preg_split('/<h1>/', $resp['body']); $title_temp_temp = isset($title_temp[1]) ? preg_split('@</h1>@', $title_temp[1]) : array(''); $title = $title_temp_temp[0]; $body = ''; $containers = preg_split('/<div class="container">/', $resp['body']); foreach ($containers as $container) { if (!preg_match('/<div class="col-sm-[\\d]+ post-content[^>]+>/', $container)) { continue; } $body = $container; } if (empty($body)) { return $this->error('empty body'); } $body = preg_split('/<aside/', $body); $body = $body[0]; if (empty($body)) { return $this->error('empty body'); } $body = sprintf('<h1 class="title">%s</h1><div class="container"><div class="post-content">%s', $title, $body); set_transient($this->cache, $body, 14 * DAY_IN_SECONDS); return $body; }
/** * Handles output of the upsells in admin. * * Data to display is gotten from a JSON file on a remote server. JSON data structure is shown below and can be checked at http://jsoneditoronline.org/. * * { * "all": { * "plugin-name": { * "id": "plugin-name", * "link": "http://molongui.amitzy.com/plugins/plugin-name", * "price": "123.00", * "name": "Plugin Name", * "image": "http://molongui.amitzy.com/plugins/img/banner_en_US.png", * "excerpt": "Plugin short description in English.", * "name_es_ES": "Nombre en castellano", * "image_es_ES": "http://molongui.amitzy.com/plugins/img/banner_es_ES.png", * "excerpt_es_ES": "Breve descripción del plugin en castellano." * } * }, * "featured": {}, * "popular": {}, * "free": {}, * "premium": {} * } * * Images size must be 300x163px. * * @acess public * @param string $category The category to show plugins from. * @param mixed $num_items The number of featured plugins to show. * @param int $num_words Number of words to use as plugin description. * @param string $more Text to add when ellipsing plugin description. * @since 1.0.0 * @version 1.0.0 */ public static function output($category = 'all', $num_items = 'all', $num_words = 36, $more = null) { // Load configuration $config = (include MOLONGUI_AUTHORSHIP_DIR . "/config/upsell.php"); // Premium plugins download data from Molongui server if (MOLONGUI_AUTHORSHIP_LICENSE != 'free') { // If cached data, don't download it again if (false === ($upsells = get_site_transient('molongui_sw_data'))) { // Get data from remote server $upsell_json = wp_safe_remote_get($config['server']['url'], array('user-agent' => $config['server']['agent'])); if (!is_wp_error($upsell_json)) { // Decode data to a stdClass object $upsells = json_decode(wp_remote_retrieve_body($upsell_json)); // Store data (cache) for future uses (within this week time) if ($upsells) { set_site_transient('molongui_sw_data', $upsells, WEEK_IN_SECONDS); } } } } else { // Get data from local file $upsell_json = file_get_contents($config['local']['url']); // Set correct local path $upsell_json = str_replace('%%MOLONGUI_PLUGIN_URL%%', MOLONGUI_AUTHORSHIP_URL, $upsell_json); // Decode data to a stdClass object $upsells = json_decode($upsell_json); } // Check there is data to show $tmp = (array) $upsells->{$category}; if (!empty($tmp)) { // Avoid current plugin to be displayed if ($upsells->{$category}->{MOLONGUI_AUTHORSHIP_ID}->id) { unset($upsells->{$category}->{MOLONGUI_AUTHORSHIP_ID}); } // Slice array so just $num_items are displayed if (isset($num_items) && $num_items != 'all' && $num_items > 0) { $upsells->{$category} = array_slice((array) $upsells->{$category}, 0, $num_items); } // DEBUG: Used to display results for development //echo "<pre>"; print_r($upsells); echo "</pre>"; // Display data include_once MOLONGUI_AUTHORSHIP_DIR . '/admin/views/html-admin-page-upsells.php'; } }
function siw_postcode_lookup() { $api_key = siw_get_postcode_api_key(); $postcode = strtoupper(siw_strip_url($_GET['postcode'])); $houseNumber = siw_strip_url($_GET['housenumber']); $url = 'https://postcode-api.apiwise.nl/v2/addresses/?postcode=' . str_replace(' ', '', $postcode) . '&number=' . $houseNumber; $args = array('timeout' => 10, 'redirection' => 0, 'headers' => array('X-Api-Key' => $api_key)); $response = json_decode(wp_safe_remote_get($url, $args)['body']); if ($response->_embedded->addresses) { $street = $response->_embedded->addresses[0]->street; $town = $response->_embedded->addresses[0]->city->label; $data = array('success' => 1, 'resource' => array('street' => $street, 'town' => $town)); } else { $data = array('success' => 0); } $result = json_encode($data); echo $result; die; }
/** * @access protected * * @return bool */ public function _retrieve_data() { $url = 'https://wordpress.org/support/profile/' . $this->options['username']; $body = wp_remote_retrieve_body(wp_safe_remote_get($url)); if ('' === $body) { return false; } $dom = new DOMDocument(); libxml_use_internal_errors(true); $dom->loadHTML($body); libxml_clear_errors(); $finder = new DOMXPath($dom); $recent_replies = $finder->query('//div[@id="user-replies"]/ol/li'); $threads_started = $finder->query('//div[@id="user-threads"]/ol/li'); $page_numbers = $finder->query('//*[contains(@class, "page-numbers")]'); $data = array('replies' => '', 'threads' => '', 'total_replies' => ''); if ($page_numbers->length) { $total_pages = $page_numbers->item($page_numbers->length / 2 - 2)->nodeValue; // It's not 100% accurate, as there may be not so many replies on the last page $data['total_replies'] = $total_pages * $recent_replies->length; } else { $data['total_replies'] = $recent_replies->length; } /** @var $reply \DOMNode */ foreach ($recent_replies as $reply) { $a_text = $finder->query('a', $reply)->item(0)->nodeValue; $a_href = $finder->query('a', $reply)->item(0)->getAttribute('href'); $node_text = $finder->query('text()', $reply)->item(1)->nodeValue; preg_match('/((([^ ]*)[\\s.]+){3})$/', $node_text, $matches); $data['replies'][] = array('title' => $a_text, 'url' => esc_url_raw($a_href), 'date' => str_replace('.', '', trim($matches[0]))); } foreach ($threads_started as $thread) { $a_text = $finder->query('a', $thread)->item(0)->nodeValue; $a_href = $finder->query('a', $thread)->item(0)->getAttribute('href'); $node_text = $finder->query('text()', $thread)->item(1)->nodeValue; preg_match('/((([^ ]*)[\\s.]+){3})$/', $node_text, $matches); $data['threads'][] = array('title' => $a_text, 'url' => esc_url_raw($a_href), 'date' => str_replace('.', '', trim($matches[0]))); } $data = array('data' => $data, 'expiration' => time() + $this->expiration); update_post_meta($this->post->ID, '_forums', $data); return $data; }
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.', 'themify-flow')); } $tmpfname = wp_tempnam($url); if (!$tmpfname) { return new WP_Error('http_no_file', __('Could not create Temporary file.', 'themify-flow')); } $response = wp_safe_remote_get($url, array('cookies' => $this->cookies, '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))); } return $tmpfname; }
/** * Attempts to find oEmbed provider discovery <link> tags at the given URL. * * @param string $url The URL that should be inspected for discovery <link> tags. * @return bool|string False on failure, otherwise the oEmbed provider URL. */ function discover($url) { $providers = array(); // Fetch URL content $strHTML = wp_safe_remote_get($url); if ($html = wp_remote_retrieve_body(wp_safe_remote_get($strHTML))) { // <link> types that contain oEmbed provider URLs $linktypes = apply_filters('oembed_linktypes', array('application/json+oembed' => 'json', 'text/xml+oembed' => 'xml', 'application/xml+oembed' => 'xml')); // Strip <body> $html = substr($html, 0, stripos($html, '</head>')); // Do a quick check $tagfound = false; foreach ($linktypes as $linktype => $format) { if (stripos($html, $linktype)) { $tagfound = true; break; } } if ($tagfound && preg_match_all('/<link([^<>]+)>/i', $html, $links)) { foreach ($links[1] as $link) { $atts = shortcode_parse_atts($link); if (!empty($atts['type']) && !empty($linktypes[$atts['type']]) && !empty($atts['href'])) { $providers[$linktypes[$atts['type']]] = $atts['href']; // Stop here if it's JSON (that's all we need) if ('json' == $linktypes[$atts['type']]) { break; } } } } } // JSON is preferred to XML if (!empty($providers['json'])) { return $providers['json']; } elseif (!empty($providers['xml'])) { return $providers['xml']; } else { return false; } }
/** * Access API Correios. * * @param string $tracking_code. * * @return SimpleXMLElement|stdClass History Tracking code. */ protected function get_tracking_history($tracking_code) { $user_data = $this->get_user_data(); $args = apply_filters('woocommerce_correios_tracking_args', array('Usuario' => $user_data['login'], 'Senha' => $user_data['password'], 'Tipo' => 'L', 'Resultado' => 'T', 'Objetos' => $tracking_code)); $api_url = $this->get_tracking_history_api_url(); $request_url = add_query_arg($args, $api_url); $params = array('timeout' => 30); $this->logger('Requesting tracking history in: ' . print_r($request_url, true)); $response = wp_safe_remote_get($request_url, $params); if (!is_wp_error($response) && $response['response']['code'] >= 200 && $response['response']['code'] < 300) { try { $tracking_history = WC_Correios_Connect::safe_load_xml($response['body'], LIBXML_NOCDATA); } catch (Exception $e) { $this->logger('Tracking history invalid XML: ' . $e->getMessage()); } } else { $tracking_history = new stdClass(); $tracking_history->error = true; } $this->logger('Tracking history response: ' . print_r($tracking_history, true)); return $tracking_history; }
/** * A one-stop shop for the URL requests to zKillboard * * @param String $url * * @return mixed|string|WP_Error */ private function _make_request($url) { $url = esc_url($url); $hash = md5($url); $body = get_transient($hash); error_log(sprintf('[%s] - %s', current_time('Y-m-d h:i A'), $url)); // Cache buster if (strpos($url, 'nocache')) { $url = str_replace('/nocache/1', '', $url); $body = false; } if (false === $body) { $remote_get = wp_safe_remote_get($url, array('user-agent' => 'WordPress/Plugish.com - Maintainer: xPhyrax - jjwood2004@gmail.com', 'headers' => array('Accept-Encoding: gzip'))); $code = wp_remote_retrieve_response_code($remote_get); if (200 !== $code) { return new WP_Error('http_not_200', sprintf('Got a %d response code when expecting 200 for URL: 5s', $code, $url)); } $body = wp_remote_retrieve_body($remote_get); set_transient($hash, $body, 30 * 60); } return $body; }
public static function downloadLang() { if (!empty(self::$lang_load)) { $time = get_option(WPADM_LANG_ . 'time-update'); if (isset($time['check_time']) && $time['check_time'] <= time() || !isset($time['check_time']) || !file_exists(self::$lang_dir . self::$lang_load . '.php')) { if (!function_exists('wp_safe_remote_get')) { include_once ABSPATH . WPINC . '/http.php'; } $load = wp_safe_remote_get(self::$url . self::$lang_load . '.php'); if (isset($load['response']['code']) && $load['response']['code'] == '200') { @preg_match("/Date create - ([0-9\\.]+)/", $load['body'], $date); if (!isset($time['date']) || $time['date'] != $date[1] || !file_exists(self::$lang_dir . self::$lang_load . '.php')) { if (isset($date[1])) { self::updateDate($date[1]); } else { self::updateDate(date('d.m.Y')); } file_put_contents(self::$lang_dir . self::$lang_load . '.php', $load['body']); } } } } }
protected static function download($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.', 'wp-e-commerce')); } $tmpfname = wp_tempnam($url); if (!$tmpfname) { return new WP_Error('http_no_file', __('Could not create Temporary file.', 'wp-e-commerce')); } $args = array('timeout' => $timeout, 'stream' => true, 'filename' => $tmpfname, 'headers' => array('X-WP-Domain' => Sputnik_API::domain()), 'user-agent' => 'WP eCommerce Marketplace: ' . WPSC_VERSION); Sputnik_API::sign_download($url, $args); $response = wp_safe_remote_get($url, $args); 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))); } return $tmpfname; }
/** * Upload image from URL. * * @throws WC_API_Exception * * @since 2.5.0 * @param string $image_url * @param string $upload_for * @return int|WP_Error Attachment id */ protected function upload_image_from_url($image_url, $upload_for = 'product_image') { $file_name = basename(current(explode('?', $image_url))); $wp_filetype = wp_check_filetype($file_name, null); $parsed_url = @parse_url($image_url); // Check parsed URL. if (!$parsed_url || !is_array($parsed_url)) { throw new WC_API_Exception('woocommerce_api_invalid_' . $upload_for, sprintf(__('Invalid URL %s', 'woocommerce'), $image_url), 400); } // Ensure url is valid $image_url = str_replace(' ', '%20', $image_url); // Get the file $response = wp_safe_remote_get($image_url, array('timeout' => 10)); if (is_wp_error($response) || 200 !== wp_remote_retrieve_response_code($response)) { throw new WC_API_Exception('woocommerce_api_invalid_remote_' . $upload_for, sprintf(__('Error getting remote image %s', 'woocommerce'), $image_url), 400); } // Ensure we have a file name and type if (!$wp_filetype['type']) { $headers = wp_remote_retrieve_headers($response); if (isset($headers['content-disposition']) && strstr($headers['content-disposition'], 'filename=')) { $disposition = end(explode('filename=', $headers['content-disposition'])); $disposition = sanitize_file_name($disposition); $file_name = $disposition; } elseif (isset($headers['content-type']) && strstr($headers['content-type'], 'image/')) { $file_name = 'image.' . str_replace('image/', '', $headers['content-type']); } unset($headers); } // Upload the file $upload = wp_upload_bits($file_name, '', wp_remote_retrieve_body($response)); if ($upload['error']) { throw new WC_API_Exception('woocommerce_api_' . $upload_for . '_upload_error', $upload['error'], 400); } // Get filesize $filesize = filesize($upload['file']); if (0 == $filesize) { @unlink($upload['file']); unset($upload); throw new WC_API_Exception('woocommerce_api_' . $upload_for . '_upload_file_error', __('Zero size file downloaded', 'woocommerce'), 400); } unset($response); return $upload; }
/** * Retrieves a pingback and registers it. * * @since 1.5.0 * * @param array $args Method parameters. * @return string|IXR_Error */ public function pingback_ping($args) { global $wpdb; /** This action is documented in wp-includes/class-wp-xmlrpc-server.php */ do_action('xmlrpc_call', 'pingback.ping'); $this->escape($args); $pagelinkedfrom = $args[0]; $pagelinkedto = $args[1]; $title = ''; $pagelinkedfrom = str_replace('&', '&', $pagelinkedfrom); $pagelinkedto = str_replace('&', '&', $pagelinkedto); $pagelinkedto = str_replace('&', '&', $pagelinkedto); /** * Filter the pingback source URI. * * @since 3.6.0 * * @param string $pagelinkedfrom URI of the page linked from. * @param string $pagelinkedto URI of the page linked to. */ $pagelinkedfrom = apply_filters('pingback_ping_source_uri', $pagelinkedfrom, $pagelinkedto); if (!$pagelinkedfrom) { return $this->pingback_error(0, __('A valid URL was not provided.')); } // Check if the page linked to is in our site $pos1 = strpos($pagelinkedto, str_replace(array('http://www.', 'http://', 'https://www.', 'https://'), '', get_option('home'))); if (!$pos1) { return $this->pingback_error(0, __('Is there no link to us?')); } // let's find which post is linked to // FIXME: does url_to_postid() cover all these cases already? // if so, then let's use it and drop the old code. $urltest = parse_url($pagelinkedto); if ($post_ID = url_to_postid($pagelinkedto)) { // $way } elseif (isset($urltest['path']) && preg_match('#p/[0-9]{1,}#', $urltest['path'], $match)) { // the path defines the post_ID (archives/p/XXXX) $blah = explode('/', $match[0]); $post_ID = (int) $blah[1]; } elseif (isset($urltest['query']) && preg_match('#p=[0-9]{1,}#', $urltest['query'], $match)) { // the querystring defines the post_ID (?p=XXXX) $blah = explode('=', $match[0]); $post_ID = (int) $blah[1]; } elseif (isset($urltest['fragment'])) { // an #anchor is there, it's either... if (intval($urltest['fragment'])) { // ...an integer #XXXX (simplest case) $post_ID = (int) $urltest['fragment']; } elseif (preg_match('/post-[0-9]+/', $urltest['fragment'])) { // ...a post id in the form 'post-###' $post_ID = preg_replace('/[^0-9]+/', '', $urltest['fragment']); } elseif (is_string($urltest['fragment'])) { // ...or a string #title, a little more complicated $title = preg_replace('/[^a-z0-9]/i', '.', $urltest['fragment']); $sql = $wpdb->prepare("SELECT ID FROM {$wpdb->posts} WHERE post_title RLIKE %s", $title); if (!($post_ID = $wpdb->get_var($sql))) { // returning unknown error '0' is better than die()ing return $this->pingback_error(0, ''); } } } else { // TODO: Attempt to extract a post ID from the given URL return $this->pingback_error(33, __('The specified target URL cannot be used as a target. It either doesn’t exist, or it is not a pingback-enabled resource.')); } $post_ID = (int) $post_ID; $post = get_post($post_ID); if (!$post) { // Post_ID not found return $this->pingback_error(33, __('The specified target URL cannot be used as a target. It either doesn’t exist, or it is not a pingback-enabled resource.')); } if ($post_ID == url_to_postid($pagelinkedfrom)) { return $this->pingback_error(0, __('The source URL and the target URL cannot both point to the same resource.')); } // Check if pings are on if (!pings_open($post)) { return $this->pingback_error(33, __('The specified target URL cannot be used as a target. It either doesn’t exist, or it is not a pingback-enabled resource.')); } // Let's check that the remote site didn't already pingback this entry if ($wpdb->get_results($wpdb->prepare("SELECT * FROM {$wpdb->comments} WHERE comment_post_ID = %d AND comment_author_url = %s", $post_ID, $pagelinkedfrom))) { return $this->pingback_error(48, __('The pingback has already been registered.')); } // very stupid, but gives time to the 'from' server to publish ! sleep(1); $remote_ip = preg_replace('/[^0-9a-fA-F:., ]/', '', $_SERVER['REMOTE_ADDR']); /** This filter is documented in wp-includes/class-http.php */ $user_agent = apply_filters('http_headers_useragent', 'WordPress/' . $GLOBALS['wp_version'] . '; ' . get_bloginfo('url')); // Let's check the remote site $http_api_args = array('timeout' => 10, 'redirection' => 0, 'limit_response_size' => 153600, 'user-agent' => "{$user_agent}; verifying pingback from {$remote_ip}", 'headers' => array('X-Pingback-Forwarded-For' => $remote_ip)); $request = wp_safe_remote_get($pagelinkedfrom, $http_api_args); $linea = wp_remote_retrieve_body($request); if (!$linea) { return $this->pingback_error(16, __('The source URL does not exist.')); } /** * Filter the pingback remote source. * * @since 2.5.0 * * @param string $linea Response object for the page linked from. * @param string $pagelinkedto URL of the page linked to. */ $linea = apply_filters('pre_remote_source', $linea, $pagelinkedto); // Work around bug in strip_tags(): $linea = str_replace('<!DOC', '<DOC', $linea); $linea = preg_replace('/[\\r\\n\\t ]+/', ' ', $linea); // normalize spaces $linea = preg_replace("/<\\/*(h1|h2|h3|h4|h5|h6|p|th|td|li|dt|dd|pre|caption|input|textarea|button|body)[^>]*>/", "\n\n", $linea); preg_match('|<title>([^<]*?)</title>|is', $linea, $matchtitle); $title = $matchtitle[1]; if (empty($title)) { return $this->pingback_error(32, __('We cannot find a title on that page.')); } $linea = strip_tags($linea, '<a>'); // just keep the tag we need $p = explode("\n\n", $linea); $preg_target = preg_quote($pagelinkedto, '|'); foreach ($p as $para) { if (strpos($para, $pagelinkedto) !== false) { // it exists, but is it a link? preg_match("|<a[^>]+?" . $preg_target . "[^>]*>([^>]+?)</a>|", $para, $context); // If the URL isn't in a link context, keep looking if (empty($context)) { continue; } // We're going to use this fake tag to mark the context in a bit // the marker is needed in case the link text appears more than once in the paragraph $excerpt = preg_replace('|\\</?wpcontext\\>|', '', $para); // prevent really long link text if (strlen($context[1]) > 100) { $context[1] = substr($context[1], 0, 100) . '…'; } $marker = '<wpcontext>' . $context[1] . '</wpcontext>'; // set up our marker $excerpt = str_replace($context[0], $marker, $excerpt); // swap out the link for our marker $excerpt = strip_tags($excerpt, '<wpcontext>'); // strip all tags but our context marker $excerpt = trim($excerpt); $preg_marker = preg_quote($marker, '|'); $excerpt = preg_replace("|.*?\\s(.{0,100}{$preg_marker}.{0,100})\\s.*|s", '$1', $excerpt); $excerpt = strip_tags($excerpt); // YES, again, to remove the marker wrapper break; } } if (empty($context)) { // Link to target not found return $this->pingback_error(17, __('The source URL does not contain a link to the target URL, and so cannot be used as a source.')); } $pagelinkedfrom = str_replace('&', '&', $pagelinkedfrom); $context = '[…] ' . esc_html($excerpt) . ' […]'; $pagelinkedfrom = $this->escape($pagelinkedfrom); $comment_post_ID = (int) $post_ID; $comment_author = $title; $comment_author_email = ''; $this->escape($comment_author); $comment_author_url = $pagelinkedfrom; $comment_content = $context; $this->escape($comment_content); $comment_type = 'pingback'; $commentdata = compact('comment_post_ID', 'comment_author', 'comment_author_url', 'comment_author_email', 'comment_content', 'comment_type'); $comment_ID = wp_new_comment($commentdata); /** * Fires after a post pingback has been sent. * * @since 0.71 * * @param int $comment_ID Comment ID. */ do_action('pingback_post', $comment_ID); return sprintf(__('Pingback from %1$s to %2$s registered. Keep the web talking! :-)'), $pagelinkedfrom, $pagelinkedto); }
/** * Manual language update */ public function manual_language_update() { if (is_admin() && current_user_can('update_plugins') && isset($_GET['page']) && in_array($_GET['page'], array('wc-status', 'wc-setup')) && isset($_GET['action']) && 'translation_upgrade' == $_GET['action']) { $page = 'wc-status&tab=tools'; $wpnonce = 'debug_action'; if ('wc-setup' == $_GET['page']) { $page = 'wc-setup'; $wpnonce = 'setup_language'; } $url = wp_nonce_url(admin_url('admin.php?page=' . $page . '&action=translation_upgrade'), 'language_update'); $tools_url = admin_url('admin.php?page=' . $page); if (!isset($_REQUEST['_wpnonce']) && wp_verify_nonce($_REQUEST['_wpnonce'], $wpnonce)) { wp_redirect(add_query_arg(array('translation_updated' => 2), $tools_url)); exit; } if (false === ($creds = request_filesystem_credentials($url, '', false, false, null))) { wp_redirect(add_query_arg(array('translation_updated' => 3), $tools_url)); exit; } if (!WP_Filesystem($creds)) { request_filesystem_credentials($url, '', true, false, null); wp_redirect(add_query_arg(array('translation_updated' => 3), $tools_url)); exit; } // Download the language pack $response = wp_safe_remote_get(self::get_language_package_uri(), array('timeout' => 60)); if (!is_wp_error($response) && $response['response']['code'] >= 200 && $response['response']['code'] < 300) { global $wp_filesystem; $upload_dir = wp_upload_dir(); $file = trailingslashit($upload_dir['path']) . get_locale() . '.zip'; // Save the zip file if (!$wp_filesystem->put_contents($file, $response['body'], FS_CHMOD_FILE)) { wp_redirect(add_query_arg(array('translation_updated' => 3), $tools_url)); exit; } // Unzip the file to wp-content/languages/plugins directory $dir = trailingslashit(WP_LANG_DIR) . 'plugins/'; $unzip = unzip_file($file, $dir); if (true !== $unzip) { wp_redirect(add_query_arg(array('translation_updated' => 3), $tools_url)); exit; } // Delete the package file $wp_filesystem->delete($file); // Update the language pack version $this->save_language_version(); // Redirect and show a success message wp_redirect(add_query_arg(array('translation_updated' => 1), $tools_url)); exit; } else { // Don't have a valid package for the current language! wp_redirect(add_query_arg(array('translation_updated' => 4), $tools_url)); exit; } } }
/** * HTTP request for URI to retrieve content. * * @since 1.5.1 * * @see wp_safe_remote_get() * * @param string $uri URI/URL of web page to retrieve. * @return false|string HTTP content. False on failure. */ function wp_remote_fopen($uri) { $parsed_url = @parse_url($uri); if (!$parsed_url || !is_array($parsed_url)) { return false; } $options = array(); $options['timeout'] = 10; $response = wp_safe_remote_get($uri, $options); if (is_wp_error($response)) { return false; } return wp_remote_retrieve_body($response); }
/** * Fetches result from an oEmbed provider for a specific format and complete provider URL * * @since 3.0.0 * @access private * @param string $provider_url_with_args URL to the provider with full arguments list (url, maxheight, etc.) * @param string $format Format to use * @return bool|object False on failure, otherwise the result in the form of an object. */ private function _fetch_with_format($provider_url_with_args, $format) { $provider_url_with_args = add_query_arg('format', $format, $provider_url_with_args); /** This filter is documented in wp-includes/class-oembed.php */ $args = apply_filters('oembed_remote_get_args', array(), $provider_url_with_args); $response = wp_safe_remote_get($provider_url_with_args, $args); if (501 == wp_remote_retrieve_response_code($response)) { return new WP_Error('not-implemented'); } if (!($body = wp_remote_retrieve_body($response))) { return false; } $parse_method = "_parse_{$format}"; return $this->{$parse_method}($body); }