/**
  * Sends and receives data to and from the server API
  *
  * @access public
  * @since  1.0.0
  * @return object $response
  */
 public function plugin_information($args)
 {
     $target_url = $this->create_upgrade_api_url($args);
     $apisslverify = get_option('mainwp_api_sslVerifyCertificate') === false || get_option('mainwp_api_sslVerifyCertificate') == 1 ? 1 : 0;
     $request = wp_remote_get($target_url, array('timeout' => 50, 'sslverify' => $apisslverify));
     //      $request = wp_remote_post( MainWP_Api_Manager::instance()->getUpgradeUrl() . 'wc-api/upgrade-api/', array('body' => $args) );
     if (is_wp_error($request) || wp_remote_retrieve_response_code($request) != 200) {
         return false;
     }
     $response = unserialize(wp_remote_retrieve_body($request));
     /**
      * For debugging errors from the API
      * For errors like: unserialize(): Error at offset 0 of 170 bytes
      * Comment out $response above first
      */
     // $response = wp_remote_retrieve_body( $request );
     // print_r($response); exit;
     if (is_object($response)) {
         if (isset($response->package)) {
             $response->package = apply_filters('mainwp_api_manager_upgrade_url', $response->package);
         }
         return $response;
     } else {
         return false;
     }
 }
 public function test_get_issuers()
 {
     add_filter('pre_http_request', array($this, 'pre_http_request'), 10, 3);
     $url = 'https://www.targetpay.com/ideal/getissuers.php?format=xml';
     $response = wp_remote_get($url);
     $this->assertEquals(200, wp_remote_retrieve_response_code($response));
 }
 public function __construct($sURL, $iTimeout = 10, $iRedirects = 5, $aHeaders = null, $sUserAgent = null, $bForceFsockOpen = false)
 {
     $this->timeout = $iTimeout;
     $this->redirects = $iRedirects;
     $this->headers = $sUserAgent;
     $this->useragent = $sUserAgent;
     $this->url = $sURL;
     // If the scheme is not http or https.
     if (!preg_match('/^http(s)?:\\/\\//i', $sURL)) {
         $this->error = '';
         $this->success = false;
         return;
     }
     // Arguments
     $aArgs = array('timeout' => $this->timeout, 'redirection' => $this->redirects, true, 'sslverify' => false);
     if (!empty($this->headers)) {
         $aArgs['headers'] = $this->headers;
     }
     if (SIMPLEPIE_USERAGENT != $this->useragent) {
         $aArgs['user-agent'] = $this->useragent;
     }
     // Request
     $res = function_exists('wp_safe_remote_request') ? wp_safe_remote_request($sURL, $aArgs) : wp_remote_get($sURL, $aArgs);
     if (is_wp_error($res)) {
         $this->error = 'WP HTTP Error: ' . $res->get_error_message();
         $this->success = false;
         return;
     }
     $this->headers = wp_remote_retrieve_headers($res);
     $this->body = wp_remote_retrieve_body($res);
     $this->status_code = wp_remote_retrieve_response_code($res);
 }
 /**
  * Check GitHub repo for updated language packs
  *
  * @param      $transient
  * @param bool $force
  * @return mixed
  */
 public function update_check($transient, $force = false)
 {
     $locale = get_locale();
     // pre_set_site_transient_update_plugins is called twice
     // we only want to act on the second run
     // also only continue for non English locales
     if (empty($transient->checked) || strpos($locale, 'en_') === 0) {
         return $transient;
     }
     // get package.json from github
     $request = wp_remote_get($this->github_url . 'package.json', array('timeout' => 45));
     if (is_wp_error($request) || wp_remote_retrieve_response_code($request) != 200) {
         return $transient;
     }
     // see if translation pack exists
     $response = json_decode(wp_remote_retrieve_body($request));
     $transient = apply_filters('woocommerce_pos_language_packs_upgrade', $transient, $response, $this->github_url, $force);
     if (!isset($response->locales->{$locale})) {
         return $transient;
     }
     // compare
     $new = strtotime($response->locales->{$locale});
     $options = get_option('woocommerce_pos_language_packs');
     if (isset($options[$locale]) && $options[$locale] >= $new && !$force) {
         return $transient;
     }
     // update required
     $transient->translations[] = array('type' => 'plugin', 'slug' => 'woocommerce-pos', 'language' => $locale, 'version' => WC_POS_VERSION, 'updated' => date('Y-m-d H:i:s', $new), 'package' => $this->github_url . 'packages/woocommerce-pos-' . $locale . '.zip', 'autoupdate' => 1);
     return $transient;
 }
Example #5
0
 protected function getURL($url, $postParams = array())
 {
     wordfence::status(4, 'info', "Calling Wordfence API v" . WORDFENCE_API_VERSION . ":" . $url);
     if (!function_exists('wp_remote_post')) {
         require_once ABSPATH . WPINC . 'http.php';
     }
     $ssl_verify = (bool) wfConfig::get('ssl_verify');
     $args = array('timeout' => 900, 'user-agent' => "Wordfence.com UA " . (defined('WORDFENCE_VERSION') ? WORDFENCE_VERSION : '[Unknown version]'), 'body' => $postParams, 'sslverify' => $ssl_verify);
     if (!$ssl_verify) {
         // Some versions of cURL will complain that SSL verification is disabled but the CA bundle was supplied.
         $args['sslcertificates'] = false;
     }
     $response = wp_remote_post($url, $args);
     $this->lastHTTPStatus = (int) wp_remote_retrieve_response_code($response);
     if (is_wp_error($response)) {
         $error_message = $response->get_error_message();
         throw new Exception("There was an " . ($error_message ? '' : 'unknown ') . "error connecting to the the Wordfence scanning servers" . ($error_message ? ": {$error_message}" : '.'));
     }
     if (!empty($response['response']['code'])) {
         $this->lastHTTPStatus = (int) $response['response']['code'];
     }
     if (200 != $this->lastHTTPStatus) {
         throw new Exception("We received an error response when trying to contact the Wordfence scanning servers. The HTTP status code was [{$this->lastHTTPStatus}]");
     }
     $this->curlContent = wp_remote_retrieve_body($response);
     return $this->curlContent;
 }
 function fetch_feed($username, $slice = 8)
 {
     $barcelona_remote_url = esc_url('http://instagram.com/' . trim(strtolower($username)));
     $barcelona_transient_key = 'barcelona_instagram_feed_' . sanitize_title_with_dashes($username);
     $slice = absint($slice);
     if (false === ($barcelona_result_data = get_transient($barcelona_transient_key))) {
         $barcelona_remote = wp_remote_get($barcelona_remote_url);
         if (is_wp_error($barcelona_remote) || 200 != wp_remote_retrieve_response_code($barcelona_remote)) {
             return new WP_Error('not-connected', esc_html__('Unable to communicate with Instagram.', 'barcelona'));
         }
         preg_match('#window\\.\\_sharedData\\s\\=\\s(.*?)\\;\\<\\/script\\>#', $barcelona_remote['body'], $barcelona_match);
         if (!empty($barcelona_match)) {
             $barcelona_data = json_decode(end($barcelona_match), true);
             if (is_array($barcelona_data) && isset($barcelona_data['entry_data']['ProfilePage'][0]['user']['media']['nodes'])) {
                 $barcelona_result_data = $barcelona_data['entry_data']['ProfilePage'][0]['user']['media']['nodes'];
             }
         }
         if (is_array($barcelona_result_data)) {
             set_transient($barcelona_transient_key, $barcelona_result_data, 60 * 60 * 2);
         }
     }
     if (empty($barcelona_result_data)) {
         return new WP_Error('no-images', esc_html__('Instagram did not return any images.', 'barcelona'));
     }
     return array_slice($barcelona_result_data, 0, $slice);
 }
Example #7
0
function _manually_load_plugin()
{
    $host = getenv('ES_HOST');
    $host = preg_replace('/(^https:\\/\\/|^http:\\/\\/)/is', '', $host);
    $port = getenv('ES_PORT');
    if (empty($host)) {
        $host = 'localhost';
    }
    if (empty($port)) {
        $port = 9200;
    }
    define('ES_HOST', $host);
    define('ES_PORT', $port);
    require dirname(dirname(__FILE__)) . '/wp-elasticsearch.php';
    $tries = 5;
    $sleep = 3;
    do {
        $response = wp_remote_get(esc_url(ES_HOST) . ':' . ES_PORT);
        if (200 == wp_remote_retrieve_response_code($response)) {
            // Looks good!
            break;
        } else {
            printf("\nInvalid response from ES, sleeping %d seconds and trying again...\n", intval($sleep));
            sleep($sleep);
        }
    } while (--$tries);
    if (200 != wp_remote_retrieve_response_code($response)) {
        exit('Could not connect to Elasticsearch server.');
    }
}
 /**
  * Request data from the thir party API.
  *
  * @since 1.5.4
  * @param string $base_url 	Base URL where API is available
  * @param string $api_key 	API Key provided by this service
  * @param string $endpoint 	Method to request available from this service.
  * @param array $params 	Data to be passed to API
  * @return array|object 	The API response.
  */
 private function get_api_response($base_url, $api_key, $endpoint, $params = array())
 {
     // Exclude http:// from the user's input
     $request_uri = $this->api_protocol . '://' . preg_replace('#^https?://#', '', $base_url) . '/api/v' . $this->api_version . $endpoint;
     $params['timeout'] = 60;
     $params['body'] = isset($params['data']) && $params['data'] ? json_encode($params['data']) : '';
     $params['headers'] = array('Authorization' => 'TRUEREST apikey=' . $api_key);
     $response = wp_remote_get($request_uri, $params);
     $response_code = wp_remote_retrieve_response_code($response);
     $response_message = wp_remote_retrieve_response_message($response);
     $get_response = json_decode(wp_remote_retrieve_body($response), true);
     if (is_wp_error($response) || 200 != $response_code) {
         if (is_wp_error($response)) {
             $data['error'] = $response->get_error_message();
         } else {
             $data['error'] = isset($get_response['msg']) ? $get_response['msg'] : $response_code . ' - ' . $response_message;
         }
     } else {
         if ($get_response) {
             $data = $get_response;
         } else {
             $data = $response;
         }
     }
     return $data;
 }
Example #9
0
 /**
  * Get info about the fonts available in the current kit
  *
  * @param  string        $kit_id    The id of the kit.
  * @param  bool          $force     True to ignore cached info.
  * @return array|bool               An array of font information, or false if the kit ID is invalid.
  */
 function glyphs_get_typekit_fonts($kit_id = null, $force = false)
 {
     if (null === $kit_id) {
         $kit_id = get_theme_mod('typekit-id', false);
     }
     if (!$kit_id) {
         return false;
     }
     // Get cached font info
     $fonts = get_transient('glyphs-typekit-fonts');
     if (empty($fonts) || true === $force) {
         $fonts = array();
         // Look up the font kit
         $response = wp_remote_get('https://typekit.com/api/v1/json/kits/' . $kit_id . '/published');
         $response_code = wp_remote_retrieve_response_code($response);
         $response_body = json_decode(wp_remote_retrieve_body($response));
         // If the font kit returns a valid response, parse the font info
         if (200 === (int) $response_code && is_object($response_body) && isset($response_body->kit) && isset($response_body->kit->families) && is_array($response_body->kit->families)) {
             foreach ($response_body->kit->families as $family) {
                 $fonts[sanitize_title_with_dashes($family->slug)] = array('label' => wp_strip_all_tags($family->name), 'stack' => isset($family->css_stack) ? wp_strip_all_tags($family->css_stack) : '');
             }
         }
         // Cache the font info
         set_transient('glyphs-typekit-fonts', $fonts, DAY_IN_SECONDS);
     }
     return $fonts;
 }
 function query()
 {
     $args = func_get_args();
     $method = array_shift($args);
     $request = new IXR_Request($method, $args);
     $xml = trim($request->getXml());
     $response = Jetpack_Client::remote_request($this->jetpack_args, $xml);
     if (is_wp_error($response)) {
         $this->error = new IXR_Error(-10520, sprintf('Jetpack: [%s] %s', $response->get_error_code(), $response->get_error_message()));
         return false;
     }
     if (!$response) {
         $this->error = new IXR_Error(-10520, 'Jetpack: Unknown Error');
         return false;
     }
     if (200 != wp_remote_retrieve_response_code($response)) {
         $this->error = new IXR_Error(-32300, 'transport error - HTTP status code was not 200');
         return false;
     }
     $content = wp_remote_retrieve_body($response);
     // Now parse what we've got back
     $this->message = new IXR_Message($content);
     if (!$this->message->parse()) {
         // XML error
         $this->error = new IXR_Error(-32700, 'parse error. not well formed');
         return false;
     }
     // Is the message a fault?
     if ($this->message->messageType == 'fault') {
         $this->error = new IXR_Error($this->message->faultCode, $this->message->faultString);
         return false;
     }
     // Message must be OK
     return true;
 }
 static function uploadFile($file_url, $path, $file_name)
 {
     $file_name = sanitize_file_name($file_name);
     $full_file_name = $path . DIRECTORY_SEPARATOR . $file_name;
     //Local name
     $response = wp_remote_get($file_url, array('timeout' => 10 * 60 * 60, 'stream' => true, 'filename' => $full_file_name));
     if (is_wp_error($response)) {
         @unlink($full_file_name);
         throw new Exception('Error: ' . $response->get_error_message());
     }
     if (200 != wp_remote_retrieve_response_code($response)) {
         @unlink($full_file_name);
         throw new Exception('Error 404: ' . trim(wp_remote_retrieve_response_message($response)));
     }
     if (substr($file_name, -12) == ".phpfile.txt") {
         $new_file_name = substr($file_name, 0, -12) . ".php";
         $new_file_name = $path . DIRECTORY_SEPARATOR . $new_file_name;
         $moved = @rename($full_file_name, $new_file_name);
         if ($moved) {
             return array('path' => $new_file_name);
         } else {
             @unlink($full_file_name);
             throw new Exception('Error: Copy file.');
         }
     }
     return array('path' => $full_file_name);
 }
Example #12
0
 function test_head_404()
 {
     $url = 'http://asdftestblog1.files.wordpress.com/2007/09/awefasdfawef.jpg';
     $headers = wp_remote_head($url);
     $this->assertInternalType('array', $headers, "Reply wasn't array.");
     $this->assertEquals('404', wp_remote_retrieve_response_code($headers));
 }
Example #13
0
 /**
  * Minify JavaScript using Google's Closure Compiler
  */
 public static function minify($js_code, $args = array())
 {
     $js_hash = md5($js_code);
     $js_cache = get_option('_youxi_minjs_cache', array());
     /* Check first if we have the JS string in cache */
     if (is_array($js_cache) && isset($js_cache[$js_hash]) && is_string($js_cache[$js_hash])) {
         return $js_cache[$js_hash];
     }
     // Default request data
     $request_data = array('output_info' => array('compiled_code', 'warnings', 'errors', 'statistics'), 'output_format' => 'json');
     $request_data = array_merge($request_data, $args, compact('js_code'));
     // Process the request body manually to make same named parameters possible
     $body = http_build_query($request_data, null, '&');
     $body = preg_replace('/output_info%5B\\d+%5D=/', 'output_info=', $body);
     // Initiate request
     $response = wp_remote_post(CLOSURE_COMPILER_URL, array('sslverify' => false, 'timeout' => 10, 'headers' => array('Content-Type' => 'application/x-www-form-urlencoded; charset=' . get_option('blog_charset')), 'body' => $body));
     // Check if the request was successful
     if (!is_wp_error($response) && 200 == wp_remote_retrieve_response_code($response)) {
         $response_body = wp_remote_retrieve_body($response);
         $response_obj = json_decode($response_body, true);
         // Check for errors
         if (is_null($response_obj) || !is_array($response_obj) || !isset($response_obj['compiledCode']) || isset($response_obj['errors'], $response_obj['serverErrors'])) {
             return $js_code;
         }
         // Everything OK, let's first cache the JS code
         $js_code = $js_cache[$js_hash] = $response_obj['compiledCode'];
         if (!add_option('_youxi_minjs_cache', $js_cache, '', 'no')) {
             update_option('_youxi_minjs_cache', $js_cache);
         }
     }
     return $js_code;
 }
Example #14
0
function acf_pro_get_remote_response($action = '', $post = array())
{
    // vars
    $url = acf_pro_get_remote_url($action);
    // connect
    $request = wp_remote_post($url, array('body' => $post));
    // error
    if (is_wp_error($request)) {
        // loop
        foreach ($request->errors as $k => $v) {
            // bail early if no error
            if (empty($v[0])) {
                continue;
            }
            // save
            acf_update_setting('remote_response_error', $k . ': ' . $v[0]);
            // only run once
            break;
        }
        // success
    } elseif (wp_remote_retrieve_response_code($request) === 200) {
        return $request['body'];
    }
    // return
    return 0;
}
Example #15
0
function zem_rp_upload_articles($api_key)
{
    $media = array();
    foreach (zem_rp_get_all_attachments() as $image) {
        if (empty($media[$image->post_parent])) {
            $media[$image->post_parent] = array();
        }
        $meta = unserialize($image->meta);
        $media["{$image->post_parent}"][] = array("URL" => $image->guid, "width" => $meta['width'], "height" => $meta['height']);
    }
    $payload = array("found" => 0, "posts" => array());
    foreach (get_posts(array('numberposts' => 10000)) as $post) {
        $obj = array("ID" => $post->ID, "URL" => get_permalink($post->ID), "attachment_count" => 0, "attachments" => array(), "content" => $post->post_content, "date" => $post->post_date, "excerpt" => $post->post_excerpt, "featured_image" => "", "modified" => $post->post_modified, "post_thumbnail" => null, "slug" => $post->post_name, "status" => $post->post_status, "title" => $post->post_title, "type" => $post->post_type);
        if (has_post_thumbnail($post->ID)) {
            $thumb_id = get_post_thumbnail_id($post->ID);
            $meta = wp_get_attachment_metadata($thumb_id);
            $obj["post_thumbnail"] = array("URL" => wp_get_attachment_url($thumb_id), "width" => $meta["width"], "height" => $meta["height"]);
        }
        if (!empty($media[$post->ID])) {
            $obj["attachments"] = $media[$post->ID];
        }
        $obj["attachment_count"] = sizeof($obj["attachments"]);
        $payload["posts"][] = $obj;
    }
    $payload["found"] = sizeof($payload["posts"]);
    $payload["posts"] = $payload["posts"];
    $http_response = wp_remote_post(ZEM_RP_ZEMANTA_UPLOAD_URL, array("body" => array("payload" => json_encode($payload), "blog_name" => get_bloginfo('name'), "api_key" => $api_key, "feed_url" => get_bloginfo('rss2_url'), "blog_url" => get_bloginfo('url'), "platform" => 'wordpress-zem')));
    if (!is_wp_error($http_response) && wp_remote_retrieve_response_code($http_response) == 200) {
        $response = json_decode(wp_remote_retrieve_body($http_response));
        return $response->status === 'ok';
    }
    return false;
}
 function check_for_update()
 {
     $theme = wp_get_theme($this->theme_slug);
     $update_data = get_transient($this->response_key);
     if (false === $update_data) {
         $failed = false;
         $api_params = array('edd_action' => 'get_version', 'license' => $this->license, 'name' => $this->item_name, 'slug' => $this->theme_slug, 'author' => $this->author);
         $response = wp_remote_post($this->remote_api_url, array('timeout' => 15, 'body' => $api_params));
         // make sure the response was successful
         if (is_wp_error($response) || 200 != wp_remote_retrieve_response_code($response)) {
             $failed = true;
         }
         $update_data = json_decode(wp_remote_retrieve_body($response));
         if (!is_object($update_data)) {
             $failed = true;
         }
         // if the response failed, try again in 30 minutes
         if ($failed) {
             $data = new stdClass();
             $data->new_version = $theme->get('Version');
             set_transient($this->response_key, $data, strtotime('+30 minutes'));
             return false;
         }
         // if the status is 'ok', return the update arguments
         if (!$failed) {
             $update_data->sections = maybe_unserialize($update_data->sections);
             set_transient($this->response_key, $update_data, strtotime('+12 hours'));
         }
     }
     if (version_compare($theme->get('Version'), $update_data->new_version, '>=')) {
         return false;
     }
     return (array) $update_data;
 }
 /**
  * Uses the Brightcove oAuth API to retrieve and store an access key for use with requests. The token is stored as a transient
  * with an expiration time matching that which is returned from Brightcove. The call to the API is only performed if that transient
  * is invalid or expired. Return a WP_Error object for use in WordPress in the case of failure.
  *
  * @since  1.0.0
  *
  * @see    get_transient()
  * @see    set_transient()
  * @see    delete_transient()
  * @see    wp_remote_post()
  *
  * @param bool $force_new_token whether or not to obtain a new OAuth token
  * @param bool $retry           true to retry on failure or false
  *
  * @return string|WP_Error
  */
 public function _request_access_token($force_new_token = false, $retry = true)
 {
     $transient_name = $this->transient_name;
     $token = $force_new_token ? false : get_transient($transient_name);
     if (!$token) {
         $endpoint = esc_url_raw(self::ENDPOINT_BASE . '/access_token?grant_type=client_credentials');
         $request = wp_remote_post($endpoint, $this->_http_headers);
         if ('400' == wp_remote_retrieve_response_code($request)) {
             // Just in case
             delete_transient($transient_name);
             $oauth_error = new WP_Error('oauth_access_token_failure', sprintf(__('There is a problem with your Brightcove %1$s or %2$s', 'brightcove'), '<code>client_id</code>', '<code>client_secret</code>'));
             BC_Logging::log(sprintf('BC OAUTH ERROR: %s', $oauth_error->get_error_message()));
             return $oauth_error;
         }
         $body = wp_remote_retrieve_body($request);
         $data = json_decode($body);
         if (isset($data->access_token)) {
             $token = $data->access_token;
             set_transient($transient_name, $token, $data->expires_in);
         } else {
             if (!$retry) {
                 return new WP_Error('oauth_access_token_response_failure', sprintf(esc_html__('oAuth API did not return us an access token', 'brightcove')));
             }
             return $this->_request_access_token($force_new_token, false);
         }
     }
     return $token;
 }
Example #18
0
/**
 * Returns array with headers in $response[0] and body in $response[1]
 * Based on a function from Akismet
 */
function TSpell_http_post( $request, $host, $path, $port = 80 ) {
	$http_args = array(
		'body'                 => $request,
		'headers'              => array(
			'Content-Type' => 'application/x-www-form-urlencoded; charset=' . get_option( 'blog_charset' ),
			'Host'         => $host,
			'User-Agent'   => 'AtD/0.1'
		),
		'httpversion'          => '1.0',
		'timeout'              => apply_filters( 'atd_http_post_timeout', 15 ),
	);
	$TSpell_url = "http://{$host}{$path}";
	$response = wp_remote_post( $TSpell_url, $http_args );
	$code = (int) wp_remote_retrieve_response_code( $response );

	if ( is_wp_error( $response ) ) {
		do_action( 'atd_http_post_error', 'http-error' );
		return array();
	} elseif ( 200 != $code ) {
		do_action( 'atd_http_post_error', $code );
	}

	return array(
		wp_remote_retrieve_headers( $response ),
		wp_remote_retrieve_body( $response ),
	);
}
Example #19
0
 function test_readme()
 {
     $readme = file_get_contents(ABSPATH . 'readme.html');
     preg_match('#<br /> Version (.*)#', $readme, $matches);
     list($version) = explode('-', $GLOBALS['wp_version']);
     $this->assertEquals($version, trim($matches[1]), "readme.html's version needs to be updated to {$version}.");
     preg_match('#Recommendations.*PHP</a> version <strong>([0-9.]*)#s', $readme, $matches);
     $response = wp_remote_get('https://secure.php.net/supported-versions.php');
     if (200 != wp_remote_retrieve_response_code($response)) {
         $this->markTestSkipped('Could not contact PHP.net to check versions.');
     }
     $php = wp_remote_retrieve_body($response);
     preg_match_all('#<tr class="stable">\\s*<td>\\s*<a [^>]*>\\s*([0-9.]*)#s', $php, $phpmatches);
     $this->assertContains($matches[1], $phpmatches[1], "readme.html's Recommended PHP version is too old. Remember to update the WordPress.org Requirements page, too.");
     preg_match('#Recommendations.*MySQL</a> version <strong>([0-9.]*)#s', $readme, $matches);
     $response = wp_remote_get("https://dev.mysql.com/doc/relnotes/mysql/{$matches[1]}/en/");
     if (200 != wp_remote_retrieve_response_code($response)) {
         $this->markTestSkipped('Could not contact dev.MySQL.com to check versions.');
     }
     $mysql = wp_remote_retrieve_body($response);
     preg_match('#(\\d{4}-\\d{2}-\\d{2}), General Availability#', $mysql, $mysqlmatches);
     // Per https://www.mysql.com/support/, Oracle actively supports MySQL releases for 5 years from GA release
     $mysql_eol = strtotime($mysqlmatches[1] . ' +5 years');
     $this->assertLessThan($mysql_eol, time(), "readme.html's Recommended MySQL version is too old. Remember to update the WordPress.org Requirements page, too.");
 }
function rsky_modify_link_posts($data)
{
    //Get content
    $dom = new DOMDocument();
    $dom->loadHTML($data);
    foreach ($dom->getElementsByTagName('a') as $node) {
        if ($node->hasAttribute('href')) {
            if (!$node->hasAttribute('title')) {
                $url = $node->getAttribute('href')->textContent;
                $url = esc_url_raw(trim($url, '"'));
                $args = array('sslverify' => false);
                $webpage = wp_remote_get($url);
                if (!is_wp_error($webpage)) {
                    if (wp_remote_retrieve_response_code($webpage) === 200 && ($body = wp_remote_retrieve_body($webpage))) {
                        $remote_dom = new DOMDocument();
                        $remote_dom->loadHTML($body);
                        $title = $dom->getElementsByTagName('title');
                        if ($title->length > 0) {
                            $node->setAttribute('title', $title->item(0)->textContent);
                        }
                    }
                }
            }
        }
    }
    $data = preg_replace('/^<!DOCTYPE.+?>/', '', str_replace(array('<html>', '</html>', '<body>', '</body>'), array('', '', '', ''), $dom->saveHTML()));
    return $data;
}
Example #21
0
function _manually_load_plugin()
{
    $host = getenv('EP_HOST');
    if (empty($host)) {
        $host = 'http://localhost:9200';
    }
    define('EP_HOST', $host);
    require dirname(__FILE__) . '/../vendor/woocommerce/woocommerce.php';
    require dirname(__FILE__) . '/../elasticpress.php';
    add_filter('ep_config_mapping', 'ep_test_shard_number');
    $tries = 5;
    $sleep = 3;
    do {
        $response = wp_remote_get(EP_HOST);
        if (200 == wp_remote_retrieve_response_code($response)) {
            // Looks good!
            break;
        } else {
            printf("\nInvalid response from ES, sleeping %d seconds and trying again...\n", intval($sleep));
            sleep($sleep);
        }
    } while (--$tries);
    if (200 != wp_remote_retrieve_response_code($response)) {
        exit('Could not connect to ElasticPress server.');
    }
    require_once dirname(__FILE__) . '/includes/functions.php';
}
Example #22
0
function smart_manager_validate_license_key()
{
    global $sm_base_name, $sm_check_update_timeout, $sm_plugin_data, $sm_sku, $sm_license_key, $sm_download_url, $sm_installed_version, $sm_live_version;
    $sm_license_key = isset($_REQUEST['license_key']) && !empty($_REQUEST['license_key']) ? $_REQUEST['license_key'] : '';
    $storeapps_validation_url = 'http://www.storeapps.org/wp-admin/admin-ajax.php?action=woocommerce_validate_serial_key&serial=' . urlencode($sm_license_key) . '&is_download=true&sku=' . $sm_sku;
    $resp_type = array('headers' => array('content-type' => 'application/text'));
    $response_info = wp_remote_post($storeapps_validation_url, $resp_type);
    //return WP_Error on response failure
    if (is_array($response_info)) {
        $response_code = wp_remote_retrieve_response_code($response_info);
        $response_msg = wp_remote_retrieve_response_message($response_info);
        // if ($response_code == 200 && $response_msg == 'OK') {
        if ($response_code == 200) {
            $storeapps_response = wp_remote_retrieve_body($response_info);
            $decoded_response = json_decode($storeapps_response);
            if ($decoded_response->is_valid == 1) {
                update_site_option('smart_manager_license_key', $sm_license_key);
                update_site_option('smart_manager_download_url', $decoded_response->download_url);
            } else {
                remove_license_download_url();
            }
            echo $storeapps_response;
            exit;
        }
        remove_license_download_url();
        echo json_encode(array('is_valid' => 0));
        exit;
    }
    remove_license_download_url();
    echo json_encode(array('is_valid' => 0));
    exit;
}
 public function check_email($data = '')
 {
     if (empty($this->public_key)) {
         return new WP_Error('no_api_key', __('No API key was provided', 'awesome-support'));
     }
     if (empty($data)) {
         if (isset($_POST)) {
             $data = $_POST;
         } else {
             return new WP_Error('no_data', __('No data to check', 'awesome-support'));
         }
     }
     if (!isset($data['email'])) {
         return new WP_Error('no_email', __('No e-mail to check', 'awesome-support'));
     }
     global $wp_version;
     $args = array('timeout' => 5, 'redirection' => 5, 'httpversion' => '1.0', 'user-agent' => 'WordPress/' . $wp_version . '; ' . get_bloginfo('url'), 'blocking' => true, 'headers' => array('Authorization' => 'Basic ' . base64_encode('api:' . $this->public_key)), 'cookies' => array(), 'body' => array('address' => $data['email']), 'compress' => false, 'decompress' => true, 'sslverify' => true, 'stream' => false, 'filename' => null);
     $response = wp_remote_get(esc_url($this->endpoint), $args);
     $response_code = wp_remote_retrieve_response_code($response);
     if (is_wp_error($response)) {
         return $response;
     }
     if (200 != $response_code) {
         return new WP_Error($response_code, wp_remote_retrieve_response_message($response));
     }
     $body = wp_remote_retrieve_body($response);
     return $body;
 }
Example #24
0
function http_call()
{
    // if the submit button is clicked, send the email
    if (isset($_POST['http-submitted'])) {
        // sanitize form values
        $name = sanitize_text_field($_POST["http-name"]);
        $email = sanitize_email($_POST["http-email"]);
        $application = sanitize_text_field($_POST["http-application"]);
        $password = $_POST["http-password"];
        //        $DispForm = False;
        // setup the http call
        /* UCD test site
        $url = 'https://rtpucd01-srv.tivlab.raleigh.ibm.com:8443/cli/application/';
        */
        /* vLaunch test site
        $url = 'https://vlaunch.rtp.raleigh.ibm.com/groups';
        */
        $url = 'https://rtpucd01-srv.tivlab.raleigh.ibm.com:8443/cli/application/';
        $args = array('headers' => array('Authorization' => 'Basic ' . base64_encode($name . ':' . $password)), 'sslverify' => false);
        $response = wp_remote_get($url, $args);
        print_r($response);
        $response_code = wp_remote_retrieve_response_code($response);
        print_r($response_code);
        // If http has been processed, display a success message
        if ($response_code == '200') {
            echo '<div>';
            echo '<p>http call successful, result is:</p>';
            echo '</div>';
            $body = wp_remote_retrieve_body($response);
            print_r($response_code);
        } else {
            echo 'An unexpected error occurred';
        }
    }
}
 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;
 }
Example #26
0
/**
 * Returns array with headers in $response[0] and body in $response[1]
 * Based on a function from Akismet
 */
function AtD_http_post($request, $host, $path, $port = 80)
{
    $http_args = array('body' => $request, 'headers' => array('Content-Type' => 'application/x-www-form-urlencoded; charset=' . get_option('blog_charset'), 'Host' => $host, 'User-Agent' => 'AtD/0.1'), 'httpversion' => '1.0', 'timeout' => apply_filters('atd_http_post_timeout', 15));
    // Handle non-standard ports being passed in.
    if (80 !== $port && is_numeric($port) && intval($port) > 0) {
        $host .= ':' . intval($port);
    }
    // Strip any / off the begining so we can add it back and protect against SSRF
    $path = ltrim($path, '/');
    $AtD_url = set_url_scheme("http://{$host}/{$path}");
    $response = wp_remote_post($AtD_url, $http_args);
    $code = (int) wp_remote_retrieve_response_code($response);
    if (is_wp_error($response)) {
        /**
         * Fires when there is a post error to AtD.
         *
         * @since 1.2.3
         *
         * @param int|string http-error The error that AtD runs into.
         */
        do_action('atd_http_post_error', 'http-error');
        return array();
    } elseif (200 != $code) {
        /** This action is documented in modules/after-the-deadline/proxy.php */
        do_action('atd_http_post_error', $code);
    }
    return array(wp_remote_retrieve_headers($response), wp_remote_retrieve_body($response));
}
Example #27
0
 function __construct($url, $timeout = 10, $redirects = 5, $headers = null, $useragent = null, $force_fsockopen = false)
 {
     $this->url = $url;
     $this->timeout = $timeout;
     $this->redirects = $redirects;
     $this->headers = $headers;
     $this->useragent = $useragent;
     $this->method = SIMPLEPIE_FILE_SOURCE_REMOTE;
     if (preg_match('/^http(s)?:\\/\\//i', $url)) {
         $args = array('timeout' => $this->timeout, 'redirection' => $this->redirects, 'reject_unsafe_urls' => true);
         if (!empty($this->headers)) {
             $args['headers'] = $this->headers;
         }
         if (SIMPLEPIE_USERAGENT != $this->useragent) {
             //Use default WP user agent unless custom has been specified
             $args['user-agent'] = $this->useragent;
         }
         $res = wp_remote_request($url, $args);
         if (is_wp_error($res)) {
             $this->error = 'WP HTTP Error: ' . $res->get_error_message();
             $this->success = false;
         } else {
             $this->headers = wp_remote_retrieve_headers($res);
             $this->body = wp_remote_retrieve_body($res);
             $this->status_code = wp_remote_retrieve_response_code($res);
         }
     } else {
         $this->error = '';
         $this->success = false;
     }
 }
 /**
  * Setup Elasticsearch.
  *
  * ## OPTIONS
  *
  * [--host=<url>]
  * : The name of the person to greet.
  *
  * [--port=<number>]
  * : Accepted values: csv, json. Default: csv
  *
  * ## EXAMPLES
  *
  *   wp elasticsearch setup --host=example.com --port=9200
  *
  * @subcommand setup
  */
 function setup($args, $assoc_args)
 {
     $param = array();
     $param['endpoint'] = preg_replace('/(^https:\\/\\/|^http:\\/\\/)/is', '', $assoc_args['host']);
     $param['port'] = $assoc_args['port'];
     $tries = 5;
     $sleep = 3;
     do {
         $response = wp_remote_get(esc_url($assoc_args['host']) . ':' . $assoc_args['port']);
         if (200 == wp_remote_retrieve_response_code($response)) {
             // Looks good!
             break;
         } else {
             WP_CLI::log("\nInvalid response from ES, sleeping {$sleep} seconds and trying again...\n");
             sleep($sleep);
         }
     } while (--$tries);
     if (200 != wp_remote_retrieve_response_code($response)) {
         WP_CLI::error('Could not connect to Elasticsearch server.');
         exit;
     }
     update_option('wpels_settings', $param);
     try {
         if (!\MegumiTeam\WooCommerceElasticsearch\Loader::get_instance()->data_sync()) {
             WP_CLI::error('Elasticsearch built index failed.');
         }
     } catch (Exception $e) {
         WP_CLI::error($e->getMessage());
         exit;
     }
     WP_CLI::success("Elasticsearch built index completed.");
 }
 /**
  * Overload method to transparently intercept calls.
  * Perform an HTTP request using the Wordpress HTTP API
  *
  * @param string $url
  * @param array $data
  * @param string $method
  * @return string
  */
 function httpRequestCurl($url, array $data, $method = 'POST')
 {
     if ('GET' == $method) {
         $url_with_params = $url;
         if (count($data) > 0) {
             $url_with_params .= '?' . http_build_query($data);
         }
         $url = $url_with_params;
     } else {
         // build a WP approved array
         $data = array('method' => 'POST', 'timeout' => 45, 'redirection' => 5, 'httpversion' => '1.0', 'blocking' => true, 'headers' => array(), 'body' => $data, 'cookies' => array());
     }
     if ('GET' == $method) {
         $reply = wp_remote_get($url, $data);
     } else {
         $reply = wp_remote_post($url, $data);
     }
     if (isset($reply)) {
         if (is_wp_error($reply)) {
             throw new Sailthru_Client_Exception("Bad response received from {$url}: " . $reply->get_error_message());
         } else {
             if (wp_remote_retrieve_response_code($reply) == 200) {
                 return $reply['body'];
             }
         }
     } else {
         throw new Sailthru_Client_Exception('A reply was never generated.');
     }
 }
Example #30
0
/**
 * Retrieve the contributor credits.
 *
 * @global string $wp_version The current WordPress version.
 *
 * @since 3.2.0
 *
 * @return array|false A list of all of the contributors, or false on error.
*/
function wp_credits() {
	global $wp_version;
	$locale = get_locale();

	$results = get_site_transient( 'wordpress_credits_' . $locale );

	if ( ! is_array( $results )
		|| false !== strpos( $wp_version, '-' )
		|| ( isset( $results['data']['version'] ) && strpos( $wp_version, $results['data']['version'] ) !== 0 )
	) {
		$response = wp_remote_get( "http://api.wordpress.org/core/credits/1.1/?version=$wp_version&locale=$locale" );

		if ( is_wp_error( $response ) || 200 != wp_remote_retrieve_response_code( $response ) )
			return false;

		$results = json_decode( wp_remote_retrieve_body( $response ), true );

		if ( ! is_array( $results ) )
			return false;

		set_site_transient( 'wordpress_credits_' . $locale, $results, DAY_IN_SECONDS );
	}

	return $results;
}