/ $locales = apply_filters( 'plugins_update_check_locales', $locales ); $locales = array_unique( $locales ); if ( $doing_cron ) { $timeout = 30; // 30 seconds. } else { // Three seconds, plus one extra second for every 10 plugins. $timeout = 3 + (int) ( count( $plugins ) / 10 ); } $options = array( 'timeout' => $timeout, 'body' => array( 'plugins' => wp_json_encode( $to_send ), 'translations' => wp_json_encode( $translations ), 'locale' => wp_json_encode( $locales ), 'all' => wp_json_encode( true ), ), 'user-agent' => 'WordPress/' . $wp_version . '; ' . home_url( '/' ), ); if ( $extra_stats ) { $options['body']['update_stats'] = wp_json_encode( $extra_stats ); } $url = 'http://api.wordpress.org/plugins/update-check/1.1/'; $http_url = $url; $ssl = wp_http_supports( array( 'ssl' ) ); if ( $ssl ) { $url = set_url_scheme( $url, 'https' ); } $raw_response = wp_remote_post( $url, $options ); if ( $ssl && is_wp_error( $raw_response ) ) { trigger_error( sprintf( /* translators: %s: Support forums URL. */ __( 'An unexpected error occurred. Something may be wrong with WordPress.org or this server’s configuration. If you continue to have problems, please try the support forums.' ), __( 'https://wordpress.org/support/forums/' ) ) . ' ' . __( '(WordPress could not establish a secure connection to WordPress.org. Please contact your server administrator.)' ), headers_sent() || WP_DEBUG ? E_USER_WARNING : E_USER_NOTICE ); $raw_response = wp_remote_post( $http_url, $options ); } if ( is_wp_error( $raw_response ) || 200 !== wp_remote_retrieve_response_code( $raw_response ) ) { return; } $response = json_decode( wp_remote_retrieve_body( $raw_response ), true ); if ( $response && is_array( $response ) ) { $updates->response = $response['plugins']; $updates->translations = $response['translations']; $updates->no_update = $response['no_update']; } // Support updates for any plugins using the `Update URI` header field. foreach ( $plugins as $plugin_file => $plugin_data ) { if ( ! $plugin_data['UpdateURI'] || isset( $updates->response[ $plugin_file ] ) ) { continue; } $hostname = wp_parse_url( sanitize_url( $plugin_data['UpdateURI'] ), PHP_URL_HOST ); /** * Filters the update response for a given plugin hostname. * * The dynamic portion of the hook name, `$hostname`, refers to the hostname * of the URI specified in the `Update URI` header field. * * @since 5.8.0 * * @param array|false $update { * The plugin update data with the latest details. Default false. * * @type string $id Optional. ID of the plugin for update purposes, should be a URI * specified in the `Update URI` header field. * @type string $slug Slug of the plugin. * @type string $version The version of the plugin. * @type string $url The URL for details of the plugin. * @type string $package Optional. The update ZIP for the plugin. * @type string $tested Optional. The version of WordPress the plugin is tested against. * @type string $requires_php Optional. The version of PHP which the plugin requires. * @type bool $autoupdate Optional. Whether the plugin should automatically update. * @type array $icons Optional. Array of plugin icons. * @type array $banners Optional. Array of plugin banners. * @type array $banners_rtl Optional. Array of plugin RTL banners. * @type array $translations { * Optional. List of translation updates for the plugin. * * @type string $language The language the translation update is for. * @type string $version The version of the plugin this translation is for. * This is not the version of the language file. * @type string $updated The update timestamp of the translation file. * Should be a date in the `YYYY-MM-DD HH:MM:SS` format. * @type string $package The ZIP location containing the translation update. * @type string $autoupdate Whether the translation should be automatically installed. * } * } * @param array $plugin_data Plugin headers. * @param string $plugin_file Plugin filename. * @param string[] $locales Installed locales to look up translations for. */ $update = apply_filters( "update_plugins_{$hostname}", false, $plugin_data, $plugin_file, $locales ); if ( ! $update ) { continue; } $update = (object) $update; // Is it valid? We require at least a version. if ( ! isset( $update->version ) ) { continue; } // These should remain constant. $update->id = $plugin_data['UpdateURI']; $update->plugin = $plugin_file; // WordPress needs the version field specified as 'new_version'. if ( ! isset( $update->new_version ) ) { $update->new_version = $update->version; } // Handle any translation updates. if ( ! empty( $update->translations ) ) { foreach ( $update->translations as $translation ) { if ( isset( $translation['language'], $translation['package'] ) ) { $translation['type'] = 'plugin'; $translation['slug'] = isset( $update->slug ) ? $update->slug : $update->id; $updates->translations[] = $translation; } } } unset( $updates->no_update[ $plugin_file ], $updates->response[ $plugin_file ] ); if ( version_compare( $update->new_version, $plugin_data['Version'], '>' ) ) { $updates->response[ $plugin_file ] = $update; } else { $updates->no_update[ $plugin_file ] = $update; } } $sanitize_plugin_update_payload = static function ( &$item ) { $item = (object) $item; unset( $item->translations, $item->compatibility ); return $item; }; array_walk( $updates->response, $sanitize_plugin_update_payload ); array_walk( $updates->no_update, $sanitize_plugin_update_payload ); set_site_transient( 'update_plugins', $updates ); } /** * Checks for available updates to themes based on the latest versions hosted on WordPress.org. * * Despite its name this function does not actually perform any updates, it only checks for available updates. * * A list of all themes installed is sent to WP, along with the site locale. * * Checks against the WordPress server at api.wordpress.org. Will only check * if WordPress isn't installing. * * @since 2.7.0 * * @global string $wp_version The WordPress version string. * * @param array $extra_stats Extra statistics to report to the WordPress.org API. */ function wp_update_themes( $extra_stats = array() ) { if ( wp_installing() ) { return; } // Include an unmodified $wp_version. require ABSPATH . WPINC . '/version.php'; $installed_themes = wp_get_themes(); $translations = wp_get_installed_translations( 'themes' ); $last_update = get_site_transient( 'update_themes' ); if ( ! is_object( $last_update ) ) { $last_update = new stdClass(); } $themes = array(); $checked = array(); $request = array(); // Put slug of active theme into request. $request['active'] = get_option( 'stylesheet' ); foreach ( $installed_themes as $theme ) { $checked[ $theme->get_stylesheet() ] = $theme->get( 'Version' ); $themes[ $theme->get_stylesheet() ] = array( 'Name' => $theme->get( 'Name' ), 'Title' => $theme->get( 'Name' ), 'Version' => $theme->get( 'Version' ), 'Author' => $theme->get( 'Author' ), 'Author URI' => $theme->get( 'AuthorURI' ), 'UpdateURI' => $theme->get( 'UpdateURI' ), 'Template' => $theme->get_template(), 'Stylesheet' => $theme->get_stylesheet(), ); } $doing_cron = wp_doing_cron(); // Check for update on a different schedule, depending on the page. switch ( current_filter() ) { case 'upgrader_process_complete': $timeout = 0; break; case 'load-update-core.php': $timeout = MINUTE_IN_SECONDS; break; case 'load-themes.php': case 'load-update.php': $timeout = HOUR_IN_SECONDS; break; default: if ( $doing_cron ) { $timeout = 2 * HOUR_IN_SECONDS; } else { $timeout = 12 * HOUR_IN_SECONDS; } } $time_not_changed = isset( $last_update->last_checked ) && $timeout > ( time() - $last_update->last_checked ); if ( $time_not_changed && ! $extra_stats ) { $theme_changed = false; foreach ( $checked as $slug => $v ) { if ( ! isset( $last_update->checked[ $slug ] ) || (string) $last_update->checked[ $slug ] !== (string) $v ) { $theme_changed = true; } } if ( isset( $last_update->response ) && is_array( $last_update->response ) ) { foreach ( $last_update->response as $slug => $update_details ) { if ( ! isset( $checked[ $slug ] ) ) { $theme_changed = true; break; } } } // Bail if we've checked recently and if nothing has changed. if ( ! $theme_changed ) { return; } } // Update last_checked for current to prevent multiple blocking requests if request hangs. $last_update->last_checked = time(); set_site_transient( 'update_themes', $last_update ); $request['themes'] = $themes; $locales = array_values( get_available_languages() ); /** * Filters the locales requested for theme translations. * * @since 3.7.0 * @since 4.5.0 The default value of the `$locales` parameter changed to include all locales. * * @param string[] $locales Theme locales. Default is all available locales of the site. */ $locales = apply_filters( 'themes_update_check_locales', $locales ); $locales = array_unique( $locales ); if ( $doing_cron ) { $timeout = 30; // 30 seconds. } else { // Three seconds, plus one extra second for every 10 themes. $timeout = 3 + (int) ( count( $themes ) / 10 ); } $options = array( 'timeout' => $timeout, 'body' => array( 'themes' => wp_json_encode( $request ), 'translations' => wp_json_encode( $translations ), 'locale' => wp_json_encode( $locales ), ), 'user-agent' => 'WordPress/' . $wp_version . '; ' . home_url( '/' ), ); if ( $extra_stats ) { $options['body']['update_stats'] = wp_json_encode( $extra_stats ); } $url = 'http://api.wordpress.org/themes/update-check/1.1/'; $http_url = $url; $ssl = wp_http_supports( array( 'ssl' ) ); if ( $ssl ) { $url = set_url_scheme( $url, 'https' ); } $raw_response = wp_remote_post( $url, $options ); if ( $ssl && is_wp_error( $raw_response ) ) { trigger_error( sprintf( /* translators: %s: Support forums URL. */ __( 'An unexpected error occurred. Something may be wrong with WordPress.org or this server’s configuration. If you continue to have problems, please try the support forums.' ), __( 'https://wordpress.org/support/forums/' ) ) . ' ' . __( '(WordPress could not establish a secure connection to WordPress.org. Please contact your server administrator.)' ), headers_sent() || WP_DEBUG ? E_USER_WARNING : E_USER_NOTICE ); $raw_response = wp_remote_post( $http_url, $options ); } if ( is_wp_error( $raw_response ) || 200 !== wp_remote_retrieve_response_code( $raw_response ) ) { return; } $new_update = new stdClass(); $new_update->last_checked = time(); $new_update->checked = $checked; $response = json_decode( wp_remote_retrieve_body( $raw_response ), true ); if ( is_array( $response ) ) { $new_update->response = $response['themes']; $new_update->no_update = $response['no_update']; $new_update->translations = $response['translations']; } // Support updates for any themes using the `Update URI` header field. foreach ( $themes as $theme_stylesheet => $theme_data ) { if ( ! $theme_data['UpdateURI'] || isset( $new_update->response[ $theme_stylesheet ] ) ) { continue; } $hostname = wp_parse_url( sanitize_url( $theme_data['UpdateURI'] ), PHP_URL_HOST ); /** * Filters the update response for a given theme hostname. * * The dynamic portion of the hook name, `$hostname`, refers to the hostname * of the URI specified in the `Update URI` header field. * * @since 6.1.0 * * @param array|false $update { * The theme update data with the latest details. Default false. * * @type string $id Optional. ID of the theme for update purposes, should be a URI * specified in the `Update URI` header field. * @type string $theme Directory name of the theme. * @type string $version The version of the theme. * @type string $url The URL for details of the theme. * @type string $package Optional. The update ZIP for the theme. * @type string $tested Optional. The version of WordPress the theme is tested against. * @type string $requires_php Optional. The version of PHP which the theme requires. * @type bool $autoupdate Optional. Whether the theme should automatically update. * @type array $translations { * Optional. List of translation updates for the theme. * * @type string $language The language the translation update is for. * @type string $version The version of the theme this translation is for. * This is not the version of the language file. * @type string $updated The update timestamp of the translation file. * Should be a date in the `YYYY-MM-DD HH:MM:SS` format. * @type string $package The ZIP location containing the translation update. * @type string $autoupdate Whether the translation should be automatically installed. * } * } * @param array $theme_data Theme headers. * @param string $theme_stylesheet Theme stylesheet. * @param string[] $locales Installed locales to look up translations for. */ $update = apply_filters( "update_themes_{$hostname}", false, $theme_data, $theme_stylesheet, $locales ); if ( ! $update ) { continue; } $update = (object) $update; // Is it valid? We require at least a version. if ( ! isset( $update->version ) ) { continue; } // This should remain constant. $update->id = $theme_data['UpdateURI']; // WordPress needs the version field specified as 'new_version'. if ( ! isset( $update->new_version ) ) { $update->new_version = $update->version; } // Handle any translation updates. if ( ! empty( $update->translations ) ) { foreach ( $update->translations as $translation ) { if ( isset( $translation['language'], $translation['package'] ) ) { $translation['type'] = 'theme'; $translation['slug'] = isset( $update->theme ) ? $update->theme : $update->id; $new_update->translations[] = $translation; } } } unset( $new_update->no_update[ $theme_stylesheet ], $new_update->response[ $theme_stylesheet ] ); if ( version_compare( $update->new_version, $theme_data['Version'], '>' ) ) { $new_update->response[ $theme_stylesheet ] = (array) $update; } else { $new_update->no_update[ $theme_stylesheet ] = (array) $update; } } set_site_transient( 'update_themes', $new_update ); } /** * Performs WordPress automatic background updates. * * Updates WordPress core plus any plugins and themes that have automatic updates enabled. * * @since 3.7.0 */ function wp_maybe_auto_update() { require_once ABSPATH . 'wp-admin/includes/admin.php'; require_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php'; $upgrader = new WP_Automatic_Updater(); $upgrader->run(); } /** * Retrieves a list of all language updates available. * * @since 3.7.0 * * @return object[] Array of translation objects that have available updates. */ function wp_get_translation_updates() { $updates = array(); $transients = array( 'update_core' => 'core', 'update_plugins' => 'plugin', 'update_themes' => 'theme', ); foreach ( $transients as $transient => $type ) { $transient = get_site_transient( $transient ); if ( empty( $transient->translations ) ) { continue; } foreach ( $transient->translations as $translation ) { $updates[] = (object) $translation; } } return $updates; } /** * Collects counts and UI strings for available updates. * * @since 3.3.0 * * @return array */ function wp_get_update_data() { $counts = array( 'plugins' => 0, 'themes' => 0, 'wordpress' => 0, 'translations' => 0, ); $plugins = current_user_can( 'update_plugins' ); if ( $plugins ) { $update_plugins = get_site_transient( 'update_plugins' ); if ( ! empty( $update_plugins->response ) ) { $counts['plugins'] = count( $update_plugins->response ); } } $themes = current_user_can( 'update_themes' ); if ( $themes ) { $update_themes = get_site_transient( 'update_themes' ); if ( ! empty( $update_themes->response ) ) { $counts['themes'] = count( $update_themes->response ); } } $core = current_user_can( 'update_core' ); if ( $core && function_exists( 'get_core_updates' ) ) { $update_wordpress = get_core_updates( array( 'dismissed' => false ) ); if ( ! empty( $update_wordpress ) && ! in_array( $update_wordpress[0]->response, array( 'development', 'latest' ), true ) && current_user_can( 'update_core' ) ) { $counts['wordpress'] = 1; } } if ( ( $core || $plugins || $themes ) && wp_get_translation_updates() ) { $counts['translations'] = 1; } $counts['total'] = $counts['plugins'] + $counts['themes'] + $counts['wordpress'] + $counts['translations']; $titles = array(); if ( $counts['wordpress'] ) { /* translators: %d: Number of available WordPress updates. */ $titles['wordpress'] = sprintf( __( '%d WordPress Update' ), $counts['wordpress'] ); } if ( $counts['plugins'] ) { /* translators: %d: Number of available plugin updates. */ $titles['plugins'] = sprintf( _n( '%d Plugin Update', '%d Plugin Updates', $counts['plugins'] ), $counts['plugins'] ); } if ( $counts['themes'] ) { /* translators: %d: Number of available theme updates. */ $titles['themes'] = sprintf( _n( '%d Theme Update', '%d Theme Updates', $counts['themes'] ), $counts['themes'] ); } if ( $counts['translations'] ) { $titles['translations'] = __( 'Translation Updates' ); } $update_title = $titles ? esc_attr( implode( ', ', $titles ) ) : ''; $update_data = array( 'counts' => $counts, 'title' => $update_title, ); /** * Filters the returned array of update data for plugins, themes, and WordPress core. * * @since 3.5.0 * * @param array $update_data { * Fetched update data. * * @type array $counts An array of counts for available plugin, theme, and WordPress updates. * @type string $update_title Titles of available updates. * } * @param array $titles An array of update counts and UI strings for available updates. */ return apply_filters( 'wp_get_update_data', $update_data, $titles ); } /** * Determines whether core should be updated. * * @since 2.8.0 * * @global string $wp_version The WordPress version string. */ function _maybe_update_core() { // Include an unmodified $wp_version. require ABSPATH . WPINC . '/version.php'; $current = get_site_transient( 'update_core' ); if ( isset( $current->last_checked, $current->version_checked ) && 12 * HOUR_IN_SECONDS > ( time() - $current->last_checked ) && $current->version_checked === $wp_version ) { return; } wp_version_check(); } /** * Checks the last time plugins were run before checking plugin versions. * * This might have been backported to WordPress 2.6.1 for performance reasons. * This is used for the wp-admin to check only so often instead of every page * load. * * @since 2.7.0 * @access private */ function _maybe_update_plugins() { $current = get_site_transient( 'update_plugins' ); if ( isset( $current->last_checked ) && 12 * HOUR_IN_SECONDS > ( time() - $current->last_checked ) ) { return; } wp_update_plugins(); } /** * Checks themes versions only after a duration of time. * * This is for performance reasons to make sure that on the theme version * checker is not run on every page load. * * @since 2.7.0 * @access private */ function _maybe_update_themes() { $current = get_site_transient( 'update_themes' ); if ( isset( $current->last_checked ) && 12 * HOUR_IN_SECONDS > ( time() - $current->last_checked ) ) { return; } wp_update_themes(); } /** * Schedules core, theme, and plugin update checks. * * @since 3.1.0 */ function wp_schedule_update_checks() { if ( ! wp_next_scheduled( 'wp_version_check' ) && ! wp_installing() ) { wp_schedule_event( time(), 'twicedaily', 'wp_version_check' ); } if ( ! wp_next_scheduled( 'wp_update_plugins' ) && ! wp_installing() ) { wp_schedule_event( time(), 'twicedaily', 'wp_update_plugins' ); } if ( ! wp_next_scheduled( 'wp_update_themes' ) && ! wp_installing() ) { wp_schedule_event( time(), 'twicedaily', 'wp_update_themes' ); } } /** * Clears existing update caches for plugins, themes, and core. * * @since 4.1.0 */ function wp_clean_update_cache() { if ( function_exists( 'wp_clean_plugins_cache' ) ) { wp_clean_plugins_cache(); } else { delete_site_transient( 'update_plugins' ); } wp_clean_themes_cache(); delete_site_transient( 'update_core' ); } /** * Schedules the removal of all contents in the temporary backup directory. * * @since 6.3.0 */ function wp_delete_all_temp_backups() { /* * Check if there is a lock, or if currently performing an Ajax request, * in which case there is a chance an update is running. * Reschedule for an hour from now and exit early. */ if ( get_option( 'core_updater.lock' ) || get_option( 'auto_updater.lock' ) || wp_doing_ajax() ) { wp_schedule_single_event( time() + HOUR_IN_SECONDS, 'wp_delete_temp_updater_backups' ); return; } // This action runs on shutdown to make sure there are no plugin updates currently running. add_action( 'shutdown', '_wp_delete_all_temp_backups' ); } /** * Deletes all contents in the temporary backup directory. * * @since 6.3.0 * * @access private * * @global WP_Filesystem_Base $wp_filesystem WordPress filesystem subclass. * * @return void|WP_Error Void on success, or a WP_Error object on failure. */ function _wp_delete_all_temp_backups() { global $wp_filesystem; if ( ! function_exists( 'WP_Filesystem' ) ) { require_once ABSPATH . '/wp-admin/includes/file.php'; } ob_start(); $credentials = request_filesystem_credentials( '' ); ob_end_clean(); if ( false === $credentials || ! WP_Filesystem( $credentials ) ) { return new WP_Error( 'fs_unavailable', __( 'Could not access filesystem.' ) ); } if ( ! $wp_filesystem->wp_content_dir() ) { return new WP_Error( 'fs_no_content_dir', /* translators: %s: Directory name. */ sprintf( __( 'Unable to locate WordPress content directory (%s).' ), 'wp-content' ) ); } $temp_backup_dir = $wp_filesystem->wp_content_dir() . 'upgrade-temp-backup/'; $dirlist = $wp_filesystem->dirlist( $temp_backup_dir ); $dirlist = $dirlist ? $dirlist : array(); foreach ( array_keys( $dirlist ) as $dir ) { if ( '.' === $dir || '..' === $dir ) { continue; } $wp_filesystem->delete( $temp_backup_dir . $dir, true ); } } if ( ( ! is_main_site() && ! is_network_admin() ) || wp_doing_ajax() ) { return; } add_action( 'admin_init', '_maybe_update_core' ); add_action( 'wp_version_check', 'wp_version_check' ); add_action( 'load-plugins.php', 'wp_update_plugins' ); add_action( 'load-update.php', 'wp_update_plugins' ); add_action( 'load-update-core.php', 'wp_update_plugins' ); add_action( 'admin_init', '_maybe_update_plugins' ); add_action( 'wp_update_plugins', 'wp_update_plugins' ); add_action( 'load-themes.php', 'wp_update_themes' ); add_action( 'load-update.php', 'wp_update_themes' ); add_action( 'load-update-core.php', 'wp_update_themes' ); add_action( 'admin_init', '_maybe_update_themes' ); add_action( 'wp_update_themes', 'wp_update_themes' ); add_action( 'update_option_WPLANG', 'wp_clean_update_cache', 10, 0 ); add_action( 'wp_maybe_auto_update', 'wp_maybe_auto_update' ); add_action( 'init', 'wp_schedule_update_checks' ); add_action( 'wp_delete_temp_updater_backups', 'wp_delete_all_temp_backups' ); tions['proxy']->pass = $proxy->password(); } } // Avoid issues where mbstring.func_overload is enabled. mbstring_binary_safe_encoding(); try { $requests_response = WpOrg\Requests\Requests::request( $url, $headers, $data, $type, $options ); // Convert the response into an array. $http_response = new WP_HTTP_Requests_Response( $requests_response, $parsed_args['filename'] ); $response = $http_response->to_array(); // Add the original object to the array. $response['http_response'] = $http_response; } catch ( WpOrg\Requests\Exception $e ) { $response = new WP_Error( 'http_request_failed', $e->getMessage() ); } reset_mbstring_encoding(); /** * Fires after an HTTP API response is received and before the response is returned. * * @since 2.8.0 * * @param array|WP_Error $response HTTP response or WP_Error object. * @param string $context Context under which the hook is fired. * @param string $class HTTP transport used. * @param array $parsed_args HTTP request arguments. * @param string $url The request URL. */ do_action( 'http_api_debug', $response, 'response', 'WpOrg\Requests\Requests', $parsed_args, $url ); if ( is_wp_error( $response ) ) { return $response; } if ( ! $parsed_args['blocking'] ) { return array( 'headers' => array(), 'body' => '', 'response' => array( 'code' => false, 'message' => false, ), 'cookies' => array(), 'http_response' => null, ); } /** * Filters a successful HTTP API response immediately before the response is returned. * * @since 2.9.0 * * @param array $response HTTP response. * @param array $parsed_args HTTP request arguments. * @param string $url The request URL. */ return apply_filters( 'http_response', $response, $parsed_args, $url ); } /** * Normalizes cookies for using in Requests. * * @since 4.6.0 * * @param array $cookies Array of cookies to send with the request. * @return WpOrg\Requests\Cookie\Jar Cookie holder object. */ public static function normalize_cookies( $cookies ) { $cookie_jar = new WpOrg\Requests\Cookie\Jar(); foreach ( $cookies as $name => $value ) { if ( $value instanceof WP_Http_Cookie ) { $attributes = array_filter( $value->get_attributes(), static function ( $attr ) { return null !== $attr; } ); $cookie_jar[ $value->name ] = new WpOrg\Requests\Cookie( (string) $value->name, $value->value, $attributes, array( 'host-only' => $value->host_only ) ); } elseif ( is_scalar( $value ) ) { $cookie_jar[ $name ] = new WpOrg\Requests\Cookie( (string) $name, (string) $value ); } } return $cookie_jar; } /** * Match redirect behavior to browser handling. * * Changes 302 redirects from POST to GET to match browser handling. Per * RFC 7231, user agents can deviate from the strict reading of the * specification for compatibility purposes. * * @since 4.6.0 * * @param string $location URL to redirect to. * @param array $headers Headers for the redirect. * @param string|array $data Body to send with the request. * @param array $options Redirect request options. * @param WpOrg\Requests\Response $original Response object. */ public static function browser_redirect_compatibility( $location, $headers, $data, &$options, $original ) { // Browser compatibility. if ( 302 === $original->status_code ) { $options['type'] = WpOrg\Requests\Requests::GET; } } /** * Validate redirected URLs. * * @since 4.7.5 * * @throws WpOrg\Requests\Exception On unsuccessful URL validation. * @param string $location URL to redirect to. */ public static function validate_redirects( $location ) { if ( ! wp_http_validate_url( $location ) ) { throw new WpOrg\Requests\Exception( __( 'A valid URL was not provided.' ), 'wp_http.redirect_failed_validation' ); } } /** * Tests which transports are capable of supporting the request. * * @since 3.2.0 * @deprecated 6.4.0 Use WpOrg\Requests\Requests::get_transport_class() * @see WpOrg\Requests\Requests::get_transport_class() * * @param array $args Request arguments. * @param string $url URL to request. * @return string|false Class name for the first transport that claims to support the request. * False if no transport claims to support the request. */ public function _get_first_available_transport( $args, $url = null ) { $transports = array( 'curl', 'streams' ); /** * Filters which HTTP transports are available and in what order. * * @since 3.7.0 * @deprecated 6.4.0 Use WpOrg\Requests\Requests::get_transport_class() * * @param string[] $transports Array of HTTP transports to check. Default array contains * 'curl' and 'streams', in that order. * @param array $args HTTP request arguments. * @param string $url The URL to request. */ $request_order = apply_filters_deprecated( 'http_api_transports', array( $transports, $args, $url ), '6.4.0' ); // Loop over each transport on each HTTP request looking for one which will serve this request's needs. foreach ( $request_order as $transport ) { if ( in_array( $transport, $transports, true ) ) { $transport = ucfirst( $transport ); } $class = 'WP_Http_' . $transport; // Check to see if this transport is a possibility, calls the transport statically. if ( ! call_user_func( array( $class, 'test' ), $args, $url ) ) { continue; } return $class; } return false; } /** * Dispatches a HTTP request to a supporting transport. * * Tests each transport in order to find a transport which matches the request arguments. * Also caches the transport instance to be used later. * * The order for requests is cURL, and then PHP Streams. * * @since 3.2.0 * @deprecated 5.1.0 Use WP_Http::request() * @see WP_Http::request() * * @param string $url URL to request. * @param array $args Request arguments. * @return array|WP_Error Array containing 'headers', 'body', 'response', 'cookies', 'filename'. * A WP_Error instance upon error. */ private function _dispatch_request( $url, $args ) { static $transports = array(); $class = $this->_get_first_available_transport( $args, $url ); if ( ! $class ) { return new WP_Error( 'http_failure', __( 'There are no HTTP transports available which can complete the requested request.' ) ); } // Transport claims to support request, instantiate it and give it a whirl. if ( empty( $transports[ $class ] ) ) { $transports[ $class ] = new $class(); } $response = $transports[ $class ]->request( $url, $args ); /** This action is documented in wp-includes/class-wp-http.php */ do_action( 'http_api_debug', $response, 'response', $class, $args, $url ); if ( is_wp_error( $response ) ) { return $response; } /** This filter is documented in wp-includes/class-wp-http.php */ return apply_filters( 'http_response', $response, $args, $url ); } /** * Uses the POST HTTP method. * * Used for sending data that is expected to be in the body. * * @since 2.7.0 * * @param string $url The request URL. * @param string|array $args Optional. Override the defaults. * @return array|WP_Error Array containing 'headers', 'body', 'response', 'cookies', 'filename'. * A WP_Error instance upon error. See WP_Http::response() for details. */ public function post( $url, $args = array() ) { $defaults = array( 'method' => 'POST' ); $parsed_args = wp_parse_args( $args, $defaults ); return $this->request( $url, $parsed_args ); } /** * Uses the GET HTTP method. * * Used for sending data that is expected to be in the body. * * @since 2.7.0 * * @param string $url The request URL. * @param string|array $args Optional. Override the defaults. * @return array|WP_Error Array containing 'headers', 'body', 'response', 'cookies', 'filename'. * A WP_Error instance upon error. See WP_Http::response() for details. */ public function get( $url, $args = array() ) { $defaults = array( 'method' => 'GET' ); $parsed_args = wp_parse_args( $args, $defaults ); return $this->request( $url, $parsed_args ); } /** * Uses the HEAD HTTP method. * * Used for sending data that is expected to be in the body. * * @since 2.7.0 * * @param string $url The request URL. * @param string|array $args Optional. Override the defaults. * @return array|WP_Error Array containing 'headers', 'body', 'response', 'cookies', 'filename'. * A WP_Error instance upon error. See WP_Http::response() for details. */ public function head( $url, $args = array() ) { $defaults = array( 'method' => 'HEAD' ); $parsed_args = wp_parse_args( $args, $defaults ); return $this->request( $url, $parsed_args ); } /** * Parses the responses and splits the parts into headers and body. * * @since 2.7.0 * * @param string $response The full response string. * @return array { * Array with response headers and body. * * @type string $headers HTTP response headers. * @type string $body HTTP response body. * } */ public static function processResponse( $response ) { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.MethodNameInvalid $response = explode( "\r\n\r\n", $response, 2 ); return array( 'headers' => $response[0], 'body' => isset( $response[1] ) ? $response[1] : '', ); } /** * Transforms header string into an array. * * @since 2.7.0 * * @param string|array $headers The original headers. If a string is passed, it will be converted * to an array. If an array is passed, then it is assumed to be * raw header data with numeric keys with the headers as the values. * No headers must be passed that were already processed. * @param string $url Optional. The URL that was requested. Default empty. * @return array { * Processed string headers. If duplicate headers are encountered, * then a numbered array is returned as the value of that header-key. * * @type array $response { * @type int $code The response status code. Default 0. * @type string $message The response message. Default empty. * } * @type array $newheaders The processed header data as a multidimensional array. * @type WP_Http_Cookie[] $cookies If the original headers contain the 'Set-Cookie' key, * an array containing `WP_Http_Cookie` objects is returned. * } */ public static function processHeaders( $headers, $url = '' ) { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.MethodNameInvalid // Split headers, one per array element. if ( is_string( $headers ) ) { // Tolerate line terminator: CRLF = LF (RFC 2616 19.3). $headers = str_replace( "\r\n", "\n", $headers ); /* * Unfold folded header fields. LWS = [CRLF] 1*( SP | HT ) , * (RFC 2616 2.2). */ $headers = preg_replace( '/\n[ \t]/', ' ', $headers ); // Create the headers array. $headers = explode( "\n", $headers ); } $response = array( 'code' => 0, 'message' => '', ); /* * If a redirection has taken place, The headers for each page request may have been passed. * In this case, determine the final HTTP header and parse from there. */ for ( $i = count( $headers ) - 1; $i >= 0; $i-- ) { if ( ! empty( $headers[ $i ] ) && ! str_contains( $headers[ $i ], ':' ) ) { $headers = array_splice( $headers, $i ); break; } } $cookies = array(); $newheaders = array(); foreach ( (array) $headers as $tempheader ) { if ( empty( $tempheader ) ) { continue; } if ( ! str_contains( $tempheader, ':' ) ) { $stack = explode( ' ', $tempheader, 3 ); $stack[] = ''; list( , $response['code'], $response['message']) = $stack; continue; } list($key, $value) = explode( ':', $tempheader, 2 ); $key = strtolower( $key ); $value = trim( $value ); if ( isset( $newheaders[ $key ] ) ) { if ( ! is_array( $newheaders[ $key ] ) ) { $newheaders[ $key ] = array( $newheaders[ $key ] ); } $newheaders[ $key ][] = $value; } else { $newheaders[ $key ] = $value; } if ( 'set-cookie' === $key ) { $cookies[] = new WP_Http_Cookie( $value, $url ); } } // Cast the Response Code to an int. $response['code'] = (int) $response['code']; return array( 'response' => $response, 'headers' => $newheaders, 'cookies' => $cookies, ); } /** * Takes the arguments for a ::request() and checks for the cookie array. * * If it's found, then it upgrades any basic name => value pairs to WP_Http_Cookie instances, * which are each parsed into strings and added to the Cookie: header (within the arguments array). * Edits the array by reference. * * @since 2.8.0 * * @param array $r Full array of args passed into ::request() */ public static function buildCookieHeader( &$r ) { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.MethodNameInvalid if ( ! empty( $r['cookies'] ) ) { // Upgrade any name => value cookie pairs to WP_HTTP_Cookie instances. foreach ( $r['cookies'] as $name => $value ) { if ( ! is_object( $value ) ) { $r['cookies'][ $name ] = new WP_Http_Cookie( array( 'name' => $name, 'value' => $value, ) ); } } $cookies_header = ''; foreach ( (array) $r['cookies'] as $cookie ) { $cookies_header .= $cookie->getHeaderValue() . '; '; } $cookies_header = substr( $cookies_header, 0, -2 ); $r['headers']['cookie'] = $cookies_header; } } /** * Decodes chunk transfer-encoding, based off the HTTP 1.1 specification. * * Based off the HTTP http_encoding_dechunk function. * * @link https://tools.ietf.org/html/rfc2616#section-19.4.6 Process for chunked decoding. * * @since 2.7.0 * * @param string $body Body content. * @return string Chunked decoded body on success or raw body on failure. */ public static function chunkTransferDecode( $body ) { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.MethodNameInvalid // The body is not chunked encoded or is malformed. if ( ! preg_match( '/^([0-9a-f]+)[^\r\n]*\r\n/i', trim( $body ) ) ) { return $body; } $parsed_body = ''; // We'll be altering $body, so need a backup in case of error. $body_original = $body; while ( true ) { $has_chunk = (bool) preg_match( '/^([0-9a-f]+)[^\r\n]*\r\n/i', $body, $match ); if ( ! $has_chunk || empty( $match[1] ) ) { return $body_original; } $length = hexdec( $match[1] ); $chunk_length = strlen( $match[0] ); // Parse out the chunk of data. $parsed_body .= substr( $body, $chunk_length, $length ); // Remove the chunk from the raw data. $body = substr( $body, $length + $chunk_length ); // End of the document. if ( '0' === trim( $body ) ) { return $parsed_body; } } } /** * Determines whether an HTTP API request to the given URL should be blocked. * * Those who are behind a proxy and want to prevent access to certain hosts may do so. This will * prevent plugins from working and core functionality, if you don't include `api.wordpress.org`. * * You block external URL requests by defining `WP_HTTP_BLOCK_EXTERNAL` as true in your `wp-config.php` * file and this will only allow localhost and your site to make requests. The constant * `WP_ACCESSIBLE_HOSTS` will allow additional hosts to go through for requests. The format of the * `WP_ACCESSIBLE_HOSTS` constant is a comma separated list of hostnames to allow, wildcard domains * are supported, eg `*.wordpress.org` will allow for all subdomains of `wordpress.org` to be contacted. * * @since 2.8.0 * * @link https://core.trac.wordpress.org/ticket/8927 Allow preventing external requests. * @link https://core.trac.wordpress.org/ticket/14636 Allow wildcard domains in WP_ACCESSIBLE_HOSTS * * @param string $uri URI of url. * @return bool True to block, false to allow. */ public function block_request( $uri ) { // We don't need to block requests, because nothing is blocked. if ( ! defined( 'WP_HTTP_BLOCK_EXTERNAL' ) || ! WP_HTTP_BLOCK_EXTERNAL ) { return false; } $check = parse_url( $uri ); if ( ! $check ) { return true; } $home = parse_url( get_option( 'siteurl' ) ); // Don't block requests back to ourselves by default. if ( 'localhost' === $check['host'] || ( isset( $home['host'] ) && $home['host'] === $check['host'] ) ) { /** * Filters whether to block local HTTP API requests. * * A local request is one to `localhost` or to the same host as the site itself. * * @since 2.8.0 * * @param bool $block Whether to block local requests. Default false. */ return apply_filters( 'block_local_requests', false ); } if ( ! defined( 'WP_ACCESSIBLE_HOSTS' ) ) { return true; } static $accessible_hosts = null; static $wildcard_regex = array(); if ( null === $accessible_hosts ) { $accessible_hosts = preg_split( '|,\s*|', WP_ACCESSIBLE_HOSTS ); if ( str_contains( WP_ACCESSIBLE_HOSTS, '*' ) ) { $wildcard_regex = array(); foreach ( $accessible_hosts as $host ) { $wildcard_regex[] = str_replace( '\*', '.+', preg_quote( $host, '/' ) ); } $wildcard_regex = '/^(' . implode( '|', $wildcard_regex ) . ')$/i'; } } if ( ! empty( $wildcard_regex ) ) { return ! preg_match( $wildcard_regex, $check['host'] ); } else { return ! in_array( $check['host'], $accessible_hosts, true ); // Inverse logic, if it's in the array, then don't block it. } } /** * Used as a wrapper for PHP's parse_url() function that handles edgecases in < PHP 5.4.7. * * @deprecated 4.4.0 Use wp_parse_url() * @see wp_parse_url() * * @param string $url The URL to parse. * @return bool|array False on failure; Array of URL components on success; * See parse_url()'s return values. */ protected static function parse_url( $url ) { _deprecated_function( __METHOD__, '4.4.0', 'wp_parse_url()' ); return wp_parse_url( $url ); } /** * Converts a relative URL to an absolute URL relative to a given URL. * * If an Absolute URL is provided, no processing of that URL is done. * * @since 3.4.0 * * @param string $maybe_relative_path The URL which might be relative. * @param string $url The URL which $maybe_relative_path is relative to. * @return string An Absolute URL, in a failure condition where the URL cannot be parsed, the relative URL will be returned. */ public static function make_absolute_url( $maybe_relative_path, $url ) { if ( empty( $url ) ) { return $maybe_relative_path; } $url_parts = wp_parse_url( $url ); if ( ! $url_parts ) { return $maybe_relative_path; } $relative_url_parts = wp_parse_url( $maybe_relative_path ); if ( ! $relative_url_parts ) { return $maybe_relative_path; } // Check for a scheme on the 'relative' URL. if ( ! empty( $relative_url_parts['scheme'] ) ) { return $maybe_relative_path; } $absolute_path = $url_parts['scheme'] . '://'; // Schemeless URLs will make it this far, so we check for a host in the relative URL // and convert it to a protocol-URL. if ( isset( $relative_url_parts['host'] ) ) { $absolute_path .= $relative_url_parts['host']; if ( isset( $relative_url_parts['port'] ) ) { $absolute_path .= ':' . $relative_url_parts['port']; } } else { $absolute_path .= $url_parts['host']; if ( isset( $url_parts['port'] ) ) { $absolute_path .= ':' . $url_parts['port']; } } // Start off with the absolute URL path. $path = ! empty( $url_parts['path'] ) ? $url_parts['path'] : '/'; // If it's a root-relative path, then great. if ( ! empty( $relative_url_parts['path'] ) && '/' === $relative_url_parts['path'][0] ) { $path = $relative_url_parts['path']; // Else it's a relative path. } elseif ( ! empty( $relative_url_parts['path'] ) ) { // Strip off any file components from the absolute path. $path = substr( $path, 0, strrpos( $path, '/' ) + 1 ); // Build the new path. $path .= $relative_url_parts['path']; // Strip all /path/../ out of the path. while ( strpos( $path, '../' ) > 1 ) { $path = preg_replace( '![^/]+/\.\./!', '', $path ); } // Strip any final leading ../ from the path. $path = preg_replace( '!^/(\.\./)+!', '', $path ); } // Add the query string. if ( ! empty( $relative_url_parts['query'] ) ) { $path .= '?' . $relative_url_parts['query']; } // Add the fragment. if ( ! empty( $relative_url_parts['fragment'] ) ) { $path .= '#' . $relative_url_parts['fragment']; } return $absolute_path . '/' . ltrim( $path, '/' ); } /** * Handles an HTTP redirect and follows it if appropriate. * * @since 3.7.0 * * @param string $url The URL which was requested. * @param array $args The arguments which were used to make the request. * @param array $response The response of the HTTP request. * @return array|false|WP_Error An HTTP API response array if the redirect is successfully followed, * false if no redirect is present, or a WP_Error object if there's an error. */ public static function handle_redirects( $url, $args, $response ) { // If no redirects are present, or, redirects were not requested, perform no action. if ( ! isset( $response['headers']['location'] ) || 0 === $args['_redirection'] ) { return false; } // Only perform redirections on redirection http codes. if ( $response['response']['code'] > 399 || $response['response']['code'] < 300 ) { return false; } // Don't redirect if we've run out of redirects. if ( $args['redirection']-- <= 0 ) { return new WP_Error( 'http_request_failed', __( 'Too many redirects.' ) ); } $redirect_location = $response['headers']['location']; // If there were multiple Location headers, use the last header specified. if ( is_array( $redirect_location ) ) { $redirect_location = array_pop( $redirect_location ); } $redirect_location = WP_Http::make_absolute_url( $redirect_location, $url ); // POST requests should not POST to a redirected location. if ( 'POST' === $args['method'] ) { if ( in_array( $response['response']['code'], array( 302, 303 ), true ) ) { $args['method'] = 'GET'; } } // Include valid cookies in the redirect process. if ( ! empty( $response['cookies'] ) ) { foreach ( $response['cookies'] as $cookie ) { if ( $cookie->test( $redirect_location ) ) { $args['cookies'][] = $cookie; } } } return wp_remote_request( $redirect_location, $args ); } /** * Determines if a specified string represents an IP address or not. * * This function also detects the type of the IP address, returning either * '4' or '6' to represent an IPv4 and IPv6 address respectively. * This does not verify if the IP is a valid IP, only that it appears to be * an IP address. * * @link http://home.deds.nl/~aeron/regex/ for IPv6 regex. * * @since 3.7.0 * * @param string $maybe_ip A suspected IP address. * @return int|false Upon success, '4' or '6' to represent an IPv4 or IPv6 address, false upon failure. */ public static function is_ip_address( $maybe_ip ) { if ( preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/', $maybe_ip ) ) { return 4; } if ( str_contains( $maybe_ip, ':' ) && preg_match( '/^(((?=.*(::))(?!.*\3.+\3))\3?|([\dA-F]{1,4}(\3|:\b|$)|\2))(?4){5}((?4){2}|(((2[0-4]|1\d|[1-9])?\d|25[0-5])\.?\b){4})$/i', trim( $maybe_ip, ' []' ) ) ) { return 6; } return false; } }