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);
 }
Esempio n. 2
0
 function pmxi_get_remote_image_ext($filePath)
 {
     $response = wp_remote_get($filePath);
     $headers = wp_remote_retrieve_headers($response);
     $content_type = !empty($headers['content-type']) ? explode('/', $headers['content-type']) : false;
     if (!empty($content_type[1])) {
         if (preg_match('%jpeg%i', $content_type[1])) {
             return 'jpeg';
         }
         if (preg_match('%jpg%i', $content_type[1])) {
             return 'jpg';
         }
         if (preg_match('%png%i', $content_type[1])) {
             return 'png';
         }
         if (preg_match('%gif%i', $content_type[1])) {
             return 'gif';
         }
         if (preg_match('%svg%i', $content_type[1])) {
             return 'svg';
         }
         return $content_type[1] == "unknown" ? "" : $content_type[1];
     }
     return '';
 }
Esempio n. 3
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;
     }
 }
Esempio n. 4
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 ),
	);
}
Esempio n. 5
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));
}
 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;
     global $wpdb;
     global $fwp_credentials;
     if (preg_match('/^http(s)?:\\/\\//i', $url)) {
         $args = array('timeout' => $this->timeout, 'redirection' => $this->redirects);
         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;
         }
         // This is ugly as hell, but communicating up and down the chain
         // in any other way is difficult.
         if (!is_null($fwp_credentials)) {
             $args['authentication'] = $fwp_credentials['authentication'];
             $args['username'] = $fwp_credentials['username'];
             $args['password'] = $fwp_credentials['password'];
         } else {
             $links = $wpdb->get_results($wpdb->prepare("SELECT * FROM {$wpdb->links} WHERE link_rss = '%s'", $url));
             if ($links) {
                 $source = new SyndicatedLink($links[0]);
                 $args['authentication'] = $source->authentication_method();
                 $args['username'] = $source->username();
                 $args['password'] = $source->password();
             }
         }
         $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 {
         if (!($this->body = file_get_contents($url))) {
             $this->error = 'file_get_contents could not read the file';
             $this->success = false;
         }
     }
     // SimplePie makes a strongly typed check against integers with
     // this, but WordPress puts a string in. Which causes caching
     // to break and fall on its ass when SimplePie is getting a 304,
     // but doesn't realize it because this member is "304" instead.
     $this->status_code = (int) $this->status_code;
 }
Esempio n. 7
0
 function test_head_request()
 {
     // this url give a direct 200 response
     $url = 'http://asdftestblog1.files.wordpress.com/2007/09/2007-06-30-dsc_4700-1.jpg';
     $response = wp_remote_head($url);
     $headers = wp_remote_retrieve_headers($response);
     $this->assertInternalType('array', $headers, "Reply wasn't array.");
     $this->assertEquals('image/jpeg', $headers['content-type']);
     $this->assertEquals('40148', $headers['content-length']);
     $this->assertEquals('200', wp_remote_retrieve_response_code($response));
 }
 function test_get_redirect()
 {
     // this will redirect to asdftestblog1.files.wordpress.com
     $url = 'https://asdftestblog1.wordpress.com/files/2007/09/2007-06-30-dsc_4700-1.jpg';
     $response = wp_remote_get($url);
     $headers = wp_remote_retrieve_headers($response);
     // should return the same headers as a head request
     $this->assertEquals('image/jpeg', $headers['content-type']);
     $this->assertEquals('40148', $headers['content-length']);
     $this->assertEquals('200', wp_remote_retrieve_response_code($response));
 }
Esempio n. 9
0
 /**
  * Execute a apiHttpRequest
  *
  * @param Yoast_Google_HttpRequest $request the http request to be executed
  *
  * @return Yoast_Google_HttpRequest http request with the response http code, response
  * headers and response body filled in
  */
 public function makeRequest(Yoast_Google_HttpRequest $request)
 {
     // First, check to see if we have a valid cached version.
     $cached = $this->getCachedRequest($request);
     if ($cached !== false) {
         if (!$this->checkMustRevaliadateCachedRequest($cached, $request)) {
             return $cached;
         }
     }
     if (array_key_exists($request->getRequestMethod(), self::$ENTITY_HTTP_METHODS)) {
         $request = $this->processEntityRequest($request);
     }
     $params = array('user-agent' => $request->getUserAgent(), 'timeout' => 30, 'sslverify' => false);
     $curl_version = $this->get_curl_version();
     if ($curl_version !== false) {
         if (version_compare($curl_version, '7.19.0', '<=') && version_compare($curl_version, '7.19.8', '>')) {
             add_filter('http_api_transports', array($this, 'filter_curl_from_transports'));
         }
     }
     if ($request->getPostBody()) {
         $params['body'] = $request->getPostBody();
     }
     $requestHeaders = $request->getRequestHeaders();
     if ($requestHeaders && is_array($requestHeaders)) {
         $params['headers'] = $requestHeaders;
     }
     switch ($request->getRequestMethod()) {
         case 'POST':
             $response = wp_remote_post($request->getUrl(), $params);
             break;
         case 'GET':
             $response = wp_remote_get($request->getUrl(), $params);
             break;
     }
     $responseBody = wp_remote_retrieve_body($response);
     $respHttpCode = wp_remote_retrieve_response_code($response);
     $responseHeaders = wp_remote_retrieve_headers($response);
     if ($respHttpCode == 304 && $cached) {
         // If the server responded NOT_MODIFIED, return the cached request.
         $this->updateCachedRequest($cached, $responseHeaders);
         return $cached;
     }
     // Fill in the apiHttpRequest with the response values
     $request->setResponseHttpCode($respHttpCode);
     $request->setResponseHeaders($responseHeaders);
     $request->setResponseBody($responseBody);
     // Store the request in cache (the function checks to see if the request
     // can actually be cached)
     $this->setCachedRequest($request);
     // And finally return it
     return $request;
 }
Esempio n. 10
0
/**
 * 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;
}
Esempio n. 11
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));
    // Strip any / off the begining so we can add it back and protect against SSRF
    $path = ltrim($path, '/');
    $AtD_url = "http://{$host}/{$path}";
    $response = wp_remote_post($AtD_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));
}
Esempio n. 12
0
 /**
  * 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)];
 }
Esempio n. 13
0
 /**
  * @param $selected_call
  * @param $method_type
  * @param $params
  * @return string
  * @throws W3tcWpHttpException
  */
 private function execute($selected_call, $method_type, $params)
 {
     //increase the http request timeout
     add_filter('http_request_timeout', array($this, 'filter_timeout_time'));
     $consumer = new W3tcOAuthConsumer($this->key, $this->secret, NULL);
     // the endpoint for your request
     $endpoint = "{$this->netdnarws_url}/{$this->alias}{$selected_call}";
     //parse endpoint before creating OAuth request
     $parsed = parse_url($endpoint);
     if (array_key_exists("parsed", $parsed)) {
         parse_str($parsed['query'], $params);
     }
     //generate a request from your consumer
     $req_req = W3tcOAuthRequest::from_consumer_and_token($consumer, NULL, $method_type, $endpoint, $params);
     //sign your OAuth request using hmac_sha1
     $sig_method = new W3tcOAuthSignatureMethod_HMAC_SHA1();
     $req_req->sign_request($sig_method, $consumer, NULL);
     $headers = $request = array();
     $request['sslverify'] = false;
     $request['method'] = $method_type;
     if ($method_type == "POST" || $method_type == "PUT" || $method_type == "DELETE") {
         $request['body'] = $params;
     }
     $response = wp_remote_request($req_req, $request);
     $json_output = '';
     if (!is_wp_error($response)) {
         // make call
         $result = wp_remote_retrieve_body($response);
         $headers = wp_remote_retrieve_headers($response);
         $response_code = wp_remote_retrieve_response_code($response);
         // $json_output contains the output string
         $json_output = $result;
     } else {
         $response_code = $response->get_error_code();
     }
     remove_filter('http_request_timeout', array($this, 'filter_timeout_time'));
     // catch errors
     if (is_wp_error($response)) {
         throw new W3tcWpHttpException("ERROR: {$response->get_error_message()}, Output: {$json_output}", $response_code, null, $headers);
     }
     return $json_output;
 }
Esempio n. 14
0
function powerpress_admin_verify_url($url)
{
    $response = wp_remote_head($url, array('httpversion' => 1.1));
    for ($x = 0; $x < 5; $x++) {
        // Redirect 1-5
        if (!is_wp_error($response) && ($response['response']['code'] == 301 || $response['response']['code'] == 302)) {
            $headers = wp_remote_retrieve_headers($response);
            $response = wp_remote_head($headers['location'], array('httpversion' => 1.1));
        } else {
            break;
            // Either we had an error or the response code is no longer a redirect
        }
    }
    if (is_wp_error($response)) {
        return array('error' => $response->get_error_message());
    }
    if (isset($response['response']['code']) && ($response['response']['code'] < 200 || $response['response']['code'] > 203)) {
        return array('error' => 'Error, HTTP ' . $response['response']['code']);
    }
    return array('error' => false);
}
Esempio n. 15
0
 public static function remote($url = FALSE, $post_vars = FALSE, $args = FALSE, $return = FALSE)
 {
     if ($url && is_string($url)) {
         $args = !is_array($args) ? array() : $args;
         /* Force array, and disable SSL verification. */
         $args["sslverify"] = !isset($args["sslverify"]) ? false : $args["sslverify"];
         /**/
         if ((is_array($post_vars) || is_string($post_vars)) && !empty($post_vars)) {
             $args = array_merge($args, array("method" => "POST", "body" => $post_vars));
         }
         /**/
         $response = wp_remote_request($url, $args);
         /* Process the remote request now. */
         /**/
         if (strcasecmp((string) $return, "array") === 0 && !is_wp_error($response) && is_array($response)) {
             $a = array("code" => (int) wp_remote_retrieve_response_code($response));
             $a = array_merge($a, array("message" => wp_remote_retrieve_response_message($response)));
             $a = array_merge($a, array("headers" => wp_remote_retrieve_headers($response)));
             $a = array_merge($a, array("body" => wp_remote_retrieve_body($response)));
             $a = array_merge($a, array("response" => $response));
             /**/
             return $a;
         } else {
             if (!is_wp_error($response) && is_array($response)) {
                 return wp_remote_retrieve_body($response);
             } else {
                 /* Else this remote request has failed completely. Return false. */
                 return false;
             }
         }
         /* Remote request failed, return false. */
     } else {
         /* Else, return false. */
         return false;
     }
 }
function powerpress_admin_verify_url($url)
{
    $wp_remote_options = array();
    $wp_remote_options['user-agent'] = 'Blubrry PowerPress/' . POWERPRESS_VERSION;
    $wp_remote_options['httpversion'] = '1.1';
    $response = wp_remote_head($url, $wp_remote_options);
    for ($x = 0; $x < 5; $x++) {
        // Redirect 1-5
        if (!is_wp_error($response) && ($response['response']['code'] == 301 || $response['response']['code'] == 302)) {
            $headers = wp_remote_retrieve_headers($response);
            $response = wp_remote_head($headers['location'], $wp_remote_options);
        } else {
            break;
            // Either we had an error or the response code is no longer a redirect
        }
    }
    if (is_wp_error($response)) {
        return array('error' => $response->get_error_message());
    }
    if (isset($response['response']['code']) && ($response['response']['code'] < 200 || $response['response']['code'] > 203)) {
        return array('error' => 'Error, HTTP ' . $response['response']['code']);
    }
    return array('error' => false);
}
Esempio n. 17
0
/**
 * Retrieve URL headers and content using WP HTTP Request API.
 *
 * @since 1.5.0
 * @package External
 * @subpackage MagpieRSS
 *
 * @param string $url URL to retrieve
 * @param array $headers Optional. Headers to send to the URL.
 * @return Snoopy style response
 */
function _fetch_remote_file($url, $headers = "")
{
    $resp = wp_safe_remote_request($url, array('headers' => $headers, 'timeout' => MAGPIE_FETCH_TIME_OUT));
    if (is_wp_error($resp)) {
        $error = array_shift($resp->errors);
        $resp = new stdClass();
        $resp->status = 500;
        $resp->response_code = 500;
        $resp->error = $error[0] . "\n";
        //\n = Snoopy compatibility
        return $resp;
    }
    // Snoopy returns headers unprocessed.
    // Also note, WP_HTTP lowercases all keys, Snoopy did not.
    $return_headers = array();
    foreach (wp_remote_retrieve_headers($resp) as $key => $value) {
        if (!is_array($value)) {
            $return_headers[] = "{$key}: {$value}";
        } else {
            foreach ($value as $v) {
                $return_headers[] = "{$key}: {$v}";
            }
        }
    }
    $response = new stdClass();
    $response->status = wp_remote_retrieve_response_code($resp);
    $response->response_code = wp_remote_retrieve_response_code($resp);
    $response->headers = $return_headers;
    $response->results = wp_remote_retrieve_body($resp);
    return $response;
}
Esempio n. 18
0
 /**
  * Handle and parse the response
  *
  * @since 2.2.0
  * @param array|WP_Error $response response data
  * @throws \SV_WC_API_Exception network issues, timeouts, API errors, etc
  * @return object request class instance that implements SV_WC_API_Request
  */
 protected function handle_response($response)
 {
     // check for WP HTTP API specific errors (network timeout, etc)
     if (is_wp_error($response)) {
         throw new SV_WC_API_Exception($response->get_error_message(), (int) $response->get_error_code());
     }
     // set response data
     $this->response_code = wp_remote_retrieve_response_code($response);
     $this->response_message = wp_remote_retrieve_response_message($response);
     $this->response_headers = wp_remote_retrieve_headers($response);
     $this->raw_response_body = wp_remote_retrieve_body($response);
     // allow child classes to validate response prior to parsing -- this is useful
     // for checking HTTP status codes, etc.
     $this->do_pre_parse_response_validation();
     // parse the response body and tie it to the request
     $this->response = $this->get_parsed_response($this->raw_response_body);
     // allow child classes to validate response after parsing -- this is useful
     // for checking error codes/messages included in a parsed response
     $this->do_post_parse_response_validation();
     // fire do_action() so other actors can act on request/response data,
     // primarily used for logging
     $this->broadcast_request();
     return $this->response;
 }
	function __construct ($url, $timeout = 10, $redirects = 5, $headers = null, $useragent = null, $force_fsockopen = false) {
		global $feedwordpress;
		global $wp_version;

		$source = NULL;
		if ($feedwordpress->subscribed($url)) :
			$source = $feedwordpress->subscription($url);
		endif;
		
		$this->url = $url;
		$this->timeout = $timeout;
		$this->redirects = $redirects;
		$this->headers = $headers;
		$this->useragent = $useragent;

		$this->method = SIMPLEPIE_FILE_SOURCE_REMOTE;
		
		global $wpdb;
		global $fwp_credentials;
		
		if ( preg_match('/^http(s)?:\/\//i', $url) ) {
			$args = array( 'timeout' => $this->timeout, 'redirection' => $this->redirects);
	
			if ( !empty($this->headers) )
				$args['headers'] = $this->headers;

			// Use default FWP user agent unless custom has been specified
			if ( SIMPLEPIE_USERAGENT != $this->useragent ) :
				$args['user-agent'] = $this->useragent;
			else :
				$args['user-agent'] = apply_filters('feedwordpress_user_agent',
					'FeedWordPress/'.FEEDWORDPRESS_VERSION
					.' (aggregator:feedwordpress; WordPress/'.$wp_version
					.' + '.SIMPLEPIE_NAME.'/'.SIMPLEPIE_VERSION
					.'; Allow like Gecko; +http://feedwordpress.radgeek.com/) at '
					. feedwordpress_display_url(get_bloginfo('url')),
					$this
				);
			endif;

			// This is ugly as hell, but communicating up and down the chain
			// in any other way is difficult.

			if (!is_null($fwp_credentials)) :

				$args['authentication'] = $fwp_credentials['authentication'];
				$args['username'] = $fwp_credentials['username'];
				$args['password'] = $fwp_credentials['password'];

			elseif ($source InstanceOf SyndicatedLink) :

				$args['authentication'] = $source->authentication_method();
				$args['username'] = $source->username();
				$args['password'] = $source->password();
			
			endif;

			FeedWordPress::diagnostic('updated_feeds:http', "HTTP [$url] &#8668; ".esc_html(FeedWordPress::val($args)));
			$res = wp_remote_request($url, $args);
			FeedWordPress::diagnostic('updated_feeds:http', "HTTP [$url] &#8669; ".esc_html(FeedWordPress::val($res)));

			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 );
			}
			
			if ($source InstanceOf SyndicatedLink) :
				$source->update_setting('link/filesize', strlen($this->body));
				$source->update_setting('link/http status', $this->status_code);
				$source->save_settings(/*reload=*/ true);
			endif;
			
		} else {
			if ( ! $this->body = file_get_contents($url) ) {
				$this->error = 'file_get_contents could not read the file';
				$this->success = false;
			}
		}

		// SimplePie makes a strongly typed check against integers with
		// this, but WordPress puts a string in. Which causes caching
		// to break and fall on its ass when SimplePie is getting a 304,
		// but doesn't realize it because this member is "304" instead.
		$this->status_code = (int) $this->status_code;
	}
Esempio n. 20
0
/**
 * Retrieve HTTP Headers from URL.
 *
 * @since 1.5.1
 *
 * @param string $url
 * @param bool $deprecated Not Used.
 * @return bool|string False on failure, headers on success.
 */
function wp_get_http_headers($url, $deprecated = false)
{
    $response = wp_remote_head($url);
    if (is_wp_error($response)) {
        return false;
    }
    return wp_remote_retrieve_headers($response);
}
 /**
  * Responsible for all remote communications processed by s2Member.
  *
  * Uses ``wp_remote_request()`` through the `WP_Http` class.
  *
  * @package s2Member\Utilities
  * @since 3.5
  *
  * @param str $url Full URL with possible query string parameters.
  * @param str|array $post_vars Optional. Either a string of POST vars, or an array.
  * @param array $args Optional. An array of additional arguments used by ``wp_remote_request()``.
  * @param bool $return_array Optional. If true, instead of a string, we return an array with elements:
  * 	`code` *(http response code)*, `message` *(http response message)*, `headers` *(an array of lowercase headers)*, `body` *(the response body string)*, `response` *(full response array)*.
  * @return str|array|bool Requested response str|array from remote location *(see ``$return_array`` parameter )*; else (bool)`false` on failure.
  */
 public static function remote($url = FALSE, $post_vars = FALSE, $args = FALSE, $return_array = FALSE)
 {
     if ($url && is_string($url)) {
         $args = !is_array($args) ? array() : $args;
         $args["sslverify"] = !isset($args["sslverify"]) ? false : $args["sslverify"];
         /**/
         if ((is_array($post_vars) || is_string($post_vars)) && !empty($post_vars)) {
             $args = array_merge($args, array("method" => "POST", "body" => $post_vars));
         }
         /**/
         if (!empty($args["method"]) && strcasecmp((string) $args["method"], "DELETE") === 0) {
             /* WordPress® v3.3 and prior, does NOT support `DELETE` via cURL unfortunately. */
             add_filter("use_curl_transport", "__return_false", 111209554);
         }
         /**/
         $response = wp_remote_request($url, $args);
         /**/
         remove_filter("use_curl_transport", "__return_false", 111209554);
         /**/
         if ($return_array && !is_wp_error($response) && is_array($response)) {
             $a = array("code" => (int) wp_remote_retrieve_response_code($response));
             $a = array_merge($a, array("message" => wp_remote_retrieve_response_message($response)));
             $a = array_merge($a, array("headers" => wp_remote_retrieve_headers($response)));
             $a = array_merge($a, array("body" => wp_remote_retrieve_body($response)));
             $a = array_merge($a, array("response" => $response));
             /**/
             return $a;
         } else {
             if (!is_wp_error($response) && is_array($response)) {
                 return wp_remote_retrieve_body($response);
             } else {
                 /* Else this remote request has failed completely. Return false. */
                 return false;
             }
         }
         /* Remote request failed, return false. */
     } else {
         /* Else, return false. */
         return false;
     }
 }
Esempio n. 22
0
/**
 * Perform a HTTP HEAD or GET request.
 *
 * If $file_path is a writable filename, this will do a GET request and write
 * the file to that path.
 *
 * @since 2.5.0
 * @deprecated 4.4.0 Use WP_Http
 * @see WP_Http
 *
 * @param string      $url       URL to fetch.
 * @param string|bool $file_path Optional. File path to write request to. Default false.
 * @param int         $red       Optional. The number of Redirects followed, Upon 5 being hit,
 *                               returns false. Default 1.
 * @return bool|string False on failure and string of headers if HEAD request.
 */
function wp_get_http($url, $file_path = false, $red = 1)
{
    _deprecated_function(__FUNCTION__, '4.4.0', 'WP_Http');
    @set_time_limit(60);
    if ($red > 5) {
        return false;
    }
    $options = array();
    $options['redirection'] = 5;
    if (false == $file_path) {
        $options['method'] = 'HEAD';
    } else {
        $options['method'] = 'GET';
    }
    $response = wp_safe_remote_request($url, $options);
    if (is_wp_error($response)) {
        return false;
    }
    $headers = wp_remote_retrieve_headers($response);
    $headers['response'] = wp_remote_retrieve_response_code($response);
    // WP_HTTP no longer follows redirects for HEAD requests.
    if ('HEAD' == $options['method'] && in_array($headers['response'], array(301, 302)) && isset($headers['location'])) {
        return wp_get_http($headers['location'], $file_path, ++$red);
    }
    if (false == $file_path) {
        return $headers;
    }
    // GET request - write it to the supplied filename
    $out_fp = fopen($file_path, 'w');
    if (!$out_fp) {
        return $headers;
    }
    fwrite($out_fp, wp_remote_retrieve_body($response));
    fclose($out_fp);
    clearstatcache();
    return $headers;
}
 /**
  * @return array
  */
 protected function handle_response()
 {
     $this->status_code = wp_remote_retrieve_response_code($this->response);
     $this->headers = wp_remote_retrieve_headers($this->response);
     $this->body = wp_remote_retrieve_body($this->response);
 }
Esempio n. 24
0
    /**
     * Page Output
     */
    public static function page()
    {
        global $wpdb;
        ?>
    <div class="wrap" id="backwpup-page">
		<h2><span id="backwpup-page-icon">&nbsp;</span><?php 
        echo sprintf(__('%s Settings', 'backwpup'), BackWPup::get_plugin_data('name'));
        ?>
</h2>
		<?php 
        $tabs = array('general' => __('General', 'backwpup'), 'job' => __('Jobs', 'backwpup'), 'log' => __('Logs', 'backwpup'), 'net' => __('Network', 'backwpup'), 'apikey' => __('API Keys', 'backwpup'), 'information' => __('Information', 'backwpup'));
        $tabs = apply_filters('backwpup_page_settings_tab', $tabs);
        echo '<h2 class="nav-tab-wrapper">';
        foreach ($tabs as $id => $name) {
            echo '<a href="#backwpup-tab-' . $id . '" class="nav-tab">' . $name . '</a>';
        }
        echo '</h2>';
        BackWPup_Admin::display_messages();
        ?>

    <form id="settingsform" action="<?php 
        echo admin_url('admin-post.php?action=backwpup');
        ?>
" method="post">
		<?php 
        wp_nonce_field('backwpupsettings_page');
        ?>
        <input type="hidden" name="page" value="backwpupsettings" />
    	<input type="hidden" name="anchor" value="#backwpup-tab-general" />

		<div class="table ui-tabs-hide" id="backwpup-tab-general">

			<h3 class="title"><?php 
        _e('Display Settings', 'backwpup');
        ?>
</h3>
            <p><?php 
        _e('Do you want to see BackWPup in the WordPress admin bar?', 'backwpup');
        ?>
</p>
            <table class="form-table">
                <tr>
                    <th scope="row"><?php 
        _e('Admin bar', 'backwpup');
        ?>
</th>
                    <td>
                        <fieldset>
                            <legend class="screen-reader-text"><span><?php 
        _e('Admin Bar', 'backwpup');
        ?>
</span>
                            </legend>
                            <label for="showadminbar">
                                <input name="showadminbar" type="checkbox" id="showadminbar"
                                       value="1" <?php 
        checked(get_site_option('backwpup_cfg_showadminbar'), TRUE);
        ?>
 />
								<?php 
        _e('Show BackWPup links in admin bar.', 'backwpup');
        ?>
</label>
                        </fieldset>
                    </td>
                </tr>
                <tr>
                    <th scope="row"><?php 
        _e('Folder sizes', 'backwpup');
        ?>
</th>
                    <td>
                        <fieldset>
                            <legend class="screen-reader-text"><span><?php 
        _e('Folder sizes', 'backwpup');
        ?>
</span>
                            </legend>
                            <label for="showfoldersize">
                                <input name="showfoldersize" type="checkbox" id="showfoldersize"
                                       value="1" <?php 
        checked(get_site_option('backwpup_cfg_showfoldersize'), TRUE);
        ?>
 />
								<?php 
        _e('Display folder sizes in the files tab when editing a job. (Might increase loading time of files tab.)', 'backwpup');
        ?>
</label>
                        </fieldset>
                    </td>
                </tr>
            </table>
			<h3 class="title"><?php 
        _e('Security', 'backwpup');
        ?>
</h3>
			<p><?php 
        _e('Security option for BackWPup', 'backwpup');
        ?>
</p>
            <table class="form-table">
                <tr>
                    <th scope="row"><?php 
        _e('Protect folders', 'backwpup');
        ?>
</th>
                    <td>
                        <fieldset>
                            <legend class="screen-reader-text"><span><?php 
        _e('Protect folders', 'backwpup');
        ?>
</span>
                            </legend>
                            <label for="protectfolders">
                                <input name="protectfolders" type="checkbox" id="protectfolders"
                                       value="1" <?php 
        checked(get_site_option('backwpup_cfg_protectfolders'), TRUE);
        ?>
 />
								<?php 
        _e('Protect BackWPup folders ( Temp, Log and Backups ) with <code>.htaccess</code> and <code>index.php</code>', 'backwpup');
        ?>
                            </label>
                        </fieldset>
                    </td>
                </tr>
            </table>

			<?php 
        do_action('backwpup_page_settings_tab_generel');
        ?>

		</div>

        <div class="table ui-tabs-hide" id="backwpup-tab-log">

            <p><?php 
        _e('Every time BackWPup runs a backup job, a log file is being generated. Choose where to store your log files and how many of them.', 'backwpup');
        ?>
</p>
            <table class="form-table">
                <tr>
                    <th scope="row"><label for="logfolder"><?php 
        _e('Log file folder', 'backwpup');
        ?>
</label></th>
                    <td>
                        <input name="logfolder" type="text" id="logfolder"
                               value="<?php 
        echo get_site_option('backwpup_cfg_logfolder');
        ?>
"
                               class="regular-text code"/>
                    </td>
                </tr>
                <tr>
                    <th scope="row"><label for="maxlogs"><?php 
        _e('Maximum number of log files in folder', 'backwpup');
        ?>
</label>
                    </th>
                    <td>
                        <input name="maxlogs" type="text" id="maxlogs" title="<?php 
        esc_attr_e('Oldest files will be deleted first.', 'backwpup');
        ?>
"
                               value="<?php 
        echo get_site_option('backwpup_cfg_maxlogs');
        ?>
" class="small-text code help-tip"/>
                    </td>
                </tr>
                <tr>
                    <th scope="row"><?php 
        _e('Compression', 'backwpup');
        ?>
</th>
                    <td>
                        <fieldset>
                            <legend class="screen-reader-text"><span><?php 
        _e('Compression', 'backwpup');
        ?>
</span>
                            </legend>
                            <label for="gzlogs">
                                <input name="gzlogs" type="checkbox" id="gzlogs"
                                       value="1" <?php 
        checked(get_site_option('backwpup_cfg_gzlogs'), TRUE);
        if (!function_exists('gzopen')) {
            echo " disabled=\"disabled\"";
        }
        ?>
 />
								<?php 
        _e('Compress log files with GZip.', 'backwpup');
        ?>
</label>
                        </fieldset>
                    </td>
                </tr>
            </table>

        </div>
        <div class="table ui-tabs-hide" id="backwpup-tab-job">

            <p><?php 
        _e('There are a couple of general options for backup jobs. Set them here.', 'backwpup');
        ?>
</p>
            <table class="form-table">
                <tr>
                    <th scope="row">
                        <label for="jobstepretry"><?php 
        _e("Maximum number of retries for job steps", 'backwpup');
        ?>
</label></th>
                    <td>
                        <input name="jobstepretry" type="text" id="jobstepretry"
                               value="<?php 
        echo get_site_option('backwpup_cfg_jobstepretry');
        ?>
"
                               class="small-text code" />
                    </td>
                </tr>
				<tr>
                    <th scope="row"><?php 
        _e('Maximum script execution time', 'backwpup');
        ?>
</th>
                    <td>
                        <fieldset>
                            <legend class="screen-reader-text"><span><?php 
        _e('Maximum PHP Script execution time', 'backwpup');
        ?>
</span>
                            </legend>
                            <label for="jobmaxexecutiontime">
                                <input name="jobmaxexecutiontime" type="text" id="jobmaxexecutiontime" size="3" title="<?php 
        esc_attr_e('Job will restart before hitting maximum execution time. It will not work with CLI and not on every step during execution. If <code>ALTERNATE_WP_CRON</code> has been defined, WordPress Cron will be used.', 'backwpup');
        ?>
"
                                       value="<?php 
        echo get_site_option('backwpup_cfg_jobmaxexecutiontime');
        ?>
" class="help-tip" />
								<?php 
        _e('seconds. 0 = disabled.', 'backwpup');
        ?>
							</label>
                        </fieldset>
                    </td>
                </tr>
				<tr>
                    <th scope="row"><?php 
        _e('Method for creating ZIP-file archives', 'backwpup');
        ?>
</th>
                    <td>
                        <fieldset>
                            <legend class="screen-reader-text"><span><?php 
        _e('Method for creating ZIP-file archives', 'backwpup');
        ?>
</span>
                            </legend>
                            <label for="jobziparchivemethod">
								<select name="jobziparchivemethod" size="1" class="help-tip" title="<?php 
        esc_attr_e('Auto = Uses PHP class ZipArchive if available; otherwise uses PclZip.<br />ZipArchive = Uses less memory, but many open files at a time.<br />PclZip = Uses more memory, but only 2 open files at a time.', 'backwpup');
        ?>
">
									<option value="" <?php 
        selected(get_site_option('backwpup_cfg_jobziparchivemethod'), '');
        ?>
><?php 
        _e('Auto', 'backwpup');
        ?>
</option>
                                    <option value="ZipArchive" <?php 
        selected(get_site_option('backwpup_cfg_jobziparchivemethod'), 'ZipArchive');
        disabled(function_exists('ZipArchive'), TRUE);
        ?>
><?php 
        _e('ZipArchive', 'backwpup');
        ?>
</option>
                                    <option value="PclZip" <?php 
        selected(get_site_option('backwpup_cfg_jobziparchivemethod'), 'PclZip');
        ?>
><?php 
        _e('PclZip', 'backwpup');
        ?>
</option>
                                </select>
                            </label>
                        </fieldset>
                    </td>
                </tr>
                <tr>
                    <th scope="row">
                        <label for="jobrunauthkey"><?php 
        _e('Key to start jobs externally with an URL', 'backwpup');
        ?>
</label>
                    </th>
                    <td>
                        <input name="jobrunauthkey" type="text" id="jobrunauthkey" title="<?php 
        esc_attr_e('empty = deactivated. Will be used to protect job starts from unauthorized person.', 'backwpup');
        ?>
"
                               value="<?php 
        echo get_site_option('backwpup_cfg_jobrunauthkey');
        ?>
" class="text code help-tip"/>
                    </td>
                </tr>
                <tr>
                    <th scope="row"><?php 
        _e('No translation', 'backwpup');
        ?>
</th>
                    <td>
                        <fieldset>
                            <legend class="screen-reader-text"><span><?php 
        _e('No Translation', 'backwpup');
        ?>
</span>
                            </legend>
                            <label for="jobnotranslate">
                                <input name="jobnotranslate" type="checkbox" id="jobnotranslate"
                                       value="1" <?php 
        checked(get_site_option('backwpup_cfg_jobnotranslate'), TRUE);
        ?>
 />
								<?php 
        _e('No translation for the job, the log will be written in English', 'backwpup');
        ?>
                            </label>
                        </fieldset>
                    </td>
                </tr>
                <tr>
                    <th scope="row"><?php 
        _e('Reduce server load', 'backwpup');
        ?>
</th>
                    <td>
                        <fieldset>
                            <legend class="screen-reader-text"><span><?php 
        _e('Reduce server load', 'backwpup');
        ?>
</span>
                            </legend>
                            <label for="jobwaittimems">
								<select name="jobwaittimems" size="1" class="help-tip" title="<?php 
        esc_attr_e('This adds short pauses to the process. Can be used to reduce the CPU load.<br /> Disabled = off<br /> minimum = shortest sleep<br /> medium = middle between minimum and maximum<br /> maximum = longest sleep<br />', 'backwpup');
        ?>
">
									<option value="0" <?php 
        selected(get_site_option('backwpup_cfg_jobwaittimems'), 0);
        ?>
><?php 
        _e('disabled', 'backwpup');
        ?>
</option>
                                    <option value="10000" <?php 
        selected(get_site_option('backwpup_cfg_jobwaittimems'), 10000);
        ?>
><?php 
        _e('minimum', 'backwpup');
        ?>
</option>
                                    <option value="30000" <?php 
        selected(get_site_option('backwpup_cfg_jobwaittimems'), 30000);
        ?>
><?php 
        _e('medium', 'backwpup');
        ?>
</option>
                                    <option value="90000" <?php 
        selected(get_site_option('backwpup_cfg_jobwaittimems'), 90000);
        ?>
><?php 
        _e('maximum', 'backwpup');
        ?>
</option>
                                </select>
                            </label>
                        </fieldset>
                    </td>
                </tr>
            </table>

        </div>

        <div class="table ui-tabs-hide" id="backwpup-tab-net">

			<h3 class="title"><?php 
        _e('Authentication', 'backwpup');
        ?>
</h3>
            <p><?php 
        _e('Is your blog protected with HTTP basic authentication (.htaccess)? If yes, please set the username and password for authentication here.', 'backwpup');
        ?>
</p>
            <table class="form-table">
                <tr>
                    <th scope="row"><label for="httpauthuser"><?php 
        _e('Username:'******'backwpup');
        ?>
</label></th>
                    <td>
                        <input name="httpauthuser" type="text" id="httpauthuser"
                               value="<?php 
        echo get_site_option('backwpup_cfg_httpauthuser');
        ?>
"
                               class="regular-text" autocomplete="off" />
                    </td>
                </tr>
                <tr>
                    <th scope="row"><label for="httpauthpassword"><?php 
        _e('Password:'******'backwpup');
        ?>
</label></th>
                    <td>
                        <input name="httpauthpassword" type="password" id="httpauthpassword"
                               value="<?php 
        echo BackWPup_Encryption::decrypt(get_site_option('backwpup_cfg_httpauthpassword'));
        ?>
"
                               class="regular-text" autocomplete="off" />
                </tr>
            </table>

        </div>

        <div class="table ui-tabs-hide" id="backwpup-tab-apikey">

			<?php 
        do_action('backwpup_page_settings_tab_apikey');
        ?>

        </div>

        <div class="table ui-tabs-hide" id="backwpup-tab-information">
			<br />
			<?php 
        echo '<table class="wp-list-table widefat fixed" cellspacing="0" style="width: 85%;margin-left:auto;;margin-right:auto;">';
        echo '<thead><tr><th width="35%">' . __('Setting', 'backwpup') . '</th><th>' . __('Value', 'backwpup') . '</th></tr></thead>';
        echo '<tfoot><tr><th>' . __('Setting', 'backwpup') . '</th><th>' . __('Value', 'backwpup') . '</th></tr></tfoot>';
        echo '<tr title="&gt;=3.2"><td>' . __('WordPress version', 'backwpup') . '</td><td>' . BackWPup::get_plugin_data('wp_version') . '</td></tr>';
        if (!class_exists('BackWPup_Pro', FALSE)) {
            echo '<tr title=""><td>' . __('BackWPup version', 'backwpup') . '</td><td>' . BackWPup::get_plugin_data('Version') . ' <a href="' . translate(BackWPup::get_plugin_data('pluginuri'), 'backwpup') . '">' . __('Get pro.', 'backwpup') . '</a></td></tr>';
        } else {
            echo '<tr title=""><td>' . __('BackWPup Pro version', 'backwpup') . '</td><td>' . BackWPup::get_plugin_data('Version') . '</td></tr>';
        }
        echo '<tr title="&gt;=5.3.3"><td>' . __('PHP version', 'backwpup') . '</td><td>' . PHP_VERSION . '</td></tr>';
        echo '<tr title="&gt;=5.0.7"><td>' . __('MySQL version', 'backwpup') . '</td><td>' . $wpdb->get_var("SELECT VERSION() AS version") . '</td></tr>';
        if (function_exists('curl_version')) {
            $curlversion = curl_version();
            echo '<tr title=""><td>' . __('cURL version', 'backwpup') . '</td><td>' . $curlversion['version'] . '</td></tr>';
            echo '<tr title=""><td>' . __('cURL SSL version', 'backwpup') . '</td><td>' . $curlversion['ssl_version'] . '</td></tr>';
        } else {
            echo '<tr title=""><td>' . __('cURL version', 'backwpup') . '</td><td>' . __('unavailable', 'backwpup') . '</td></tr>';
        }
        echo '<tr title=""><td>' . __('WP-Cron url:', 'backwpup') . '</td><td>' . site_url('wp-cron.php') . '</td></tr>';
        //response test
        echo '<tr><td>' . __('Server self connect:', 'backwpup') . '</td><td>';
        $raw_response = BackWPup_Job::get_jobrun_url('test');
        $test_result = '';
        if (is_wp_error($raw_response)) {
            $test_result .= sprintf(__('The HTTP response test get an error "%s"', 'backwpup'), $raw_response->get_error_message());
        } elseif (200 != wp_remote_retrieve_response_code($raw_response) && 204 != wp_remote_retrieve_response_code($raw_response)) {
            $test_result .= sprintf(__('The HTTP response test get a false http status (%s)', 'backwpup'), wp_remote_retrieve_response_code($raw_response));
        }
        $headers = wp_remote_retrieve_headers($raw_response);
        if (isset($headers['x-backwpup-ver']) && $headers['x-backwpup-ver'] != BackWPup::get_plugin_data('version')) {
            $test_result .= sprintf(__('The BackWPup HTTP response header returns a false value: "%s"', 'backwpup'), $headers['x-backwpup-ver']);
        }
        if (empty($test_result)) {
            _e('Response Test O.K.', 'backwpup');
        } else {
            echo $test_result;
        }
        echo '</td></tr>';
        //folder test
        echo '<tr><td>' . __('Temp folder:', 'backwpup') . '</td><td>';
        if (!is_dir(BackWPup::get_plugin_data('TEMP'))) {
            echo sprintf(__('Temp folder %s doesn\'t exist.', 'backwpup'), BackWPup::get_plugin_data('TEMP'));
        } elseif (!is_writable(BackWPup::get_plugin_data('TEMP'))) {
            echo sprintf(__('Temporary folder %s is not writable.', 'backwpup'), BackWPup::get_plugin_data('TEMP'));
        } else {
            echo BackWPup::get_plugin_data('TEMP');
        }
        echo '</td></tr>';
        echo '<tr><td>' . __('Log folder:', 'backwpup') . '</td><td>';
        if (!is_dir(get_site_option('backwpup_cfg_logfolder'))) {
            echo sprintf(__('Logs folder %s not exist.', 'backwpup'), get_site_option('backwpup_cfg_logfolder'));
        } elseif (!is_writable(get_site_option('backwpup_cfg_logfolder'))) {
            echo sprintf(__('Log folder %s is not writable.', 'backwpup'), get_site_option('backwpup_cfg_logfolder'));
        } else {
            echo get_site_option('backwpup_cfg_logfolder');
        }
        echo '</td></tr>';
        echo '<tr title=""><td>' . __('Server', 'backwpup') . '</td><td>' . $_SERVER['SERVER_SOFTWARE'] . '</td></tr>';
        echo '<tr title=""><td>' . __('Operating System', 'backwpup') . '</td><td>' . PHP_OS . '</td></tr>';
        echo '<tr title=""><td>' . __('PHP SAPI', 'backwpup') . '</td><td>' . PHP_SAPI . '</td></tr>';
        echo '<tr title=""><td>' . __('Current PHP user', 'backwpup') . '</td><td>' . get_current_user() . '</td></tr>';
        $text = (bool) ini_get('safe_mode') ? __('On', 'backwpup') : __('Off', 'backwpup');
        echo '<tr title=""><td>' . __('Safe Mode', 'backwpup') . '</td><td>' . $text . '</td></tr>';
        echo '<tr title="&gt;=30"><td>' . __('Maximum execution time', 'backwpup') . '</td><td>' . ini_get('max_execution_time') . ' ' . __('seconds', 'backwpup') . '</td></tr>';
        if (defined('ALTERNATE_WP_CRON') && ALTERNATE_WP_CRON) {
            echo '<tr title="ALTERNATE_WP_CRON"><td>' . __('Alternative WP Cron', 'backwpup') . '</td><td>' . __('On', 'backwpup') . '</td></tr>';
        } else {
            echo '<tr title="ALTERNATE_WP_CRON"><td>' . __('Alternative WP Cron', 'backwpup') . '</td><td>' . __('Off', 'backwpup') . '</td></tr>';
        }
        if (defined('DISABLE_WP_CRON') && DISABLE_WP_CRON) {
            echo '<tr title="DISABLE_WP_CRON"><td>' . __('Disabled WP Cron', 'backwpup') . '</td><td>' . __('On', 'backwpup') . '</td></tr>';
        } else {
            echo '<tr title="DISABLE_WP_CRON"><td>' . __('Disabled WP Cron', 'backwpup') . '</td><td>' . __('Off', 'backwpup') . '</td></tr>';
        }
        if (defined('FS_CHMOD_DIR')) {
            echo '<tr title="FS_CHMOD_DIR"><td>' . __('CHMOD Dir', 'backwpup') . '</td><td>' . FS_CHMOD_DIR . '</td></tr>';
        } else {
            echo '<tr title="FS_CHMOD_DIR"><td>' . __('CHMOD Dir', 'backwpup') . '</td><td>0755</td></tr>';
        }
        $now = localtime(time(), TRUE);
        echo '<tr title=""><td>' . __('Server Time', 'backwpup') . '</td><td>' . $now['tm_hour'] . ':' . $now['tm_min'] . '</td></tr>';
        echo '<tr title=""><td>' . __('Blog Time', 'backwpup') . '</td><td>' . date_i18n('H:i') . '</td></tr>';
        echo '<tr title=""><td>' . __('Blog Timezone', 'backwpup') . '</td><td>' . get_option('timezone_string') . '</td></tr>';
        echo '<tr title=""><td>' . __('Blog Time offset', 'backwpup') . '</td><td>' . sprintf(__('%s hours', 'backwpup'), get_option('gmt_offset')) . '</td></tr>';
        echo '<tr title="WPLANG"><td>' . __('Blog language', 'backwpup') . '</td><td>' . get_bloginfo('language') . '</td></tr>';
        echo '<tr title="utf8"><td>' . __('MySQL Client encoding', 'backwpup') . '</td><td>';
        echo defined('DB_CHARSET') ? DB_CHARSET : '';
        echo '</td></tr>';
        echo '<tr title="URF-8"><td>' . __('Blog charset', 'backwpup') . '</td><td>' . get_bloginfo('charset') . '</td></tr>';
        echo '<tr title="&gt;=128M"><td>' . __('PHP Memory limit', 'backwpup') . '</td><td>' . ini_get('memory_limit') . '</td></tr>';
        echo '<tr title="WP_MEMORY_LIMIT"><td>' . __('WP memory limit', 'backwpup') . '</td><td>' . WP_MEMORY_LIMIT . '</td></tr>';
        echo '<tr title="WP_MAX_MEMORY_LIMIT"><td>' . __('WP maximum memory limit', 'backwpup') . '</td><td>' . WP_MAX_MEMORY_LIMIT . '</td></tr>';
        echo '<tr title=""><td>' . __('Memory in use', 'backwpup') . '</td><td>' . size_format(@memory_get_usage(TRUE), 2) . '</td></tr>';
        //disabled PHP functions
        $disabled = ini_get('disable_functions');
        if (!empty($disabled)) {
            $disabledarry = explode(',', $disabled);
            echo '<tr title=""><td>' . __('Disabled PHP Functions:', 'backwpup') . '</td><td>';
            echo implode(', ', $disabledarry);
            echo '</td></tr>';
        }
        //Loaded PHP Extensions
        echo '<tr title=""><td>' . __('Loaded PHP Extensions:', 'backwpup') . '</td><td>';
        $extensions = get_loaded_extensions();
        sort($extensions);
        echo implode(', ', $extensions);
        echo '</td></tr>';
        echo '</table>';
        ?>
        </div>

		<?php 
        do_action('backwpup_page_settings_tab_content');
        ?>

        <p class="submit">
            <input type="submit" name="submit" id="submit" class="button-primary" value="<?php 
        _e('Save Changes', 'backwpup');
        ?>
" />
			&nbsp;
			<input type="submit" name="default_settings" id="default_settings" class="button-secondary" value="<?php 
        _e('Reset all settings to default', 'backwpup');
        ?>
" />
        </p>
    </form>
    </div>
	<?php 
    }
Esempio n. 25
0
 /**
  * Log the delivery request/response
  *
  * @since 2.2
  * @param int $delivery_id previously created comment ID
  * @param array $request request data
  * @param array $response response data
  * @param float $duration request duration
  */
 public function log_delivery($delivery_id, $request, $response, $duration)
 {
     // save request data
     add_comment_meta($delivery_id, '_request_method', $request['method']);
     add_comment_meta($delivery_id, '_request_headers', array_merge(array('User-Agent' => $request['user-agent']), $request['headers']));
     add_comment_meta($delivery_id, '_request_body', $request['body']);
     // parse response
     if (is_wp_error($response)) {
         $response_code = $response->get_error_code();
         $response_message = $response->get_error_message();
         $response_headers = $response_body = array();
     } else {
         $response_code = wp_remote_retrieve_response_code($response);
         $response_message = wp_remote_retrieve_response_message($response);
         $response_headers = wp_remote_retrieve_headers($response);
         $response_body = wp_remote_retrieve_body($response);
     }
     // save response data
     add_comment_meta($delivery_id, '_response_code', $response_code);
     add_comment_meta($delivery_id, '_response_message', $response_message);
     add_comment_meta($delivery_id, '_response_headers', $response_headers);
     add_comment_meta($delivery_id, '_response_body', $response_body);
     // save duration
     add_comment_meta($delivery_id, '_duration', $duration);
     // set a summary for quick display
     $args = array('comment_ID' => $delivery_id, 'comment_content' => sprintf('HTTP %s %s: %s', $response_code, $response_message, $response_body));
     wp_update_comment($args);
     // track failures
     if (intval($response_code) >= 200 && intval($response_code) < 300) {
         delete_post_meta($this->id, '_failure_count');
     } else {
         $this->failed_delivery();
     }
     // keep the 25 most recent delivery logs
     $log = wp_count_comments($this->id);
     if ($log->total_comments > apply_filters('woocommerce_max_webhook_delivery_logs', 25)) {
         global $wpdb;
         $comment_id = $wpdb->get_var($wpdb->prepare("SELECT comment_ID FROM {$wpdb->comments} WHERE comment_post_ID = %d ORDER BY comment_date_gmt ASC LIMIT 1", $this->id));
         if ($comment_id) {
             wp_delete_comment($comment_id, true);
         }
     }
 }
Esempio n. 26
0
 /**
  * Checks whether the response is JSON encoded
  * @param  mixed $response
  * @return bool
  */
 protected function isJsonEncoded($response)
 {
     $headers = wp_remote_retrieve_headers($response);
     if (!isset($headers['content-type'])) {
         return false;
     }
     if (!preg_match('/json/ui', $headers['content-type'])) {
         return false;
     }
     return true;
 }
Esempio n. 27
0
/**
 * Retrieve HTTP Headers from URL.
 *
 * @since 1.5.1
 *
 * @param string $url        URL to retrieve HTTP headers from.
 * @param bool   $deprecated Not Used.
 * @return bool|string False on failure, headers on success.
 */
function wp_get_http_headers($url, $deprecated = false)
{
    if (!empty($deprecated)) {
        _deprecated_argument(__FUNCTION__, '2.7');
    }
    $response = wp_safe_remote_head($url);
    if (is_wp_error($response)) {
        return false;
    }
    return wp_remote_retrieve_headers($response);
}
 /**
  * Attempt to download a remote file attachment
  *
  * @param string $url URL of item to fetch
  * @param array $post Attachment details
  * @return array|WP_Error Local file location details on success, WP_Error otherwise
  */
 protected function fetch_remote_file($url, $post)
 {
     // extract the file name and extension from the url
     $file_name = basename($url);
     // get placeholder file in the upload dir with a unique, sanitized filename
     $upload = wp_upload_bits($file_name, 0, '', $post['upload_date']);
     if ($upload['error']) {
         return new WP_Error('upload_dir_error', $upload['error']);
     }
     // fetch the remote url and write it to the placeholder file
     $response = wp_remote_get($url, array('stream' => true, 'filename' => $upload['file']));
     // request failed
     if (is_wp_error($response)) {
         @unlink($upload['file']);
         return $response;
     }
     $code = (int) wp_remote_retrieve_response_code($response);
     // make sure the fetch was successful
     if ($code !== 200) {
         @unlink($upload['file']);
         return new WP_Error('import_file_error', sprintf(__('Remote server returned %1$d %2$s for %3$s', 'wordpress-importer'), $code, get_status_header_desc($code), $url));
     }
     $filesize = filesize($upload['file']);
     $headers = wp_remote_retrieve_headers($response);
     if (isset($headers['content-length']) && $filesize != $headers['content-length']) {
         @unlink($upload['file']);
         return new WP_Error('import_file_error', __('Remote file is incorrect size', 'wordpress-importer'));
     }
     if (0 == $filesize) {
         @unlink($upload['file']);
         return new WP_Error('import_file_error', __('Zero size file downloaded', 'wordpress-importer'));
     }
     $max_size = (int) $this->max_attachment_size();
     if (!empty($max_size) && $filesize > $max_size) {
         @unlink($upload['file']);
         return new WP_Error('import_file_error', sprintf(__('Remote file is too large, limit is %s', 'wordpress-importer'), size_format($max_size)));
     }
     return $upload;
 }
 /**
  * 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;
 }
Esempio n. 30
0
 public function wpfc_check_url_ajax_request_callback()
 {
     $_GET["url"] = strip_tags($_GET["url"]);
     $_GET["url"] = str_replace(array("'", '"'), "", $_GET["url"]);
     if (!preg_match("/^http/", $_GET["url"])) {
         $_GET["url"] = "http://" . $_GET["url"];
     }
     $response = wp_remote_get($_GET["url"], array('timeout' => 10));
     $header = wp_remote_retrieve_headers($response);
     if (!$response || is_wp_error($response)) {
         $res = array("success" => false, "error_message" => $response->get_error_message());
         if ($response->get_error_code() == "http_request_failed") {
             if ($response->get_error_message() == "Failure when receiving data from the peer") {
                 $res = array("success" => true);
             }
         }
     } else {
         $response_code = wp_remote_retrieve_response_code($response);
         if ($response_code == 200) {
             $res = array("success" => true);
         } else {
             if (method_exists($response, "get_error_message")) {
                 $res = array("success" => false, "error_message" => $response->get_error_message());
             } else {
                 $res = array("success" => false, "error_message" => wp_remote_retrieve_response_message($response));
             }
             if (isset($header["server"]) && preg_match("/squid/i", $header["server"])) {
                 $res = array("success" => true);
             }
         }
     }
     echo json_encode($res);
     exit;
 }