/** * Check authentication and do update * */ public function table_test() { if (!defined('DOING_AJAX') && $this->has_auth()) { // Grab all config file and test them. $config_files = glob($this->get_config_dir() . '/db/*.php'); if (!empty($config_files)) { try { $messages = []; foreach ($config_files as $file) { $message = $this->db_update($file); if (!empty($message)) { $messages[] = $message; } } if (!empty($messages)) { add_action('admin_notices', function () use($messages) { printf('<div class="updated">%s</div>', implode('', array_map(function ($message) { return sprintf('<p>%s</p>', $message); }, $messages))); }); } } catch (\Exception $e) { wp_die(sprintf('[DB Error] Failed to parse DB configs: ' . $e->getMessage()), get_status_header_desc(500), ['response' => 500]); } } } }
function fetch_remote_file($url, $post) { global $url_remap; // 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 $headers = wp_get_http($url, $upload['file']); // request failed if (!$headers) { @unlink($upload['file']); return new WP_Error('import_file_error', __('Remote server did not respond', 'wordpress-importer')); } // make sure the fetch was successful if ($headers['response'] != '200') { @unlink($upload['file']); return new WP_Error('import_file_error', sprintf(__('Remote server returned error response %1$d %2$s', 'wordpress-importer'), esc_html($headers['response']), get_status_header_desc($headers['response']))); } $filesize = filesize($upload['file']); 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')); } // keep track of the old and new urls so we can substitute them later $url_remap[$url] = $upload['url']; return $upload; }
/** * @ticket 35426 */ public function test_http_response_code_constants() { global $wp_header_to_desc; $ref = new ReflectionClass('WP_Http'); $constants = $ref->getConstants(); // This primes the `$wp_header_to_desc` global: get_status_header_desc(200); $this->assertEquals(array_keys($wp_header_to_desc), array_values($constants)); }
/** * @param array $template * @param mixed $query * @param int $status_code * @param bool $tparams * @return bool */ public static function load_view($template, $query = false, $status_code = 200, $tparams = false) { $fullPath = is_readable($template); if (!$fullPath) { $template = locate_template($template); } if ($tparams) { global $params; $params = $tparams; } if ($status_code) { add_filter('status_header', function ($status_header, $header, $text, $protocol) use($status_code) { $text = get_status_header_desc($status_code); $header_string = "{$protocol} {$status_code} {$text}"; return $header_string; }, 10, 4); if (404 != $status_code) { add_action('parse_query', function ($query) { if ($query->is_main_query()) { $query->is_404 = false; } }, 1); add_action('template_redirect', function () { global $wp_query; $wp_query->is_404 = false; }, 1); } } if ($query) { add_action('do_parse_request', function () use($query) { global $wp; if (is_callable($query)) { $query = call_user_func($query); } if (is_array($query)) { $wp->query_vars = $query; } elseif (!empty($query)) { parse_str($query, $wp->query_vars); } else { return true; } // Could not interpret query. Let WP try. return false; }); } if ($template) { add_filter('template_include', function ($t) use($template) { return $template; }); return true; } return false; }
public function addHeader($status_header) { global $clmvc_http_code; if ($clmvc_http_code) { header_remove('X-Powered-By'); header_remove('X-Pingback'); header_remove('Pragma'); $description = get_status_header_desc($clmvc_http_code); $protocol = 'HTTP/1.0'; $status_header = "{$protocol} {$clmvc_http_code} {$description}"; } return $status_header; }
public static function findById($app, $taxonomy_name, $id) { $taxonomy = Taxonomies::findById($app, $taxonomy_name); $term = self::model()->findById($taxonomy_name, $id); if (!$term) { $app->halt('404', get_status_header_desc('404')); } if ($lastModified = apply_filters('thermal_term_last_modified', false)) { $app->lastModified(strtotime($lastModified . ' GMT')); } self::format($term, 'read'); return $term; }
/** * wp_redirect_status() * * @param int $status_code * @return int $status_code **/ static function wp_redirect_status($status_code) { $text = get_status_header_desc($status_code); $protocol = $_SERVER["SERVER_PROTOCOL"]; if ('HTTP/1.1' != $protocol && 'HTTP/1.0' != $protocol) { $protocol = 'HTTP/1.0'; } $status_header = "{$protocol} {$status_code} {$text}"; if (function_exists('apply_filters')) { $status_header = apply_filters('status_header', $status_header, $status_code, $text, $protocol); } return $status_code; }
/** * Check comment stability * * @param int $comment_post_ID */ public function preprocess_comment_submit($comment_post_ID) { if (!is_user_logged_in() && $this->is_thread(get_post_type($comment_post_ID)) && $this->input->verify_nonce('nichan_comment', '_nichancommentnonce')) { $recaptcha = $this->recaptcha->verify($this->option->recaptcha_priv_key, $this->input->post('g-recaptcha-response'), $this->input->remote_ip()); if (!$recaptcha || is_wp_error($recaptcha)) { // This is anonymous comment. wp_die(__('Anonimous comment requires spam check of reCAPTCHA', '2ch'), get_status_header_desc(401) . ' | ' . get_bloginfo('name'), array('back_link' => true, 'response' => 401)); } else { // Set current user as Anonymous user. wp_set_current_user($this->option->post_as); } } }
public static function findById($app, $id) { if (($list_users_cap = self::get_list_users_cap()) && !current_user_can($list_users_cap) && $id !== get_current_user_id()) { $app->halt('403', get_status_header_desc('403')); } $model = self::model(); $user = $model->findById($id); if (!$user) { $user->halt('404', get_status_header_desc('404')); } self::format($user, 'read'); return $user; }
/** * Constructor * * @param array $setting */ public function __construct(array $setting = []) { try { $this->test_setting($setting); $setting = $this->parse_args($setting); $this->setting = $setting; } catch (\Exception $e) { if (headers_sent()) { // Header sent. printf('<div class="error"><p>%s</p></div>', $e->getMessage()); } else { // Header didn't sent wp_die($e->getMessage(), get_status_header_desc($e->getCode()), ['response' => $e->getCode(), 'back_link' => true]); } } }
public static function findById($app, $id) { $taxonomy = self::model()->findById($id); if (!$taxonomy) { $app->halt('404', get_status_header_desc('404')); } if (!$taxonomy->public) { if (is_user_logged_in()) { if (!current_user_can($taxonomy->cap->manage_terms, $taxonomy->ID)) { $app->halt('403', get_status_header_desc('403')); } } else { $app->halt('401', get_status_header_desc('401')); } } self::format($taxonomy, 'read'); return $taxonomy; }
/** * Callback for the API endpoint. * * Returns the JSON object for the post. * * @since 4.4.0 * * @param WP_REST_Request $request Full data about the request. * @return WP_Error|array oEmbed response data or WP_Error on failure. */ public function get_item($request) { $post_id = url_to_postid($request['url']); /** * Filter the determined post ID. * * @since 4.4.0 * * @param int $post_id The post ID. * @param string $url The requested URL. */ $post_id = apply_filters('oembed_request_post_id', $post_id, $request['url']); $data = get_oembed_response_data($post_id, $request['maxwidth']); if (!$data) { return new WP_Error('oembed_invalid_url', get_status_header_desc(404), array('status' => 404)); } return $data; }
/** * @param int $status Http status code * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ private function setupStatusCode($status) { add_filter('status_header', function ($statusHeader, $header, $text, $protocol) use($status) { $text = get_status_header_desc($status); $header = "{$protocol} {$status} {$text}"; return $header; }, 10, 4); if ($status == 404) { return; } add_action('parse_query', function ($query) { if ($query->is_main_query()) { $query->is_404 = false; } }); add_action('template_redirect', function () { global $wp_query; $wp_query->is_404 = false; }); }
public static function findById($app, $id) { $post = self::model()->findById($id); if (!$post) { $app->halt('404', get_status_header_desc('404')); } $post_type_obj = get_post_type_object(get_post_type($post)); $post_status_obj = get_post_status_object(get_post_status($post)); if (is_user_logged_in()) { if (!current_user_can($post_type_obj->cap->read, $post->ID)) { $app->halt('403', get_status_header_desc('403')); } } elseif (!($post_type_obj->public && $post_status_obj->public)) { $app->halt('401', get_status_header_desc('401')); } if ($lastModified = apply_filters('thermal_post_last_modified', $post->post_modified_gmt)) { $app->lastModified(strtotime($lastModified . ' GMT')); } self::format($post, 'read'); return $post; }
/** * Filter and validate the parameters that will be passed to the model. * @param array $request_args * @return array */ protected static function convert_request($request_args) { // Remove any args that are not allowed by the API $request_filters = array('before' => array(), 'after' => array(), 's' => array(), 'paged' => array(), 'per_page' => array('\\intval'), 'offset' => array('\\intval'), 'orderby' => array(), 'order' => array(), 'in' => array('\\Voce\\Thermal\\v1\\toArray', '\\Voce\\Thermal\\v1\\applyInt'), 'parent' => array('\\intval'), 'post_id' => array('\\intval'), 'post_name' => array(), 'type' => array(), 'status' => array(), 'user_id' => array('\\intval'), 'include_found' => array('\\Voce\\Thermal\\v1\\toBool')); //strip any nonsafe args $request_args = array_intersect_key($request_args, $request_filters); //run through basic sanitation foreach ($request_args as $key => $value) { foreach ($request_filters[$key] as $callback) { $value = call_user_func($callback, $value); } $request_args[$key] = $value; } //make sure per_page is below MAX if (!empty($request_args['per_page'])) { if (absint($request_args['per_page']) > \Voce\Thermal\v1\MAX_TERMS_PER_PAGE) { $request_args['per_page'] = \Voce\Thermal\v1\MAX_COMMENTS_PER_PAGE; } else { $request_args['per_page'] = absint($request_args['per_page']); } } //filter status by user privelages if (isset($request_args['status']) && $request_args['status'] !== 'approve') { if (is_user_logged_in()) { if (!current_user_can('moderate_comments')) { $app->halt('403', get_status_header_desc('403')); } } else { $app->halt('401', get_status_header_desc('401')); } } if (!empty($request_args['per_page']) && $request_args['per_page'] > \Voce\Thermal\v1\MAX_POSTS_PER_PAGE) { $request_args['per_page'] = \Voce\Thermal\v1\MAX_POSTS_PER_PAGE; } if (!empty($request_args['paged']) && !isset($request_args['include_found'])) { $request_args['include_found'] = true; } return $request_args; }
/** * Set HTTP status header. * * @since 2.0.0 * * @see get_status_header_desc() * * @param int $code HTTP status code. */ function status_header($code) { $description = get_status_header_desc($code); if (empty($description)) { return; } $protocol = $_SERVER['SERVER_PROTOCOL']; if ('HTTP/1.1' != $protocol && 'HTTP/1.0' != $protocol) { $protocol = 'HTTP/1.0'; } $status_header = "{$protocol} {$code} {$description}"; if (function_exists('apply_filters')) { /** * Filter an HTTP status header. * * @since 2.2.0 * * @param string $status_header HTTP status header. * @param int $code HTTP status code. * @param string $description Description for the status code. * @param string $protocol Server protocol. */ $status_header = apply_filters('status_header', $status_header, $code, $description, $protocol); } @header($status_header, true, $code); }
/** * Set HTTP status header. * * @since 2.0.0 * @since 4.4.0 Added the `$description` parameter. * * @see get_status_header_desc() * * @param int $code HTTP status code. * @param string $description Optional. A custom description for the HTTP status. */ function status_header($code, $description = '') { if (!$description) { $description = get_status_header_desc($code); } if (empty($description)) { return; } $protocol = wp_get_server_protocol(); $status_header = "{$protocol} {$code} {$description}"; if (function_exists('apply_filters')) { /** * Filter an HTTP status header. * * @since 2.2.0 * * @param string $status_header HTTP status header. * @param int $code HTTP status code. * @param string $description Description for the status code. * @param string $protocol Server protocol. */ $status_header = apply_filters('status_header', $status_header, $code, $description, $protocol); } @header($status_header, true, $code); }
/** * status_header * Set HTTP status header from status code * @Inspired from WordPress */ function status_header($code) { $desc = get_status_header_desc($code); if (empty($desc)) { return false; } $protocol = $_SERVER['SERVER_PROTOCOL']; if ('HTTP/1.1' != $protocol && 'HTTP/1.0' != $protocol) { $protocol = 'HTTP/1.0'; } $status_header = "{$protocol} {$code} {$desc}"; return @header($status_header, true, $code); }
function fetch_remote_file($post, $url) { add_filter('http_request_timeout', array(&$this, 'bump_request_timeout')); $upload = wp_upload_dir($post['post_date']); // 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['post_date']); if ($upload['error']) { echo $upload['error']; return new WP_Error('upload_dir_error', $upload['error']); } // fetch the remote url and write it to the placeholder file $headers = wp_get_http($url, $upload['file']); //Request failed if (!$headers) { @unlink($upload['file']); return new WP_Error('import_file_error', __('Remote server did not respond', 'wordpress-importer')); } // make sure the fetch was successful if ($headers['response'] != '200') { @unlink($upload['file']); return new WP_Error('import_file_error', sprintf(__('Remote file returned error response %1$d %2$s', 'wordpress-importer'), $headers['response'], get_status_header_desc($headers['response']))); } elseif (isset($headers['content-length']) && filesize($upload['file']) != $headers['content-length']) { @unlink($upload['file']); return new WP_Error('import_file_error', __('Remote file is incorrect size', 'wordpress-importer')); } $max_size = $this->max_attachment_size(); if (!empty($max_size) and filesize($upload['file']) > $max_size) { @unlink($upload['file']); return new WP_Error('import_file_error', sprintf(__('Remote file is too large, limit is %s', size_format($max_size), 'wordpress-importer'))); } // keep track of the old and new urls so we can substitute them later $this->url_remap[$url] = $upload['url']; $this->url_remap[$post['guid']] = $upload['url']; // if the remote url is redirected somewhere else, keep track of the destination too if ($headers['x-final-location'] != $url) { $this->url_remap[$headers['x-final-location']] = $upload['url']; } return $upload; }
/** * Fetches remote images. * * @param type $url * @return \WP_Error */ function wpcf_fields_image_get_remote($url) { global $wpcf; $refresh = false; // Set directory $cache_dir = wpcf_fields_image_get_cache_directory(); if (is_wp_error($cache_dir)) { return $cache_dir; } // Validate image $extension = pathinfo($url, PATHINFO_EXTENSION); if (!in_array(strtolower($extension), wpcf_fields_image_valid_extension())) { return new WP_Error('wpcf_image_cache_not_valid', sprintf(__('Image %s not valid', 'wpcf'), $url)); } $image = $cache_dir . md5($url) . '.' . $extension; // Refresh if necessary $refresh_time = intval(wpcf_get_settings('images_remote_cache_time')); if ($refresh_time != 0 && file_exists($image)) { $time_modified = filemtime($image); if (time() - $time_modified > $refresh_time * 60 * 60) { $refresh = true; $files = glob($cache_dir . DIRECTORY_SEPARATOR . md5($url) . "-*"); if ($files) { foreach ($files as $filename) { @unlink($filename); } } } } // Check if image is fetched if ($refresh || !file_exists($image)) { // fetch the remote url and write it to the placeholder file add_filter('http_request_timeout', 'wpcf_image_http_request_timeout', 10, 1); $resp = wp_safe_remote_get($url); // Check if response type is expected if (is_object($resp)) { return new WP_Error('wpcf_image_cache_file_error', sprintf(__('Remote server returned error response %1$d %2$s', 'wpcf'), esc_html($resp->errors["http_request_failed"][0]), get_status_header_desc($resp->errors["http_request_failed"][0]))); } remove_filter('http_request_timeout', 'wpcf_image_http_request_timeout', 10, 1); // make sure the fetch was successful if ($resp['response']['code'] != '200') { return new WP_Error('wpcf_image_cache_file_error', sprintf(__('Remote server returned error response %1$d %2$s', 'wpcf'), esc_html($resp['response']), get_status_header_desc($resp['response']))); } if (!isset($resp['headers']['content-length']) || strlen($resp['body']) != $resp['headers']['content-length']) { return new WP_Error('wpcf_image_cache_file_error', __('Remote file is incorrect size', 'wpcf')); } $out_fp = fopen($image, 'w'); if (!$out_fp) { return new WP_Error('wpcf_image_cache_file_error', __('Could not create cache file', 'wpcf')); } fwrite($out_fp, $resp['body']); fclose($out_fp); $max_size = (int) apply_filters('import_attachment_size_limit', 0); $filesize = filesize($image); if (!empty($max_size) && $filesize > $max_size) { @unlink($image); return new WP_Error('wpcf_image_cache_file_error', sprintf(__('Remote file is too large, limit is %s', 'wpcf'), size_format($max_size))); } } return array('abspath' => $image, 'relpath' => wpcf_image_attachment_url($image)); }
function action_codes() { return array(404 => get_status_header_desc(404), 410 => get_status_header_desc(410)); }
function show() { $codes = array(301 => get_status_header_desc(301), 302 => get_status_header_desc(302), 307 => get_status_header_desc(307)); ?> <tr> <th width="100"><?php _e('Referrer', 'redirection'); ?> :</th> <td valign="top"> <input style="width: 85%" type="text" name="referrer" value="<?php echo esc_attr($this->referrer); ?> "/> <label><?php _e('Regex', 'redirection'); ?> : <input type="checkbox" name="regex" <?php if ($this->regex === true) { echo ' checked="checked"'; } ?> /></label> </td> </tr> <tr> <th><?php _e('HTTP Code', 'redirection'); ?> :</th> <td> <select name="action_code"> <?php foreach ($codes as $key => $code) { ?> <option value="<?php echo $key; ?> "<?php if ($key === intval($this->action_code)) { echo ' selected="selected"'; } ?> ><?php printf('%s - %s', $key, $code); ?> </option> <?php } ?> </select> </td> </tr> <tr> <th><?php _e('HTTP Code', 'redirection'); ?> :</th> <td> <p style="padding: 0.5em"><?php _e('The visitor will be redirected from the source URL if the referrer matches. You can specify a <em>matched</em> target URL as the address to send visitors if they do match, and <em>not matched</em> if they don\'t match. Leaving a URL blank means that the visitor is not redirected.', 'redirection'); ?> </p> </td> </tr> <tr> <th width="100" valign="top"> <?php if (strlen($this->url_from) > 0) { ?> <a target="_blank" href="<?php echo esc_url($this->url_from); ?> "><?php _e('Matched', 'redirection'); ?> :</a> <?php } else { ?> <?php _e('Matched', 'redirection'); ?> : <?php } ?> </th> <td valign="top"><input style="width: 95%" type="text" name="url_from" value="<?php echo esc_attr($this->url_from); ?> " id="new"/></td> </tr> <tr> <th width="100" valign="top"> <?php if (strlen($this->url_notfrom) > 0) { ?> <a target="_blank" href="<?php echo $this->url_notfrom; ?> "><?php _e('Not matched', 'redirection'); ?> :</a> <?php } else { ?> <?php _e('Not matched', 'redirection'); ?> : <?php } ?> </th> <td valign="top"> <input style="width: 95%" type="text" name="url_notfrom" value="<?php echo esc_attr($this->url_notfrom); ?> " id="new"/><br/> </td> </tr> <?php }
/** * Print the oEmbed XML response. * * @since 4.4.0 * * @param array $data The oEmbed response data. * @return string The XML response data. */ public function xml_response($data) { if (!class_exists('SimpleXMLElement')) { status_header(501); return get_status_header_desc(501); } $result = _oembed_create_xml($data); // Bail if there's no XML. if (!$result) { status_header(501); return get_status_header_desc(501); } if (!headers_sent()) { header('Content-Type: text/xml; charset=' . get_option('blog_charset')); } return $result; }
/** * Send a HTTP request to a URI using cURL extension. * * @access public * @since 2.7.0 * * @param string $url * @param str|array $args Optional. Override the defaults. * @return array 'headers', 'body', 'cookies' and 'response' keys. */ function request($url, $args = array()) { $defaults = array('method' => 'GET', 'timeout' => 5, 'redirection' => 5, 'httpversion' => '1.0', 'blocking' => true, 'headers' => array(), 'body' => null, 'cookies' => array()); $r = wp_parse_args($args, $defaults); if (isset($r['headers']['User-Agent'])) { $r['user-agent'] = $r['headers']['User-Agent']; unset($r['headers']['User-Agent']); } else { if (isset($r['headers']['user-agent'])) { $r['user-agent'] = $r['headers']['user-agent']; unset($r['headers']['user-agent']); } } // Construct Cookie: header if any cookies are set. WP_Http::buildCookieHeader($r); // cURL extension will sometimes fail when the timeout is less than 1 as it may round down // to 0, which gives it unlimited timeout. if ($r['timeout'] > 0 && $r['timeout'] < 1) { $r['timeout'] = 1; } $handle = curl_init(); // cURL offers really easy proxy support. $proxy = new WP_HTTP_Proxy(); if ($proxy->is_enabled() && $proxy->send_through_proxy($url)) { $isPHP5 = version_compare(PHP_VERSION, '5.0.0', '>='); if ($isPHP5) { curl_setopt($handle, CURLOPT_PROXYTYPE, CURLPROXY_HTTP); curl_setopt($handle, CURLOPT_PROXY, $proxy->host()); curl_setopt($handle, CURLOPT_PROXYPORT, $proxy->port()); } else { curl_setopt($handle, CURLOPT_PROXY, $proxy->host() . ':' . $proxy->port()); } if ($proxy->use_authentication()) { if ($isPHP5) { curl_setopt($handle, CURLOPT_PROXYAUTH, CURLAUTH_BASIC); } curl_setopt($handle, CURLOPT_PROXYUSERPWD, $proxy->authentication()); } } $is_local = isset($args['local']) && $args['local']; $ssl_verify = isset($args['sslverify']) && $args['sslverify']; if ($is_local) { $ssl_verify = apply_filters('https_local_ssl_verify', $ssl_verify); } elseif (!$is_local) { $ssl_verify = apply_filters('https_ssl_verify', $ssl_verify); } curl_setopt($handle, CURLOPT_URL, $url); curl_setopt($handle, CURLOPT_RETURNTRANSFER, true); curl_setopt($handle, CURLOPT_SSL_VERIFYHOST, $ssl_verify); curl_setopt($handle, CURLOPT_SSL_VERIFYPEER, $ssl_verify); curl_setopt($handle, CURLOPT_USERAGENT, $r['user-agent']); curl_setopt($handle, CURLOPT_CONNECTTIMEOUT, $r['timeout']); curl_setopt($handle, CURLOPT_TIMEOUT, $r['timeout']); curl_setopt($handle, CURLOPT_MAXREDIRS, $r['redirection']); switch ($r['method']) { case 'HEAD': curl_setopt($handle, CURLOPT_NOBODY, true); break; case 'POST': curl_setopt($handle, CURLOPT_POST, true); curl_setopt($handle, CURLOPT_POSTFIELDS, $r['body']); break; case 'PUT': curl_setopt($handle, CURLOPT_CUSTOMREQUEST, 'PUT'); curl_setopt($handle, CURLOPT_POSTFIELDS, $r['body']); break; } if (true === $r['blocking']) { curl_setopt($handle, CURLOPT_HEADER, true); } else { curl_setopt($handle, CURLOPT_HEADER, false); } // The option doesn't work with safe mode or when open_basedir is set. if (!ini_get('safe_mode') && !ini_get('open_basedir')) { curl_setopt($handle, CURLOPT_FOLLOWLOCATION, true); } if (!empty($r['headers'])) { // cURL expects full header strings in each element $headers = array(); foreach ($r['headers'] as $name => $value) { $headers[] = "{$name}: {$value}"; } curl_setopt($handle, CURLOPT_HTTPHEADER, $headers); } if ($r['httpversion'] == '1.0') { curl_setopt($handle, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); } else { curl_setopt($handle, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); } // Cookies are not handled by the HTTP API currently. Allow for plugin authors to handle it // themselves... Although, it is somewhat pointless without some reference. do_action_ref_array('http_api_curl', array(&$handle)); // We don't need to return the body, so don't. Just execute request and return. if (!$r['blocking']) { curl_exec($handle); curl_close($handle); return array('headers' => array(), 'body' => '', 'response' => array('code' => false, 'message' => false), 'cookies' => array()); } $theResponse = curl_exec($handle); if (!empty($theResponse)) { $headerLength = curl_getinfo($handle, CURLINFO_HEADER_SIZE); $theHeaders = trim(substr($theResponse, 0, $headerLength)); $theBody = substr($theResponse, $headerLength); if (false !== strrpos($theHeaders, "\r\n\r\n")) { $headerParts = explode("\r\n\r\n", $theHeaders); $theHeaders = $headerParts[count($headerParts) - 1]; } $theHeaders = WP_Http::processHeaders($theHeaders); } else { if ($curl_error = curl_error($handle)) { return new WP_Error('http_request_failed', $curl_error); } if (in_array(curl_getinfo($handle, CURLINFO_HTTP_CODE), array(301, 302))) { return new WP_Error('http_request_failed', __('Too many redirects.')); } $theHeaders = array('headers' => array(), 'cookies' => array()); $theBody = ''; } $response = array(); $response['code'] = curl_getinfo($handle, CURLINFO_HTTP_CODE); $response['message'] = get_status_header_desc($response['code']); curl_close($handle); if (true === $r['decompress'] && true === WP_Http_Encoding::should_decode($theHeaders['headers'])) { $theBody = WP_Http_Encoding::decompress($theBody); } return array('headers' => $theHeaders['headers'], 'body' => $theBody, 'response' => $response, 'cookies' => $theHeaders['cookies']); }
function upload_handler() { if ('POST' !== strtoupper($_SERVER['REQUEST_METHOD'])) { return new Jetpack_Error(405, get_status_header_desc(405), 405); } $user = wp_authenticate('', ''); if (!$user || is_wp_error($user)) { return new Jetpack_Error(403, get_status_header_desc(403), 403); } wp_set_current_user($user->ID); if (!current_user_can('upload_files')) { return new Jetpack_Error('cannot_upload_files', 'User does not have permission to upload files', 403); } if (empty($_FILES)) { return new Jetpack_Error('no_files_uploaded', 'No files were uploaded: nothing to process', 400); } foreach (array_keys($_FILES) as $files_key) { if (!isset($_POST["_jetpack_file_hmac_{$files_key}"])) { return new Jetpack_Error('missing_hmac', 'An HMAC for one or more files is missing', 400); } } $media_keys = array_keys($_FILES['media']); $token = Jetpack_Data::get_access_token(get_current_user_id()); if (!$token || is_wp_error($token)) { return new Jetpack_Error('unknown_token', 'Unknown Jetpack token', 403); } $uploaded_files = array(); $global_post = isset($GLOBALS['post']) ? $GLOBALS['post'] : null; unset($GLOBALS['post']); foreach ($_FILES['media']['name'] as $index => $name) { $file = array(); foreach ($media_keys as $media_key) { $file[$media_key] = $_FILES['media'][$media_key][$index]; } list($hmac_provided, $salt) = explode(':', $_POST['_jetpack_file_hmac_media'][$index]); $hmac_file = hash_hmac_file('sha1', $file['tmp_name'], $salt . $token->secret); if ($hmac_provided !== $hmac_file) { $uploaded_files[$index] = (object) array('error' => 'invalid_hmac', 'error_description' => 'The corresponding HMAC for this file does not match'); continue; } $_FILES['.jetpack.upload.'] = $file; $post_id = isset($_POST['post_id'][$index]) ? absint($_POST['post_id'][$index]) : 0; if (!current_user_can('edit_post', $post_id)) { $post_id = 0; } $attachment_id = media_handle_upload('.jetpack.upload.', $post_id, array(), array('action' => 'jetpack_upload_file')); if (!$attachment_id) { $uploaded_files[$index] = (object) array('error' => 'unknown', 'error_description' => 'An unknown problem occurred processing the upload on the Jetpack site'); } elseif (is_wp_error($attachment_id)) { $uploaded_files[$index] = (object) array('error' => 'attachment_' . $attachment_id->get_error_code(), 'error_description' => $attachment_id->get_error_message()); } else { $attachment = get_post($attachment_id); $uploaded_files[$index] = (object) array('id' => (string) $attachment_id, 'file' => $attachment->post_title, 'url' => wp_get_attachment_url($attachment_id), 'type' => $attachment->post_mime_type, 'meta' => wp_get_attachment_metadata($attachment_id)); } } if (!is_null($global_post)) { $GLOBALS['post'] = $global_post; } return $uploaded_files; }
/** * 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 */ 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 $headers = wp_get_http($url, $upload['file']); // request failed if (!$headers) { @unlink($upload['file']); return new WP_Error('import_file_error', __('Remote server did not respond', 'radium')); } // make sure the fetch was successful if ($headers['response'] != '200') { @unlink($upload['file']); return new WP_Error('import_file_error', sprintf(__('Remote server returned error response %1$d %2$s', 'radium'), esc_html($headers['response']), get_status_header_desc($headers['response']))); } $filesize = filesize($upload['file']); if (isset($headers['content-length']) && $filesize != $headers['content-length']) { @unlink($upload['file']); return new WP_Error('import_file_error', __('Remote file is incorrect size', 'radium')); } if (0 == $filesize) { @unlink($upload['file']); return new WP_Error('import_file_error', __('Zero size file downloaded', 'radium')); } $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', 'radium'), size_format($max_size))); } // keep track of the old and new urls so we can substitute them later $this->url_remap[$url] = $upload['url']; $this->url_remap[$post['guid']] = $upload['url']; // r13735, really needed? // keep track of the destination if the remote url is redirected somewhere else if (isset($headers['x-final-location']) && $headers['x-final-location'] != $url) { $this->url_remap[$headers['x-final-location']] = $upload['url']; } return $upload; }
/** * Set HTTP status header. * * @since 2.0.0 * @uses apply_filters() Calls 'status_header' on status header string, HTTP * HTTP code, HTTP code description, and protocol string as separate * parameters. * * @param int $header HTTP status code * @return null Does not return anything. */ function status_header($header) { $text = get_status_header_desc($header); if (empty($text)) { return false; } $protocol = $_SERVER["SERVER_PROTOCOL"]; if ('HTTP/1.1' != $protocol && 'HTTP/1.0' != $protocol) { $protocol = 'HTTP/1.0'; } $status_header = "{$protocol} {$header} {$text}"; if (function_exists('apply_filters')) { $status_header = apply_filters('status_header', $status_header, $header, $text, $protocol); } if (version_compare(phpversion(), '4.3.0', '>=')) { return @header($status_header, true, $header); } else { return @header($status_header); } }
/** * Converts the object to a WP_Http response array. * * @since 4.6.0 * @access public * * @return array WP_Http response array, per WP_Http::request(). */ public function to_array() { return array('headers' => $this->get_headers(), 'body' => $this->get_data(), 'response' => array('code' => $this->get_status(), 'message' => get_status_header_desc($this->get_status())), 'cookies' => $this->get_cookies(), 'filename' => $this->filename); }
/** * Hooks into the REST API output to print XML instead of JSON. * * This is only done for the oEmbed API endpoint, * which supports both formats. * * @access private * @since 4.4.0 * * @param bool $served Whether the request has already been served. * @param WP_HTTP_ResponseInterface $result Result to send to the client. Usually a WP_REST_Response. * @param WP_REST_Request $request Request used to generate the response. * @param WP_REST_Server $server Server instance. * @return true */ function _oembed_rest_pre_serve_request($served, $result, $request, $server) { $params = $request->get_params(); if ('/oembed/1.0/embed' !== $request->get_route() || 'GET' !== $request->get_method()) { return $served; } if (!isset($params['format']) || 'xml' !== $params['format']) { return $served; } // Embed links inside the request. $data = $server->response_to_data($result, false); if (404 === $result->get_status()) { $data = $data[0]; } if (!class_exists('SimpleXMLElement')) { status_header(501); die(get_status_header_desc(501)); } $result = _oembed_create_xml($data); // Bail if there's no XML. if (!$result) { status_header(501); return get_status_header_desc(501); } if (!headers_sent()) { $server->send_header('Content-Type', 'text/xml; charset=' . get_option('blog_charset')); } echo $result; return true; }
function evc_fetch_remote_file($args) { if (!empty($args)) { extract($args); } //$post_date = date('Y-m-d H:i:s'); $upload = wp_upload_dir(); $upload = wp_upload_bits($file_name, 0, ''); if ($upload['error']) { return new WP_Error('upload_dir_error', $upload['error']); } $headers = wp_get_http($url, $upload['file']); if (!$headers) { @unlink($upload['file']); return new WP_Error('import_file_error', __('Remote server did not respond', 'evc')); } if ($headers['response'] != '200') { @unlink($upload['file']); return new WP_Error('import_file_error', sprintf(__('Remote server says: %1$d %2$s', 'evc'), $headers['response'], get_status_header_desc($headers['response']))); } elseif (isset($headers['content-length']) && filesize($upload['file']) != $headers['content-length']) { @unlink($upload['file']); return new WP_Error('import_file_error', __('Remote file is incorrect size', 'evc')); } $max_size = (int) get_site_option('fileupload_maxk') * 1024; // fileupload_maxk for wpmu compatibility $file_size = filesize($upload['file']); if (!empty($max_size) && $file_size > $max_size) { @unlink($upload['file']); return new WP_Error('import_file_error', sprintf(__('Remote file is %1$d KB but limit is %2$d', 'evc'), $file_size / 1024, $max_size / 1024)); } // This check is for wpmu compatibility if (function_exists('get_space_allowed')) { $space_allowed = 1048576 * get_space_allowed(); $space_used = get_dirsize(BLOGUPLOADDIR); $space_left = $space_allowed - $space_used; if ($space_left < 0) { @unlink($upload['file']); return new WP_Error('not_enough_diskspace', sprintf(__('You have %1$d KB diskspace used but %2$d allowed.', 'evc'), $space_used / 1024, $space_allowed / 1024)); } } $upload['content-type'] = $headers['content-type']; return $upload; }