/** * 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; }
/** * Send the api request to Brickset. Returns an XML formatted response. * * @author Nate Jacobs * @since 0.1 * @updated 1.0 * * @param string url needed after base url * @param string query parameters * * @return object WP_Error * @return array */ protected function remote_request($type, $extra_url, $params = '') { $api_url = 'http://www.brickset.com/webservices/brickset.asmx'; if ('get' == $type) { //wp_die( $api_url.'/'.$extra_url.'?'.$params ); $response = wp_remote_get($api_url . '/' . $extra_url . '?' . $params); } elseif ('post' == $type) { $response = wp_remote_post($api_url . '/' . $extra_url, $params); } else { return new WP_Error('no-type-specified', __('Specify a type of request: get or post', 'bs_api')); } // Did the HTTP request fail? if (is_wp_error($response)) { return $response; } $response_code = wp_remote_retrieve_response_code($response); $response_message = wp_remote_retrieve_response_message($response); $response_body = wp_remote_retrieve_body($response); if (200 != $response_code && !empty($response_message)) { return new WP_Error($response_code, __('Don\'t Panic! Something went wrong and Brickset didn\'t reply.', 'bs_api')); } elseif (200 != $response_code) { return new WP_Error($response_code, __('Unknown error occurred', 'bs_api')); } elseif ($extra_url != 'login' && 300 > strlen($response_body) && $type == 'get') { return new WP_Error('brickset-no-data', __('Sorry, no sets were found for that query', 'bs_api')); } else { return $response_body; } }
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); }
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; }
function wclv_get_repos($username) { $response = wp_remote_get("https://api.github.com/users/{$username}/repos"); if ('200' != wp_remote_retrieve_response_code($response)) { return wp_remote_retrieve_response_message($response); } // Error retrieving repos $body = wp_remote_retrieve_body($response); $body = json_decode($body); return $body; }
function callAPI($url) { // FIXME set timeout, useragent, etc. $api_response = wp_remote_get($url); $rsp_code = wp_remote_retrieve_response_code($api_response); $rsp_msg = wp_remote_retrieve_response_message($api_response); $rsp_body = wp_remote_retrieve_body($api_response); // If request wasn't successfull return error. if ($rsp_code != 200) { return new WP_ERROR('api_call_failed', "Failed calling " . $url, $rsp_msg); } return new APIResponse($rsp_body); }
function countryCode($ip = '') { if (!$ip) { $ip = $_SERVER['REMOTE_ADDR']; } $response = @wp_remote_get("http://ipinfo.io/" . $ip . "/json"); if (200 == wp_remote_retrieve_response_code($response) && 'OK' == wp_remote_retrieve_response_message($response) && !is_wp_error($response)) { $data = json_decode($response['body'], 1); return $data['country']; //code } return false; }
public function makeRequest($method, $url, $params = null) { $method = strtolower($method); $headers = self::getHeaders(); $credentials = Config::getCredentials(); if (empty($credentials) || empty($credentials['login']) || empty($credentials['apiToken'])) { throw new ApiException("Authorization error. Please ensure your login and API Token credentials are correct."); } $headers['Authorization'] = 'Basic ' . base64_encode($credentials['login'] . ':' . $credentials['apiToken']); $opts = array('timeout' => Config::DEFAULT_REQUEST_TIMEOUT, 'headers' => $headers); switch ($method) { case 'get': if (count($params) > 0) { $url = "{$url}?" . http_build_query($params, null, '&'); } $response = wp_remote_get($url, $opts); break; case 'post': $opts['body'] = json_encode($params); $response = wp_remote_post($url, $opts); break; case 'delete': $opts['method'] = 'DELETE'; if (count($params) > 0) { $url = "{$url}?" . http_build_query($params, null, '&'); } $response = wp_remote_request($url, $opts); break; case 'put': $opts['method'] = 'PUT'; $opts['body'] = json_encode($params); $response = wp_remote_request($url, $opts); break; default: throw new ApiException("Unrecognized API Method: {$method}"); } $response_code = wp_remote_retrieve_response_code($response); if ($response_code < 200 || $response_code >= 300) { $message = wp_remote_retrieve_response_message($response); if (empty($message)) { $message = "API Error ({$httpCode})"; } throw new ApiException($message, $response_code); } try { $result = json_decode(wp_remote_retrieve_body($response), true); } catch (Exception $e) { throw new ApiException("Invalid API Response: " . wp_remote_retrieve_body($response), $response_code); } return $result; }
/** * Process registration * * @since 2.1 */ public function process_signup() { global $rcp_options; $args = array('USER' => $this->username, 'PWD' => $this->password, 'SIGNATURE' => $this->signature, 'VERSION' => '124', 'METHOD' => $this->auto_renew ? 'CreateRecurringPaymentsProfile' : 'DoDirectPayment', 'AMT' => $this->amount, 'CURRENCYCODE' => strtoupper($this->currency), 'SHIPPINGAMT' => 0, 'TAXAMT' => 0, 'DESC' => $this->subscription_name, 'SOFTDESCRIPTOR' => get_bloginfo('name') . ' - ' . $this->subscription_name, 'SOFTDESCRIPTORCITY' => get_bloginfo('admin_email'), 'CUSTOM' => $this->user_id, 'NOTIFYURL' => add_query_arg('listener', 'EIPN', home_url('index.php')), 'EMAIL' => $this->email, 'CREDITCARDTYPE' => '', 'ACCT' => sanitize_text_field($_POST['rcp_card_number']), 'EXPDATE' => sanitize_text_field($_POST['rcp_card_exp_month'] . $_POST['rcp_card_exp_year']), 'CVV2' => sanitize_text_field($_POST['rcp_card_cvc']), 'ZIP' => sanitize_text_field($_POST['rcp_card_zip']), 'BUTTONSOURCE' => 'EasyDigitalDownloads_SP', 'PROFILESTARTDATE' => date('Y-m-d\\TH:i:s', strtotime('+' . $this->length . ' ' . $this->length_unit, time())), 'BILLINGPERIOD' => ucwords($this->length_unit), 'BILLINGFREQUENCY' => $this->length, 'FAILEDINITAMTACTION' => 'CancelOnFailure', 'TOTALBILLINGCYCLES' => $this->auto_renew ? 0 : 1); if ($this->auto_renew) { $initamt = round($this->amount + $this->signup_fee, 2); if ($initamt >= 0) { $args['INITAMT'] = $initamt; } } $request = wp_remote_post($this->api_endpoint, array('timeout' => 45, 'sslverify' => false, 'httpversion' => '1.1', 'body' => $args)); $body = wp_remote_retrieve_body($request); $code = wp_remote_retrieve_response_code($request); $message = wp_remote_retrieve_response_message($request); if (is_wp_error($request)) { do_action('rcp_paypal_pro_signup_payment_failed', $request, $this); $error = '<p>' . __('An unidentified error occurred.', 'rcp') . '</p>'; $error .= '<p>' . $request->get_error_message() . '</p>'; wp_die($error, __('Error', 'rcp'), array('response' => '401')); } elseif (200 == $code && 'OK' == $message) { if (is_string($body)) { wp_parse_str($body, $body); } if (false !== strpos(strtolower($body['ACK']), 'failure')) { do_action('rcp_paypal_pro_signup_payment_failed', $request, $this); $error = '<p>' . __('PayPal subscription creation failed.', 'rcp') . '</p>'; $error .= '<p>' . __('Error message:', 'rcp') . ' ' . $body['L_LONGMESSAGE0'] . '</p>'; $error .= '<p>' . __('Error code:', 'rcp') . ' ' . $body['L_ERRORCODE0'] . '</p>'; wp_die($error, __('Error', 'rcp'), array('response' => '401')); } else { // Successful signup $member = new RCP_Member($this->user_id); if ($member->just_upgraded() && rcp_can_member_cancel($member->ID)) { $cancelled = rcp_cancel_member_payment_profile($member->ID, false); } if (isset($body['PROFILEID'])) { $member->set_payment_profile_id($body['PROFILEID']); } if (isset($body['PROFILESTATUS']) && 'ActiveProfile' === $body['PROFILESTATUS']) { // Confirm a one-time payment $member->renew($this->auto_renew); } wp_redirect(esc_url_raw(rcp_get_return_url())); exit; exit; } } else { wp_die(__('Something has gone wrong, please try again', 'rcp'), __('Error', 'rcp'), array('back_link' => true, 'response' => '401')); } }
/** * @param object $response * @return boolean */ private function validate_raw_response($response) { // make sure response came back okay if (is_wp_error($response)) { $this->error_message = $response->get_error_message(); return false; } // check response code, should be 200 $response_code = wp_remote_retrieve_response_code($response); if (false === strstr($response_code, '200')) { $response_message = wp_remote_retrieve_response_message($response); $this->error_message = "{$response_code} {$response_message}"; return false; } return true; }
function call_http() { // if submit button clicked, make the call if (isset($_POST['call-submitted'])) { // sanitize form values $name = sanitize_text_field($_POST["call-name"]); $email = sanitize_email($_POST["call-email"]); $application = sanitize_text_field($_POST["call-application"]); $password = sanitize_text_field($_POST["http-password"]); // 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'; // vLaunch create VM // $url = 'https://vlaunch.rtp.raleigh.ibm.com/newrequests/RTP/1/createVM'; $args = array('headers' => array('Authorization' => 'Basic ' . base64_encode($name . ':' . $password)), 'sslverify' => false); // end arg definition $response = wp_remote_get($url, $args); $msg = wp_remote_retrieve_response_message($response); // If not empty, display message if (!empty($msg)) { echo 'Message: <pre>'; print_r($msg); echo '</pre>'; } $http_code = wp_remote_retrieve_response_code($response); if (!empty($http_code)) { echo 'Code: <pre>'; print_r($http_code); echo '</pre>'; } // Display result if ($http_code == '200') { echo '<p>Success!</p>'; } else { echo '<p>An unexpected error occurred</p>'; } echo 'Response: <pre>'; print_r($response); // var_dump ($response); echo '</pre>'; $body = wp_remote_retrieve_body($response); echo '<p>Body:' . $body . '</p>'; } // end isset($_POST['call-submitted']) }
/** * Test the WP Cron spawning system and report back its status. * * This command tests the spawning system by performing the following steps: * * * Checks to see if the `DISABLE_WP_CRON` constant is set; errors if true * because WP-Cron is disabled. * * Checks to see if the `ALTERNATE_WP_CRON` constant is set; warns if true. * * Attempts to spawn WP-Cron over HTTP; warns if non 200 response code is * returned. * * ## EXAMPLES * * # Cron test runs successfully. * $ wp cron test * Success: WP-Cron spawning is working as expected. */ public function test() { if (defined('DISABLE_WP_CRON') && DISABLE_WP_CRON) { WP_CLI::error('The DISABLE_WP_CRON constant is set to true. WP-Cron spawning is disabled.'); } if (defined('ALTERNATE_WP_CRON') && ALTERNATE_WP_CRON) { WP_CLI::warning('The ALTERNATE_WP_CRON constant is set to true. WP-Cron spawning is not asynchronous.'); } $spawn = self::get_cron_spawn(); if (is_wp_error($spawn)) { WP_CLI::error(sprintf('WP-Cron spawn failed with error: %s', $spawn->get_error_message())); } $code = wp_remote_retrieve_response_code($spawn); $message = wp_remote_retrieve_response_message($spawn); if (200 === $code) { WP_CLI::success('WP-Cron spawning is working as expected.'); } else { WP_CLI::warning(sprintf('WP-Cron spawn succeeded but returned HTTP status code: %1$s %2$s', $code, $message)); } }
/** * Makes an HTTP request using WordPress' WP_Http class and related functions. * * @param RESTian_Request $request * @param RESTian_Response $response * @return RESTian_Response */ function make_request($request, $response) { switch ($request->http_method) { case 'GET': $url = $request->get_url(); $args = $this->get_args($request); $result = wp_remote_get($url, $args); break; case 'POST': if ($content_type = $request->get_content_type()) { $request->add_header('Content-type', $content_type); } $url = $request->get_url(); $args = $this->get_args($request); $result = wp_remote_post($url, $args); break; case 'PUT': $result = new WP_Error(-1, 'HTTP PUT not yet supported.'); break; case 'DELETE': $result = new WP_Error(-2, 'HTTP DELETE not yet supported.'); break; } if (method_exists($request->client, 'filter_result')) { $result = $request->client->filter_result($result, $response); } if (is_wp_error($result)) { /** * These errors likely won't be 100% compatible with the errors from CURL when standalone */ $error_num = $result->get_error_code(); $response->set_http_error($error_num, $result->get_error_message($error_num)); } else { $response->message = wp_remote_retrieve_response_message($result); } $response->status_code = wp_remote_retrieve_response_code($result); $response->body = wp_remote_retrieve_body($result); $response->body = $request->client->apply_filters('result_body', $response->body, $response); $response->result = $result; return $response; }
function process() { global $wp_version, $wpdb, $wpmudev_un; $mysql_vars = array('key_buffer_size' => true, 'max_allowed_packet' => false, 'max_connections' => false, 'query_cache_limit' => true, 'query_cache_size' => true, 'query_cache_type' => 'ON'); $variables = $wpdb->get_results("\n\t\t\tSHOW VARIABLES\n\t\t\tWHERE Variable_name IN ( '" . implode("', '", array_keys($mysql_vars)) . "' )\n\t\t"); if (is_resource($wpdb->dbh)) { $version = mysql_get_server_info($wpdb->dbh); $driver = 'mysql'; } else { if (is_object($wpdb->dbh) and method_exists($wpdb->dbh, 'db_version')) { $version = $wpdb->dbh->db_version(); $driver = get_class($wpdb->dbh); } else { $version = $driver = '<span class="qm-warn">' . __('Unknown', 'wpmudev') . '</span>'; } } $this->data['db'] = array('version' => $version, 'driver' => $driver, 'vars' => $mysql_vars, 'variables' => $variables); $this->data['php']['version'] = phpversion(); foreach ($this->php_vars as $setting) { $this->data['php']['variables'][$setting] = @ini_get($setting); } $this->data['php']['extensions'] = get_loaded_extensions(); natcasesort($this->data['php']['extensions']); $this->data['php']['error_reporting'] = error_reporting(); # @TODO put WP's other debugging constants in here, eg. SCRIPT_DEBUG $this->data['wp'] = array('Version' => $wp_version, 'ABSPATH' => self::format_constant('ABSPATH'), 'WP_CONTENT_DIR' => self::format_constant('WP_CONTENT_DIR'), 'WP_PLUGINS_DIR' => self::format_constant('WP_PLUGINS_DIR'), 'SUNRISE' => self::format_constant('SUNRISE'), 'UPLOADBLOGSDIR' => self::format_constant('UPLOADBLOGSDIR'), 'UPLOADS' => self::format_constant('UPLOADS'), 'SUBDOMAIN_INSTALL' => self::format_constant('SUBDOMAIN_INSTALL'), 'DOMAIN_CURRENT_SITE' => self::format_constant('DOMAIN_CURRENT_SITE'), 'PATH_CURRENT_SITE' => self::format_constant('PATH_CURRENT_SITE'), 'SITE_ID_CURRENT_SITE' => self::format_constant('SITE_ID_CURRENT_SITE'), 'BLOGID_CURRENT_SITE' => self::format_constant('BLOGID_CURRENT_SITE'), 'COOKIE_DOMAIN' => self::format_constant('COOKIE_DOMAIN'), 'COOKIEPATH' => self::format_constant('COOKIEPATH'), 'SITECOOKIEPATH' => self::format_constant('SITECOOKIEPATH'), 'DISABLE_WP_CRON' => self::format_constant('DISABLE_WP_CRON'), 'ALTERNATE_WP_CRON' => self::format_constant('ALTERNATE_WP_CRON'), 'DISALLOW_FILE_MODS' => self::format_constant('DISALLOW_FILE_MODS'), 'WP_HTTP_BLOCK_EXTERNAL' => self::format_constant('WP_HTTP_BLOCK_EXTERNAL'), 'WP_ACCESSIBLE_HOSTS' => self::format_constant('WP_ACCESSIBLE_HOSTS')); $server = explode(' ', $_SERVER['SERVER_SOFTWARE']); $server = explode('/', reset($server)); if (isset($server[1])) { $server_version = $server[1]; } else { $server_version = 'Unknown'; } $this->data['server'] = array('name' => $server[0], 'version' => $server_version, 'address' => $_SERVER['SERVER_ADDR'], 'host' => @php_uname('n')); $remote_get = wp_remote_get($wpmudev_un->server_url); $remote_post = wp_remote_post($wpmudev_un->server_url); $remote_paypal = wp_remote_post("https://api-3t.paypal.com/nvp", array('body' => '"METHOD=SetExpressCheckout&VERSION=63.0&USER=xxxxx&PWD=xxxxx&SIGNATURE=xxxxx')); $this->data['remote']['WPMU DEV: GET'] = is_wp_error($remote_get) ? $remote_get->get_error_message() : wp_remote_retrieve_response_message($remote_get); $this->data['remote']['WPMU DEV: POST'] = is_wp_error($remote_post) ? $remote_post->get_error_message() : wp_remote_retrieve_response_message($remote_post); $this->data['remote']['PayPal API: POST'] = is_wp_error($remote_paypal) ? $remote_paypal->get_error_message() : wp_remote_retrieve_response_message($remote_paypal); }
function download_url($url, $timeout = 300) { //WARNING: The file is not automatically deleted, The script must unlink() the file. if (!$url) { return new WP_Error('http_no_url', __('Invalid URL Provided.', 'themify-flow')); } $tmpfname = wp_tempnam($url); if (!$tmpfname) { return new WP_Error('http_no_file', __('Could not create Temporary file.', 'themify-flow')); } $response = wp_safe_remote_get($url, array('cookies' => $this->cookies, 'timeout' => $timeout, 'stream' => true, 'filename' => $tmpfname)); if (is_wp_error($response)) { unlink($tmpfname); return $response; } if (200 != wp_remote_retrieve_response_code($response)) { unlink($tmpfname); return new WP_Error('http_404', trim(wp_remote_retrieve_response_message($response))); } return $tmpfname; }
function check_error($response) { $msg = wp_remote_retrieve_response_message($response); $code = wp_remote_retrieve_response_code($response); echo '<br>Code = ' . $code . ', ' . $msg; switch ($code) { case '200': echo ' - Success!'; break; case '201': $body = wp_remote_retrieve_body($response); echo '<br>'; print_r($body); break; case '401': echo ' - Insufficient privileges, bad credentials, or malformed request.'; break; case '404': echo ' - Endpoint does not exist.'; break; case '413': // echo ' - Request Entity too Large.'; break; case '422': echo ' - No valid search predicate.'; break; default: echo 'Unexpected error'; } if ($code !== 200) { // Print error from response body $body = wp_remote_retrieve_body($response); echo '<br>'; print_r($body); } // end $code !== 200 echo '<br>'; return $code; }
protected static function download($url, $timeout = 300) { //WARNING: The file is not automatically deleted, The script must unlink() the file. if (!$url) { return new WP_Error('http_no_url', __('Invalid URL Provided.', 'wp-e-commerce')); } $tmpfname = wp_tempnam($url); if (!$tmpfname) { return new WP_Error('http_no_file', __('Could not create Temporary file.', 'wp-e-commerce')); } $args = array('timeout' => $timeout, 'stream' => true, 'filename' => $tmpfname, 'headers' => array('X-WP-Domain' => Sputnik_API::domain()), 'user-agent' => 'WP eCommerce Marketplace: ' . WPSC_VERSION); Sputnik_API::sign_download($url, $args); $response = wp_safe_remote_get($url, $args); if (is_wp_error($response)) { unlink($tmpfname); return $response; } if (200 != wp_remote_retrieve_response_code($response)) { unlink($tmpfname); return new WP_Error('http_404', trim(wp_remote_retrieve_response_message($response))); } return $tmpfname; }
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; } }
/** * Check for new messages. * * @return array|WP_Error Array of new messages or error. */ public function pull_updates() { $response = $this->client->get_undelivered_updates(); if (is_wp_error($response)) { return $response; } if (200 != wp_remote_retrieve_response_code($response)) { return new WP_Error(Prompt_Enum_Error_Codes::INBOUND, wp_remote_retrieve_response_message($response), $response); } $data = json_decode($response['body']); if (!isset($data->updates)) { return new WP_Error(Prompt_Enum_Error_Codes::INBOUND, __('Inbound messages arrived in an unrecognized format.', 'Postmatic'), $data); } if (!$data->updates) { $data->updates = array(); } $result_updates = array(); foreach ($data->updates as $update) { $result = array('id' => $update->id); $result['status'] = $this->process_update($update); $result_updates[] = $result; } return array('updates' => $result_updates); }
/** * Attempt to sniff out a new color palette based on the most recent post. * * @since 2.0.0 * * @return array|WP_Error */ public function refresh() { $this->styles = array(); $latest_post = get_posts(array('posts_per_page' => 1)); $sample_url = $latest_post ? get_permalink($latest_post[0]) : home_url(); // Stylify doesn't work for HTTPS scheme, try archive.org version $sample_url = preg_replace('/^https:/', 'http://web.archive.org/web/https:', $sample_url); $stylify_url = 'https://stylify.herokuapp.com/query?url=' . urlencode($sample_url); $get = wp_remote_get($stylify_url, array('timeout' => 30)); if (is_wp_error($get)) { return $get; } if (200 != $get['response']['code']) { return new WP_Error('wp_remote_get_error', wp_remote_retrieve_response_message($get)); } $data = json_decode(wp_remote_retrieve_body($get), true); if (isset($data['error'])) { return new WP_Error('stylify_error', $data['error']); } if (isset($data['a-text-colour']) and $this->is_acceptable_text_color($data['a-text-colour'])) { $this->styles['a']['color'] = $data['a-text-colour']; } $this->import_stylify_typography($data); }
/** * Downloads a url to a local temporary file using the WordPress HTTP Class. * Please note, That the calling function must unlink() the file. * * @since 2.5.0 * * @param string $url the URL of the file to download * @param int $timeout The timeout for the request to download the file default 300 seconds * @return mixed WP_Error on failure, string Filename on success. */ function download_url( $url, $timeout = 300 ) { //WARNING: The file is not automatically deleted, The script must unlink() the file. if ( ! $url ) return new WP_Error('http_no_url', __('Invalid URL Provided.')); $tmpfname = wp_tempnam($url); if ( ! $tmpfname ) return new WP_Error('http_no_file', __('Could not create Temporary file.')); $response = wp_safe_remote_get( $url, array( 'timeout' => $timeout, 'stream' => true, 'filename' => $tmpfname ) ); if ( is_wp_error( $response ) ) { unlink( $tmpfname ); return $response; } if ( 200 != wp_remote_retrieve_response_code( $response ) ){ unlink( $tmpfname ); return new WP_Error( 'http_404', trim( wp_remote_retrieve_response_message( $response ) ) ); } $content_md5 = wp_remote_retrieve_header( $response, 'content-md5' ); if ( $content_md5 ) { $md5_check = verify_file_md5( $tmpfname, $content_md5 ); if ( is_wp_error( $md5_check ) ) { unlink( $tmpfname ); return $md5_check; } } return $tmpfname; }
/** * Posts an image to Smush. * * @param $file_path path of file to send to Smush * @param $file_size * * @return bool|array array containing success status, and stats */ function _post($file_path, $file_size) { $data = false; $file = @fopen($file_path, 'r'); $file_data = fread($file, $file_size); $headers = array('accept' => 'application/json', 'content-type' => 'application/binary'); //Check if premium member, add API key $api_key = $this->_get_api_key(); if (!empty($api_key)) { $headers['apikey'] = $api_key; } //Check if lossy compression allowed and add it to headers $lossy = get_option(WP_SMUSH_PREFIX . 'lossy'); if ($lossy && $this->is_pro()) { $headers['lossy'] = 'true'; } else { $headers['lossy'] = 'false'; } $api_url = defined('WP_SMUSH_API_HTTP') ? WP_SMUSH_API_HTTP : WP_SMUSH_API; $args = array('headers' => $headers, 'body' => $file_data, 'timeout' => WP_SMUSH_TIMEOUT, 'user-agent' => WP_SMUSH_UA); $result = wp_remote_post($api_url, $args); //Close file connection fclose($file); unset($file_data); //free memory if (is_wp_error($result)) { $er_msg = $result->get_error_message(); //Hostgator Issue if (!empty($er_msg) && strpos($er_msg, 'SSL CA cert') !== false) { //Update DB for using http protocol update_option(WP_SMUSH_PREFIX . 'use_http', 1); } //Handle error $data['message'] = sprintf(__('Error posting to API: %s', 'wp-smushit'), $result->get_error_message()); $data['success'] = false; unset($result); //free memory return $data; } else { if ('200' != wp_remote_retrieve_response_code($result)) { //Handle error $data['message'] = sprintf(__('Error posting to API: %s %s', 'wp-smushit'), wp_remote_retrieve_response_code($result), wp_remote_retrieve_response_message($result)); $data['success'] = false; unset($result); //free memory return $data; } } //If there is a response and image was successfully optimised $response = json_decode($result['body']); if ($response && $response->success == true) { //If there is any savings if ($response->data->bytes_saved > 0) { $image = base64_decode($response->data->image); //base64_decode is necessary to send binary img over JSON, no security problems here! $image_md5 = md5($response->data->image); if ($response->data->image_md5 != $image_md5) { //Handle error $data['message'] = __('Smush data corrupted, try again.', 'wp-smushit'); $data['success'] = false; unset($image); //free memory } else { $data['success'] = true; $data['data'] = $response->data; $data['data']->image = $image; unset($image); //free memory } } else { //just return the data $data['success'] = true; $data['data'] = $response->data; } } else { //Server side error, get message from response $data['message'] = !empty($response->data) ? $response->data : __("Image couldn't be smushed", 'wp-smushit'); $data['success'] = false; } unset($result); //free memory unset($response); //free memory return $data; }
/** * 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; } }
/** * Download an external file via a URL * * @param string $url * @param int $timeout * @return string|WP_Error the location of the temporay file name or an error * @deprecated since 0.20.0 */ static function download_url($url, $timeout = 300) { if (!$url) { return new WP_Error('http_no_url', __('Invalid URL Provided.')); } $tmpfname = wp_tempnam($url); if (!$tmpfname) { return new WP_Error('http_no_file', __('Could not create Temporary file.')); } $response = wp_remote_get($url, array('timeout' => $timeout, 'stream' => true, 'filename' => $tmpfname)); if (is_wp_error($response)) { unlink($tmpfname); return $response; } if (200 != wp_remote_retrieve_response_code($response)) { unlink($tmpfname); return new WP_Error('http_404', trim(wp_remote_retrieve_response_message($response))); } return $tmpfname; }
/** * 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); } } }
/** * Fetch the contents of a URL. * * @author John Blackbourn * @param string $url URL to fetch. * @param array $args Array of arguments passed to wp_remote_get(). * @return WP_Error|string WP_Error object on failure, string contents of URL body on success. */ public static function fetch($url, array $args = array()) { $args = array_merge(array('timeout' => 5), $args); $response = wp_remote_get($url, $args); if (is_wp_error($response)) { return $response; } $code = wp_remote_retrieve_response_code($response); $message = wp_remote_retrieve_response_message($response); if (200 != $code) { return new WP_Error('fetch_failed', esc_html($code . ' ' . $message)); } return wp_remote_retrieve_body($response); }
/** * Cancel a member's payment profile * * @access public * @since 2.1 */ function rcp_cancel_member_payment_profile($member_id = 0, $set_status = true) { global $rcp_options; $success = false; $member = new RCP_Member($member_id); if (!rcp_can_member_cancel($member_id)) { return $success; } if (rcp_is_stripe_subscriber($member_id)) { if (!class_exists('Stripe\\Stripe')) { require_once RCP_PLUGIN_DIR . 'includes/libraries/stripe/init.php'; } if (rcp_is_sandbox()) { $secret_key = trim($rcp_options['stripe_test_secret']); } else { $secret_key = trim($rcp_options['stripe_live_secret']); } \Stripe\Stripe::setApiKey($secret_key); try { $subscription_id = $member->get_merchant_subscription_id(); $customer = \Stripe\Customer::retrieve($member->get_payment_profile_id()); if (!empty($subscription_id)) { $customer->subscriptions->retrieve($subscription_id)->cancel(array('at_period_end' => false)); } else { $customer->cancelSubscription(array('at_period_end' => false)); } $success = true; } catch (\Stripe\Error\InvalidRequest $e) { // Invalid parameters were supplied to Stripe's API $body = $e->getJsonBody(); $err = $body['error']; $error = "<h4>" . __('An error occurred', 'rcp') . "</h4>"; if (isset($err['code'])) { $error .= "<p>" . __('Error code:', 'rcp') . " " . $err['code'] . "</p>"; } $error .= "<p>Status: " . $e->getHttpStatus() . "</p>"; $error .= "<p>Message: " . $err['message'] . "</p>"; wp_die($error, __('Error', 'rcp'), array('response' => 401)); } catch (\Stripe\Error\Authentication $e) { // Authentication with Stripe's API failed // (maybe you changed API keys recently) $body = $e->getJsonBody(); $err = $body['error']; $error = "<h4>" . __('An error occurred', 'rcp') . "</h4>"; if (isset($err['code'])) { $error .= "<p>" . __('Error code:', 'rcp') . " " . $err['code'] . "</p>"; } $error .= "<p>Status: " . $e->getHttpStatus() . "</p>"; $error .= "<p>Message: " . $err['message'] . "</p>"; wp_die($error, __('Error', 'rcp'), array('response' => 401)); } catch (\Stripe\Error\ApiConnection $e) { // Network communication with Stripe failed $body = $e->getJsonBody(); $err = $body['error']; $error = "<h4>" . __('An error occurred', 'rcp') . "</h4>"; if (isset($err['code'])) { $error .= "<p>" . __('Error code:', 'rcp') . " " . $err['code'] . "</p>"; } $error .= "<p>Status: " . $e->getHttpStatus() . "</p>"; $error .= "<p>Message: " . $err['message'] . "</p>"; wp_die($error, __('Error', 'rcp'), array('response' => 401)); } catch (\Stripe\Error\Base $e) { // Display a very generic error to the user $body = $e->getJsonBody(); $err = $body['error']; $error = "<h4>" . __('An error occurred', 'rcp') . "</h4>"; if (isset($err['code'])) { $error .= "<p>" . __('Error code:', 'rcp') . " " . $err['code'] . "</p>"; } $error .= "<p>Status: " . $e->getHttpStatus() . "</p>"; $error .= "<p>Message: " . $err['message'] . "</p>"; wp_die($error, __('Error', 'rcp'), array('response' => 401)); } catch (Exception $e) { // Something else happened, completely unrelated to Stripe $error = "<h4>" . __('An error occurred', 'rcp') . "</h4>"; $error .= print_r($e, true); wp_die($error, __('Error', 'rcp'), array('response' => 401)); } } elseif (rcp_is_paypal_subscriber($member_id)) { if (rcp_has_paypal_api_access() && $member->get_payment_profile_id()) { // Set PayPal API key credentials. $api_username = rcp_is_sandbox() ? 'test_paypal_api_username' : 'live_paypal_api_username'; $api_password = rcp_is_sandbox() ? 'test_paypal_api_password' : 'live_paypal_api_password'; $api_signature = rcp_is_sandbox() ? 'test_paypal_api_signature' : 'live_paypal_api_signature'; $api_endpoint = rcp_is_sandbox() ? 'https://api-3t.sandbox.paypal.com/nvp' : 'https://api-3t.paypal.com/nvp'; $args = array('USER' => trim($rcp_options[$api_username]), 'PWD' => trim($rcp_options[$api_password]), 'SIGNATURE' => trim($rcp_options[$api_signature]), 'VERSION' => '124', 'METHOD' => 'ManageRecurringPaymentsProfileStatus', 'PROFILEID' => $member->get_payment_profile_id(), 'ACTION' => 'Cancel'); $error_msg = ''; $request = wp_remote_post($api_endpoint, array('body' => $args, 'timeout' => 30, 'httpversion' => '1.1')); if (is_wp_error($request)) { $success = false; $error_msg = $request->get_error_message(); } else { $body = wp_remote_retrieve_body($request); $code = wp_remote_retrieve_response_code($request); $message = wp_remote_retrieve_response_message($request); if (is_string($body)) { wp_parse_str($body, $body); } if (200 !== (int) $code) { $success = false; } if ('OK' !== $message) { $success = false; } if (isset($body['ACK']) && 'success' === strtolower($body['ACK'])) { $success = true; } else { $success = false; if (isset($body['L_LONGMESSAGE0'])) { $error_msg = $body['L_LONGMESSAGE0']; } } } if (!$success) { wp_die(sprintf(__('There was a problem cancelling the subscription, please contact customer support. Error: %s', 'rcp'), $error_msg), array('response' => 400)); } } } elseif (rcp_is_2checkout_subscriber($member_id)) { $cancelled = rcp_2checkout_cancel_member($member_id); if (is_wp_error($cancelled)) { wp_die($cancelled->get_error_message(), __('Error', 'rcp'), array('response' => 401)); } else { $success = true; } } if ($success && $set_status) { $member->cancel(); } return $success; }
/** * Tab: activation / Action: activate_token * * @since 1.0.0 */ public function do_activation_activate_token() { $_message_type = $this->message_type['err']; $_message = null; $submit_data = $this->validate_submit_data(); $_SESSION[$submit_data['active_tab']] = array_map('stripslashes_deep', $submit_data); if (!array_key_exists($this->domain_name, $submit_data) || empty($submit_data[$this->domain_name])) { $_message = __('Required data are not sent.', $this->domain_name); } if (!array_key_exists('access_token', $submit_data[$this->domain_name]) || empty($submit_data[$this->domain_name]['access_token'])) { $_message = __('Access token is not specified.', $this->domain_name); } $this->token = $submit_data[$this->domain_name]['access_token']; $url = $this->get_api_url(array('authenticated_user')); if (method_exists($this, 'request_api')) { $request_args = array('method' => 'GET', 'headers' => array('Content-Type' => 'application/json', 'Authorization' => 'Bearer ' . $this->token)); $response = wp_remote_request($url, $request_args); } else { // Note: I don't understand why it is not working if calling method in the inheritance original wrapper class, yet. // // @since 1.0.0 $response = $this->request_api($url, 'get', array()); } if ($this->validate_response_code($response)) { // Success $_parse_response = json_decode(wp_remote_retrieve_body($response)); $_qiita_user_meta = array_merge((array) $_parse_response, array('access_token' => $this->token, 'activated' => true)); $_current_user_meta = get_user_meta($submit_data['user_id'], 'wpqt_qiita_authenticated_user', true); if (!empty($_current_user_meta)) { $_qiita_user_meta = array_merge($_current_user_meta, $_qiita_user_meta); } update_user_meta($submit_data['user_id'], 'wpqt_qiita_authenticated_user', $_qiita_user_meta); $_message = __('Activation successful. You will work with Qiita.', $this->domain_name); $_message_type = $this->message_type['note']; } else { // Fails $_message = sprintf(__('Your request has been response of "%s". Please check again whether there is a miss in the access token.', $this->domain_name), wp_remote_retrieve_response_message($response)); } if (!empty($_message)) { $this->register_admin_notices($_message_type, $_message, 1, true); } return; }
/** * Test the response from each oEmbed provider when provided with invalid data * * @group external-oembed * @ticket 32360 * * @dataProvider oEmbedProviderData */ public function testOembedProviderHandlesInvalidData($match, array $urls) { if (empty($urls)) { $this->markTestIncomplete(); } $this->setup_http_hooks(); add_filter('oembed_fetch_url', array($this, 'filter_oembed_fetch_url'), 99, 3); $invalid = '500" onmouseover="alert(document.cookie)'; $args = array('width' => $invalid, 'height' => $invalid); // Only need to test with one URL for each provider $url = $urls[0]; $msg = sprintf("- Test URL: %s", $url); $provider = self::$oembed->get_provider($url, array('discover' => false)); $this->assertNotFalse($provider, "{$msg}\n- No oEmbed provider found."); $data = self::$oembed->fetch($provider, $url, $args); $r = $this->http_response; $msg .= sprintf("\n- oEmbed URL: %s", $r['url']); $query = parse_url($r['url'], PHP_URL_QUERY); parse_str($query, $query_vars); // Test request $this->assertInternalType('array', $query_vars, $msg); $this->assertArrayHasKey('maxheight', $query_vars, $msg); $this->assertArrayHasKey('maxwidth', $query_vars, $msg); $this->assertEquals($args['width'], $query_vars['maxwidth'], $msg); $this->assertEquals($args['height'], $query_vars['maxheight'], $msg); // `WP_oEmbed::fetch()` only returns boolean false, so we need to hook into the HTTP API to get its error if (is_wp_error($r['response'])) { $error_message = $r['response']->get_error_message(); if (empty($error_message)) { $error_message = '- no message -'; } $this->fail(sprintf("%s (%s)\n%s", $error_message, $r['response']->get_error_code(), $msg)); } $http_code = wp_remote_retrieve_response_code($r['response']); $http_message = wp_remote_retrieve_response_message($r['response']); $this->assertContains($http_code, array(200, 400, 404), "{$msg}\n- HTTP response code: {$http_code} {$http_message}"); if (false === $data) { // For an erroneous request, it's valid to return no data (or no JSON/XML, which evaluates to false) and // therefore the rest of the assertions can be skipped return; } // Check invalid data isn't echoed $this->assertNotContains('onmouseover', wp_remote_retrieve_body($r['response']), $msg); if (isset($data->width)) { $this->assertTrue(is_numeric($data->width), $msg); } if (isset($data->height)) { $this->assertTrue(is_numeric($data->height), $msg); } if (isset($data->thumbnail_width)) { $this->assertTrue(is_numeric($data->thumbnail_width), $msg); } if (isset($data->thumbnail_height)) { $this->assertTrue(is_numeric($data->thumbnail_height), $msg); } remove_filter('oembed_fetch_url', array($this, 'filter_oembed_fetch_url'), 99); $this->teardown_http_hooks(); }