screen.php000064400000014352147206365750006560 0ustar00id ] ) ) { /** * Filters the column headers for a list table on a specific screen. * * The dynamic portion of the hook name, `$screen->id`, refers to the * ID of a specific screen. For example, the screen ID for the Posts * list table is edit-post, so the filter for that screen would be * manage_edit-post_columns. * * @since 3.0.0 * * @param string[] $columns The column header labels keyed by column ID. */ $column_headers[ $screen->id ] = apply_filters( "manage_{$screen->id}_columns", array() ); } return $column_headers[ $screen->id ]; } /** * Get a list of hidden columns. * * @since 2.7.0 * * @param string|WP_Screen $screen The screen you want the hidden columns for * @return string[] Array of IDs of hidden columns. */ function get_hidden_columns( $screen ) { if ( is_string( $screen ) ) { $screen = convert_to_screen( $screen ); } $hidden = get_user_option( 'manage' . $screen->id . 'columnshidden' ); $use_defaults = ! is_array( $hidden ); if ( $use_defaults ) { $hidden = array(); /** * Filters the default list of hidden columns. * * @since 4.4.0 * * @param string[] $hidden Array of IDs of columns hidden by default. * @param WP_Screen $screen WP_Screen object of the current screen. */ $hidden = apply_filters( 'default_hidden_columns', $hidden, $screen ); } /** * Filters the list of hidden columns. * * @since 4.4.0 * @since 4.4.1 Added the `use_defaults` parameter. * * @param string[] $hidden Array of IDs of hidden columns. * @param WP_Screen $screen WP_Screen object of the current screen. * @param bool $use_defaults Whether to show the default columns. */ return apply_filters( 'hidden_columns', $hidden, $screen, $use_defaults ); } /** * Prints the meta box preferences for screen meta. * * @since 2.7.0 * * @global array $wp_meta_boxes Global meta box state. * * @param WP_Screen $screen */ function meta_box_prefs( $screen ) { global $wp_meta_boxes; if ( is_string( $screen ) ) { $screen = convert_to_screen( $screen ); } if ( empty( $wp_meta_boxes[ $screen->id ] ) ) { return; } $hidden = get_hidden_meta_boxes( $screen ); foreach ( array_keys( $wp_meta_boxes[ $screen->id ] ) as $context ) { foreach ( array( 'high', 'core', 'default', 'low' ) as $priority ) { if ( ! isset( $wp_meta_boxes[ $screen->id ][ $context ][ $priority ] ) ) { continue; } foreach ( $wp_meta_boxes[ $screen->id ][ $context ][ $priority ] as $box ) { if ( false === $box || ! $box['title'] ) { continue; } // Submit box cannot be hidden. if ( 'submitdiv' === $box['id'] || 'linksubmitdiv' === $box['id'] ) { continue; } $widget_title = $box['title']; if ( is_array( $box['args'] ) && isset( $box['args']['__widget_basename'] ) ) { $widget_title = $box['args']['__widget_basename']; } $is_hidden = in_array( $box['id'], $hidden, true ); printf( '', esc_attr( $box['id'] ), checked( $is_hidden, false, false ), $widget_title ); } } } } /** * Gets an array of IDs of hidden meta boxes. * * @since 2.7.0 * * @param string|WP_Screen $screen Screen identifier * @return string[] IDs of hidden meta boxes. */ function get_hidden_meta_boxes( $screen ) { if ( is_string( $screen ) ) { $screen = convert_to_screen( $screen ); } $hidden = get_user_option( "metaboxhidden_{$screen->id}" ); $use_defaults = ! is_array( $hidden ); // Hide slug boxes by default. if ( $use_defaults ) { $hidden = array(); if ( 'post' === $screen->base ) { if ( in_array( $screen->post_type, array( 'post', 'page', 'attachment' ), true ) ) { $hidden = array( 'slugdiv', 'trackbacksdiv', 'postcustom', 'postexcerpt', 'commentstatusdiv', 'commentsdiv', 'authordiv', 'revisionsdiv' ); } else { $hidden = array( 'slugdiv' ); } } /** * Filters the default list of hidden meta boxes. * * @since 3.1.0 * * @param string[] $hidden An array of IDs of meta boxes hidden by default. * @param WP_Screen $screen WP_Screen object of the current screen. */ $hidden = apply_filters( 'default_hidden_meta_boxes', $hidden, $screen ); } /** * Filters the list of hidden meta boxes. * * @since 3.3.0 * * @param string[] $hidden An array of IDs of hidden meta boxes. * @param WP_Screen $screen WP_Screen object of the current screen. * @param bool $use_defaults Whether to show the default meta boxes. * Default true. */ return apply_filters( 'hidden_meta_boxes', $hidden, $screen, $use_defaults ); } /** * Register and configure an admin screen option * * @since 3.1.0 * * @param string $option An option name. * @param mixed $args Option-dependent arguments. */ function add_screen_option( $option, $args = array() ) { $current_screen = get_current_screen(); if ( ! $current_screen ) { return; } $current_screen->add_option( $option, $args ); } /** * Get the current screen object * * @since 3.1.0 * * @global WP_Screen $current_screen WordPress current screen object. * * @return WP_Screen|null Current screen object or null when screen not defined. */ function get_current_screen() { global $current_screen; if ( ! isset( $current_screen ) ) { return null; } return $current_screen; } /** * Set the current screen object * * @since 3.0.0 * * @param string|WP_Screen $hook_name Optional. The hook name (also known as the hook suffix) used to determine the screen, * or an existing screen object. */ function set_current_screen( $hook_name = '' ) { WP_Screen::get( $hook_name )->set_current_screen(); } class-wp-debug-data.php000064400000177410147206365750011032 0ustar00 self::get_wp_core(), 'wp-paths-sizes' => self::get_wp_paths_sizes(), 'wp-dropins' => self::get_wp_dropins(), 'wp-active-theme' => self::get_wp_active_theme(), 'wp-parent-theme' => self::get_wp_parent_theme(), 'wp-themes-inactive' => self::get_wp_themes_inactive(), 'wp-mu-plugins' => self::get_wp_mu_plugins(), 'wp-plugins-active' => self::get_wp_plugins_active(), 'wp-plugins-inactive' => self::get_wp_plugins_inactive(), 'wp-media' => self::get_wp_media(), 'wp-server' => self::get_wp_server(), 'wp-database' => self::get_wp_database(), 'wp-constants' => self::get_wp_constants(), 'wp-filesystem' => self::get_wp_filesystem(), ); /* * Remove null elements from the array. The individual methods are * allowed to return `null`, which communicates that the category * of debug data isn't relevant and shouldn't be passed through. */ $info = array_filter( $info, static function ( $section ) { return isset( $section ); } ); /** * Filters the debug information shown on the Tools -> Site Health -> Info screen. * * Plugin or themes may wish to introduce their own debug information without creating * additional admin pages. They can utilize this filter to introduce their own sections * or add more data to existing sections. * * Array keys for sections added by core are all prefixed with `wp-`. Plugins and themes * should use their own slug as a prefix, both for consistency as well as avoiding * key collisions. Note that the array keys are used as labels for the copied data. * * All strings are expected to be plain text except `$description` that can contain * inline HTML tags (see below). * * @since 5.2.0 * * @param array $args { * The debug information to be added to the core information page. * * This is an associative multi-dimensional array, up to three levels deep. * The topmost array holds the sections, keyed by section ID. * * @type array ...$0 { * Each section has a `$fields` associative array (see below), and each `$value` in `$fields` * can be another associative array of name/value pairs when there is more structured data * to display. * * @type string $label Required. The title for this section of the debug output. * @type string $description Optional. A description for your information section which * may contain basic HTML markup, inline tags only as it is * outputted in a paragraph. * @type bool $show_count Optional. If set to `true`, the amount of fields will be included * in the title for this section. Default false. * @type bool $private Optional. If set to `true`, the section and all associated fields * will be excluded from the copied data. Default false. * @type array $fields { * Required. An associative array containing the fields to be displayed in the section, * keyed by field ID. * * @type array ...$0 { * An associative array containing the data to be displayed for the field. * * @type string $label Required. The label for this piece of information. * @type mixed $value Required. The output that is displayed for this field. * Text should be translated. Can be an associative array * that is displayed as name/value pairs. * Accepted types: `string|int|float|(string|int|float)[]`. * @type string $debug Optional. The output that is used for this field when * the user copies the data. It should be more concise and * not translated. If not set, the content of `$value` * is used. Note that the array keys are used as labels * for the copied data. * @type bool $private Optional. If set to `true`, the field will be excluded * from the copied data, allowing you to show, for example, * API keys here. Default false. * } * } * } * } */ $info = apply_filters( 'debug_information', $info ); return $info; } /** * Gets the WordPress core section of the debug data. * * @since 6.7.0 * * @return array */ private static function get_wp_core(): array { // Save few function calls. $permalink_structure = get_option( 'permalink_structure' ); $is_ssl = is_ssl(); $users_can_register = get_option( 'users_can_register' ); $blog_public = get_option( 'blog_public' ); $default_comment_status = get_option( 'default_comment_status' ); $environment_type = wp_get_environment_type(); $core_version = wp_get_wp_version(); $core_updates = get_core_updates(); $core_update_needed = ''; if ( is_array( $core_updates ) ) { foreach ( $core_updates as $core => $update ) { if ( 'upgrade' === $update->response ) { /* translators: %s: Latest WordPress version number. */ $core_update_needed = ' ' . sprintf( __( '(Latest version: %s)' ), $update->version ); } else { $core_update_needed = ''; } } } $fields = array( 'version' => array( 'label' => __( 'Version' ), 'value' => $core_version . $core_update_needed, 'debug' => $core_version, ), 'site_language' => array( 'label' => __( 'Site Language' ), 'value' => get_locale(), ), 'user_language' => array( 'label' => __( 'User Language' ), 'value' => get_user_locale(), ), 'timezone' => array( 'label' => __( 'Timezone' ), 'value' => wp_timezone_string(), ), 'home_url' => array( 'label' => __( 'Home URL' ), 'value' => get_bloginfo( 'url' ), 'private' => true, ), 'site_url' => array( 'label' => __( 'Site URL' ), 'value' => get_bloginfo( 'wpurl' ), 'private' => true, ), 'permalink' => array( 'label' => __( 'Permalink structure' ), 'value' => $permalink_structure ? $permalink_structure : __( 'No permalink structure set' ), 'debug' => $permalink_structure, ), 'https_status' => array( 'label' => __( 'Is this site using HTTPS?' ), 'value' => $is_ssl ? __( 'Yes' ) : __( 'No' ), 'debug' => $is_ssl, ), 'multisite' => array( 'label' => __( 'Is this a multisite?' ), 'value' => is_multisite() ? __( 'Yes' ) : __( 'No' ), 'debug' => is_multisite(), ), 'user_registration' => array( 'label' => __( 'Can anyone register on this site?' ), 'value' => $users_can_register ? __( 'Yes' ) : __( 'No' ), 'debug' => $users_can_register, ), 'blog_public' => array( 'label' => __( 'Is this site discouraging search engines?' ), 'value' => $blog_public ? __( 'No' ) : __( 'Yes' ), 'debug' => $blog_public, ), 'default_comment_status' => array( 'label' => __( 'Default comment status' ), 'value' => 'open' === $default_comment_status ? _x( 'Open', 'comment status' ) : _x( 'Closed', 'comment status' ), 'debug' => $default_comment_status, ), 'environment_type' => array( 'label' => __( 'Environment type' ), 'value' => $environment_type, 'debug' => $environment_type, ), ); // Conditionally add debug information for multisite setups. if ( is_multisite() ) { $site_id = get_current_blog_id(); $fields['site_id'] = array( 'label' => __( 'Site ID' ), 'value' => $site_id, 'debug' => $site_id, ); $network_query = new WP_Network_Query(); $network_ids = $network_query->query( array( 'fields' => 'ids', 'number' => 100, 'no_found_rows' => false, ) ); $site_count = 0; foreach ( $network_ids as $network_id ) { $site_count += get_blog_count( $network_id ); } $fields['site_count'] = array( 'label' => __( 'Site count' ), 'value' => $site_count, ); $fields['network_count'] = array( 'label' => __( 'Network count' ), 'value' => $network_query->found_networks, ); } $fields['user_count'] = array( 'label' => __( 'User count' ), 'value' => get_user_count(), ); // WordPress features requiring processing. $wp_dotorg = wp_remote_get( 'https://wordpress.org', array( 'timeout' => 10 ) ); if ( ! is_wp_error( $wp_dotorg ) ) { $fields['dotorg_communication'] = array( 'label' => __( 'Communication with WordPress.org' ), 'value' => __( 'WordPress.org is reachable' ), 'debug' => 'true', ); } else { $fields['dotorg_communication'] = array( 'label' => __( 'Communication with WordPress.org' ), 'value' => sprintf( /* translators: 1: The IP address WordPress.org resolves to. 2: The error returned by the lookup. */ __( 'Unable to reach WordPress.org at %1$s: %2$s' ), gethostbyname( 'wordpress.org' ), $wp_dotorg->get_error_message() ), 'debug' => $wp_dotorg->get_error_message(), ); } return array( 'label' => __( 'WordPress' ), 'fields' => $fields, ); } /** * Gets the WordPress drop-in section of the debug data. * * @since 6.7.0 * * @return array */ private static function get_wp_dropins(): array { // Get a list of all drop-in replacements. $dropins = get_dropins(); // Get drop-ins descriptions. $dropin_descriptions = _get_dropins(); $fields = array(); foreach ( $dropins as $dropin_key => $dropin ) { $fields[ sanitize_text_field( $dropin_key ) ] = array( 'label' => $dropin_key, 'value' => $dropin_descriptions[ $dropin_key ][0], 'debug' => 'true', ); } return array( 'label' => __( 'Drop-ins' ), 'show_count' => true, 'description' => sprintf( /* translators: %s: wp-content directory name. */ __( 'Drop-ins are single files, found in the %s directory, that replace or enhance WordPress features in ways that are not possible for traditional plugins.' ), '' . str_replace( ABSPATH, '', WP_CONTENT_DIR ) . '' ), 'fields' => $fields, ); } /** * Gets the WordPress server section of the debug data. * * @since 6.7.0 * * @return array */ private static function get_wp_server(): array { // Populate the server debug fields. if ( function_exists( 'php_uname' ) ) { $server_architecture = sprintf( '%s %s %s', php_uname( 's' ), php_uname( 'r' ), php_uname( 'm' ) ); } else { $server_architecture = 'unknown'; } $php_version_debug = PHP_VERSION; // Whether PHP supports 64-bit. $php64bit = ( PHP_INT_SIZE * 8 === 64 ); $php_version = sprintf( '%s %s', $php_version_debug, ( $php64bit ? __( '(Supports 64bit values)' ) : __( '(Does not support 64bit values)' ) ) ); if ( $php64bit ) { $php_version_debug .= ' 64bit'; } $fields = array(); $fields['server_architecture'] = array( 'label' => __( 'Server architecture' ), 'value' => ( 'unknown' !== $server_architecture ? $server_architecture : __( 'Unable to determine server architecture' ) ), 'debug' => $server_architecture, ); $fields['httpd_software'] = array( 'label' => __( 'Web server' ), 'value' => ( isset( $_SERVER['SERVER_SOFTWARE'] ) ? $_SERVER['SERVER_SOFTWARE'] : __( 'Unable to determine what web server software is used' ) ), 'debug' => ( isset( $_SERVER['SERVER_SOFTWARE'] ) ? $_SERVER['SERVER_SOFTWARE'] : 'unknown' ), ); $fields['php_version'] = array( 'label' => __( 'PHP version' ), 'value' => $php_version, 'debug' => $php_version_debug, ); $fields['php_sapi'] = array( 'label' => __( 'PHP SAPI' ), 'value' => PHP_SAPI, 'debug' => PHP_SAPI, ); // Some servers disable `ini_set()` and `ini_get()`, we check this before trying to get configuration values. if ( ! function_exists( 'ini_get' ) ) { $fields['ini_get'] = array( 'label' => __( 'Server settings' ), 'value' => sprintf( /* translators: %s: ini_get() */ __( 'Unable to determine some settings, as the %s function has been disabled.' ), 'ini_get()' ), 'debug' => 'ini_get() is disabled', ); } else { $fields['max_input_variables'] = array( 'label' => __( 'PHP max input variables' ), 'value' => ini_get( 'max_input_vars' ), ); $fields['time_limit'] = array( 'label' => __( 'PHP time limit' ), 'value' => ini_get( 'max_execution_time' ), ); if ( WP_Site_Health::get_instance()->php_memory_limit !== ini_get( 'memory_limit' ) ) { $fields['memory_limit'] = array( 'label' => __( 'PHP memory limit' ), 'value' => WP_Site_Health::get_instance()->php_memory_limit, ); $fields['admin_memory_limit'] = array( 'label' => __( 'PHP memory limit (only for admin screens)' ), 'value' => ini_get( 'memory_limit' ), ); } else { $fields['memory_limit'] = array( 'label' => __( 'PHP memory limit' ), 'value' => ini_get( 'memory_limit' ), ); } $fields['max_input_time'] = array( 'label' => __( 'Max input time' ), 'value' => ini_get( 'max_input_time' ), ); $fields['upload_max_filesize'] = array( 'label' => __( 'Upload max filesize' ), 'value' => ini_get( 'upload_max_filesize' ), ); $fields['php_post_max_size'] = array( 'label' => __( 'PHP post max size' ), 'value' => ini_get( 'post_max_size' ), ); } if ( function_exists( 'curl_version' ) ) { $curl = curl_version(); $fields['curl_version'] = array( 'label' => __( 'cURL version' ), 'value' => sprintf( '%s %s', $curl['version'], $curl['ssl_version'] ), ); } else { $fields['curl_version'] = array( 'label' => __( 'cURL version' ), 'value' => __( 'Not available' ), 'debug' => 'not available', ); } // SUHOSIN. $suhosin_loaded = ( extension_loaded( 'suhosin' ) || ( defined( 'SUHOSIN_PATCH' ) && constant( 'SUHOSIN_PATCH' ) ) ); $fields['suhosin'] = array( 'label' => __( 'Is SUHOSIN installed?' ), 'value' => ( $suhosin_loaded ? __( 'Yes' ) : __( 'No' ) ), 'debug' => $suhosin_loaded, ); // Imagick. $imagick_loaded = extension_loaded( 'imagick' ); $fields['imagick_availability'] = array( 'label' => __( 'Is the Imagick library available?' ), 'value' => ( $imagick_loaded ? __( 'Yes' ) : __( 'No' ) ), 'debug' => $imagick_loaded, ); // Pretty permalinks. $pretty_permalinks_supported = got_url_rewrite(); $fields['pretty_permalinks'] = array( 'label' => __( 'Are pretty permalinks supported?' ), 'value' => ( $pretty_permalinks_supported ? __( 'Yes' ) : __( 'No' ) ), 'debug' => $pretty_permalinks_supported, ); // Check if a .htaccess file exists. if ( is_file( ABSPATH . '.htaccess' ) ) { // If the file exists, grab the content of it. $htaccess_content = file_get_contents( ABSPATH . '.htaccess' ); // Filter away the core WordPress rules. $filtered_htaccess_content = trim( preg_replace( '/\# BEGIN WordPress[\s\S]+?# END WordPress/si', '', $htaccess_content ) ); $filtered_htaccess_content = ! empty( $filtered_htaccess_content ); if ( $filtered_htaccess_content ) { /* translators: %s: .htaccess */ $htaccess_rules_string = sprintf( __( 'Custom rules have been added to your %s file.' ), '.htaccess' ); } else { /* translators: %s: .htaccess */ $htaccess_rules_string = sprintf( __( 'Your %s file contains only core WordPress features.' ), '.htaccess' ); } $fields['htaccess_extra_rules'] = array( 'label' => __( '.htaccess rules' ), 'value' => $htaccess_rules_string, 'debug' => $filtered_htaccess_content, ); } // Server time. $date = new DateTime( 'now', new DateTimeZone( 'UTC' ) ); $fields['current'] = array( 'label' => __( 'Current time' ), 'value' => $date->format( DateTime::ATOM ), ); $fields['utc-time'] = array( 'label' => __( 'Current UTC time' ), 'value' => $date->format( DateTime::RFC850 ), ); $fields['server-time'] = array( 'label' => __( 'Current Server time' ), 'value' => wp_date( 'c', $_SERVER['REQUEST_TIME'] ), ); return array( 'label' => __( 'Server' ), 'description' => __( 'The options shown below relate to your server setup. If changes are required, you may need your web host’s assistance.' ), 'fields' => $fields, ); } /** * Gets the WordPress media section of the debug data. * * @since 6.7.0 * * @throws ImagickException * @return array */ private static function get_wp_media(): array { // Spare few function calls. $not_available = __( 'Not available' ); // Populate the media fields. $fields['image_editor'] = array( 'label' => __( 'Active editor' ), 'value' => _wp_image_editor_choose(), ); // Get ImageMagic information, if available. if ( class_exists( 'Imagick' ) ) { // Save the Imagick instance for later use. $imagick = new Imagick(); $imagemagick_version = $imagick->getVersion(); } else { $imagemagick_version = __( 'Not available' ); } $fields['imagick_module_version'] = array( 'label' => __( 'ImageMagick version number' ), 'value' => ( is_array( $imagemagick_version ) ? $imagemagick_version['versionNumber'] : $imagemagick_version ), ); $fields['imagemagick_version'] = array( 'label' => __( 'ImageMagick version string' ), 'value' => ( is_array( $imagemagick_version ) ? $imagemagick_version['versionString'] : $imagemagick_version ), ); $imagick_version = phpversion( 'imagick' ); $fields['imagick_version'] = array( 'label' => __( 'Imagick version' ), 'value' => ( $imagick_version ) ? $imagick_version : __( 'Not available' ), ); if ( ! function_exists( 'ini_get' ) ) { $fields['ini_get'] = array( 'label' => __( 'File upload settings' ), 'value' => sprintf( /* translators: %s: ini_get() */ __( 'Unable to determine some settings, as the %s function has been disabled.' ), 'ini_get()' ), 'debug' => 'ini_get() is disabled', ); } else { // Get the PHP ini directive values. $file_uploads = ini_get( 'file_uploads' ); $post_max_size = ini_get( 'post_max_size' ); $upload_max_filesize = ini_get( 'upload_max_filesize' ); $max_file_uploads = ini_get( 'max_file_uploads' ); $effective = min( wp_convert_hr_to_bytes( $post_max_size ), wp_convert_hr_to_bytes( $upload_max_filesize ) ); // Add info in Media section. $fields['file_uploads'] = array( 'label' => __( 'File uploads' ), 'value' => $file_uploads ? __( 'Enabled' ) : __( 'Disabled' ), 'debug' => $file_uploads, ); $fields['post_max_size'] = array( 'label' => __( 'Max size of post data allowed' ), 'value' => $post_max_size, ); $fields['upload_max_filesize'] = array( 'label' => __( 'Max size of an uploaded file' ), 'value' => $upload_max_filesize, ); $fields['max_effective_size'] = array( 'label' => __( 'Max effective file size' ), 'value' => size_format( $effective ), ); $fields['max_file_uploads'] = array( 'label' => __( 'Max simultaneous file uploads' ), 'value' => $max_file_uploads, ); } // If Imagick is used as our editor, provide some more information about its limitations. if ( 'WP_Image_Editor_Imagick' === _wp_image_editor_choose() && isset( $imagick ) && $imagick instanceof Imagick ) { $limits = array( 'area' => ( defined( 'imagick::RESOURCETYPE_AREA' ) ? size_format( $imagick->getResourceLimit( imagick::RESOURCETYPE_AREA ) ) : $not_available ), 'disk' => ( defined( 'imagick::RESOURCETYPE_DISK' ) ? $imagick->getResourceLimit( imagick::RESOURCETYPE_DISK ) : $not_available ), 'file' => ( defined( 'imagick::RESOURCETYPE_FILE' ) ? $imagick->getResourceLimit( imagick::RESOURCETYPE_FILE ) : $not_available ), 'map' => ( defined( 'imagick::RESOURCETYPE_MAP' ) ? size_format( $imagick->getResourceLimit( imagick::RESOURCETYPE_MAP ) ) : $not_available ), 'memory' => ( defined( 'imagick::RESOURCETYPE_MEMORY' ) ? size_format( $imagick->getResourceLimit( imagick::RESOURCETYPE_MEMORY ) ) : $not_available ), 'thread' => ( defined( 'imagick::RESOURCETYPE_THREAD' ) ? $imagick->getResourceLimit( imagick::RESOURCETYPE_THREAD ) : $not_available ), 'time' => ( defined( 'imagick::RESOURCETYPE_TIME' ) ? $imagick->getResourceLimit( imagick::RESOURCETYPE_TIME ) : $not_available ), ); $limits_debug = array( 'imagick::RESOURCETYPE_AREA' => ( defined( 'imagick::RESOURCETYPE_AREA' ) ? size_format( $imagick->getResourceLimit( imagick::RESOURCETYPE_AREA ) ) : 'not available' ), 'imagick::RESOURCETYPE_DISK' => ( defined( 'imagick::RESOURCETYPE_DISK' ) ? $imagick->getResourceLimit( imagick::RESOURCETYPE_DISK ) : 'not available' ), 'imagick::RESOURCETYPE_FILE' => ( defined( 'imagick::RESOURCETYPE_FILE' ) ? $imagick->getResourceLimit( imagick::RESOURCETYPE_FILE ) : 'not available' ), 'imagick::RESOURCETYPE_MAP' => ( defined( 'imagick::RESOURCETYPE_MAP' ) ? size_format( $imagick->getResourceLimit( imagick::RESOURCETYPE_MAP ) ) : 'not available' ), 'imagick::RESOURCETYPE_MEMORY' => ( defined( 'imagick::RESOURCETYPE_MEMORY' ) ? size_format( $imagick->getResourceLimit( imagick::RESOURCETYPE_MEMORY ) ) : 'not available' ), 'imagick::RESOURCETYPE_THREAD' => ( defined( 'imagick::RESOURCETYPE_THREAD' ) ? $imagick->getResourceLimit( imagick::RESOURCETYPE_THREAD ) : 'not available' ), 'imagick::RESOURCETYPE_TIME' => ( defined( 'imagick::RESOURCETYPE_TIME' ) ? $imagick->getResourceLimit( imagick::RESOURCETYPE_TIME ) : 'not available' ), ); $fields['imagick_limits'] = array( 'label' => __( 'Imagick Resource Limits' ), 'value' => $limits, 'debug' => $limits_debug, ); try { $formats = Imagick::queryFormats( '*' ); } catch ( Exception $e ) { $formats = array(); } $fields['imagemagick_file_formats'] = array( 'label' => __( 'ImageMagick supported file formats' ), 'value' => ( empty( $formats ) ) ? __( 'Unable to determine' ) : implode( ', ', $formats ), 'debug' => ( empty( $formats ) ) ? 'Unable to determine' : implode( ', ', $formats ), ); } // Get GD information, if available. if ( function_exists( 'gd_info' ) ) { $gd = gd_info(); } else { $gd = false; } $fields['gd_version'] = array( 'label' => __( 'GD version' ), 'value' => ( is_array( $gd ) ? $gd['GD Version'] : $not_available ), 'debug' => ( is_array( $gd ) ? $gd['GD Version'] : 'not available' ), ); $gd_image_formats = array(); $gd_supported_formats = array( 'GIF Create' => 'GIF', 'JPEG' => 'JPEG', 'PNG' => 'PNG', 'WebP' => 'WebP', 'BMP' => 'BMP', 'AVIF' => 'AVIF', 'HEIF' => 'HEIF', 'TIFF' => 'TIFF', 'XPM' => 'XPM', ); foreach ( $gd_supported_formats as $format_key => $format ) { $index = $format_key . ' Support'; if ( isset( $gd[ $index ] ) && $gd[ $index ] ) { array_push( $gd_image_formats, $format ); } } if ( ! empty( $gd_image_formats ) ) { $fields['gd_formats'] = array( 'label' => __( 'GD supported file formats' ), 'value' => implode( ', ', $gd_image_formats ), ); } // Get Ghostscript information, if available. if ( function_exists( 'exec' ) ) { $gs = exec( 'gs --version' ); if ( empty( $gs ) ) { $gs = $not_available; $gs_debug = 'not available'; } else { $gs_debug = $gs; } } else { $gs = __( 'Unable to determine if Ghostscript is installed' ); $gs_debug = 'unknown'; } $fields['ghostscript_version'] = array( 'label' => __( 'Ghostscript version' ), 'value' => $gs, 'debug' => $gs_debug, ); return array( 'label' => __( 'Media Handling' ), 'fields' => $fields, ); } /** * Gets the WordPress MU plugins section of the debug data. * * @since 6.7.0 * * @return array */ private static function get_wp_mu_plugins(): array { // List must use plugins if there are any. $mu_plugins = get_mu_plugins(); $fields = array(); foreach ( $mu_plugins as $plugin_path => $plugin ) { $plugin_version = $plugin['Version']; $plugin_author = $plugin['Author']; $plugin_version_string = __( 'No version or author information is available.' ); $plugin_version_string_debug = 'author: (undefined), version: (undefined)'; if ( ! empty( $plugin_version ) && ! empty( $plugin_author ) ) { /* translators: 1: Plugin version number. 2: Plugin author name. */ $plugin_version_string = sprintf( __( 'Version %1$s by %2$s' ), $plugin_version, $plugin_author ); $plugin_version_string_debug = sprintf( 'version: %s, author: %s', $plugin_version, $plugin_author ); } else { if ( ! empty( $plugin_author ) ) { /* translators: %s: Plugin author name. */ $plugin_version_string = sprintf( __( 'By %s' ), $plugin_author ); $plugin_version_string_debug = sprintf( 'author: %s, version: (undefined)', $plugin_author ); } if ( ! empty( $plugin_version ) ) { /* translators: %s: Plugin version number. */ $plugin_version_string = sprintf( __( 'Version %s' ), $plugin_version ); $plugin_version_string_debug = sprintf( 'author: (undefined), version: %s', $plugin_version ); } } $fields[ sanitize_text_field( $plugin['Name'] ) ] = array( 'label' => $plugin['Name'], 'value' => $plugin_version_string, 'debug' => $plugin_version_string_debug, ); } return array( 'label' => __( 'Must Use Plugins' ), 'show_count' => true, 'fields' => $fields, ); } /** * Gets the WordPress paths and sizes section of the debug data. * * @since 6.7.0 * * @return array|null Paths and sizes debug data for single sites, * otherwise `null` for multi-site installs. */ private static function get_wp_paths_sizes(): ?array { if ( is_multisite() ) { return null; } $loading = __( 'Loading…' ); $fields = array( 'wordpress_path' => array( 'label' => __( 'WordPress directory location' ), 'value' => untrailingslashit( ABSPATH ), ), 'wordpress_size' => array( 'label' => __( 'WordPress directory size' ), 'value' => $loading, 'debug' => 'loading...', ), 'uploads_path' => array( 'label' => __( 'Uploads directory location' ), 'value' => wp_upload_dir()['basedir'], ), 'uploads_size' => array( 'label' => __( 'Uploads directory size' ), 'value' => $loading, 'debug' => 'loading...', ), 'themes_path' => array( 'label' => __( 'Themes directory location' ), 'value' => get_theme_root(), ), 'themes_size' => array( 'label' => __( 'Themes directory size' ), 'value' => $loading, 'debug' => 'loading...', ), 'plugins_path' => array( 'label' => __( 'Plugins directory location' ), 'value' => WP_PLUGIN_DIR, ), 'plugins_size' => array( 'label' => __( 'Plugins directory size' ), 'value' => $loading, 'debug' => 'loading...', ), 'fonts_path' => array( 'label' => __( 'Fonts directory location' ), 'value' => wp_get_font_dir()['basedir'], ), 'fonts_size' => array( 'label' => __( 'Fonts directory size' ), 'value' => $loading, 'debug' => 'loading...', ), 'database_size' => array( 'label' => __( 'Database size' ), 'value' => $loading, 'debug' => 'loading...', ), 'total_size' => array( 'label' => __( 'Total installation size' ), 'value' => $loading, 'debug' => 'loading...', ), ); return array( /* translators: Filesystem directory paths and storage sizes. */ 'label' => __( 'Directories and Sizes' ), 'fields' => $fields, ); } /** * Gets the WordPress active plugins section of the debug data. * * @since 6.7.0 * * @return array */ private static function get_wp_plugins_active(): array { return array( 'label' => __( 'Active Plugins' ), 'show_count' => true, 'fields' => self::get_wp_plugins_raw_data()['wp-plugins-active'], ); } /** * Gets the WordPress inactive plugins section of the debug data. * * @since 6.7.0 * * @return array */ private static function get_wp_plugins_inactive(): array { return array( 'label' => __( 'Inactive Plugins' ), 'show_count' => true, 'fields' => self::get_wp_plugins_raw_data()['wp-plugins-inactive'], ); } /** * Gets the raw plugin data for the WordPress active and inactive sections of the debug data. * * @since 6.7.0 * * @return array */ private static function get_wp_plugins_raw_data(): array { // List all available plugins. $plugins = get_plugins(); $plugin_updates = get_plugin_updates(); $transient = get_site_transient( 'update_plugins' ); $auto_updates = array(); $fields = array( 'wp-plugins-active' => array(), 'wp-plugins-inactive' => array(), ); $auto_updates_enabled = wp_is_auto_update_enabled_for_type( 'plugin' ); if ( $auto_updates_enabled ) { $auto_updates = (array) get_site_option( 'auto_update_plugins', array() ); } foreach ( $plugins as $plugin_path => $plugin ) { $plugin_part = ( is_plugin_active( $plugin_path ) ) ? 'wp-plugins-active' : 'wp-plugins-inactive'; $plugin_version = $plugin['Version']; $plugin_author = $plugin['Author']; $plugin_version_string = __( 'No version or author information is available.' ); $plugin_version_string_debug = 'author: (undefined), version: (undefined)'; if ( ! empty( $plugin_version ) && ! empty( $plugin_author ) ) { /* translators: 1: Plugin version number. 2: Plugin author name. */ $plugin_version_string = sprintf( __( 'Version %1$s by %2$s' ), $plugin_version, $plugin_author ); $plugin_version_string_debug = sprintf( 'version: %s, author: %s', $plugin_version, $plugin_author ); } else { if ( ! empty( $plugin_author ) ) { /* translators: %s: Plugin author name. */ $plugin_version_string = sprintf( __( 'By %s' ), $plugin_author ); $plugin_version_string_debug = sprintf( 'author: %s, version: (undefined)', $plugin_author ); } if ( ! empty( $plugin_version ) ) { /* translators: %s: Plugin version number. */ $plugin_version_string = sprintf( __( 'Version %s' ), $plugin_version ); $plugin_version_string_debug = sprintf( 'author: (undefined), version: %s', $plugin_version ); } } if ( array_key_exists( $plugin_path, $plugin_updates ) ) { /* translators: %s: Latest plugin version number. */ $plugin_version_string .= ' ' . sprintf( __( '(Latest version: %s)' ), $plugin_updates[ $plugin_path ]->update->new_version ); $plugin_version_string_debug .= sprintf( ' (latest version: %s)', $plugin_updates[ $plugin_path ]->update->new_version ); } if ( $auto_updates_enabled ) { if ( isset( $transient->response[ $plugin_path ] ) ) { $item = $transient->response[ $plugin_path ]; } elseif ( isset( $transient->no_update[ $plugin_path ] ) ) { $item = $transient->no_update[ $plugin_path ]; } else { $item = array( 'id' => $plugin_path, 'slug' => '', 'plugin' => $plugin_path, 'new_version' => '', 'url' => '', 'package' => '', 'icons' => array(), 'banners' => array(), 'banners_rtl' => array(), 'tested' => '', 'requires_php' => '', 'compatibility' => new stdClass(), ); $item = wp_parse_args( $plugin, $item ); } $auto_update_forced = wp_is_auto_update_forced_for_item( 'plugin', null, (object) $item ); if ( ! is_null( $auto_update_forced ) ) { $enabled = $auto_update_forced; } else { $enabled = in_array( $plugin_path, $auto_updates, true ); } if ( $enabled ) { $auto_updates_string = __( 'Auto-updates enabled' ); } else { $auto_updates_string = __( 'Auto-updates disabled' ); } /** * Filters the text string of the auto-updates setting for each plugin in the Site Health debug data. * * @since 5.5.0 * * @param string $auto_updates_string The string output for the auto-updates column. * @param string $plugin_path The path to the plugin file. * @param array $plugin An array of plugin data. * @param bool $enabled Whether auto-updates are enabled for this item. */ $auto_updates_string = apply_filters( 'plugin_auto_update_debug_string', $auto_updates_string, $plugin_path, $plugin, $enabled ); $plugin_version_string .= ' | ' . $auto_updates_string; $plugin_version_string_debug .= ', ' . $auto_updates_string; } $fields[ $plugin_part ][ sanitize_text_field( $plugin['Name'] ) ] = array( 'label' => $plugin['Name'], 'value' => $plugin_version_string, 'debug' => $plugin_version_string_debug, ); } return $fields; } /** * Gets the WordPress active theme section of the debug data. * * @since 6.7.0 * * @global array $_wp_theme_features * * @return array */ private static function get_wp_active_theme(): array { global $_wp_theme_features; // Populate the section for the currently active theme. $theme_features = array(); if ( ! empty( $_wp_theme_features ) ) { foreach ( $_wp_theme_features as $feature => $options ) { $theme_features[] = $feature; } } $active_theme = wp_get_theme(); $theme_updates = get_theme_updates(); $transient = get_site_transient( 'update_themes' ); $active_theme_version = $active_theme->version; $active_theme_version_debug = $active_theme_version; $auto_updates = array(); $auto_updates_enabled = wp_is_auto_update_enabled_for_type( 'theme' ); if ( $auto_updates_enabled ) { $auto_updates = (array) get_site_option( 'auto_update_themes', array() ); } if ( array_key_exists( $active_theme->stylesheet, $theme_updates ) ) { $theme_update_new_version = $theme_updates[ $active_theme->stylesheet ]->update['new_version']; /* translators: %s: Latest theme version number. */ $active_theme_version .= ' ' . sprintf( __( '(Latest version: %s)' ), $theme_update_new_version ); $active_theme_version_debug .= sprintf( ' (latest version: %s)', $theme_update_new_version ); } $active_theme_author_uri = $active_theme->display( 'AuthorURI' ); if ( $active_theme->parent_theme ) { $active_theme_parent_theme = sprintf( /* translators: 1: Theme name. 2: Theme slug. */ __( '%1$s (%2$s)' ), $active_theme->parent_theme, $active_theme->template ); $active_theme_parent_theme_debug = sprintf( '%s (%s)', $active_theme->parent_theme, $active_theme->template ); } else { $active_theme_parent_theme = __( 'None' ); $active_theme_parent_theme_debug = 'none'; } $fields = array( 'name' => array( 'label' => __( 'Name' ), 'value' => sprintf( /* translators: 1: Theme name. 2: Theme slug. */ __( '%1$s (%2$s)' ), $active_theme->name, $active_theme->stylesheet ), ), 'version' => array( 'label' => __( 'Version' ), 'value' => $active_theme_version, 'debug' => $active_theme_version_debug, ), 'author' => array( 'label' => __( 'Author' ), 'value' => wp_kses( $active_theme->author, array() ), ), 'author_website' => array( 'label' => __( 'Author website' ), 'value' => ( $active_theme_author_uri ? $active_theme_author_uri : __( 'Undefined' ) ), 'debug' => ( $active_theme_author_uri ? $active_theme_author_uri : '(undefined)' ), ), 'parent_theme' => array( 'label' => __( 'Parent theme' ), 'value' => $active_theme_parent_theme, 'debug' => $active_theme_parent_theme_debug, ), 'theme_features' => array( 'label' => __( 'Theme features' ), 'value' => implode( ', ', $theme_features ), ), 'theme_path' => array( 'label' => __( 'Theme directory location' ), 'value' => get_stylesheet_directory(), ), ); if ( $auto_updates_enabled ) { if ( isset( $transient->response[ $active_theme->stylesheet ] ) ) { $item = $transient->response[ $active_theme->stylesheet ]; } elseif ( isset( $transient->no_update[ $active_theme->stylesheet ] ) ) { $item = $transient->no_update[ $active_theme->stylesheet ]; } else { $item = array( 'theme' => $active_theme->stylesheet, 'new_version' => $active_theme->version, 'url' => '', 'package' => '', 'requires' => '', 'requires_php' => '', ); } $auto_update_forced = wp_is_auto_update_forced_for_item( 'theme', null, (object) $item ); if ( ! is_null( $auto_update_forced ) ) { $enabled = $auto_update_forced; } else { $enabled = in_array( $active_theme->stylesheet, $auto_updates, true ); } if ( $enabled ) { $auto_updates_string = __( 'Enabled' ); } else { $auto_updates_string = __( 'Disabled' ); } /** This filter is documented in wp-admin/includes/class-wp-debug-data.php */ $auto_updates_string = apply_filters( 'theme_auto_update_debug_string', $auto_updates_string, $active_theme, $enabled ); $fields['auto_update'] = array( 'label' => __( 'Auto-updates' ), 'value' => $auto_updates_string, 'debug' => $auto_updates_string, ); } return array( 'label' => __( 'Active Theme' ), 'fields' => $fields, ); } /** * Gets the WordPress parent theme section of the debug data. * * @since 6.7.0 * * @return array */ private static function get_wp_parent_theme(): array { $theme_updates = get_theme_updates(); $transient = get_site_transient( 'update_themes' ); $auto_updates = array(); $auto_updates_enabled = wp_is_auto_update_enabled_for_type( 'theme' ); if ( $auto_updates_enabled ) { $auto_updates = (array) get_site_option( 'auto_update_themes', array() ); } $active_theme = wp_get_theme(); $parent_theme = $active_theme->parent(); $fields = array(); if ( $parent_theme ) { $parent_theme_version = $parent_theme->version; $parent_theme_version_debug = $parent_theme_version; if ( array_key_exists( $parent_theme->stylesheet, $theme_updates ) ) { $parent_theme_update_new_version = $theme_updates[ $parent_theme->stylesheet ]->update['new_version']; /* translators: %s: Latest theme version number. */ $parent_theme_version .= ' ' . sprintf( __( '(Latest version: %s)' ), $parent_theme_update_new_version ); $parent_theme_version_debug .= sprintf( ' (latest version: %s)', $parent_theme_update_new_version ); } $parent_theme_author_uri = $parent_theme->display( 'AuthorURI' ); $fields = array( 'name' => array( 'label' => __( 'Name' ), 'value' => sprintf( /* translators: 1: Theme name. 2: Theme slug. */ __( '%1$s (%2$s)' ), $parent_theme->name, $parent_theme->stylesheet ), ), 'version' => array( 'label' => __( 'Version' ), 'value' => $parent_theme_version, 'debug' => $parent_theme_version_debug, ), 'author' => array( 'label' => __( 'Author' ), 'value' => wp_kses( $parent_theme->author, array() ), ), 'author_website' => array( 'label' => __( 'Author website' ), 'value' => ( $parent_theme_author_uri ? $parent_theme_author_uri : __( 'Undefined' ) ), 'debug' => ( $parent_theme_author_uri ? $parent_theme_author_uri : '(undefined)' ), ), 'theme_path' => array( 'label' => __( 'Theme directory location' ), 'value' => get_template_directory(), ), ); if ( $auto_updates_enabled ) { if ( isset( $transient->response[ $parent_theme->stylesheet ] ) ) { $item = $transient->response[ $parent_theme->stylesheet ]; } elseif ( isset( $transient->no_update[ $parent_theme->stylesheet ] ) ) { $item = $transient->no_update[ $parent_theme->stylesheet ]; } else { $item = array( 'theme' => $parent_theme->stylesheet, 'new_version' => $parent_theme->version, 'url' => '', 'package' => '', 'requires' => '', 'requires_php' => '', ); } $auto_update_forced = wp_is_auto_update_forced_for_item( 'theme', null, (object) $item ); if ( ! is_null( $auto_update_forced ) ) { $enabled = $auto_update_forced; } else { $enabled = in_array( $parent_theme->stylesheet, $auto_updates, true ); } if ( $enabled ) { $parent_theme_auto_update_string = __( 'Enabled' ); } else { $parent_theme_auto_update_string = __( 'Disabled' ); } /** This filter is documented in wp-admin/includes/class-wp-debug-data.php */ $parent_theme_auto_update_string = apply_filters( 'theme_auto_update_debug_string', $parent_theme_auto_update_string, $parent_theme, $enabled ); $fields['auto_update'] = array( 'label' => __( 'Auto-update' ), 'value' => $parent_theme_auto_update_string, 'debug' => $parent_theme_auto_update_string, ); } } return array( 'label' => __( 'Parent Theme' ), 'fields' => $fields, ); } /** * Gets the WordPress inactive themes section of the debug data. * * @since 6.7.0 * * @return array */ private static function get_wp_themes_inactive(): array { $active_theme = wp_get_theme(); $parent_theme = $active_theme->parent(); $theme_updates = get_theme_updates(); $auto_updates = array(); $auto_updates_enabled = wp_is_auto_update_enabled_for_type( 'theme' ); if ( $auto_updates_enabled ) { $auto_updates = (array) get_site_option( 'auto_update_themes', array() ); } // Populate a list of all themes available in the installation. $all_themes = wp_get_themes(); $fields = array(); foreach ( $all_themes as $theme_slug => $theme ) { // Exclude the currently active theme from the list of all themes. if ( $active_theme->stylesheet === $theme_slug ) { continue; } // Exclude the currently active parent theme from the list of all themes. if ( ! empty( $parent_theme ) && $parent_theme->stylesheet === $theme_slug ) { continue; } $theme_version = $theme->version; $theme_author = $theme->author; // Sanitize. $theme_author = wp_kses( $theme_author, array() ); $theme_version_string = __( 'No version or author information is available.' ); $theme_version_string_debug = 'undefined'; if ( ! empty( $theme_version ) && ! empty( $theme_author ) ) { /* translators: 1: Theme version number. 2: Theme author name. */ $theme_version_string = sprintf( __( 'Version %1$s by %2$s' ), $theme_version, $theme_author ); $theme_version_string_debug = sprintf( 'version: %s, author: %s', $theme_version, $theme_author ); } else { if ( ! empty( $theme_author ) ) { /* translators: %s: Theme author name. */ $theme_version_string = sprintf( __( 'By %s' ), $theme_author ); $theme_version_string_debug = sprintf( 'author: %s, version: (undefined)', $theme_author ); } if ( ! empty( $theme_version ) ) { /* translators: %s: Theme version number. */ $theme_version_string = sprintf( __( 'Version %s' ), $theme_version ); $theme_version_string_debug = sprintf( 'author: (undefined), version: %s', $theme_version ); } } if ( array_key_exists( $theme_slug, $theme_updates ) ) { /* translators: %s: Latest theme version number. */ $theme_version_string .= ' ' . sprintf( __( '(Latest version: %s)' ), $theme_updates[ $theme_slug ]->update['new_version'] ); $theme_version_string_debug .= sprintf( ' (latest version: %s)', $theme_updates[ $theme_slug ]->update['new_version'] ); } if ( $auto_updates_enabled ) { if ( isset( $transient->response[ $theme_slug ] ) ) { $item = $transient->response[ $theme_slug ]; } elseif ( isset( $transient->no_update[ $theme_slug ] ) ) { $item = $transient->no_update[ $theme_slug ]; } else { $item = array( 'theme' => $theme_slug, 'new_version' => $theme->version, 'url' => '', 'package' => '', 'requires' => '', 'requires_php' => '', ); } $auto_update_forced = wp_is_auto_update_forced_for_item( 'theme', null, (object) $item ); if ( ! is_null( $auto_update_forced ) ) { $enabled = $auto_update_forced; } else { $enabled = in_array( $theme_slug, $auto_updates, true ); } if ( $enabled ) { $auto_updates_string = __( 'Auto-updates enabled' ); } else { $auto_updates_string = __( 'Auto-updates disabled' ); } /** * Filters the text string of the auto-updates setting for each theme in the Site Health debug data. * * @since 5.5.0 * * @param string $auto_updates_string The string output for the auto-updates column. * @param WP_Theme $theme An object of theme data. * @param bool $enabled Whether auto-updates are enabled for this item. */ $auto_updates_string = apply_filters( 'theme_auto_update_debug_string', $auto_updates_string, $theme, $enabled ); $theme_version_string .= ' | ' . $auto_updates_string; $theme_version_string_debug .= ', ' . $auto_updates_string; } $fields[ sanitize_text_field( $theme->name ) ] = array( 'label' => sprintf( /* translators: 1: Theme name. 2: Theme slug. */ __( '%1$s (%2$s)' ), $theme->name, $theme_slug ), 'value' => $theme_version_string, 'debug' => $theme_version_string_debug, ); } return array( 'label' => __( 'Inactive Themes' ), 'show_count' => true, 'fields' => $fields, ); } /** * Gets the WordPress constants section of the debug data. * * @since 6.7.0 * * @return array */ private static function get_wp_constants(): array { // Check if WP_DEBUG_LOG is set. $wp_debug_log_value = __( 'Disabled' ); if ( is_string( WP_DEBUG_LOG ) ) { $wp_debug_log_value = WP_DEBUG_LOG; } elseif ( WP_DEBUG_LOG ) { $wp_debug_log_value = __( 'Enabled' ); } // Check CONCATENATE_SCRIPTS. if ( defined( 'CONCATENATE_SCRIPTS' ) ) { $concatenate_scripts = CONCATENATE_SCRIPTS ? __( 'Enabled' ) : __( 'Disabled' ); $concatenate_scripts_debug = CONCATENATE_SCRIPTS ? 'true' : 'false'; } else { $concatenate_scripts = __( 'Undefined' ); $concatenate_scripts_debug = 'undefined'; } // Check COMPRESS_SCRIPTS. if ( defined( 'COMPRESS_SCRIPTS' ) ) { $compress_scripts = COMPRESS_SCRIPTS ? __( 'Enabled' ) : __( 'Disabled' ); $compress_scripts_debug = COMPRESS_SCRIPTS ? 'true' : 'false'; } else { $compress_scripts = __( 'Undefined' ); $compress_scripts_debug = 'undefined'; } // Check COMPRESS_CSS. if ( defined( 'COMPRESS_CSS' ) ) { $compress_css = COMPRESS_CSS ? __( 'Enabled' ) : __( 'Disabled' ); $compress_css_debug = COMPRESS_CSS ? 'true' : 'false'; } else { $compress_css = __( 'Undefined' ); $compress_css_debug = 'undefined'; } // Check WP_ENVIRONMENT_TYPE. if ( defined( 'WP_ENVIRONMENT_TYPE' ) ) { $wp_environment_type = WP_ENVIRONMENT_TYPE ? WP_ENVIRONMENT_TYPE : __( 'Empty value' ); $wp_environment_type_debug = WP_ENVIRONMENT_TYPE; } else { $wp_environment_type = __( 'Undefined' ); $wp_environment_type_debug = 'undefined'; } // Check DB_COLLATE. if ( defined( 'DB_COLLATE' ) ) { $db_collate = DB_COLLATE ? DB_COLLATE : __( 'Empty value' ); $db_collate_debug = DB_COLLATE; } else { $db_collate = __( 'Undefined' ); $db_collate_debug = 'undefined'; } $fields = array( 'ABSPATH' => array( 'label' => 'ABSPATH', 'value' => ABSPATH, 'private' => true, ), 'WP_HOME' => array( 'label' => 'WP_HOME', 'value' => ( defined( 'WP_HOME' ) ? WP_HOME : __( 'Undefined' ) ), 'debug' => ( defined( 'WP_HOME' ) ? WP_HOME : 'undefined' ), ), 'WP_SITEURL' => array( 'label' => 'WP_SITEURL', 'value' => ( defined( 'WP_SITEURL' ) ? WP_SITEURL : __( 'Undefined' ) ), 'debug' => ( defined( 'WP_SITEURL' ) ? WP_SITEURL : 'undefined' ), ), 'WP_CONTENT_DIR' => array( 'label' => 'WP_CONTENT_DIR', 'value' => WP_CONTENT_DIR, ), 'WP_PLUGIN_DIR' => array( 'label' => 'WP_PLUGIN_DIR', 'value' => WP_PLUGIN_DIR, ), 'WP_MEMORY_LIMIT' => array( 'label' => 'WP_MEMORY_LIMIT', 'value' => WP_MEMORY_LIMIT, ), 'WP_MAX_MEMORY_LIMIT' => array( 'label' => 'WP_MAX_MEMORY_LIMIT', 'value' => WP_MAX_MEMORY_LIMIT, ), 'WP_DEBUG' => array( 'label' => 'WP_DEBUG', 'value' => WP_DEBUG ? __( 'Enabled' ) : __( 'Disabled' ), 'debug' => WP_DEBUG, ), 'WP_DEBUG_DISPLAY' => array( 'label' => 'WP_DEBUG_DISPLAY', 'value' => WP_DEBUG_DISPLAY ? __( 'Enabled' ) : __( 'Disabled' ), 'debug' => WP_DEBUG_DISPLAY, ), 'WP_DEBUG_LOG' => array( 'label' => 'WP_DEBUG_LOG', 'value' => $wp_debug_log_value, 'debug' => WP_DEBUG_LOG, ), 'SCRIPT_DEBUG' => array( 'label' => 'SCRIPT_DEBUG', 'value' => SCRIPT_DEBUG ? __( 'Enabled' ) : __( 'Disabled' ), 'debug' => SCRIPT_DEBUG, ), 'WP_CACHE' => array( 'label' => 'WP_CACHE', 'value' => WP_CACHE ? __( 'Enabled' ) : __( 'Disabled' ), 'debug' => WP_CACHE, ), 'CONCATENATE_SCRIPTS' => array( 'label' => 'CONCATENATE_SCRIPTS', 'value' => $concatenate_scripts, 'debug' => $concatenate_scripts_debug, ), 'COMPRESS_SCRIPTS' => array( 'label' => 'COMPRESS_SCRIPTS', 'value' => $compress_scripts, 'debug' => $compress_scripts_debug, ), 'COMPRESS_CSS' => array( 'label' => 'COMPRESS_CSS', 'value' => $compress_css, 'debug' => $compress_css_debug, ), 'WP_ENVIRONMENT_TYPE' => array( 'label' => 'WP_ENVIRONMENT_TYPE', 'value' => $wp_environment_type, 'debug' => $wp_environment_type_debug, ), 'WP_DEVELOPMENT_MODE' => array( 'label' => 'WP_DEVELOPMENT_MODE', 'value' => WP_DEVELOPMENT_MODE ? WP_DEVELOPMENT_MODE : __( 'Disabled' ), 'debug' => WP_DEVELOPMENT_MODE, ), 'DB_CHARSET' => array( 'label' => 'DB_CHARSET', 'value' => ( defined( 'DB_CHARSET' ) ? DB_CHARSET : __( 'Undefined' ) ), 'debug' => ( defined( 'DB_CHARSET' ) ? DB_CHARSET : 'undefined' ), ), 'DB_COLLATE' => array( 'label' => 'DB_COLLATE', 'value' => $db_collate, 'debug' => $db_collate_debug, ), ); return array( 'label' => __( 'WordPress Constants' ), 'description' => __( 'These settings alter where and how parts of WordPress are loaded.' ), 'fields' => $fields, ); } /** * Gets the WordPress database section of the debug data. * * @since 6.7.0 * * @global wpdb $wpdb WordPress database abstraction object. * * @return array */ private static function get_wp_database(): array { global $wpdb; // Populate the database debug fields. if ( is_object( $wpdb->dbh ) ) { // mysqli or PDO. $extension = get_class( $wpdb->dbh ); } else { // Unknown sql extension. $extension = null; } $server = $wpdb->get_var( 'SELECT VERSION()' ); $client_version = $wpdb->dbh->client_info; $fields = array( 'extension' => array( 'label' => __( 'Database Extension' ), 'value' => $extension, ), 'server_version' => array( 'label' => __( 'Server version' ), 'value' => $server, ), 'client_version' => array( 'label' => __( 'Client version' ), 'value' => $client_version, ), 'database_user' => array( 'label' => __( 'Database username' ), 'value' => $wpdb->dbuser, 'private' => true, ), 'database_host' => array( 'label' => __( 'Database host' ), 'value' => $wpdb->dbhost, 'private' => true, ), 'database_name' => array( 'label' => __( 'Database name' ), 'value' => $wpdb->dbname, 'private' => true, ), 'database_prefix' => array( 'label' => __( 'Table prefix' ), 'value' => $wpdb->prefix, 'private' => true, ), 'database_charset' => array( 'label' => __( 'Database charset' ), 'value' => $wpdb->charset, 'private' => true, ), 'database_collate' => array( 'label' => __( 'Database collation' ), 'value' => $wpdb->collate, 'private' => true, ), 'max_allowed_packet' => array( 'label' => __( 'Max allowed packet size' ), 'value' => self::get_mysql_var( 'max_allowed_packet' ), ), 'max_connections' => array( 'label' => __( 'Max connections number' ), 'value' => self::get_mysql_var( 'max_connections' ), ), ); return array( 'label' => __( 'Database' ), 'fields' => $fields, ); } /** * Gets the file system section of the debug data. * * @since 6.7.0 * * @return array */ private static function get_wp_filesystem(): array { $upload_dir = wp_upload_dir(); $is_writable_abspath = wp_is_writable( ABSPATH ); $is_writable_wp_content_dir = wp_is_writable( WP_CONTENT_DIR ); $is_writable_upload_dir = wp_is_writable( $upload_dir['basedir'] ); $is_writable_wp_plugin_dir = wp_is_writable( WP_PLUGIN_DIR ); $is_writable_template_directory = wp_is_writable( get_theme_root( get_template() ) ); $is_writable_fonts_dir = wp_is_writable( wp_get_font_dir()['basedir'] ); $fields = array( 'wordpress' => array( 'label' => __( 'The main WordPress directory' ), 'value' => ( $is_writable_abspath ? __( 'Writable' ) : __( 'Not writable' ) ), 'debug' => ( $is_writable_abspath ? 'writable' : 'not writable' ), ), 'wp-content' => array( 'label' => __( 'The wp-content directory' ), 'value' => ( $is_writable_wp_content_dir ? __( 'Writable' ) : __( 'Not writable' ) ), 'debug' => ( $is_writable_wp_content_dir ? 'writable' : 'not writable' ), ), 'uploads' => array( 'label' => __( 'The uploads directory' ), 'value' => ( $is_writable_upload_dir ? __( 'Writable' ) : __( 'Not writable' ) ), 'debug' => ( $is_writable_upload_dir ? 'writable' : 'not writable' ), ), 'plugins' => array( 'label' => __( 'The plugins directory' ), 'value' => ( $is_writable_wp_plugin_dir ? __( 'Writable' ) : __( 'Not writable' ) ), 'debug' => ( $is_writable_wp_plugin_dir ? 'writable' : 'not writable' ), ), 'themes' => array( 'label' => __( 'The themes directory' ), 'value' => ( $is_writable_template_directory ? __( 'Writable' ) : __( 'Not writable' ) ), 'debug' => ( $is_writable_template_directory ? 'writable' : 'not writable' ), ), 'fonts' => array( 'label' => __( 'The fonts directory' ), 'value' => ( $is_writable_fonts_dir ? __( 'Writable' ) : __( 'Not writable' ) ), 'debug' => ( $is_writable_fonts_dir ? 'writable' : 'not writable' ), ), ); // Add more filesystem checks. if ( defined( 'WPMU_PLUGIN_DIR' ) && is_dir( WPMU_PLUGIN_DIR ) ) { $is_writable_wpmu_plugin_dir = wp_is_writable( WPMU_PLUGIN_DIR ); $fields['mu-plugins'] = array( 'label' => __( 'The must use plugins directory' ), 'value' => ( $is_writable_wpmu_plugin_dir ? __( 'Writable' ) : __( 'Not writable' ) ), 'debug' => ( $is_writable_wpmu_plugin_dir ? 'writable' : 'not writable' ), ); } return array( 'label' => __( 'Filesystem Permissions' ), 'description' => __( 'Shows whether WordPress is able to write to the directories it needs access to.' ), 'fields' => $fields, ); } /** * Returns the value of a MySQL system variable. * * @since 5.9.0 * * @global wpdb $wpdb WordPress database abstraction object. * * @param string $mysql_var Name of the MySQL system variable. * @return string|null The variable value on success. Null if the variable does not exist. */ public static function get_mysql_var( $mysql_var ) { global $wpdb; $result = $wpdb->get_row( $wpdb->prepare( 'SHOW VARIABLES LIKE %s', $mysql_var ), ARRAY_A ); if ( ! empty( $result ) && array_key_exists( 'Value', $result ) ) { return $result['Value']; } return null; } /** * Formats the information gathered for debugging, in a manner suitable for copying to a forum or support ticket. * * @since 5.2.0 * * @param array $info_array Information gathered from the `WP_Debug_Data::debug_data()` function. * @param string $data_type The data type to return, either 'info' or 'debug'. * @return string The formatted data. */ public static function format( $info_array, $data_type ) { $return = "`\n"; foreach ( $info_array as $section => $details ) { // Skip this section if there are no fields, or the section has been declared as private. if ( empty( $details['fields'] ) || ( isset( $details['private'] ) && $details['private'] ) ) { continue; } $section_label = 'debug' === $data_type ? $section : $details['label']; $return .= sprintf( "### %s%s ###\n\n", $section_label, ( isset( $details['show_count'] ) && $details['show_count'] ? sprintf( ' (%d)', count( $details['fields'] ) ) : '' ) ); foreach ( $details['fields'] as $field_name => $field ) { if ( isset( $field['private'] ) && true === $field['private'] ) { continue; } if ( 'debug' === $data_type && isset( $field['debug'] ) ) { $debug_data = $field['debug']; } else { $debug_data = $field['value']; } // Can be array, one level deep only. if ( is_array( $debug_data ) ) { $value = ''; foreach ( $debug_data as $sub_field_name => $sub_field_value ) { $value .= sprintf( "\n\t%s: %s", $sub_field_name, $sub_field_value ); } } elseif ( is_bool( $debug_data ) ) { $value = $debug_data ? 'true' : 'false'; } elseif ( empty( $debug_data ) && '0' !== $debug_data ) { $value = 'undefined'; } else { $value = $debug_data; } if ( 'debug' === $data_type ) { $label = $field_name; } else { $label = $field['label']; } $return .= sprintf( "%s: %s\n", $label, $value ); } $return .= "\n"; } $return .= '`'; return $return; } /** * Fetches the total size of all the database tables for the active database user. * * @since 5.2.0 * * @global wpdb $wpdb WordPress database abstraction object. * * @return int The size of the database, in bytes. */ public static function get_database_size() { global $wpdb; $size = 0; $rows = $wpdb->get_results( 'SHOW TABLE STATUS', ARRAY_A ); if ( $wpdb->num_rows > 0 ) { foreach ( $rows as $row ) { $size += $row['Data_length'] + $row['Index_length']; } } return (int) $size; } /** * Fetches the sizes of the WordPress directories: `wordpress` (ABSPATH), `plugins`, `themes`, and `uploads`. * Intended to supplement the array returned by `WP_Debug_Data::debug_data()`. * * @since 5.2.0 * * @return array The sizes of the directories, also the database size and total installation size. */ public static function get_sizes() { $size_db = self::get_database_size(); $upload_dir = wp_get_upload_dir(); /* * We will be using the PHP max execution time to prevent the size calculations * from causing a timeout. The default value is 30 seconds, and some * hosts do not allow you to read configuration values. */ if ( function_exists( 'ini_get' ) ) { $max_execution_time = ini_get( 'max_execution_time' ); } /* * The max_execution_time defaults to 0 when PHP runs from cli. * We still want to limit it below. */ if ( empty( $max_execution_time ) ) { $max_execution_time = 30; // 30 seconds. } if ( $max_execution_time > 20 ) { /* * If the max_execution_time is set to lower than 20 seconds, reduce it a bit to prevent * edge-case timeouts that may happen after the size loop has finished running. */ $max_execution_time -= 2; } /* * Go through the various installation directories and calculate their sizes. * No trailing slashes. */ $paths = array( 'wordpress_size' => untrailingslashit( ABSPATH ), 'themes_size' => get_theme_root(), 'plugins_size' => WP_PLUGIN_DIR, 'uploads_size' => $upload_dir['basedir'], 'fonts_size' => wp_get_font_dir()['basedir'], ); $exclude = $paths; unset( $exclude['wordpress_size'] ); $exclude = array_values( $exclude ); $size_total = 0; $all_sizes = array(); // Loop over all the directories we want to gather the sizes for. foreach ( $paths as $name => $path ) { $dir_size = null; // Default to timeout. $results = array( 'path' => $path, 'raw' => 0, ); // If the directory does not exist, skip checking it, as it will skew the other results. if ( ! is_dir( $path ) ) { $all_sizes[ $name ] = array( 'path' => $path, 'raw' => 0, 'size' => __( 'The directory does not exist.' ), 'debug' => 'directory not found', ); continue; } if ( microtime( true ) - WP_START_TIMESTAMP < $max_execution_time ) { if ( 'wordpress_size' === $name ) { $dir_size = recurse_dirsize( $path, $exclude, $max_execution_time ); } else { $dir_size = recurse_dirsize( $path, null, $max_execution_time ); } } if ( false === $dir_size ) { // Error reading. $results['size'] = __( 'The size cannot be calculated. The directory is not accessible. Usually caused by invalid permissions.' ); $results['debug'] = 'not accessible'; // Stop total size calculation. $size_total = null; } elseif ( null === $dir_size ) { // Timeout. $results['size'] = __( 'The directory size calculation has timed out. Usually caused by a very large number of sub-directories and files.' ); $results['debug'] = 'timeout while calculating size'; // Stop total size calculation. $size_total = null; } else { if ( null !== $size_total ) { $size_total += $dir_size; } $results['raw'] = $dir_size; $results['size'] = size_format( $dir_size, 2 ); $results['debug'] = $results['size'] . " ({$dir_size} bytes)"; } $all_sizes[ $name ] = $results; } if ( $size_db > 0 ) { $database_size = size_format( $size_db, 2 ); $all_sizes['database_size'] = array( 'raw' => $size_db, 'size' => $database_size, 'debug' => $database_size . " ({$size_db} bytes)", ); } else { $all_sizes['database_size'] = array( 'size' => __( 'Not available' ), 'debug' => 'not available', ); } if ( null !== $size_total && $size_db > 0 ) { $total_size = $size_total + $size_db; $total_size_mb = size_format( $total_size, 2 ); $all_sizes['total_size'] = array( 'raw' => $total_size, 'size' => $total_size_mb, 'debug' => $total_size_mb . " ({$total_size} bytes)", ); } else { $all_sizes['total_size'] = array( 'size' => __( 'Total size is not available. Some errors were encountered when determining the size of your installation.' ), 'debug' => 'not available', ); } return $all_sizes; } } update-core.php000064400000207323147206365750007513 0ustar00 'wp-includes/Requests/Auth.php', 'Requests_Hooker' => 'wp-includes/Requests/Hooker.php', 'Requests_Proxy' => 'wp-includes/Requests/Proxy.php', 'Requests_Transport' => 'wp-includes/Requests/Transport.php', // Classes. 'Requests_Auth_Basic' => 'wp-includes/Requests/Auth/Basic.php', 'Requests_Cookie_Jar' => 'wp-includes/Requests/Cookie/Jar.php', 'Requests_Exception_HTTP' => 'wp-includes/Requests/Exception/HTTP.php', 'Requests_Exception_Transport' => 'wp-includes/Requests/Exception/Transport.php', 'Requests_Exception_HTTP_304' => 'wp-includes/Requests/Exception/HTTP/304.php', 'Requests_Exception_HTTP_305' => 'wp-includes/Requests/Exception/HTTP/305.php', 'Requests_Exception_HTTP_306' => 'wp-includes/Requests/Exception/HTTP/306.php', 'Requests_Exception_HTTP_400' => 'wp-includes/Requests/Exception/HTTP/400.php', 'Requests_Exception_HTTP_401' => 'wp-includes/Requests/Exception/HTTP/401.php', 'Requests_Exception_HTTP_402' => 'wp-includes/Requests/Exception/HTTP/402.php', 'Requests_Exception_HTTP_403' => 'wp-includes/Requests/Exception/HTTP/403.php', 'Requests_Exception_HTTP_404' => 'wp-includes/Requests/Exception/HTTP/404.php', 'Requests_Exception_HTTP_405' => 'wp-includes/Requests/Exception/HTTP/405.php', 'Requests_Exception_HTTP_406' => 'wp-includes/Requests/Exception/HTTP/406.php', 'Requests_Exception_HTTP_407' => 'wp-includes/Requests/Exception/HTTP/407.php', 'Requests_Exception_HTTP_408' => 'wp-includes/Requests/Exception/HTTP/408.php', 'Requests_Exception_HTTP_409' => 'wp-includes/Requests/Exception/HTTP/409.php', 'Requests_Exception_HTTP_410' => 'wp-includes/Requests/Exception/HTTP/410.php', 'Requests_Exception_HTTP_411' => 'wp-includes/Requests/Exception/HTTP/411.php', 'Requests_Exception_HTTP_412' => 'wp-includes/Requests/Exception/HTTP/412.php', 'Requests_Exception_HTTP_413' => 'wp-includes/Requests/Exception/HTTP/413.php', 'Requests_Exception_HTTP_414' => 'wp-includes/Requests/Exception/HTTP/414.php', 'Requests_Exception_HTTP_415' => 'wp-includes/Requests/Exception/HTTP/415.php', 'Requests_Exception_HTTP_416' => 'wp-includes/Requests/Exception/HTTP/416.php', 'Requests_Exception_HTTP_417' => 'wp-includes/Requests/Exception/HTTP/417.php', 'Requests_Exception_HTTP_418' => 'wp-includes/Requests/Exception/HTTP/418.php', 'Requests_Exception_HTTP_428' => 'wp-includes/Requests/Exception/HTTP/428.php', 'Requests_Exception_HTTP_429' => 'wp-includes/Requests/Exception/HTTP/429.php', 'Requests_Exception_HTTP_431' => 'wp-includes/Requests/Exception/HTTP/431.php', 'Requests_Exception_HTTP_500' => 'wp-includes/Requests/Exception/HTTP/500.php', 'Requests_Exception_HTTP_501' => 'wp-includes/Requests/Exception/HTTP/501.php', 'Requests_Exception_HTTP_502' => 'wp-includes/Requests/Exception/HTTP/502.php', 'Requests_Exception_HTTP_503' => 'wp-includes/Requests/Exception/HTTP/503.php', 'Requests_Exception_HTTP_504' => 'wp-includes/Requests/Exception/HTTP/504.php', 'Requests_Exception_HTTP_505' => 'wp-includes/Requests/Exception/HTTP/505.php', 'Requests_Exception_HTTP_511' => 'wp-includes/Requests/Exception/HTTP/511.php', 'Requests_Exception_HTTP_Unknown' => 'wp-includes/Requests/Exception/HTTP/Unknown.php', 'Requests_Exception_Transport_cURL' => 'wp-includes/Requests/Exception/Transport/cURL.php', 'Requests_Proxy_HTTP' => 'wp-includes/Requests/Proxy/HTTP.php', 'Requests_Response_Headers' => 'wp-includes/Requests/Response/Headers.php', 'Requests_Transport_cURL' => 'wp-includes/Requests/Transport/cURL.php', 'Requests_Transport_fsockopen' => 'wp-includes/Requests/Transport/fsockopen.php', 'Requests_Utility_CaseInsensitiveDictionary' => 'wp-includes/Requests/Utility/CaseInsensitiveDictionary.php', 'Requests_Utility_FilteredIterator' => 'wp-includes/Requests/Utility/FilteredIterator.php', 'Requests_Cookie' => 'wp-includes/Requests/Cookie.php', 'Requests_Exception' => 'wp-includes/Requests/Exception.php', 'Requests_Hooks' => 'wp-includes/Requests/Hooks.php', 'Requests_IDNAEncoder' => 'wp-includes/Requests/IDNAEncoder.php', 'Requests_IPv6' => 'wp-includes/Requests/IPv6.php', 'Requests_IRI' => 'wp-includes/Requests/IRI.php', 'Requests_Response' => 'wp-includes/Requests/Response.php', 'Requests_SSL' => 'wp-includes/Requests/SSL.php', 'Requests_Session' => 'wp-includes/Requests/Session.php', // Directories. 'wp-includes/Requests/Auth/', 'wp-includes/Requests/Cookie/', 'wp-includes/Requests/Exception/HTTP/', 'wp-includes/Requests/Exception/Transport/', 'wp-includes/Requests/Exception/', 'wp-includes/Requests/Proxy/', 'wp-includes/Requests/Response/', 'wp-includes/Requests/Transport/', 'wp-includes/Requests/Utility/', ); /** * Stores new files in wp-content to copy * * The contents of this array indicate any new bundled plugins/themes which * should be installed with the WordPress Upgrade. These items will not be * re-installed in future upgrades, this behavior is controlled by the * introduced version present here being older than the current installed version. * * The content of this array should follow the following format: * Filename (relative to wp-content) => Introduced version * Directories should be noted by suffixing it with a trailing slash (/) * * @since 3.2.0 * @since 4.7.0 New themes were not automatically installed for 4.4-4.6 on * upgrade. New themes are now installed again. To disable new * themes from being installed on upgrade, explicitly define * CORE_UPGRADE_SKIP_NEW_BUNDLED as true. * @global array $_new_bundled_files * @var array * @name $_new_bundled_files */ global $_new_bundled_files; $_new_bundled_files = array( 'plugins/akismet/' => '2.0', 'themes/twentyten/' => '3.0', 'themes/twentyeleven/' => '3.2', 'themes/twentytwelve/' => '3.5', 'themes/twentythirteen/' => '3.6', 'themes/twentyfourteen/' => '3.8', 'themes/twentyfifteen/' => '4.1', 'themes/twentysixteen/' => '4.4', 'themes/twentyseventeen/' => '4.7', 'themes/twentynineteen/' => '5.0', 'themes/twentytwenty/' => '5.3', 'themes/twentytwentyone/' => '5.6', 'themes/twentytwentytwo/' => '5.9', 'themes/twentytwentythree/' => '6.1', 'themes/twentytwentyfour/' => '6.4', 'themes/twentytwentyfive/' => '6.7', ); /** * Upgrades the core of WordPress. * * This will create a .maintenance file at the base of the WordPress directory * to ensure that people can not access the website, when the files are being * copied to their locations. * * The files in the `$_old_files` list will be removed and the new files * copied from the zip file after the database is upgraded. * * The files in the `$_new_bundled_files` list will be added to the installation * if the version is greater than or equal to the old version being upgraded. * * The steps for the upgrader for after the new release is downloaded and * unzipped is: * 1. Test unzipped location for select files to ensure that unzipped worked. * 2. Create the .maintenance file in current WordPress base. * 3. Copy new WordPress directory over old WordPress files. * 4. Upgrade WordPress to new version. * 4.1. Copy all files/folders other than wp-content * 4.2. Copy any language files to WP_LANG_DIR (which may differ from WP_CONTENT_DIR * 4.3. Copy any new bundled themes/plugins to their respective locations * 5. Delete new WordPress directory path. * 6. Delete .maintenance file. * 7. Remove old files. * 8. Delete 'update_core' option. * * There are several areas of failure. For instance if PHP times out before step * 6, then you will not be able to access any portion of your site. Also, since * the upgrade will not continue where it left off, you will not be able to * automatically remove old files and remove the 'update_core' option. This * isn't that bad. * * If the copy of the new WordPress over the old fails, then the worse is that * the new WordPress directory will remain. * * If it is assumed that every file will be copied over, including plugins and * themes, then if you edit the default theme, you should rename it, so that * your changes remain. * * @since 2.7.0 * * @global WP_Filesystem_Base $wp_filesystem WordPress filesystem subclass. * @global array $_old_files * @global array $_old_requests_files * @global array $_new_bundled_files * @global wpdb $wpdb WordPress database abstraction object. * @global string $wp_version * @global string $required_php_version * @global string $required_mysql_version * * @param string $from New release unzipped path. * @param string $to Path to old WordPress installation. * @return string|WP_Error New WordPress version on success, WP_Error on failure. */ function update_core( $from, $to ) { global $wp_filesystem, $_old_files, $_old_requests_files, $_new_bundled_files, $wpdb; if ( function_exists( 'set_time_limit' ) ) { // Gives core update script time an additional 300 seconds(5 minutes) to finish updating large files or run on slower servers. set_time_limit( 300 ); } /* * Merge the old Requests files and directories into the `$_old_files`. * Then preload these Requests files first, before the files are deleted * and replaced to ensure the code is in memory if needed. */ $_old_files = array_merge( $_old_files, array_values( $_old_requests_files ) ); _preload_old_requests_classes_and_interfaces( $to ); /** * Filters feedback messages displayed during the core update process. * * The filter is first evaluated after the zip file for the latest version * has been downloaded and unzipped. It is evaluated five more times during * the process: * * 1. Before WordPress begins the core upgrade process. * 2. Before Maintenance Mode is enabled. * 3. Before WordPress begins copying over the necessary files. * 4. Before Maintenance Mode is disabled. * 5. Before the database is upgraded. * * @since 2.5.0 * * @param string $feedback The core update feedback messages. */ apply_filters( 'update_feedback', __( 'Verifying the unpacked files…' ) ); // Confidence check the unzipped distribution. $distro = ''; $roots = array( '/wordpress/', '/wordpress-mu/' ); foreach ( $roots as $root ) { if ( $wp_filesystem->exists( $from . $root . 'readme.html' ) && $wp_filesystem->exists( $from . $root . 'wp-includes/version.php' ) ) { $distro = $root; break; } } if ( ! $distro ) { $wp_filesystem->delete( $from, true ); return new WP_Error( 'insane_distro', __( 'The update could not be unpacked' ) ); } /* * Import $wp_version, $required_php_version, and $required_mysql_version from the new version. * DO NOT globalize any variables imported from `version-current.php` in this function. * * BC Note: $wp_filesystem->wp_content_dir() returned unslashed pre-2.8. */ $versions_file = trailingslashit( $wp_filesystem->wp_content_dir() ) . 'upgrade/version-current.php'; if ( ! $wp_filesystem->copy( $from . $distro . 'wp-includes/version.php', $versions_file ) ) { $wp_filesystem->delete( $from, true ); return new WP_Error( 'copy_failed_for_version_file', __( 'The update cannot be installed because some files could not be copied. This is usually due to inconsistent file permissions.' ), 'wp-includes/version.php' ); } $wp_filesystem->chmod( $versions_file, FS_CHMOD_FILE ); /* * `wp_opcache_invalidate()` only exists in WordPress 5.5 or later, * so don't run it when upgrading from older versions. */ if ( function_exists( 'wp_opcache_invalidate' ) ) { wp_opcache_invalidate( $versions_file ); } require WP_CONTENT_DIR . '/upgrade/version-current.php'; $wp_filesystem->delete( $versions_file ); $php_version = PHP_VERSION; $mysql_version = $wpdb->db_version(); $old_wp_version = $GLOBALS['wp_version']; // The version of WordPress we're updating from. /* * Note: str_contains() is not used here, as this file is included * when updating from older WordPress versions, in which case * the polyfills from wp-includes/compat.php may not be available. */ $development_build = ( false !== strpos( $old_wp_version . $wp_version, '-' ) ); // A dash in the version indicates a development release. $php_compat = version_compare( $php_version, $required_php_version, '>=' ); if ( file_exists( WP_CONTENT_DIR . '/db.php' ) && empty( $wpdb->is_mysql ) ) { $mysql_compat = true; } else { $mysql_compat = version_compare( $mysql_version, $required_mysql_version, '>=' ); } if ( ! $mysql_compat || ! $php_compat ) { $wp_filesystem->delete( $from, true ); } $php_update_message = ''; if ( function_exists( 'wp_get_update_php_url' ) ) { $php_update_message = '

' . sprintf( /* translators: %s: URL to Update PHP page. */ __( 'Learn more about updating PHP.' ), esc_url( wp_get_update_php_url() ) ); if ( function_exists( 'wp_get_update_php_annotation' ) ) { $annotation = wp_get_update_php_annotation(); if ( $annotation ) { $php_update_message .= '

' . $annotation . ''; } } } if ( ! $mysql_compat && ! $php_compat ) { return new WP_Error( 'php_mysql_not_compatible', sprintf( /* translators: 1: WordPress version number, 2: Minimum required PHP version number, 3: Minimum required MySQL version number, 4: Current PHP version number, 5: Current MySQL version number. */ __( 'The update cannot be installed because WordPress %1$s requires PHP version %2$s or higher and MySQL version %3$s or higher. You are running PHP version %4$s and MySQL version %5$s.' ), $wp_version, $required_php_version, $required_mysql_version, $php_version, $mysql_version ) . $php_update_message ); } elseif ( ! $php_compat ) { return new WP_Error( 'php_not_compatible', sprintf( /* translators: 1: WordPress version number, 2: Minimum required PHP version number, 3: Current PHP version number. */ __( 'The update cannot be installed because WordPress %1$s requires PHP version %2$s or higher. You are running version %3$s.' ), $wp_version, $required_php_version, $php_version ) . $php_update_message ); } elseif ( ! $mysql_compat ) { return new WP_Error( 'mysql_not_compatible', sprintf( /* translators: 1: WordPress version number, 2: Minimum required MySQL version number, 3: Current MySQL version number. */ __( 'The update cannot be installed because WordPress %1$s requires MySQL version %2$s or higher. You are running version %3$s.' ), $wp_version, $required_mysql_version, $mysql_version ) ); } // Add a warning when the JSON PHP extension is missing. if ( ! extension_loaded( 'json' ) ) { return new WP_Error( 'php_not_compatible_json', sprintf( /* translators: 1: WordPress version number, 2: The PHP extension name needed. */ __( 'The update cannot be installed because WordPress %1$s requires the %2$s PHP extension.' ), $wp_version, 'JSON' ) ); } /** This filter is documented in wp-admin/includes/update-core.php */ apply_filters( 'update_feedback', __( 'Preparing to install the latest version…' ) ); /* * Don't copy wp-content, we'll deal with that below. * We also copy version.php last so failed updates report their old version. */ $skip = array( 'wp-content', 'wp-includes/version.php' ); $check_is_writable = array(); // Check to see which files don't really need updating - only available for 3.7 and higher. if ( function_exists( 'get_core_checksums' ) ) { // Find the local version of the working directory. $working_dir_local = WP_CONTENT_DIR . '/upgrade/' . basename( $from ) . $distro; $checksums = get_core_checksums( $wp_version, isset( $wp_local_package ) ? $wp_local_package : 'en_US' ); if ( is_array( $checksums ) && isset( $checksums[ $wp_version ] ) ) { $checksums = $checksums[ $wp_version ]; // Compat code for 3.7-beta2. } if ( is_array( $checksums ) ) { foreach ( $checksums as $file => $checksum ) { /* * Note: str_starts_with() is not used here, as this file is included * when updating from older WordPress versions, in which case * the polyfills from wp-includes/compat.php may not be available. */ if ( 'wp-content' === substr( $file, 0, 10 ) ) { continue; } if ( ! file_exists( ABSPATH . $file ) ) { continue; } if ( ! file_exists( $working_dir_local . $file ) ) { continue; } if ( '.' === dirname( $file ) && in_array( pathinfo( $file, PATHINFO_EXTENSION ), array( 'html', 'txt' ), true ) ) { continue; } if ( md5_file( ABSPATH . $file ) === $checksum ) { $skip[] = $file; } else { $check_is_writable[ $file ] = ABSPATH . $file; } } } } // If we're using the direct method, we can predict write failures that are due to permissions. if ( $check_is_writable && 'direct' === $wp_filesystem->method ) { $files_writable = array_filter( $check_is_writable, array( $wp_filesystem, 'is_writable' ) ); if ( $files_writable !== $check_is_writable ) { $files_not_writable = array_diff_key( $check_is_writable, $files_writable ); foreach ( $files_not_writable as $relative_file_not_writable => $file_not_writable ) { // If the writable check failed, chmod file to 0644 and try again, same as copy_dir(). $wp_filesystem->chmod( $file_not_writable, FS_CHMOD_FILE ); if ( $wp_filesystem->is_writable( $file_not_writable ) ) { unset( $files_not_writable[ $relative_file_not_writable ] ); } } // Store package-relative paths (the key) of non-writable files in the WP_Error object. $error_data = version_compare( $old_wp_version, '3.7-beta2', '>' ) ? array_keys( $files_not_writable ) : ''; if ( $files_not_writable ) { return new WP_Error( 'files_not_writable', __( 'The update cannot be installed because your site is unable to copy some files. This is usually due to inconsistent file permissions.' ), implode( ', ', $error_data ) ); } } } /** This filter is documented in wp-admin/includes/update-core.php */ apply_filters( 'update_feedback', __( 'Enabling Maintenance mode…' ) ); // Create maintenance file to signal that we are upgrading. $maintenance_string = ''; $maintenance_file = $to . '.maintenance'; $wp_filesystem->delete( $maintenance_file ); $wp_filesystem->put_contents( $maintenance_file, $maintenance_string, FS_CHMOD_FILE ); /** This filter is documented in wp-admin/includes/update-core.php */ apply_filters( 'update_feedback', __( 'Copying the required files…' ) ); // Copy new versions of WP files into place. $result = copy_dir( $from . $distro, $to, $skip ); if ( is_wp_error( $result ) ) { $result = new WP_Error( $result->get_error_code(), $result->get_error_message(), substr( $result->get_error_data(), strlen( $to ) ) ); } // Since we know the core files have copied over, we can now copy the version file. if ( ! is_wp_error( $result ) ) { if ( ! $wp_filesystem->copy( $from . $distro . 'wp-includes/version.php', $to . 'wp-includes/version.php', true /* overwrite */ ) ) { $wp_filesystem->delete( $from, true ); $result = new WP_Error( 'copy_failed_for_version_file', __( 'The update cannot be installed because your site is unable to copy some files. This is usually due to inconsistent file permissions.' ), 'wp-includes/version.php' ); } $wp_filesystem->chmod( $to . 'wp-includes/version.php', FS_CHMOD_FILE ); /* * `wp_opcache_invalidate()` only exists in WordPress 5.5 or later, * so don't run it when upgrading from older versions. */ if ( function_exists( 'wp_opcache_invalidate' ) ) { wp_opcache_invalidate( $to . 'wp-includes/version.php' ); } } // Check to make sure everything copied correctly, ignoring the contents of wp-content. $skip = array( 'wp-content' ); $failed = array(); if ( isset( $checksums ) && is_array( $checksums ) ) { foreach ( $checksums as $file => $checksum ) { /* * Note: str_starts_with() is not used here, as this file is included * when updating from older WordPress versions, in which case * the polyfills from wp-includes/compat.php may not be available. */ if ( 'wp-content' === substr( $file, 0, 10 ) ) { continue; } if ( ! file_exists( $working_dir_local . $file ) ) { continue; } if ( '.' === dirname( $file ) && in_array( pathinfo( $file, PATHINFO_EXTENSION ), array( 'html', 'txt' ), true ) ) { $skip[] = $file; continue; } if ( file_exists( ABSPATH . $file ) && md5_file( ABSPATH . $file ) === $checksum ) { $skip[] = $file; } else { $failed[] = $file; } } } // Some files didn't copy properly. if ( ! empty( $failed ) ) { $total_size = 0; foreach ( $failed as $file ) { if ( file_exists( $working_dir_local . $file ) ) { $total_size += filesize( $working_dir_local . $file ); } } /* * If we don't have enough free space, it isn't worth trying again. * Unlikely to be hit due to the check in unzip_file(). */ $available_space = function_exists( 'disk_free_space' ) ? @disk_free_space( ABSPATH ) : false; if ( $available_space && $total_size >= $available_space ) { $result = new WP_Error( 'disk_full', __( 'There is not enough free disk space to complete the update.' ) ); } else { $result = copy_dir( $from . $distro, $to, $skip ); if ( is_wp_error( $result ) ) { $result = new WP_Error( $result->get_error_code() . '_retry', $result->get_error_message(), substr( $result->get_error_data(), strlen( $to ) ) ); } } } /* * Custom content directory needs updating now. * Copy languages. */ if ( ! is_wp_error( $result ) && $wp_filesystem->is_dir( $from . $distro . 'wp-content/languages' ) ) { if ( WP_LANG_DIR !== ABSPATH . WPINC . '/languages' || @is_dir( WP_LANG_DIR ) ) { $lang_dir = WP_LANG_DIR; } else { $lang_dir = WP_CONTENT_DIR . '/languages'; } /* * Note: str_starts_with() is not used here, as this file is included * when updating from older WordPress versions, in which case * the polyfills from wp-includes/compat.php may not be available. */ // Check if the language directory exists first. if ( ! @is_dir( $lang_dir ) && 0 === strpos( $lang_dir, ABSPATH ) ) { // If it's within the ABSPATH we can handle it here, otherwise they're out of luck. $wp_filesystem->mkdir( $to . str_replace( ABSPATH, '', $lang_dir ), FS_CHMOD_DIR ); clearstatcache(); // For FTP, need to clear the stat cache. } if ( @is_dir( $lang_dir ) ) { $wp_lang_dir = $wp_filesystem->find_folder( $lang_dir ); if ( $wp_lang_dir ) { $result = copy_dir( $from . $distro . 'wp-content/languages/', $wp_lang_dir ); if ( is_wp_error( $result ) ) { $result = new WP_Error( $result->get_error_code() . '_languages', $result->get_error_message(), substr( $result->get_error_data(), strlen( $wp_lang_dir ) ) ); } } } } /** This filter is documented in wp-admin/includes/update-core.php */ apply_filters( 'update_feedback', __( 'Disabling Maintenance mode…' ) ); // Remove maintenance file, we're done with potential site-breaking changes. $wp_filesystem->delete( $maintenance_file ); /* * 3.5 -> 3.5+ - an empty twentytwelve directory was created upon upgrade to 3.5 for some users, * preventing installation of Twenty Twelve. */ if ( '3.5' === $old_wp_version ) { if ( is_dir( WP_CONTENT_DIR . '/themes/twentytwelve' ) && ! file_exists( WP_CONTENT_DIR . '/themes/twentytwelve/style.css' ) ) { $wp_filesystem->delete( $wp_filesystem->wp_themes_dir() . 'twentytwelve/' ); } } /* * Copy new bundled plugins & themes. * This gives us the ability to install new plugins & themes bundled with * future versions of WordPress whilst avoiding the re-install upon upgrade issue. * $development_build controls us overwriting bundled themes and plugins when a non-stable release is being updated. */ if ( ! is_wp_error( $result ) && ( ! defined( 'CORE_UPGRADE_SKIP_NEW_BUNDLED' ) || ! CORE_UPGRADE_SKIP_NEW_BUNDLED ) ) { foreach ( (array) $_new_bundled_files as $file => $introduced_version ) { // If a $development_build or if $introduced version is greater than what the site was previously running. if ( $development_build || version_compare( $introduced_version, $old_wp_version, '>' ) ) { $directory = ( '/' === $file[ strlen( $file ) - 1 ] ); list( $type, $filename ) = explode( '/', $file, 2 ); // Check to see if the bundled items exist before attempting to copy them. if ( ! $wp_filesystem->exists( $from . $distro . 'wp-content/' . $file ) ) { continue; } if ( 'plugins' === $type ) { $dest = $wp_filesystem->wp_plugins_dir(); } elseif ( 'themes' === $type ) { // Back-compat, ::wp_themes_dir() did not return trailingslash'd pre-3.2. $dest = trailingslashit( $wp_filesystem->wp_themes_dir() ); } else { continue; } if ( ! $directory ) { if ( ! $development_build && $wp_filesystem->exists( $dest . $filename ) ) { continue; } if ( ! $wp_filesystem->copy( $from . $distro . 'wp-content/' . $file, $dest . $filename, FS_CHMOD_FILE ) ) { $result = new WP_Error( "copy_failed_for_new_bundled_$type", __( 'Could not copy file.' ), $dest . $filename ); } } else { if ( ! $development_build && $wp_filesystem->is_dir( $dest . $filename ) ) { continue; } $wp_filesystem->mkdir( $dest . $filename, FS_CHMOD_DIR ); $_result = copy_dir( $from . $distro . 'wp-content/' . $file, $dest . $filename ); /* * If an error occurs partway through this final step, * keep the error flowing through, but keep the process going. */ if ( is_wp_error( $_result ) ) { if ( ! is_wp_error( $result ) ) { $result = new WP_Error(); } $result->add( $_result->get_error_code() . "_$type", $_result->get_error_message(), substr( $_result->get_error_data(), strlen( $dest ) ) ); } } } } // End foreach. } // Handle $result error from the above blocks. if ( is_wp_error( $result ) ) { $wp_filesystem->delete( $from, true ); return $result; } // Remove old files. foreach ( $_old_files as $old_file ) { $old_file = $to . $old_file; if ( ! $wp_filesystem->exists( $old_file ) ) { continue; } // If the file isn't deleted, try writing an empty string to the file instead. if ( ! $wp_filesystem->delete( $old_file, true ) && $wp_filesystem->is_file( $old_file ) ) { $wp_filesystem->put_contents( $old_file, '' ); } } // Remove any Genericons example.html's from the filesystem. _upgrade_422_remove_genericons(); // Deactivate the REST API plugin if its version is 2.0 Beta 4 or lower. _upgrade_440_force_deactivate_incompatible_plugins(); // Deactivate incompatible plugins. _upgrade_core_deactivate_incompatible_plugins(); // Upgrade DB with separate request. /** This filter is documented in wp-admin/includes/update-core.php */ apply_filters( 'update_feedback', __( 'Upgrading database…' ) ); $db_upgrade_url = admin_url( 'upgrade.php?step=upgrade_db' ); wp_remote_post( $db_upgrade_url, array( 'timeout' => 60 ) ); // Clear the cache to prevent an update_option() from saving a stale db_version to the cache. wp_cache_flush(); // Not all cache back ends listen to 'flush'. wp_cache_delete( 'alloptions', 'options' ); // Remove working directory. $wp_filesystem->delete( $from, true ); // Force refresh of update information. if ( function_exists( 'delete_site_transient' ) ) { delete_site_transient( 'update_core' ); } else { delete_option( 'update_core' ); } /** * Fires after WordPress core has been successfully updated. * * @since 3.3.0 * * @param string $wp_version The current WordPress version. */ do_action( '_core_updated_successfully', $wp_version ); // Clear the option that blocks auto-updates after failures, now that we've been successful. if ( function_exists( 'delete_site_option' ) ) { delete_site_option( 'auto_core_update_failed' ); } return $wp_version; } /** * Preloads old Requests classes and interfaces. * * This function preloads the old Requests code into memory before the * upgrade process deletes the files. Why? Requests code is loaded into * memory via an autoloader, meaning when a class or interface is needed * If a request is in process, Requests could attempt to access code. If * the file is not there, a fatal error could occur. If the file was * replaced, the new code is not compatible with the old, resulting in * a fatal error. Preloading ensures the code is in memory before the * code is updated. * * @since 6.2.0 * * @global array $_old_requests_files Requests files to be preloaded. * @global WP_Filesystem_Base $wp_filesystem WordPress filesystem subclass. * @global string $wp_version The WordPress version string. * * @param string $to Path to old WordPress installation. */ function _preload_old_requests_classes_and_interfaces( $to ) { global $_old_requests_files, $wp_filesystem, $wp_version; /* * Requests was introduced in WordPress 4.6. * * Skip preloading if the website was previously using * an earlier version of WordPress. */ if ( version_compare( $wp_version, '4.6', '<' ) ) { return; } if ( ! defined( 'REQUESTS_SILENCE_PSR0_DEPRECATIONS' ) ) { define( 'REQUESTS_SILENCE_PSR0_DEPRECATIONS', true ); } foreach ( $_old_requests_files as $name => $file ) { // Skip files that aren't interfaces or classes. if ( is_int( $name ) ) { continue; } // Skip if it's already loaded. if ( class_exists( $name ) || interface_exists( $name ) ) { continue; } // Skip if the file is missing. if ( ! $wp_filesystem->is_file( $to . $file ) ) { continue; } require_once $to . $file; } } /** * Redirect to the About WordPress page after a successful upgrade. * * This function is only needed when the existing installation is older than 3.4.0. * * @since 3.3.0 * * @global string $wp_version The WordPress version string. * @global string $pagenow The filename of the current screen. * @global string $action * * @param string $new_version */ function _redirect_to_about_wordpress( $new_version ) { global $wp_version, $pagenow, $action; if ( version_compare( $wp_version, '3.4-RC1', '>=' ) ) { return; } // Ensure we only run this on the update-core.php page. The Core_Upgrader may be used in other contexts. if ( 'update-core.php' !== $pagenow ) { return; } if ( 'do-core-upgrade' !== $action && 'do-core-reinstall' !== $action ) { return; } // Load the updated default text localization domain for new strings. load_default_textdomain(); // See do_core_upgrade(). show_message( __( 'WordPress updated successfully.' ) ); // self_admin_url() won't exist when upgrading from <= 3.0, so relative URLs are intentional. show_message( '' . sprintf( /* translators: 1: WordPress version, 2: URL to About screen. */ __( 'Welcome to WordPress %1$s. You will be redirected to the About WordPress screen. If not, click here.' ), $new_version, 'about.php?updated' ) . '' ); show_message( '' . sprintf( /* translators: 1: WordPress version, 2: URL to About screen. */ __( 'Welcome to WordPress %1$s. Learn more.' ), $new_version, 'about.php?updated' ) . '' ); echo ''; ?> find_folder( trailingslashit( dirname( $file ) ) ); if ( empty( $gen_dir ) ) { continue; } // The path when the file is accessed via WP_Filesystem may differ in the case of FTP. $remote_file = $gen_dir . basename( $file ); if ( ! $wp_filesystem->exists( $remote_file ) ) { continue; } if ( ! $wp_filesystem->delete( $remote_file, false, 'f' ) ) { $wp_filesystem->put_contents( $remote_file, '' ); } } } /** * Recursively find Genericons example files in a given folder. * * @ignore * @since 4.2.2 * * @param string $directory Directory path. Expects trailingslashed. * @return array */ function _upgrade_422_find_genericons_files_in_folder( $directory ) { $directory = trailingslashit( $directory ); $files = array(); if ( file_exists( "{$directory}example.html" ) /* * Note: str_contains() is not used here, as this file is included * when updating from older WordPress versions, in which case * the polyfills from wp-includes/compat.php may not be available. */ && false !== strpos( file_get_contents( "{$directory}example.html" ), 'Genericons' ) ) { $files[] = "{$directory}example.html"; } $dirs = glob( $directory . '*', GLOB_ONLYDIR ); $dirs = array_filter( $dirs, static function ( $dir ) { /* * Skip any node_modules directories. * * Note: str_contains() is not used here, as this file is included * when updating from older WordPress versions, in which case * the polyfills from wp-includes/compat.php may not be available. */ return false === strpos( $dir, 'node_modules' ); } ); if ( $dirs ) { foreach ( $dirs as $dir ) { $files = array_merge( $files, _upgrade_422_find_genericons_files_in_folder( $dir ) ); } } return $files; } /** * @ignore * @since 4.4.0 */ function _upgrade_440_force_deactivate_incompatible_plugins() { if ( defined( 'REST_API_VERSION' ) && version_compare( REST_API_VERSION, '2.0-beta4', '<=' ) ) { deactivate_plugins( array( 'rest-api/plugin.php' ), true ); } } /** * @access private * @ignore * @since 5.8.0 * @since 5.9.0 The minimum compatible version of Gutenberg is 11.9. * @since 6.1.1 The minimum compatible version of Gutenberg is 14.1. * @since 6.4.0 The minimum compatible version of Gutenberg is 16.5. * @since 6.5.0 The minimum compatible version of Gutenberg is 17.6. */ function _upgrade_core_deactivate_incompatible_plugins() { if ( defined( 'GUTENBERG_VERSION' ) && version_compare( GUTENBERG_VERSION, '17.6', '<' ) ) { $deactivated_gutenberg['gutenberg'] = array( 'plugin_name' => 'Gutenberg', 'version_deactivated' => GUTENBERG_VERSION, 'version_compatible' => '17.6', ); if ( is_plugin_active_for_network( 'gutenberg/gutenberg.php' ) ) { $deactivated_plugins = get_site_option( 'wp_force_deactivated_plugins', array() ); $deactivated_plugins = array_merge( $deactivated_plugins, $deactivated_gutenberg ); update_site_option( 'wp_force_deactivated_plugins', $deactivated_plugins ); } else { $deactivated_plugins = get_option( 'wp_force_deactivated_plugins', array() ); $deactivated_plugins = array_merge( $deactivated_plugins, $deactivated_gutenberg ); update_option( 'wp_force_deactivated_plugins', $deactivated_plugins, false ); } deactivate_plugins( array( 'gutenberg/gutenberg.php' ), true ); } } edit-tag-messages.php000064400000002706147206365750010604 0ustar00 '', 1 => __( 'Item added.' ), 2 => __( 'Item deleted.' ), 3 => __( 'Item updated.' ), 4 => __( 'Item not added.' ), 5 => __( 'Item not updated.' ), 6 => __( 'Items deleted.' ), ); $messages['category'] = array( 0 => '', 1 => __( 'Category added.' ), 2 => __( 'Category deleted.' ), 3 => __( 'Category updated.' ), 4 => __( 'Category not added.' ), 5 => __( 'Category not updated.' ), 6 => __( 'Categories deleted.' ), ); $messages['post_tag'] = array( 0 => '', 1 => __( 'Tag added.' ), 2 => __( 'Tag deleted.' ), 3 => __( 'Tag updated.' ), 4 => __( 'Tag not added.' ), 5 => __( 'Tag not updated.' ), 6 => __( 'Tags deleted.' ), ); /** * Filters the messages displayed when a tag is updated. * * @since 3.7.0 * * @param array[] $messages Array of arrays of messages to be displayed, keyed by taxonomy name. */ $messages = apply_filters( 'term_updated_messages', $messages ); $message = false; if ( isset( $_REQUEST['message'] ) && (int) $_REQUEST['message'] ) { $msg = (int) $_REQUEST['message']; if ( isset( $messages[ $taxonomy ][ $msg ] ) ) { $message = $messages[ $taxonomy ][ $msg ]; } elseif ( ! isset( $messages[ $taxonomy ] ) && isset( $messages['_item'][ $msg ] ) ) { $message = $messages['_item'][ $msg ]; } } user.php000064400000055732147206365750006266 0ustar00ID = $user_id; $userdata = get_userdata( $user_id ); $user->user_login = wp_slash( $userdata->user_login ); } else { $update = false; } if ( ! $update && isset( $_POST['user_login'] ) ) { $user->user_login = sanitize_user( wp_unslash( $_POST['user_login'] ), true ); } $pass1 = ''; $pass2 = ''; if ( isset( $_POST['pass1'] ) ) { $pass1 = trim( $_POST['pass1'] ); } if ( isset( $_POST['pass2'] ) ) { $pass2 = trim( $_POST['pass2'] ); } if ( isset( $_POST['role'] ) && current_user_can( 'promote_users' ) && ( ! $user_id || current_user_can( 'promote_user', $user_id ) ) ) { $new_role = sanitize_text_field( $_POST['role'] ); // If the new role isn't editable by the logged-in user die with error. $editable_roles = get_editable_roles(); if ( ! empty( $new_role ) && empty( $editable_roles[ $new_role ] ) ) { wp_die( __( 'Sorry, you are not allowed to give users that role.' ), 403 ); } $potential_role = isset( $wp_roles->role_objects[ $new_role ] ) ? $wp_roles->role_objects[ $new_role ] : false; /* * Don't let anyone with 'promote_users' edit their own role to something without it. * Multisite super admins can freely edit their roles, they possess all caps. */ if ( ( is_multisite() && current_user_can( 'manage_network_users' ) ) || get_current_user_id() !== $user_id || ( $potential_role && $potential_role->has_cap( 'promote_users' ) ) ) { $user->role = $new_role; } } if ( isset( $_POST['email'] ) ) { $user->user_email = sanitize_text_field( wp_unslash( $_POST['email'] ) ); } if ( isset( $_POST['url'] ) ) { if ( empty( $_POST['url'] ) || 'http://' === $_POST['url'] ) { $user->user_url = ''; } else { $user->user_url = sanitize_url( $_POST['url'] ); $protocols = implode( '|', array_map( 'preg_quote', wp_allowed_protocols() ) ); $user->user_url = preg_match( '/^(' . $protocols . '):/is', $user->user_url ) ? $user->user_url : 'http://' . $user->user_url; } } if ( isset( $_POST['first_name'] ) ) { $user->first_name = sanitize_text_field( $_POST['first_name'] ); } if ( isset( $_POST['last_name'] ) ) { $user->last_name = sanitize_text_field( $_POST['last_name'] ); } if ( isset( $_POST['nickname'] ) ) { $user->nickname = sanitize_text_field( $_POST['nickname'] ); } if ( isset( $_POST['display_name'] ) ) { $user->display_name = sanitize_text_field( $_POST['display_name'] ); } if ( isset( $_POST['description'] ) ) { $user->description = trim( $_POST['description'] ); } foreach ( wp_get_user_contact_methods( $user ) as $method => $name ) { if ( isset( $_POST[ $method ] ) ) { $user->$method = sanitize_text_field( $_POST[ $method ] ); } } if ( isset( $_POST['locale'] ) ) { $locale = sanitize_text_field( $_POST['locale'] ); if ( 'site-default' === $locale ) { $locale = ''; } elseif ( '' === $locale ) { $locale = 'en_US'; } elseif ( ! in_array( $locale, get_available_languages(), true ) ) { if ( current_user_can( 'install_languages' ) && wp_can_install_language_pack() ) { if ( ! wp_download_language_pack( $locale ) ) { $locale = ''; } } else { $locale = ''; } } $user->locale = $locale; } if ( $update ) { $user->rich_editing = isset( $_POST['rich_editing'] ) && 'false' === $_POST['rich_editing'] ? 'false' : 'true'; $user->syntax_highlighting = isset( $_POST['syntax_highlighting'] ) && 'false' === $_POST['syntax_highlighting'] ? 'false' : 'true'; $user->admin_color = isset( $_POST['admin_color'] ) ? sanitize_text_field( $_POST['admin_color'] ) : 'fresh'; $user->show_admin_bar_front = isset( $_POST['admin_bar_front'] ) ? 'true' : 'false'; } $user->comment_shortcuts = isset( $_POST['comment_shortcuts'] ) && 'true' === $_POST['comment_shortcuts'] ? 'true' : ''; $user->use_ssl = 0; if ( ! empty( $_POST['use_ssl'] ) ) { $user->use_ssl = 1; } $errors = new WP_Error(); /* checking that username has been typed */ if ( '' === $user->user_login ) { $errors->add( 'user_login', __( 'Error: Please enter a username.' ) ); } /* checking that nickname has been typed */ if ( $update && empty( $user->nickname ) ) { $errors->add( 'nickname', __( 'Error: Please enter a nickname.' ) ); } /** * Fires before the password and confirm password fields are checked for congruity. * * @since 1.5.1 * * @param string $user_login The username. * @param string $pass1 The password (passed by reference). * @param string $pass2 The confirmed password (passed by reference). */ do_action_ref_array( 'check_passwords', array( $user->user_login, &$pass1, &$pass2 ) ); // Check for blank password when adding a user. if ( ! $update && empty( $pass1 ) ) { $errors->add( 'pass', __( 'Error: Please enter a password.' ), array( 'form-field' => 'pass1' ) ); } // Check for "\" in password. if ( str_contains( wp_unslash( $pass1 ), '\\' ) ) { $errors->add( 'pass', __( 'Error: Passwords may not contain the character "\\".' ), array( 'form-field' => 'pass1' ) ); } // Checking the password has been typed twice the same. if ( ( $update || ! empty( $pass1 ) ) && $pass1 !== $pass2 ) { $errors->add( 'pass', __( 'Error: Passwords do not match. Please enter the same password in both password fields.' ), array( 'form-field' => 'pass1' ) ); } if ( ! empty( $pass1 ) ) { $user->user_pass = $pass1; } if ( ! $update && isset( $_POST['user_login'] ) && ! validate_username( $_POST['user_login'] ) ) { $errors->add( 'user_login', __( 'Error: This username is invalid because it uses illegal characters. Please enter a valid username.' ) ); } if ( ! $update && username_exists( $user->user_login ) ) { $errors->add( 'user_login', __( 'Error: This username is already registered. Please choose another one.' ) ); } /** This filter is documented in wp-includes/user.php */ $illegal_logins = (array) apply_filters( 'illegal_user_logins', array() ); if ( in_array( strtolower( $user->user_login ), array_map( 'strtolower', $illegal_logins ), true ) ) { $errors->add( 'invalid_username', __( 'Error: Sorry, that username is not allowed.' ) ); } // Checking email address. if ( empty( $user->user_email ) ) { $errors->add( 'empty_email', __( 'Error: Please enter an email address.' ), array( 'form-field' => 'email' ) ); } elseif ( ! is_email( $user->user_email ) ) { $errors->add( 'invalid_email', __( 'Error: The email address is not correct.' ), array( 'form-field' => 'email' ) ); } else { $owner_id = email_exists( $user->user_email ); if ( $owner_id && ( ! $update || ( $owner_id !== $user->ID ) ) ) { $errors->add( 'email_exists', __( 'Error: This email is already registered. Please choose another one.' ), array( 'form-field' => 'email' ) ); } } /** * Fires before user profile update errors are returned. * * @since 2.8.0 * * @param WP_Error $errors WP_Error object (passed by reference). * @param bool $update Whether this is a user update. * @param stdClass $user User object (passed by reference). */ do_action_ref_array( 'user_profile_update_errors', array( &$errors, $update, &$user ) ); if ( $errors->has_errors() ) { return $errors; } if ( $update ) { $user_id = wp_update_user( $user ); } else { $user_id = wp_insert_user( $user ); $notify = isset( $_POST['send_user_notification'] ) ? 'both' : 'admin'; /** * Fires after a new user has been created. * * @since 4.4.0 * * @param int|WP_Error $user_id ID of the newly created user or WP_Error on failure. * @param string $notify Type of notification that should happen. See * wp_send_new_user_notifications() for more information. */ do_action( 'edit_user_created_user', $user_id, $notify ); } return $user_id; } /** * Fetch a filtered list of user roles that the current user is * allowed to edit. * * Simple function whose main purpose is to allow filtering of the * list of roles in the $wp_roles object so that plugins can remove * inappropriate ones depending on the situation or user making edits. * Specifically because without filtering anyone with the edit_users * capability can edit others to be administrators, even if they are * only editors or authors. This filter allows admins to delegate * user management. * * @since 2.8.0 * * @return array[] Array of arrays containing role information. */ function get_editable_roles() { $all_roles = wp_roles()->roles; /** * Filters the list of editable roles. * * @since 2.8.0 * * @param array[] $all_roles Array of arrays containing role information. */ $editable_roles = apply_filters( 'editable_roles', $all_roles ); return $editable_roles; } /** * Retrieve user data and filter it. * * @since 2.0.5 * * @param int $user_id User ID. * @return WP_User|false WP_User object on success, false on failure. */ function get_user_to_edit( $user_id ) { $user = get_userdata( $user_id ); if ( $user ) { $user->filter = 'edit'; } return $user; } /** * Retrieve the user's drafts. * * @since 2.0.0 * * @global wpdb $wpdb WordPress database abstraction object. * * @param int $user_id User ID. * @return array */ function get_users_drafts( $user_id ) { global $wpdb; $query = $wpdb->prepare( "SELECT ID, post_title FROM $wpdb->posts WHERE post_type = 'post' AND post_status = 'draft' AND post_author = %d ORDER BY post_modified DESC", $user_id ); /** * Filters the user's drafts query string. * * @since 2.0.0 * * @param string $query The user's drafts query string. */ $query = apply_filters( 'get_users_drafts', $query ); return $wpdb->get_results( $query ); } /** * Delete user and optionally reassign posts and links to another user. * * Note that on a Multisite installation the user only gets removed from the site * and does not get deleted from the database. * * If the `$reassign` parameter is not assigned to a user ID, then all posts will * be deleted of that user. The action {@see 'delete_user'} that is passed the user ID * being deleted will be run after the posts are either reassigned or deleted. * The user meta will also be deleted that are for that user ID. * * @since 2.0.0 * * @global wpdb $wpdb WordPress database abstraction object. * * @param int $id User ID. * @param int $reassign Optional. Reassign posts and links to new User ID. * @return bool True when finished. */ function wp_delete_user( $id, $reassign = null ) { global $wpdb; if ( ! is_numeric( $id ) ) { return false; } $id = (int) $id; $user = new WP_User( $id ); if ( ! $user->exists() ) { return false; } // Normalize $reassign to null or a user ID. 'novalue' was an older default. if ( 'novalue' === $reassign ) { $reassign = null; } elseif ( null !== $reassign ) { $reassign = (int) $reassign; } /** * Fires immediately before a user is deleted from the site. * * Note that on a Multisite installation the user only gets removed from the site * and does not get deleted from the database. * * @since 2.0.0 * @since 5.5.0 Added the `$user` parameter. * * @param int $id ID of the user to delete. * @param int|null $reassign ID of the user to reassign posts and links to. * Default null, for no reassignment. * @param WP_User $user WP_User object of the user to delete. */ do_action( 'delete_user', $id, $reassign, $user ); if ( null === $reassign ) { $post_types_to_delete = array(); foreach ( get_post_types( array(), 'objects' ) as $post_type ) { if ( $post_type->delete_with_user ) { $post_types_to_delete[] = $post_type->name; } elseif ( null === $post_type->delete_with_user && post_type_supports( $post_type->name, 'author' ) ) { $post_types_to_delete[] = $post_type->name; } } /** * Filters the list of post types to delete with a user. * * @since 3.4.0 * * @param string[] $post_types_to_delete Array of post types to delete. * @param int $id User ID. */ $post_types_to_delete = apply_filters( 'post_types_to_delete_with_user', $post_types_to_delete, $id ); $post_types_to_delete = implode( "', '", $post_types_to_delete ); $post_ids = $wpdb->get_col( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_author = %d AND post_type IN ('$post_types_to_delete')", $id ) ); if ( $post_ids ) { foreach ( $post_ids as $post_id ) { wp_delete_post( $post_id ); } } // Clean links. $link_ids = $wpdb->get_col( $wpdb->prepare( "SELECT link_id FROM $wpdb->links WHERE link_owner = %d", $id ) ); if ( $link_ids ) { foreach ( $link_ids as $link_id ) { wp_delete_link( $link_id ); } } } else { $post_ids = $wpdb->get_col( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_author = %d", $id ) ); $wpdb->update( $wpdb->posts, array( 'post_author' => $reassign ), array( 'post_author' => $id ) ); if ( ! empty( $post_ids ) ) { foreach ( $post_ids as $post_id ) { clean_post_cache( $post_id ); } } $link_ids = $wpdb->get_col( $wpdb->prepare( "SELECT link_id FROM $wpdb->links WHERE link_owner = %d", $id ) ); $wpdb->update( $wpdb->links, array( 'link_owner' => $reassign ), array( 'link_owner' => $id ) ); if ( ! empty( $link_ids ) ) { foreach ( $link_ids as $link_id ) { clean_bookmark_cache( $link_id ); } } } // FINALLY, delete user. if ( is_multisite() ) { remove_user_from_blog( $id, get_current_blog_id() ); } else { $meta = $wpdb->get_col( $wpdb->prepare( "SELECT umeta_id FROM $wpdb->usermeta WHERE user_id = %d", $id ) ); foreach ( $meta as $mid ) { delete_metadata_by_mid( 'user', $mid ); } $wpdb->delete( $wpdb->users, array( 'ID' => $id ) ); } clean_user_cache( $user ); /** * Fires immediately after a user is deleted from the site. * * Note that on a Multisite installation the user may not have been deleted from * the database depending on whether `wp_delete_user()` or `wpmu_delete_user()` * was called. * * @since 2.9.0 * @since 5.5.0 Added the `$user` parameter. * * @param int $id ID of the deleted user. * @param int|null $reassign ID of the user to reassign posts and links to. * Default null, for no reassignment. * @param WP_User $user WP_User object of the deleted user. */ do_action( 'deleted_user', $id, $reassign, $user ); return true; } /** * Remove all capabilities from user. * * @since 2.1.0 * * @param int $id User ID. */ function wp_revoke_user( $id ) { $id = (int) $id; $user = new WP_User( $id ); $user->remove_all_caps(); } /** * @since 2.8.0 * * @global int $user_ID * * @param false $errors Deprecated. */ function default_password_nag_handler( $errors = false ) { global $user_ID; // Short-circuit it. if ( ! get_user_option( 'default_password_nag' ) ) { return; } // get_user_setting() = JS-saved UI setting. Else no-js-fallback code. if ( 'hide' === get_user_setting( 'default_password_nag' ) || isset( $_GET['default_password_nag'] ) && '0' === $_GET['default_password_nag'] ) { delete_user_setting( 'default_password_nag' ); update_user_meta( $user_ID, 'default_password_nag', false ); } } /** * @since 2.8.0 * * @param int $user_ID * @param WP_User $old_data */ function default_password_nag_edit_user( $user_ID, $old_data ) { // Short-circuit it. if ( ! get_user_option( 'default_password_nag', $user_ID ) ) { return; } $new_data = get_userdata( $user_ID ); // Remove the nag if the password has been changed. if ( $new_data->user_pass !== $old_data->user_pass ) { delete_user_setting( 'default_password_nag' ); update_user_meta( $user_ID, 'default_password_nag', false ); } } /** * @since 2.8.0 * * @global string $pagenow The filename of the current screen. */ function default_password_nag() { global $pagenow; // Short-circuit it. if ( 'profile.php' === $pagenow || ! get_user_option( 'default_password_nag' ) ) { return; } $default_password_nag_message = sprintf( '

%1$s %2$s

', __( 'Notice:' ), __( 'You are using the auto-generated password for your account. Would you like to change it?' ) ); $default_password_nag_message .= sprintf( '

%2$s | ', esc_url( get_edit_profile_url() . '#password' ), __( 'Yes, take me to my profile page' ) ); $default_password_nag_message .= sprintf( '%2$s

', '?default_password_nag=0', __( 'No thanks, do not remind me again' ) ); wp_admin_notice( $default_password_nag_message, array( 'additional_classes' => array( 'error', 'default-password-nag' ), 'paragraph_wrap' => false, ) ); } /** * @since 3.5.0 * @access private */ function delete_users_add_js() { ?> add( $validated_success_url->get_error_code(), $validated_success_url->get_error_message() ); } } if ( isset( $request['reject_url'] ) ) { $validated_reject_url = wp_is_authorize_application_redirect_url_valid( $request['reject_url'] ); if ( is_wp_error( $validated_reject_url ) ) { $error->add( $validated_reject_url->get_error_code(), $validated_reject_url->get_error_message() ); } } if ( ! empty( $request['app_id'] ) && ! wp_is_uuid( $request['app_id'] ) ) { $error->add( 'invalid_app_id', __( 'The application ID must be a UUID.' ) ); } /** * Fires before application password errors are returned. * * @since 5.6.0 * * @param WP_Error $error The error object. * @param array $request The array of request data. * @param WP_User $user The user authorizing the application. */ do_action( 'wp_authorize_application_password_request_errors', $error, $request, $user ); if ( $error->has_errors() ) { return $error; } return true; } /** * Validates the redirect URL protocol scheme. The protocol can be anything except `http` and `javascript`. * * @since 6.3.2 * * @param string $url The redirect URL to be validated. * @return true|WP_Error True if the redirect URL is valid, a WP_Error object otherwise. */ function wp_is_authorize_application_redirect_url_valid( $url ) { $bad_protocols = array( 'javascript', 'data' ); if ( empty( $url ) ) { return true; } // Based on https://www.rfc-editor.org/rfc/rfc2396#section-3.1 $valid_scheme_regex = '/^[a-zA-Z][a-zA-Z0-9+.-]*:/'; if ( ! preg_match( $valid_scheme_regex, $url ) ) { return new WP_Error( 'invalid_redirect_url_format', __( 'Invalid URL format.' ) ); } /** * Filters the list of invalid protocols used in applications redirect URLs. * * @since 6.3.2 * * @param string[] $bad_protocols Array of invalid protocols. * @param string $url The redirect URL to be validated. */ $invalid_protocols = apply_filters( 'wp_authorize_application_redirect_url_invalid_protocols', $bad_protocols, $url ); $invalid_protocols = array_map( 'strtolower', $invalid_protocols ); $scheme = wp_parse_url( $url, PHP_URL_SCHEME ); $host = wp_parse_url( $url, PHP_URL_HOST ); $is_local = 'local' === wp_get_environment_type(); // Validates if the proper URI format is applied to the URL. if ( empty( $host ) || empty( $scheme ) || in_array( strtolower( $scheme ), $invalid_protocols, true ) ) { return new WP_Error( 'invalid_redirect_url_format', __( 'Invalid URL format.' ) ); } if ( 'http' === $scheme && ! $is_local ) { return new WP_Error( 'invalid_redirect_scheme', __( 'The URL must be served over a secure connection.' ) ); } return true; } class-core-upgrader.php000064400000035527147206365750011152 0ustar00strings['up_to_date'] = __( 'WordPress is at the latest version.' ); $this->strings['locked'] = __( 'Another update is currently in progress.' ); $this->strings['no_package'] = __( 'Update package not available.' ); /* translators: %s: Package URL. */ $this->strings['downloading_package'] = sprintf( __( 'Downloading update from %s…' ), '%s' ); $this->strings['unpack_package'] = __( 'Unpacking the update…' ); $this->strings['copy_failed'] = __( 'Could not copy files.' ); $this->strings['copy_failed_space'] = __( 'Could not copy files. You may have run out of disk space.' ); $this->strings['start_rollback'] = __( 'Attempting to restore the previous version.' ); $this->strings['rollback_was_required'] = __( 'Due to an error during updating, WordPress has been restored to your previous version.' ); } /** * Upgrades WordPress core. * * @since 2.8.0 * * @global WP_Filesystem_Base $wp_filesystem WordPress filesystem subclass. * @global callable $_wp_filesystem_direct_method * * @param object $current Response object for whether WordPress is current. * @param array $args { * Optional. Arguments for upgrading WordPress core. Default empty array. * * @type bool $pre_check_md5 Whether to check the file checksums before * attempting the upgrade. Default true. * @type bool $attempt_rollback Whether to attempt to rollback the chances if * there is a problem. Default false. * @type bool $do_rollback Whether to perform this "upgrade" as a rollback. * Default false. * } * @return string|false|WP_Error New WordPress version on success, false or WP_Error on failure. */ public function upgrade( $current, $args = array() ) { global $wp_filesystem; require ABSPATH . WPINC . '/version.php'; // $wp_version; $start_time = time(); $defaults = array( 'pre_check_md5' => true, 'attempt_rollback' => false, 'do_rollback' => false, 'allow_relaxed_file_ownership' => false, ); $parsed_args = wp_parse_args( $args, $defaults ); $this->init(); $this->upgrade_strings(); // Is an update available? if ( ! isset( $current->response ) || 'latest' === $current->response ) { return new WP_Error( 'up_to_date', $this->strings['up_to_date'] ); } $res = $this->fs_connect( array( ABSPATH, WP_CONTENT_DIR ), $parsed_args['allow_relaxed_file_ownership'] ); if ( ! $res || is_wp_error( $res ) ) { return $res; } $wp_dir = trailingslashit( $wp_filesystem->abspath() ); $partial = true; if ( $parsed_args['do_rollback'] ) { $partial = false; } elseif ( $parsed_args['pre_check_md5'] && ! $this->check_files() ) { $partial = false; } /* * If partial update is returned from the API, use that, unless we're doing * a reinstallation. If we cross the new_bundled version number, then use * the new_bundled zip. Don't though if the constant is set to skip bundled items. * If the API returns a no_content zip, go with it. Finally, default to the full zip. */ if ( $parsed_args['do_rollback'] && $current->packages->rollback ) { $to_download = 'rollback'; } elseif ( $current->packages->partial && 'reinstall' !== $current->response && $wp_version === $current->partial_version && $partial ) { $to_download = 'partial'; } elseif ( $current->packages->new_bundled && version_compare( $wp_version, $current->new_bundled, '<' ) && ( ! defined( 'CORE_UPGRADE_SKIP_NEW_BUNDLED' ) || ! CORE_UPGRADE_SKIP_NEW_BUNDLED ) ) { $to_download = 'new_bundled'; } elseif ( $current->packages->no_content ) { $to_download = 'no_content'; } else { $to_download = 'full'; } // Lock to prevent multiple Core Updates occurring. $lock = WP_Upgrader::create_lock( 'core_updater', 15 * MINUTE_IN_SECONDS ); if ( ! $lock ) { return new WP_Error( 'locked', $this->strings['locked'] ); } $download = $this->download_package( $current->packages->$to_download, false ); /* * Allow for signature soft-fail. * WARNING: This may be removed in the future. */ if ( is_wp_error( $download ) && $download->get_error_data( 'softfail-filename' ) ) { // Output the failure error as a normal feedback, and not as an error: /** This filter is documented in wp-admin/includes/update-core.php */ apply_filters( 'update_feedback', $download->get_error_message() ); // Report this failure back to WordPress.org for debugging purposes. wp_version_check( array( 'signature_failure_code' => $download->get_error_code(), 'signature_failure_data' => $download->get_error_data(), ) ); // Pretend this error didn't happen. $download = $download->get_error_data( 'softfail-filename' ); } if ( is_wp_error( $download ) ) { WP_Upgrader::release_lock( 'core_updater' ); return $download; } $working_dir = $this->unpack_package( $download ); if ( is_wp_error( $working_dir ) ) { WP_Upgrader::release_lock( 'core_updater' ); return $working_dir; } // Copy update-core.php from the new version into place. if ( ! $wp_filesystem->copy( $working_dir . '/wordpress/wp-admin/includes/update-core.php', $wp_dir . 'wp-admin/includes/update-core.php', true ) ) { $wp_filesystem->delete( $working_dir, true ); WP_Upgrader::release_lock( 'core_updater' ); return new WP_Error( 'copy_failed_for_update_core_file', __( 'The update cannot be installed because some files could not be copied. This is usually due to inconsistent file permissions.' ), 'wp-admin/includes/update-core.php' ); } $wp_filesystem->chmod( $wp_dir . 'wp-admin/includes/update-core.php', FS_CHMOD_FILE ); wp_opcache_invalidate( ABSPATH . 'wp-admin/includes/update-core.php' ); require_once ABSPATH . 'wp-admin/includes/update-core.php'; if ( ! function_exists( 'update_core' ) ) { WP_Upgrader::release_lock( 'core_updater' ); return new WP_Error( 'copy_failed_space', $this->strings['copy_failed_space'] ); } $result = update_core( $working_dir, $wp_dir ); // In the event of an issue, we may be able to roll back. if ( $parsed_args['attempt_rollback'] && $current->packages->rollback && ! $parsed_args['do_rollback'] ) { $try_rollback = false; if ( is_wp_error( $result ) ) { $error_code = $result->get_error_code(); /* * Not all errors are equal. These codes are critical: copy_failed__copy_dir, * mkdir_failed__copy_dir, copy_failed__copy_dir_retry, and disk_full. * do_rollback allows for update_core() to trigger a rollback if needed. */ if ( str_contains( $error_code, 'do_rollback' ) ) { $try_rollback = true; } elseif ( str_contains( $error_code, '__copy_dir' ) ) { $try_rollback = true; } elseif ( 'disk_full' === $error_code ) { $try_rollback = true; } } if ( $try_rollback ) { /** This filter is documented in wp-admin/includes/update-core.php */ apply_filters( 'update_feedback', $result ); /** This filter is documented in wp-admin/includes/update-core.php */ apply_filters( 'update_feedback', $this->strings['start_rollback'] ); $rollback_result = $this->upgrade( $current, array_merge( $parsed_args, array( 'do_rollback' => true ) ) ); $original_result = $result; $result = new WP_Error( 'rollback_was_required', $this->strings['rollback_was_required'], (object) array( 'update' => $original_result, 'rollback' => $rollback_result, ) ); } } /** This action is documented in wp-admin/includes/class-wp-upgrader.php */ do_action( 'upgrader_process_complete', $this, array( 'action' => 'update', 'type' => 'core', ) ); // Clear the current updates. delete_site_transient( 'update_core' ); if ( ! $parsed_args['do_rollback'] ) { $stats = array( 'update_type' => $current->response, 'success' => true, 'fs_method' => $wp_filesystem->method, 'fs_method_forced' => defined( 'FS_METHOD' ) || has_filter( 'filesystem_method' ), 'fs_method_direct' => ! empty( $GLOBALS['_wp_filesystem_direct_method'] ) ? $GLOBALS['_wp_filesystem_direct_method'] : '', 'time_taken' => time() - $start_time, 'reported' => $wp_version, 'attempted' => $current->version, ); if ( is_wp_error( $result ) ) { $stats['success'] = false; // Did a rollback occur? if ( ! empty( $try_rollback ) ) { $stats['error_code'] = $original_result->get_error_code(); $stats['error_data'] = $original_result->get_error_data(); // Was the rollback successful? If not, collect its error too. $stats['rollback'] = ! is_wp_error( $rollback_result ); if ( is_wp_error( $rollback_result ) ) { $stats['rollback_code'] = $rollback_result->get_error_code(); $stats['rollback_data'] = $rollback_result->get_error_data(); } } else { $stats['error_code'] = $result->get_error_code(); $stats['error_data'] = $result->get_error_data(); } } wp_version_check( $stats ); } WP_Upgrader::release_lock( 'core_updater' ); return $result; } /** * Determines if this WordPress Core version should update to an offered version or not. * * @since 3.7.0 * * @param string $offered_ver The offered version, of the format x.y.z. * @return bool True if we should update to the offered version, otherwise false. */ public static function should_update_to_version( $offered_ver ) { require ABSPATH . WPINC . '/version.php'; // $wp_version; // x.y.z $current_branch = implode( '.', array_slice( preg_split( '/[.-]/', $wp_version ), 0, 2 ) ); // x.y $new_branch = implode( '.', array_slice( preg_split( '/[.-]/', $offered_ver ), 0, 2 ) ); // x.y $current_is_development_version = (bool) strpos( $wp_version, '-' ); // Defaults: $upgrade_dev = get_site_option( 'auto_update_core_dev', 'enabled' ) === 'enabled'; $upgrade_minor = get_site_option( 'auto_update_core_minor', 'enabled' ) === 'enabled'; $upgrade_major = get_site_option( 'auto_update_core_major', 'unset' ) === 'enabled'; // WP_AUTO_UPDATE_CORE = true (all), 'beta', 'rc', 'development', 'branch-development', 'minor', false. if ( defined( 'WP_AUTO_UPDATE_CORE' ) ) { if ( false === WP_AUTO_UPDATE_CORE ) { // Defaults to turned off, unless a filter allows it. $upgrade_dev = false; $upgrade_minor = false; $upgrade_major = false; } elseif ( true === WP_AUTO_UPDATE_CORE || in_array( WP_AUTO_UPDATE_CORE, array( 'beta', 'rc', 'development', 'branch-development' ), true ) ) { // ALL updates for core. $upgrade_dev = true; $upgrade_minor = true; $upgrade_major = true; } elseif ( 'minor' === WP_AUTO_UPDATE_CORE ) { // Only minor updates for core. $upgrade_dev = false; $upgrade_minor = true; $upgrade_major = false; } } // 1: If we're already on that version, not much point in updating? if ( $offered_ver === $wp_version ) { return false; } // 2: If we're running a newer version, that's a nope. if ( version_compare( $wp_version, $offered_ver, '>' ) ) { return false; } $failure_data = get_site_option( 'auto_core_update_failed' ); if ( $failure_data ) { // If this was a critical update failure, cannot update. if ( ! empty( $failure_data['critical'] ) ) { return false; } // Don't claim we can update on update-core.php if we have a non-critical failure logged. if ( $wp_version === $failure_data['current'] && str_contains( $offered_ver, '.1.next.minor' ) ) { return false; } /* * Cannot update if we're retrying the same A to B update that caused a non-critical failure. * Some non-critical failures do allow retries, like download_failed. * 3.7.1 => 3.7.2 resulted in files_not_writable, if we are still on 3.7.1 and still trying to update to 3.7.2. */ if ( empty( $failure_data['retry'] ) && $wp_version === $failure_data['current'] && $offered_ver === $failure_data['attempted'] ) { return false; } } // 3: 3.7-alpha-25000 -> 3.7-alpha-25678 -> 3.7-beta1 -> 3.7-beta2. if ( $current_is_development_version ) { /** * Filters whether to enable automatic core updates for development versions. * * @since 3.7.0 * * @param bool $upgrade_dev Whether to enable automatic updates for * development versions. */ if ( ! apply_filters( 'allow_dev_auto_core_updates', $upgrade_dev ) ) { return false; } // Else fall through to minor + major branches below. } // 4: Minor in-branch updates (3.7.0 -> 3.7.1 -> 3.7.2 -> 3.7.4). if ( $current_branch === $new_branch ) { /** * Filters whether to enable minor automatic core updates. * * @since 3.7.0 * * @param bool $upgrade_minor Whether to enable minor automatic core updates. */ return apply_filters( 'allow_minor_auto_core_updates', $upgrade_minor ); } // 5: Major version updates (3.7.0 -> 3.8.0 -> 3.9.1). if ( version_compare( $new_branch, $current_branch, '>' ) ) { /** * Filters whether to enable major automatic core updates. * * @since 3.7.0 * * @param bool $upgrade_major Whether to enable major automatic core updates. */ return apply_filters( 'allow_major_auto_core_updates', $upgrade_major ); } // If we're not sure, we don't want it. return false; } /** * Compares the disk file checksums against the expected checksums. * * @since 3.7.0 * * @global string $wp_version The WordPress version string. * @global string $wp_local_package Locale code of the package. * * @return bool True if the checksums match, otherwise false. */ public function check_files() { global $wp_version, $wp_local_package; $checksums = get_core_checksums( $wp_version, isset( $wp_local_package ) ? $wp_local_package : 'en_US' ); if ( ! is_array( $checksums ) ) { return false; } foreach ( $checksums as $file => $checksum ) { // Skip files which get updated. if ( str_starts_with( $file, 'wp-content' ) ) { continue; } if ( ! file_exists( ABSPATH . $file ) || md5_file( ABSPATH . $file ) !== $checksum ) { return false; } } return true; } } class-ftp-pure.php000064400000012462147206365750010146 0ustar00 // // function _settimeout($sock) { if(!@stream_set_timeout($sock, $this->_timeout)) { $this->PushError('_settimeout','socket set send timeout'); $this->_quit(); return FALSE; } return TRUE; } function _connect($host, $port) { $this->SendMSG("Creating socket"); $sock = @fsockopen($host, $port, $errno, $errstr, $this->_timeout); if (!$sock) { $this->PushError('_connect','socket connect failed', $errstr." (".$errno.")"); return FALSE; } $this->_connected=true; return $sock; } function _readmsg($fnction="_readmsg"){ if(!$this->_connected) { $this->PushError($fnction, 'Connect first'); return FALSE; } $result=true; $this->_message=""; $this->_code=0; $go=true; do { $tmp=@fgets($this->_ftp_control_sock, 512); if($tmp===false) { $go=$result=false; $this->PushError($fnction,'Read failed'); } else { $this->_message.=$tmp; if(preg_match("/^([0-9]{3})(-(.*[".CRLF."]{1,2})+\\1)? [^".CRLF."]+[".CRLF."]{1,2}$/", $this->_message, $regs)) $go=false; } } while($go); if($this->LocalEcho) echo "GET < ".rtrim($this->_message, CRLF).CRLF; $this->_code=(int)$regs[1]; return $result; } function _exec($cmd, $fnction="_exec") { if(!$this->_ready) { $this->PushError($fnction,'Connect first'); return FALSE; } if($this->LocalEcho) echo "PUT > ",$cmd,CRLF; $status=@fputs($this->_ftp_control_sock, $cmd.CRLF); if($status===false) { $this->PushError($fnction,'socket write failed'); return FALSE; } $this->_lastaction=time(); if(!$this->_readmsg($fnction)) return FALSE; return TRUE; } function _data_prepare($mode=FTP_ASCII) { if(!$this->_settype($mode)) return FALSE; if($this->_passive) { if(!$this->_exec("PASV", "pasv")) { $this->_data_close(); return FALSE; } if(!$this->_checkCode()) { $this->_data_close(); return FALSE; } $ip_port = explode(",", preg_replace("/^.+ \\(?([0-9]{1,3},[0-9]{1,3},[0-9]{1,3},[0-9]{1,3},[0-9]+,[0-9]+)\\)?.*$/s", "\\1", $this->_message)); $this->_datahost=$ip_port[0].".".$ip_port[1].".".$ip_port[2].".".$ip_port[3]; $this->_dataport=(((int)$ip_port[4])<<8) + ((int)$ip_port[5]); $this->SendMSG("Connecting to ".$this->_datahost.":".$this->_dataport); $this->_ftp_data_sock=@fsockopen($this->_datahost, $this->_dataport, $errno, $errstr, $this->_timeout); if(!$this->_ftp_data_sock) { $this->PushError("_data_prepare","fsockopen fails", $errstr." (".$errno.")"); $this->_data_close(); return FALSE; } else $this->_ftp_data_sock; } else { $this->SendMSG("Only passive connections available!"); return FALSE; } return TRUE; } function _data_read($mode=FTP_ASCII, $fp=NULL) { if(is_resource($fp)) $out=0; else $out=""; if(!$this->_passive) { $this->SendMSG("Only passive connections available!"); return FALSE; } while (!feof($this->_ftp_data_sock)) { $block=fread($this->_ftp_data_sock, $this->_ftp_buff_size); if($mode!=FTP_BINARY) $block=preg_replace("/\r\n|\r|\n/", $this->_eol_code[$this->OS_local], $block); if(is_resource($fp)) $out+=fwrite($fp, $block, strlen($block)); else $out.=$block; } return $out; } function _data_write($mode=FTP_ASCII, $fp=NULL) { if(is_resource($fp)) $out=0; else $out=""; if(!$this->_passive) { $this->SendMSG("Only passive connections available!"); return FALSE; } if(is_resource($fp)) { while(!feof($fp)) { $block=fread($fp, $this->_ftp_buff_size); if(!$this->_data_write_block($mode, $block)) return false; } } elseif(!$this->_data_write_block($mode, $fp)) return false; return TRUE; } function _data_write_block($mode, $block) { if($mode!=FTP_BINARY) $block=preg_replace("/\r\n|\r|\n/", $this->_eol_code[$this->OS_remote], $block); do { if(($t=@fwrite($this->_ftp_data_sock, $block))===FALSE) { $this->PushError("_data_write","Can't write to socket"); return FALSE; } $block=substr($block, $t); } while(!empty($block)); return true; } function _data_close() { @fclose($this->_ftp_data_sock); $this->SendMSG("Disconnected data from remote host"); return TRUE; } function _quit($force=FALSE) { if($this->_connected or $force) { @fclose($this->_ftp_control_sock); $this->_connected=false; $this->SendMSG("Socket closed"); } } } ?> class-bulk-theme-upgrader-skin.php000064400000005144147206365750013211 0ustar00upgrader->strings['skin_before_update_header'] = __( 'Updating Theme %1$s (%2$d/%3$d)' ); } /** * Performs an action before a bulk theme update. * * @since 3.0.0 * * @param string $title */ public function before( $title = '' ) { parent::before( $this->theme_info->display( 'Name' ) ); } /** * Performs an action following a bulk theme update. * * @since 3.0.0 * * @param string $title */ public function after( $title = '' ) { parent::after( $this->theme_info->display( 'Name' ) ); $this->decrement_update_count( 'theme' ); } /** * Displays the footer following the bulk update process. * * @since 3.0.0 */ public function bulk_footer() { parent::bulk_footer(); $update_actions = array( 'themes_page' => sprintf( '%s', self_admin_url( 'themes.php' ), __( 'Go to Themes page' ) ), 'updates_page' => sprintf( '%s', self_admin_url( 'update-core.php' ), __( 'Go to WordPress Updates page' ) ), ); if ( ! current_user_can( 'switch_themes' ) && ! current_user_can( 'edit_theme_options' ) ) { unset( $update_actions['themes_page'] ); } /** * Filters the list of action links available following bulk theme updates. * * @since 3.0.0 * * @param string[] $update_actions Array of theme action links. * @param WP_Theme $theme_info Theme object for the last-updated theme. */ $update_actions = apply_filters( 'update_bulk_theme_complete_actions', $update_actions, $this->theme_info ); if ( ! empty( $update_actions ) ) { $this->feedback( implode( ' | ', (array) $update_actions ) ); } } } class-wp-list-table-compat.php000064400000002731147206365750012347 0ustar00_screen = $screen; if ( ! empty( $columns ) ) { $this->_columns = $columns; add_filter( 'manage_' . $screen->id . '_columns', array( $this, 'get_columns' ), 0 ); } } /** * Gets a list of all, hidden, and sortable columns. * * @since 3.1.0 * * @return array */ protected function get_column_info() { $columns = get_column_headers( $this->_screen ); $hidden = get_hidden_columns( $this->_screen ); $sortable = array(); $primary = $this->get_default_primary_column_name(); return array( $columns, $hidden, $sortable, $primary ); } /** * Gets a list of columns. * * @since 3.1.0 * * @return array */ public function get_columns() { return $this->_columns; } } class-wp-filesystem-ssh2.php000064400000055416147206365750012077 0ustar00method = 'ssh2'; $this->errors = new WP_Error(); // Check if possible to use ssh2 functions. if ( ! extension_loaded( 'ssh2' ) ) { $this->errors->add( 'no_ssh2_ext', __( 'The ssh2 PHP extension is not available' ) ); return; } // Set defaults: if ( empty( $opt['port'] ) ) { $this->options['port'] = 22; } else { $this->options['port'] = $opt['port']; } if ( empty( $opt['hostname'] ) ) { $this->errors->add( 'empty_hostname', __( 'SSH2 hostname is required' ) ); } else { $this->options['hostname'] = $opt['hostname']; } // Check if the options provided are OK. if ( ! empty( $opt['public_key'] ) && ! empty( $opt['private_key'] ) ) { $this->options['public_key'] = $opt['public_key']; $this->options['private_key'] = $opt['private_key']; $this->options['hostkey'] = array( 'hostkey' => 'ssh-rsa,ssh-ed25519' ); $this->keys = true; } elseif ( empty( $opt['username'] ) ) { $this->errors->add( 'empty_username', __( 'SSH2 username is required' ) ); } if ( ! empty( $opt['username'] ) ) { $this->options['username'] = $opt['username']; } if ( empty( $opt['password'] ) ) { // Password can be blank if we are using keys. if ( ! $this->keys ) { $this->errors->add( 'empty_password', __( 'SSH2 password is required' ) ); } else { $this->options['password'] = null; } } else { $this->options['password'] = $opt['password']; } } /** * Connects filesystem. * * @since 2.7.0 * * @return bool True on success, false on failure. */ public function connect() { if ( ! $this->keys ) { $this->link = @ssh2_connect( $this->options['hostname'], $this->options['port'] ); } else { $this->link = @ssh2_connect( $this->options['hostname'], $this->options['port'], $this->options['hostkey'] ); } if ( ! $this->link ) { $this->errors->add( 'connect', sprintf( /* translators: %s: hostname:port */ __( 'Failed to connect to SSH2 Server %s' ), $this->options['hostname'] . ':' . $this->options['port'] ) ); return false; } if ( ! $this->keys ) { if ( ! @ssh2_auth_password( $this->link, $this->options['username'], $this->options['password'] ) ) { $this->errors->add( 'auth', sprintf( /* translators: %s: Username. */ __( 'Username/Password incorrect for %s' ), $this->options['username'] ) ); return false; } } else { if ( ! @ssh2_auth_pubkey_file( $this->link, $this->options['username'], $this->options['public_key'], $this->options['private_key'], $this->options['password'] ) ) { $this->errors->add( 'auth', sprintf( /* translators: %s: Username. */ __( 'Public and Private keys incorrect for %s' ), $this->options['username'] ) ); return false; } } $this->sftp_link = ssh2_sftp( $this->link ); if ( ! $this->sftp_link ) { $this->errors->add( 'connect', sprintf( /* translators: %s: hostname:port */ __( 'Failed to initialize a SFTP subsystem session with the SSH2 Server %s' ), $this->options['hostname'] . ':' . $this->options['port'] ) ); return false; } return true; } /** * Gets the ssh2.sftp PHP stream wrapper path to open for the given file. * * This method also works around a PHP bug where the root directory (/) cannot * be opened by PHP functions, causing a false failure. In order to work around * this, the path is converted to /./ which is semantically the same as / * See https://bugs.php.net/bug.php?id=64169 for more details. * * @since 4.4.0 * * @param string $path The File/Directory path on the remote server to return * @return string The ssh2.sftp:// wrapped path to use. */ public function sftp_path( $path ) { if ( '/' === $path ) { $path = '/./'; } return 'ssh2.sftp://' . $this->sftp_link . '/' . ltrim( $path, '/' ); } /** * @since 2.7.0 * * @param string $command * @param bool $returnbool * @return bool|string True on success, false on failure. String if the command was executed, `$returnbool` * is false (default), and data from the resulting stream was retrieved. */ public function run_command( $command, $returnbool = false ) { if ( ! $this->link ) { return false; } $stream = ssh2_exec( $this->link, $command ); if ( ! $stream ) { $this->errors->add( 'command', sprintf( /* translators: %s: Command. */ __( 'Unable to perform command: %s' ), $command ) ); } else { stream_set_blocking( $stream, true ); stream_set_timeout( $stream, FS_TIMEOUT ); $data = stream_get_contents( $stream ); fclose( $stream ); if ( $returnbool ) { return ( false === $data ) ? false : '' !== trim( $data ); } else { return $data; } } return false; } /** * Reads entire file into a string. * * @since 2.7.0 * * @param string $file Name of the file to read. * @return string|false Read data on success, false if no temporary file could be opened, * or if the file couldn't be retrieved. */ public function get_contents( $file ) { return file_get_contents( $this->sftp_path( $file ) ); } /** * Reads entire file into an array. * * @since 2.7.0 * * @param string $file Path to the file. * @return array|false File contents in an array on success, false on failure. */ public function get_contents_array( $file ) { return file( $this->sftp_path( $file ) ); } /** * Writes a string to a file. * * @since 2.7.0 * * @param string $file Remote path to the file where to write the data. * @param string $contents The data to write. * @param int|false $mode Optional. The file permissions as octal number, usually 0644. * Default false. * @return bool True on success, false on failure. */ public function put_contents( $file, $contents, $mode = false ) { $ret = file_put_contents( $this->sftp_path( $file ), $contents ); if ( strlen( $contents ) !== $ret ) { return false; } $this->chmod( $file, $mode ); return true; } /** * Gets the current working directory. * * @since 2.7.0 * * @return string|false The current working directory on success, false on failure. */ public function cwd() { $cwd = ssh2_sftp_realpath( $this->sftp_link, '.' ); if ( $cwd ) { $cwd = trailingslashit( trim( $cwd ) ); } return $cwd; } /** * Changes current directory. * * @since 2.7.0 * * @param string $dir The new current directory. * @return bool True on success, false on failure. */ public function chdir( $dir ) { return $this->run_command( 'cd ' . $dir, true ); } /** * Changes the file group. * * @since 2.7.0 * * @param string $file Path to the file. * @param string|int $group A group name or number. * @param bool $recursive Optional. If set to true, changes file group recursively. * Default false. * @return bool True on success, false on failure. */ public function chgrp( $file, $group, $recursive = false ) { if ( ! $this->exists( $file ) ) { return false; } if ( ! $recursive || ! $this->is_dir( $file ) ) { return $this->run_command( sprintf( 'chgrp %s %s', escapeshellarg( $group ), escapeshellarg( $file ) ), true ); } return $this->run_command( sprintf( 'chgrp -R %s %s', escapeshellarg( $group ), escapeshellarg( $file ) ), true ); } /** * Changes filesystem permissions. * * @since 2.7.0 * * @param string $file Path to the file. * @param int|false $mode Optional. The permissions as octal number, usually 0644 for files, * 0755 for directories. Default false. * @param bool $recursive Optional. If set to true, changes file permissions recursively. * Default false. * @return bool True on success, false on failure. */ public function chmod( $file, $mode = false, $recursive = false ) { if ( ! $this->exists( $file ) ) { return false; } if ( ! $mode ) { if ( $this->is_file( $file ) ) { $mode = FS_CHMOD_FILE; } elseif ( $this->is_dir( $file ) ) { $mode = FS_CHMOD_DIR; } else { return false; } } if ( ! $recursive || ! $this->is_dir( $file ) ) { return $this->run_command( sprintf( 'chmod %o %s', $mode, escapeshellarg( $file ) ), true ); } return $this->run_command( sprintf( 'chmod -R %o %s', $mode, escapeshellarg( $file ) ), true ); } /** * Changes the owner of a file or directory. * * @since 2.7.0 * * @param string $file Path to the file or directory. * @param string|int $owner A user name or number. * @param bool $recursive Optional. If set to true, changes file owner recursively. * Default false. * @return bool True on success, false on failure. */ public function chown( $file, $owner, $recursive = false ) { if ( ! $this->exists( $file ) ) { return false; } if ( ! $recursive || ! $this->is_dir( $file ) ) { return $this->run_command( sprintf( 'chown %s %s', escapeshellarg( $owner ), escapeshellarg( $file ) ), true ); } return $this->run_command( sprintf( 'chown -R %s %s', escapeshellarg( $owner ), escapeshellarg( $file ) ), true ); } /** * Gets the file owner. * * @since 2.7.0 * * @param string $file Path to the file. * @return string|false Username of the owner on success, false on failure. */ public function owner( $file ) { $owneruid = @fileowner( $this->sftp_path( $file ) ); if ( ! $owneruid ) { return false; } if ( ! function_exists( 'posix_getpwuid' ) ) { return $owneruid; } $ownerarray = posix_getpwuid( $owneruid ); if ( ! $ownerarray ) { return false; } return $ownerarray['name']; } /** * Gets the permissions of the specified file or filepath in their octal format. * * @since 2.7.0 * * @param string $file Path to the file. * @return string Mode of the file (the last 3 digits). */ public function getchmod( $file ) { return substr( decoct( @fileperms( $this->sftp_path( $file ) ) ), -3 ); } /** * Gets the file's group. * * @since 2.7.0 * * @param string $file Path to the file. * @return string|false The group on success, false on failure. */ public function group( $file ) { $gid = @filegroup( $this->sftp_path( $file ) ); if ( ! $gid ) { return false; } if ( ! function_exists( 'posix_getgrgid' ) ) { return $gid; } $grouparray = posix_getgrgid( $gid ); if ( ! $grouparray ) { return false; } return $grouparray['name']; } /** * Copies a file. * * @since 2.7.0 * * @param string $source Path to the source file. * @param string $destination Path to the destination file. * @param bool $overwrite Optional. Whether to overwrite the destination file if it exists. * Default false. * @param int|false $mode Optional. The permissions as octal number, usually 0644 for files, * 0755 for dirs. Default false. * @return bool True on success, false on failure. */ public function copy( $source, $destination, $overwrite = false, $mode = false ) { if ( ! $overwrite && $this->exists( $destination ) ) { return false; } $content = $this->get_contents( $source ); if ( false === $content ) { return false; } return $this->put_contents( $destination, $content, $mode ); } /** * Moves a file or directory. * * After moving files or directories, OPcache will need to be invalidated. * * If moving a directory fails, `copy_dir()` can be used for a recursive copy. * * Use `move_dir()` for moving directories with OPcache invalidation and a * fallback to `copy_dir()`. * * @since 2.7.0 * * @param string $source Path to the source file or directory. * @param string $destination Path to the destination file or directory. * @param bool $overwrite Optional. Whether to overwrite the destination if it exists. * Default false. * @return bool True on success, false on failure. */ public function move( $source, $destination, $overwrite = false ) { if ( $this->exists( $destination ) ) { if ( $overwrite ) { // We need to remove the destination before we can rename the source. $this->delete( $destination, false, 'f' ); } else { // If we're not overwriting, the rename will fail, so return early. return false; } } return ssh2_sftp_rename( $this->sftp_link, $source, $destination ); } /** * Deletes a file or directory. * * @since 2.7.0 * * @param string $file Path to the file or directory. * @param bool $recursive Optional. If set to true, deletes files and folders recursively. * Default false. * @param string|false $type Type of resource. 'f' for file, 'd' for directory. * Default false. * @return bool True on success, false on failure. */ public function delete( $file, $recursive = false, $type = false ) { if ( 'f' === $type || $this->is_file( $file ) ) { return ssh2_sftp_unlink( $this->sftp_link, $file ); } if ( ! $recursive ) { return ssh2_sftp_rmdir( $this->sftp_link, $file ); } $filelist = $this->dirlist( $file ); if ( is_array( $filelist ) ) { foreach ( $filelist as $filename => $fileinfo ) { $this->delete( $file . '/' . $filename, $recursive, $fileinfo['type'] ); } } return ssh2_sftp_rmdir( $this->sftp_link, $file ); } /** * Checks if a file or directory exists. * * @since 2.7.0 * * @param string $path Path to file or directory. * @return bool Whether $path exists or not. */ public function exists( $path ) { return file_exists( $this->sftp_path( $path ) ); } /** * Checks if resource is a file. * * @since 2.7.0 * * @param string $file File path. * @return bool Whether $file is a file. */ public function is_file( $file ) { return is_file( $this->sftp_path( $file ) ); } /** * Checks if resource is a directory. * * @since 2.7.0 * * @param string $path Directory path. * @return bool Whether $path is a directory. */ public function is_dir( $path ) { return is_dir( $this->sftp_path( $path ) ); } /** * Checks if a file is readable. * * @since 2.7.0 * * @param string $file Path to file. * @return bool Whether $file is readable. */ public function is_readable( $file ) { return is_readable( $this->sftp_path( $file ) ); } /** * Checks if a file or directory is writable. * * @since 2.7.0 * * @param string $path Path to file or directory. * @return bool Whether $path is writable. */ public function is_writable( $path ) { // PHP will base its writable checks on system_user === file_owner, not ssh_user === file_owner. return true; } /** * Gets the file's last access time. * * @since 2.7.0 * * @param string $file Path to file. * @return int|false Unix timestamp representing last access time, false on failure. */ public function atime( $file ) { return fileatime( $this->sftp_path( $file ) ); } /** * Gets the file modification time. * * @since 2.7.0 * * @param string $file Path to file. * @return int|false Unix timestamp representing modification time, false on failure. */ public function mtime( $file ) { return filemtime( $this->sftp_path( $file ) ); } /** * Gets the file size (in bytes). * * @since 2.7.0 * * @param string $file Path to file. * @return int|false Size of the file in bytes on success, false on failure. */ public function size( $file ) { return filesize( $this->sftp_path( $file ) ); } /** * Sets the access and modification times of a file. * * Note: Not implemented. * * @since 2.7.0 * * @param string $file Path to file. * @param int $time Optional. Modified time to set for file. * Default 0. * @param int $atime Optional. Access time to set for file. * Default 0. */ public function touch( $file, $time = 0, $atime = 0 ) { // Not implemented. } /** * Creates a directory. * * @since 2.7.0 * * @param string $path Path for new directory. * @param int|false $chmod Optional. The permissions as octal number (or false to skip chmod). * Default false. * @param string|int|false $chown Optional. A user name or number (or false to skip chown). * Default false. * @param string|int|false $chgrp Optional. A group name or number (or false to skip chgrp). * Default false. * @return bool True on success, false on failure. */ public function mkdir( $path, $chmod = false, $chown = false, $chgrp = false ) { $path = untrailingslashit( $path ); if ( empty( $path ) ) { return false; } if ( ! $chmod ) { $chmod = FS_CHMOD_DIR; } if ( ! ssh2_sftp_mkdir( $this->sftp_link, $path, $chmod, true ) ) { return false; } // Set directory permissions. ssh2_sftp_chmod( $this->sftp_link, $path, $chmod ); if ( $chown ) { $this->chown( $path, $chown ); } if ( $chgrp ) { $this->chgrp( $path, $chgrp ); } return true; } /** * Deletes a directory. * * @since 2.7.0 * * @param string $path Path to directory. * @param bool $recursive Optional. Whether to recursively remove files/directories. * Default false. * @return bool True on success, false on failure. */ public function rmdir( $path, $recursive = false ) { return $this->delete( $path, $recursive ); } /** * Gets details for files in a directory or a specific file. * * @since 2.7.0 * * @param string $path Path to directory or file. * @param bool $include_hidden Optional. Whether to include details of hidden ("." prefixed) files. * Default true. * @param bool $recursive Optional. Whether to recursively include file details in nested directories. * Default false. * @return array|false { * Array of arrays containing file information. False if unable to list directory contents. * * @type array ...$0 { * Array of file information. Note that some elements may not be available on all filesystems. * * @type string $name Name of the file or directory. * @type string $perms *nix representation of permissions. * @type string $permsn Octal representation of permissions. * @type false $number File number. Always false in this context. * @type string|false $owner Owner name or ID, or false if not available. * @type string|false $group File permissions group, or false if not available. * @type int|string|false $size Size of file in bytes. May be a numeric string. * False if not available. * @type int|string|false $lastmodunix Last modified unix timestamp. May be a numeric string. * False if not available. * @type string|false $lastmod Last modified month (3 letters) and day (without leading 0), or * false if not available. * @type string|false $time Last modified time, or false if not available. * @type string $type Type of resource. 'f' for file, 'd' for directory, 'l' for link. * @type array|false $files If a directory and `$recursive` is true, contains another array of * files. False if unable to list directory contents. * } * } */ public function dirlist( $path, $include_hidden = true, $recursive = false ) { if ( $this->is_file( $path ) ) { $limit_file = basename( $path ); $path = dirname( $path ); } else { $limit_file = false; } if ( ! $this->is_dir( $path ) || ! $this->is_readable( $path ) ) { return false; } $ret = array(); $dir = dir( $this->sftp_path( $path ) ); if ( ! $dir ) { return false; } $path = trailingslashit( $path ); while ( false !== ( $entry = $dir->read() ) ) { $struc = array(); $struc['name'] = $entry; if ( '.' === $struc['name'] || '..' === $struc['name'] ) { continue; // Do not care about these folders. } if ( ! $include_hidden && '.' === $struc['name'][0] ) { continue; } if ( $limit_file && $struc['name'] !== $limit_file ) { continue; } $struc['perms'] = $this->gethchmod( $path . $entry ); $struc['permsn'] = $this->getnumchmodfromh( $struc['perms'] ); $struc['number'] = false; $struc['owner'] = $this->owner( $path . $entry ); $struc['group'] = $this->group( $path . $entry ); $struc['size'] = $this->size( $path . $entry ); $struc['lastmodunix'] = $this->mtime( $path . $entry ); $struc['lastmod'] = gmdate( 'M j', $struc['lastmodunix'] ); $struc['time'] = gmdate( 'h:i:s', $struc['lastmodunix'] ); $struc['type'] = $this->is_dir( $path . $entry ) ? 'd' : 'f'; if ( 'd' === $struc['type'] ) { if ( $recursive ) { $struc['files'] = $this->dirlist( $path . $struc['name'], $include_hidden, $recursive ); } else { $struc['files'] = array(); } } $ret[ $struc['name'] ] = $struc; } $dir->close(); unset( $dir ); return $ret; } } theme.php000064400000135176147206365750006413 0ustar00errors ) && $wp_filesystem->errors->has_errors() ) { return new WP_Error( 'fs_error', __( 'Filesystem error.' ), $wp_filesystem->errors ); } // Get the base theme folder. $themes_dir = $wp_filesystem->wp_themes_dir(); if ( empty( $themes_dir ) ) { return new WP_Error( 'fs_no_themes_dir', __( 'Unable to locate WordPress theme directory.' ) ); } /** * Fires immediately before a theme deletion attempt. * * @since 5.8.0 * * @param string $stylesheet Stylesheet of the theme to delete. */ do_action( 'delete_theme', $stylesheet ); $theme = wp_get_theme( $stylesheet ); $themes_dir = trailingslashit( $themes_dir ); $theme_dir = trailingslashit( $themes_dir . $stylesheet ); $deleted = $wp_filesystem->delete( $theme_dir, true ); /** * Fires immediately after a theme deletion attempt. * * @since 5.8.0 * * @param string $stylesheet Stylesheet of the theme to delete. * @param bool $deleted Whether the theme deletion was successful. */ do_action( 'deleted_theme', $stylesheet, $deleted ); if ( ! $deleted ) { return new WP_Error( 'could_not_remove_theme', /* translators: %s: Theme name. */ sprintf( __( 'Could not fully remove the theme %s.' ), $stylesheet ) ); } $theme_translations = wp_get_installed_translations( 'themes' ); // Remove language files, silently. if ( ! empty( $theme_translations[ $stylesheet ] ) ) { $translations = $theme_translations[ $stylesheet ]; foreach ( $translations as $translation => $data ) { $wp_filesystem->delete( WP_LANG_DIR . '/themes/' . $stylesheet . '-' . $translation . '.po' ); $wp_filesystem->delete( WP_LANG_DIR . '/themes/' . $stylesheet . '-' . $translation . '.mo' ); $wp_filesystem->delete( WP_LANG_DIR . '/themes/' . $stylesheet . '-' . $translation . '.l10n.php' ); $json_translation_files = glob( WP_LANG_DIR . '/themes/' . $stylesheet . '-' . $translation . '-*.json' ); if ( $json_translation_files ) { array_map( array( $wp_filesystem, 'delete' ), $json_translation_files ); } } } // Remove the theme from allowed themes on the network. if ( is_multisite() ) { WP_Theme::network_disable_theme( $stylesheet ); } // Clear theme caches. $theme->cache_delete(); // Force refresh of theme update information. delete_site_transient( 'update_themes' ); return true; } /** * Gets the page templates available in this theme. * * @since 1.5.0 * @since 4.7.0 Added the `$post_type` parameter. * * @param WP_Post|null $post Optional. The post being edited, provided for context. * @param string $post_type Optional. Post type to get the templates for. Default 'page'. * @return string[] Array of template file names keyed by the template header name. */ function get_page_templates( $post = null, $post_type = 'page' ) { return array_flip( wp_get_theme()->get_page_templates( $post, $post_type ) ); } /** * Tidies a filename for url display by the theme file editor. * * @since 2.9.0 * @access private * * @param string $fullpath Full path to the theme file * @param string $containingfolder Path of the theme parent folder * @return string */ function _get_template_edit_filename( $fullpath, $containingfolder ) { return str_replace( dirname( $containingfolder, 2 ), '', $fullpath ); } /** * Check if there is an update for a theme available. * * Will display link, if there is an update available. * * @since 2.7.0 * * @see get_theme_update_available() * * @param WP_Theme $theme Theme data object. */ function theme_update_available( $theme ) { echo get_theme_update_available( $theme ); } /** * Retrieves the update link if there is a theme update available. * * Will return a link if there is an update available. * * @since 3.8.0 * * @param WP_Theme $theme WP_Theme object. * @return string|false HTML for the update link, or false if invalid info was passed. */ function get_theme_update_available( $theme ) { static $themes_update = null; if ( ! current_user_can( 'update_themes' ) ) { return false; } if ( ! isset( $themes_update ) ) { $themes_update = get_site_transient( 'update_themes' ); } if ( ! ( $theme instanceof WP_Theme ) ) { return false; } $stylesheet = $theme->get_stylesheet(); $html = ''; if ( isset( $themes_update->response[ $stylesheet ] ) ) { $update = $themes_update->response[ $stylesheet ]; $theme_name = $theme->display( 'Name' ); $details_url = add_query_arg( array( 'TB_iframe' => 'true', 'width' => 1024, 'height' => 800, ), $update['url'] ); // Theme browser inside WP? Replace this. Also, theme preview JS will override this on the available list. $update_url = wp_nonce_url( admin_url( 'update.php?action=upgrade-theme&theme=' . urlencode( $stylesheet ) ), 'upgrade-theme_' . $stylesheet ); if ( ! is_multisite() ) { if ( ! current_user_can( 'update_themes' ) ) { $html = sprintf( /* translators: 1: Theme name, 2: Theme details URL, 3: Additional link attributes, 4: Version number. */ '

' . __( 'There is a new version of %1$s available. View version %4$s details.' ) . '

', $theme_name, esc_url( $details_url ), sprintf( 'class="thickbox open-plugin-details-modal" aria-label="%s"', /* translators: 1: Theme name, 2: Version number. */ esc_attr( sprintf( __( 'View %1$s version %2$s details' ), $theme_name, $update['new_version'] ) ) ), $update['new_version'] ); } elseif ( empty( $update['package'] ) ) { $html = sprintf( /* translators: 1: Theme name, 2: Theme details URL, 3: Additional link attributes, 4: Version number. */ '

' . __( 'There is a new version of %1$s available. View version %4$s details. Automatic update is unavailable for this theme.' ) . '

', $theme_name, esc_url( $details_url ), sprintf( 'class="thickbox open-plugin-details-modal" aria-label="%s"', /* translators: 1: Theme name, 2: Version number. */ esc_attr( sprintf( __( 'View %1$s version %2$s details' ), $theme_name, $update['new_version'] ) ) ), $update['new_version'] ); } else { $html = sprintf( /* translators: 1: Theme name, 2: Theme details URL, 3: Additional link attributes, 4: Version number, 5: Update URL, 6: Additional link attributes. */ '

' . __( 'There is a new version of %1$s available. View version %4$s details or update now.' ) . '

', $theme_name, esc_url( $details_url ), sprintf( 'class="thickbox open-plugin-details-modal" aria-label="%s"', /* translators: 1: Theme name, 2: Version number. */ esc_attr( sprintf( __( 'View %1$s version %2$s details' ), $theme_name, $update['new_version'] ) ) ), $update['new_version'], $update_url, sprintf( 'aria-label="%s" id="update-theme" data-slug="%s"', /* translators: %s: Theme name. */ esc_attr( sprintf( _x( 'Update %s now', 'theme' ), $theme_name ) ), $stylesheet ) ); } } } return $html; } /** * Retrieves list of WordPress theme features (aka theme tags). * * @since 3.1.0 * @since 3.2.0 Added 'Gray' color and 'Featured Image Header', 'Featured Images', * 'Full Width Template', and 'Post Formats' features. * @since 3.5.0 Added 'Flexible Header' feature. * @since 3.8.0 Renamed 'Width' filter to 'Layout'. * @since 3.8.0 Renamed 'Fixed Width' and 'Flexible Width' options * to 'Fixed Layout' and 'Fluid Layout'. * @since 3.8.0 Added 'Accessibility Ready' feature and 'Responsive Layout' option. * @since 3.9.0 Combined 'Layout' and 'Columns' filters. * @since 4.6.0 Removed 'Colors' filter. * @since 4.6.0 Added 'Grid Layout' option. * Removed 'Fixed Layout', 'Fluid Layout', and 'Responsive Layout' options. * @since 4.6.0 Added 'Custom Logo' and 'Footer Widgets' features. * Removed 'Blavatar' feature. * @since 4.6.0 Added 'Blog', 'E-Commerce', 'Education', 'Entertainment', 'Food & Drink', * 'Holiday', 'News', 'Photography', and 'Portfolio' subjects. * Removed 'Photoblogging' and 'Seasonal' subjects. * @since 4.9.0 Reordered the filters from 'Layout', 'Features', 'Subject' * to 'Subject', 'Features', 'Layout'. * @since 4.9.0 Removed 'BuddyPress', 'Custom Menu', 'Flexible Header', * 'Front Page Posting', 'Microformats', 'RTL Language Support', * 'Threaded Comments', and 'Translation Ready' features. * @since 5.5.0 Added 'Block Editor Patterns', 'Block Editor Styles', * and 'Full Site Editing' features. * @since 5.5.0 Added 'Wide Blocks' layout option. * @since 5.8.1 Added 'Template Editing' feature. * @since 6.1.1 Replaced 'Full Site Editing' feature name with 'Site Editor'. * @since 6.2.0 Added 'Style Variations' feature. * * @param bool $api Optional. Whether try to fetch tags from the WordPress.org API. Defaults to true. * @return array Array of features keyed by category with translations keyed by slug. */ function get_theme_feature_list( $api = true ) { // Hard-coded list is used if API is not accessible. $features = array( __( 'Subject' ) => array( 'blog' => __( 'Blog' ), 'e-commerce' => __( 'E-Commerce' ), 'education' => __( 'Education' ), 'entertainment' => __( 'Entertainment' ), 'food-and-drink' => __( 'Food & Drink' ), 'holiday' => __( 'Holiday' ), 'news' => __( 'News' ), 'photography' => __( 'Photography' ), 'portfolio' => __( 'Portfolio' ), ), __( 'Features' ) => array( 'accessibility-ready' => __( 'Accessibility Ready' ), 'block-patterns' => __( 'Block Editor Patterns' ), 'block-styles' => __( 'Block Editor Styles' ), 'custom-background' => __( 'Custom Background' ), 'custom-colors' => __( 'Custom Colors' ), 'custom-header' => __( 'Custom Header' ), 'custom-logo' => __( 'Custom Logo' ), 'editor-style' => __( 'Editor Style' ), 'featured-image-header' => __( 'Featured Image Header' ), 'featured-images' => __( 'Featured Images' ), 'footer-widgets' => __( 'Footer Widgets' ), 'full-site-editing' => __( 'Site Editor' ), 'full-width-template' => __( 'Full Width Template' ), 'post-formats' => __( 'Post Formats' ), 'sticky-post' => __( 'Sticky Post' ), 'style-variations' => __( 'Style Variations' ), 'template-editing' => __( 'Template Editing' ), 'theme-options' => __( 'Theme Options' ), ), __( 'Layout' ) => array( 'grid-layout' => __( 'Grid Layout' ), 'one-column' => __( 'One Column' ), 'two-columns' => __( 'Two Columns' ), 'three-columns' => __( 'Three Columns' ), 'four-columns' => __( 'Four Columns' ), 'left-sidebar' => __( 'Left Sidebar' ), 'right-sidebar' => __( 'Right Sidebar' ), 'wide-blocks' => __( 'Wide Blocks' ), ), ); if ( ! $api || ! current_user_can( 'install_themes' ) ) { return $features; } $feature_list = get_site_transient( 'wporg_theme_feature_list' ); if ( ! $feature_list ) { set_site_transient( 'wporg_theme_feature_list', array(), 3 * HOUR_IN_SECONDS ); } if ( ! $feature_list ) { $feature_list = themes_api( 'feature_list', array() ); if ( is_wp_error( $feature_list ) ) { return $features; } } if ( ! $feature_list ) { return $features; } set_site_transient( 'wporg_theme_feature_list', $feature_list, 3 * HOUR_IN_SECONDS ); $category_translations = array( 'Layout' => __( 'Layout' ), 'Features' => __( 'Features' ), 'Subject' => __( 'Subject' ), ); $wporg_features = array(); // Loop over the wp.org canonical list and apply translations. foreach ( (array) $feature_list as $feature_category => $feature_items ) { if ( isset( $category_translations[ $feature_category ] ) ) { $feature_category = $category_translations[ $feature_category ]; } $wporg_features[ $feature_category ] = array(); foreach ( $feature_items as $feature ) { if ( isset( $features[ $feature_category ][ $feature ] ) ) { $wporg_features[ $feature_category ][ $feature ] = $features[ $feature_category ][ $feature ]; } else { $wporg_features[ $feature_category ][ $feature ] = $feature; } } } return $wporg_features; } /** * Retrieves theme installer pages from the WordPress.org Themes API. * * It is possible for a theme to override the Themes API result with three * filters. Assume this is for themes, which can extend on the Theme Info to * offer more choices. This is very powerful and must be used with care, when * overriding the filters. * * The first filter, {@see 'themes_api_args'}, is for the args and gives the action * as the second parameter. The hook for {@see 'themes_api_args'} must ensure that * an object is returned. * * The second filter, {@see 'themes_api'}, allows a plugin to override the WordPress.org * Theme API entirely. If `$action` is 'query_themes', 'theme_information', or 'feature_list', * an object MUST be passed. If `$action` is 'hot_tags', an array should be passed. * * Finally, the third filter, {@see 'themes_api_result'}, makes it possible to filter the * response object or array, depending on the `$action` type. * * Supported arguments per action: * * | Argument Name | 'query_themes' | 'theme_information' | 'hot_tags' | 'feature_list' | * | -------------------| :------------: | :-----------------: | :--------: | :--------------: | * | `$slug` | No | Yes | No | No | * | `$per_page` | Yes | No | No | No | * | `$page` | Yes | No | No | No | * | `$number` | No | No | Yes | No | * | `$search` | Yes | No | No | No | * | `$tag` | Yes | No | No | No | * | `$author` | Yes | No | No | No | * | `$user` | Yes | No | No | No | * | `$browse` | Yes | No | No | No | * | `$locale` | Yes | Yes | No | No | * | `$fields` | Yes | Yes | No | No | * * @since 2.8.0 * * @param string $action API action to perform: Accepts 'query_themes', 'theme_information', * 'hot_tags' or 'feature_list'. * @param array|object $args { * Optional. Array or object of arguments to serialize for the Themes API. Default empty array. * * @type string $slug The theme slug. Default empty. * @type int $per_page Number of themes per page. Default 24. * @type int $page Number of current page. Default 1. * @type int $number Number of tags to be queried. * @type string $search A search term. Default empty. * @type string $tag Tag to filter themes. Default empty. * @type string $author Username of an author to filter themes. Default empty. * @type string $user Username to query for their favorites. Default empty. * @type string $browse Browse view: 'featured', 'popular', 'updated', 'favorites'. * @type string $locale Locale to provide context-sensitive results. Default is the value of get_locale(). * @type array $fields { * Array of fields which should or should not be returned. * * @type bool $description Whether to return the theme full description. Default false. * @type bool $sections Whether to return the theme readme sections: description, installation, * FAQ, screenshots, other notes, and changelog. Default false. * @type bool $rating Whether to return the rating in percent and total number of ratings. * Default false. * @type bool $ratings Whether to return the number of rating for each star (1-5). Default false. * @type bool $downloaded Whether to return the download count. Default false. * @type bool $downloadlink Whether to return the download link for the package. Default false. * @type bool $last_updated Whether to return the date of the last update. Default false. * @type bool $tags Whether to return the assigned tags. Default false. * @type bool $homepage Whether to return the theme homepage link. Default false. * @type bool $screenshots Whether to return the screenshots. Default false. * @type int $screenshot_count Number of screenshots to return. Default 1. * @type bool $screenshot_url Whether to return the URL of the first screenshot. Default false. * @type bool $photon_screenshots Whether to return the screenshots via Photon. Default false. * @type bool $template Whether to return the slug of the parent theme. Default false. * @type bool $parent Whether to return the slug, name and homepage of the parent theme. Default false. * @type bool $versions Whether to return the list of all available versions. Default false. * @type bool $theme_url Whether to return theme's URL. Default false. * @type bool $extended_author Whether to return nicename or nicename and display name. Default false. * } * } * @return object|array|WP_Error Response object or array on success, WP_Error on failure. See the * {@link https://developer.wordpress.org/reference/functions/themes_api/ function reference article} * for more information on the make-up of possible return objects depending on the value of `$action`. */ function themes_api( $action, $args = array() ) { if ( is_array( $args ) ) { $args = (object) $args; } if ( 'query_themes' === $action ) { if ( ! isset( $args->per_page ) ) { $args->per_page = 24; } } if ( ! isset( $args->locale ) ) { $args->locale = get_user_locale(); } if ( ! isset( $args->wp_version ) ) { $args->wp_version = substr( wp_get_wp_version(), 0, 3 ); // x.y } /** * Filters arguments used to query for installer pages from the WordPress.org Themes API. * * Important: An object MUST be returned to this filter. * * @since 2.8.0 * * @param object $args Arguments used to query for installer pages from the WordPress.org Themes API. * @param string $action Requested action. Likely values are 'theme_information', * 'feature_list', or 'query_themes'. */ $args = apply_filters( 'themes_api_args', $args, $action ); /** * Filters whether to override the WordPress.org Themes API. * * Returning a non-false value will effectively short-circuit the WordPress.org API request. * * If `$action` is 'query_themes', 'theme_information', or 'feature_list', an object MUST * be passed. If `$action` is 'hot_tags', an array should be passed. * * @since 2.8.0 * * @param false|object|array $override Whether to override the WordPress.org Themes API. Default false. * @param string $action Requested action. Likely values are 'theme_information', * 'feature_list', or 'query_themes'. * @param object $args Arguments used to query for installer pages from the Themes API. */ $res = apply_filters( 'themes_api', false, $action, $args ); if ( ! $res ) { $url = 'http://api.wordpress.org/themes/info/1.2/'; $url = add_query_arg( array( 'action' => $action, 'request' => $args, ), $url ); $http_url = $url; $ssl = wp_http_supports( array( 'ssl' ) ); if ( $ssl ) { $url = set_url_scheme( $url, 'https' ); } $http_args = array( 'timeout' => 15, 'user-agent' => 'WordPress/' . wp_get_wp_version() . '; ' . home_url( '/' ), ); $request = wp_remote_get( $url, $http_args ); if ( $ssl && is_wp_error( $request ) ) { if ( ! wp_doing_ajax() ) { wp_trigger_error( __FUNCTION__, 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 ); } $request = wp_remote_get( $http_url, $http_args ); } if ( is_wp_error( $request ) ) { $res = new WP_Error( 'themes_api_failed', 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/' ) ), $request->get_error_message() ); } else { $res = json_decode( wp_remote_retrieve_body( $request ), true ); if ( is_array( $res ) ) { // Object casting is required in order to match the info/1.0 format. $res = (object) $res; } elseif ( null === $res ) { $res = new WP_Error( 'themes_api_failed', 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/' ) ), wp_remote_retrieve_body( $request ) ); } if ( isset( $res->error ) ) { $res = new WP_Error( 'themes_api_failed', $res->error ); } } if ( ! is_wp_error( $res ) ) { // Back-compat for info/1.2 API, upgrade the theme objects in query_themes to objects. if ( 'query_themes' === $action ) { foreach ( $res->themes as $i => $theme ) { $res->themes[ $i ] = (object) $theme; } } // Back-compat for info/1.2 API, downgrade the feature_list result back to an array. if ( 'feature_list' === $action ) { $res = (array) $res; } } } /** * Filters the returned WordPress.org Themes API response. * * @since 2.8.0 * * @param array|stdClass|WP_Error $res WordPress.org Themes API response. * @param string $action Requested action. Likely values are 'theme_information', * 'feature_list', or 'query_themes'. * @param stdClass $args Arguments used to query for installer pages from the WordPress.org Themes API. */ return apply_filters( 'themes_api_result', $res, $action, $args ); } /** * Prepares themes for JavaScript. * * @since 3.8.0 * * @param WP_Theme[] $themes Optional. Array of theme objects to prepare. * Defaults to all allowed themes. * * @return array An associative array of theme data, sorted by name. */ function wp_prepare_themes_for_js( $themes = null ) { $current_theme = get_stylesheet(); /** * Filters theme data before it is prepared for JavaScript. * * Passing a non-empty array will result in wp_prepare_themes_for_js() returning * early with that value instead. * * @since 4.2.0 * * @param array $prepared_themes An associative array of theme data. Default empty array. * @param WP_Theme[]|null $themes An array of theme objects to prepare, if any. * @param string $current_theme The active theme slug. */ $prepared_themes = (array) apply_filters( 'pre_prepare_themes_for_js', array(), $themes, $current_theme ); if ( ! empty( $prepared_themes ) ) { return $prepared_themes; } // Make sure the active theme is listed first. $prepared_themes[ $current_theme ] = array(); if ( null === $themes ) { $themes = wp_get_themes( array( 'allowed' => true ) ); if ( ! isset( $themes[ $current_theme ] ) ) { $themes[ $current_theme ] = wp_get_theme(); } } $updates = array(); $no_updates = array(); if ( ! is_multisite() && current_user_can( 'update_themes' ) ) { $updates_transient = get_site_transient( 'update_themes' ); if ( isset( $updates_transient->response ) ) { $updates = $updates_transient->response; } if ( isset( $updates_transient->no_update ) ) { $no_updates = $updates_transient->no_update; } } WP_Theme::sort_by_name( $themes ); $parents = array(); $auto_updates = (array) get_site_option( 'auto_update_themes', array() ); foreach ( $themes as $theme ) { $slug = $theme->get_stylesheet(); $encoded_slug = urlencode( $slug ); $parent = false; if ( $theme->parent() ) { $parent = $theme->parent(); $parents[ $slug ] = $parent->get_stylesheet(); $parent = $parent->display( 'Name' ); } $customize_action = null; $can_edit_theme_options = current_user_can( 'edit_theme_options' ); $can_customize = current_user_can( 'customize' ); $is_block_theme = $theme->is_block_theme(); if ( $is_block_theme && $can_edit_theme_options ) { $customize_action = admin_url( 'site-editor.php' ); if ( $current_theme !== $slug ) { $customize_action = add_query_arg( 'wp_theme_preview', $slug, $customize_action ); } } elseif ( ! $is_block_theme && $can_customize && $can_edit_theme_options ) { $customize_action = wp_customize_url( $slug ); } if ( null !== $customize_action ) { $customize_action = add_query_arg( array( 'return' => urlencode( sanitize_url( remove_query_arg( wp_removable_query_args(), wp_unslash( $_SERVER['REQUEST_URI'] ) ) ) ), ), $customize_action ); $customize_action = esc_url( $customize_action ); } $update_requires_wp = isset( $updates[ $slug ]['requires'] ) ? $updates[ $slug ]['requires'] : null; $update_requires_php = isset( $updates[ $slug ]['requires_php'] ) ? $updates[ $slug ]['requires_php'] : null; $auto_update = in_array( $slug, $auto_updates, true ); $auto_update_action = $auto_update ? 'disable-auto-update' : 'enable-auto-update'; if ( isset( $updates[ $slug ] ) ) { $auto_update_supported = true; $auto_update_filter_payload = (object) $updates[ $slug ]; } elseif ( isset( $no_updates[ $slug ] ) ) { $auto_update_supported = true; $auto_update_filter_payload = (object) $no_updates[ $slug ]; } else { $auto_update_supported = false; /* * Create the expected payload for the auto_update_theme filter, this is the same data * as contained within $updates or $no_updates but used when the Theme is not known. */ $auto_update_filter_payload = (object) array( 'theme' => $slug, 'new_version' => $theme->get( 'Version' ), 'url' => '', 'package' => '', 'requires' => $theme->get( 'RequiresWP' ), 'requires_php' => $theme->get( 'RequiresPHP' ), ); } $auto_update_forced = wp_is_auto_update_forced_for_item( 'theme', null, $auto_update_filter_payload ); $prepared_themes[ $slug ] = array( 'id' => $slug, 'name' => $theme->display( 'Name' ), 'screenshot' => array( $theme->get_screenshot() ), // @todo Multiple screenshots. 'description' => $theme->display( 'Description' ), 'author' => $theme->display( 'Author', false, true ), 'authorAndUri' => $theme->display( 'Author' ), 'tags' => $theme->display( 'Tags' ), 'version' => $theme->get( 'Version' ), 'compatibleWP' => is_wp_version_compatible( $theme->get( 'RequiresWP' ) ), 'compatiblePHP' => is_php_version_compatible( $theme->get( 'RequiresPHP' ) ), 'updateResponse' => array( 'compatibleWP' => is_wp_version_compatible( $update_requires_wp ), 'compatiblePHP' => is_php_version_compatible( $update_requires_php ), ), 'parent' => $parent, 'active' => $slug === $current_theme, 'hasUpdate' => isset( $updates[ $slug ] ), 'hasPackage' => isset( $updates[ $slug ] ) && ! empty( $updates[ $slug ]['package'] ), 'update' => get_theme_update_available( $theme ), 'autoupdate' => array( 'enabled' => $auto_update || $auto_update_forced, 'supported' => $auto_update_supported, 'forced' => $auto_update_forced, ), 'actions' => array( 'activate' => current_user_can( 'switch_themes' ) ? wp_nonce_url( admin_url( 'themes.php?action=activate&stylesheet=' . $encoded_slug ), 'switch-theme_' . $slug ) : null, 'customize' => $customize_action, 'delete' => ( ! is_multisite() && current_user_can( 'delete_themes' ) ) ? wp_nonce_url( admin_url( 'themes.php?action=delete&stylesheet=' . $encoded_slug ), 'delete-theme_' . $slug ) : null, 'autoupdate' => wp_is_auto_update_enabled_for_type( 'theme' ) && ! is_multisite() && current_user_can( 'update_themes' ) ? wp_nonce_url( admin_url( 'themes.php?action=' . $auto_update_action . '&stylesheet=' . $encoded_slug ), 'updates' ) : null, ), 'blockTheme' => $theme->is_block_theme(), ); } // Remove 'delete' action if theme has an active child. if ( ! empty( $parents ) && array_key_exists( $current_theme, $parents ) ) { unset( $prepared_themes[ $parents[ $current_theme ] ]['actions']['delete'] ); } /** * Filters the themes prepared for JavaScript, for themes.php. * * Could be useful for changing the order, which is by name by default. * * @since 3.8.0 * * @param array $prepared_themes Array of theme data. */ $prepared_themes = apply_filters( 'wp_prepare_themes_for_js', $prepared_themes ); $prepared_themes = array_values( $prepared_themes ); return array_filter( $prepared_themes ); } /** * Prints JS templates for the theme-browsing UI in the Customizer. * * @since 4.2.0 */ function customize_themes_print_templates() { ?> delete( $extension ); if ( ! $result ) { return new WP_Error( 'could_not_resume_theme', __( 'Could not resume the theme.' ) ); } return true; } /** * Renders an admin notice in case some themes have been paused due to errors. * * @since 5.2.0 * * @global string $pagenow The filename of the current screen. * @global WP_Paused_Extensions_Storage $_paused_themes */ function paused_themes_notice() { if ( 'themes.php' === $GLOBALS['pagenow'] ) { return; } if ( ! current_user_can( 'resume_themes' ) ) { return; } if ( ! isset( $GLOBALS['_paused_themes'] ) || empty( $GLOBALS['_paused_themes'] ) ) { return; } $message = sprintf( '

%s
%s

%s

', __( 'One or more themes failed to load properly.' ), __( 'You can find more details and make changes on the Themes screen.' ), esc_url( admin_url( 'themes.php' ) ), __( 'Go to the Themes screen' ) ); wp_admin_notice( $message, array( 'type' => 'error', 'paragraph_wrap' => false, ) ); } class-custom-background.php000064400000052163147206365750012035 0ustar00admin_header_callback = $admin_header_callback; $this->admin_image_div_callback = $admin_image_div_callback; add_action( 'admin_menu', array( $this, 'init' ) ); add_action( 'wp_ajax_custom-background-add', array( $this, 'ajax_background_add' ) ); // Unused since 3.5.0. add_action( 'wp_ajax_set-background-image', array( $this, 'wp_set_background_image' ) ); } /** * Sets up the hooks for the Custom Background admin page. * * @since 3.0.0 */ public function init() { $page = add_theme_page( _x( 'Background', 'custom background' ), _x( 'Background', 'custom background' ), 'edit_theme_options', 'custom-background', array( $this, 'admin_page' ) ); if ( ! $page ) { return; } add_action( "load-{$page}", array( $this, 'admin_load' ) ); add_action( "load-{$page}", array( $this, 'take_action' ), 49 ); add_action( "load-{$page}", array( $this, 'handle_upload' ), 49 ); if ( $this->admin_header_callback ) { add_action( "admin_head-{$page}", $this->admin_header_callback, 51 ); } } /** * Sets up the enqueue for the CSS & JavaScript files. * * @since 3.0.0 */ public function admin_load() { get_current_screen()->add_help_tab( array( 'id' => 'overview', 'title' => __( 'Overview' ), 'content' => '

' . __( 'You can customize the look of your site without touching any of your theme’s code by using a custom background. Your background can be an image or a color.' ) . '

' . '

' . __( 'To use a background image, simply upload it or choose an image that has already been uploaded to your Media Library by clicking the “Choose Image” button. You can display a single instance of your image, or tile it to fill the screen. You can have your background fixed in place, so your site content moves on top of it, or you can have it scroll with your site.' ) . '

' . '

' . __( 'You can also choose a background color by clicking the Select Color button and either typing in a legitimate HTML hex value, e.g. “#ff0000” for red, or by choosing a color using the color picker.' ) . '

' . '

' . __( 'Do not forget to click on the Save Changes button when you are finished.' ) . '

', ) ); get_current_screen()->set_help_sidebar( '

' . __( 'For more information:' ) . '

' . '

' . __( 'Documentation on Custom Background' ) . '

' . '

' . __( 'Support forums' ) . '

' ); wp_enqueue_media(); wp_enqueue_script( 'custom-background' ); wp_enqueue_style( 'wp-color-picker' ); } /** * Executes custom background modification. * * @since 3.0.0 */ public function take_action() { if ( empty( $_POST ) ) { return; } if ( isset( $_POST['reset-background'] ) ) { check_admin_referer( 'custom-background-reset', '_wpnonce-custom-background-reset' ); remove_theme_mod( 'background_image' ); remove_theme_mod( 'background_image_thumb' ); $this->updated = true; return; } if ( isset( $_POST['remove-background'] ) ) { // @todo Uploaded files are not removed here. check_admin_referer( 'custom-background-remove', '_wpnonce-custom-background-remove' ); set_theme_mod( 'background_image', '' ); set_theme_mod( 'background_image_thumb', '' ); $this->updated = true; wp_safe_redirect( $_POST['_wp_http_referer'] ); return; } if ( isset( $_POST['background-preset'] ) ) { check_admin_referer( 'custom-background' ); if ( in_array( $_POST['background-preset'], array( 'default', 'fill', 'fit', 'repeat', 'custom' ), true ) ) { $preset = $_POST['background-preset']; } else { $preset = 'default'; } set_theme_mod( 'background_preset', $preset ); } if ( isset( $_POST['background-position'] ) ) { check_admin_referer( 'custom-background' ); $position = explode( ' ', $_POST['background-position'] ); if ( in_array( $position[0], array( 'left', 'center', 'right' ), true ) ) { $position_x = $position[0]; } else { $position_x = 'left'; } if ( in_array( $position[1], array( 'top', 'center', 'bottom' ), true ) ) { $position_y = $position[1]; } else { $position_y = 'top'; } set_theme_mod( 'background_position_x', $position_x ); set_theme_mod( 'background_position_y', $position_y ); } if ( isset( $_POST['background-size'] ) ) { check_admin_referer( 'custom-background' ); if ( in_array( $_POST['background-size'], array( 'auto', 'contain', 'cover' ), true ) ) { $size = $_POST['background-size']; } else { $size = 'auto'; } set_theme_mod( 'background_size', $size ); } if ( isset( $_POST['background-repeat'] ) ) { check_admin_referer( 'custom-background' ); $repeat = $_POST['background-repeat']; if ( 'no-repeat' !== $repeat ) { $repeat = 'repeat'; } set_theme_mod( 'background_repeat', $repeat ); } if ( isset( $_POST['background-attachment'] ) ) { check_admin_referer( 'custom-background' ); $attachment = $_POST['background-attachment']; if ( 'fixed' !== $attachment ) { $attachment = 'scroll'; } set_theme_mod( 'background_attachment', $attachment ); } if ( isset( $_POST['background-color'] ) ) { check_admin_referer( 'custom-background' ); $color = preg_replace( '/[^0-9a-fA-F]/', '', $_POST['background-color'] ); if ( strlen( $color ) === 6 || strlen( $color ) === 3 ) { set_theme_mod( 'background_color', $color ); } else { set_theme_mod( 'background_color', '' ); } } $this->updated = true; } /** * Displays the custom background page. * * @since 3.0.0 */ public function admin_page() { ?>

Customizer.' ), admin_url( 'customize.php?autofocus[control]=background_image' ) ); wp_admin_notice( $message, array( 'type' => 'info', 'additional_classes' => array( 'hide-if-no-customize' ), ) ); } if ( ! empty( $this->updated ) ) { $updated_message = sprintf( /* translators: %s: Home URL. */ __( 'Background updated. Visit your site to see how it looks.' ), esc_url( home_url( '/' ) ) ); wp_admin_notice( $updated_message, array( 'id' => 'message', 'additional_classes' => array( 'updated' ), ) ); } ?>

array( 'label' => __( 'Top Left' ), 'icon' => 'dashicons dashicons-arrow-left-alt', ), 'center top' => array( 'label' => __( 'Top' ), 'icon' => 'dashicons dashicons-arrow-up-alt', ), 'right top' => array( 'label' => __( 'Top Right' ), 'icon' => 'dashicons dashicons-arrow-right-alt', ), ), array( 'left center' => array( 'label' => __( 'Left' ), 'icon' => 'dashicons dashicons-arrow-left-alt', ), 'center center' => array( 'label' => __( 'Center' ), 'icon' => 'background-position-center-icon', ), 'right center' => array( 'label' => __( 'Right' ), 'icon' => 'dashicons dashicons-arrow-right-alt', ), ), array( 'left bottom' => array( 'label' => __( 'Bottom Left' ), 'icon' => 'dashicons dashicons-arrow-left-alt', ), 'center bottom' => array( 'label' => __( 'Bottom' ), 'icon' => 'dashicons dashicons-arrow-down-alt', ), 'right bottom' => array( 'label' => __( 'Bottom Right' ), 'icon' => 'dashicons dashicons-arrow-right-alt', ), ), ); ?>
false ); $uploaded_file = $_FILES['import']; $wp_filetype = wp_check_filetype_and_ext( $uploaded_file['tmp_name'], $uploaded_file['name'] ); if ( ! wp_match_mime_types( 'image', $wp_filetype['type'] ) ) { wp_die( __( 'The uploaded file is not a valid image. Please try again.' ) ); } $file = wp_handle_upload( $uploaded_file, $overrides ); if ( isset( $file['error'] ) ) { wp_die( $file['error'] ); } $url = $file['url']; $type = $file['type']; $file = $file['file']; $filename = wp_basename( $file ); // Construct the attachment array. $attachment = array( 'post_title' => $filename, 'post_content' => $url, 'post_mime_type' => $type, 'guid' => $url, 'context' => 'custom-background', ); // Save the data. $id = wp_insert_attachment( $attachment, $file ); // Add the metadata. wp_update_attachment_metadata( $id, wp_generate_attachment_metadata( $id, $file ) ); update_post_meta( $id, '_wp_attachment_is_custom_background', get_option( 'stylesheet' ) ); set_theme_mod( 'background_image', sanitize_url( $url ) ); $thumbnail = wp_get_attachment_image_src( $id, 'thumbnail' ); set_theme_mod( 'background_image_thumb', sanitize_url( $thumbnail[0] ) ); /** This filter is documented in wp-admin/includes/class-custom-image-header.php */ $file = apply_filters( 'wp_create_file_in_uploads', $file, $id ); // For replication. $this->updated = true; } /** * Handles Ajax request for adding custom background context to an attachment. * * Triggers when the user adds a new background image from the * Media Manager. * * @since 4.1.0 */ public function ajax_background_add() { check_ajax_referer( 'background-add', 'nonce' ); if ( ! current_user_can( 'edit_theme_options' ) ) { wp_send_json_error(); } $attachment_id = absint( $_POST['attachment_id'] ); if ( $attachment_id < 1 ) { wp_send_json_error(); } update_post_meta( $attachment_id, '_wp_attachment_is_custom_background', get_stylesheet() ); wp_send_json_success(); } /** * @since 3.4.0 * @deprecated 3.5.0 * * @param array $form_fields * @return array $form_fields */ public function attachment_fields_to_edit( $form_fields ) { return $form_fields; } /** * @since 3.4.0 * @deprecated 3.5.0 * * @param array $tabs * @return array $tabs */ public function filter_upload_tabs( $tabs ) { return $tabs; } /** * @since 3.4.0 * @deprecated 3.5.0 */ public function wp_set_background_image() { check_ajax_referer( 'custom-background' ); if ( ! current_user_can( 'edit_theme_options' ) || ! isset( $_POST['attachment_id'] ) ) { exit; } $attachment_id = absint( $_POST['attachment_id'] ); $sizes = array_keys( /** This filter is documented in wp-admin/includes/media.php */ apply_filters( 'image_size_names_choose', array( 'thumbnail' => __( 'Thumbnail' ), 'medium' => __( 'Medium' ), 'large' => __( 'Large' ), 'full' => __( 'Full Size' ), ) ) ); $size = 'thumbnail'; if ( in_array( $_POST['size'], $sizes, true ) ) { $size = esc_attr( $_POST['size'] ); } update_post_meta( $attachment_id, '_wp_attachment_is_custom_background', get_option( 'stylesheet' ) ); $url = wp_get_attachment_image_src( $attachment_id, $size ); $thumbnail = wp_get_attachment_image_src( $attachment_id, 'thumbnail' ); set_theme_mod( 'background_image', sanitize_url( $url[0] ) ); set_theme_mod( 'background_image_thumb', sanitize_url( $thumbnail[0] ) ); exit; } } class-wp-internal-pointers.php000064400000010741147206365750012503 0ustar00 pointer callback * ) * * Example: * array( * 'themes.php' => 'wp390_widgets' * ) */ $registered_pointers = array( // None currently. ); // Check if screen related pointer is registered. if ( empty( $registered_pointers[ $hook_suffix ] ) ) { return; } $pointers = (array) $registered_pointers[ $hook_suffix ]; /* * Specify required capabilities for feature pointers * * Format: * array( * pointer callback => Array of required capabilities * ) * * Example: * array( * 'wp390_widgets' => array( 'edit_theme_options' ) * ) */ $caps_required = array( // None currently. ); // Get dismissed pointers. $dismissed = explode( ',', (string) get_user_meta( get_current_user_id(), 'dismissed_wp_pointers', true ) ); $got_pointers = false; foreach ( array_diff( $pointers, $dismissed ) as $pointer ) { if ( isset( $caps_required[ $pointer ] ) ) { foreach ( $caps_required[ $pointer ] as $cap ) { if ( ! current_user_can( $cap ) ) { continue 2; } } } // Bind pointer print function. add_action( 'admin_print_footer_scripts', array( 'WP_Internal_Pointers', 'pointer_' . $pointer ) ); $got_pointers = true; } if ( ! $got_pointers ) { return; } // Add pointers script and style to queue. wp_enqueue_style( 'wp-pointer' ); wp_enqueue_script( 'wp-pointer' ); } /** * Prints the pointer JavaScript data. * * @since 3.3.0 * * @param string $pointer_id The pointer ID. * @param string $selector The HTML elements, on which the pointer should be attached. * @param array $args Arguments to be passed to the pointer JS (see wp-pointer.js). */ private static function print_js( $pointer_id, $selector, $args ) { if ( empty( $pointer_id ) || empty( $selector ) || empty( $args ) || empty( $args['content'] ) ) { return; } ?> admin_header_callback = $admin_header_callback; $this->admin_image_div_callback = $admin_image_div_callback; add_action( 'admin_menu', array( $this, 'init' ) ); add_action( 'customize_save_after', array( $this, 'customize_set_last_used' ) ); add_action( 'wp_ajax_custom-header-crop', array( $this, 'ajax_header_crop' ) ); add_action( 'wp_ajax_custom-header-add', array( $this, 'ajax_header_add' ) ); add_action( 'wp_ajax_custom-header-remove', array( $this, 'ajax_header_remove' ) ); } /** * Sets up the hooks for the Custom Header admin page. * * @since 2.1.0 */ public function init() { $page = add_theme_page( _x( 'Header', 'custom image header' ), _x( 'Header', 'custom image header' ), 'edit_theme_options', 'custom-header', array( $this, 'admin_page' ) ); if ( ! $page ) { return; } add_action( "admin_print_scripts-{$page}", array( $this, 'js_includes' ) ); add_action( "admin_print_styles-{$page}", array( $this, 'css_includes' ) ); add_action( "admin_head-{$page}", array( $this, 'help' ) ); add_action( "admin_head-{$page}", array( $this, 'take_action' ), 50 ); add_action( "admin_head-{$page}", array( $this, 'js' ), 50 ); if ( $this->admin_header_callback ) { add_action( "admin_head-{$page}", $this->admin_header_callback, 51 ); } } /** * Adds contextual help. * * @since 3.0.0 */ public function help() { get_current_screen()->add_help_tab( array( 'id' => 'overview', 'title' => __( 'Overview' ), 'content' => '

' . __( 'This screen is used to customize the header section of your theme.' ) . '

' . '

' . __( 'You can choose from the theme’s default header images, or use one of your own. You can also customize how your Site Title and Tagline are displayed.' ) . '

', ) ); get_current_screen()->add_help_tab( array( 'id' => 'set-header-image', 'title' => __( 'Header Image' ), 'content' => '

' . __( 'You can set a custom image header for your site. Simply upload the image and crop it, and the new header will go live immediately. Alternatively, you can use an image that has already been uploaded to your Media Library by clicking the “Choose Image” button.' ) . '

' . '

' . __( 'Some themes come with additional header images bundled. If you see multiple images displayed, select the one you would like and click the “Save Changes” button.' ) . '

' . '

' . __( 'If your theme has more than one default header image, or you have uploaded more than one custom header image, you have the option of having WordPress display a randomly different image on each page of your site. Click the “Random” radio button next to the Uploaded Images or Default Images section to enable this feature.' ) . '

' . '

' . __( 'If you do not want a header image to be displayed on your site at all, click the “Remove Header Image” button at the bottom of the Header Image section of this page. If you want to re-enable the header image later, you just have to select one of the other image options and click “Save Changes”.' ) . '

', ) ); get_current_screen()->add_help_tab( array( 'id' => 'set-header-text', 'title' => __( 'Header Text' ), 'content' => '

' . sprintf( /* translators: %s: URL to General Settings screen. */ __( 'For most themes, the header text is your Site Title and Tagline, as defined in the General Settings section.' ), admin_url( 'options-general.php' ) ) . '

' . '

' . __( 'In the Header Text section of this page, you can choose whether to display this text or hide it. You can also choose a color for the text by clicking the Select Color button and either typing in a legitimate HTML hex value, e.g. “#ff0000” for red, or by choosing a color using the color picker.' ) . '

' . '

' . __( 'Do not forget to click “Save Changes” when you are done!' ) . '

', ) ); get_current_screen()->set_help_sidebar( '

' . __( 'For more information:' ) . '

' . '

' . __( 'Documentation on Custom Header' ) . '

' . '

' . __( 'Support forums' ) . '

' ); } /** * Gets the current step. * * @since 2.6.0 * * @return int Current step. */ public function step() { if ( ! isset( $_GET['step'] ) ) { return 1; } $step = (int) $_GET['step']; if ( $step < 1 || 3 < $step || ( 2 === $step && ! wp_verify_nonce( $_REQUEST['_wpnonce-custom-header-upload'], 'custom-header-upload' ) ) || ( 3 === $step && ! wp_verify_nonce( $_REQUEST['_wpnonce'], 'custom-header-crop-image' ) ) ) { return 1; } return $step; } /** * Sets up the enqueue for the JavaScript files. * * @since 2.1.0 */ public function js_includes() { $step = $this->step(); if ( ( 1 === $step || 3 === $step ) ) { wp_enqueue_media(); wp_enqueue_script( 'custom-header' ); if ( current_theme_supports( 'custom-header', 'header-text' ) ) { wp_enqueue_script( 'wp-color-picker' ); } } elseif ( 2 === $step ) { wp_enqueue_script( 'imgareaselect' ); } } /** * Sets up the enqueue for the CSS files. * * @since 2.7.0 */ public function css_includes() { $step = $this->step(); if ( ( 1 === $step || 3 === $step ) && current_theme_supports( 'custom-header', 'header-text' ) ) { wp_enqueue_style( 'wp-color-picker' ); } elseif ( 2 === $step ) { wp_enqueue_style( 'imgareaselect' ); } } /** * Executes custom header modification. * * @since 2.6.0 */ public function take_action() { if ( ! current_user_can( 'edit_theme_options' ) ) { return; } if ( empty( $_POST ) ) { return; } $this->updated = true; if ( isset( $_POST['resetheader'] ) ) { check_admin_referer( 'custom-header-options', '_wpnonce-custom-header-options' ); $this->reset_header_image(); return; } if ( isset( $_POST['removeheader'] ) ) { check_admin_referer( 'custom-header-options', '_wpnonce-custom-header-options' ); $this->remove_header_image(); return; } if ( isset( $_POST['text-color'] ) && ! isset( $_POST['display-header-text'] ) ) { check_admin_referer( 'custom-header-options', '_wpnonce-custom-header-options' ); set_theme_mod( 'header_textcolor', 'blank' ); } elseif ( isset( $_POST['text-color'] ) ) { check_admin_referer( 'custom-header-options', '_wpnonce-custom-header-options' ); $_POST['text-color'] = str_replace( '#', '', $_POST['text-color'] ); $color = preg_replace( '/[^0-9a-fA-F]/', '', $_POST['text-color'] ); if ( strlen( $color ) === 6 || strlen( $color ) === 3 ) { set_theme_mod( 'header_textcolor', $color ); } elseif ( ! $color ) { set_theme_mod( 'header_textcolor', 'blank' ); } } if ( isset( $_POST['default-header'] ) ) { check_admin_referer( 'custom-header-options', '_wpnonce-custom-header-options' ); $this->set_header_image( $_POST['default-header'] ); return; } } /** * Processes the default headers. * * @since 3.0.0 * * @global array $_wp_default_headers */ public function process_default_headers() { global $_wp_default_headers; if ( ! isset( $_wp_default_headers ) ) { return; } if ( ! empty( $this->default_headers ) ) { return; } $this->default_headers = $_wp_default_headers; $template_directory_uri = get_template_directory_uri(); $stylesheet_directory_uri = get_stylesheet_directory_uri(); foreach ( array_keys( $this->default_headers ) as $header ) { $this->default_headers[ $header ]['url'] = sprintf( $this->default_headers[ $header ]['url'], $template_directory_uri, $stylesheet_directory_uri ); $this->default_headers[ $header ]['thumbnail_url'] = sprintf( $this->default_headers[ $header ]['thumbnail_url'], $template_directory_uri, $stylesheet_directory_uri ); } } /** * Displays UI for selecting one of several default headers. * * Shows the random image option if this theme has multiple header images. * Random image option is on by default if no header has been set. * * @since 3.0.0 * * @param string $type The header type. One of 'default' (for the Uploaded Images control) * or 'uploaded' (for the Uploaded Images control). */ public function show_header_selector( $type = 'default' ) { if ( 'default' === $type ) { $headers = $this->default_headers; } else { $headers = get_uploaded_header_images(); $type = 'uploaded'; } if ( 1 < count( $headers ) ) { echo '
'; echo ''; echo '
'; } echo '
'; foreach ( $headers as $header_key => $header ) { $header_thumbnail = $header['thumbnail_url']; $header_url = $header['url']; $header_alt_text = empty( $header['alt_text'] ) ? '' : $header['alt_text']; echo '
'; echo ''; echo '
'; } echo '
'; } /** * Executes JavaScript depending on step. * * @since 2.1.0 */ public function js() { $step = $this->step(); if ( ( 1 === $step || 3 === $step ) && current_theme_supports( 'custom-header', 'header-text' ) ) { $this->js_1(); } elseif ( 2 === $step ) { $this->js_2(); } } /** * Displays JavaScript based on Step 1 and 3. * * @since 2.6.0 */ public function js_1() { $default_color = ''; if ( current_theme_supports( 'custom-header', 'default-text-color' ) ) { $default_color = get_theme_support( 'custom-header', 'default-text-color' ); if ( $default_color && ! str_contains( $default_color, '#' ) ) { $default_color = '#' . $default_color; } } ?> process_default_headers(); ?>

Customizer.' ), admin_url( 'customize.php?autofocus[control]=header_image' ) ); wp_admin_notice( $message, array( 'type' => 'info', 'additional_classes' => array( 'hide-if-no-customize' ), ) ); } if ( ! empty( $this->updated ) ) { $updated_message = sprintf( /* translators: %s: Home URL. */ __( 'Header updated. Visit your site to see how it looks.' ), esc_url( home_url( '/' ) ) ); wp_admin_notice( $updated_message, array( 'id' => 'message', 'additional_classes' => array( 'updated' ), ) ); } ?>

default_headers ) ) : ?>

' . __( 'Something went wrong.' ) . '' . '

' . __( 'The active theme does not support uploading a custom header image.' ) . '

', 403 ); } if ( empty( $_POST ) && isset( $_GET['file'] ) ) { $attachment_id = absint( $_GET['file'] ); $file = get_attached_file( $attachment_id, true ); $url = wp_get_attachment_image_src( $attachment_id, 'full' ); $url = $url[0]; } elseif ( isset( $_POST ) ) { $data = $this->step_2_manage_upload(); $attachment_id = $data['attachment_id']; $file = $data['file']; $url = $data['url']; } if ( file_exists( $file ) ) { list( $width, $height, $type, $attr ) = wp_getimagesize( $file ); } else { $data = wp_get_attachment_metadata( $attachment_id ); $height = isset( $data['height'] ) ? (int) $data['height'] : 0; $width = isset( $data['width'] ) ? (int) $data['width'] : 0; unset( $data ); } $max_width = 0; // For flex, limit size of image displayed to 1500px unless theme says otherwise. if ( current_theme_supports( 'custom-header', 'flex-width' ) ) { $max_width = 1500; } if ( current_theme_supports( 'custom-header', 'max-width' ) ) { $max_width = max( $max_width, get_theme_support( 'custom-header', 'max-width' ) ); } $max_width = max( $max_width, get_theme_support( 'custom-header', 'width' ) ); // If flexible height isn't supported and the image is the exact right size. if ( ! current_theme_supports( 'custom-header', 'flex-height' ) && ! current_theme_supports( 'custom-header', 'flex-width' ) && (int) get_theme_support( 'custom-header', 'width' ) === $width && (int) get_theme_support( 'custom-header', 'height' ) === $height ) { // Add the metadata. if ( file_exists( $file ) ) { wp_update_attachment_metadata( $attachment_id, wp_generate_attachment_metadata( $attachment_id, $file ) ); } $this->set_header_image( compact( 'url', 'attachment_id', 'width', 'height' ) ); /** * Filters the attachment file path after the custom header or background image is set. * * Used for file replication. * * @since 2.1.0 * * @param string $file Path to the file. * @param int $attachment_id Attachment ID. */ $file = apply_filters( 'wp_create_file_in_uploads', $file, $attachment_id ); // For replication. return $this->finished(); } elseif ( $width > $max_width ) { $oitar = $width / $max_width; $image = wp_crop_image( $attachment_id, 0, 0, $width, $height, $max_width, $height / $oitar, false, str_replace( wp_basename( $file ), 'midsize-' . wp_basename( $file ), $file ) ); if ( ! $image || is_wp_error( $image ) ) { wp_die( __( 'Image could not be processed. Please go back and try again.' ), __( 'Image Processing Error' ) ); } /** This filter is documented in wp-admin/includes/class-custom-image-header.php */ $image = apply_filters( 'wp_create_file_in_uploads', $image, $attachment_id ); // For replication. $url = str_replace( wp_basename( $url ), wp_basename( $image ), $url ); $width = $width / $oitar; $height = $height / $oitar; } else { $oitar = 1; } ?>

false ); $uploaded_file = $_FILES['import']; $wp_filetype = wp_check_filetype_and_ext( $uploaded_file['tmp_name'], $uploaded_file['name'] ); if ( ! wp_match_mime_types( 'image', $wp_filetype['type'] ) ) { wp_die( __( 'The uploaded file is not a valid image. Please try again.' ) ); } $file = wp_handle_upload( $uploaded_file, $overrides ); if ( isset( $file['error'] ) ) { wp_die( $file['error'], __( 'Image Upload Error' ) ); } $url = $file['url']; $type = $file['type']; $file = $file['file']; $filename = wp_basename( $file ); // Construct the attachment array. $attachment = array( 'post_title' => $filename, 'post_content' => $url, 'post_mime_type' => $type, 'guid' => $url, 'context' => 'custom-header', ); // Save the data. $attachment_id = wp_insert_attachment( $attachment, $file ); return compact( 'attachment_id', 'file', 'filename', 'url', 'type' ); } /** * Displays third step of custom header image page. * * @since 2.1.0 * @since 4.4.0 Switched to using wp_get_attachment_url() instead of the guid * for retrieving the header image URL. */ public function step_3() { check_admin_referer( 'custom-header-crop-image' ); if ( ! current_theme_supports( 'custom-header', 'uploads' ) ) { wp_die( '

' . __( 'Something went wrong.' ) . '

' . '

' . __( 'The active theme does not support uploading a custom header image.' ) . '

', 403 ); } if ( ! empty( $_POST['skip-cropping'] ) && ! current_theme_supports( 'custom-header', 'flex-height' ) && ! current_theme_supports( 'custom-header', 'flex-width' ) ) { wp_die( '

' . __( 'Something went wrong.' ) . '

' . '

' . __( 'The active theme does not support a flexible sized header image.' ) . '

', 403 ); } if ( $_POST['oitar'] > 1 ) { $_POST['x1'] = $_POST['x1'] * $_POST['oitar']; $_POST['y1'] = $_POST['y1'] * $_POST['oitar']; $_POST['width'] = $_POST['width'] * $_POST['oitar']; $_POST['height'] = $_POST['height'] * $_POST['oitar']; } $attachment_id = absint( $_POST['attachment_id'] ); $original = get_attached_file( $attachment_id ); $dimensions = $this->get_header_dimensions( array( 'height' => $_POST['height'], 'width' => $_POST['width'], ) ); $height = $dimensions['dst_height']; $width = $dimensions['dst_width']; if ( empty( $_POST['skip-cropping'] ) ) { $cropped = wp_crop_image( $attachment_id, (int) $_POST['x1'], (int) $_POST['y1'], (int) $_POST['width'], (int) $_POST['height'], $width, $height ); } elseif ( ! empty( $_POST['create-new-attachment'] ) ) { $cropped = _copy_image_file( $attachment_id ); } else { $cropped = get_attached_file( $attachment_id ); } if ( ! $cropped || is_wp_error( $cropped ) ) { wp_die( __( 'Image could not be processed. Please go back and try again.' ), __( 'Image Processing Error' ) ); } /** This filter is documented in wp-admin/includes/class-custom-image-header.php */ $cropped = apply_filters( 'wp_create_file_in_uploads', $cropped, $attachment_id ); // For replication. $attachment = wp_copy_parent_attachment_properties( $cropped, $attachment_id, 'custom-header' ); if ( ! empty( $_POST['create-new-attachment'] ) ) { unset( $attachment['ID'] ); } // Update the attachment. $attachment_id = $this->insert_attachment( $attachment, $cropped ); $url = wp_get_attachment_url( $attachment_id ); $this->set_header_image( compact( 'url', 'attachment_id', 'width', 'height' ) ); // Cleanup. $medium = str_replace( wp_basename( $original ), 'midsize-' . wp_basename( $original ), $original ); if ( file_exists( $medium ) ) { wp_delete_file( $medium ); } if ( empty( $_POST['create-new-attachment'] ) && empty( $_POST['skip-cropping'] ) ) { wp_delete_file( $original ); } return $this->finished(); } /** * Displays last step of custom header image page. * * @since 2.1.0 */ public function finished() { $this->updated = true; $this->step_1(); } /** * Displays the page based on the current step. * * @since 2.1.0 */ public function admin_page() { if ( ! current_user_can( 'edit_theme_options' ) ) { wp_die( __( 'Sorry, you are not allowed to customize headers.' ) ); } $step = $this->step(); if ( 2 === $step ) { $this->step_2(); } elseif ( 3 === $step ) { $this->step_3(); } else { $this->step_1(); } } /** * Unused since 3.5.0. * * @since 3.4.0 * * @param array $form_fields * @return array $form_fields */ public function attachment_fields_to_edit( $form_fields ) { return $form_fields; } /** * Unused since 3.5.0. * * @since 3.4.0 * * @param array $tabs * @return array $tabs */ public function filter_upload_tabs( $tabs ) { return $tabs; } /** * Chooses a header image, selected from existing uploaded and default headers, * or provides an array of uploaded header data (either new, or from media library). * * @since 3.4.0 * * @param mixed $choice Which header image to select. Allows for values of 'random-default-image', * for randomly cycling among the default images; 'random-uploaded-image', * for randomly cycling among the uploaded images; the key of a default image * registered for that theme; and the key of an image uploaded for that theme * (the attachment ID of the image). Or an array of arguments: attachment_id, * url, width, height. All are required. */ final public function set_header_image( $choice ) { if ( is_array( $choice ) || is_object( $choice ) ) { $choice = (array) $choice; if ( ! isset( $choice['attachment_id'] ) || ! isset( $choice['url'] ) ) { return; } $choice['url'] = sanitize_url( $choice['url'] ); $header_image_data = (object) array( 'attachment_id' => $choice['attachment_id'], 'url' => $choice['url'], 'thumbnail_url' => $choice['url'], 'height' => $choice['height'], 'width' => $choice['width'], ); update_post_meta( $choice['attachment_id'], '_wp_attachment_is_custom_header', get_stylesheet() ); set_theme_mod( 'header_image', $choice['url'] ); set_theme_mod( 'header_image_data', $header_image_data ); return; } if ( in_array( $choice, array( 'remove-header', 'random-default-image', 'random-uploaded-image' ), true ) ) { set_theme_mod( 'header_image', $choice ); remove_theme_mod( 'header_image_data' ); return; } $uploaded = get_uploaded_header_images(); if ( $uploaded && isset( $uploaded[ $choice ] ) ) { $header_image_data = $uploaded[ $choice ]; } else { $this->process_default_headers(); if ( isset( $this->default_headers[ $choice ] ) ) { $header_image_data = $this->default_headers[ $choice ]; } else { return; } } set_theme_mod( 'header_image', sanitize_url( $header_image_data['url'] ) ); set_theme_mod( 'header_image_data', $header_image_data ); } /** * Removes a header image. * * @since 3.4.0 */ final public function remove_header_image() { $this->set_header_image( 'remove-header' ); } /** * Resets a header image to the default image for the theme. * * This method does not do anything if the theme does not have a default header image. * * @since 3.4.0 */ final public function reset_header_image() { $this->process_default_headers(); $default = get_theme_support( 'custom-header', 'default-image' ); if ( ! $default ) { $this->remove_header_image(); return; } $default = sprintf( $default, get_template_directory_uri(), get_stylesheet_directory_uri() ); $default_data = array(); foreach ( $this->default_headers as $header => $details ) { if ( $details['url'] === $default ) { $default_data = $details; break; } } set_theme_mod( 'header_image', $default ); set_theme_mod( 'header_image_data', (object) $default_data ); } /** * Calculates width and height based on what the currently selected theme supports. * * @since 3.9.0 * * @param array $dimensions * @return array dst_height and dst_width of header image. */ final public function get_header_dimensions( $dimensions ) { $max_width = 0; $width = absint( $dimensions['width'] ); $height = absint( $dimensions['height'] ); $theme_height = get_theme_support( 'custom-header', 'height' ); $theme_width = get_theme_support( 'custom-header', 'width' ); $has_flex_width = current_theme_supports( 'custom-header', 'flex-width' ); $has_flex_height = current_theme_supports( 'custom-header', 'flex-height' ); $has_max_width = current_theme_supports( 'custom-header', 'max-width' ); $dst = array( 'dst_height' => null, 'dst_width' => null, ); // For flex, limit size of image displayed to 1500px unless theme says otherwise. if ( $has_flex_width ) { $max_width = 1500; } if ( $has_max_width ) { $max_width = max( $max_width, get_theme_support( 'custom-header', 'max-width' ) ); } $max_width = max( $max_width, $theme_width ); if ( $has_flex_height && ( ! $has_flex_width || $width > $max_width ) ) { $dst['dst_height'] = absint( $height * ( $max_width / $width ) ); } elseif ( $has_flex_height && $has_flex_width ) { $dst['dst_height'] = $height; } else { $dst['dst_height'] = $theme_height; } if ( $has_flex_width && ( ! $has_flex_height || $width > $max_width ) ) { $dst['dst_width'] = absint( $width * ( $max_width / $width ) ); } elseif ( $has_flex_width && $has_flex_height ) { $dst['dst_width'] = $width; } else { $dst['dst_width'] = $theme_width; } return $dst; } /** * Creates an attachment 'object'. * * @since 3.9.0 * @deprecated 6.5.0 * * @param string $cropped Cropped image URL. * @param int $parent_attachment_id Attachment ID of parent image. * @return array An array with attachment object data. */ final public function create_attachment_object( $cropped, $parent_attachment_id ) { _deprecated_function( __METHOD__, '6.5.0', 'wp_copy_parent_attachment_properties()' ); $parent = get_post( $parent_attachment_id ); $parent_url = wp_get_attachment_url( $parent->ID ); $url = str_replace( wp_basename( $parent_url ), wp_basename( $cropped ), $parent_url ); $size = wp_getimagesize( $cropped ); $image_type = ( $size ) ? $size['mime'] : 'image/jpeg'; $attachment = array( 'ID' => $parent_attachment_id, 'post_title' => wp_basename( $cropped ), 'post_mime_type' => $image_type, 'guid' => $url, 'context' => 'custom-header', 'post_parent' => $parent_attachment_id, ); return $attachment; } /** * Inserts an attachment and its metadata. * * @since 3.9.0 * * @param array $attachment An array with attachment object data. * @param string $cropped File path to cropped image. * @return int Attachment ID. */ final public function insert_attachment( $attachment, $cropped ) { $parent_id = isset( $attachment['post_parent'] ) ? $attachment['post_parent'] : null; unset( $attachment['post_parent'] ); $attachment_id = wp_insert_attachment( $attachment, $cropped ); $metadata = wp_generate_attachment_metadata( $attachment_id, $cropped ); // If this is a crop, save the original attachment ID as metadata. if ( $parent_id ) { $metadata['attachment_parent'] = $parent_id; } /** * Filters the header image attachment metadata. * * @since 3.9.0 * * @see wp_generate_attachment_metadata() * * @param array $metadata Attachment metadata. */ $metadata = apply_filters( 'wp_header_image_attachment_metadata', $metadata ); wp_update_attachment_metadata( $attachment_id, $metadata ); return $attachment_id; } /** * Gets attachment uploaded by Media Manager, crops it, then saves it as a * new object. Returns JSON-encoded object details. * * @since 3.9.0 */ public function ajax_header_crop() { check_ajax_referer( 'image_editor-' . $_POST['id'], 'nonce' ); if ( ! current_user_can( 'edit_theme_options' ) ) { wp_send_json_error(); } if ( ! current_theme_supports( 'custom-header', 'uploads' ) ) { wp_send_json_error(); } $crop_details = $_POST['cropDetails']; $dimensions = $this->get_header_dimensions( array( 'height' => $crop_details['height'], 'width' => $crop_details['width'], ) ); $attachment_id = absint( $_POST['id'] ); $cropped = wp_crop_image( $attachment_id, (int) $crop_details['x1'], (int) $crop_details['y1'], (int) $crop_details['width'], (int) $crop_details['height'], (int) $dimensions['dst_width'], (int) $dimensions['dst_height'] ); if ( ! $cropped || is_wp_error( $cropped ) ) { wp_send_json_error( array( 'message' => __( 'Image could not be processed. Please go back and try again.' ) ) ); } /** This filter is documented in wp-admin/includes/class-custom-image-header.php */ $cropped = apply_filters( 'wp_create_file_in_uploads', $cropped, $attachment_id ); // For replication. $attachment = wp_copy_parent_attachment_properties( $cropped, $attachment_id, 'custom-header' ); $previous = $this->get_previous_crop( $attachment ); if ( $previous ) { $attachment['ID'] = $previous; } else { unset( $attachment['ID'] ); } $new_attachment_id = $this->insert_attachment( $attachment, $cropped ); $attachment['attachment_id'] = $new_attachment_id; $attachment['url'] = wp_get_attachment_url( $new_attachment_id ); $attachment['width'] = $dimensions['dst_width']; $attachment['height'] = $dimensions['dst_height']; wp_send_json_success( $attachment ); } /** * Given an attachment ID for a header image, updates its "last used" * timestamp to now. * * Triggered when the user tries adds a new header image from the * Media Manager, even if s/he doesn't save that change. * * @since 3.9.0 */ public function ajax_header_add() { check_ajax_referer( 'header-add', 'nonce' ); if ( ! current_user_can( 'edit_theme_options' ) ) { wp_send_json_error(); } $attachment_id = absint( $_POST['attachment_id'] ); if ( $attachment_id < 1 ) { wp_send_json_error(); } $key = '_wp_attachment_custom_header_last_used_' . get_stylesheet(); update_post_meta( $attachment_id, $key, time() ); update_post_meta( $attachment_id, '_wp_attachment_is_custom_header', get_stylesheet() ); wp_send_json_success(); } /** * Given an attachment ID for a header image, unsets it as a user-uploaded * header image for the active theme. * * Triggered when the user clicks the overlay "X" button next to each image * choice in the Customizer's Header tool. * * @since 3.9.0 */ public function ajax_header_remove() { check_ajax_referer( 'header-remove', 'nonce' ); if ( ! current_user_can( 'edit_theme_options' ) ) { wp_send_json_error(); } $attachment_id = absint( $_POST['attachment_id'] ); if ( $attachment_id < 1 ) { wp_send_json_error(); } $key = '_wp_attachment_custom_header_last_used_' . get_stylesheet(); delete_post_meta( $attachment_id, $key ); delete_post_meta( $attachment_id, '_wp_attachment_is_custom_header', get_stylesheet() ); wp_send_json_success(); } /** * Updates the last-used postmeta on a header image attachment after saving a new header image via the Customizer. * * @since 3.9.0 * * @param WP_Customize_Manager $wp_customize Customize manager. */ public function customize_set_last_used( $wp_customize ) { $header_image_data_setting = $wp_customize->get_setting( 'header_image_data' ); if ( ! $header_image_data_setting ) { return; } $data = $header_image_data_setting->post_value(); if ( ! isset( $data['attachment_id'] ) ) { return; } $attachment_id = $data['attachment_id']; $key = '_wp_attachment_custom_header_last_used_' . get_stylesheet(); update_post_meta( $attachment_id, $key, time() ); } /** * Gets the details of default header images if defined. * * @since 3.9.0 * * @return array Default header images. */ public function get_default_header_images() { $this->process_default_headers(); // Get the default image if there is one. $default = get_theme_support( 'custom-header', 'default-image' ); if ( ! $default ) { // If not, easy peasy. return $this->default_headers; } $default = sprintf( $default, get_template_directory_uri(), get_stylesheet_directory_uri() ); $already_has_default = false; foreach ( $this->default_headers as $k => $h ) { if ( $h['url'] === $default ) { $already_has_default = true; break; } } if ( $already_has_default ) { return $this->default_headers; } // If the one true image isn't included in the default set, prepend it. $header_images = array(); $header_images['default'] = array( 'url' => $default, 'thumbnail_url' => $default, 'description' => 'Default', ); // The rest of the set comes after. return array_merge( $header_images, $this->default_headers ); } /** * Gets the previously uploaded header images. * * @since 3.9.0 * * @return array Uploaded header images. */ public function get_uploaded_header_images() { $header_images = get_uploaded_header_images(); $timestamp_key = '_wp_attachment_custom_header_last_used_' . get_stylesheet(); $alt_text_key = '_wp_attachment_image_alt'; foreach ( $header_images as &$header_image ) { $header_meta = get_post_meta( $header_image['attachment_id'] ); $header_image['timestamp'] = isset( $header_meta[ $timestamp_key ] ) ? $header_meta[ $timestamp_key ] : ''; $header_image['alt_text'] = isset( $header_meta[ $alt_text_key ] ) ? $header_meta[ $alt_text_key ] : ''; } return $header_images; } /** * Gets the ID of a previous crop from the same base image. * * @since 4.9.0 * * @param array $attachment An array with a cropped attachment object data. * @return int|false An attachment ID if one exists. False if none. */ public function get_previous_crop( $attachment ) { $header_images = $this->get_uploaded_header_images(); // Bail early if there are no header images. if ( empty( $header_images ) ) { return false; } $previous = false; foreach ( $header_images as $image ) { if ( $image['attachment_parent'] === $attachment['post_parent'] ) { $previous = $image['attachment_id']; break; } } return $previous; } } import.php000064400000014731147206365750006614 0ustar00 sprintf( /* translators: 1: php.ini, 2: post_max_size, 3: upload_max_filesize */ __( 'File is empty. Please upload something more substantial. This error could also be caused by uploads being disabled in your %1$s file or by %2$s being defined as smaller than %3$s in %1$s.' ), 'php.ini', 'post_max_size', 'upload_max_filesize' ), ); } $overrides = array( 'test_form' => false, 'test_type' => false, ); $_FILES['import']['name'] .= '.txt'; $upload = wp_handle_upload( $_FILES['import'], $overrides ); if ( isset( $upload['error'] ) ) { return $upload; } // Construct the attachment array. $attachment = array( 'post_title' => wp_basename( $upload['file'] ), 'post_content' => $upload['url'], 'post_mime_type' => $upload['type'], 'guid' => $upload['url'], 'context' => 'import', 'post_status' => 'private', ); // Save the data. $id = wp_insert_attachment( $attachment, $upload['file'] ); /* * Schedule a cleanup for one day from now in case of failed * import or missing wp_import_cleanup() call. */ wp_schedule_single_event( time() + DAY_IN_SECONDS, 'importer_scheduled_cleanup', array( $id ) ); return array( 'file' => $upload['file'], 'id' => $id, ); } /** * Returns a list from WordPress.org of popular importer plugins. * * @since 3.5.0 * * @return array Importers with metadata for each. */ function wp_get_popular_importers() { $locale = get_user_locale(); $cache_key = 'popular_importers_' . md5( $locale . wp_get_wp_version() ); $popular_importers = get_site_transient( $cache_key ); if ( ! $popular_importers ) { $url = add_query_arg( array( 'locale' => $locale, 'version' => wp_get_wp_version(), ), 'http://api.wordpress.org/core/importers/1.1/' ); $options = array( 'user-agent' => 'WordPress/' . wp_get_wp_version() . '; ' . home_url( '/' ) ); if ( wp_http_supports( array( 'ssl' ) ) ) { $url = set_url_scheme( $url, 'https' ); } $response = wp_remote_get( $url, $options ); $popular_importers = json_decode( wp_remote_retrieve_body( $response ), true ); if ( is_array( $popular_importers ) ) { set_site_transient( $cache_key, $popular_importers, 2 * DAY_IN_SECONDS ); } else { $popular_importers = false; } } if ( is_array( $popular_importers ) ) { // If the data was received as translated, return it as-is. if ( $popular_importers['translated'] ) { return $popular_importers['importers']; } foreach ( $popular_importers['importers'] as &$importer ) { // phpcs:ignore WordPress.WP.I18n.LowLevelTranslationFunction,WordPress.WP.I18n.NonSingularStringLiteralText $importer['description'] = translate( $importer['description'] ); if ( 'WordPress' !== $importer['name'] ) { // phpcs:ignore WordPress.WP.I18n.LowLevelTranslationFunction,WordPress.WP.I18n.NonSingularStringLiteralText $importer['name'] = translate( $importer['name'] ); } } return $popular_importers['importers']; } return array( // slug => name, description, plugin slug, and register_importer() slug. 'blogger' => array( 'name' => __( 'Blogger' ), 'description' => __( 'Import posts, comments, and users from a Blogger blog.' ), 'plugin-slug' => 'blogger-importer', 'importer-id' => 'blogger', ), 'wpcat2tag' => array( 'name' => __( 'Categories and Tags Converter' ), 'description' => __( 'Convert existing categories to tags or tags to categories, selectively.' ), 'plugin-slug' => 'wpcat2tag-importer', 'importer-id' => 'wp-cat2tag', ), 'livejournal' => array( 'name' => __( 'LiveJournal' ), 'description' => __( 'Import posts from LiveJournal using their API.' ), 'plugin-slug' => 'livejournal-importer', 'importer-id' => 'livejournal', ), 'movabletype' => array( 'name' => __( 'Movable Type and TypePad' ), 'description' => __( 'Import posts and comments from a Movable Type or TypePad blog.' ), 'plugin-slug' => 'movabletype-importer', 'importer-id' => 'mt', ), 'rss' => array( 'name' => __( 'RSS' ), 'description' => __( 'Import posts from an RSS feed.' ), 'plugin-slug' => 'rss-importer', 'importer-id' => 'rss', ), 'tumblr' => array( 'name' => __( 'Tumblr' ), 'description' => __( 'Import posts & media from Tumblr using their API.' ), 'plugin-slug' => 'tumblr-importer', 'importer-id' => 'tumblr', ), 'wordpress' => array( 'name' => 'WordPress', 'description' => __( 'Import posts, pages, comments, custom fields, categories, and tags from a WordPress export file.' ), 'plugin-slug' => 'wordpress-importer', 'importer-id' => 'wordpress', ), ); } class-wp-privacy-data-export-requests-list-table.php000064400000012673147206365750016646 0ustar00status; $request_id = $item->ID; $nonce = wp_create_nonce( 'wp-privacy-export-personal-data-' . $request_id ); $download_data_markup = ''; $download_data_markup .= '' . '' . '' . ''; $download_data_markup .= ''; $row_actions['download-data'] = $download_data_markup; if ( 'request-completed' !== $status ) { $complete_request_markup = ''; $complete_request_markup .= sprintf( '%s', esc_url( wp_nonce_url( add_query_arg( array( 'action' => 'complete', 'request_id' => array( $request_id ), ), admin_url( 'export-personal-data.php' ) ), 'bulk-privacy_requests' ) ), esc_attr( sprintf( /* translators: %s: Request email. */ __( 'Mark export request for “%s” as completed.' ), $item->email ) ), __( 'Complete request' ) ); $complete_request_markup .= ''; } if ( ! empty( $complete_request_markup ) ) { $row_actions['complete-request'] = $complete_request_markup; } return sprintf( '%2$s %3$s', esc_url( 'mailto:' . $item->email ), $item->email, $this->row_actions( $row_actions ) ); } /** * Displays the next steps column. * * @since 4.9.6 * * @param WP_User_Request $item Item being shown. */ public function column_next_steps( $item ) { $status = $item->status; switch ( $status ) { case 'request-pending': esc_html_e( 'Waiting for confirmation' ); break; case 'request-confirmed': /** This filter is documented in wp-admin/includes/ajax-actions.php */ $exporters = apply_filters( 'wp_privacy_personal_data_exporters', array() ); $exporters_count = count( $exporters ); $request_id = $item->ID; $nonce = wp_create_nonce( 'wp-privacy-export-personal-data-' . $request_id ); echo '
'; ?> '; break; case 'request-failed': echo ''; break; case 'request-completed': echo '' . esc_html__( 'Remove request' ) . ''; break; } } } class-wp-site-health-auto-updates.php000064400000032371147206365750013651 0ustar00test_constants( 'WP_AUTO_UPDATE_CORE', array( true, 'beta', 'rc', 'development', 'branch-development', 'minor' ) ), $this->test_wp_version_check_attached(), $this->test_filters_automatic_updater_disabled(), $this->test_wp_automatic_updates_disabled(), $this->test_if_failed_update(), $this->test_vcs_abspath(), $this->test_check_wp_filesystem_method(), $this->test_all_files_writable(), $this->test_accepts_dev_updates(), $this->test_accepts_minor_updates(), ); $tests = array_filter( $tests ); $tests = array_map( static function ( $test ) { $test = (object) $test; if ( empty( $test->severity ) ) { $test->severity = 'warning'; } return $test; }, $tests ); return $tests; } /** * Tests if auto-updates related constants are set correctly. * * @since 5.2.0 * @since 5.5.1 The `$value` parameter can accept an array. * * @param string $constant The name of the constant to check. * @param bool|string|array $value The value that the constant should be, if set, * or an array of acceptable values. * @return array The test results. */ public function test_constants( $constant, $value ) { $acceptable_values = (array) $value; if ( defined( $constant ) && ! in_array( constant( $constant ), $acceptable_values, true ) ) { return array( 'description' => sprintf( /* translators: 1: Name of the constant used. 2: Value of the constant used. */ __( 'The %1$s constant is defined as %2$s' ), "$constant", '' . esc_html( var_export( constant( $constant ), true ) ) . '' ), 'severity' => 'fail', ); } } /** * Checks if updates are intercepted by a filter. * * @since 5.2.0 * * @return array The test results. */ public function test_wp_version_check_attached() { if ( ( ! is_multisite() || is_main_site() && is_network_admin() ) && ! has_filter( 'wp_version_check', 'wp_version_check' ) ) { return array( 'description' => sprintf( /* translators: %s: Name of the filter used. */ __( 'A plugin has prevented updates by disabling %s.' ), 'wp_version_check()' ), 'severity' => 'fail', ); } } /** * Checks if automatic updates are disabled by a filter. * * @since 5.2.0 * * @return array The test results. */ public function test_filters_automatic_updater_disabled() { /** This filter is documented in wp-admin/includes/class-wp-automatic-updater.php */ if ( apply_filters( 'automatic_updater_disabled', false ) ) { return array( 'description' => sprintf( /* translators: %s: Name of the filter used. */ __( 'The %s filter is enabled.' ), 'automatic_updater_disabled' ), 'severity' => 'fail', ); } } /** * Checks if automatic updates are disabled. * * @since 5.3.0 * * @return array|false The test results. False if auto-updates are enabled. */ public function test_wp_automatic_updates_disabled() { if ( ! class_exists( 'WP_Automatic_Updater' ) ) { require_once ABSPATH . 'wp-admin/includes/class-wp-automatic-updater.php'; } $auto_updates = new WP_Automatic_Updater(); if ( ! $auto_updates->is_disabled() ) { return false; } return array( 'description' => __( 'All automatic updates are disabled.' ), 'severity' => 'fail', ); } /** * Checks if automatic updates have tried to run, but failed, previously. * * @since 5.2.0 * * @return array|false The test results. False if the auto-updates failed. */ public function test_if_failed_update() { $failed = get_site_option( 'auto_core_update_failed' ); if ( ! $failed ) { return false; } if ( ! empty( $failed['critical'] ) ) { $description = __( 'A previous automatic background update ended with a critical failure, so updates are now disabled.' ); $description .= ' ' . __( 'You would have received an email because of this.' ); $description .= ' ' . __( "When you've been able to update using the \"Update now\" button on Dashboard > Updates, this error will be cleared for future update attempts." ); $description .= ' ' . sprintf( /* translators: %s: Code of error shown. */ __( 'The error code was %s.' ), '' . $failed['error_code'] . '' ); return array( 'description' => $description, 'severity' => 'warning', ); } $description = __( 'A previous automatic background update could not occur.' ); if ( empty( $failed['retry'] ) ) { $description .= ' ' . __( 'You would have received an email because of this.' ); } $description .= ' ' . __( 'Another attempt will be made with the next release.' ); $description .= ' ' . sprintf( /* translators: %s: Code of error shown. */ __( 'The error code was %s.' ), '' . $failed['error_code'] . '' ); return array( 'description' => $description, 'severity' => 'warning', ); } /** * Checks if WordPress is controlled by a VCS (Git, Subversion etc). * * @since 5.2.0 * * @return array The test results. */ public function test_vcs_abspath() { $context_dirs = array( ABSPATH ); $vcs_dirs = array( '.svn', '.git', '.hg', '.bzr' ); $check_dirs = array(); foreach ( $context_dirs as $context_dir ) { // Walk up from $context_dir to the root. do { $check_dirs[] = $context_dir; // Once we've hit '/' or 'C:\', we need to stop. dirname will keep returning the input here. if ( dirname( $context_dir ) === $context_dir ) { break; } // Continue one level at a time. } while ( $context_dir = dirname( $context_dir ) ); } $check_dirs = array_unique( $check_dirs ); $updater = new WP_Automatic_Updater(); $checkout = false; // Search all directories we've found for evidence of version control. foreach ( $vcs_dirs as $vcs_dir ) { foreach ( $check_dirs as $check_dir ) { if ( ! $updater->is_allowed_dir( $check_dir ) ) { continue; } $checkout = is_dir( rtrim( $check_dir, '\\/' ) . "/$vcs_dir" ); if ( $checkout ) { break 2; } } } /** This filter is documented in wp-admin/includes/class-wp-automatic-updater.php */ if ( $checkout && ! apply_filters( 'automatic_updates_is_vcs_checkout', true, ABSPATH ) ) { return array( 'description' => sprintf( /* translators: 1: Folder name. 2: Version control directory. 3: Filter name. */ __( 'The folder %1$s was detected as being under version control (%2$s), but the %3$s filter is allowing updates.' ), '' . $check_dir . '', "$vcs_dir", 'automatic_updates_is_vcs_checkout' ), 'severity' => 'info', ); } if ( $checkout ) { return array( 'description' => sprintf( /* translators: 1: Folder name. 2: Version control directory. */ __( 'The folder %1$s was detected as being under version control (%2$s).' ), '' . $check_dir . '', "$vcs_dir" ), 'severity' => 'warning', ); } return array( 'description' => __( 'No version control systems were detected.' ), 'severity' => 'pass', ); } /** * Checks if we can access files without providing credentials. * * @since 5.2.0 * * @return array The test results. */ public function test_check_wp_filesystem_method() { // Make sure the `request_filesystem_credentials()` function is available during our REST API call. if ( ! function_exists( 'request_filesystem_credentials' ) ) { require_once ABSPATH . 'wp-admin/includes/file.php'; } $skin = new Automatic_Upgrader_Skin(); $success = $skin->request_filesystem_credentials( false, ABSPATH ); if ( ! $success ) { $description = __( 'Your installation of WordPress prompts for FTP credentials to perform updates.' ); $description .= ' ' . __( '(Your site is performing updates over FTP due to file ownership. Talk to your hosting company.)' ); return array( 'description' => $description, 'severity' => 'fail', ); } return array( 'description' => __( 'Your installation of WordPress does not require FTP credentials to perform updates.' ), 'severity' => 'pass', ); } /** * Checks if core files are writable by the web user/group. * * @since 5.2.0 * * @global WP_Filesystem_Base $wp_filesystem WordPress filesystem subclass. * * @return array|false The test results. False if they're not writeable. */ public function test_all_files_writable() { global $wp_filesystem; require ABSPATH . WPINC . '/version.php'; // $wp_version; // x.y.z $skin = new Automatic_Upgrader_Skin(); $success = $skin->request_filesystem_credentials( false, ABSPATH ); if ( ! $success ) { return false; } WP_Filesystem(); if ( 'direct' !== $wp_filesystem->method ) { return false; } // Make sure the `get_core_checksums()` function is available during our REST API call. if ( ! function_exists( 'get_core_checksums' ) ) { require_once ABSPATH . 'wp-admin/includes/update.php'; } $checksums = get_core_checksums( $wp_version, 'en_US' ); $dev = ( str_contains( $wp_version, '-' ) ); // Get the last stable version's files and test against that. if ( ! $checksums && $dev ) { $checksums = get_core_checksums( (float) $wp_version - 0.1, 'en_US' ); } // There aren't always checksums for development releases, so just skip the test if we still can't find any. if ( ! $checksums && $dev ) { return false; } if ( ! $checksums ) { $description = sprintf( /* translators: %s: WordPress version. */ __( "Couldn't retrieve a list of the checksums for WordPress %s." ), $wp_version ); $description .= ' ' . __( 'This could mean that connections are failing to WordPress.org.' ); return array( 'description' => $description, 'severity' => 'warning', ); } $unwritable_files = array(); foreach ( array_keys( $checksums ) as $file ) { if ( str_starts_with( $file, 'wp-content' ) ) { continue; } if ( ! file_exists( ABSPATH . $file ) ) { continue; } if ( ! is_writable( ABSPATH . $file ) ) { $unwritable_files[] = $file; } } if ( $unwritable_files ) { if ( count( $unwritable_files ) > 20 ) { $unwritable_files = array_slice( $unwritable_files, 0, 20 ); $unwritable_files[] = '...'; } return array( 'description' => __( 'Some files are not writable by WordPress:' ) . ' ', 'severity' => 'fail', ); } else { return array( 'description' => __( 'All of your WordPress files are writable.' ), 'severity' => 'pass', ); } } /** * Checks if the install is using a development branch and can use nightly packages. * * @since 5.2.0 * * @return array|false The test results. False if it isn't a development version. */ public function test_accepts_dev_updates() { require ABSPATH . WPINC . '/version.php'; // $wp_version; // x.y.z // Only for dev versions. if ( ! str_contains( $wp_version, '-' ) ) { return false; } if ( defined( 'WP_AUTO_UPDATE_CORE' ) && ( 'minor' === WP_AUTO_UPDATE_CORE || false === WP_AUTO_UPDATE_CORE ) ) { return array( 'description' => sprintf( /* translators: %s: Name of the constant used. */ __( 'WordPress development updates are blocked by the %s constant.' ), 'WP_AUTO_UPDATE_CORE' ), 'severity' => 'fail', ); } /** This filter is documented in wp-admin/includes/class-core-upgrader.php */ if ( ! apply_filters( 'allow_dev_auto_core_updates', $wp_version ) ) { return array( 'description' => sprintf( /* translators: %s: Name of the filter used. */ __( 'WordPress development updates are blocked by the %s filter.' ), 'allow_dev_auto_core_updates' ), 'severity' => 'fail', ); } } /** * Checks if the site supports automatic minor updates. * * @since 5.2.0 * * @return array The test results. */ public function test_accepts_minor_updates() { if ( defined( 'WP_AUTO_UPDATE_CORE' ) && false === WP_AUTO_UPDATE_CORE ) { return array( 'description' => sprintf( /* translators: %s: Name of the constant used. */ __( 'WordPress security and maintenance releases are blocked by %s.' ), "define( 'WP_AUTO_UPDATE_CORE', false );" ), 'severity' => 'fail', ); } /** This filter is documented in wp-admin/includes/class-core-upgrader.php */ if ( ! apply_filters( 'allow_minor_auto_core_updates', true ) ) { return array( 'description' => sprintf( /* translators: %s: Name of the filter used. */ __( 'WordPress security and maintenance releases are blocked by the %s filter.' ), 'allow_minor_auto_core_updates' ), 'severity' => 'fail', ); } } } ms.php000064400000102246147206365750005720 0ustar00 0 ) { // There's already an error. return $file; } if ( defined( 'WP_IMPORTING' ) ) { return $file; } $space_left = get_upload_space_available(); $file_size = filesize( $file['tmp_name'] ); if ( $space_left < $file_size ) { /* translators: %s: Required disk space in kilobytes. */ $file['error'] = sprintf( __( 'Not enough space to upload. %s KB needed.' ), number_format( ( $file_size - $space_left ) / KB_IN_BYTES ) ); } if ( $file_size > ( KB_IN_BYTES * get_site_option( 'fileupload_maxk', 1500 ) ) ) { /* translators: %s: Maximum allowed file size in kilobytes. */ $file['error'] = sprintf( __( 'This file is too big. Files must be less than %s KB in size.' ), get_site_option( 'fileupload_maxk', 1500 ) ); } if ( upload_is_user_over_quota( false ) ) { $file['error'] = __( 'You have used your space quota. Please delete files before uploading.' ); } if ( $file['error'] > 0 && ! isset( $_POST['html-upload'] ) && ! wp_doing_ajax() ) { wp_die( $file['error'] . ' ' . __( 'Back' ) . '' ); } return $file; } /** * Deletes a site. * * @since 3.0.0 * @since 5.1.0 Use wp_delete_site() internally to delete the site row from the database. * * @param int $blog_id Site ID. * @param bool $drop True if site's database tables should be dropped. Default false. */ function wpmu_delete_blog( $blog_id, $drop = false ) { $blog_id = (int) $blog_id; $switch = false; if ( get_current_blog_id() !== $blog_id ) { $switch = true; switch_to_blog( $blog_id ); } $blog = get_site( $blog_id ); $current_network = get_network(); // If a full blog object is not available, do not destroy anything. if ( $drop && ! $blog ) { $drop = false; } // Don't destroy the initial, main, or root blog. if ( $drop && ( 1 === $blog_id || is_main_site( $blog_id ) || ( $blog->path === $current_network->path && $blog->domain === $current_network->domain ) ) ) { $drop = false; } $upload_path = trim( get_option( 'upload_path' ) ); // If ms_files_rewriting is enabled and upload_path is empty, wp_upload_dir is not reliable. if ( $drop && get_site_option( 'ms_files_rewriting' ) && empty( $upload_path ) ) { $drop = false; } if ( $drop ) { wp_delete_site( $blog_id ); } else { /** This action is documented in wp-includes/ms-blogs.php */ do_action_deprecated( 'delete_blog', array( $blog_id, false ), '5.1.0' ); $users = get_users( array( 'blog_id' => $blog_id, 'fields' => 'ids', ) ); // Remove users from this blog. if ( ! empty( $users ) ) { foreach ( $users as $user_id ) { remove_user_from_blog( $user_id, $blog_id ); } } update_blog_status( $blog_id, 'deleted', 1 ); /** This action is documented in wp-includes/ms-blogs.php */ do_action_deprecated( 'deleted_blog', array( $blog_id, false ), '5.1.0' ); } if ( $switch ) { restore_current_blog(); } } /** * Deletes a user and all of their posts from the network. * * This function: * * - Deletes all posts (of all post types) authored by the user on all sites on the network * - Deletes all links owned by the user on all sites on the network * - Removes the user from all sites on the network * - Deletes the user from the database * * @since 3.0.0 * * @global wpdb $wpdb WordPress database abstraction object. * * @param int $id The user ID. * @return bool True if the user was deleted, false otherwise. */ function wpmu_delete_user( $id ) { global $wpdb; if ( ! is_numeric( $id ) ) { return false; } $id = (int) $id; $user = new WP_User( $id ); if ( ! $user->exists() ) { return false; } // Global super-administrators are protected, and cannot be deleted. $_super_admins = get_super_admins(); if ( in_array( $user->user_login, $_super_admins, true ) ) { return false; } /** * Fires before a user is deleted from the network. * * @since MU (3.0.0) * @since 5.5.0 Added the `$user` parameter. * * @param int $id ID of the user about to be deleted from the network. * @param WP_User $user WP_User object of the user about to be deleted from the network. */ do_action( 'wpmu_delete_user', $id, $user ); $blogs = get_blogs_of_user( $id ); if ( ! empty( $blogs ) ) { foreach ( $blogs as $blog ) { switch_to_blog( $blog->userblog_id ); remove_user_from_blog( $id, $blog->userblog_id ); $post_ids = $wpdb->get_col( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_author = %d", $id ) ); foreach ( (array) $post_ids as $post_id ) { wp_delete_post( $post_id ); } // Clean links. $link_ids = $wpdb->get_col( $wpdb->prepare( "SELECT link_id FROM $wpdb->links WHERE link_owner = %d", $id ) ); if ( $link_ids ) { foreach ( $link_ids as $link_id ) { wp_delete_link( $link_id ); } } restore_current_blog(); } } $meta = $wpdb->get_col( $wpdb->prepare( "SELECT umeta_id FROM $wpdb->usermeta WHERE user_id = %d", $id ) ); foreach ( $meta as $mid ) { delete_metadata_by_mid( 'user', $mid ); } $wpdb->delete( $wpdb->users, array( 'ID' => $id ) ); clean_user_cache( $user ); /** This action is documented in wp-admin/includes/user.php */ do_action( 'deleted_user', $id, null, $user ); return true; } /** * Checks whether a site has used its allotted upload space. * * @since MU (3.0.0) * * @param bool $display_message Optional. If set to true and the quota is exceeded, * a warning message is displayed. Default true. * @return bool True if user is over upload space quota, otherwise false. */ function upload_is_user_over_quota( $display_message = true ) { if ( get_site_option( 'upload_space_check_disabled' ) ) { return false; } $space_allowed = get_space_allowed(); if ( ! is_numeric( $space_allowed ) ) { $space_allowed = 10; // Default space allowed is 10 MB. } $space_used = get_space_used(); if ( ( $space_allowed - $space_used ) < 0 ) { if ( $display_message ) { printf( /* translators: %s: Allowed space allocation. */ __( 'Sorry, you have used your space allocation of %s. Please delete some files to upload more files.' ), size_format( $space_allowed * MB_IN_BYTES ) ); } return true; } else { return false; } } /** * Displays the amount of disk space used by the current site. Not used in core. * * @since MU (3.0.0) */ function display_space_usage() { $space_allowed = get_space_allowed(); $space_used = get_space_used(); $percent_used = ( $space_used / $space_allowed ) * 100; $space = size_format( $space_allowed * MB_IN_BYTES ); ?> 'Afar', 'ab' => 'Abkhazian', 'af' => 'Afrikaans', 'ak' => 'Akan', 'sq' => 'Albanian', 'am' => 'Amharic', 'ar' => 'Arabic', 'an' => 'Aragonese', 'hy' => 'Armenian', 'as' => 'Assamese', 'av' => 'Avaric', 'ae' => 'Avestan', 'ay' => 'Aymara', 'az' => 'Azerbaijani', 'ba' => 'Bashkir', 'bm' => 'Bambara', 'eu' => 'Basque', 'be' => 'Belarusian', 'bn' => 'Bengali', 'bh' => 'Bihari', 'bi' => 'Bislama', 'bs' => 'Bosnian', 'br' => 'Breton', 'bg' => 'Bulgarian', 'my' => 'Burmese', 'ca' => 'Catalan; Valencian', 'ch' => 'Chamorro', 'ce' => 'Chechen', 'zh' => 'Chinese', 'cu' => 'Church Slavic; Old Slavonic; Church Slavonic; Old Bulgarian; Old Church Slavonic', 'cv' => 'Chuvash', 'kw' => 'Cornish', 'co' => 'Corsican', 'cr' => 'Cree', 'cs' => 'Czech', 'da' => 'Danish', 'dv' => 'Divehi; Dhivehi; Maldivian', 'nl' => 'Dutch; Flemish', 'dz' => 'Dzongkha', 'en' => 'English', 'eo' => 'Esperanto', 'et' => 'Estonian', 'ee' => 'Ewe', 'fo' => 'Faroese', 'fj' => 'Fijjian', 'fi' => 'Finnish', 'fr' => 'French', 'fy' => 'Western Frisian', 'ff' => 'Fulah', 'ka' => 'Georgian', 'de' => 'German', 'gd' => 'Gaelic; Scottish Gaelic', 'ga' => 'Irish', 'gl' => 'Galician', 'gv' => 'Manx', 'el' => 'Greek, Modern', 'gn' => 'Guarani', 'gu' => 'Gujarati', 'ht' => 'Haitian; Haitian Creole', 'ha' => 'Hausa', 'he' => 'Hebrew', 'hz' => 'Herero', 'hi' => 'Hindi', 'ho' => 'Hiri Motu', 'hu' => 'Hungarian', 'ig' => 'Igbo', 'is' => 'Icelandic', 'io' => 'Ido', 'ii' => 'Sichuan Yi', 'iu' => 'Inuktitut', 'ie' => 'Interlingue', 'ia' => 'Interlingua (International Auxiliary Language Association)', 'id' => 'Indonesian', 'ik' => 'Inupiaq', 'it' => 'Italian', 'jv' => 'Javanese', 'ja' => 'Japanese', 'kl' => 'Kalaallisut; Greenlandic', 'kn' => 'Kannada', 'ks' => 'Kashmiri', 'kr' => 'Kanuri', 'kk' => 'Kazakh', 'km' => 'Central Khmer', 'ki' => 'Kikuyu; Gikuyu', 'rw' => 'Kinyarwanda', 'ky' => 'Kirghiz; Kyrgyz', 'kv' => 'Komi', 'kg' => 'Kongo', 'ko' => 'Korean', 'kj' => 'Kuanyama; Kwanyama', 'ku' => 'Kurdish', 'lo' => 'Lao', 'la' => 'Latin', 'lv' => 'Latvian', 'li' => 'Limburgan; Limburger; Limburgish', 'ln' => 'Lingala', 'lt' => 'Lithuanian', 'lb' => 'Luxembourgish; Letzeburgesch', 'lu' => 'Luba-Katanga', 'lg' => 'Ganda', 'mk' => 'Macedonian', 'mh' => 'Marshallese', 'ml' => 'Malayalam', 'mi' => 'Maori', 'mr' => 'Marathi', 'ms' => 'Malay', 'mg' => 'Malagasy', 'mt' => 'Maltese', 'mo' => 'Moldavian', 'mn' => 'Mongolian', 'na' => 'Nauru', 'nv' => 'Navajo; Navaho', 'nr' => 'Ndebele, South; South Ndebele', 'nd' => 'Ndebele, North; North Ndebele', 'ng' => 'Ndonga', 'ne' => 'Nepali', 'nn' => 'Norwegian Nynorsk; Nynorsk, Norwegian', 'nb' => 'Bokmål, Norwegian, Norwegian Bokmål', 'no' => 'Norwegian', 'ny' => 'Chichewa; Chewa; Nyanja', 'oc' => 'Occitan, Provençal', 'oj' => 'Ojibwa', 'or' => 'Oriya', 'om' => 'Oromo', 'os' => 'Ossetian; Ossetic', 'pa' => 'Panjabi; Punjabi', 'fa' => 'Persian', 'pi' => 'Pali', 'pl' => 'Polish', 'pt' => 'Portuguese', 'ps' => 'Pushto', 'qu' => 'Quechua', 'rm' => 'Romansh', 'ro' => 'Romanian', 'rn' => 'Rundi', 'ru' => 'Russian', 'sg' => 'Sango', 'sa' => 'Sanskrit', 'sr' => 'Serbian', 'hr' => 'Croatian', 'si' => 'Sinhala; Sinhalese', 'sk' => 'Slovak', 'sl' => 'Slovenian', 'se' => 'Northern Sami', 'sm' => 'Samoan', 'sn' => 'Shona', 'sd' => 'Sindhi', 'so' => 'Somali', 'st' => 'Sotho, Southern', 'es' => 'Spanish; Castilian', 'sc' => 'Sardinian', 'ss' => 'Swati', 'su' => 'Sundanese', 'sw' => 'Swahili', 'sv' => 'Swedish', 'ty' => 'Tahitian', 'ta' => 'Tamil', 'tt' => 'Tatar', 'te' => 'Telugu', 'tg' => 'Tajik', 'tl' => 'Tagalog', 'th' => 'Thai', 'bo' => 'Tibetan', 'ti' => 'Tigrinya', 'to' => 'Tonga (Tonga Islands)', 'tn' => 'Tswana', 'ts' => 'Tsonga', 'tk' => 'Turkmen', 'tr' => 'Turkish', 'tw' => 'Twi', 'ug' => 'Uighur; Uyghur', 'uk' => 'Ukrainian', 'ur' => 'Urdu', 'uz' => 'Uzbek', 've' => 'Venda', 'vi' => 'Vietnamese', 'vo' => 'Volapük', 'cy' => 'Welsh', 'wa' => 'Walloon', 'wo' => 'Wolof', 'xh' => 'Xhosa', 'yi' => 'Yiddish', 'yo' => 'Yoruba', 'za' => 'Zhuang; Chuang', 'zu' => 'Zulu', ); /** * Filters the language codes. * * @since MU (3.0.0) * * @param string[] $lang_codes Array of key/value pairs of language codes where key is the short version. * @param string $code A two-letter designation of the language. */ $lang_codes = apply_filters( 'lang_codes', $lang_codes, $code ); return strtr( $code, $lang_codes ); } /** * Displays an access denied message when a user tries to view a site's dashboard they * do not have access to. * * @since 3.2.0 * @access private */ function _access_denied_splash() { if ( ! is_user_logged_in() || is_network_admin() ) { return; } $blogs = get_blogs_of_user( get_current_user_id() ); if ( wp_list_filter( $blogs, array( 'userblog_id' => get_current_blog_id() ) ) ) { return; } $blog_name = get_bloginfo( 'name' ); if ( empty( $blogs ) ) { wp_die( sprintf( /* translators: 1: Site title. */ __( 'You attempted to access the "%1$s" dashboard, but you do not currently have privileges on this site. If you believe you should be able to access the "%1$s" dashboard, please contact your network administrator.' ), $blog_name ), 403 ); } $output = '

' . sprintf( /* translators: 1: Site title. */ __( 'You attempted to access the "%1$s" dashboard, but you do not currently have privileges on this site. If you believe you should be able to access the "%1$s" dashboard, please contact your network administrator.' ), $blog_name ) . '

'; $output .= '

' . __( 'If you reached this screen by accident and meant to visit one of your own sites, here are some shortcuts to help you find your way.' ) . '

'; $output .= '

' . __( 'Your Sites' ) . '

'; $output .= ''; foreach ( $blogs as $blog ) { $output .= ''; $output .= ""; $output .= ''; $output .= ''; } $output .= '
{$blog->blogname}' . __( 'Visit Dashboard' ) . ' | ' . '' . __( 'View Site' ) . '
'; wp_die( $output, 403 ); } /** * Checks if the current user has permissions to import new users. * * @since 3.0.0 * * @param string $permission A permission to be checked. Currently not used. * @return bool True if the user has proper permissions, false if they do not. */ function check_import_new_users( $permission ) { if ( ! current_user_can( 'manage_network_users' ) ) { return false; } return true; } // See "import_allow_fetch_attachments" and "import_attachment_size_limit" filters too. /** * Generates and displays a drop-down of available languages. * * @since 3.0.0 * * @param string[] $lang_files Optional. An array of the language files. Default empty array. * @param string $current Optional. The current language code. Default empty. */ function mu_dropdown_languages( $lang_files = array(), $current = '' ) { $flag = false; $output = array(); foreach ( (array) $lang_files as $val ) { $code_lang = basename( $val, '.mo' ); if ( 'en_US' === $code_lang ) { // American English. $flag = true; $ae = __( 'American English' ); $output[ $ae ] = ''; } elseif ( 'en_GB' === $code_lang ) { // British English. $flag = true; $be = __( 'British English' ); $output[ $be ] = ''; } else { $translated = format_code_lang( $code_lang ); $output[ $translated ] = ''; } } if ( false === $flag ) { // WordPress English. $output[] = ''; } // Order by name. uksort( $output, 'strnatcasecmp' ); /** * Filters the languages available in the dropdown. * * @since MU (3.0.0) * * @param string[] $output Array of HTML output for the dropdown. * @param string[] $lang_files Array of available language files. * @param string $current The current language code. */ $output = apply_filters( 'mu_dropdown_languages', $output, $lang_files, $current ); echo implode( "\n\t", $output ); } /** * Displays an admin notice to upgrade all sites after a core upgrade. * * @since 3.0.0 * * @global int $wp_db_version WordPress database version. * @global string $pagenow The filename of the current screen. * * @return void|false Void on success. False if the current user is not a super admin. */ function site_admin_notice() { global $wp_db_version, $pagenow; if ( ! current_user_can( 'upgrade_network' ) ) { return false; } if ( 'upgrade.php' === $pagenow ) { return; } if ( (int) get_site_option( 'wpmu_upgrade_site' ) !== $wp_db_version ) { $upgrade_network_message = sprintf( /* translators: %s: URL to Upgrade Network screen. */ __( 'Thank you for Updating! Please visit the Upgrade Network page to update all your sites.' ), esc_url( network_admin_url( 'upgrade.php' ) ) ); wp_admin_notice( $upgrade_network_message, array( 'type' => 'warning', 'additional_classes' => array( 'update-nag', 'inline' ), 'paragraph_wrap' => false, ) ); } } /** * Avoids a collision between a site slug and a permalink slug. * * In a subdirectory installation this will make sure that a site and a post do not use the * same subdirectory by checking for a site with the same name as a new post. * * @since 3.0.0 * * @param array $data An array of post data. * @param array $postarr An array of posts. Not currently used. * @return array The new array of post data after checking for collisions. */ function avoid_blog_page_permalink_collision( $data, $postarr ) { if ( is_subdomain_install() ) { return $data; } if ( 'page' !== $data['post_type'] ) { return $data; } if ( ! isset( $data['post_name'] ) || '' === $data['post_name'] ) { return $data; } if ( ! is_main_site() ) { return $data; } if ( isset( $data['post_parent'] ) && $data['post_parent'] ) { return $data; } $post_name = $data['post_name']; $c = 0; while ( $c < 10 && get_id_from_blogname( $post_name ) ) { $post_name .= mt_rand( 1, 10 ); ++$c; } if ( $post_name !== $data['post_name'] ) { $data['post_name'] = $post_name; } return $data; } /** * Handles the display of choosing a user's primary site. * * This displays the user's primary site and allows the user to choose * which site is primary. * * @since 3.0.0 */ function choose_primary_blog() { ?>

ID ) . '">' . $current_user->user_login . ''; ?> ID ) ) { wp_die( sprintf( /* translators: %s: User login. */ __( 'Warning! User %s cannot be deleted.' ), $delete_user->user_login ) ); } if ( in_array( $delete_user->user_login, $site_admins, true ) ) { wp_die( sprintf( /* translators: %s: User login. */ __( 'Warning! User cannot be deleted. The user %s is a network administrator.' ), '' . $delete_user->user_login . '' ) ); } ?> '; } else { ?>

array( 'label' => __( 'Info' ), 'url' => 'site-info.php', 'cap' => 'manage_sites', ), 'site-users' => array( 'label' => __( 'Users' ), 'url' => 'site-users.php', 'cap' => 'manage_sites', ), 'site-themes' => array( 'label' => __( 'Themes' ), 'url' => 'site-themes.php', 'cap' => 'manage_sites', ), 'site-settings' => array( 'label' => __( 'Settings' ), 'url' => 'site-settings.php', 'cap' => 'manage_sites', ), ) ); // Parse arguments. $parsed_args = wp_parse_args( $args, array( 'blog_id' => isset( $_GET['blog_id'] ) ? (int) $_GET['blog_id'] : 0, 'links' => $links, 'selected' => 'site-info', ) ); // Setup the links array. $screen_links = array(); // Loop through tabs. foreach ( $parsed_args['links'] as $link_id => $link ) { // Skip link if user can't access. if ( ! current_user_can( $link['cap'], $parsed_args['blog_id'] ) ) { continue; } // Link classes. $classes = array( 'nav-tab' ); // Aria-current attribute. $aria_current = ''; // Selected is set by the parent OR assumed by the $pagenow global. if ( $parsed_args['selected'] === $link_id || $link['url'] === $GLOBALS['pagenow'] ) { $classes[] = 'nav-tab-active'; $aria_current = ' aria-current="page"'; } // Escape each class. $esc_classes = implode( ' ', $classes ); // Get the URL for this link. $url = add_query_arg( array( 'id' => $parsed_args['blog_id'] ), network_admin_url( $link['url'] ) ); // Add link to nav links. $screen_links[ $link_id ] = '' . esc_html( $link['label'] ) . ''; } // All done! echo ''; } /** * Returns the arguments for the help tab on the Edit Site screens. * * @since 4.9.0 * * @return array Help tab arguments. */ function get_site_screen_help_tab_args() { return array( 'id' => 'overview', 'title' => __( 'Overview' ), 'content' => '

' . __( 'The menu is for editing information specific to individual sites, particularly if the admin area of a site is unavailable.' ) . '

' . '

' . __( 'Info — The site URL is rarely edited as this can cause the site to not work properly. The Registered date and Last Updated date are displayed. Network admins can mark a site as archived, spam, deleted and mature, to remove from public listings or disable.' ) . '

' . '

' . __( 'Users — This displays the users associated with this site. You can also change their role, reset their password, or remove them from the site. Removing the user from the site does not remove the user from the network.' ) . '

' . '

' . sprintf( /* translators: %s: URL to Network Themes screen. */ __( 'Themes — This area shows themes that are not already enabled across the network. Enabling a theme in this menu makes it accessible to this site. It does not activate the theme, but allows it to show in the site’s Appearance menu. To enable a theme for the entire network, see the Network Themes screen.' ), network_admin_url( 'themes.php' ) ) . '

' . '

' . __( 'Settings — This page shows a list of all settings associated with this site. Some are created by WordPress and others are created by plugins you activate. Note that some fields are grayed out and say Serialized Data. You cannot modify these values due to the way the setting is stored in the database.' ) . '

', ); } /** * Returns the content for the help sidebar on the Edit Site screens. * * @since 4.9.0 * * @return string Help sidebar content. */ function get_site_screen_help_sidebar_content() { return '

' . __( 'For more information:' ) . '

' . '

' . __( 'Documentation on Site Management' ) . '

' . '

' . __( 'Support forums' ) . '

'; } class-wp-privacy-data-removal-requests-list-table.php000064400000013123147206365750016761 0ustar00status; $request_id = $item->ID; $row_actions = array(); if ( 'request-confirmed' !== $status ) { /** This filter is documented in wp-admin/includes/ajax-actions.php */ $erasers = apply_filters( 'wp_privacy_personal_data_erasers', array() ); $erasers_count = count( $erasers ); $nonce = wp_create_nonce( 'wp-privacy-erase-personal-data-' . $request_id ); $remove_data_markup = ''; $remove_data_markup .= '' . '' . '' . ''; $remove_data_markup .= ''; $row_actions['remove-data'] = $remove_data_markup; } if ( 'request-completed' !== $status ) { $complete_request_markup = ''; $complete_request_markup .= sprintf( '%s', esc_url( wp_nonce_url( add_query_arg( array( 'action' => 'complete', 'request_id' => array( $request_id ), ), admin_url( 'erase-personal-data.php' ) ), 'bulk-privacy_requests' ) ), esc_attr( sprintf( /* translators: %s: Request email. */ __( 'Mark export request for “%s” as completed.' ), $item->email ) ), __( 'Complete request' ) ); $complete_request_markup .= ''; } if ( ! empty( $complete_request_markup ) ) { $row_actions['complete-request'] = $complete_request_markup; } return sprintf( '%2$s %3$s', esc_url( 'mailto:' . $item->email ), $item->email, $this->row_actions( $row_actions ) ); } /** * Outputs the Next steps column. * * @since 4.9.6 * * @param WP_User_Request $item Item being shown. */ public function column_next_steps( $item ) { $status = $item->status; switch ( $status ) { case 'request-pending': esc_html_e( 'Waiting for confirmation' ); break; case 'request-confirmed': /** This filter is documented in wp-admin/includes/ajax-actions.php */ $erasers = apply_filters( 'wp_privacy_personal_data_erasers', array() ); $erasers_count = count( $erasers ); $request_id = $item->ID; $nonce = wp_create_nonce( 'wp-privacy-erase-personal-data-' . $request_id ); echo '
'; ?> '; break; case 'request-failed': echo ''; break; case 'request-completed': echo '' . esc_html__( 'Remove request' ) . ''; break; } } } class-language-pack-upgrader-skin.php000064400000005466147206365750013662 0ustar00 '', 'nonce' => '', 'title' => __( 'Update Translations' ), 'skip_header_footer' => false, ); $args = wp_parse_args( $args, $defaults ); if ( $args['skip_header_footer'] ) { $this->done_header = true; $this->done_footer = true; $this->display_footer_actions = false; } parent::__construct( $args ); } /** * Performs an action before a language pack update. * * @since 3.7.0 */ public function before() { $name = $this->upgrader->get_name_for_update( $this->language_update ); echo '
'; /* translators: 1: Project name (plugin, theme, or WordPress), 2: Language. */ printf( '

' . __( 'Updating translations for %1$s (%2$s)…' ) . '

', $name, $this->language_update->language ); } /** * Displays an error message about the update. * * @since 3.7.0 * @since 5.9.0 Renamed `$error` to `$errors` for PHP 8 named parameter support. * * @param string|WP_Error $errors Errors. */ public function error( $errors ) { echo '
'; parent::error( $errors ); echo '
'; } /** * Performs an action following a language pack update. * * @since 3.7.0 */ public function after() { echo '
'; } /** * Displays the footer following the bulk update process. * * @since 3.7.0 */ public function bulk_footer() { $this->decrement_update_count( 'translation' ); $update_actions = array( 'updates_page' => sprintf( '%s', self_admin_url( 'update-core.php' ), __( 'Go to WordPress Updates page' ) ), ); /** * Filters the list of action links available following a translations update. * * @since 3.7.0 * * @param string[] $update_actions Array of translations update links. */ $update_actions = apply_filters( 'update_translations_complete_actions', $update_actions ); if ( $update_actions && $this->display_footer_actions ) { $this->feedback( implode( ' | ', $update_actions ) ); } } } class-plugin-installer-skin.php000064400000027425147206365750012644 0ustar00 'web', 'url' => '', 'plugin' => '', 'nonce' => '', 'title' => '', 'overwrite' => '', ); $args = wp_parse_args( $args, $defaults ); $this->type = $args['type']; $this->url = $args['url']; $this->api = isset( $args['api'] ) ? $args['api'] : array(); $this->overwrite = $args['overwrite']; parent::__construct( $args ); } /** * Performs an action before installing a plugin. * * @since 2.8.0 */ public function before() { if ( ! empty( $this->api ) ) { $this->upgrader->strings['process_success'] = sprintf( $this->upgrader->strings['process_success_specific'], $this->api->name, $this->api->version ); } } /** * Hides the `process_failed` error when updating a plugin by uploading a zip file. * * @since 5.5.0 * * @param WP_Error $wp_error WP_Error object. * @return bool True if the error should be hidden, false otherwise. */ public function hide_process_failed( $wp_error ) { if ( 'upload' === $this->type && '' === $this->overwrite && $wp_error->get_error_code() === 'folder_exists' ) { return true; } return false; } /** * Performs an action following a plugin install. * * @since 2.8.0 */ public function after() { // Check if the plugin can be overwritten and output the HTML. if ( $this->do_overwrite() ) { return; } $plugin_file = $this->upgrader->plugin_info(); $install_actions = array(); $from = isset( $_GET['from'] ) ? wp_unslash( $_GET['from'] ) : 'plugins'; if ( 'import' === $from ) { $install_actions['activate_plugin'] = sprintf( '%s', wp_nonce_url( 'plugins.php?action=activate&from=import&plugin=' . urlencode( $plugin_file ), 'activate-plugin_' . $plugin_file ), __( 'Activate Plugin & Run Importer' ) ); } elseif ( 'press-this' === $from ) { $install_actions['activate_plugin'] = sprintf( '%s', wp_nonce_url( 'plugins.php?action=activate&from=press-this&plugin=' . urlencode( $plugin_file ), 'activate-plugin_' . $plugin_file ), __( 'Activate Plugin & Go to Press This' ) ); } else { $install_actions['activate_plugin'] = sprintf( '%s', wp_nonce_url( 'plugins.php?action=activate&plugin=' . urlencode( $plugin_file ), 'activate-plugin_' . $plugin_file ), __( 'Activate Plugin' ) ); } if ( is_multisite() && current_user_can( 'manage_network_plugins' ) ) { $install_actions['network_activate'] = sprintf( '%s', wp_nonce_url( 'plugins.php?action=activate&networkwide=1&plugin=' . urlencode( $plugin_file ), 'activate-plugin_' . $plugin_file ), _x( 'Network Activate', 'plugin' ) ); unset( $install_actions['activate_plugin'] ); } if ( 'import' === $from ) { $install_actions['importers_page'] = sprintf( '%s', admin_url( 'import.php' ), __( 'Go to Importers' ) ); } elseif ( 'web' === $this->type ) { $install_actions['plugins_page'] = sprintf( '%s', self_admin_url( 'plugin-install.php' ), __( 'Go to Plugin Installer' ) ); } elseif ( 'upload' === $this->type && 'plugins' === $from ) { $install_actions['plugins_page'] = sprintf( '%s', self_admin_url( 'plugin-install.php' ), __( 'Go to Plugin Installer' ) ); } else { $install_actions['plugins_page'] = sprintf( '%s', self_admin_url( 'plugins.php' ), __( 'Go to Plugins page' ) ); } if ( ! $this->result || is_wp_error( $this->result ) ) { unset( $install_actions['activate_plugin'], $install_actions['network_activate'] ); } elseif ( ! current_user_can( 'activate_plugin', $plugin_file ) || is_plugin_active( $plugin_file ) ) { unset( $install_actions['activate_plugin'] ); } /** * Filters the list of action links available following a single plugin installation. * * @since 2.7.0 * * @param string[] $install_actions Array of plugin action links. * @param object $api Object containing WordPress.org API plugin data. Empty * for non-API installs, such as when a plugin is installed * via upload. * @param string $plugin_file Path to the plugin file relative to the plugins directory. */ $install_actions = apply_filters( 'install_plugin_complete_actions', $install_actions, $this->api, $plugin_file ); if ( ! empty( $install_actions ) ) { $this->feedback( implode( ' ', (array) $install_actions ) ); } } /** * Checks if the plugin can be overwritten and outputs the HTML for overwriting a plugin on upload. * * @since 5.5.0 * * @return bool Whether the plugin can be overwritten and HTML was outputted. */ private function do_overwrite() { if ( 'upload' !== $this->type || ! is_wp_error( $this->result ) || 'folder_exists' !== $this->result->get_error_code() ) { return false; } $folder = $this->result->get_error_data( 'folder_exists' ); $folder = ltrim( substr( $folder, strlen( WP_PLUGIN_DIR ) ), '/' ); $current_plugin_data = false; $all_plugins = get_plugins(); foreach ( $all_plugins as $plugin => $plugin_data ) { if ( strrpos( $plugin, $folder ) !== 0 ) { continue; } $current_plugin_data = $plugin_data; } $new_plugin_data = $this->upgrader->new_plugin_data; if ( ! $current_plugin_data || ! $new_plugin_data ) { return false; } echo '

' . esc_html__( 'This plugin is already installed.' ) . '

'; $this->is_downgrading = version_compare( $current_plugin_data['Version'], $new_plugin_data['Version'], '>' ); $rows = array( 'Name' => __( 'Plugin name' ), 'Version' => __( 'Version' ), 'Author' => __( 'Author' ), 'RequiresWP' => __( 'Required WordPress version' ), 'RequiresPHP' => __( 'Required PHP version' ), ); $table = ''; $table .= ''; $table .= ''; $is_same_plugin = true; // Let's consider only these rows. foreach ( $rows as $field => $label ) { $old_value = ! empty( $current_plugin_data[ $field ] ) ? (string) $current_plugin_data[ $field ] : '-'; $new_value = ! empty( $new_plugin_data[ $field ] ) ? (string) $new_plugin_data[ $field ] : '-'; $is_same_plugin = $is_same_plugin && ( $old_value === $new_value ); $diff_field = ( 'Version' !== $field && $new_value !== $old_value ); $diff_version = ( 'Version' === $field && $this->is_downgrading ); $table .= ''; $table .= ( $diff_field || $diff_version ) ? ''; } $table .= '
' . esc_html_x( 'Current', 'plugin' ) . '' . esc_html_x( 'Uploaded', 'plugin' ) . '
' . $label . '' . wp_strip_all_tags( $old_value ) . '' : ''; $table .= wp_strip_all_tags( $new_value ) . '
'; /** * Filters the compare table output for overwriting a plugin package on upload. * * @since 5.5.0 * * @param string $table The output table with Name, Version, Author, RequiresWP, and RequiresPHP info. * @param array $current_plugin_data Array with current plugin data. * @param array $new_plugin_data Array with uploaded plugin data. */ echo apply_filters( 'install_plugin_overwrite_comparison', $table, $current_plugin_data, $new_plugin_data ); $install_actions = array(); $can_update = true; $blocked_message = '

' . esc_html__( 'The plugin cannot be updated due to the following:' ) . '

'; $blocked_message .= ''; if ( $can_update ) { if ( $this->is_downgrading ) { $warning = sprintf( /* translators: %s: Documentation URL. */ __( 'You are uploading an older version of a current plugin. You can continue to install the older version, but be sure to back up your database and files first.' ), __( 'https://developer.wordpress.org/advanced-administration/security/backup/' ) ); } else { $warning = sprintf( /* translators: %s: Documentation URL. */ __( 'You are updating a plugin. Be sure to back up your database and files first.' ), __( 'https://developer.wordpress.org/advanced-administration/security/backup/' ) ); } echo '

' . $warning . '

'; $overwrite = $this->is_downgrading ? 'downgrade-plugin' : 'update-plugin'; $install_actions['overwrite_plugin'] = sprintf( '%s', wp_nonce_url( add_query_arg( 'overwrite', $overwrite, $this->url ), 'plugin-upload' ), _x( 'Replace current with uploaded', 'plugin' ) ); } else { echo $blocked_message; } $cancel_url = add_query_arg( 'action', 'upload-plugin-cancel-overwrite', $this->url ); $install_actions['plugins_page'] = sprintf( '%s', wp_nonce_url( $cancel_url, 'plugin-upload-cancel-overwrite' ), __( 'Cancel and go back' ) ); /** * Filters the list of action links available following a single plugin installation failure * when overwriting is allowed. * * @since 5.5.0 * * @param string[] $install_actions Array of plugin action links. * @param object $api Object containing WordPress.org API plugin data. * @param array $new_plugin_data Array with uploaded plugin data. */ $install_actions = apply_filters( 'install_plugin_overwrite_actions', $install_actions, $this->api, $new_plugin_data ); if ( ! empty( $install_actions ) ) { printf( '', __( 'The uploaded file has expired. Please go back and upload it again.' ) ); echo '

' . implode( ' ', (array) $install_actions ) . '

'; } return true; } } class-wp-plugin-install-list-table.php000064400000060322147206365750014026 0ustar00no_update ) ) { foreach ( $plugin_info->no_update as $plugin ) { if ( isset( $plugin->slug ) ) { $plugin->upgrade = false; $plugins[ $plugin->slug ] = $plugin; } } } if ( isset( $plugin_info->response ) ) { foreach ( $plugin_info->response as $plugin ) { if ( isset( $plugin->slug ) ) { $plugin->upgrade = true; $plugins[ $plugin->slug ] = $plugin; } } } return $plugins; } /** * Returns a list of slugs of installed plugins, if known. * * Uses the transient data from the updates API to determine the slugs of * known installed plugins. This might be better elsewhere, perhaps even * within get_plugins(). * * @since 4.0.0 * * @return array */ protected function get_installed_plugin_slugs() { return array_keys( $this->get_installed_plugins() ); } /** * @global array $tabs * @global string $tab * @global int $paged * @global string $type * @global string $term */ public function prepare_items() { require_once ABSPATH . 'wp-admin/includes/plugin-install.php'; global $tabs, $tab, $paged, $type, $term; $tab = ! empty( $_REQUEST['tab'] ) ? sanitize_text_field( $_REQUEST['tab'] ) : ''; $paged = $this->get_pagenum(); $per_page = 36; // These are the tabs which are shown on the page. $tabs = array(); if ( 'search' === $tab ) { $tabs['search'] = __( 'Search Results' ); } if ( 'beta' === $tab || str_contains( get_bloginfo( 'version' ), '-' ) ) { $tabs['beta'] = _x( 'Beta Testing', 'Plugin Installer' ); } $tabs['featured'] = _x( 'Featured', 'Plugin Installer' ); $tabs['popular'] = _x( 'Popular', 'Plugin Installer' ); $tabs['recommended'] = _x( 'Recommended', 'Plugin Installer' ); $tabs['favorites'] = _x( 'Favorites', 'Plugin Installer' ); if ( current_user_can( 'upload_plugins' ) ) { /* * No longer a real tab. Here for filter compatibility. * Gets skipped in get_views(). */ $tabs['upload'] = __( 'Upload Plugin' ); } $nonmenu_tabs = array( 'plugin-information' ); // Valid actions to perform which do not have a Menu item. /** * Filters the tabs shown on the Add Plugins screen. * * @since 2.7.0 * * @param string[] $tabs The tabs shown on the Add Plugins screen. Defaults include * 'featured', 'popular', 'recommended', 'favorites', and 'upload'. */ $tabs = apply_filters( 'install_plugins_tabs', $tabs ); /** * Filters tabs not associated with a menu item on the Add Plugins screen. * * @since 2.7.0 * * @param string[] $nonmenu_tabs The tabs that don't have a menu item on the Add Plugins screen. */ $nonmenu_tabs = apply_filters( 'install_plugins_nonmenu_tabs', $nonmenu_tabs ); // If a non-valid menu tab has been selected, And it's not a non-menu action. if ( empty( $tab ) || ( ! isset( $tabs[ $tab ] ) && ! in_array( $tab, (array) $nonmenu_tabs, true ) ) ) { $tab = key( $tabs ); } $installed_plugins = $this->get_installed_plugins(); $args = array( 'page' => $paged, 'per_page' => $per_page, // Send the locale to the API so it can provide context-sensitive results. 'locale' => get_user_locale(), ); switch ( $tab ) { case 'search': $type = isset( $_REQUEST['type'] ) ? wp_unslash( $_REQUEST['type'] ) : 'term'; $term = isset( $_REQUEST['s'] ) ? wp_unslash( $_REQUEST['s'] ) : ''; switch ( $type ) { case 'tag': $args['tag'] = sanitize_title_with_dashes( $term ); break; case 'term': $args['search'] = $term; break; case 'author': $args['author'] = $term; break; } break; case 'featured': case 'popular': case 'new': case 'beta': $args['browse'] = $tab; break; case 'recommended': $args['browse'] = $tab; // Include the list of installed plugins so we can get relevant results. $args['installed_plugins'] = array_keys( $installed_plugins ); break; case 'favorites': $action = 'save_wporg_username_' . get_current_user_id(); if ( isset( $_GET['_wpnonce'] ) && wp_verify_nonce( wp_unslash( $_GET['_wpnonce'] ), $action ) ) { $user = isset( $_GET['user'] ) ? wp_unslash( $_GET['user'] ) : get_user_option( 'wporg_favorites' ); // If the save url parameter is passed with a falsey value, don't save the favorite user. if ( ! isset( $_GET['save'] ) || $_GET['save'] ) { update_user_meta( get_current_user_id(), 'wporg_favorites', $user ); } } else { $user = get_user_option( 'wporg_favorites' ); } if ( $user ) { $args['user'] = $user; } else { $args = false; } add_action( 'install_plugins_favorites', 'install_plugins_favorites_form', 9, 0 ); break; default: $args = false; break; } /** * Filters API request arguments for each Add Plugins screen tab. * * The dynamic portion of the hook name, `$tab`, refers to the plugin install tabs. * * Possible hook names include: * * - `install_plugins_table_api_args_favorites` * - `install_plugins_table_api_args_featured` * - `install_plugins_table_api_args_popular` * - `install_plugins_table_api_args_recommended` * - `install_plugins_table_api_args_upload` * - `install_plugins_table_api_args_search` * - `install_plugins_table_api_args_beta` * * @since 3.7.0 * * @param array|false $args Plugin install API arguments. */ $args = apply_filters( "install_plugins_table_api_args_{$tab}", $args ); if ( ! $args ) { return; } $api = plugins_api( 'query_plugins', $args ); if ( is_wp_error( $api ) ) { $this->error = $api; return; } $this->items = $api->plugins; if ( $this->orderby ) { uasort( $this->items, array( $this, 'order_callback' ) ); } $this->set_pagination_args( array( 'total_items' => $api->info['results'], 'per_page' => $args['per_page'], ) ); if ( isset( $api->info['groups'] ) ) { $this->groups = $api->info['groups']; } if ( $installed_plugins ) { $js_plugins = array_fill_keys( array( 'all', 'search', 'active', 'inactive', 'recently_activated', 'mustuse', 'dropins' ), array() ); $js_plugins['all'] = array_values( wp_list_pluck( $installed_plugins, 'plugin' ) ); $upgrade_plugins = wp_filter_object_list( $installed_plugins, array( 'upgrade' => true ), 'and', 'plugin' ); if ( $upgrade_plugins ) { $js_plugins['upgrade'] = array_values( $upgrade_plugins ); } wp_localize_script( 'updates', '_wpUpdatesItemCounts', array( 'plugins' => $js_plugins, 'totals' => wp_get_update_data(), ) ); } } /** */ public function no_items() { if ( isset( $this->error ) ) { $error_message = '

' . $this->error->get_error_message() . '

'; $error_message .= '

'; wp_admin_notice( $error_message, array( 'additional_classes' => array( 'inline', 'error' ), 'paragraph_wrap' => false, ) ); ?>
$text ) { $display_tabs[ 'plugin-install-' . $action ] = array( 'url' => self_admin_url( 'plugin-install.php?tab=' . $action ), 'label' => $text, 'current' => $action === $tab, ); } // No longer a real tab. unset( $display_tabs['plugin-install-upload'] ); return $this->get_views_links( $display_tabs ); } /** * Overrides parent views so we can use the filter bar display. */ public function views() { $views = $this->get_views(); /** This filter is documented in wp-admin/includes/class-wp-list-table.php */ $views = apply_filters( "views_{$this->screen->id}", $views ); $this->screen->render_screen_reader_content( 'heading_views' ); ?>
_args['singular']; $data_attr = ''; if ( $singular ) { $data_attr = " data-wp-lists='list:$singular'"; } $this->display_tablenav( 'top' ); ?>
screen->render_screen_reader_content( 'heading_list' ); ?>
> display_rows_or_placeholder(); ?>
display_tablenav( 'bottom' ); } /** * @global string $tab * * @param string $which */ protected function display_tablenav( $which ) { if ( 'featured' === $GLOBALS['tab'] ) { return; } if ( 'top' === $which ) { wp_referer_field(); ?>
pagination( $which ); ?>
pagination( $which ); ?>
_args['plural'] ); } /** * @return string[] Array of column titles keyed by their column name. */ public function get_columns() { return array(); } /** * @param object $plugin_a * @param object $plugin_b * @return int */ private function order_callback( $plugin_a, $plugin_b ) { $orderby = $this->orderby; if ( ! isset( $plugin_a->$orderby, $plugin_b->$orderby ) ) { return 0; } $a = $plugin_a->$orderby; $b = $plugin_b->$orderby; if ( $a === $b ) { return 0; } if ( 'DESC' === $this->order ) { return ( $a < $b ) ? 1 : -1; } else { return ( $a < $b ) ? -1 : 1; } } /** * Generates the list table rows. * * @since 3.1.0 */ public function display_rows() { $plugins_allowedtags = array( 'a' => array( 'href' => array(), 'title' => array(), 'target' => array(), ), 'abbr' => array( 'title' => array() ), 'acronym' => array( 'title' => array() ), 'code' => array(), 'pre' => array(), 'em' => array(), 'strong' => array(), 'ul' => array(), 'ol' => array(), 'li' => array(), 'p' => array(), 'br' => array(), ); $plugins_group_titles = array( 'Performance' => _x( 'Performance', 'Plugin installer group title' ), 'Social' => _x( 'Social', 'Plugin installer group title' ), 'Tools' => _x( 'Tools', 'Plugin installer group title' ), ); $group = null; foreach ( (array) $this->items as $plugin ) { if ( is_object( $plugin ) ) { $plugin = (array) $plugin; } // Display the group heading if there is one. if ( isset( $plugin['group'] ) && $plugin['group'] !== $group ) { if ( isset( $this->groups[ $plugin['group'] ] ) ) { $group_name = $this->groups[ $plugin['group'] ]; if ( isset( $plugins_group_titles[ $group_name ] ) ) { $group_name = $plugins_group_titles[ $group_name ]; } } else { $group_name = $plugin['group']; } // Starting a new group, close off the divs of the last one. if ( ! empty( $group ) ) { echo '
'; } echo '

' . esc_html( $group_name ) . '

'; // Needs an extra wrapping div for nth-child selectors to work. echo '
'; $group = $plugin['group']; } $title = wp_kses( $plugin['name'], $plugins_allowedtags ); // Remove any HTML from the description. $description = strip_tags( $plugin['short_description'] ); /** * Filters the plugin card description on the Add Plugins screen. * * @since 6.0.0 * * @param string $description Plugin card description. * @param array $plugin An array of plugin data. See {@see plugins_api()} * for the list of possible values. */ $description = apply_filters( 'plugin_install_description', $description, $plugin ); $version = wp_kses( $plugin['version'], $plugins_allowedtags ); $name = strip_tags( $title . ' ' . $version ); $author = wp_kses( $plugin['author'], $plugins_allowedtags ); if ( ! empty( $author ) ) { /* translators: %s: Plugin author. */ $author = ' ' . sprintf( __( 'By %s' ), $author ) . ''; } $requires_php = isset( $plugin['requires_php'] ) ? $plugin['requires_php'] : null; $requires_wp = isset( $plugin['requires'] ) ? $plugin['requires'] : null; $compatible_php = is_php_version_compatible( $requires_php ); $compatible_wp = is_wp_version_compatible( $requires_wp ); $tested_wp = ( empty( $plugin['tested'] ) || version_compare( get_bloginfo( 'version' ), $plugin['tested'], '<=' ) ); $action_links = array(); $action_links[] = wp_get_plugin_action_button( $name, $plugin, $compatible_php, $compatible_wp ); $details_link = self_admin_url( 'plugin-install.php?tab=plugin-information&plugin=' . $plugin['slug'] . '&TB_iframe=true&width=600&height=550' ); $action_links[] = sprintf( '%s', esc_url( $details_link ), /* translators: %s: Plugin name and version. */ esc_attr( sprintf( __( 'More information about %s' ), $name ) ), esc_attr( $name ), __( 'More Details' ) ); if ( ! empty( $plugin['icons']['svg'] ) ) { $plugin_icon_url = $plugin['icons']['svg']; } elseif ( ! empty( $plugin['icons']['2x'] ) ) { $plugin_icon_url = $plugin['icons']['2x']; } elseif ( ! empty( $plugin['icons']['1x'] ) ) { $plugin_icon_url = $plugin['icons']['1x']; } else { $plugin_icon_url = $plugin['icons']['default']; } /** * Filters the install action links for a plugin. * * @since 2.7.0 * * @param string[] $action_links An array of plugin action links. * Defaults are links to Details and Install Now. * @param array $plugin An array of plugin data. See {@see plugins_api()} * for the list of possible values. */ $action_links = apply_filters( 'plugin_install_action_links', $action_links, $plugin ); $last_updated_timestamp = strtotime( $plugin['last_updated'] ); ?>
Please update WordPress, and then learn more about updating PHP.' ), self_admin_url( 'update-core.php' ), esc_url( wp_get_update_php_url() ) ); $incompatible_notice_message .= wp_update_php_annotation( '

', '', false ); } elseif ( current_user_can( 'update_core' ) ) { $incompatible_notice_message .= sprintf( /* translators: %s: URL to WordPress Updates screen. */ ' ' . __( 'Please update WordPress.' ), self_admin_url( 'update-core.php' ) ); } elseif ( current_user_can( 'update_php' ) ) { $incompatible_notice_message .= sprintf( /* translators: %s: URL to Update PHP page. */ ' ' . __( 'Learn more about updating PHP.' ), esc_url( wp_get_update_php_url() ) ); $incompatible_notice_message .= wp_update_php_annotation( '

', '', false ); } } elseif ( ! $compatible_wp ) { $incompatible_notice_message .= __( 'This plugin does not work with your version of WordPress.' ); if ( current_user_can( 'update_core' ) ) { $incompatible_notice_message .= sprintf( /* translators: %s: URL to WordPress Updates screen. */ ' ' . __( 'Please update WordPress.' ), self_admin_url( 'update-core.php' ) ); } } elseif ( ! $compatible_php ) { $incompatible_notice_message .= __( 'This plugin does not work with your version of PHP.' ); if ( current_user_can( 'update_php' ) ) { $incompatible_notice_message .= sprintf( /* translators: %s: URL to Update PHP page. */ ' ' . __( 'Learn more about updating PHP.' ), esc_url( wp_get_update_php_url() ) ); $incompatible_notice_message .= wp_update_php_annotation( '

', '', false ); } } wp_admin_notice( $incompatible_notice_message, array( 'type' => 'error', 'additional_classes' => array( 'notice-alt', 'inline' ), ) ); } ?>

get_dependencies_notice( $plugin ); if ( ! empty( $dependencies_notice ) ) { echo $dependencies_notice; } ?>
$plugin['rating'], 'type' => 'percent', 'number' => $plugin['num_ratings'], ) ); ?>
= 1000000 ) { $active_installs_millions = floor( $plugin['active_installs'] / 1000000 ); $active_installs_text = sprintf( /* translators: %s: Number of millions. */ _nx( '%s+ Million', '%s+ Million', $active_installs_millions, 'Active plugin installations' ), number_format_i18n( $active_installs_millions ) ); } elseif ( 0 === $plugin['active_installs'] ) { $active_installs_text = _x( 'Less Than 10', 'Active plugin installations' ); } else { $active_installs_text = number_format_i18n( $plugin['active_installs'] ) . '+'; } /* translators: %s: Number of installations. */ printf( __( '%s Active Installations' ), $active_installs_text ); ?>
' . __( 'Untested with your version of WordPress' ) . ''; } elseif ( ! $compatible_wp ) { echo '' . __( 'Incompatible with your version of WordPress' ) . ''; } else { echo '' . __( 'Compatible with your version of WordPress' ) . ''; } ?>
'; } } /** * Returns a notice containing a list of dependencies required by the plugin. * * @since 6.5.0 * * @param array $plugin_data An array of plugin data. See {@see plugins_api()} * for the list of possible values. * @return string A notice containing a list of dependencies required by the plugin, * or an empty string if none is required. */ protected function get_dependencies_notice( $plugin_data ) { if ( empty( $plugin_data['requires_plugins'] ) ) { return ''; } $no_name_markup = '
%s
'; $has_name_markup = '
%s %s
'; $dependencies_list = ''; foreach ( $plugin_data['requires_plugins'] as $dependency ) { $dependency_data = WP_Plugin_Dependencies::get_dependency_data( $dependency ); if ( false !== $dependency_data && ! empty( $dependency_data['name'] ) && ! empty( $dependency_data['slug'] ) && ! empty( $dependency_data['version'] ) ) { $more_details_link = $this->get_more_details_link( $dependency_data['name'], $dependency_data['slug'] ); $dependencies_list .= sprintf( $has_name_markup, esc_html( $dependency_data['name'] ), $more_details_link ); continue; } $result = plugins_api( 'plugin_information', array( 'slug' => $dependency ) ); if ( ! empty( $result->name ) ) { $more_details_link = $this->get_more_details_link( $result->name, $result->slug ); $dependencies_list .= sprintf( $has_name_markup, esc_html( $result->name ), $more_details_link ); continue; } $dependencies_list .= sprintf( $no_name_markup, esc_html( $dependency ) ); } $dependencies_notice = sprintf( '

%s

%s
', '' . __( 'Additional plugins are required' ) . '', $dependencies_list ); return $dependencies_notice; } /** * Creates a 'More details' link for the plugin. * * @since 6.5.0 * * @param string $name The plugin's name. * @param string $slug The plugin's slug. * @return string The 'More details' link for the plugin. */ protected function get_more_details_link( $name, $slug ) { $url = add_query_arg( array( 'tab' => 'plugin-information', 'plugin' => $slug, 'TB_iframe' => 'true', 'width' => '600', 'height' => '550', ), network_admin_url( 'plugin-install.php' ) ); $more_details_link = sprintf( '%4$s', esc_url( $url ), /* translators: %s: Plugin name. */ sprintf( __( 'More information about %s' ), esc_html( $name ) ), esc_attr( $name ), __( 'More Details' ) ); return $more_details_link; } } class-wp-automatic-updater.php000064400000167320147206365750012464 0ustar00is_allowed_dir( $check_dir ) ) { continue; } $checkout = is_dir( rtrim( $check_dir, '\\/' ) . "/$vcs_dir" ); if ( $checkout ) { break 2; } } } /** * Filters whether the automatic updater should consider a filesystem * location to be potentially managed by a version control system. * * @since 3.7.0 * * @param bool $checkout Whether a VCS checkout was discovered at `$context` * or ABSPATH, or anywhere higher. * @param string $context The filesystem context (a path) against which * filesystem status should be checked. */ return apply_filters( 'automatic_updates_is_vcs_checkout', $checkout, $context ); } /** * Tests to see if we can and should update a specific item. * * @since 3.7.0 * * @global wpdb $wpdb WordPress database abstraction object. * * @param string $type The type of update being checked: 'core', 'theme', * 'plugin', 'translation'. * @param object $item The update offer. * @param string $context The filesystem context (a path) against which filesystem * access and status should be checked. * @return bool True if the item should be updated, false otherwise. */ public function should_update( $type, $item, $context ) { // Used to see if WP_Filesystem is set up to allow unattended updates. $skin = new Automatic_Upgrader_Skin(); if ( $this->is_disabled() ) { return false; } // Only relax the filesystem checks when the update doesn't include new files. $allow_relaxed_file_ownership = false; if ( 'core' === $type && isset( $item->new_files ) && ! $item->new_files ) { $allow_relaxed_file_ownership = true; } // If we can't do an auto core update, we may still be able to email the user. if ( ! $skin->request_filesystem_credentials( false, $context, $allow_relaxed_file_ownership ) || $this->is_vcs_checkout( $context ) ) { if ( 'core' === $type ) { $this->send_core_update_notification_email( $item ); } return false; } // Next up, is this an item we can update? if ( 'core' === $type ) { $update = Core_Upgrader::should_update_to_version( $item->current ); } elseif ( 'plugin' === $type || 'theme' === $type ) { $update = ! empty( $item->autoupdate ); if ( ! $update && wp_is_auto_update_enabled_for_type( $type ) ) { // Check if the site admin has enabled auto-updates by default for the specific item. $auto_updates = (array) get_site_option( "auto_update_{$type}s", array() ); $update = in_array( $item->{$type}, $auto_updates, true ); } } else { $update = ! empty( $item->autoupdate ); } // If the `disable_autoupdate` flag is set, override any user-choice, but allow filters. if ( ! empty( $item->disable_autoupdate ) ) { $update = false; } /** * Filters whether to automatically update core, a plugin, a theme, or a language. * * The dynamic portion of the hook name, `$type`, refers to the type of update * being checked. * * Possible hook names include: * * - `auto_update_core` * - `auto_update_plugin` * - `auto_update_theme` * - `auto_update_translation` * * Since WordPress 3.7, minor and development versions of core, and translations have * been auto-updated by default. New installs on WordPress 5.6 or higher will also * auto-update major versions by default. Starting in 5.6, older sites can opt-in to * major version auto-updates, and auto-updates for plugins and themes. * * See the {@see 'allow_dev_auto_core_updates'}, {@see 'allow_minor_auto_core_updates'}, * and {@see 'allow_major_auto_core_updates'} filters for a more straightforward way to * adjust core updates. * * @since 3.7.0 * @since 5.5.0 The `$update` parameter accepts the value of null. * * @param bool|null $update Whether to update. The value of null is internally used * to detect whether nothing has hooked into this filter. * @param object $item The update offer. */ $update = apply_filters( "auto_update_{$type}", $update, $item ); if ( ! $update ) { if ( 'core' === $type ) { $this->send_core_update_notification_email( $item ); } return false; } // If it's a core update, are we actually compatible with its requirements? if ( 'core' === $type ) { global $wpdb; $php_compat = version_compare( PHP_VERSION, $item->php_version, '>=' ); if ( file_exists( WP_CONTENT_DIR . '/db.php' ) && empty( $wpdb->is_mysql ) ) { $mysql_compat = true; } else { $mysql_compat = version_compare( $wpdb->db_version(), $item->mysql_version, '>=' ); } if ( ! $php_compat || ! $mysql_compat ) { return false; } } // If updating a plugin or theme, ensure the minimum PHP version requirements are satisfied. if ( in_array( $type, array( 'plugin', 'theme' ), true ) ) { if ( ! empty( $item->requires_php ) && version_compare( PHP_VERSION, $item->requires_php, '<' ) ) { return false; } } return true; } /** * Notifies an administrator of a core update. * * @since 3.7.0 * * @param object $item The update offer. * @return bool True if the site administrator is notified of a core update, * false otherwise. */ protected function send_core_update_notification_email( $item ) { $notified = get_site_option( 'auto_core_update_notified' ); // Don't notify if we've already notified the same email address of the same version. if ( $notified && get_site_option( 'admin_email' ) === $notified['email'] && $notified['version'] === $item->current ) { return false; } // See if we need to notify users of a core update. $notify = ! empty( $item->notify_email ); /** * Filters whether to notify the site administrator of a new core update. * * By default, administrators are notified when the update offer received * from WordPress.org sets a particular flag. This allows some discretion * in if and when to notify. * * This filter is only evaluated once per release. If the same email address * was already notified of the same new version, WordPress won't repeatedly * email the administrator. * * This filter is also used on about.php to check if a plugin has disabled * these notifications. * * @since 3.7.0 * * @param bool $notify Whether the site administrator is notified. * @param object $item The update offer. */ if ( ! apply_filters( 'send_core_update_notification_email', $notify, $item ) ) { return false; } $this->send_email( 'manual', $item ); return true; } /** * Updates an item, if appropriate. * * @since 3.7.0 * * @param string $type The type of update being checked: 'core', 'theme', 'plugin', 'translation'. * @param object $item The update offer. * @return null|WP_Error */ public function update( $type, $item ) { $skin = new Automatic_Upgrader_Skin(); switch ( $type ) { case 'core': // The Core upgrader doesn't use the Upgrader's skin during the actual main part of the upgrade, instead, firing a filter. add_filter( 'update_feedback', array( $skin, 'feedback' ) ); $upgrader = new Core_Upgrader( $skin ); $context = ABSPATH; break; case 'plugin': $upgrader = new Plugin_Upgrader( $skin ); $context = WP_PLUGIN_DIR; // We don't support custom Plugin directories, or updates for WPMU_PLUGIN_DIR. break; case 'theme': $upgrader = new Theme_Upgrader( $skin ); $context = get_theme_root( $item->theme ); break; case 'translation': $upgrader = new Language_Pack_Upgrader( $skin ); $context = WP_CONTENT_DIR; // WP_LANG_DIR; break; } // Determine whether we can and should perform this update. if ( ! $this->should_update( $type, $item, $context ) ) { return false; } /** * Fires immediately prior to an auto-update. * * @since 4.4.0 * * @param string $type The type of update being checked: 'core', 'theme', 'plugin', or 'translation'. * @param object $item The update offer. * @param string $context The filesystem context (a path) against which filesystem access and status * should be checked. */ do_action( 'pre_auto_update', $type, $item, $context ); $upgrader_item = $item; switch ( $type ) { case 'core': /* translators: %s: WordPress version. */ $skin->feedback( __( 'Updating to WordPress %s' ), $item->version ); /* translators: %s: WordPress version. */ $item_name = sprintf( __( 'WordPress %s' ), $item->version ); break; case 'theme': $upgrader_item = $item->theme; $theme = wp_get_theme( $upgrader_item ); $item_name = $theme->Get( 'Name' ); // Add the current version so that it can be reported in the notification email. $item->current_version = $theme->get( 'Version' ); if ( empty( $item->current_version ) ) { $item->current_version = false; } /* translators: %s: Theme name. */ $skin->feedback( __( 'Updating theme: %s' ), $item_name ); break; case 'plugin': $upgrader_item = $item->plugin; $plugin_data = get_plugin_data( $context . '/' . $upgrader_item ); $item_name = $plugin_data['Name']; // Add the current version so that it can be reported in the notification email. $item->current_version = $plugin_data['Version']; if ( empty( $item->current_version ) ) { $item->current_version = false; } /* translators: %s: Plugin name. */ $skin->feedback( __( 'Updating plugin: %s' ), $item_name ); break; case 'translation': $language_item_name = $upgrader->get_name_for_update( $item ); /* translators: %s: Project name (plugin, theme, or WordPress). */ $item_name = sprintf( __( 'Translations for %s' ), $language_item_name ); /* translators: 1: Project name (plugin, theme, or WordPress), 2: Language. */ $skin->feedback( sprintf( __( 'Updating translations for %1$s (%2$s)…' ), $language_item_name, $item->language ) ); break; } $allow_relaxed_file_ownership = false; if ( 'core' === $type && isset( $item->new_files ) && ! $item->new_files ) { $allow_relaxed_file_ownership = true; } $is_debug = WP_DEBUG && WP_DEBUG_LOG; if ( 'plugin' === $type ) { $was_active = is_plugin_active( $upgrader_item ); if ( $is_debug ) { error_log( ' Upgrading plugin ' . var_export( $item->slug, true ) . '...' ); } } if ( 'theme' === $type && $is_debug ) { error_log( ' Upgrading theme ' . var_export( $item->theme, true ) . '...' ); } /* * Enable maintenance mode before upgrading the plugin or theme. * * This avoids potential non-fatal errors being detected * while scraping for a fatal error if some files are still * being moved. * * While these checks are intended only for plugins, * maintenance mode is enabled for all upgrade types as any * update could contain an error or warning, which could cause * the scrape to miss a fatal error in the plugin update. */ if ( 'translation' !== $type ) { $upgrader->maintenance_mode( true ); } // Boom, this site's about to get a whole new splash of paint! $upgrade_result = $upgrader->upgrade( $upgrader_item, array( 'clear_update_cache' => false, // Always use partial builds if possible for core updates. 'pre_check_md5' => false, // Only available for core updates. 'attempt_rollback' => true, // Allow relaxed file ownership in some scenarios. 'allow_relaxed_file_ownership' => $allow_relaxed_file_ownership, ) ); /* * After WP_Upgrader::upgrade() completes, maintenance mode is disabled. * * Re-enable maintenance mode while attempting to detect fatal errors * and potentially rolling back. * * This avoids errors if the site is visited while fatal errors exist * or while files are still being moved. */ if ( 'translation' !== $type ) { $upgrader->maintenance_mode( true ); } // If the filesystem is unavailable, false is returned. if ( false === $upgrade_result ) { $upgrade_result = new WP_Error( 'fs_unavailable', __( 'Could not access filesystem.' ) ); } if ( 'core' === $type ) { if ( is_wp_error( $upgrade_result ) && ( 'up_to_date' === $upgrade_result->get_error_code() || 'locked' === $upgrade_result->get_error_code() ) ) { // Allow visitors to browse the site again. $upgrader->maintenance_mode( false ); /* * These aren't actual errors, treat it as a skipped-update instead * to avoid triggering the post-core update failure routines. */ return false; } // Core doesn't output this, so let's append it, so we don't get confused. if ( is_wp_error( $upgrade_result ) ) { $upgrade_result->add( 'installation_failed', __( 'Installation failed.' ) ); $skin->error( $upgrade_result ); } else { $skin->feedback( __( 'WordPress updated successfully.' ) ); } } $is_debug = WP_DEBUG && WP_DEBUG_LOG; if ( 'theme' === $type && $is_debug ) { error_log( ' Theme ' . var_export( $item->theme, true ) . ' has been upgraded.' ); } if ( 'plugin' === $type ) { if ( $is_debug ) { error_log( ' Plugin ' . var_export( $item->slug, true ) . ' has been upgraded.' ); if ( is_plugin_inactive( $upgrader_item ) ) { error_log( ' ' . var_export( $upgrader_item, true ) . ' is inactive and will not be checked for fatal errors.' ); } } if ( $was_active && ! is_wp_error( $upgrade_result ) ) { /* * The usual time limit is five minutes. However, as a loopback request * is about to be performed, increase the time limit to account for this. */ if ( function_exists( 'set_time_limit' ) ) { set_time_limit( 10 * MINUTE_IN_SECONDS ); } /* * Avoids a race condition when there are 2 sequential plugins that have * fatal errors. It seems a slight delay is required for the loopback to * use the updated plugin code in the request. This can cause the second * plugin's fatal error checking to be inaccurate, and may also affect * subsequent plugin checks. */ sleep( 2 ); if ( $this->has_fatal_error() ) { $upgrade_result = new WP_Error(); $temp_backup = array( array( 'dir' => 'plugins', 'slug' => $item->slug, 'src' => WP_PLUGIN_DIR, ), ); $backup_restored = $upgrader->restore_temp_backup( $temp_backup ); if ( is_wp_error( $backup_restored ) ) { $upgrade_result->add( 'plugin_update_fatal_error_rollback_failed', sprintf( /* translators: %s: The plugin's slug. */ __( "The update for '%s' contained a fatal error. The previously installed version could not be restored." ), $item->slug ) ); $upgrade_result->merge_from( $backup_restored ); } else { $upgrade_result->add( 'plugin_update_fatal_error_rollback_successful', sprintf( /* translators: %s: The plugin's slug. */ __( "The update for '%s' contained a fatal error. The previously installed version has been restored." ), $item->slug ) ); $backup_deleted = $upgrader->delete_temp_backup( $temp_backup ); if ( is_wp_error( $backup_deleted ) ) { $upgrade_result->merge_from( $backup_deleted ); } } /* * Should emails not be working, log the message(s) so that * the log file contains context for the fatal error, * and whether a rollback was performed. * * `trigger_error()` is not used as it outputs a stack trace * to this location rather than to the fatal error, which will * appear above this entry in the log file. */ if ( $is_debug ) { error_log( ' ' . implode( "\n", $upgrade_result->get_error_messages() ) ); } } elseif ( $is_debug ) { error_log( ' The update for ' . var_export( $item->slug, true ) . ' has no fatal errors.' ); } } } // All processes are complete. Allow visitors to browse the site again. if ( 'translation' !== $type ) { $upgrader->maintenance_mode( false ); } $this->update_results[ $type ][] = (object) array( 'item' => $item, 'result' => $upgrade_result, 'name' => $item_name, 'messages' => $skin->get_upgrade_messages(), ); return $upgrade_result; } /** * Kicks off the background update process, looping through all pending updates. * * @since 3.7.0 */ public function run() { if ( $this->is_disabled() ) { return; } if ( ! is_main_network() || ! is_main_site() ) { return; } if ( ! WP_Upgrader::create_lock( 'auto_updater' ) ) { return; } $is_debug = WP_DEBUG && WP_DEBUG_LOG; if ( $is_debug ) { error_log( 'Automatic updates starting...' ); } // Don't automatically run these things, as we'll handle it ourselves. remove_action( 'upgrader_process_complete', array( 'Language_Pack_Upgrader', 'async_upgrade' ), 20 ); remove_action( 'upgrader_process_complete', 'wp_version_check' ); remove_action( 'upgrader_process_complete', 'wp_update_plugins' ); remove_action( 'upgrader_process_complete', 'wp_update_themes' ); // Next, plugins. wp_update_plugins(); // Check for plugin updates. $plugin_updates = get_site_transient( 'update_plugins' ); if ( $plugin_updates && ! empty( $plugin_updates->response ) ) { if ( $is_debug ) { error_log( ' Automatic plugin updates starting...' ); } foreach ( $plugin_updates->response as $plugin ) { $this->update( 'plugin', $plugin ); } // Force refresh of plugin update information. wp_clean_plugins_cache(); if ( $is_debug ) { error_log( ' Automatic plugin updates complete.' ); } } // Next, those themes we all love. wp_update_themes(); // Check for theme updates. $theme_updates = get_site_transient( 'update_themes' ); if ( $theme_updates && ! empty( $theme_updates->response ) ) { if ( $is_debug ) { error_log( ' Automatic theme updates starting...' ); } foreach ( $theme_updates->response as $theme ) { $this->update( 'theme', (object) $theme ); } // Force refresh of theme update information. wp_clean_themes_cache(); if ( $is_debug ) { error_log( ' Automatic theme updates complete.' ); } } if ( $is_debug ) { error_log( 'Automatic updates complete.' ); } // Next, process any core update. wp_version_check(); // Check for core updates. $core_update = find_core_auto_update(); if ( $core_update ) { $this->update( 'core', $core_update ); } /* * Clean up, and check for any pending translations. * (Core_Upgrader checks for core updates.) */ $theme_stats = array(); if ( isset( $this->update_results['theme'] ) ) { foreach ( $this->update_results['theme'] as $upgrade ) { $theme_stats[ $upgrade->item->theme ] = ( true === $upgrade->result ); } } wp_update_themes( $theme_stats ); // Check for theme updates. $plugin_stats = array(); if ( isset( $this->update_results['plugin'] ) ) { foreach ( $this->update_results['plugin'] as $upgrade ) { $plugin_stats[ $upgrade->item->plugin ] = ( true === $upgrade->result ); } } wp_update_plugins( $plugin_stats ); // Check for plugin updates. // Finally, process any new translations. $language_updates = wp_get_translation_updates(); if ( $language_updates ) { foreach ( $language_updates as $update ) { $this->update( 'translation', $update ); } // Clear existing caches. wp_clean_update_cache(); wp_version_check(); // Check for core updates. wp_update_themes(); // Check for theme updates. wp_update_plugins(); // Check for plugin updates. } // Send debugging email to admin for all development installations. if ( ! empty( $this->update_results ) ) { $development_version = str_contains( wp_get_wp_version(), '-' ); /** * Filters whether to send a debugging email for each automatic background update. * * @since 3.7.0 * * @param bool $development_version By default, emails are sent if the * install is a development version. * Return false to avoid the email. */ if ( apply_filters( 'automatic_updates_send_debug_email', $development_version ) ) { $this->send_debug_email(); } if ( ! empty( $this->update_results['core'] ) ) { $this->after_core_update( $this->update_results['core'][0] ); } elseif ( ! empty( $this->update_results['plugin'] ) || ! empty( $this->update_results['theme'] ) ) { $this->after_plugin_theme_update( $this->update_results ); } /** * Fires after all automatic updates have run. * * @since 3.8.0 * * @param array $update_results The results of all attempted updates. */ do_action( 'automatic_updates_complete', $this->update_results ); } WP_Upgrader::release_lock( 'auto_updater' ); } /** * Checks whether to send an email and avoid processing future updates after * attempting a core update. * * @since 3.7.0 * * @param object $update_result The result of the core update. Includes the update offer and result. */ protected function after_core_update( $update_result ) { $wp_version = wp_get_wp_version(); $core_update = $update_result->item; $result = $update_result->result; if ( ! is_wp_error( $result ) ) { $this->send_email( 'success', $core_update ); return; } $error_code = $result->get_error_code(); /* * Any of these WP_Error codes are critical failures, as in they occurred after we started to copy core files. * We should not try to perform a background update again until there is a successful one-click update performed by the user. */ $critical = false; if ( 'disk_full' === $error_code || str_contains( $error_code, '__copy_dir' ) ) { $critical = true; } elseif ( 'rollback_was_required' === $error_code && is_wp_error( $result->get_error_data()->rollback ) ) { // A rollback is only critical if it failed too. $critical = true; $rollback_result = $result->get_error_data()->rollback; } elseif ( str_contains( $error_code, 'do_rollback' ) ) { $critical = true; } if ( $critical ) { $critical_data = array( 'attempted' => $core_update->current, 'current' => $wp_version, 'error_code' => $error_code, 'error_data' => $result->get_error_data(), 'timestamp' => time(), 'critical' => true, ); if ( isset( $rollback_result ) ) { $critical_data['rollback_code'] = $rollback_result->get_error_code(); $critical_data['rollback_data'] = $rollback_result->get_error_data(); } update_site_option( 'auto_core_update_failed', $critical_data ); $this->send_email( 'critical', $core_update, $result ); return; } /* * Any other WP_Error code (like download_failed or files_not_writable) occurs before * we tried to copy over core files. Thus, the failures are early and graceful. * * We should avoid trying to perform a background update again for the same version. * But we can try again if another version is released. * * For certain 'transient' failures, like download_failed, we should allow retries. * In fact, let's schedule a special update for an hour from now. (It's possible * the issue could actually be on WordPress.org's side.) If that one fails, then email. */ $send = true; $transient_failures = array( 'incompatible_archive', 'download_failed', 'insane_distro', 'locked' ); if ( in_array( $error_code, $transient_failures, true ) && ! get_site_option( 'auto_core_update_failed' ) ) { wp_schedule_single_event( time() + HOUR_IN_SECONDS, 'wp_maybe_auto_update' ); $send = false; } $notified = get_site_option( 'auto_core_update_notified' ); // Don't notify if we've already notified the same email address of the same version of the same notification type. if ( $notified && 'fail' === $notified['type'] && get_site_option( 'admin_email' ) === $notified['email'] && $notified['version'] === $core_update->current ) { $send = false; } update_site_option( 'auto_core_update_failed', array( 'attempted' => $core_update->current, 'current' => $wp_version, 'error_code' => $error_code, 'error_data' => $result->get_error_data(), 'timestamp' => time(), 'retry' => in_array( $error_code, $transient_failures, true ), ) ); if ( $send ) { $this->send_email( 'fail', $core_update, $result ); } } /** * Sends an email upon the completion or failure of a background core update. * * @since 3.7.0 * * @param string $type The type of email to send. Can be one of 'success', 'fail', 'manual', 'critical'. * @param object $core_update The update offer that was attempted. * @param mixed $result Optional. The result for the core update. Can be WP_Error. */ protected function send_email( $type, $core_update, $result = null ) { update_site_option( 'auto_core_update_notified', array( 'type' => $type, 'email' => get_site_option( 'admin_email' ), 'version' => $core_update->current, 'timestamp' => time(), ) ); $next_user_core_update = get_preferred_from_update_core(); // If the update transient is empty, use the update we just performed. if ( ! $next_user_core_update ) { $next_user_core_update = $core_update; } if ( 'upgrade' === $next_user_core_update->response && version_compare( $next_user_core_update->version, $core_update->version, '>' ) ) { $newer_version_available = true; } else { $newer_version_available = false; } /** * Filters whether to send an email following an automatic background core update. * * @since 3.7.0 * * @param bool $send Whether to send the email. Default true. * @param string $type The type of email to send. Can be one of * 'success', 'fail', 'critical'. * @param object $core_update The update offer that was attempted. * @param mixed $result The result for the core update. Can be WP_Error. */ if ( 'manual' !== $type && ! apply_filters( 'auto_core_update_send_email', true, $type, $core_update, $result ) ) { return; } switch ( $type ) { case 'success': // We updated. /* translators: Site updated notification email subject. 1: Site title, 2: WordPress version. */ $subject = __( '[%1$s] Your site has updated to WordPress %2$s' ); break; case 'fail': // We tried to update but couldn't. case 'manual': // We can't update (and made no attempt). /* translators: Update available notification email subject. 1: Site title, 2: WordPress version. */ $subject = __( '[%1$s] WordPress %2$s is available. Please update!' ); break; case 'critical': // We tried to update, started to copy files, then things went wrong. /* translators: Site down notification email subject. 1: Site title. */ $subject = __( '[%1$s] URGENT: Your site may be down due to a failed update' ); break; default: return; } // If the auto-update is not to the latest version, say that the current version of WP is available instead. $version = 'success' === $type ? $core_update->current : $next_user_core_update->current; $subject = sprintf( $subject, wp_specialchars_decode( get_option( 'blogname' ), ENT_QUOTES ), $version ); $body = ''; switch ( $type ) { case 'success': $body .= sprintf( /* translators: 1: Home URL, 2: WordPress version. */ __( 'Howdy! Your site at %1$s has been updated automatically to WordPress %2$s.' ), home_url(), $core_update->current ); $body .= "\n\n"; if ( ! $newer_version_available ) { $body .= __( 'No further action is needed on your part.' ) . ' '; } // Can only reference the About screen if their update was successful. list( $about_version ) = explode( '-', $core_update->current, 2 ); /* translators: %s: WordPress version. */ $body .= sprintf( __( 'For more on version %s, see the About WordPress screen:' ), $about_version ); $body .= "\n" . admin_url( 'about.php' ); if ( $newer_version_available ) { /* translators: %s: WordPress latest version. */ $body .= "\n\n" . sprintf( __( 'WordPress %s is also now available.' ), $next_user_core_update->current ) . ' '; $body .= __( 'Updating is easy and only takes a few moments:' ); $body .= "\n" . network_admin_url( 'update-core.php' ); } break; case 'fail': case 'manual': $body .= sprintf( /* translators: 1: Home URL, 2: WordPress version. */ __( 'Please update your site at %1$s to WordPress %2$s.' ), home_url(), $next_user_core_update->current ); $body .= "\n\n"; /* * Don't show this message if there is a newer version available. * Potential for confusion, and also not useful for them to know at this point. */ if ( 'fail' === $type && ! $newer_version_available ) { $body .= __( 'An attempt was made, but your site could not be updated automatically.' ) . ' '; } $body .= __( 'Updating is easy and only takes a few moments:' ); $body .= "\n" . network_admin_url( 'update-core.php' ); break; case 'critical': if ( $newer_version_available ) { $body .= sprintf( /* translators: 1: Home URL, 2: WordPress version. */ __( 'Your site at %1$s experienced a critical failure while trying to update WordPress to version %2$s.' ), home_url(), $core_update->current ); } else { $body .= sprintf( /* translators: 1: Home URL, 2: WordPress latest version. */ __( 'Your site at %1$s experienced a critical failure while trying to update to the latest version of WordPress, %2$s.' ), home_url(), $core_update->current ); } $body .= "\n\n" . __( "This means your site may be offline or broken. Don't panic; this can be fixed." ); $body .= "\n\n" . __( "Please check out your site now. It's possible that everything is working. If it says you need to update, you should do so:" ); $body .= "\n" . network_admin_url( 'update-core.php' ); break; } $critical_support = 'critical' === $type && ! empty( $core_update->support_email ); if ( $critical_support ) { // Support offer if available. $body .= "\n\n" . sprintf( /* translators: %s: Support email address. */ __( 'The WordPress team is willing to help you. Forward this email to %s and the team will work with you to make sure your site is working.' ), $core_update->support_email ); } else { // Add a note about the support forums. $body .= "\n\n" . __( 'If you experience any issues or need support, the volunteers in the WordPress.org support forums may be able to help.' ); $body .= "\n" . __( 'https://wordpress.org/support/forums/' ); } // Updates are important! if ( 'success' !== $type || $newer_version_available ) { $body .= "\n\n" . __( 'Keeping your site updated is important for security. It also makes the internet a safer place for you and your readers.' ); } if ( $critical_support ) { $body .= ' ' . __( "Reach out to WordPress Core developers to ensure you'll never have this problem again." ); } // If things are successful and we're now on the latest, mention plugins and themes if any are out of date. if ( 'success' === $type && ! $newer_version_available && ( get_plugin_updates() || get_theme_updates() ) ) { $body .= "\n\n" . __( 'You also have some plugins or themes with updates available. Update them now:' ); $body .= "\n" . network_admin_url(); } $body .= "\n\n" . __( 'The WordPress Team' ) . "\n"; if ( 'critical' === $type && is_wp_error( $result ) ) { $body .= "\n***\n\n"; /* translators: %s: WordPress version. */ $body .= sprintf( __( 'Your site was running version %s.' ), get_bloginfo( 'version' ) ); $body .= ' ' . __( 'Some data that describes the error your site encountered has been put together.' ); $body .= ' ' . __( 'Your hosting company, support forum volunteers, or a friendly developer may be able to use this information to help you:' ); /* * If we had a rollback and we're still critical, then the rollback failed too. * Loop through all errors (the main WP_Error, the update result, the rollback result) for code, data, etc. */ if ( 'rollback_was_required' === $result->get_error_code() ) { $errors = array( $result, $result->get_error_data()->update, $result->get_error_data()->rollback ); } else { $errors = array( $result ); } foreach ( $errors as $error ) { if ( ! is_wp_error( $error ) ) { continue; } $error_code = $error->get_error_code(); /* translators: %s: Error code. */ $body .= "\n\n" . sprintf( __( 'Error code: %s' ), $error_code ); if ( 'rollback_was_required' === $error_code ) { continue; } if ( $error->get_error_message() ) { $body .= "\n" . $error->get_error_message(); } $error_data = $error->get_error_data(); if ( $error_data ) { $body .= "\n" . implode( ', ', (array) $error_data ); } } $body .= "\n"; } $to = get_site_option( 'admin_email' ); $headers = ''; $email = compact( 'to', 'subject', 'body', 'headers' ); /** * Filters the email sent following an automatic background core update. * * @since 3.7.0 * * @param array $email { * Array of email arguments that will be passed to wp_mail(). * * @type string $to The email recipient. An array of emails * can be returned, as handled by wp_mail(). * @type string $subject The email's subject. * @type string $body The email message body. * @type string $headers Any email headers, defaults to no headers. * } * @param string $type The type of email being sent. Can be one of * 'success', 'fail', 'manual', 'critical'. * @param object $core_update The update offer that was attempted. * @param mixed $result The result for the core update. Can be WP_Error. */ $email = apply_filters( 'auto_core_update_email', $email, $type, $core_update, $result ); wp_mail( $email['to'], wp_specialchars_decode( $email['subject'] ), $email['body'], $email['headers'] ); } /** * Checks whether an email should be sent after attempting plugin or theme updates. * * @since 5.5.0 * * @param array $update_results The results of update tasks. */ protected function after_plugin_theme_update( $update_results ) { $successful_updates = array(); $failed_updates = array(); if ( ! empty( $update_results['plugin'] ) ) { /** * Filters whether to send an email following an automatic background plugin update. * * @since 5.5.0 * @since 5.5.1 Added the `$update_results` parameter. * * @param bool $enabled True if plugin update notifications are enabled, false otherwise. * @param array $update_results The results of plugins update tasks. */ $notifications_enabled = apply_filters( 'auto_plugin_update_send_email', true, $update_results['plugin'] ); if ( $notifications_enabled ) { foreach ( $update_results['plugin'] as $update_result ) { if ( true === $update_result->result ) { $successful_updates['plugin'][] = $update_result; } else { $failed_updates['plugin'][] = $update_result; } } } } if ( ! empty( $update_results['theme'] ) ) { /** * Filters whether to send an email following an automatic background theme update. * * @since 5.5.0 * @since 5.5.1 Added the `$update_results` parameter. * * @param bool $enabled True if theme update notifications are enabled, false otherwise. * @param array $update_results The results of theme update tasks. */ $notifications_enabled = apply_filters( 'auto_theme_update_send_email', true, $update_results['theme'] ); if ( $notifications_enabled ) { foreach ( $update_results['theme'] as $update_result ) { if ( true === $update_result->result ) { $successful_updates['theme'][] = $update_result; } else { $failed_updates['theme'][] = $update_result; } } } } if ( empty( $successful_updates ) && empty( $failed_updates ) ) { return; } if ( empty( $failed_updates ) ) { $this->send_plugin_theme_email( 'success', $successful_updates, $failed_updates ); } elseif ( empty( $successful_updates ) ) { $this->send_plugin_theme_email( 'fail', $successful_updates, $failed_updates ); } else { $this->send_plugin_theme_email( 'mixed', $successful_updates, $failed_updates ); } } /** * Sends an email upon the completion or failure of a plugin or theme background update. * * @since 5.5.0 * * @param string $type The type of email to send. Can be one of 'success', 'fail', 'mixed'. * @param array $successful_updates A list of updates that succeeded. * @param array $failed_updates A list of updates that failed. */ protected function send_plugin_theme_email( $type, $successful_updates, $failed_updates ) { // No updates were attempted. if ( empty( $successful_updates ) && empty( $failed_updates ) ) { return; } $unique_failures = false; $past_failure_emails = get_option( 'auto_plugin_theme_update_emails', array() ); /* * When only failures have occurred, an email should only be sent if there are unique failures. * A failure is considered unique if an email has not been sent for an update attempt failure * to a plugin or theme with the same new_version. */ if ( 'fail' === $type ) { foreach ( $failed_updates as $update_type => $failures ) { foreach ( $failures as $failed_update ) { if ( ! isset( $past_failure_emails[ $failed_update->item->{$update_type} ] ) ) { $unique_failures = true; continue; } // Check that the failure represents a new failure based on the new_version. if ( version_compare( $past_failure_emails[ $failed_update->item->{$update_type} ], $failed_update->item->new_version, '<' ) ) { $unique_failures = true; } } } if ( ! $unique_failures ) { return; } } $body = array(); $successful_plugins = ( ! empty( $successful_updates['plugin'] ) ); $successful_themes = ( ! empty( $successful_updates['theme'] ) ); $failed_plugins = ( ! empty( $failed_updates['plugin'] ) ); $failed_themes = ( ! empty( $failed_updates['theme'] ) ); switch ( $type ) { case 'success': if ( $successful_plugins && $successful_themes ) { /* translators: %s: Site title. */ $subject = __( '[%s] Some plugins and themes have automatically updated' ); $body[] = sprintf( /* translators: %s: Home URL. */ __( 'Howdy! Some plugins and themes have automatically updated to their latest versions on your site at %s. No further action is needed on your part.' ), home_url() ); } elseif ( $successful_plugins ) { /* translators: %s: Site title. */ $subject = __( '[%s] Some plugins were automatically updated' ); $body[] = sprintf( /* translators: %s: Home URL. */ __( 'Howdy! Some plugins have automatically updated to their latest versions on your site at %s. No further action is needed on your part.' ), home_url() ); } else { /* translators: %s: Site title. */ $subject = __( '[%s] Some themes were automatically updated' ); $body[] = sprintf( /* translators: %s: Home URL. */ __( 'Howdy! Some themes have automatically updated to their latest versions on your site at %s. No further action is needed on your part.' ), home_url() ); } break; case 'fail': case 'mixed': if ( $failed_plugins && $failed_themes ) { /* translators: %s: Site title. */ $subject = __( '[%s] Some plugins and themes have failed to update' ); $body[] = sprintf( /* translators: %s: Home URL. */ __( 'Howdy! Plugins and themes failed to update on your site at %s.' ), home_url() ); } elseif ( $failed_plugins ) { /* translators: %s: Site title. */ $subject = __( '[%s] Some plugins have failed to update' ); $body[] = sprintf( /* translators: %s: Home URL. */ __( 'Howdy! Plugins failed to update on your site at %s.' ), home_url() ); } else { /* translators: %s: Site title. */ $subject = __( '[%s] Some themes have failed to update' ); $body[] = sprintf( /* translators: %s: Home URL. */ __( 'Howdy! Themes failed to update on your site at %s.' ), home_url() ); } break; } if ( in_array( $type, array( 'fail', 'mixed' ), true ) ) { $body[] = "\n"; $body[] = __( 'Please check your site now. It’s possible that everything is working. If there are updates available, you should update.' ); $body[] = "\n"; // List failed plugin updates. if ( ! empty( $failed_updates['plugin'] ) ) { $body[] = __( 'The following plugins failed to update. If there was a fatal error in the update, the previously installed version has been restored.' ); foreach ( $failed_updates['plugin'] as $item ) { $body_message = ''; $item_url = ''; if ( ! empty( $item->item->url ) ) { $item_url = ' : ' . esc_url( $item->item->url ); } if ( $item->item->current_version ) { $body_message .= sprintf( /* translators: 1: Plugin name, 2: Current version number, 3: New version number, 4: Plugin URL. */ __( '- %1$s (from version %2$s to %3$s)%4$s' ), html_entity_decode( $item->name ), $item->item->current_version, $item->item->new_version, $item_url ); } else { $body_message .= sprintf( /* translators: 1: Plugin name, 2: Version number, 3: Plugin URL. */ __( '- %1$s version %2$s%3$s' ), html_entity_decode( $item->name ), $item->item->new_version, $item_url ); } $body[] = $body_message; $past_failure_emails[ $item->item->plugin ] = $item->item->new_version; } $body[] = "\n"; } // List failed theme updates. if ( ! empty( $failed_updates['theme'] ) ) { $body[] = __( 'These themes failed to update:' ); foreach ( $failed_updates['theme'] as $item ) { if ( $item->item->current_version ) { $body[] = sprintf( /* translators: 1: Theme name, 2: Current version number, 3: New version number. */ __( '- %1$s (from version %2$s to %3$s)' ), html_entity_decode( $item->name ), $item->item->current_version, $item->item->new_version ); } else { $body[] = sprintf( /* translators: 1: Theme name, 2: Version number. */ __( '- %1$s version %2$s' ), html_entity_decode( $item->name ), $item->item->new_version ); } $past_failure_emails[ $item->item->theme ] = $item->item->new_version; } $body[] = "\n"; } } // List successful updates. if ( in_array( $type, array( 'success', 'mixed' ), true ) ) { $body[] = "\n"; // List successful plugin updates. if ( ! empty( $successful_updates['plugin'] ) ) { $body[] = __( 'These plugins are now up to date:' ); foreach ( $successful_updates['plugin'] as $item ) { $body_message = ''; $item_url = ''; if ( ! empty( $item->item->url ) ) { $item_url = ' : ' . esc_url( $item->item->url ); } if ( $item->item->current_version ) { $body_message .= sprintf( /* translators: 1: Plugin name, 2: Current version number, 3: New version number, 4: Plugin URL. */ __( '- %1$s (from version %2$s to %3$s)%4$s' ), html_entity_decode( $item->name ), $item->item->current_version, $item->item->new_version, $item_url ); } else { $body_message .= sprintf( /* translators: 1: Plugin name, 2: Version number, 3: Plugin URL. */ __( '- %1$s version %2$s%3$s' ), html_entity_decode( $item->name ), $item->item->new_version, $item_url ); } $body[] = $body_message; unset( $past_failure_emails[ $item->item->plugin ] ); } $body[] = "\n"; } // List successful theme updates. if ( ! empty( $successful_updates['theme'] ) ) { $body[] = __( 'These themes are now up to date:' ); foreach ( $successful_updates['theme'] as $item ) { if ( $item->item->current_version ) { $body[] = sprintf( /* translators: 1: Theme name, 2: Current version number, 3: New version number. */ __( '- %1$s (from version %2$s to %3$s)' ), html_entity_decode( $item->name ), $item->item->current_version, $item->item->new_version ); } else { $body[] = sprintf( /* translators: 1: Theme name, 2: Version number. */ __( '- %1$s version %2$s' ), html_entity_decode( $item->name ), $item->item->new_version ); } unset( $past_failure_emails[ $item->item->theme ] ); } $body[] = "\n"; } } if ( $failed_plugins ) { $body[] = sprintf( /* translators: %s: Plugins screen URL. */ __( 'To manage plugins on your site, visit the Plugins page: %s' ), admin_url( 'plugins.php' ) ); $body[] = "\n"; } if ( $failed_themes ) { $body[] = sprintf( /* translators: %s: Themes screen URL. */ __( 'To manage themes on your site, visit the Themes page: %s' ), admin_url( 'themes.php' ) ); $body[] = "\n"; } // Add a note about the support forums. $body[] = __( 'If you experience any issues or need support, the volunteers in the WordPress.org support forums may be able to help.' ); $body[] = __( 'https://wordpress.org/support/forums/' ); $body[] = "\n" . __( 'The WordPress Team' ); if ( '' !== get_option( 'blogname' ) ) { $site_title = wp_specialchars_decode( get_option( 'blogname' ), ENT_QUOTES ); } else { $site_title = parse_url( home_url(), PHP_URL_HOST ); } $body = implode( "\n", $body ); $to = get_site_option( 'admin_email' ); $subject = sprintf( $subject, $site_title ); $headers = ''; $email = compact( 'to', 'subject', 'body', 'headers' ); /** * Filters the email sent following an automatic background update for plugins and themes. * * @since 5.5.0 * * @param array $email { * Array of email arguments that will be passed to wp_mail(). * * @type string $to The email recipient. An array of emails * can be returned, as handled by wp_mail(). * @type string $subject The email's subject. * @type string $body The email message body. * @type string $headers Any email headers, defaults to no headers. * } * @param string $type The type of email being sent. Can be one of 'success', 'fail', 'mixed'. * @param array $successful_updates A list of updates that succeeded. * @param array $failed_updates A list of updates that failed. */ $email = apply_filters( 'auto_plugin_theme_update_email', $email, $type, $successful_updates, $failed_updates ); $result = wp_mail( $email['to'], wp_specialchars_decode( $email['subject'] ), $email['body'], $email['headers'] ); if ( $result ) { update_option( 'auto_plugin_theme_update_emails', $past_failure_emails ); } } /** * Prepares and sends an email of a full log of background update results, useful for debugging and geekery. * * @since 3.7.0 */ protected function send_debug_email() { $update_count = 0; foreach ( $this->update_results as $type => $updates ) { $update_count += count( $updates ); } $body = array(); $failures = 0; /* translators: %s: Network home URL. */ $body[] = sprintf( __( 'WordPress site: %s' ), network_home_url( '/' ) ); // Core. if ( isset( $this->update_results['core'] ) ) { $result = $this->update_results['core'][0]; if ( $result->result && ! is_wp_error( $result->result ) ) { /* translators: %s: WordPress version. */ $body[] = sprintf( __( 'SUCCESS: WordPress was successfully updated to %s' ), $result->name ); } else { /* translators: %s: WordPress version. */ $body[] = sprintf( __( 'FAILED: WordPress failed to update to %s' ), $result->name ); ++$failures; } $body[] = ''; } // Plugins, Themes, Translations. foreach ( array( 'plugin', 'theme', 'translation' ) as $type ) { if ( ! isset( $this->update_results[ $type ] ) ) { continue; } $success_items = wp_list_filter( $this->update_results[ $type ], array( 'result' => true ) ); if ( $success_items ) { $messages = array( 'plugin' => __( 'The following plugins were successfully updated:' ), 'theme' => __( 'The following themes were successfully updated:' ), 'translation' => __( 'The following translations were successfully updated:' ), ); $body[] = $messages[ $type ]; foreach ( wp_list_pluck( $success_items, 'name' ) as $name ) { /* translators: %s: Name of plugin / theme / translation. */ $body[] = ' * ' . sprintf( __( 'SUCCESS: %s' ), $name ); } } if ( $success_items !== $this->update_results[ $type ] ) { // Failed updates. $messages = array( 'plugin' => __( 'The following plugins failed to update:' ), 'theme' => __( 'The following themes failed to update:' ), 'translation' => __( 'The following translations failed to update:' ), ); $body[] = $messages[ $type ]; foreach ( $this->update_results[ $type ] as $item ) { if ( ! $item->result || is_wp_error( $item->result ) ) { /* translators: %s: Name of plugin / theme / translation. */ $body[] = ' * ' . sprintf( __( 'FAILED: %s' ), $item->name ); ++$failures; } } } $body[] = ''; } if ( '' !== get_bloginfo( 'name' ) ) { $site_title = wp_specialchars_decode( get_bloginfo( 'name' ), ENT_QUOTES ); } else { $site_title = parse_url( home_url(), PHP_URL_HOST ); } if ( $failures ) { $body[] = trim( __( "BETA TESTING? ============= This debugging email is sent when you are using a development version of WordPress. If you think these failures might be due to a bug in WordPress, could you report it? * Open a thread in the support forums: https://wordpress.org/support/forum/alphabeta * Or, if you're comfortable writing a bug report: https://core.trac.wordpress.org/ Thanks! -- The WordPress Team" ) ); $body[] = ''; /* translators: Background update failed notification email subject. %s: Site title. */ $subject = sprintf( __( '[%s] Background Update Failed' ), $site_title ); } else { /* translators: Background update finished notification email subject. %s: Site title. */ $subject = sprintf( __( '[%s] Background Update Finished' ), $site_title ); } $body[] = trim( __( 'UPDATE LOG ==========' ) ); $body[] = ''; foreach ( array( 'core', 'plugin', 'theme', 'translation' ) as $type ) { if ( ! isset( $this->update_results[ $type ] ) ) { continue; } foreach ( $this->update_results[ $type ] as $update ) { $body[] = $update->name; $body[] = str_repeat( '-', strlen( $update->name ) ); foreach ( $update->messages as $message ) { $body[] = ' ' . html_entity_decode( str_replace( '…', '...', $message ) ); } if ( is_wp_error( $update->result ) ) { $results = array( 'update' => $update->result ); // If we rolled back, we want to know an error that occurred then too. if ( 'rollback_was_required' === $update->result->get_error_code() ) { $results = (array) $update->result->get_error_data(); } foreach ( $results as $result_type => $result ) { if ( ! is_wp_error( $result ) ) { continue; } if ( 'rollback' === $result_type ) { /* translators: 1: Error code, 2: Error message. */ $body[] = ' ' . sprintf( __( 'Rollback Error: [%1$s] %2$s' ), $result->get_error_code(), $result->get_error_message() ); } else { /* translators: 1: Error code, 2: Error message. */ $body[] = ' ' . sprintf( __( 'Error: [%1$s] %2$s' ), $result->get_error_code(), $result->get_error_message() ); } if ( $result->get_error_data() ) { $body[] = ' ' . implode( ', ', (array) $result->get_error_data() ); } } } $body[] = ''; } } $email = array( 'to' => get_site_option( 'admin_email' ), 'subject' => $subject, 'body' => implode( "\n", $body ), 'headers' => '', ); /** * Filters the debug email that can be sent following an automatic * background core update. * * @since 3.8.0 * * @param array $email { * Array of email arguments that will be passed to wp_mail(). * * @type string $to The email recipient. An array of emails * can be returned, as handled by wp_mail(). * @type string $subject Email subject. * @type string $body Email message body. * @type string $headers Any email headers. Default empty. * } * @param int $failures The number of failures encountered while upgrading. * @param mixed $results The results of all attempted updates. */ $email = apply_filters( 'automatic_updates_debug_email', $email, $failures, $this->update_results ); wp_mail( $email['to'], wp_specialchars_decode( $email['subject'] ), $email['body'], $email['headers'] ); } /** * Performs a loopback request to check for potential fatal errors. * * Fatal errors cannot be detected unless maintenance mode is enabled. * * @since 6.6.0 * * @global int $upgrading The Unix timestamp marking when upgrading WordPress began. * * @return bool Whether a fatal error was detected. */ protected function has_fatal_error() { global $upgrading; $maintenance_file = ABSPATH . '.maintenance'; if ( ! file_exists( $maintenance_file ) ) { return false; } require $maintenance_file; if ( ! is_int( $upgrading ) ) { return false; } $scrape_key = md5( $upgrading ); $scrape_nonce = (string) $upgrading; $transient = 'scrape_key_' . $scrape_key; set_transient( $transient, $scrape_nonce, 30 ); $cookies = wp_unslash( $_COOKIE ); $scrape_params = array( 'wp_scrape_key' => $scrape_key, 'wp_scrape_nonce' => $scrape_nonce, ); $headers = array( 'Cache-Control' => 'no-cache', ); /** This filter is documented in wp-includes/class-wp-http-streams.php */ $sslverify = apply_filters( 'https_local_ssl_verify', false ); // Include Basic auth in the loopback request. if ( isset( $_SERVER['PHP_AUTH_USER'] ) && isset( $_SERVER['PHP_AUTH_PW'] ) ) { $headers['Authorization'] = 'Basic ' . base64_encode( wp_unslash( $_SERVER['PHP_AUTH_USER'] ) . ':' . wp_unslash( $_SERVER['PHP_AUTH_PW'] ) ); } // Time to wait for loopback request to finish. $timeout = 50; // 50 seconds. $is_debug = WP_DEBUG && WP_DEBUG_LOG; if ( $is_debug ) { error_log( ' Scraping home page...' ); } $needle_start = "###### wp_scraping_result_start:$scrape_key ######"; $needle_end = "###### wp_scraping_result_end:$scrape_key ######"; $url = add_query_arg( $scrape_params, home_url( '/' ) ); $response = wp_remote_get( $url, compact( 'cookies', 'headers', 'timeout', 'sslverify' ) ); if ( is_wp_error( $response ) ) { if ( $is_debug ) { error_log( 'Loopback request failed: ' . $response->get_error_message() ); } return true; } // If this outputs `true` in the log, it means there were no fatal errors detected. if ( $is_debug ) { error_log( var_export( substr( $response['body'], strpos( $response['body'], '###### wp_scraping_result_start:' ) ), true ) ); } $body = wp_remote_retrieve_body( $response ); $scrape_result_position = strpos( $body, $needle_start ); $result = null; if ( false !== $scrape_result_position ) { $error_output = substr( $body, $scrape_result_position + strlen( $needle_start ) ); $error_output = substr( $error_output, 0, strpos( $error_output, $needle_end ) ); $result = json_decode( trim( $error_output ), true ); } delete_transient( $transient ); // Only fatal errors will result in a 'type' key. return isset( $result['type'] ); } } deprecated.php000064400000121460147206365750007400 0ustar00 0) ); if ( $categories ) { foreach ( $categories as $category ) { if ( $current_cat != $category->term_id && $category_parent == $category->parent) { $pad = str_repeat( '– ', $level ); $category->name = esc_html( $category->name ); echo "\n\t"; wp_dropdown_cats( $current_cat, $current_parent, $category->term_id, $level +1, $categories ); } } } else { return false; } } /** * Register a setting and its sanitization callback * * @since 2.7.0 * @deprecated 3.0.0 Use register_setting() * @see register_setting() * * @param string $option_group A settings group name. Should correspond to an allowed option key name. * Default allowed option key names include 'general', 'discussion', 'media', * 'reading', 'writing', and 'options'. * @param string $option_name The name of an option to sanitize and save. * @param callable $sanitize_callback Optional. A callback function that sanitizes the option's value. */ function add_option_update_handler( $option_group, $option_name, $sanitize_callback = '' ) { _deprecated_function( __FUNCTION__, '3.0.0', 'register_setting()' ); register_setting( $option_group, $option_name, $sanitize_callback ); } /** * Unregister a setting * * @since 2.7.0 * @deprecated 3.0.0 Use unregister_setting() * @see unregister_setting() * * @param string $option_group The settings group name used during registration. * @param string $option_name The name of the option to unregister. * @param callable $sanitize_callback Optional. Deprecated. */ function remove_option_update_handler( $option_group, $option_name, $sanitize_callback = '' ) { _deprecated_function( __FUNCTION__, '3.0.0', 'unregister_setting()' ); unregister_setting( $option_group, $option_name, $sanitize_callback ); } /** * Determines the language to use for CodePress syntax highlighting. * * @since 2.8.0 * @deprecated 3.0.0 * * @param string $filename */ function codepress_get_lang( $filename ) { _deprecated_function( __FUNCTION__, '3.0.0' ); } /** * Adds JavaScript required to make CodePress work on the theme/plugin file editors. * * @since 2.8.0 * @deprecated 3.0.0 */ function codepress_footer_js() { _deprecated_function( __FUNCTION__, '3.0.0' ); } /** * Determine whether to use CodePress. * * @since 2.8.0 * @deprecated 3.0.0 */ function use_codepress() { _deprecated_function( __FUNCTION__, '3.0.0' ); } /** * Get all user IDs. * * @deprecated 3.1.0 Use get_users() * * @global wpdb $wpdb WordPress database abstraction object. * * @return array List of user IDs. */ function get_author_user_ids() { _deprecated_function( __FUNCTION__, '3.1.0', 'get_users()' ); global $wpdb; if ( !is_multisite() ) $level_key = $wpdb->get_blog_prefix() . 'user_level'; else $level_key = $wpdb->get_blog_prefix() . 'capabilities'; // WPMU site admins don't have user_levels. return $wpdb->get_col( $wpdb->prepare("SELECT user_id FROM $wpdb->usermeta WHERE meta_key = %s AND meta_value != '0'", $level_key) ); } /** * Gets author users who can edit posts. * * @deprecated 3.1.0 Use get_users() * * @global wpdb $wpdb WordPress database abstraction object. * * @param int $user_id User ID. * @return array|false List of editable authors. False if no editable users. */ function get_editable_authors( $user_id ) { _deprecated_function( __FUNCTION__, '3.1.0', 'get_users()' ); global $wpdb; $editable = get_editable_user_ids( $user_id ); if ( !$editable ) { return false; } else { $editable = join(',', $editable); $authors = $wpdb->get_results( "SELECT * FROM $wpdb->users WHERE ID IN ($editable) ORDER BY display_name" ); } return apply_filters('get_editable_authors', $authors); } /** * Gets the IDs of any users who can edit posts. * * @deprecated 3.1.0 Use get_users() * * @global wpdb $wpdb WordPress database abstraction object. * * @param int $user_id User ID. * @param bool $exclude_zeros Optional. Whether to exclude zeroes. Default true. * @return array Array of editable user IDs, empty array otherwise. */ function get_editable_user_ids( $user_id, $exclude_zeros = true, $post_type = 'post' ) { _deprecated_function( __FUNCTION__, '3.1.0', 'get_users()' ); global $wpdb; if ( ! $user = get_userdata( $user_id ) ) return array(); $post_type_obj = get_post_type_object($post_type); if ( ! $user->has_cap($post_type_obj->cap->edit_others_posts) ) { if ( $user->has_cap($post_type_obj->cap->edit_posts) || ! $exclude_zeros ) return array($user->ID); else return array(); } if ( !is_multisite() ) $level_key = $wpdb->get_blog_prefix() . 'user_level'; else $level_key = $wpdb->get_blog_prefix() . 'capabilities'; // WPMU site admins don't have user_levels. $query = $wpdb->prepare("SELECT user_id FROM $wpdb->usermeta WHERE meta_key = %s", $level_key); if ( $exclude_zeros ) $query .= " AND meta_value != '0'"; return $wpdb->get_col( $query ); } /** * Gets all users who are not authors. * * @deprecated 3.1.0 Use get_users() * * @global wpdb $wpdb WordPress database abstraction object. */ function get_nonauthor_user_ids() { _deprecated_function( __FUNCTION__, '3.1.0', 'get_users()' ); global $wpdb; if ( !is_multisite() ) $level_key = $wpdb->get_blog_prefix() . 'user_level'; else $level_key = $wpdb->get_blog_prefix() . 'capabilities'; // WPMU site admins don't have user_levels. return $wpdb->get_col( $wpdb->prepare("SELECT user_id FROM $wpdb->usermeta WHERE meta_key = %s AND meta_value = '0'", $level_key) ); } if ( ! class_exists( 'WP_User_Search', false ) ) : /** * WordPress User Search class. * * @since 2.1.0 * @deprecated 3.1.0 Use WP_User_Query */ class WP_User_Search { /** * {@internal Missing Description}} * * @since 2.1.0 * @access private * @var mixed */ var $results; /** * {@internal Missing Description}} * * @since 2.1.0 * @access private * @var string */ var $search_term; /** * Page number. * * @since 2.1.0 * @access private * @var int */ var $page; /** * Role name that users have. * * @since 2.5.0 * @access private * @var string */ var $role; /** * Raw page number. * * @since 2.1.0 * @access private * @var int|bool */ var $raw_page; /** * Amount of users to display per page. * * @since 2.1.0 * @access public * @var int */ var $users_per_page = 50; /** * {@internal Missing Description}} * * @since 2.1.0 * @access private * @var int */ var $first_user; /** * {@internal Missing Description}} * * @since 2.1.0 * @access private * @var int */ var $last_user; /** * {@internal Missing Description}} * * @since 2.1.0 * @access private * @var string */ var $query_limit; /** * {@internal Missing Description}} * * @since 3.0.0 * @access private * @var string */ var $query_orderby; /** * {@internal Missing Description}} * * @since 3.0.0 * @access private * @var string */ var $query_from; /** * {@internal Missing Description}} * * @since 3.0.0 * @access private * @var string */ var $query_where; /** * {@internal Missing Description}} * * @since 2.1.0 * @access private * @var int */ var $total_users_for_query = 0; /** * {@internal Missing Description}} * * @since 2.1.0 * @access private * @var bool */ var $too_many_total_users = false; /** * {@internal Missing Description}} * * @since 2.1.0 * @access private * @var WP_Error */ var $search_errors; /** * {@internal Missing Description}} * * @since 2.7.0 * @access private * @var string */ var $paging_text; /** * PHP5 Constructor - Sets up the object properties. * * @since 2.1.0 * * @param string $search_term Search terms string. * @param int $page Optional. Page ID. * @param string $role Role name. * @return WP_User_Search */ function __construct( $search_term = '', $page = '', $role = '' ) { _deprecated_class( 'WP_User_Search', '3.1.0', 'WP_User_Query' ); $this->search_term = wp_unslash( $search_term ); $this->raw_page = ( '' == $page ) ? false : (int) $page; $this->page = ( '' == $page ) ? 1 : (int) $page; $this->role = $role; $this->prepare_query(); $this->query(); $this->do_paging(); } /** * PHP4 Constructor - Sets up the object properties. * * @since 2.1.0 * * @param string $search_term Search terms string. * @param int $page Optional. Page ID. * @param string $role Role name. * @return WP_User_Search */ public function WP_User_Search( $search_term = '', $page = '', $role = '' ) { _deprecated_constructor( 'WP_User_Search', '3.1.0', get_class( $this ) ); self::__construct( $search_term, $page, $role ); } /** * Prepares the user search query (legacy). * * @since 2.1.0 * @access public * * @global wpdb $wpdb WordPress database abstraction object. */ public function prepare_query() { global $wpdb; $this->first_user = ($this->page - 1) * $this->users_per_page; $this->query_limit = $wpdb->prepare(" LIMIT %d, %d", $this->first_user, $this->users_per_page); $this->query_orderby = ' ORDER BY user_login'; $search_sql = ''; if ( $this->search_term ) { $searches = array(); $search_sql = 'AND ('; foreach ( array('user_login', 'user_nicename', 'user_email', 'user_url', 'display_name') as $col ) $searches[] = $wpdb->prepare( $col . ' LIKE %s', '%' . like_escape($this->search_term) . '%' ); $search_sql .= implode(' OR ', $searches); $search_sql .= ')'; } $this->query_from = " FROM $wpdb->users"; $this->query_where = " WHERE 1=1 $search_sql"; if ( $this->role ) { $this->query_from .= " INNER JOIN $wpdb->usermeta ON $wpdb->users.ID = $wpdb->usermeta.user_id"; $this->query_where .= $wpdb->prepare(" AND $wpdb->usermeta.meta_key = '{$wpdb->prefix}capabilities' AND $wpdb->usermeta.meta_value LIKE %s", '%' . $this->role . '%'); } elseif ( is_multisite() ) { $level_key = $wpdb->prefix . 'capabilities'; // WPMU site admins don't have user_levels. $this->query_from .= ", $wpdb->usermeta"; $this->query_where .= " AND $wpdb->users.ID = $wpdb->usermeta.user_id AND meta_key = '{$level_key}'"; } do_action_ref_array( 'pre_user_search', array( &$this ) ); } /** * Executes the user search query. * * @since 2.1.0 * @access public * * @global wpdb $wpdb WordPress database abstraction object. */ public function query() { global $wpdb; $this->results = $wpdb->get_col("SELECT DISTINCT($wpdb->users.ID)" . $this->query_from . $this->query_where . $this->query_orderby . $this->query_limit); if ( $this->results ) $this->total_users_for_query = $wpdb->get_var("SELECT COUNT(DISTINCT($wpdb->users.ID))" . $this->query_from . $this->query_where); // No limit. else $this->search_errors = new WP_Error('no_matching_users_found', __('No users found.')); } /** * Prepares variables for use in templates. * * @since 2.1.0 * @access public */ function prepare_vars_for_template_usage() {} /** * Handles paging for the user search query. * * @since 2.1.0 * @access public */ public function do_paging() { if ( $this->total_users_for_query > $this->users_per_page ) { // Have to page the results. $args = array(); if ( ! empty($this->search_term) ) $args['usersearch'] = urlencode($this->search_term); if ( ! empty($this->role) ) $args['role'] = urlencode($this->role); $this->paging_text = paginate_links( array( 'total' => ceil($this->total_users_for_query / $this->users_per_page), 'current' => $this->page, 'base' => 'users.php?%_%', 'format' => 'userspage=%#%', 'add_args' => $args ) ); if ( $this->paging_text ) { $this->paging_text = sprintf( /* translators: 1: Starting number of users on the current page, 2: Ending number of users, 3: Total number of users. */ '' . __( 'Displaying %1$s–%2$s of %3$s' ) . '%s', number_format_i18n( ( $this->page - 1 ) * $this->users_per_page + 1 ), number_format_i18n( min( $this->page * $this->users_per_page, $this->total_users_for_query ) ), number_format_i18n( $this->total_users_for_query ), $this->paging_text ); } } } /** * Retrieves the user search query results. * * @since 2.1.0 * @access public * * @return array */ public function get_results() { return (array) $this->results; } /** * Displaying paging text. * * @see do_paging() Builds paging text. * * @since 2.1.0 * @access public */ function page_links() { echo $this->paging_text; } /** * Whether paging is enabled. * * @see do_paging() Builds paging text. * * @since 2.1.0 * @access public * * @return bool */ function results_are_paged() { if ( $this->paging_text ) return true; return false; } /** * Whether there are search terms. * * @since 2.1.0 * @access public * * @return bool */ function is_search() { if ( $this->search_term ) return true; return false; } } endif; /** * Retrieves editable posts from other users. * * @since 2.3.0 * @deprecated 3.1.0 Use get_posts() * @see get_posts() * * @global wpdb $wpdb WordPress database abstraction object. * * @param int $user_id User ID to not retrieve posts from. * @param string $type Optional. Post type to retrieve. Accepts 'draft', 'pending' or 'any' (all). * Default 'any'. * @return array List of posts from others. */ function get_others_unpublished_posts( $user_id, $type = 'any' ) { _deprecated_function( __FUNCTION__, '3.1.0' ); global $wpdb; $editable = get_editable_user_ids( $user_id ); if ( in_array($type, array('draft', 'pending')) ) $type_sql = " post_status = '$type' "; else $type_sql = " ( post_status = 'draft' OR post_status = 'pending' ) "; $dir = ( 'pending' == $type ) ? 'ASC' : 'DESC'; if ( !$editable ) { $other_unpubs = ''; } else { $editable = join(',', $editable); $other_unpubs = $wpdb->get_results( $wpdb->prepare("SELECT ID, post_title, post_author FROM $wpdb->posts WHERE post_type = 'post' AND $type_sql AND post_author IN ($editable) AND post_author != %d ORDER BY post_modified $dir", $user_id) ); } return apply_filters('get_others_drafts', $other_unpubs); } /** * Retrieve drafts from other users. * * @deprecated 3.1.0 Use get_posts() * @see get_posts() * * @param int $user_id User ID. * @return array List of drafts from other users. */ function get_others_drafts($user_id) { _deprecated_function( __FUNCTION__, '3.1.0' ); return get_others_unpublished_posts($user_id, 'draft'); } /** * Retrieve pending review posts from other users. * * @deprecated 3.1.0 Use get_posts() * @see get_posts() * * @param int $user_id User ID. * @return array List of posts with pending review post type from other users. */ function get_others_pending($user_id) { _deprecated_function( __FUNCTION__, '3.1.0' ); return get_others_unpublished_posts($user_id, 'pending'); } /** * Output the QuickPress dashboard widget. * * @since 3.0.0 * @deprecated 3.2.0 Use wp_dashboard_quick_press() * @see wp_dashboard_quick_press() */ function wp_dashboard_quick_press_output() { _deprecated_function( __FUNCTION__, '3.2.0', 'wp_dashboard_quick_press()' ); wp_dashboard_quick_press(); } /** * Outputs the TinyMCE editor. * * @since 2.7.0 * @deprecated 3.3.0 Use wp_editor() * @see wp_editor() */ function wp_tiny_mce( $teeny = false, $settings = false ) { _deprecated_function( __FUNCTION__, '3.3.0', 'wp_editor()' ); static $num = 1; if ( ! class_exists( '_WP_Editors', false ) ) require_once ABSPATH . WPINC . '/class-wp-editor.php'; $editor_id = 'content' . $num++; $set = array( 'teeny' => $teeny, 'tinymce' => $settings ? $settings : true, 'quicktags' => false ); $set = _WP_Editors::parse_settings($editor_id, $set); _WP_Editors::editor_settings($editor_id, $set); } /** * Preloads TinyMCE dialogs. * * @deprecated 3.3.0 Use wp_editor() * @see wp_editor() */ function wp_preload_dialogs() { _deprecated_function( __FUNCTION__, '3.3.0', 'wp_editor()' ); } /** * Prints TinyMCE editor JS. * * @deprecated 3.3.0 Use wp_editor() * @see wp_editor() */ function wp_print_editor_js() { _deprecated_function( __FUNCTION__, '3.3.0', 'wp_editor()' ); } /** * Handles quicktags. * * @deprecated 3.3.0 Use wp_editor() * @see wp_editor() */ function wp_quicktags() { _deprecated_function( __FUNCTION__, '3.3.0', 'wp_editor()' ); } /** * Returns the screen layout options. * * @since 2.8.0 * @deprecated 3.3.0 WP_Screen::render_screen_layout() * @see WP_Screen::render_screen_layout() */ function screen_layout( $screen ) { _deprecated_function( __FUNCTION__, '3.3.0', '$current_screen->render_screen_layout()' ); $current_screen = get_current_screen(); if ( ! $current_screen ) return ''; ob_start(); $current_screen->render_screen_layout(); return ob_get_clean(); } /** * Returns the screen's per-page options. * * @since 2.8.0 * @deprecated 3.3.0 Use WP_Screen::render_per_page_options() * @see WP_Screen::render_per_page_options() */ function screen_options( $screen ) { _deprecated_function( __FUNCTION__, '3.3.0', '$current_screen->render_per_page_options()' ); $current_screen = get_current_screen(); if ( ! $current_screen ) return ''; ob_start(); $current_screen->render_per_page_options(); return ob_get_clean(); } /** * Renders the screen's help. * * @since 2.7.0 * @deprecated 3.3.0 Use WP_Screen::render_screen_meta() * @see WP_Screen::render_screen_meta() */ function screen_meta( $screen ) { $current_screen = get_current_screen(); $current_screen->render_screen_meta(); } /** * Favorite actions were deprecated in version 3.2. Use the admin bar instead. * * @since 2.7.0 * @deprecated 3.2.0 Use WP_Admin_Bar * @see WP_Admin_Bar */ function favorite_actions() { _deprecated_function( __FUNCTION__, '3.2.0', 'WP_Admin_Bar' ); } /** * Handles uploading an image. * * @deprecated 3.3.0 Use wp_media_upload_handler() * @see wp_media_upload_handler() * * @return null|string */ function media_upload_image() { _deprecated_function( __FUNCTION__, '3.3.0', 'wp_media_upload_handler()' ); return wp_media_upload_handler(); } /** * Handles uploading an audio file. * * @deprecated 3.3.0 Use wp_media_upload_handler() * @see wp_media_upload_handler() * * @return null|string */ function media_upload_audio() { _deprecated_function( __FUNCTION__, '3.3.0', 'wp_media_upload_handler()' ); return wp_media_upload_handler(); } /** * Handles uploading a video file. * * @deprecated 3.3.0 Use wp_media_upload_handler() * @see wp_media_upload_handler() * * @return null|string */ function media_upload_video() { _deprecated_function( __FUNCTION__, '3.3.0', 'wp_media_upload_handler()' ); return wp_media_upload_handler(); } /** * Handles uploading a generic file. * * @deprecated 3.3.0 Use wp_media_upload_handler() * @see wp_media_upload_handler() * * @return null|string */ function media_upload_file() { _deprecated_function( __FUNCTION__, '3.3.0', 'wp_media_upload_handler()' ); return wp_media_upload_handler(); } /** * Handles retrieving the insert-from-URL form for an image. * * @deprecated 3.3.0 Use wp_media_insert_url_form() * @see wp_media_insert_url_form() * * @return string */ function type_url_form_image() { _deprecated_function( __FUNCTION__, '3.3.0', "wp_media_insert_url_form('image')" ); return wp_media_insert_url_form( 'image' ); } /** * Handles retrieving the insert-from-URL form for an audio file. * * @deprecated 3.3.0 Use wp_media_insert_url_form() * @see wp_media_insert_url_form() * * @return string */ function type_url_form_audio() { _deprecated_function( __FUNCTION__, '3.3.0', "wp_media_insert_url_form('audio')" ); return wp_media_insert_url_form( 'audio' ); } /** * Handles retrieving the insert-from-URL form for a video file. * * @deprecated 3.3.0 Use wp_media_insert_url_form() * @see wp_media_insert_url_form() * * @return string */ function type_url_form_video() { _deprecated_function( __FUNCTION__, '3.3.0', "wp_media_insert_url_form('video')" ); return wp_media_insert_url_form( 'video' ); } /** * Handles retrieving the insert-from-URL form for a generic file. * * @deprecated 3.3.0 Use wp_media_insert_url_form() * @see wp_media_insert_url_form() * * @return string */ function type_url_form_file() { _deprecated_function( __FUNCTION__, '3.3.0', "wp_media_insert_url_form('file')" ); return wp_media_insert_url_form( 'file' ); } /** * Add contextual help text for a page. * * Creates an 'Overview' help tab. * * @since 2.7.0 * @deprecated 3.3.0 Use WP_Screen::add_help_tab() * @see WP_Screen::add_help_tab() * * @param string $screen The handle for the screen to add help to. This is usually * the hook name returned by the `add_*_page()` functions. * @param string $help The content of an 'Overview' help tab. */ function add_contextual_help( $screen, $help ) { _deprecated_function( __FUNCTION__, '3.3.0', 'get_current_screen()->add_help_tab()' ); if ( is_string( $screen ) ) $screen = convert_to_screen( $screen ); WP_Screen::add_old_compat_help( $screen, $help ); } /** * Get the allowed themes for the current site. * * @since 3.0.0 * @deprecated 3.4.0 Use wp_get_themes() * @see wp_get_themes() * * @return WP_Theme[] Array of WP_Theme objects keyed by their name. */ function get_allowed_themes() { _deprecated_function( __FUNCTION__, '3.4.0', "wp_get_themes( array( 'allowed' => true ) )" ); $themes = wp_get_themes( array( 'allowed' => true ) ); $wp_themes = array(); foreach ( $themes as $theme ) { $wp_themes[ $theme->get('Name') ] = $theme; } return $wp_themes; } /** * Retrieves a list of broken themes. * * @since 1.5.0 * @deprecated 3.4.0 Use wp_get_themes() * @see wp_get_themes() * * @return array */ function get_broken_themes() { _deprecated_function( __FUNCTION__, '3.4.0', "wp_get_themes( array( 'errors' => true )" ); $themes = wp_get_themes( array( 'errors' => true ) ); $broken = array(); foreach ( $themes as $theme ) { $name = $theme->get('Name'); $broken[ $name ] = array( 'Name' => $name, 'Title' => $name, 'Description' => $theme->errors()->get_error_message(), ); } return $broken; } /** * Retrieves information on the current active theme. * * @since 2.0.0 * @deprecated 3.4.0 Use wp_get_theme() * @see wp_get_theme() * * @return WP_Theme */ function current_theme_info() { _deprecated_function( __FUNCTION__, '3.4.0', 'wp_get_theme()' ); return wp_get_theme(); } /** * This was once used to display an 'Insert into Post' button. * * Now it is deprecated and stubbed. * * @deprecated 3.5.0 */ function _insert_into_post_button( $type ) { _deprecated_function( __FUNCTION__, '3.5.0' ); } /** * This was once used to display a media button. * * Now it is deprecated and stubbed. * * @deprecated 3.5.0 */ function _media_button($title, $icon, $type, $id) { _deprecated_function( __FUNCTION__, '3.5.0' ); } /** * Gets an existing post and format it for editing. * * @since 2.0.0 * @deprecated 3.5.0 Use get_post() * @see get_post() * * @param int $id * @return WP_Post */ function get_post_to_edit( $id ) { _deprecated_function( __FUNCTION__, '3.5.0', 'get_post()' ); return get_post( $id, OBJECT, 'edit' ); } /** * Gets the default page information to use. * * @since 2.5.0 * @deprecated 3.5.0 Use get_default_post_to_edit() * @see get_default_post_to_edit() * * @return WP_Post Post object containing all the default post data as attributes */ function get_default_page_to_edit() { _deprecated_function( __FUNCTION__, '3.5.0', "get_default_post_to_edit( 'page' )" ); $page = get_default_post_to_edit(); $page->post_type = 'page'; return $page; } /** * This was once used to create a thumbnail from an Image given a maximum side size. * * @since 1.2.0 * @deprecated 3.5.0 Use image_resize() * @see image_resize() * * @param mixed $file Filename of the original image, Or attachment ID. * @param int $max_side Maximum length of a single side for the thumbnail. * @param mixed $deprecated Never used. * @return string Thumbnail path on success, Error string on failure. */ function wp_create_thumbnail( $file, $max_side, $deprecated = '' ) { _deprecated_function( __FUNCTION__, '3.5.0', 'image_resize()' ); return apply_filters( 'wp_create_thumbnail', image_resize( $file, $max_side, $max_side ) ); } /** * This was once used to display a meta box for the nav menu theme locations. * * Deprecated in favor of a 'Manage Locations' tab added to nav menus management screen. * * @since 3.0.0 * @deprecated 3.6.0 */ function wp_nav_menu_locations_meta_box() { _deprecated_function( __FUNCTION__, '3.6.0' ); } /** * This was once used to kick-off the Core Updater. * * Deprecated in favor of instantiating a Core_Upgrader instance directly, * and calling the 'upgrade' method. * * @since 2.7.0 * @deprecated 3.7.0 Use Core_Upgrader * @see Core_Upgrader */ function wp_update_core($current, $feedback = '') { _deprecated_function( __FUNCTION__, '3.7.0', 'new Core_Upgrader();' ); if ( !empty($feedback) ) add_filter('update_feedback', $feedback); require ABSPATH . 'wp-admin/includes/class-wp-upgrader.php'; $upgrader = new Core_Upgrader(); return $upgrader->upgrade($current); } /** * This was once used to kick-off the Plugin Updater. * * Deprecated in favor of instantiating a Plugin_Upgrader instance directly, * and calling the 'upgrade' method. * Unused since 2.8.0. * * @since 2.5.0 * @deprecated 3.7.0 Use Plugin_Upgrader * @see Plugin_Upgrader */ function wp_update_plugin($plugin, $feedback = '') { _deprecated_function( __FUNCTION__, '3.7.0', 'new Plugin_Upgrader();' ); if ( !empty($feedback) ) add_filter('update_feedback', $feedback); require ABSPATH . 'wp-admin/includes/class-wp-upgrader.php'; $upgrader = new Plugin_Upgrader(); return $upgrader->upgrade($plugin); } /** * This was once used to kick-off the Theme Updater. * * Deprecated in favor of instantiating a Theme_Upgrader instance directly, * and calling the 'upgrade' method. * Unused since 2.8.0. * * @since 2.7.0 * @deprecated 3.7.0 Use Theme_Upgrader * @see Theme_Upgrader */ function wp_update_theme($theme, $feedback = '') { _deprecated_function( __FUNCTION__, '3.7.0', 'new Theme_Upgrader();' ); if ( !empty($feedback) ) add_filter('update_feedback', $feedback); require ABSPATH . 'wp-admin/includes/class-wp-upgrader.php'; $upgrader = new Theme_Upgrader(); return $upgrader->upgrade($theme); } /** * This was once used to display attachment links. Now it is deprecated and stubbed. * * @since 2.0.0 * @deprecated 3.7.0 * * @param int|bool $id */ function the_attachment_links( $id = false ) { _deprecated_function( __FUNCTION__, '3.7.0' ); } /** * Displays a screen icon. * * @since 2.7.0 * @deprecated 3.8.0 */ function screen_icon() { _deprecated_function( __FUNCTION__, '3.8.0' ); echo get_screen_icon(); } /** * Retrieves the screen icon (no longer used in 3.8+). * * @since 3.2.0 * @deprecated 3.8.0 * * @return string An HTML comment explaining that icons are no longer used. */ function get_screen_icon() { _deprecated_function( __FUNCTION__, '3.8.0' ); return ''; } /** * Deprecated dashboard widget controls. * * @since 2.5.0 * @deprecated 3.8.0 */ function wp_dashboard_incoming_links_output() {} /** * Deprecated dashboard secondary output. * * @deprecated 3.8.0 */ function wp_dashboard_secondary_output() {} /** * Deprecated dashboard widget controls. * * @since 2.7.0 * @deprecated 3.8.0 */ function wp_dashboard_incoming_links() {} /** * Deprecated dashboard incoming links control. * * @deprecated 3.8.0 */ function wp_dashboard_incoming_links_control() {} /** * Deprecated dashboard plugins control. * * @deprecated 3.8.0 */ function wp_dashboard_plugins() {} /** * Deprecated dashboard primary control. * * @deprecated 3.8.0 */ function wp_dashboard_primary_control() {} /** * Deprecated dashboard recent comments control. * * @deprecated 3.8.0 */ function wp_dashboard_recent_comments_control() {} /** * Deprecated dashboard secondary section. * * @deprecated 3.8.0 */ function wp_dashboard_secondary() {} /** * Deprecated dashboard secondary control. * * @deprecated 3.8.0 */ function wp_dashboard_secondary_control() {} /** * Display plugins text for the WordPress news widget. * * @since 2.5.0 * @deprecated 4.8.0 * * @param string $rss The RSS feed URL. * @param array $args Array of arguments for this RSS feed. */ function wp_dashboard_plugins_output( $rss, $args = array() ) { _deprecated_function( __FUNCTION__, '4.8.0' ); // Plugin feeds plus link to install them. $popular = fetch_feed( $args['url']['popular'] ); if ( false === $plugin_slugs = get_transient( 'plugin_slugs' ) ) { $plugin_slugs = array_keys( get_plugins() ); set_transient( 'plugin_slugs', $plugin_slugs, DAY_IN_SECONDS ); } echo ''; } /** * This was once used to move child posts to a new parent. * * @since 2.3.0 * @deprecated 3.9.0 * @access private * * @param int $old_ID * @param int $new_ID */ function _relocate_children( $old_ID, $new_ID ) { _deprecated_function( __FUNCTION__, '3.9.0' ); } /** * Add a top-level menu page in the 'objects' section. * * This function takes a capability which will be used to determine whether * or not a page is included in the menu. * * The function which is hooked in to handle the output of the page must check * that the user has the required capability as well. * * @since 2.7.0 * * @deprecated 4.5.0 Use add_menu_page() * @see add_menu_page() * @global int $_wp_last_object_menu * * @param string $page_title The text to be displayed in the title tags of the page when the menu is selected. * @param string $menu_title The text to be used for the menu. * @param string $capability The capability required for this menu to be displayed to the user. * @param string $menu_slug The slug name to refer to this menu by (should be unique for this menu). * @param callable $callback Optional. The function to be called to output the content for this page. * @param string $icon_url Optional. The URL to the icon to be used for this menu. * @return string The resulting page's hook_suffix. */ function add_object_page( $page_title, $menu_title, $capability, $menu_slug, $callback = '', $icon_url = '') { _deprecated_function( __FUNCTION__, '4.5.0', 'add_menu_page()' ); global $_wp_last_object_menu; $_wp_last_object_menu++; return add_menu_page($page_title, $menu_title, $capability, $menu_slug, $callback, $icon_url, $_wp_last_object_menu); } /** * Add a top-level menu page in the 'utility' section. * * This function takes a capability which will be used to determine whether * or not a page is included in the menu. * * The function which is hooked in to handle the output of the page must check * that the user has the required capability as well. * * @since 2.7.0 * * @deprecated 4.5.0 Use add_menu_page() * @see add_menu_page() * @global int $_wp_last_utility_menu * * @param string $page_title The text to be displayed in the title tags of the page when the menu is selected. * @param string $menu_title The text to be used for the menu. * @param string $capability The capability required for this menu to be displayed to the user. * @param string $menu_slug The slug name to refer to this menu by (should be unique for this menu). * @param callable $callback Optional. The function to be called to output the content for this page. * @param string $icon_url Optional. The URL to the icon to be used for this menu. * @return string The resulting page's hook_suffix. */ function add_utility_page( $page_title, $menu_title, $capability, $menu_slug, $callback = '', $icon_url = '') { _deprecated_function( __FUNCTION__, '4.5.0', 'add_menu_page()' ); global $_wp_last_utility_menu; $_wp_last_utility_menu++; return add_menu_page($page_title, $menu_title, $capability, $menu_slug, $callback, $icon_url, $_wp_last_utility_menu); } /** * Disables autocomplete on the 'post' form (Add/Edit Post screens) for WebKit browsers, * as they disregard the autocomplete setting on the editor textarea. That can break the editor * when the user navigates to it with the browser's Back button. See #28037 * * Replaced with wp_page_reload_on_back_button_js() that also fixes this problem. * * @since 4.0.0 * @deprecated 4.6.0 * * @link https://core.trac.wordpress.org/ticket/35852 * * @global bool $is_safari * @global bool $is_chrome */ function post_form_autocomplete_off() { global $is_safari, $is_chrome; _deprecated_function( __FUNCTION__, '4.6.0' ); if ( $is_safari || $is_chrome ) { echo ' autocomplete="off"'; } } /** * Display JavaScript on the page. * * @since 3.5.0 * @deprecated 4.9.0 */ function options_permalink_add_js() { ?> $text ) { $instructions[ $line ] = '# ' . $text; } /** * Filters the inline instructions inserted before the dynamically generated content. * * @since 5.3.0 * * @param string[] $instructions Array of lines with inline instructions. * @param string $marker The marker being inserted. */ $instructions = apply_filters( 'insert_with_markers_inline_instructions', $instructions, $marker ); if ( $switched_locale ) { restore_previous_locale(); } $insertion = array_merge( $instructions, $insertion ); $start_marker = "# BEGIN {$marker}"; $end_marker = "# END {$marker}"; $fp = fopen( $filename, 'r+' ); if ( ! $fp ) { return false; } // Attempt to get a lock. If the filesystem supports locking, this will block until the lock is acquired. flock( $fp, LOCK_EX ); $lines = array(); while ( ! feof( $fp ) ) { $lines[] = rtrim( fgets( $fp ), "\r\n" ); } // Split out the existing file into the preceding lines, and those that appear after the marker. $pre_lines = array(); $post_lines = array(); $existing_lines = array(); $found_marker = false; $found_end_marker = false; foreach ( $lines as $line ) { if ( ! $found_marker && str_contains( $line, $start_marker ) ) { $found_marker = true; continue; } elseif ( ! $found_end_marker && str_contains( $line, $end_marker ) ) { $found_end_marker = true; continue; } if ( ! $found_marker ) { $pre_lines[] = $line; } elseif ( $found_marker && $found_end_marker ) { $post_lines[] = $line; } else { $existing_lines[] = $line; } } // Check to see if there was a change. if ( $existing_lines === $insertion ) { flock( $fp, LOCK_UN ); fclose( $fp ); return true; } // Generate the new file data. $new_file_data = implode( "\n", array_merge( $pre_lines, array( $start_marker ), $insertion, array( $end_marker ), $post_lines ) ); // Write to the start of the file, and truncate it to that length. fseek( $fp, 0 ); $bytes = fwrite( $fp, $new_file_data ); if ( $bytes ) { ftruncate( $fp, ftell( $fp ) ); } fflush( $fp ); flock( $fp, LOCK_UN ); fclose( $fp ); return (bool) $bytes; } /** * Updates the htaccess file with the current rules if it is writable. * * Always writes to the file if it exists and is writable to ensure that we * blank out old rules. * * @since 1.5.0 * * @global WP_Rewrite $wp_rewrite WordPress rewrite component. * * @return bool|null True on write success, false on failure. Null in multisite. */ function save_mod_rewrite_rules() { global $wp_rewrite; if ( is_multisite() ) { return; } // Ensure get_home_path() is declared. require_once ABSPATH . 'wp-admin/includes/file.php'; $home_path = get_home_path(); $htaccess_file = $home_path . '.htaccess'; /* * If the file doesn't already exist check for write access to the directory * and whether we have some rules. Else check for write access to the file. */ if ( ! file_exists( $htaccess_file ) && is_writable( $home_path ) && $wp_rewrite->using_mod_rewrite_permalinks() || is_writable( $htaccess_file ) ) { if ( got_mod_rewrite() ) { $rules = explode( "\n", $wp_rewrite->mod_rewrite_rules() ); return insert_with_markers( $htaccess_file, 'WordPress', $rules ); } } return false; } /** * Updates the IIS web.config file with the current rules if it is writable. * If the permalinks do not require rewrite rules then the rules are deleted from the web.config file. * * @since 2.8.0 * * @global WP_Rewrite $wp_rewrite WordPress rewrite component. * * @return bool|null True on write success, false on failure. Null in multisite. */ function iis7_save_url_rewrite_rules() { global $wp_rewrite; if ( is_multisite() ) { return; } // Ensure get_home_path() is declared. require_once ABSPATH . 'wp-admin/includes/file.php'; $home_path = get_home_path(); $web_config_file = $home_path . 'web.config'; // Using win_is_writable() instead of is_writable() because of a bug in Windows PHP. if ( iis7_supports_permalinks() && ( ! file_exists( $web_config_file ) && win_is_writable( $home_path ) && $wp_rewrite->using_mod_rewrite_permalinks() || win_is_writable( $web_config_file ) ) ) { $rule = $wp_rewrite->iis7_url_rewrite_rules( false ); if ( ! empty( $rule ) ) { return iis7_add_rewrite_rule( $web_config_file, $rule ); } else { return iis7_delete_rewrite_rule( $web_config_file ); } } return false; } /** * Updates the "recently-edited" file for the plugin or theme file editor. * * @since 1.5.0 * * @param string $file */ function update_recently_edited( $file ) { $oldfiles = (array) get_option( 'recently_edited' ); if ( $oldfiles ) { $oldfiles = array_reverse( $oldfiles ); $oldfiles[] = $file; $oldfiles = array_reverse( $oldfiles ); $oldfiles = array_unique( $oldfiles ); if ( 5 < count( $oldfiles ) ) { array_pop( $oldfiles ); } } else { $oldfiles[] = $file; } update_option( 'recently_edited', $oldfiles ); } /** * Makes a tree structure for the theme file editor's file list. * * @since 4.9.0 * @access private * * @param array $allowed_files List of theme file paths. * @return array Tree structure for listing theme files. */ function wp_make_theme_file_tree( $allowed_files ) { $tree_list = array(); foreach ( $allowed_files as $file_name => $absolute_filename ) { $list = explode( '/', $file_name ); $last_dir = &$tree_list; foreach ( $list as $dir ) { $last_dir =& $last_dir[ $dir ]; } $last_dir = $file_name; } return $tree_list; } /** * Outputs the formatted file list for the theme file editor. * * @since 4.9.0 * @access private * * @global string $relative_file Name of the file being edited relative to the * theme directory. * @global string $stylesheet The stylesheet name of the theme being edited. * * @param array|string $tree List of file/folder paths, or filename. * @param int $level The aria-level for the current iteration. * @param int $size The aria-setsize for the current iteration. * @param int $index The aria-posinset for the current iteration. */ function wp_print_theme_file_tree( $tree, $level = 2, $size = 1, $index = 1 ) { global $relative_file, $stylesheet; if ( is_array( $tree ) ) { $index = 0; $size = count( $tree ); foreach ( $tree as $label => $theme_file ) : ++$index; if ( ! is_array( $theme_file ) ) { wp_print_theme_file_tree( $theme_file, $level, $index, $size ); continue; } ?>
  • rawurlencode( $tree ), 'theme' => rawurlencode( $stylesheet ), ), self_admin_url( 'theme-editor.php' ) ); ?>
  • (' . esc_html( $filename ) . ')'; } if ( $relative_file === $filename ) { echo '' . $file_description . ''; } else { echo $file_description; } ?>
  • $plugin_file ) : ++$index; if ( ! is_array( $plugin_file ) ) { wp_print_plugin_file_tree( $plugin_file, $label, $level, $index, $size ); continue; } ?>
  • rawurlencode( $tree ), 'plugin' => rawurlencode( $plugin ), ), self_admin_url( 'plugin-editor.php' ) ); ?>
  • ' . esc_html( $label ) . ''; } else { echo esc_html( $label ); } ?>
  • get_error_data() && is_string( $message->get_error_data() ) ) { $message = $message->get_error_message() . ': ' . $message->get_error_data(); } else { $message = $message->get_error_message(); } } echo "

    $message

    \n"; wp_ob_end_flush_all(); flush(); } /** * @since 2.8.0 * * @param string $content * @return array */ function wp_doc_link_parse( $content ) { if ( ! is_string( $content ) || empty( $content ) ) { return array(); } if ( ! function_exists( 'token_get_all' ) ) { return array(); } $tokens = token_get_all( $content ); $count = count( $tokens ); $functions = array(); $ignore_functions = array(); for ( $t = 0; $t < $count - 2; $t++ ) { if ( ! is_array( $tokens[ $t ] ) ) { continue; } if ( T_STRING === $tokens[ $t ][0] && ( '(' === $tokens[ $t + 1 ] || '(' === $tokens[ $t + 2 ] ) ) { // If it's a function or class defined locally, there's not going to be any docs available. if ( ( isset( $tokens[ $t - 2 ][1] ) && in_array( $tokens[ $t - 2 ][1], array( 'function', 'class' ), true ) ) || ( isset( $tokens[ $t - 2 ][0] ) && T_OBJECT_OPERATOR === $tokens[ $t - 1 ][0] ) ) { $ignore_functions[] = $tokens[ $t ][1]; } // Add this to our stack of unique references. $functions[] = $tokens[ $t ][1]; } } $functions = array_unique( $functions ); sort( $functions ); /** * Filters the list of functions and classes to be ignored from the documentation lookup. * * @since 2.8.0 * * @param string[] $ignore_functions Array of names of functions and classes to be ignored. */ $ignore_functions = apply_filters( 'documentation_ignore_functions', $ignore_functions ); $ignore_functions = array_unique( $ignore_functions ); $output = array(); foreach ( $functions as $function ) { if ( in_array( $function, $ignore_functions, true ) ) { continue; } $output[] = $function; } return $output; } /** * Saves option for number of rows when listing posts, pages, comments, etc. * * @since 2.8.0 */ function set_screen_options() { if ( ! isset( $_POST['wp_screen_options'] ) || ! is_array( $_POST['wp_screen_options'] ) ) { return; } check_admin_referer( 'screen-options-nonce', 'screenoptionnonce' ); $user = wp_get_current_user(); if ( ! $user ) { return; } $option = $_POST['wp_screen_options']['option']; $value = $_POST['wp_screen_options']['value']; if ( sanitize_key( $option ) !== $option ) { return; } $map_option = $option; $type = str_replace( 'edit_', '', $map_option ); $type = str_replace( '_per_page', '', $type ); if ( in_array( $type, get_taxonomies(), true ) ) { $map_option = 'edit_tags_per_page'; } elseif ( in_array( $type, get_post_types(), true ) ) { $map_option = 'edit_per_page'; } else { $option = str_replace( '-', '_', $option ); } switch ( $map_option ) { case 'edit_per_page': case 'users_per_page': case 'edit_comments_per_page': case 'upload_per_page': case 'edit_tags_per_page': case 'plugins_per_page': case 'export_personal_data_requests_per_page': case 'remove_personal_data_requests_per_page': // Network admin. case 'sites_network_per_page': case 'users_network_per_page': case 'site_users_network_per_page': case 'plugins_network_per_page': case 'themes_network_per_page': case 'site_themes_network_per_page': $value = (int) $value; if ( $value < 1 || $value > 999 ) { return; } break; default: $screen_option = false; if ( str_ends_with( $option, '_page' ) || 'layout_columns' === $option ) { /** * Filters a screen option value before it is set. * * The filter can also be used to modify non-standard `[items]_per_page` * settings. See the parent function for a full list of standard options. * * Returning false from the filter will skip saving the current option. * * @since 2.8.0 * @since 5.4.2 Only applied to options ending with '_page', * or the 'layout_columns' option. * * @see set_screen_options() * * @param mixed $screen_option The value to save instead of the option value. * Default false (to skip saving the current option). * @param string $option The option name. * @param int $value The option value. */ $screen_option = apply_filters( 'set-screen-option', $screen_option, $option, $value ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores } /** * Filters a screen option value before it is set. * * The dynamic portion of the hook name, `$option`, refers to the option name. * * Returning false from the filter will skip saving the current option. * * @since 5.4.2 * * @see set_screen_options() * * @param mixed $screen_option The value to save instead of the option value. * Default false (to skip saving the current option). * @param string $option The option name. * @param int $value The option value. */ $value = apply_filters( "set_screen_option_{$option}", $screen_option, $option, $value ); if ( false === $value ) { return; } break; } update_user_meta( $user->ID, $option, $value ); $url = remove_query_arg( array( 'pagenum', 'apage', 'paged' ), wp_get_referer() ); if ( isset( $_POST['mode'] ) ) { $url = add_query_arg( array( 'mode' => $_POST['mode'] ), $url ); } wp_safe_redirect( $url ); exit; } /** * Checks if rewrite rule for WordPress already exists in the IIS 7+ configuration file. * * @since 2.8.0 * * @param string $filename The file path to the configuration file. * @return bool */ function iis7_rewrite_rule_exists( $filename ) { if ( ! file_exists( $filename ) ) { return false; } if ( ! class_exists( 'DOMDocument', false ) ) { return false; } $doc = new DOMDocument(); if ( $doc->load( $filename ) === false ) { return false; } $xpath = new DOMXPath( $doc ); $rules = $xpath->query( '/configuration/system.webServer/rewrite/rules/rule[starts-with(@name,\'wordpress\')] | /configuration/system.webServer/rewrite/rules/rule[starts-with(@name,\'WordPress\')]' ); if ( 0 === $rules->length ) { return false; } return true; } /** * Deletes WordPress rewrite rule from web.config file if it exists there. * * @since 2.8.0 * * @param string $filename Name of the configuration file. * @return bool */ function iis7_delete_rewrite_rule( $filename ) { // If configuration file does not exist then rules also do not exist, so there is nothing to delete. if ( ! file_exists( $filename ) ) { return true; } if ( ! class_exists( 'DOMDocument', false ) ) { return false; } $doc = new DOMDocument(); $doc->preserveWhiteSpace = false; if ( $doc->load( $filename ) === false ) { return false; } $xpath = new DOMXPath( $doc ); $rules = $xpath->query( '/configuration/system.webServer/rewrite/rules/rule[starts-with(@name,\'wordpress\')] | /configuration/system.webServer/rewrite/rules/rule[starts-with(@name,\'WordPress\')]' ); if ( $rules->length > 0 ) { $child = $rules->item( 0 ); $parent = $child->parentNode; $parent->removeChild( $child ); $doc->formatOutput = true; saveDomDocument( $doc, $filename ); } return true; } /** * Adds WordPress rewrite rule to the IIS 7+ configuration file. * * @since 2.8.0 * * @param string $filename The file path to the configuration file. * @param string $rewrite_rule The XML fragment with URL Rewrite rule. * @return bool */ function iis7_add_rewrite_rule( $filename, $rewrite_rule ) { if ( ! class_exists( 'DOMDocument', false ) ) { return false; } // If configuration file does not exist then we create one. if ( ! file_exists( $filename ) ) { $fp = fopen( $filename, 'w' ); fwrite( $fp, '' ); fclose( $fp ); } $doc = new DOMDocument(); $doc->preserveWhiteSpace = false; if ( $doc->load( $filename ) === false ) { return false; } $xpath = new DOMXPath( $doc ); // First check if the rule already exists as in that case there is no need to re-add it. $wordpress_rules = $xpath->query( '/configuration/system.webServer/rewrite/rules/rule[starts-with(@name,\'wordpress\')] | /configuration/system.webServer/rewrite/rules/rule[starts-with(@name,\'WordPress\')]' ); if ( $wordpress_rules->length > 0 ) { return true; } // Check the XPath to the rewrite rule and create XML nodes if they do not exist. $xml_nodes = $xpath->query( '/configuration/system.webServer/rewrite/rules' ); if ( $xml_nodes->length > 0 ) { $rules_node = $xml_nodes->item( 0 ); } else { $rules_node = $doc->createElement( 'rules' ); $xml_nodes = $xpath->query( '/configuration/system.webServer/rewrite' ); if ( $xml_nodes->length > 0 ) { $rewrite_node = $xml_nodes->item( 0 ); $rewrite_node->appendChild( $rules_node ); } else { $rewrite_node = $doc->createElement( 'rewrite' ); $rewrite_node->appendChild( $rules_node ); $xml_nodes = $xpath->query( '/configuration/system.webServer' ); if ( $xml_nodes->length > 0 ) { $system_web_server_node = $xml_nodes->item( 0 ); $system_web_server_node->appendChild( $rewrite_node ); } else { $system_web_server_node = $doc->createElement( 'system.webServer' ); $system_web_server_node->appendChild( $rewrite_node ); $xml_nodes = $xpath->query( '/configuration' ); if ( $xml_nodes->length > 0 ) { $config_node = $xml_nodes->item( 0 ); $config_node->appendChild( $system_web_server_node ); } else { $config_node = $doc->createElement( 'configuration' ); $doc->appendChild( $config_node ); $config_node->appendChild( $system_web_server_node ); } } } } $rule_fragment = $doc->createDocumentFragment(); $rule_fragment->appendXML( $rewrite_rule ); $rules_node->appendChild( $rule_fragment ); $doc->encoding = 'UTF-8'; $doc->formatOutput = true; saveDomDocument( $doc, $filename ); return true; } /** * Saves the XML document into a file. * * @since 2.8.0 * * @param DOMDocument $doc * @param string $filename */ function saveDomDocument( $doc, $filename ) { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.FunctionNameInvalid $config = $doc->saveXML(); $config = preg_replace( "/([^\r])\n/", "$1\r\n", $config ); $fp = fopen( $filename, 'w' ); fwrite( $fp, $config ); fclose( $fp ); } /** * Displays the default admin color scheme picker (Used in user-edit.php). * * @since 3.0.0 * * @global array $_wp_admin_css_colors * * @param int $user_id User ID. */ function admin_color_scheme_picker( $user_id ) { global $_wp_admin_css_colors; ksort( $_wp_admin_css_colors ); if ( isset( $_wp_admin_css_colors['fresh'] ) ) { // Set Default ('fresh') and Light should go first. $_wp_admin_css_colors = array_filter( array_merge( array( 'fresh' => '', 'light' => '', 'modern' => '', ), $_wp_admin_css_colors ) ); } $current_color = get_user_option( 'admin_color', $user_id ); if ( empty( $current_color ) || ! isset( $_wp_admin_css_colors[ $current_color ] ) ) { $current_color = 'fresh'; } ?>
    $color_info ) : ?>
    />
    colors as $html_color ) { ?>
     
    icon_colors ) ) { $icon_colors = $_wp_admin_css_colors[ $color_scheme ]->icon_colors; } elseif ( ! empty( $_wp_admin_css_colors['fresh']->icon_colors ) ) { $icon_colors = $_wp_admin_css_colors['fresh']->icon_colors; } else { // Fall back to the default set of icon colors if the default scheme is missing. $icon_colors = array( 'base' => '#a7aaad', 'focus' => '#72aee6', 'current' => '#fff', ); } echo '\n"; } /** * Displays the viewport meta in the admin. * * @since 5.5.0 */ function wp_admin_viewport_meta() { /** * Filters the viewport meta in the admin. * * @since 5.5.0 * * @param string $viewport_meta The viewport meta. */ $viewport_meta = apply_filters( 'admin_viewport_meta', 'width=device-width,initial-scale=1.0' ); if ( empty( $viewport_meta ) ) { return; } echo ''; } /** * Adds viewport meta for mobile in Customizer. * * Hooked to the {@see 'admin_viewport_meta'} filter. * * @since 5.5.0 * * @param string $viewport_meta The viewport meta. * @return string Filtered viewport meta. */ function _customizer_mobile_viewport_meta( $viewport_meta ) { return trim( $viewport_meta, ',' ) . ',minimum-scale=0.5,maximum-scale=1.2'; } /** * Checks lock status for posts displayed on the Posts screen. * * @since 3.6.0 * * @param array $response The Heartbeat response. * @param array $data The $_POST data sent. * @param string $screen_id The screen ID. * @return array The Heartbeat response. */ function wp_check_locked_posts( $response, $data, $screen_id ) { $checked = array(); if ( array_key_exists( 'wp-check-locked-posts', $data ) && is_array( $data['wp-check-locked-posts'] ) ) { foreach ( $data['wp-check-locked-posts'] as $key ) { $post_id = absint( substr( $key, 5 ) ); if ( ! $post_id ) { continue; } $user_id = wp_check_post_lock( $post_id ); if ( $user_id ) { $user = get_userdata( $user_id ); if ( $user && current_user_can( 'edit_post', $post_id ) ) { $send = array( 'name' => $user->display_name, /* translators: %s: User's display name. */ 'text' => sprintf( __( '%s is currently editing' ), $user->display_name ), ); if ( get_option( 'show_avatars' ) ) { $send['avatar_src'] = get_avatar_url( $user->ID, array( 'size' => 18 ) ); $send['avatar_src_2x'] = get_avatar_url( $user->ID, array( 'size' => 36 ) ); } $checked[ $key ] = $send; } } } } if ( ! empty( $checked ) ) { $response['wp-check-locked-posts'] = $checked; } return $response; } /** * Checks lock status on the New/Edit Post screen and refresh the lock. * * @since 3.6.0 * * @param array $response The Heartbeat response. * @param array $data The $_POST data sent. * @param string $screen_id The screen ID. * @return array The Heartbeat response. */ function wp_refresh_post_lock( $response, $data, $screen_id ) { if ( array_key_exists( 'wp-refresh-post-lock', $data ) ) { $received = $data['wp-refresh-post-lock']; $send = array(); $post_id = absint( $received['post_id'] ); if ( ! $post_id ) { return $response; } if ( ! current_user_can( 'edit_post', $post_id ) ) { return $response; } $user_id = wp_check_post_lock( $post_id ); $user = get_userdata( $user_id ); if ( $user ) { $error = array( 'name' => $user->display_name, /* translators: %s: User's display name. */ 'text' => sprintf( __( '%s has taken over and is currently editing.' ), $user->display_name ), ); if ( get_option( 'show_avatars' ) ) { $error['avatar_src'] = get_avatar_url( $user->ID, array( 'size' => 64 ) ); $error['avatar_src_2x'] = get_avatar_url( $user->ID, array( 'size' => 128 ) ); } $send['lock_error'] = $error; } else { $new_lock = wp_set_post_lock( $post_id ); if ( $new_lock ) { $send['new_lock'] = implode( ':', $new_lock ); } } $response['wp-refresh-post-lock'] = $send; } return $response; } /** * Checks nonce expiration on the New/Edit Post screen and refresh if needed. * * @since 3.6.0 * * @param array $response The Heartbeat response. * @param array $data The $_POST data sent. * @param string $screen_id The screen ID. * @return array The Heartbeat response. */ function wp_refresh_post_nonces( $response, $data, $screen_id ) { if ( array_key_exists( 'wp-refresh-post-nonces', $data ) ) { $received = $data['wp-refresh-post-nonces']; $response['wp-refresh-post-nonces'] = array( 'check' => 1 ); $post_id = absint( $received['post_id'] ); if ( ! $post_id ) { return $response; } if ( ! current_user_can( 'edit_post', $post_id ) ) { return $response; } $response['wp-refresh-post-nonces'] = array( 'replace' => array( 'getpermalinknonce' => wp_create_nonce( 'getpermalink' ), 'samplepermalinknonce' => wp_create_nonce( 'samplepermalink' ), 'closedpostboxesnonce' => wp_create_nonce( 'closedpostboxes' ), '_ajax_linking_nonce' => wp_create_nonce( 'internal-linking' ), '_wpnonce' => wp_create_nonce( 'update-post_' . $post_id ), ), ); } return $response; } /** * Refresh nonces used with meta boxes in the block editor. * * @since 6.1.0 * * @param array $response The Heartbeat response. * @param array $data The $_POST data sent. * @return array The Heartbeat response. */ function wp_refresh_metabox_loader_nonces( $response, $data ) { if ( empty( $data['wp-refresh-metabox-loader-nonces'] ) ) { return $response; } $received = $data['wp-refresh-metabox-loader-nonces']; $post_id = (int) $received['post_id']; if ( ! $post_id ) { return $response; } if ( ! current_user_can( 'edit_post', $post_id ) ) { return $response; } $response['wp-refresh-metabox-loader-nonces'] = array( 'replace' => array( 'metabox_loader_nonce' => wp_create_nonce( 'meta-box-loader' ), '_wpnonce' => wp_create_nonce( 'update-post_' . $post_id ), ), ); return $response; } /** * Adds the latest Heartbeat and REST API nonce to the Heartbeat response. * * @since 5.0.0 * * @param array $response The Heartbeat response. * @return array The Heartbeat response. */ function wp_refresh_heartbeat_nonces( $response ) { // Refresh the Rest API nonce. $response['rest_nonce'] = wp_create_nonce( 'wp_rest' ); // Refresh the Heartbeat nonce. $response['heartbeat_nonce'] = wp_create_nonce( 'heartbeat-nonce' ); return $response; } /** * Disables suspension of Heartbeat on the Add/Edit Post screens. * * @since 3.8.0 * * @global string $pagenow The filename of the current screen. * * @param array $settings An array of Heartbeat settings. * @return array Filtered Heartbeat settings. */ function wp_heartbeat_set_suspension( $settings ) { global $pagenow; if ( 'post.php' === $pagenow || 'post-new.php' === $pagenow ) { $settings['suspension'] = 'disable'; } return $settings; } /** * Performs autosave with heartbeat. * * @since 3.9.0 * * @param array $response The Heartbeat response. * @param array $data The $_POST data sent. * @return array The Heartbeat response. */ function heartbeat_autosave( $response, $data ) { if ( ! empty( $data['wp_autosave'] ) ) { $saved = wp_autosave( $data['wp_autosave'] ); if ( is_wp_error( $saved ) ) { $response['wp_autosave'] = array( 'success' => false, 'message' => $saved->get_error_message(), ); } elseif ( empty( $saved ) ) { $response['wp_autosave'] = array( 'success' => false, 'message' => __( 'Error while saving.' ), ); } else { /* translators: Draft saved date format, see https://www.php.net/manual/datetime.format.php */ $draft_saved_date_format = __( 'g:i:s a' ); $response['wp_autosave'] = array( 'success' => true, /* translators: %s: Date and time. */ 'message' => sprintf( __( 'Draft saved at %s.' ), date_i18n( $draft_saved_date_format ) ), ); } } return $response; } /** * Removes single-use URL parameters and create canonical link based on new URL. * * Removes specific query string parameters from a URL, create the canonical link, * put it in the admin header, and change the current URL to match. * * @since 4.2.0 */ function wp_admin_canonical_url() { $removable_query_args = wp_removable_query_args(); if ( empty( $removable_query_args ) ) { return; } // Ensure we're using an absolute URL. $current_url = set_url_scheme( 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ); $filtered_url = remove_query_arg( $removable_query_args, $current_url ); /** * Filters the admin canonical URL value. * * @since 6.5.0 * * @param string $filtered_url The admin canonical URL value. */ $filtered_url = apply_filters( 'wp_admin_canonical_url', $filtered_url ); ?> $hash, 'newemail' => $value, ); update_option( 'adminhash', $new_admin_email, false ); $switched_locale = switch_to_user_locale( get_current_user_id() ); /* translators: Do not translate USERNAME, ADMIN_URL, EMAIL, SITENAME, SITEURL: those are placeholders. */ $email_text = __( 'Howdy ###USERNAME###, Someone with administrator capabilities recently requested to have the administration email address changed on this site: ###SITEURL### To confirm this change, please click on the following link: ###ADMIN_URL### You can safely ignore and delete this email if you do not want to take this action. This email has been sent to ###EMAIL### Regards, All at ###SITENAME### ###SITEURL###' ); /** * Filters the text of the email sent when a change of site admin email address is attempted. * * The following strings have a special meaning and will get replaced dynamically: * - ###USERNAME### The current user's username. * - ###ADMIN_URL### The link to click on to confirm the email change. * - ###EMAIL### The proposed new site admin email address. * - ###SITENAME### The name of the site. * - ###SITEURL### The URL to the site. * * @since MU (3.0.0) * @since 4.9.0 This filter is no longer Multisite specific. * * @param string $email_text Text in the email. * @param array $new_admin_email { * Data relating to the new site admin email address. * * @type string $hash The secure hash used in the confirmation link URL. * @type string $newemail The proposed new site admin email address. * } */ $content = apply_filters( 'new_admin_email_content', $email_text, $new_admin_email ); $current_user = wp_get_current_user(); $content = str_replace( '###USERNAME###', $current_user->user_login, $content ); $content = str_replace( '###ADMIN_URL###', esc_url( self_admin_url( 'options.php?adminhash=' . $hash ) ), $content ); $content = str_replace( '###EMAIL###', $value, $content ); $content = str_replace( '###SITENAME###', wp_specialchars_decode( get_option( 'blogname' ), ENT_QUOTES ), $content ); $content = str_replace( '###SITEURL###', home_url(), $content ); if ( '' !== get_option( 'blogname' ) ) { $site_title = wp_specialchars_decode( get_option( 'blogname' ), ENT_QUOTES ); } else { $site_title = parse_url( home_url(), PHP_URL_HOST ); } $subject = sprintf( /* translators: New admin email address notification email subject. %s: Site title. */ __( '[%s] New Admin Email Address' ), $site_title ); /** * Filters the subject of the email sent when a change of site admin email address is attempted. * * @since 6.5.0 * * @param string $subject Subject of the email. */ $subject = apply_filters( 'new_admin_email_subject', $subject ); wp_mail( $value, $subject, $content ); if ( $switched_locale ) { restore_previous_locale(); } } /** * Appends '(Draft)' to draft page titles in the privacy page dropdown * so that unpublished content is obvious. * * @since 4.9.8 * @access private * * @param string $title Page title. * @param WP_Post $page Page data object. * @return string Page title. */ function _wp_privacy_settings_filter_draft_page_titles( $title, $page ) { if ( 'draft' === $page->post_status && 'privacy' === get_current_screen()->id ) { /* translators: %s: Page title. */ $title = sprintf( __( '%s (Draft)' ), $title ); } return $title; } /** * Checks if the user needs to update PHP. * * @since 5.1.0 * @since 5.1.1 Added the {@see 'wp_is_php_version_acceptable'} filter. * * @return array|false { * Array of PHP version data. False on failure. * * @type string $recommended_version The PHP version recommended by WordPress. * @type string $minimum_version The minimum required PHP version. * @type bool $is_supported Whether the PHP version is actively supported. * @type bool $is_secure Whether the PHP version receives security updates. * @type bool $is_acceptable Whether the PHP version is still acceptable or warnings * should be shown and an update recommended. * } */ function wp_check_php_version() { $version = PHP_VERSION; $key = md5( $version ); $response = get_site_transient( 'php_check_' . $key ); if ( false === $response ) { $url = 'http://api.wordpress.org/core/serve-happy/1.0/'; if ( wp_http_supports( array( 'ssl' ) ) ) { $url = set_url_scheme( $url, 'https' ); } $url = add_query_arg( 'php_version', $version, $url ); $response = wp_remote_get( $url ); if ( is_wp_error( $response ) || 200 !== wp_remote_retrieve_response_code( $response ) ) { return false; } $response = json_decode( wp_remote_retrieve_body( $response ), true ); if ( ! is_array( $response ) ) { return false; } set_site_transient( 'php_check_' . $key, $response, WEEK_IN_SECONDS ); } if ( isset( $response['is_acceptable'] ) && $response['is_acceptable'] ) { /** * Filters whether the active PHP version is considered acceptable by WordPress. * * Returning false will trigger a PHP version warning to show up in the admin dashboard to administrators. * * This filter is only run if the wordpress.org Serve Happy API considers the PHP version acceptable, ensuring * that this filter can only make this check stricter, but not loosen it. * * @since 5.1.1 * * @param bool $is_acceptable Whether the PHP version is considered acceptable. Default true. * @param string $version PHP version checked. */ $response['is_acceptable'] = (bool) apply_filters( 'wp_is_php_version_acceptable', true, $version ); } $response['is_lower_than_future_minimum'] = false; // The minimum supported PHP version will be updated to 7.4 in the future. Check if the current version is lower. if ( version_compare( $version, '7.4', '<' ) ) { $response['is_lower_than_future_minimum'] = true; // Force showing of warnings. $response['is_acceptable'] = false; } return $response; } ajax-actions.php000064400000450113147206365750007661 0ustar00id and the JS global 'pagenow'. if ( ! empty( $_POST['screen_id'] ) ) { $screen_id = sanitize_key( $_POST['screen_id'] ); } else { $screen_id = 'front'; } if ( ! empty( $_POST['data'] ) ) { $data = wp_unslash( (array) $_POST['data'] ); /** * Filters Heartbeat Ajax response in no-privilege environments. * * @since 3.6.0 * * @param array $response The no-priv Heartbeat response. * @param array $data The $_POST data sent. * @param string $screen_id The screen ID. */ $response = apply_filters( 'heartbeat_nopriv_received', $response, $data, $screen_id ); } /** * Filters Heartbeat Ajax response in no-privilege environments when no data is passed. * * @since 3.6.0 * * @param array $response The no-priv Heartbeat response. * @param string $screen_id The screen ID. */ $response = apply_filters( 'heartbeat_nopriv_send', $response, $screen_id ); /** * Fires when Heartbeat ticks in no-privilege environments. * * Allows the transport to be easily replaced with long-polling. * * @since 3.6.0 * * @param array $response The no-priv Heartbeat response. * @param string $screen_id The screen ID. */ do_action( 'heartbeat_nopriv_tick', $response, $screen_id ); // Send the current time according to the server. $response['server_time'] = time(); wp_send_json( $response ); } // // GET-based Ajax handlers. // /** * Handles fetching a list table via AJAX. * * @since 3.1.0 */ function wp_ajax_fetch_list() { $list_class = $_GET['list_args']['class']; check_ajax_referer( "fetch-list-$list_class", '_ajax_fetch_list_nonce' ); $wp_list_table = _get_list_table( $list_class, array( 'screen' => $_GET['list_args']['screen']['id'] ) ); if ( ! $wp_list_table ) { wp_die( 0 ); } if ( ! $wp_list_table->ajax_user_can() ) { wp_die( -1 ); } $wp_list_table->ajax_response(); wp_die( 0 ); } /** * Handles tag search via AJAX. * * @since 3.1.0 */ function wp_ajax_ajax_tag_search() { if ( ! isset( $_GET['tax'] ) ) { wp_die( 0 ); } $taxonomy = sanitize_key( $_GET['tax'] ); $taxonomy_object = get_taxonomy( $taxonomy ); if ( ! $taxonomy_object ) { wp_die( 0 ); } if ( ! current_user_can( $taxonomy_object->cap->assign_terms ) ) { wp_die( -1 ); } $search = wp_unslash( $_GET['q'] ); $comma = _x( ',', 'tag delimiter' ); if ( ',' !== $comma ) { $search = str_replace( $comma, ',', $search ); } if ( str_contains( $search, ',' ) ) { $search = explode( ',', $search ); $search = $search[ count( $search ) - 1 ]; } $search = trim( $search ); /** * Filters the minimum number of characters required to fire a tag search via Ajax. * * @since 4.0.0 * * @param int $characters The minimum number of characters required. Default 2. * @param WP_Taxonomy $taxonomy_object The taxonomy object. * @param string $search The search term. */ $term_search_min_chars = (int) apply_filters( 'term_search_min_chars', 2, $taxonomy_object, $search ); /* * Require $term_search_min_chars chars for matching (default: 2) * ensure it's a non-negative, non-zero integer. */ if ( ( 0 === $term_search_min_chars ) || ( strlen( $search ) < $term_search_min_chars ) ) { wp_die(); } $results = get_terms( array( 'taxonomy' => $taxonomy, 'name__like' => $search, 'fields' => 'names', 'hide_empty' => false, 'number' => isset( $_GET['number'] ) ? (int) $_GET['number'] : 0, ) ); /** * Filters the Ajax term search results. * * @since 6.1.0 * * @param string[] $results Array of term names. * @param WP_Taxonomy $taxonomy_object The taxonomy object. * @param string $search The search term. */ $results = apply_filters( 'ajax_term_search_results', $results, $taxonomy_object, $search ); echo implode( "\n", $results ); wp_die(); } /** * Handles compression testing via AJAX. * * @since 3.1.0 */ function wp_ajax_wp_compression_test() { if ( ! current_user_can( 'manage_options' ) ) { wp_die( -1 ); } if ( ini_get( 'zlib.output_compression' ) || 'ob_gzhandler' === ini_get( 'output_handler' ) ) { // Use `update_option()` on single site to mark the option for autoloading. if ( is_multisite() ) { update_site_option( 'can_compress_scripts', 0 ); } else { update_option( 'can_compress_scripts', 0, true ); } wp_die( 0 ); } if ( isset( $_GET['test'] ) ) { header( 'Expires: Wed, 11 Jan 1984 05:00:00 GMT' ); header( 'Last-Modified: ' . gmdate( 'D, d M Y H:i:s' ) . ' GMT' ); header( 'Cache-Control: no-cache, must-revalidate, max-age=0' ); header( 'Content-Type: application/javascript; charset=UTF-8' ); $force_gzip = ( defined( 'ENFORCE_GZIP' ) && ENFORCE_GZIP ); $test_str = '"wpCompressionTest Lorem ipsum dolor sit amet consectetuer mollis sapien urna ut a. Eu nonummy condimentum fringilla tempor pretium platea vel nibh netus Maecenas. Hac molestie amet justo quis pellentesque est ultrices interdum nibh Morbi. Cras mattis pretium Phasellus ante ipsum ipsum ut sociis Suspendisse Lorem. Ante et non molestie. Porta urna Vestibulum egestas id congue nibh eu risus gravida sit. Ac augue auctor Ut et non a elit massa id sodales. Elit eu Nulla at nibh adipiscing mattis lacus mauris at tempus. Netus nibh quis suscipit nec feugiat eget sed lorem et urna. Pellentesque lacus at ut massa consectetuer ligula ut auctor semper Pellentesque. Ut metus massa nibh quam Curabitur molestie nec mauris congue. Volutpat molestie elit justo facilisis neque ac risus Ut nascetur tristique. Vitae sit lorem tellus et quis Phasellus lacus tincidunt nunc Fusce. Pharetra wisi Suspendisse mus sagittis libero lacinia Integer consequat ac Phasellus. Et urna ac cursus tortor aliquam Aliquam amet tellus volutpat Vestibulum. Justo interdum condimentum In augue congue tellus sollicitudin Quisque quis nibh."'; if ( '1' === $_GET['test'] ) { echo $test_str; wp_die(); } elseif ( '2' === $_GET['test'] ) { if ( ! isset( $_SERVER['HTTP_ACCEPT_ENCODING'] ) ) { wp_die( -1 ); } if ( false !== stripos( $_SERVER['HTTP_ACCEPT_ENCODING'], 'deflate' ) && function_exists( 'gzdeflate' ) && ! $force_gzip ) { header( 'Content-Encoding: deflate' ); $out = gzdeflate( $test_str, 1 ); } elseif ( false !== stripos( $_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip' ) && function_exists( 'gzencode' ) ) { header( 'Content-Encoding: gzip' ); $out = gzencode( $test_str, 1 ); } else { wp_die( -1 ); } echo $out; wp_die(); } elseif ( 'no' === $_GET['test'] ) { check_ajax_referer( 'update_can_compress_scripts' ); // Use `update_option()` on single site to mark the option for autoloading. if ( is_multisite() ) { update_site_option( 'can_compress_scripts', 0 ); } else { update_option( 'can_compress_scripts', 0, true ); } } elseif ( 'yes' === $_GET['test'] ) { check_ajax_referer( 'update_can_compress_scripts' ); // Use `update_option()` on single site to mark the option for autoloading. if ( is_multisite() ) { update_site_option( 'can_compress_scripts', 1 ); } else { update_option( 'can_compress_scripts', 1, true ); } } } wp_die( 0 ); } /** * Handles image editor previews via AJAX. * * @since 3.1.0 */ function wp_ajax_imgedit_preview() { $post_id = (int) $_GET['postid']; if ( empty( $post_id ) || ! current_user_can( 'edit_post', $post_id ) ) { wp_die( -1 ); } check_ajax_referer( "image_editor-$post_id" ); require_once ABSPATH . 'wp-admin/includes/image-edit.php'; if ( ! stream_preview_image( $post_id ) ) { wp_die( -1 ); } wp_die(); } /** * Handles oEmbed caching via AJAX. * * @since 3.1.0 * * @global WP_Embed $wp_embed WordPress Embed object. */ function wp_ajax_oembed_cache() { $GLOBALS['wp_embed']->cache_oembed( $_GET['post'] ); wp_die( 0 ); } /** * Handles user autocomplete via AJAX. * * @since 3.4.0 */ function wp_ajax_autocomplete_user() { if ( ! is_multisite() || ! current_user_can( 'promote_users' ) || wp_is_large_network( 'users' ) ) { wp_die( -1 ); } /** This filter is documented in wp-admin/user-new.php */ if ( ! current_user_can( 'manage_network_users' ) && ! apply_filters( 'autocomplete_users_for_site_admins', false ) ) { wp_die( -1 ); } $return = array(); /* * Check the type of request. * Current allowed values are `add` and `search`. */ if ( isset( $_REQUEST['autocomplete_type'] ) && 'search' === $_REQUEST['autocomplete_type'] ) { $type = $_REQUEST['autocomplete_type']; } else { $type = 'add'; } /* * Check the desired field for value. * Current allowed values are `user_email` and `user_login`. */ if ( isset( $_REQUEST['autocomplete_field'] ) && 'user_email' === $_REQUEST['autocomplete_field'] ) { $field = $_REQUEST['autocomplete_field']; } else { $field = 'user_login'; } // Exclude current users of this blog. if ( isset( $_REQUEST['site_id'] ) ) { $id = absint( $_REQUEST['site_id'] ); } else { $id = get_current_blog_id(); } $include_blog_users = ( 'search' === $type ? get_users( array( 'blog_id' => $id, 'fields' => 'ID', ) ) : array() ); $exclude_blog_users = ( 'add' === $type ? get_users( array( 'blog_id' => $id, 'fields' => 'ID', ) ) : array() ); $users = get_users( array( 'blog_id' => false, 'search' => '*' . $_REQUEST['term'] . '*', 'include' => $include_blog_users, 'exclude' => $exclude_blog_users, 'search_columns' => array( 'user_login', 'user_nicename', 'user_email' ), ) ); foreach ( $users as $user ) { $return[] = array( /* translators: 1: User login, 2: User email address. */ 'label' => sprintf( _x( '%1$s (%2$s)', 'user autocomplete result' ), $user->user_login, $user->user_email ), 'value' => $user->$field, ); } wp_die( wp_json_encode( $return ) ); } /** * Handles Ajax requests for community events * * @since 4.8.0 */ function wp_ajax_get_community_events() { require_once ABSPATH . 'wp-admin/includes/class-wp-community-events.php'; check_ajax_referer( 'community_events' ); $search = isset( $_POST['location'] ) ? wp_unslash( $_POST['location'] ) : ''; $timezone = isset( $_POST['timezone'] ) ? wp_unslash( $_POST['timezone'] ) : ''; $user_id = get_current_user_id(); $saved_location = get_user_option( 'community-events-location', $user_id ); $events_client = new WP_Community_Events( $user_id, $saved_location ); $events = $events_client->get_events( $search, $timezone ); $ip_changed = false; if ( is_wp_error( $events ) ) { wp_send_json_error( array( 'error' => $events->get_error_message(), ) ); } else { if ( empty( $saved_location['ip'] ) && ! empty( $events['location']['ip'] ) ) { $ip_changed = true; } elseif ( isset( $saved_location['ip'] ) && ! empty( $events['location']['ip'] ) && $saved_location['ip'] !== $events['location']['ip'] ) { $ip_changed = true; } /* * The location should only be updated when it changes. The API doesn't always return * a full location; sometimes it's missing the description or country. The location * that was saved during the initial request is known to be good and complete, though. * It should be left intact until the user explicitly changes it (either by manually * searching for a new location, or by changing their IP address). * * If the location was updated with an incomplete response from the API, then it could * break assumptions that the UI makes (e.g., that there will always be a description * that corresponds to a latitude/longitude location). * * The location is stored network-wide, so that the user doesn't have to set it on each site. */ if ( $ip_changed || $search ) { update_user_meta( $user_id, 'community-events-location', $events['location'] ); } wp_send_json_success( $events ); } } /** * Handles dashboard widgets via AJAX. * * @since 3.4.0 */ function wp_ajax_dashboard_widgets() { require_once ABSPATH . 'wp-admin/includes/dashboard.php'; $pagenow = $_GET['pagenow']; if ( 'dashboard-user' === $pagenow || 'dashboard-network' === $pagenow || 'dashboard' === $pagenow ) { set_current_screen( $pagenow ); } switch ( $_GET['widget'] ) { case 'dashboard_primary': wp_dashboard_primary(); break; } wp_die(); } /** * Handles Customizer preview logged-in status via AJAX. * * @since 3.4.0 */ function wp_ajax_logged_in() { wp_die( 1 ); } // // Ajax helpers. // /** * Sends back current comment total and new page links if they need to be updated. * * Contrary to normal success Ajax response ("1"), die with time() on success. * * @since 2.7.0 * @access private * * @param int $comment_id * @param int $delta */ function _wp_ajax_delete_comment_response( $comment_id, $delta = -1 ) { $total = isset( $_POST['_total'] ) ? (int) $_POST['_total'] : 0; $per_page = isset( $_POST['_per_page'] ) ? (int) $_POST['_per_page'] : 0; $page = isset( $_POST['_page'] ) ? (int) $_POST['_page'] : 0; $url = isset( $_POST['_url'] ) ? sanitize_url( $_POST['_url'] ) : ''; // JS didn't send us everything we need to know. Just die with success message. if ( ! $total || ! $per_page || ! $page || ! $url ) { $time = time(); $comment = get_comment( $comment_id ); $comment_status = ''; $comment_link = ''; if ( $comment ) { $comment_status = $comment->comment_approved; } if ( 1 === (int) $comment_status ) { $comment_link = get_comment_link( $comment ); } $counts = wp_count_comments(); $x = new WP_Ajax_Response( array( 'what' => 'comment', // Here for completeness - not used. 'id' => $comment_id, 'supplemental' => array( 'status' => $comment_status, 'postId' => $comment ? $comment->comment_post_ID : '', 'time' => $time, 'in_moderation' => $counts->moderated, 'i18n_comments_text' => sprintf( /* translators: %s: Number of comments. */ _n( '%s Comment', '%s Comments', $counts->approved ), number_format_i18n( $counts->approved ) ), 'i18n_moderation_text' => sprintf( /* translators: %s: Number of comments. */ _n( '%s Comment in moderation', '%s Comments in moderation', $counts->moderated ), number_format_i18n( $counts->moderated ) ), 'comment_link' => $comment_link, ), ) ); $x->send(); } $total += $delta; if ( $total < 0 ) { $total = 0; } // Only do the expensive stuff on a page-break, and about 1 other time per page. if ( 0 === $total % $per_page || 1 === mt_rand( 1, $per_page ) ) { $post_id = 0; // What type of comment count are we looking for? $status = 'all'; $parsed = parse_url( $url ); if ( isset( $parsed['query'] ) ) { parse_str( $parsed['query'], $query_vars ); if ( ! empty( $query_vars['comment_status'] ) ) { $status = $query_vars['comment_status']; } if ( ! empty( $query_vars['p'] ) ) { $post_id = (int) $query_vars['p']; } if ( ! empty( $query_vars['comment_type'] ) ) { $type = $query_vars['comment_type']; } } if ( empty( $type ) ) { // Only use the comment count if not filtering by a comment_type. $comment_count = wp_count_comments( $post_id ); // We're looking for a known type of comment count. if ( isset( $comment_count->$status ) ) { $total = $comment_count->$status; } } // Else use the decremented value from above. } // The time since the last comment count. $time = time(); $comment = get_comment( $comment_id ); $counts = wp_count_comments(); $x = new WP_Ajax_Response( array( 'what' => 'comment', 'id' => $comment_id, 'supplemental' => array( 'status' => $comment ? $comment->comment_approved : '', 'postId' => $comment ? $comment->comment_post_ID : '', /* translators: %s: Number of comments. */ 'total_items_i18n' => sprintf( _n( '%s item', '%s items', $total ), number_format_i18n( $total ) ), 'total_pages' => (int) ceil( $total / $per_page ), 'total_pages_i18n' => number_format_i18n( (int) ceil( $total / $per_page ) ), 'total' => $total, 'time' => $time, 'in_moderation' => $counts->moderated, 'i18n_moderation_text' => sprintf( /* translators: %s: Number of comments. */ _n( '%s Comment in moderation', '%s Comments in moderation', $counts->moderated ), number_format_i18n( $counts->moderated ) ), ), ) ); $x->send(); } // // POST-based Ajax handlers. // /** * Handles adding a hierarchical term via AJAX. * * @since 3.1.0 * @access private */ function _wp_ajax_add_hierarchical_term() { $action = $_POST['action']; $taxonomy = get_taxonomy( substr( $action, 4 ) ); check_ajax_referer( $action, '_ajax_nonce-add-' . $taxonomy->name ); if ( ! current_user_can( $taxonomy->cap->edit_terms ) ) { wp_die( -1 ); } $names = explode( ',', $_POST[ 'new' . $taxonomy->name ] ); $parent = isset( $_POST[ 'new' . $taxonomy->name . '_parent' ] ) ? (int) $_POST[ 'new' . $taxonomy->name . '_parent' ] : 0; if ( 0 > $parent ) { $parent = 0; } if ( 'category' === $taxonomy->name ) { $post_category = isset( $_POST['post_category'] ) ? (array) $_POST['post_category'] : array(); } else { $post_category = ( isset( $_POST['tax_input'] ) && isset( $_POST['tax_input'][ $taxonomy->name ] ) ) ? (array) $_POST['tax_input'][ $taxonomy->name ] : array(); } $checked_categories = array_map( 'absint', (array) $post_category ); $popular_ids = wp_popular_terms_checklist( $taxonomy->name, 0, 10, false ); foreach ( $names as $cat_name ) { $cat_name = trim( $cat_name ); $category_nicename = sanitize_title( $cat_name ); if ( '' === $category_nicename ) { continue; } $cat_id = wp_insert_term( $cat_name, $taxonomy->name, array( 'parent' => $parent ) ); if ( ! $cat_id || is_wp_error( $cat_id ) ) { continue; } else { $cat_id = $cat_id['term_id']; } $checked_categories[] = $cat_id; if ( $parent ) { // Do these all at once in a second. continue; } ob_start(); wp_terms_checklist( 0, array( 'taxonomy' => $taxonomy->name, 'descendants_and_self' => $cat_id, 'selected_cats' => $checked_categories, 'popular_cats' => $popular_ids, ) ); $data = ob_get_clean(); $add = array( 'what' => $taxonomy->name, 'id' => $cat_id, 'data' => str_replace( array( "\n", "\t" ), '', $data ), 'position' => -1, ); } if ( $parent ) { // Foncy - replace the parent and all its children. $parent = get_term( $parent, $taxonomy->name ); $term_id = $parent->term_id; while ( $parent->parent ) { // Get the top parent. $parent = get_term( $parent->parent, $taxonomy->name ); if ( is_wp_error( $parent ) ) { break; } $term_id = $parent->term_id; } ob_start(); wp_terms_checklist( 0, array( 'taxonomy' => $taxonomy->name, 'descendants_and_self' => $term_id, 'selected_cats' => $checked_categories, 'popular_cats' => $popular_ids, ) ); $data = ob_get_clean(); $add = array( 'what' => $taxonomy->name, 'id' => $term_id, 'data' => str_replace( array( "\n", "\t" ), '', $data ), 'position' => -1, ); } ob_start(); wp_dropdown_categories( array( 'taxonomy' => $taxonomy->name, 'hide_empty' => 0, 'name' => 'new' . $taxonomy->name . '_parent', 'orderby' => 'name', 'hierarchical' => 1, 'show_option_none' => '— ' . $taxonomy->labels->parent_item . ' —', ) ); $sup = ob_get_clean(); $add['supplemental'] = array( 'newcat_parent' => $sup ); $x = new WP_Ajax_Response( $add ); $x->send(); } /** * Handles deleting a comment via AJAX. * * @since 3.1.0 */ function wp_ajax_delete_comment() { $id = isset( $_POST['id'] ) ? (int) $_POST['id'] : 0; $comment = get_comment( $id ); if ( ! $comment ) { wp_die( time() ); } if ( ! current_user_can( 'edit_comment', $comment->comment_ID ) ) { wp_die( -1 ); } check_ajax_referer( "delete-comment_$id" ); $status = wp_get_comment_status( $comment ); $delta = -1; if ( isset( $_POST['trash'] ) && '1' === $_POST['trash'] ) { if ( 'trash' === $status ) { wp_die( time() ); } $r = wp_trash_comment( $comment ); } elseif ( isset( $_POST['untrash'] ) && '1' === $_POST['untrash'] ) { if ( 'trash' !== $status ) { wp_die( time() ); } $r = wp_untrash_comment( $comment ); // Undo trash, not in Trash. if ( ! isset( $_POST['comment_status'] ) || 'trash' !== $_POST['comment_status'] ) { $delta = 1; } } elseif ( isset( $_POST['spam'] ) && '1' === $_POST['spam'] ) { if ( 'spam' === $status ) { wp_die( time() ); } $r = wp_spam_comment( $comment ); } elseif ( isset( $_POST['unspam'] ) && '1' === $_POST['unspam'] ) { if ( 'spam' !== $status ) { wp_die( time() ); } $r = wp_unspam_comment( $comment ); // Undo spam, not in spam. if ( ! isset( $_POST['comment_status'] ) || 'spam' !== $_POST['comment_status'] ) { $delta = 1; } } elseif ( isset( $_POST['delete'] ) && '1' === $_POST['delete'] ) { $r = wp_delete_comment( $comment ); } else { wp_die( -1 ); } if ( $r ) { // Decide if we need to send back '1' or a more complicated response including page links and comment counts. _wp_ajax_delete_comment_response( $comment->comment_ID, $delta ); } wp_die( 0 ); } /** * Handles deleting a tag via AJAX. * * @since 3.1.0 */ function wp_ajax_delete_tag() { $tag_id = (int) $_POST['tag_ID']; check_ajax_referer( "delete-tag_$tag_id" ); if ( ! current_user_can( 'delete_term', $tag_id ) ) { wp_die( -1 ); } $taxonomy = ! empty( $_POST['taxonomy'] ) ? $_POST['taxonomy'] : 'post_tag'; $tag = get_term( $tag_id, $taxonomy ); if ( ! $tag || is_wp_error( $tag ) ) { wp_die( 1 ); } if ( wp_delete_term( $tag_id, $taxonomy ) ) { wp_die( 1 ); } else { wp_die( 0 ); } } /** * Handles deleting a link via AJAX. * * @since 3.1.0 */ function wp_ajax_delete_link() { $id = isset( $_POST['id'] ) ? (int) $_POST['id'] : 0; check_ajax_referer( "delete-bookmark_$id" ); if ( ! current_user_can( 'manage_links' ) ) { wp_die( -1 ); } $link = get_bookmark( $id ); if ( ! $link || is_wp_error( $link ) ) { wp_die( 1 ); } if ( wp_delete_link( $id ) ) { wp_die( 1 ); } else { wp_die( 0 ); } } /** * Handles deleting meta via AJAX. * * @since 3.1.0 */ function wp_ajax_delete_meta() { $id = isset( $_POST['id'] ) ? (int) $_POST['id'] : 0; check_ajax_referer( "delete-meta_$id" ); $meta = get_metadata_by_mid( 'post', $id ); if ( ! $meta ) { wp_die( 1 ); } if ( is_protected_meta( $meta->meta_key, 'post' ) || ! current_user_can( 'delete_post_meta', $meta->post_id, $meta->meta_key ) ) { wp_die( -1 ); } if ( delete_meta( $meta->meta_id ) ) { wp_die( 1 ); } wp_die( 0 ); } /** * Handles deleting a post via AJAX. * * @since 3.1.0 * * @param string $action Action to perform. */ function wp_ajax_delete_post( $action ) { if ( empty( $action ) ) { $action = 'delete-post'; } $id = isset( $_POST['id'] ) ? (int) $_POST['id'] : 0; check_ajax_referer( "{$action}_$id" ); if ( ! current_user_can( 'delete_post', $id ) ) { wp_die( -1 ); } if ( ! get_post( $id ) ) { wp_die( 1 ); } if ( wp_delete_post( $id ) ) { wp_die( 1 ); } else { wp_die( 0 ); } } /** * Handles sending a post to the Trash via AJAX. * * @since 3.1.0 * * @param string $action Action to perform. */ function wp_ajax_trash_post( $action ) { if ( empty( $action ) ) { $action = 'trash-post'; } $id = isset( $_POST['id'] ) ? (int) $_POST['id'] : 0; check_ajax_referer( "{$action}_$id" ); if ( ! current_user_can( 'delete_post', $id ) ) { wp_die( -1 ); } if ( ! get_post( $id ) ) { wp_die( 1 ); } if ( 'trash-post' === $action ) { $done = wp_trash_post( $id ); } else { $done = wp_untrash_post( $id ); } if ( $done ) { wp_die( 1 ); } wp_die( 0 ); } /** * Handles restoring a post from the Trash via AJAX. * * @since 3.1.0 * * @param string $action Action to perform. */ function wp_ajax_untrash_post( $action ) { if ( empty( $action ) ) { $action = 'untrash-post'; } wp_ajax_trash_post( $action ); } /** * Handles deleting a page via AJAX. * * @since 3.1.0 * * @param string $action Action to perform. */ function wp_ajax_delete_page( $action ) { if ( empty( $action ) ) { $action = 'delete-page'; } $id = isset( $_POST['id'] ) ? (int) $_POST['id'] : 0; check_ajax_referer( "{$action}_$id" ); if ( ! current_user_can( 'delete_page', $id ) ) { wp_die( -1 ); } if ( ! get_post( $id ) ) { wp_die( 1 ); } if ( wp_delete_post( $id ) ) { wp_die( 1 ); } else { wp_die( 0 ); } } /** * Handles dimming a comment via AJAX. * * @since 3.1.0 */ function wp_ajax_dim_comment() { $id = isset( $_POST['id'] ) ? (int) $_POST['id'] : 0; $comment = get_comment( $id ); if ( ! $comment ) { $x = new WP_Ajax_Response( array( 'what' => 'comment', 'id' => new WP_Error( 'invalid_comment', /* translators: %d: Comment ID. */ sprintf( __( 'Comment %d does not exist' ), $id ) ), ) ); $x->send(); } if ( ! current_user_can( 'edit_comment', $comment->comment_ID ) && ! current_user_can( 'moderate_comments' ) ) { wp_die( -1 ); } $current = wp_get_comment_status( $comment ); if ( isset( $_POST['new'] ) && $_POST['new'] === $current ) { wp_die( time() ); } check_ajax_referer( "approve-comment_$id" ); if ( in_array( $current, array( 'unapproved', 'spam' ), true ) ) { $result = wp_set_comment_status( $comment, 'approve', true ); } else { $result = wp_set_comment_status( $comment, 'hold', true ); } if ( is_wp_error( $result ) ) { $x = new WP_Ajax_Response( array( 'what' => 'comment', 'id' => $result, ) ); $x->send(); } // Decide if we need to send back '1' or a more complicated response including page links and comment counts. _wp_ajax_delete_comment_response( $comment->comment_ID ); wp_die( 0 ); } /** * Handles adding a link category via AJAX. * * @since 3.1.0 * * @param string $action Action to perform. */ function wp_ajax_add_link_category( $action ) { if ( empty( $action ) ) { $action = 'add-link-category'; } check_ajax_referer( $action ); $taxonomy_object = get_taxonomy( 'link_category' ); if ( ! current_user_can( $taxonomy_object->cap->manage_terms ) ) { wp_die( -1 ); } $names = explode( ',', wp_unslash( $_POST['newcat'] ) ); $x = new WP_Ajax_Response(); foreach ( $names as $cat_name ) { $cat_name = trim( $cat_name ); $slug = sanitize_title( $cat_name ); if ( '' === $slug ) { continue; } $cat_id = wp_insert_term( $cat_name, 'link_category' ); if ( ! $cat_id || is_wp_error( $cat_id ) ) { continue; } else { $cat_id = $cat_id['term_id']; } $cat_name = esc_html( $cat_name ); $x->add( array( 'what' => 'link-category', 'id' => $cat_id, 'data' => "", 'position' => -1, ) ); } $x->send(); } /** * Handles adding a tag via AJAX. * * @since 3.1.0 */ function wp_ajax_add_tag() { check_ajax_referer( 'add-tag', '_wpnonce_add-tag' ); $taxonomy = ! empty( $_POST['taxonomy'] ) ? $_POST['taxonomy'] : 'post_tag'; $taxonomy_object = get_taxonomy( $taxonomy ); if ( ! current_user_can( $taxonomy_object->cap->edit_terms ) ) { wp_die( -1 ); } $x = new WP_Ajax_Response(); $tag = wp_insert_term( $_POST['tag-name'], $taxonomy, $_POST ); if ( $tag && ! is_wp_error( $tag ) ) { $tag = get_term( $tag['term_id'], $taxonomy ); } if ( ! $tag || is_wp_error( $tag ) ) { $message = __( 'An error has occurred. Please reload the page and try again.' ); $error_code = 'error'; if ( is_wp_error( $tag ) && $tag->get_error_message() ) { $message = $tag->get_error_message(); } if ( is_wp_error( $tag ) && $tag->get_error_code() ) { $error_code = $tag->get_error_code(); } $x->add( array( 'what' => 'taxonomy', 'data' => new WP_Error( $error_code, $message ), ) ); $x->send(); } $wp_list_table = _get_list_table( 'WP_Terms_List_Table', array( 'screen' => $_POST['screen'] ) ); $level = 0; $noparents = ''; if ( is_taxonomy_hierarchical( $taxonomy ) ) { $level = count( get_ancestors( $tag->term_id, $taxonomy, 'taxonomy' ) ); ob_start(); $wp_list_table->single_row( $tag, $level ); $noparents = ob_get_clean(); } ob_start(); $wp_list_table->single_row( $tag ); $parents = ob_get_clean(); require ABSPATH . 'wp-admin/includes/edit-tag-messages.php'; $message = ''; if ( isset( $messages[ $taxonomy_object->name ][1] ) ) { $message = $messages[ $taxonomy_object->name ][1]; } elseif ( isset( $messages['_item'][1] ) ) { $message = $messages['_item'][1]; } $x->add( array( 'what' => 'taxonomy', 'data' => $message, 'supplemental' => array( 'parents' => $parents, 'noparents' => $noparents, 'notice' => $message, ), ) ); $x->add( array( 'what' => 'term', 'position' => $level, 'supplemental' => (array) $tag, ) ); $x->send(); } /** * Handles getting a tagcloud via AJAX. * * @since 3.1.0 */ function wp_ajax_get_tagcloud() { if ( ! isset( $_POST['tax'] ) ) { wp_die( 0 ); } $taxonomy = sanitize_key( $_POST['tax'] ); $taxonomy_object = get_taxonomy( $taxonomy ); if ( ! $taxonomy_object ) { wp_die( 0 ); } if ( ! current_user_can( $taxonomy_object->cap->assign_terms ) ) { wp_die( -1 ); } $tags = get_terms( array( 'taxonomy' => $taxonomy, 'number' => 45, 'orderby' => 'count', 'order' => 'DESC', ) ); if ( empty( $tags ) ) { wp_die( $taxonomy_object->labels->not_found ); } if ( is_wp_error( $tags ) ) { wp_die( $tags->get_error_message() ); } foreach ( $tags as $key => $tag ) { $tags[ $key ]->link = '#'; $tags[ $key ]->id = $tag->term_id; } // We need raw tag names here, so don't filter the output. $return = wp_generate_tag_cloud( $tags, array( 'filter' => 0, 'format' => 'list', ) ); if ( empty( $return ) ) { wp_die( 0 ); } echo $return; wp_die(); } /** * Handles getting comments via AJAX. * * @since 3.1.0 * * @global int $post_id * * @param string $action Action to perform. */ function wp_ajax_get_comments( $action ) { global $post_id; if ( empty( $action ) ) { $action = 'get-comments'; } check_ajax_referer( $action ); if ( empty( $post_id ) && ! empty( $_REQUEST['p'] ) ) { $id = absint( $_REQUEST['p'] ); if ( ! empty( $id ) ) { $post_id = $id; } } if ( empty( $post_id ) ) { wp_die( -1 ); } $wp_list_table = _get_list_table( 'WP_Post_Comments_List_Table', array( 'screen' => 'edit-comments' ) ); if ( ! current_user_can( 'edit_post', $post_id ) ) { wp_die( -1 ); } $wp_list_table->prepare_items(); if ( ! $wp_list_table->has_items() ) { wp_die( 1 ); } $x = new WP_Ajax_Response(); ob_start(); foreach ( $wp_list_table->items as $comment ) { if ( ! current_user_can( 'edit_comment', $comment->comment_ID ) && 0 === $comment->comment_approved ) { continue; } get_comment( $comment ); $wp_list_table->single_row( $comment ); } $comment_list_item = ob_get_clean(); $x->add( array( 'what' => 'comments', 'data' => $comment_list_item, ) ); $x->send(); } /** * Handles replying to a comment via AJAX. * * @since 3.1.0 * * @param string $action Action to perform. */ function wp_ajax_replyto_comment( $action ) { if ( empty( $action ) ) { $action = 'replyto-comment'; } check_ajax_referer( $action, '_ajax_nonce-replyto-comment' ); $comment_post_id = (int) $_POST['comment_post_ID']; $post = get_post( $comment_post_id ); if ( ! $post ) { wp_die( -1 ); } if ( ! current_user_can( 'edit_post', $comment_post_id ) ) { wp_die( -1 ); } if ( empty( $post->post_status ) ) { wp_die( 1 ); } elseif ( in_array( $post->post_status, array( 'draft', 'pending', 'trash' ), true ) ) { wp_die( __( 'You cannot reply to a comment on a draft post.' ) ); } $user = wp_get_current_user(); if ( $user->exists() ) { $comment_author = wp_slash( $user->display_name ); $comment_author_email = wp_slash( $user->user_email ); $comment_author_url = wp_slash( $user->user_url ); $user_id = $user->ID; if ( current_user_can( 'unfiltered_html' ) ) { if ( ! isset( $_POST['_wp_unfiltered_html_comment'] ) ) { $_POST['_wp_unfiltered_html_comment'] = ''; } if ( wp_create_nonce( 'unfiltered-html-comment' ) !== $_POST['_wp_unfiltered_html_comment'] ) { kses_remove_filters(); // Start with a clean slate. kses_init_filters(); // Set up the filters. remove_filter( 'pre_comment_content', 'wp_filter_post_kses' ); add_filter( 'pre_comment_content', 'wp_filter_kses' ); } } } else { wp_die( __( 'Sorry, you must be logged in to reply to a comment.' ) ); } $comment_content = trim( $_POST['content'] ); if ( '' === $comment_content ) { wp_die( __( 'Please type your comment text.' ) ); } $comment_type = isset( $_POST['comment_type'] ) ? trim( $_POST['comment_type'] ) : 'comment'; $comment_parent = 0; if ( isset( $_POST['comment_ID'] ) ) { $comment_parent = absint( $_POST['comment_ID'] ); } $comment_auto_approved = false; $commentdata = array( 'comment_post_ID' => $comment_post_id, ); $commentdata += compact( 'comment_author', 'comment_author_email', 'comment_author_url', 'comment_content', 'comment_type', 'comment_parent', 'user_id' ); // Automatically approve parent comment. if ( ! empty( $_POST['approve_parent'] ) ) { $parent = get_comment( $comment_parent ); if ( $parent && '0' === $parent->comment_approved && (int) $parent->comment_post_ID === $comment_post_id ) { if ( ! current_user_can( 'edit_comment', $parent->comment_ID ) ) { wp_die( -1 ); } if ( wp_set_comment_status( $parent, 'approve' ) ) { $comment_auto_approved = true; } } } $comment_id = wp_new_comment( $commentdata ); if ( is_wp_error( $comment_id ) ) { wp_die( $comment_id->get_error_message() ); } $comment = get_comment( $comment_id ); if ( ! $comment ) { wp_die( 1 ); } $position = ( isset( $_POST['position'] ) && (int) $_POST['position'] ) ? (int) $_POST['position'] : '-1'; ob_start(); if ( isset( $_REQUEST['mode'] ) && 'dashboard' === $_REQUEST['mode'] ) { require_once ABSPATH . 'wp-admin/includes/dashboard.php'; _wp_dashboard_recent_comments_row( $comment ); } else { if ( isset( $_REQUEST['mode'] ) && 'single' === $_REQUEST['mode'] ) { $wp_list_table = _get_list_table( 'WP_Post_Comments_List_Table', array( 'screen' => 'edit-comments' ) ); } else { $wp_list_table = _get_list_table( 'WP_Comments_List_Table', array( 'screen' => 'edit-comments' ) ); } $wp_list_table->single_row( $comment ); } $comment_list_item = ob_get_clean(); $response = array( 'what' => 'comment', 'id' => $comment->comment_ID, 'data' => $comment_list_item, 'position' => $position, ); $counts = wp_count_comments(); $response['supplemental'] = array( 'in_moderation' => $counts->moderated, 'i18n_comments_text' => sprintf( /* translators: %s: Number of comments. */ _n( '%s Comment', '%s Comments', $counts->approved ), number_format_i18n( $counts->approved ) ), 'i18n_moderation_text' => sprintf( /* translators: %s: Number of comments. */ _n( '%s Comment in moderation', '%s Comments in moderation', $counts->moderated ), number_format_i18n( $counts->moderated ) ), ); if ( $comment_auto_approved ) { $response['supplemental']['parent_approved'] = $parent->comment_ID; $response['supplemental']['parent_post_id'] = $parent->comment_post_ID; } $x = new WP_Ajax_Response(); $x->add( $response ); $x->send(); } /** * Handles editing a comment via AJAX. * * @since 3.1.0 */ function wp_ajax_edit_comment() { check_ajax_referer( 'replyto-comment', '_ajax_nonce-replyto-comment' ); $comment_id = (int) $_POST['comment_ID']; if ( ! current_user_can( 'edit_comment', $comment_id ) ) { wp_die( -1 ); } if ( '' === $_POST['content'] ) { wp_die( __( 'Please type your comment text.' ) ); } if ( isset( $_POST['status'] ) ) { $_POST['comment_status'] = $_POST['status']; } $updated = edit_comment(); if ( is_wp_error( $updated ) ) { wp_die( $updated->get_error_message() ); } $position = ( isset( $_POST['position'] ) && (int) $_POST['position'] ) ? (int) $_POST['position'] : '-1'; /* * Checkbox is used to differentiate between the Edit Comments screen (1) * and the Comments section on the Edit Post screen (0). */ $checkbox = ( isset( $_POST['checkbox'] ) && '1' === $_POST['checkbox'] ) ? 1 : 0; $wp_list_table = _get_list_table( $checkbox ? 'WP_Comments_List_Table' : 'WP_Post_Comments_List_Table', array( 'screen' => 'edit-comments' ) ); $comment = get_comment( $comment_id ); if ( empty( $comment->comment_ID ) ) { wp_die( -1 ); } ob_start(); $wp_list_table->single_row( $comment ); $comment_list_item = ob_get_clean(); $x = new WP_Ajax_Response(); $x->add( array( 'what' => 'edit_comment', 'id' => $comment->comment_ID, 'data' => $comment_list_item, 'position' => $position, ) ); $x->send(); } /** * Handles adding a menu item via AJAX. * * @since 3.1.0 */ function wp_ajax_add_menu_item() { check_ajax_referer( 'add-menu_item', 'menu-settings-column-nonce' ); if ( ! current_user_can( 'edit_theme_options' ) ) { wp_die( -1 ); } require_once ABSPATH . 'wp-admin/includes/nav-menu.php'; /* * For performance reasons, we omit some object properties from the checklist. * The following is a hacky way to restore them when adding non-custom items. */ $menu_items_data = array(); foreach ( (array) $_POST['menu-item'] as $menu_item_data ) { if ( ! empty( $menu_item_data['menu-item-type'] ) && 'custom' !== $menu_item_data['menu-item-type'] && ! empty( $menu_item_data['menu-item-object-id'] ) ) { switch ( $menu_item_data['menu-item-type'] ) { case 'post_type': $_object = get_post( $menu_item_data['menu-item-object-id'] ); break; case 'post_type_archive': $_object = get_post_type_object( $menu_item_data['menu-item-object'] ); break; case 'taxonomy': $_object = get_term( $menu_item_data['menu-item-object-id'], $menu_item_data['menu-item-object'] ); break; } $_menu_items = array_map( 'wp_setup_nav_menu_item', array( $_object ) ); $_menu_item = reset( $_menu_items ); // Restore the missing menu item properties. $menu_item_data['menu-item-description'] = $_menu_item->description; } $menu_items_data[] = $menu_item_data; } $item_ids = wp_save_nav_menu_items( 0, $menu_items_data ); if ( is_wp_error( $item_ids ) ) { wp_die( 0 ); } $menu_items = array(); foreach ( (array) $item_ids as $menu_item_id ) { $menu_obj = get_post( $menu_item_id ); if ( ! empty( $menu_obj->ID ) ) { $menu_obj = wp_setup_nav_menu_item( $menu_obj ); $menu_obj->title = empty( $menu_obj->title ) ? __( 'Menu Item' ) : $menu_obj->title; $menu_obj->label = $menu_obj->title; // Don't show "(pending)" in ajax-added items. $menu_items[] = $menu_obj; } } /** This filter is documented in wp-admin/includes/nav-menu.php */ $walker_class_name = apply_filters( 'wp_edit_nav_menu_walker', 'Walker_Nav_Menu_Edit', $_POST['menu'] ); if ( ! class_exists( $walker_class_name ) ) { wp_die( 0 ); } if ( ! empty( $menu_items ) ) { $args = array( 'after' => '', 'before' => '', 'link_after' => '', 'link_before' => '', 'walker' => new $walker_class_name(), ); echo walk_nav_menu_tree( $menu_items, 0, (object) $args ); } wp_die(); } /** * Handles adding meta via AJAX. * * @since 3.1.0 */ function wp_ajax_add_meta() { check_ajax_referer( 'add-meta', '_ajax_nonce-add-meta' ); $c = 0; $pid = (int) $_POST['post_id']; $post = get_post( $pid ); if ( isset( $_POST['metakeyselect'] ) || isset( $_POST['metakeyinput'] ) ) { if ( ! current_user_can( 'edit_post', $pid ) ) { wp_die( -1 ); } if ( isset( $_POST['metakeyselect'] ) && '#NONE#' === $_POST['metakeyselect'] && empty( $_POST['metakeyinput'] ) ) { wp_die( 1 ); } // If the post is an autodraft, save the post as a draft and then attempt to save the meta. if ( 'auto-draft' === $post->post_status ) { $post_data = array(); $post_data['action'] = 'draft'; // Warning fix. $post_data['post_ID'] = $pid; $post_data['post_type'] = $post->post_type; $post_data['post_status'] = 'draft'; $now = time(); $post_data['post_title'] = sprintf( /* translators: 1: Post creation date, 2: Post creation time. */ __( 'Draft created on %1$s at %2$s' ), gmdate( __( 'F j, Y' ), $now ), gmdate( __( 'g:i a' ), $now ) ); $pid = edit_post( $post_data ); if ( $pid ) { if ( is_wp_error( $pid ) ) { $x = new WP_Ajax_Response( array( 'what' => 'meta', 'data' => $pid, ) ); $x->send(); } $mid = add_meta( $pid ); if ( ! $mid ) { wp_die( __( 'Please provide a custom field value.' ) ); } } else { wp_die( 0 ); } } else { $mid = add_meta( $pid ); if ( ! $mid ) { wp_die( __( 'Please provide a custom field value.' ) ); } } $meta = get_metadata_by_mid( 'post', $mid ); $pid = (int) $meta->post_id; $meta = get_object_vars( $meta ); $x = new WP_Ajax_Response( array( 'what' => 'meta', 'id' => $mid, 'data' => _list_meta_row( $meta, $c ), 'position' => 1, 'supplemental' => array( 'postid' => $pid ), ) ); } else { // Update? $mid = (int) key( $_POST['meta'] ); $key = wp_unslash( $_POST['meta'][ $mid ]['key'] ); $value = wp_unslash( $_POST['meta'][ $mid ]['value'] ); if ( '' === trim( $key ) ) { wp_die( __( 'Please provide a custom field name.' ) ); } $meta = get_metadata_by_mid( 'post', $mid ); if ( ! $meta ) { wp_die( 0 ); // If meta doesn't exist. } if ( is_protected_meta( $meta->meta_key, 'post' ) || is_protected_meta( $key, 'post' ) || ! current_user_can( 'edit_post_meta', $meta->post_id, $meta->meta_key ) || ! current_user_can( 'edit_post_meta', $meta->post_id, $key ) ) { wp_die( -1 ); } if ( $meta->meta_value !== $value || $meta->meta_key !== $key ) { $u = update_metadata_by_mid( 'post', $mid, $value, $key ); if ( ! $u ) { wp_die( 0 ); // We know meta exists; we also know it's unchanged (or DB error, in which case there are bigger problems). } } $x = new WP_Ajax_Response( array( 'what' => 'meta', 'id' => $mid, 'old_id' => $mid, 'data' => _list_meta_row( array( 'meta_key' => $key, 'meta_value' => $value, 'meta_id' => $mid, ), $c ), 'position' => 0, 'supplemental' => array( 'postid' => $meta->post_id ), ) ); } $x->send(); } /** * Handles adding a user via AJAX. * * @since 3.1.0 * * @param string $action Action to perform. */ function wp_ajax_add_user( $action ) { if ( empty( $action ) ) { $action = 'add-user'; } check_ajax_referer( $action ); if ( ! current_user_can( 'create_users' ) ) { wp_die( -1 ); } $user_id = edit_user(); if ( ! $user_id ) { wp_die( 0 ); } elseif ( is_wp_error( $user_id ) ) { $x = new WP_Ajax_Response( array( 'what' => 'user', 'id' => $user_id, ) ); $x->send(); } $user_object = get_userdata( $user_id ); $wp_list_table = _get_list_table( 'WP_Users_List_Table' ); $role = current( $user_object->roles ); $x = new WP_Ajax_Response( array( 'what' => 'user', 'id' => $user_id, 'data' => $wp_list_table->single_row( $user_object, '', $role ), 'supplemental' => array( 'show-link' => sprintf( /* translators: %s: The new user. */ __( 'User %s added' ), '' . $user_object->user_login . '' ), 'role' => $role, ), ) ); $x->send(); } /** * Handles closed post boxes via AJAX. * * @since 3.1.0 */ function wp_ajax_closed_postboxes() { check_ajax_referer( 'closedpostboxes', 'closedpostboxesnonce' ); $closed = isset( $_POST['closed'] ) ? explode( ',', $_POST['closed'] ) : array(); $closed = array_filter( $closed ); $hidden = isset( $_POST['hidden'] ) ? explode( ',', $_POST['hidden'] ) : array(); $hidden = array_filter( $hidden ); $page = isset( $_POST['page'] ) ? $_POST['page'] : ''; if ( sanitize_key( $page ) !== $page ) { wp_die( 0 ); } $user = wp_get_current_user(); if ( ! $user ) { wp_die( -1 ); } if ( is_array( $closed ) ) { update_user_meta( $user->ID, "closedpostboxes_$page", $closed ); } if ( is_array( $hidden ) ) { // Postboxes that are always shown. $hidden = array_diff( $hidden, array( 'submitdiv', 'linksubmitdiv', 'manage-menu', 'create-menu' ) ); update_user_meta( $user->ID, "metaboxhidden_$page", $hidden ); } wp_die( 1 ); } /** * Handles hidden columns via AJAX. * * @since 3.1.0 */ function wp_ajax_hidden_columns() { check_ajax_referer( 'screen-options-nonce', 'screenoptionnonce' ); $page = isset( $_POST['page'] ) ? $_POST['page'] : ''; if ( sanitize_key( $page ) !== $page ) { wp_die( 0 ); } $user = wp_get_current_user(); if ( ! $user ) { wp_die( -1 ); } $hidden = ! empty( $_POST['hidden'] ) ? explode( ',', $_POST['hidden'] ) : array(); update_user_meta( $user->ID, "manage{$page}columnshidden", $hidden ); wp_die( 1 ); } /** * Handles updating whether to display the welcome panel via AJAX. * * @since 3.1.0 */ function wp_ajax_update_welcome_panel() { check_ajax_referer( 'welcome-panel-nonce', 'welcomepanelnonce' ); if ( ! current_user_can( 'edit_theme_options' ) ) { wp_die( -1 ); } update_user_meta( get_current_user_id(), 'show_welcome_panel', empty( $_POST['visible'] ) ? 0 : 1 ); wp_die( 1 ); } /** * Handles for retrieving menu meta boxes via AJAX. * * @since 3.1.0 */ function wp_ajax_menu_get_metabox() { if ( ! current_user_can( 'edit_theme_options' ) ) { wp_die( -1 ); } require_once ABSPATH . 'wp-admin/includes/nav-menu.php'; if ( isset( $_POST['item-type'] ) && 'post_type' === $_POST['item-type'] ) { $type = 'posttype'; $callback = 'wp_nav_menu_item_post_type_meta_box'; $items = (array) get_post_types( array( 'show_in_nav_menus' => true ), 'object' ); } elseif ( isset( $_POST['item-type'] ) && 'taxonomy' === $_POST['item-type'] ) { $type = 'taxonomy'; $callback = 'wp_nav_menu_item_taxonomy_meta_box'; $items = (array) get_taxonomies( array( 'show_ui' => true ), 'object' ); } if ( ! empty( $_POST['item-object'] ) && isset( $items[ $_POST['item-object'] ] ) ) { $menus_meta_box_object = $items[ $_POST['item-object'] ]; /** This filter is documented in wp-admin/includes/nav-menu.php */ $item = apply_filters( 'nav_menu_meta_box_object', $menus_meta_box_object ); $box_args = array( 'id' => 'add-' . $item->name, 'title' => $item->labels->name, 'callback' => $callback, 'args' => $item, ); ob_start(); $callback( null, $box_args ); $markup = ob_get_clean(); echo wp_json_encode( array( 'replace-id' => $type . '-' . $item->name, 'markup' => $markup, ) ); } wp_die(); } /** * Handles internal linking via AJAX. * * @since 3.1.0 */ function wp_ajax_wp_link_ajax() { check_ajax_referer( 'internal-linking', '_ajax_linking_nonce' ); $args = array(); if ( isset( $_POST['search'] ) ) { $args['s'] = wp_unslash( $_POST['search'] ); } if ( isset( $_POST['term'] ) ) { $args['s'] = wp_unslash( $_POST['term'] ); } $args['pagenum'] = ! empty( $_POST['page'] ) ? absint( $_POST['page'] ) : 1; if ( ! class_exists( '_WP_Editors', false ) ) { require ABSPATH . WPINC . '/class-wp-editor.php'; } $results = _WP_Editors::wp_link_query( $args ); if ( ! isset( $results ) ) { wp_die( 0 ); } echo wp_json_encode( $results ); echo "\n"; wp_die(); } /** * Handles saving menu locations via AJAX. * * @since 3.1.0 */ function wp_ajax_menu_locations_save() { if ( ! current_user_can( 'edit_theme_options' ) ) { wp_die( -1 ); } check_ajax_referer( 'add-menu_item', 'menu-settings-column-nonce' ); if ( ! isset( $_POST['menu-locations'] ) ) { wp_die( 0 ); } set_theme_mod( 'nav_menu_locations', array_map( 'absint', $_POST['menu-locations'] ) ); wp_die( 1 ); } /** * Handles saving the meta box order via AJAX. * * @since 3.1.0 */ function wp_ajax_meta_box_order() { check_ajax_referer( 'meta-box-order' ); $order = isset( $_POST['order'] ) ? (array) $_POST['order'] : false; $page_columns = isset( $_POST['page_columns'] ) ? $_POST['page_columns'] : 'auto'; if ( 'auto' !== $page_columns ) { $page_columns = (int) $page_columns; } $page = isset( $_POST['page'] ) ? $_POST['page'] : ''; if ( sanitize_key( $page ) !== $page ) { wp_die( 0 ); } $user = wp_get_current_user(); if ( ! $user ) { wp_die( -1 ); } if ( $order ) { update_user_meta( $user->ID, "meta-box-order_$page", $order ); } if ( $page_columns ) { update_user_meta( $user->ID, "screen_layout_$page", $page_columns ); } wp_send_json_success(); } /** * Handles menu quick searching via AJAX. * * @since 3.1.0 */ function wp_ajax_menu_quick_search() { if ( ! current_user_can( 'edit_theme_options' ) ) { wp_die( -1 ); } require_once ABSPATH . 'wp-admin/includes/nav-menu.php'; _wp_ajax_menu_quick_search( $_POST ); wp_die(); } /** * Handles retrieving a permalink via AJAX. * * @since 3.1.0 */ function wp_ajax_get_permalink() { check_ajax_referer( 'getpermalink', 'getpermalinknonce' ); $post_id = isset( $_POST['post_id'] ) ? (int) $_POST['post_id'] : 0; wp_die( get_preview_post_link( $post_id ) ); } /** * Handles retrieving a sample permalink via AJAX. * * @since 3.1.0 */ function wp_ajax_sample_permalink() { check_ajax_referer( 'samplepermalink', 'samplepermalinknonce' ); $post_id = isset( $_POST['post_id'] ) ? (int) $_POST['post_id'] : 0; $title = isset( $_POST['new_title'] ) ? $_POST['new_title'] : ''; $slug = isset( $_POST['new_slug'] ) ? $_POST['new_slug'] : null; wp_die( get_sample_permalink_html( $post_id, $title, $slug ) ); } /** * Handles Quick Edit saving a post from a list table via AJAX. * * @since 3.1.0 * * @global string $mode List table view mode. */ function wp_ajax_inline_save() { global $mode; check_ajax_referer( 'inlineeditnonce', '_inline_edit' ); if ( ! isset( $_POST['post_ID'] ) || ! (int) $_POST['post_ID'] ) { wp_die(); } $post_id = (int) $_POST['post_ID']; if ( 'page' === $_POST['post_type'] ) { if ( ! current_user_can( 'edit_page', $post_id ) ) { wp_die( __( 'Sorry, you are not allowed to edit this page.' ) ); } } else { if ( ! current_user_can( 'edit_post', $post_id ) ) { wp_die( __( 'Sorry, you are not allowed to edit this post.' ) ); } } $last = wp_check_post_lock( $post_id ); if ( $last ) { $last_user = get_userdata( $last ); $last_user_name = $last_user ? $last_user->display_name : __( 'Someone' ); /* translators: %s: User's display name. */ $msg_template = __( 'Saving is disabled: %s is currently editing this post.' ); if ( 'page' === $_POST['post_type'] ) { /* translators: %s: User's display name. */ $msg_template = __( 'Saving is disabled: %s is currently editing this page.' ); } printf( $msg_template, esc_html( $last_user_name ) ); wp_die(); } $data = &$_POST; $post = get_post( $post_id, ARRAY_A ); // Since it's coming from the database. $post = wp_slash( $post ); $data['content'] = $post['post_content']; $data['excerpt'] = $post['post_excerpt']; // Rename. $data['user_ID'] = get_current_user_id(); if ( isset( $data['post_parent'] ) ) { $data['parent_id'] = $data['post_parent']; } // Status. if ( isset( $data['keep_private'] ) && 'private' === $data['keep_private'] ) { $data['visibility'] = 'private'; $data['post_status'] = 'private'; } else { $data['post_status'] = $data['_status']; } if ( empty( $data['comment_status'] ) ) { $data['comment_status'] = 'closed'; } if ( empty( $data['ping_status'] ) ) { $data['ping_status'] = 'closed'; } // Exclude terms from taxonomies that are not supposed to appear in Quick Edit. if ( ! empty( $data['tax_input'] ) ) { foreach ( $data['tax_input'] as $taxonomy => $terms ) { $tax_object = get_taxonomy( $taxonomy ); /** This filter is documented in wp-admin/includes/class-wp-posts-list-table.php */ if ( ! apply_filters( 'quick_edit_show_taxonomy', $tax_object->show_in_quick_edit, $taxonomy, $post['post_type'] ) ) { unset( $data['tax_input'][ $taxonomy ] ); } } } // Hack: wp_unique_post_slug() doesn't work for drafts, so we will fake that our post is published. if ( ! empty( $data['post_name'] ) && in_array( $post['post_status'], array( 'draft', 'pending' ), true ) ) { $post['post_status'] = 'publish'; $data['post_name'] = wp_unique_post_slug( $data['post_name'], $post['ID'], $post['post_status'], $post['post_type'], $post['post_parent'] ); } // Update the post. edit_post(); $wp_list_table = _get_list_table( 'WP_Posts_List_Table', array( 'screen' => $_POST['screen'] ) ); $mode = 'excerpt' === $_POST['post_view'] ? 'excerpt' : 'list'; $level = 0; if ( is_post_type_hierarchical( $wp_list_table->screen->post_type ) ) { $request_post = array( get_post( $_POST['post_ID'] ) ); $parent = $request_post[0]->post_parent; while ( $parent > 0 ) { $parent_post = get_post( $parent ); $parent = $parent_post->post_parent; ++$level; } } $wp_list_table->display_rows( array( get_post( $_POST['post_ID'] ) ), $level ); wp_die(); } /** * Handles Quick Edit saving for a term via AJAX. * * @since 3.1.0 */ function wp_ajax_inline_save_tax() { check_ajax_referer( 'taxinlineeditnonce', '_inline_edit' ); $taxonomy = sanitize_key( $_POST['taxonomy'] ); $taxonomy_object = get_taxonomy( $taxonomy ); if ( ! $taxonomy_object ) { wp_die( 0 ); } if ( ! isset( $_POST['tax_ID'] ) || ! (int) $_POST['tax_ID'] ) { wp_die( -1 ); } $id = (int) $_POST['tax_ID']; if ( ! current_user_can( 'edit_term', $id ) ) { wp_die( -1 ); } $wp_list_table = _get_list_table( 'WP_Terms_List_Table', array( 'screen' => 'edit-' . $taxonomy ) ); $tag = get_term( $id, $taxonomy ); $_POST['description'] = $tag->description; $updated = wp_update_term( $id, $taxonomy, $_POST ); if ( $updated && ! is_wp_error( $updated ) ) { $tag = get_term( $updated['term_id'], $taxonomy ); if ( ! $tag || is_wp_error( $tag ) ) { if ( is_wp_error( $tag ) && $tag->get_error_message() ) { wp_die( $tag->get_error_message() ); } wp_die( __( 'Item not updated.' ) ); } } else { if ( is_wp_error( $updated ) && $updated->get_error_message() ) { wp_die( $updated->get_error_message() ); } wp_die( __( 'Item not updated.' ) ); } $level = 0; $parent = $tag->parent; while ( $parent > 0 ) { $parent_tag = get_term( $parent, $taxonomy ); $parent = $parent_tag->parent; ++$level; } $wp_list_table->single_row( $tag, $level ); wp_die(); } /** * Handles querying posts for the Find Posts modal via AJAX. * * @see window.findPosts * * @since 3.1.0 */ function wp_ajax_find_posts() { check_ajax_referer( 'find-posts' ); $post_types = get_post_types( array( 'public' => true ), 'objects' ); unset( $post_types['attachment'] ); $args = array( 'post_type' => array_keys( $post_types ), 'post_status' => 'any', 'posts_per_page' => 50, ); $search = wp_unslash( $_POST['ps'] ); if ( '' !== $search ) { $args['s'] = $search; } $posts = get_posts( $args ); if ( ! $posts ) { wp_send_json_error( __( 'No items found.' ) ); } $html = ''; $alt = ''; foreach ( $posts as $post ) { $title = trim( $post->post_title ) ? $post->post_title : __( '(no title)' ); $alt = ( 'alternate' === $alt ) ? '' : 'alternate'; switch ( $post->post_status ) { case 'publish': case 'private': $stat = __( 'Published' ); break; case 'future': $stat = __( 'Scheduled' ); break; case 'pending': $stat = __( 'Pending Review' ); break; case 'draft': $stat = __( 'Draft' ); break; } if ( '0000-00-00 00:00:00' === $post->post_date ) { $time = ''; } else { /* translators: Date format in table columns, see https://www.php.net/manual/datetime.format.php */ $time = mysql2date( __( 'Y/m/d' ), $post->post_date ); } $html .= ''; $html .= '' . "\n\n"; } $html .= '

    ' . __( 'Title' ) . '' . __( 'Type' ) . '' . __( 'Date' ) . '' . __( 'Status' ) . '
    ' . esc_html( $post_types[ $post->post_type ]->labels->singular_name ) . '' . esc_html( $time ) . '' . esc_html( $stat ) . '
    '; wp_send_json_success( $html ); } /** * Handles saving the widgets order via AJAX. * * @since 3.1.0 */ function wp_ajax_widgets_order() { check_ajax_referer( 'save-sidebar-widgets', 'savewidgets' ); if ( ! current_user_can( 'edit_theme_options' ) ) { wp_die( -1 ); } unset( $_POST['savewidgets'], $_POST['action'] ); // Save widgets order for all sidebars. if ( is_array( $_POST['sidebars'] ) ) { $sidebars = array(); foreach ( wp_unslash( $_POST['sidebars'] ) as $key => $val ) { $sb = array(); if ( ! empty( $val ) ) { $val = explode( ',', $val ); foreach ( $val as $k => $v ) { if ( ! str_contains( $v, 'widget-' ) ) { continue; } $sb[ $k ] = substr( $v, strpos( $v, '_' ) + 1 ); } } $sidebars[ $key ] = $sb; } wp_set_sidebars_widgets( $sidebars ); wp_die( 1 ); } wp_die( -1 ); } /** * Handles saving a widget via AJAX. * * @since 3.1.0 * * @global array $wp_registered_widgets * @global array $wp_registered_widget_controls * @global array $wp_registered_widget_updates */ function wp_ajax_save_widget() { global $wp_registered_widgets, $wp_registered_widget_controls, $wp_registered_widget_updates; check_ajax_referer( 'save-sidebar-widgets', 'savewidgets' ); if ( ! current_user_can( 'edit_theme_options' ) || ! isset( $_POST['id_base'] ) ) { wp_die( -1 ); } unset( $_POST['savewidgets'], $_POST['action'] ); /** * Fires early when editing the widgets displayed in sidebars. * * @since 2.8.0 */ do_action( 'load-widgets.php' ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores /** * Fires early when editing the widgets displayed in sidebars. * * @since 2.8.0 */ do_action( 'widgets.php' ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores /** This action is documented in wp-admin/widgets.php */ do_action( 'sidebar_admin_setup' ); $id_base = wp_unslash( $_POST['id_base'] ); $widget_id = wp_unslash( $_POST['widget-id'] ); $sidebar_id = $_POST['sidebar']; $multi_number = ! empty( $_POST['multi_number'] ) ? (int) $_POST['multi_number'] : 0; $settings = isset( $_POST[ 'widget-' . $id_base ] ) && is_array( $_POST[ 'widget-' . $id_base ] ) ? $_POST[ 'widget-' . $id_base ] : false; $error = '

    ' . __( 'An error has occurred. Please reload the page and try again.' ) . '

    '; $sidebars = wp_get_sidebars_widgets(); $sidebar = isset( $sidebars[ $sidebar_id ] ) ? $sidebars[ $sidebar_id ] : array(); // Delete. if ( isset( $_POST['delete_widget'] ) && $_POST['delete_widget'] ) { if ( ! isset( $wp_registered_widgets[ $widget_id ] ) ) { wp_die( $error ); } $sidebar = array_diff( $sidebar, array( $widget_id ) ); $_POST = array( 'sidebar' => $sidebar_id, 'widget-' . $id_base => array(), 'the-widget-id' => $widget_id, 'delete_widget' => '1', ); /** This action is documented in wp-admin/widgets.php */ do_action( 'delete_widget', $widget_id, $sidebar_id, $id_base ); } elseif ( $settings && preg_match( '/__i__|%i%/', key( $settings ) ) ) { if ( ! $multi_number ) { wp_die( $error ); } $_POST[ 'widget-' . $id_base ] = array( $multi_number => reset( $settings ) ); $widget_id = $id_base . '-' . $multi_number; $sidebar[] = $widget_id; } $_POST['widget-id'] = $sidebar; foreach ( (array) $wp_registered_widget_updates as $name => $control ) { if ( $name === $id_base ) { if ( ! is_callable( $control['callback'] ) ) { continue; } ob_start(); call_user_func_array( $control['callback'], $control['params'] ); ob_end_clean(); break; } } if ( isset( $_POST['delete_widget'] ) && $_POST['delete_widget'] ) { $sidebars[ $sidebar_id ] = $sidebar; wp_set_sidebars_widgets( $sidebars ); echo "deleted:$widget_id"; wp_die(); } if ( ! empty( $_POST['add_new'] ) ) { wp_die(); } $form = $wp_registered_widget_controls[ $widget_id ]; if ( $form ) { call_user_func_array( $form['callback'], $form['params'] ); } wp_die(); } /** * Handles updating a widget via AJAX. * * @since 3.9.0 * * @global WP_Customize_Manager $wp_customize */ function wp_ajax_update_widget() { global $wp_customize; $wp_customize->widgets->wp_ajax_update_widget(); } /** * Handles removing inactive widgets via AJAX. * * @since 4.4.0 */ function wp_ajax_delete_inactive_widgets() { check_ajax_referer( 'remove-inactive-widgets', 'removeinactivewidgets' ); if ( ! current_user_can( 'edit_theme_options' ) ) { wp_die( -1 ); } unset( $_POST['removeinactivewidgets'], $_POST['action'] ); /** This action is documented in wp-admin/includes/ajax-actions.php */ do_action( 'load-widgets.php' ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores /** This action is documented in wp-admin/includes/ajax-actions.php */ do_action( 'widgets.php' ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores /** This action is documented in wp-admin/widgets.php */ do_action( 'sidebar_admin_setup' ); $sidebars_widgets = wp_get_sidebars_widgets(); foreach ( $sidebars_widgets['wp_inactive_widgets'] as $key => $widget_id ) { $pieces = explode( '-', $widget_id ); $multi_number = array_pop( $pieces ); $id_base = implode( '-', $pieces ); $widget = get_option( 'widget_' . $id_base ); unset( $widget[ $multi_number ] ); update_option( 'widget_' . $id_base, $widget ); unset( $sidebars_widgets['wp_inactive_widgets'][ $key ] ); } wp_set_sidebars_widgets( $sidebars_widgets ); wp_die(); } /** * Handles creating missing image sub-sizes for just uploaded images via AJAX. * * @since 5.3.0 */ function wp_ajax_media_create_image_subsizes() { check_ajax_referer( 'media-form' ); if ( ! current_user_can( 'upload_files' ) ) { wp_send_json_error( array( 'message' => __( 'Sorry, you are not allowed to upload files.' ) ) ); } if ( empty( $_POST['attachment_id'] ) ) { wp_send_json_error( array( 'message' => __( 'Upload failed. Please reload and try again.' ) ) ); } $attachment_id = (int) $_POST['attachment_id']; if ( ! empty( $_POST['_wp_upload_failed_cleanup'] ) ) { // Upload failed. Cleanup. if ( wp_attachment_is_image( $attachment_id ) && current_user_can( 'delete_post', $attachment_id ) ) { $attachment = get_post( $attachment_id ); // Created at most 10 min ago. if ( $attachment && ( time() - strtotime( $attachment->post_date_gmt ) < 600 ) ) { wp_delete_attachment( $attachment_id, true ); wp_send_json_success(); } } } /* * Set a custom header with the attachment_id. * Used by the browser/client to resume creating image sub-sizes after a PHP fatal error. */ if ( ! headers_sent() ) { header( 'X-WP-Upload-Attachment-ID: ' . $attachment_id ); } /* * This can still be pretty slow and cause timeout or out of memory errors. * The js that handles the response would need to also handle HTTP 500 errors. */ wp_update_image_subsizes( $attachment_id ); if ( ! empty( $_POST['_legacy_support'] ) ) { // The old (inline) uploader. Only needs the attachment_id. $response = array( 'id' => $attachment_id ); } else { // Media modal and Media Library grid view. $response = wp_prepare_attachment_for_js( $attachment_id ); if ( ! $response ) { wp_send_json_error( array( 'message' => __( 'Upload failed.' ) ) ); } } // At this point the image has been uploaded successfully. wp_send_json_success( $response ); } /** * Handles uploading attachments via AJAX. * * @since 3.3.0 */ function wp_ajax_upload_attachment() { check_ajax_referer( 'media-form' ); /* * This function does not use wp_send_json_success() / wp_send_json_error() * as the html4 Plupload handler requires a text/html Content-Type for older IE. * See https://core.trac.wordpress.org/ticket/31037 */ if ( ! current_user_can( 'upload_files' ) ) { echo wp_json_encode( array( 'success' => false, 'data' => array( 'message' => __( 'Sorry, you are not allowed to upload files.' ), 'filename' => esc_html( $_FILES['async-upload']['name'] ), ), ) ); wp_die(); } if ( isset( $_REQUEST['post_id'] ) ) { $post_id = $_REQUEST['post_id']; if ( ! current_user_can( 'edit_post', $post_id ) ) { echo wp_json_encode( array( 'success' => false, 'data' => array( 'message' => __( 'Sorry, you are not allowed to attach files to this post.' ), 'filename' => esc_html( $_FILES['async-upload']['name'] ), ), ) ); wp_die(); } } else { $post_id = null; } $post_data = ! empty( $_REQUEST['post_data'] ) ? _wp_get_allowed_postdata( _wp_translate_postdata( false, (array) $_REQUEST['post_data'] ) ) : array(); if ( is_wp_error( $post_data ) ) { wp_die( $post_data->get_error_message() ); } // If the context is custom header or background, make sure the uploaded file is an image. if ( isset( $post_data['context'] ) && in_array( $post_data['context'], array( 'custom-header', 'custom-background' ), true ) ) { $wp_filetype = wp_check_filetype_and_ext( $_FILES['async-upload']['tmp_name'], $_FILES['async-upload']['name'] ); if ( ! wp_match_mime_types( 'image', $wp_filetype['type'] ) ) { echo wp_json_encode( array( 'success' => false, 'data' => array( 'message' => __( 'The uploaded file is not a valid image. Please try again.' ), 'filename' => esc_html( $_FILES['async-upload']['name'] ), ), ) ); wp_die(); } } $attachment_id = media_handle_upload( 'async-upload', $post_id, $post_data ); if ( is_wp_error( $attachment_id ) ) { echo wp_json_encode( array( 'success' => false, 'data' => array( 'message' => $attachment_id->get_error_message(), 'filename' => esc_html( $_FILES['async-upload']['name'] ), ), ) ); wp_die(); } if ( isset( $post_data['context'] ) && isset( $post_data['theme'] ) ) { if ( 'custom-background' === $post_data['context'] ) { update_post_meta( $attachment_id, '_wp_attachment_is_custom_background', $post_data['theme'] ); } if ( 'custom-header' === $post_data['context'] ) { update_post_meta( $attachment_id, '_wp_attachment_is_custom_header', $post_data['theme'] ); } } $attachment = wp_prepare_attachment_for_js( $attachment_id ); if ( ! $attachment ) { wp_die(); } echo wp_json_encode( array( 'success' => true, 'data' => $attachment, ) ); wp_die(); } /** * Handles image editing via AJAX. * * @since 3.1.0 */ function wp_ajax_image_editor() { $attachment_id = (int) $_POST['postid']; if ( empty( $attachment_id ) || ! current_user_can( 'edit_post', $attachment_id ) ) { wp_die( -1 ); } check_ajax_referer( "image_editor-$attachment_id" ); require_once ABSPATH . 'wp-admin/includes/image-edit.php'; $msg = false; switch ( $_POST['do'] ) { case 'save': $msg = wp_save_image( $attachment_id ); if ( ! empty( $msg->error ) ) { wp_send_json_error( $msg ); } wp_send_json_success( $msg ); break; case 'scale': $msg = wp_save_image( $attachment_id ); break; case 'restore': $msg = wp_restore_image( $attachment_id ); break; } ob_start(); wp_image_editor( $attachment_id, $msg ); $html = ob_get_clean(); if ( ! empty( $msg->error ) ) { wp_send_json_error( array( 'message' => $msg, 'html' => $html, ) ); } wp_send_json_success( array( 'message' => $msg, 'html' => $html, ) ); } /** * Handles setting the featured image via AJAX. * * @since 3.1.0 */ function wp_ajax_set_post_thumbnail() { $json = ! empty( $_REQUEST['json'] ); // New-style request. $post_id = (int) $_POST['post_id']; if ( ! current_user_can( 'edit_post', $post_id ) ) { wp_die( -1 ); } $thumbnail_id = (int) $_POST['thumbnail_id']; if ( $json ) { check_ajax_referer( "update-post_$post_id" ); } else { check_ajax_referer( "set_post_thumbnail-$post_id" ); } if ( -1 === $thumbnail_id ) { if ( delete_post_thumbnail( $post_id ) ) { $return = _wp_post_thumbnail_html( null, $post_id ); $json ? wp_send_json_success( $return ) : wp_die( $return ); } else { wp_die( 0 ); } } if ( set_post_thumbnail( $post_id, $thumbnail_id ) ) { $return = _wp_post_thumbnail_html( $thumbnail_id, $post_id ); $json ? wp_send_json_success( $return ) : wp_die( $return ); } wp_die( 0 ); } /** * Handles retrieving HTML for the featured image via AJAX. * * @since 4.6.0 */ function wp_ajax_get_post_thumbnail_html() { $post_id = (int) $_POST['post_id']; check_ajax_referer( "update-post_$post_id" ); if ( ! current_user_can( 'edit_post', $post_id ) ) { wp_die( -1 ); } $thumbnail_id = (int) $_POST['thumbnail_id']; // For backward compatibility, -1 refers to no featured image. if ( -1 === $thumbnail_id ) { $thumbnail_id = null; } $return = _wp_post_thumbnail_html( $thumbnail_id, $post_id ); wp_send_json_success( $return ); } /** * Handles setting the featured image for an attachment via AJAX. * * @since 4.0.0 * * @see set_post_thumbnail() */ function wp_ajax_set_attachment_thumbnail() { if ( empty( $_POST['urls'] ) || ! is_array( $_POST['urls'] ) ) { wp_send_json_error(); } $thumbnail_id = (int) $_POST['thumbnail_id']; if ( empty( $thumbnail_id ) ) { wp_send_json_error(); } if ( false === check_ajax_referer( 'set-attachment-thumbnail', '_ajax_nonce', false ) ) { wp_send_json_error(); } $post_ids = array(); // For each URL, try to find its corresponding post ID. foreach ( $_POST['urls'] as $url ) { $post_id = attachment_url_to_postid( $url ); if ( ! empty( $post_id ) ) { $post_ids[] = $post_id; } } if ( empty( $post_ids ) ) { wp_send_json_error(); } $success = 0; // For each found attachment, set its thumbnail. foreach ( $post_ids as $post_id ) { if ( ! current_user_can( 'edit_post', $post_id ) ) { continue; } if ( set_post_thumbnail( $post_id, $thumbnail_id ) ) { ++$success; } } if ( 0 === $success ) { wp_send_json_error(); } else { wp_send_json_success(); } wp_send_json_error(); } /** * Handles formatting a date via AJAX. * * @since 3.1.0 */ function wp_ajax_date_format() { wp_die( date_i18n( sanitize_option( 'date_format', wp_unslash( $_POST['date'] ) ) ) ); } /** * Handles formatting a time via AJAX. * * @since 3.1.0 */ function wp_ajax_time_format() { wp_die( date_i18n( sanitize_option( 'time_format', wp_unslash( $_POST['date'] ) ) ) ); } /** * Handles saving posts from the fullscreen editor via AJAX. * * @since 3.1.0 * @deprecated 4.3.0 */ function wp_ajax_wp_fullscreen_save_post() { $post_id = isset( $_POST['post_ID'] ) ? (int) $_POST['post_ID'] : 0; $post = null; if ( $post_id ) { $post = get_post( $post_id ); } check_ajax_referer( 'update-post_' . $post_id, '_wpnonce' ); $post_id = edit_post(); if ( is_wp_error( $post_id ) ) { wp_send_json_error(); } if ( $post ) { $last_date = mysql2date( __( 'F j, Y' ), $post->post_modified ); $last_time = mysql2date( __( 'g:i a' ), $post->post_modified ); } else { $last_date = date_i18n( __( 'F j, Y' ) ); $last_time = date_i18n( __( 'g:i a' ) ); } $last_id = get_post_meta( $post_id, '_edit_last', true ); if ( $last_id ) { $last_user = get_userdata( $last_id ); /* translators: 1: User's display name, 2: Date of last edit, 3: Time of last edit. */ $last_edited = sprintf( __( 'Last edited by %1$s on %2$s at %3$s' ), esc_html( $last_user->display_name ), $last_date, $last_time ); } else { /* translators: 1: Date of last edit, 2: Time of last edit. */ $last_edited = sprintf( __( 'Last edited on %1$s at %2$s' ), $last_date, $last_time ); } wp_send_json_success( array( 'last_edited' => $last_edited ) ); } /** * Handles removing a post lock via AJAX. * * @since 3.1.0 */ function wp_ajax_wp_remove_post_lock() { if ( empty( $_POST['post_ID'] ) || empty( $_POST['active_post_lock'] ) ) { wp_die( 0 ); } $post_id = (int) $_POST['post_ID']; $post = get_post( $post_id ); if ( ! $post ) { wp_die( 0 ); } check_ajax_referer( 'update-post_' . $post_id ); if ( ! current_user_can( 'edit_post', $post_id ) ) { wp_die( -1 ); } $active_lock = array_map( 'absint', explode( ':', $_POST['active_post_lock'] ) ); if ( get_current_user_id() !== $active_lock[1] ) { wp_die( 0 ); } /** * Filters the post lock window duration. * * @since 3.3.0 * * @param int $interval The interval in seconds the post lock duration * should last, plus 5 seconds. Default 150. */ $new_lock = ( time() - apply_filters( 'wp_check_post_lock_window', 150 ) + 5 ) . ':' . $active_lock[1]; update_post_meta( $post_id, '_edit_lock', $new_lock, implode( ':', $active_lock ) ); wp_die( 1 ); } /** * Handles dismissing a WordPress pointer via AJAX. * * @since 3.1.0 */ function wp_ajax_dismiss_wp_pointer() { $pointer = $_POST['pointer']; if ( sanitize_key( $pointer ) !== $pointer ) { wp_die( 0 ); } // check_ajax_referer( 'dismiss-pointer_' . $pointer ); $dismissed = array_filter( explode( ',', (string) get_user_meta( get_current_user_id(), 'dismissed_wp_pointers', true ) ) ); if ( in_array( $pointer, $dismissed, true ) ) { wp_die( 0 ); } $dismissed[] = $pointer; $dismissed = implode( ',', $dismissed ); update_user_meta( get_current_user_id(), 'dismissed_wp_pointers', $dismissed ); wp_die( 1 ); } /** * Handles getting an attachment via AJAX. * * @since 3.5.0 */ function wp_ajax_get_attachment() { if ( ! isset( $_REQUEST['id'] ) ) { wp_send_json_error(); } $id = absint( $_REQUEST['id'] ); if ( ! $id ) { wp_send_json_error(); } $post = get_post( $id ); if ( ! $post ) { wp_send_json_error(); } if ( 'attachment' !== $post->post_type ) { wp_send_json_error(); } if ( ! current_user_can( 'upload_files' ) ) { wp_send_json_error(); } $attachment = wp_prepare_attachment_for_js( $id ); if ( ! $attachment ) { wp_send_json_error(); } wp_send_json_success( $attachment ); } /** * Handles querying attachments via AJAX. * * @since 3.5.0 */ function wp_ajax_query_attachments() { if ( ! current_user_can( 'upload_files' ) ) { wp_send_json_error(); } $query = isset( $_REQUEST['query'] ) ? (array) $_REQUEST['query'] : array(); $keys = array( 's', 'order', 'orderby', 'posts_per_page', 'paged', 'post_mime_type', 'post_parent', 'author', 'post__in', 'post__not_in', 'year', 'monthnum', ); foreach ( get_taxonomies_for_attachments( 'objects' ) as $t ) { if ( $t->query_var && isset( $query[ $t->query_var ] ) ) { $keys[] = $t->query_var; } } $query = array_intersect_key( $query, array_flip( $keys ) ); $query['post_type'] = 'attachment'; if ( MEDIA_TRASH && ! empty( $_REQUEST['query']['post_status'] ) && 'trash' === $_REQUEST['query']['post_status'] ) { $query['post_status'] = 'trash'; } else { $query['post_status'] = 'inherit'; } if ( current_user_can( get_post_type_object( 'attachment' )->cap->read_private_posts ) ) { $query['post_status'] .= ',private'; } // Filter query clauses to include filenames. if ( isset( $query['s'] ) ) { add_filter( 'wp_allow_query_attachment_by_filename', '__return_true' ); } /** * Filters the arguments passed to WP_Query during an Ajax * call for querying attachments. * * @since 3.7.0 * * @see WP_Query::parse_query() * * @param array $query An array of query variables. */ $query = apply_filters( 'ajax_query_attachments_args', $query ); $attachments_query = new WP_Query( $query ); update_post_parent_caches( $attachments_query->posts ); $posts = array_map( 'wp_prepare_attachment_for_js', $attachments_query->posts ); $posts = array_filter( $posts ); $total_posts = $attachments_query->found_posts; if ( $total_posts < 1 ) { // Out-of-bounds, run the query again without LIMIT for total count. unset( $query['paged'] ); $count_query = new WP_Query(); $count_query->query( $query ); $total_posts = $count_query->found_posts; } $posts_per_page = (int) $attachments_query->get( 'posts_per_page' ); $max_pages = $posts_per_page ? (int) ceil( $total_posts / $posts_per_page ) : 0; header( 'X-WP-Total: ' . (int) $total_posts ); header( 'X-WP-TotalPages: ' . $max_pages ); wp_send_json_success( $posts ); } /** * Handles updating attachment attributes via AJAX. * * @since 3.5.0 */ function wp_ajax_save_attachment() { if ( ! isset( $_REQUEST['id'] ) || ! isset( $_REQUEST['changes'] ) ) { wp_send_json_error(); } $id = absint( $_REQUEST['id'] ); if ( ! $id ) { wp_send_json_error(); } check_ajax_referer( 'update-post_' . $id, 'nonce' ); if ( ! current_user_can( 'edit_post', $id ) ) { wp_send_json_error(); } $changes = $_REQUEST['changes']; $post = get_post( $id, ARRAY_A ); if ( 'attachment' !== $post['post_type'] ) { wp_send_json_error(); } if ( isset( $changes['parent'] ) ) { $post['post_parent'] = $changes['parent']; } if ( isset( $changes['title'] ) ) { $post['post_title'] = $changes['title']; } if ( isset( $changes['caption'] ) ) { $post['post_excerpt'] = $changes['caption']; } if ( isset( $changes['description'] ) ) { $post['post_content'] = $changes['description']; } if ( MEDIA_TRASH && isset( $changes['status'] ) ) { $post['post_status'] = $changes['status']; } if ( isset( $changes['alt'] ) ) { $alt = wp_unslash( $changes['alt'] ); if ( get_post_meta( $id, '_wp_attachment_image_alt', true ) !== $alt ) { $alt = wp_strip_all_tags( $alt, true ); update_post_meta( $id, '_wp_attachment_image_alt', wp_slash( $alt ) ); } } if ( wp_attachment_is( 'audio', $post['ID'] ) ) { $changed = false; $id3data = wp_get_attachment_metadata( $post['ID'] ); if ( ! is_array( $id3data ) ) { $changed = true; $id3data = array(); } foreach ( wp_get_attachment_id3_keys( (object) $post, 'edit' ) as $key => $label ) { if ( isset( $changes[ $key ] ) ) { $changed = true; $id3data[ $key ] = sanitize_text_field( wp_unslash( $changes[ $key ] ) ); } } if ( $changed ) { wp_update_attachment_metadata( $id, $id3data ); } } if ( MEDIA_TRASH && isset( $changes['status'] ) && 'trash' === $changes['status'] ) { wp_delete_post( $id ); } else { wp_update_post( $post ); } wp_send_json_success(); } /** * Handles saving backward compatible attachment attributes via AJAX. * * @since 3.5.0 */ function wp_ajax_save_attachment_compat() { if ( ! isset( $_REQUEST['id'] ) ) { wp_send_json_error(); } $id = absint( $_REQUEST['id'] ); if ( ! $id ) { wp_send_json_error(); } if ( empty( $_REQUEST['attachments'] ) || empty( $_REQUEST['attachments'][ $id ] ) ) { wp_send_json_error(); } $attachment_data = $_REQUEST['attachments'][ $id ]; check_ajax_referer( 'update-post_' . $id, 'nonce' ); if ( ! current_user_can( 'edit_post', $id ) ) { wp_send_json_error(); } $post = get_post( $id, ARRAY_A ); if ( 'attachment' !== $post['post_type'] ) { wp_send_json_error(); } /** This filter is documented in wp-admin/includes/media.php */ $post = apply_filters( 'attachment_fields_to_save', $post, $attachment_data ); if ( isset( $post['errors'] ) ) { $errors = $post['errors']; // @todo return me and display me! unset( $post['errors'] ); } wp_update_post( $post ); foreach ( get_attachment_taxonomies( $post ) as $taxonomy ) { if ( isset( $attachment_data[ $taxonomy ] ) ) { wp_set_object_terms( $id, array_map( 'trim', preg_split( '/,+/', $attachment_data[ $taxonomy ] ) ), $taxonomy, false ); } } $attachment = wp_prepare_attachment_for_js( $id ); if ( ! $attachment ) { wp_send_json_error(); } wp_send_json_success( $attachment ); } /** * Handles saving the attachment order via AJAX. * * @since 3.5.0 */ function wp_ajax_save_attachment_order() { if ( ! isset( $_REQUEST['post_id'] ) ) { wp_send_json_error(); } $post_id = absint( $_REQUEST['post_id'] ); if ( ! $post_id ) { wp_send_json_error(); } if ( empty( $_REQUEST['attachments'] ) ) { wp_send_json_error(); } check_ajax_referer( 'update-post_' . $post_id, 'nonce' ); $attachments = $_REQUEST['attachments']; if ( ! current_user_can( 'edit_post', $post_id ) ) { wp_send_json_error(); } foreach ( $attachments as $attachment_id => $menu_order ) { if ( ! current_user_can( 'edit_post', $attachment_id ) ) { continue; } $attachment = get_post( $attachment_id ); if ( ! $attachment ) { continue; } if ( 'attachment' !== $attachment->post_type ) { continue; } wp_update_post( array( 'ID' => $attachment_id, 'menu_order' => $menu_order, ) ); } wp_send_json_success(); } /** * Handles sending an attachment to the editor via AJAX. * * Generates the HTML to send an attachment to the editor. * Backward compatible with the {@see 'media_send_to_editor'} filter * and the chain of filters that follow. * * @since 3.5.0 */ function wp_ajax_send_attachment_to_editor() { check_ajax_referer( 'media-send-to-editor', 'nonce' ); $attachment = wp_unslash( $_POST['attachment'] ); $id = (int) $attachment['id']; $post = get_post( $id ); if ( ! $post ) { wp_send_json_error(); } if ( 'attachment' !== $post->post_type ) { wp_send_json_error(); } if ( current_user_can( 'edit_post', $id ) ) { // If this attachment is unattached, attach it. Primarily a back compat thing. $insert_into_post_id = (int) $_POST['post_id']; if ( 0 === $post->post_parent && $insert_into_post_id ) { wp_update_post( array( 'ID' => $id, 'post_parent' => $insert_into_post_id, ) ); } } $url = empty( $attachment['url'] ) ? '' : $attachment['url']; $rel = ( str_contains( $url, 'attachment_id' ) || get_attachment_link( $id ) === $url ); remove_filter( 'media_send_to_editor', 'image_media_send_to_editor' ); if ( str_starts_with( $post->post_mime_type, 'image' ) ) { $align = isset( $attachment['align'] ) ? $attachment['align'] : 'none'; $size = isset( $attachment['image-size'] ) ? $attachment['image-size'] : 'medium'; $alt = isset( $attachment['image_alt'] ) ? $attachment['image_alt'] : ''; // No whitespace-only captions. $caption = isset( $attachment['post_excerpt'] ) ? $attachment['post_excerpt'] : ''; if ( '' === trim( $caption ) ) { $caption = ''; } $title = ''; // We no longer insert title tags into tags, as they are redundant. $html = get_image_send_to_editor( $id, $caption, $title, $align, $url, $rel, $size, $alt ); } elseif ( wp_attachment_is( 'video', $post ) || wp_attachment_is( 'audio', $post ) ) { $html = stripslashes_deep( $_POST['html'] ); } else { $html = isset( $attachment['post_title'] ) ? $attachment['post_title'] : ''; $rel = $rel ? ' rel="attachment wp-att-' . $id . '"' : ''; // Hard-coded string, $id is already sanitized. if ( ! empty( $url ) ) { $html = '' . $html . ''; } } /** This filter is documented in wp-admin/includes/media.php */ $html = apply_filters( 'media_send_to_editor', $html, $id, $attachment ); wp_send_json_success( $html ); } /** * Handles sending a link to the editor via AJAX. * * Generates the HTML to send a non-image embed link to the editor. * * Backward compatible with the following filters: * - file_send_to_editor_url * - audio_send_to_editor_url * - video_send_to_editor_url * * @since 3.5.0 * * @global WP_Post $post Global post object. * @global WP_Embed $wp_embed WordPress Embed object. */ function wp_ajax_send_link_to_editor() { global $post, $wp_embed; check_ajax_referer( 'media-send-to-editor', 'nonce' ); $src = wp_unslash( $_POST['src'] ); if ( ! $src ) { wp_send_json_error(); } if ( ! strpos( $src, '://' ) ) { $src = 'http://' . $src; } $src = sanitize_url( $src ); if ( ! $src ) { wp_send_json_error(); } $link_text = trim( wp_unslash( $_POST['link_text'] ) ); if ( ! $link_text ) { $link_text = wp_basename( $src ); } $post = get_post( isset( $_POST['post_id'] ) ? $_POST['post_id'] : 0 ); // Ping WordPress for an embed. $check_embed = $wp_embed->run_shortcode( '[embed]' . $src . '[/embed]' ); // Fallback that WordPress creates when no oEmbed was found. $fallback = $wp_embed->maybe_make_link( $src ); if ( $check_embed !== $fallback ) { // TinyMCE view for [embed] will parse this. $html = '[embed]' . $src . '[/embed]'; } elseif ( $link_text ) { $html = '' . $link_text . ''; } else { $html = ''; } // Figure out what filter to run: $type = 'file'; $ext = preg_replace( '/^.+?\.([^.]+)$/', '$1', $src ); if ( $ext ) { $ext_type = wp_ext2type( $ext ); if ( 'audio' === $ext_type || 'video' === $ext_type ) { $type = $ext_type; } } /** This filter is documented in wp-admin/includes/media.php */ $html = apply_filters( "{$type}_send_to_editor_url", $html, $src, $link_text ); wp_send_json_success( $html ); } /** * Handles the Heartbeat API via AJAX. * * Runs when the user is logged in. * * @since 3.6.0 */ function wp_ajax_heartbeat() { if ( empty( $_POST['_nonce'] ) ) { wp_send_json_error(); } $response = array(); $data = array(); $nonce_state = wp_verify_nonce( $_POST['_nonce'], 'heartbeat-nonce' ); // 'screen_id' is the same as $current_screen->id and the JS global 'pagenow'. if ( ! empty( $_POST['screen_id'] ) ) { $screen_id = sanitize_key( $_POST['screen_id'] ); } else { $screen_id = 'front'; } if ( ! empty( $_POST['data'] ) ) { $data = wp_unslash( (array) $_POST['data'] ); } if ( 1 !== $nonce_state ) { /** * Filters the nonces to send to the New/Edit Post screen. * * @since 4.3.0 * * @param array $response The Heartbeat response. * @param array $data The $_POST data sent. * @param string $screen_id The screen ID. */ $response = apply_filters( 'wp_refresh_nonces', $response, $data, $screen_id ); if ( false === $nonce_state ) { // User is logged in but nonces have expired. $response['nonces_expired'] = true; wp_send_json( $response ); } } if ( ! empty( $data ) ) { /** * Filters the Heartbeat response received. * * @since 3.6.0 * * @param array $response The Heartbeat response. * @param array $data The $_POST data sent. * @param string $screen_id The screen ID. */ $response = apply_filters( 'heartbeat_received', $response, $data, $screen_id ); } /** * Filters the Heartbeat response sent. * * @since 3.6.0 * * @param array $response The Heartbeat response. * @param string $screen_id The screen ID. */ $response = apply_filters( 'heartbeat_send', $response, $screen_id ); /** * Fires when Heartbeat ticks in logged-in environments. * * Allows the transport to be easily replaced with long-polling. * * @since 3.6.0 * * @param array $response The Heartbeat response. * @param string $screen_id The screen ID. */ do_action( 'heartbeat_tick', $response, $screen_id ); // Send the current time according to the server. $response['server_time'] = time(); wp_send_json( $response ); } /** * Handles getting revision diffs via AJAX. * * @since 3.6.0 */ function wp_ajax_get_revision_diffs() { require ABSPATH . 'wp-admin/includes/revision.php'; $post = get_post( (int) $_REQUEST['post_id'] ); if ( ! $post ) { wp_send_json_error(); } if ( ! current_user_can( 'edit_post', $post->ID ) ) { wp_send_json_error(); } // Really just pre-loading the cache here. $revisions = wp_get_post_revisions( $post->ID, array( 'check_enabled' => false ) ); if ( ! $revisions ) { wp_send_json_error(); } $return = array(); // Removes the script timeout limit by setting it to 0 allowing ample time for diff UI setup. if ( function_exists( 'set_time_limit' ) ) { set_time_limit( 0 ); } foreach ( $_REQUEST['compare'] as $compare_key ) { list( $compare_from, $compare_to ) = explode( ':', $compare_key ); // from:to $return[] = array( 'id' => $compare_key, 'fields' => wp_get_revision_ui_diff( $post, $compare_from, $compare_to ), ); } wp_send_json_success( $return ); } /** * Handles auto-saving the selected color scheme for * a user's own profile via AJAX. * * @since 3.8.0 * * @global array $_wp_admin_css_colors */ function wp_ajax_save_user_color_scheme() { global $_wp_admin_css_colors; check_ajax_referer( 'save-color-scheme', 'nonce' ); $color_scheme = sanitize_key( $_POST['color_scheme'] ); if ( ! isset( $_wp_admin_css_colors[ $color_scheme ] ) ) { wp_send_json_error(); } $previous_color_scheme = get_user_meta( get_current_user_id(), 'admin_color', true ); update_user_meta( get_current_user_id(), 'admin_color', $color_scheme ); wp_send_json_success( array( 'previousScheme' => 'admin-color-' . $previous_color_scheme, 'currentScheme' => 'admin-color-' . $color_scheme, ) ); } /** * Handles getting themes from themes_api() via AJAX. * * @since 3.9.0 * * @global array $themes_allowedtags * @global array $theme_field_defaults */ function wp_ajax_query_themes() { global $themes_allowedtags, $theme_field_defaults; if ( ! current_user_can( 'install_themes' ) ) { wp_send_json_error(); } $args = wp_parse_args( wp_unslash( $_REQUEST['request'] ), array( 'per_page' => 20, 'fields' => array_merge( (array) $theme_field_defaults, array( 'reviews_url' => true, // Explicitly request the reviews URL to be linked from the Add Themes screen. ) ), ) ); if ( isset( $args['browse'] ) && 'favorites' === $args['browse'] && ! isset( $args['user'] ) ) { $user = get_user_option( 'wporg_favorites' ); if ( $user ) { $args['user'] = $user; } } $old_filter = isset( $args['browse'] ) ? $args['browse'] : 'search'; /** This filter is documented in wp-admin/includes/class-wp-theme-install-list-table.php */ $args = apply_filters( 'install_themes_table_api_args_' . $old_filter, $args ); $api = themes_api( 'query_themes', $args ); if ( is_wp_error( $api ) ) { wp_send_json_error(); } $update_php = network_admin_url( 'update.php?action=install-theme' ); $installed_themes = search_theme_directories(); if ( false === $installed_themes ) { $installed_themes = array(); } foreach ( $installed_themes as $theme_slug => $theme_data ) { // Ignore child themes. if ( str_contains( $theme_slug, '/' ) ) { unset( $installed_themes[ $theme_slug ] ); } } foreach ( $api->themes as &$theme ) { $theme->install_url = add_query_arg( array( 'theme' => $theme->slug, '_wpnonce' => wp_create_nonce( 'install-theme_' . $theme->slug ), ), $update_php ); if ( current_user_can( 'switch_themes' ) ) { if ( is_multisite() ) { $theme->activate_url = add_query_arg( array( 'action' => 'enable', '_wpnonce' => wp_create_nonce( 'enable-theme_' . $theme->slug ), 'theme' => $theme->slug, ), network_admin_url( 'themes.php' ) ); } else { $theme->activate_url = add_query_arg( array( 'action' => 'activate', '_wpnonce' => wp_create_nonce( 'switch-theme_' . $theme->slug ), 'stylesheet' => $theme->slug, ), admin_url( 'themes.php' ) ); } } $is_theme_installed = array_key_exists( $theme->slug, $installed_themes ); // We only care about installed themes. $theme->block_theme = $is_theme_installed && wp_get_theme( $theme->slug )->is_block_theme(); if ( ! is_multisite() && current_user_can( 'edit_theme_options' ) && current_user_can( 'customize' ) ) { $customize_url = $theme->block_theme ? admin_url( 'site-editor.php' ) : wp_customize_url( $theme->slug ); $theme->customize_url = add_query_arg( array( 'return' => urlencode( network_admin_url( 'theme-install.php', 'relative' ) ), ), $customize_url ); } $theme->name = wp_kses( $theme->name, $themes_allowedtags ); $theme->author = wp_kses( $theme->author['display_name'], $themes_allowedtags ); $theme->version = wp_kses( $theme->version, $themes_allowedtags ); $theme->description = wp_kses( $theme->description, $themes_allowedtags ); $theme->stars = wp_star_rating( array( 'rating' => $theme->rating, 'type' => 'percent', 'number' => $theme->num_ratings, 'echo' => false, ) ); $theme->num_ratings = number_format_i18n( $theme->num_ratings ); $theme->preview_url = set_url_scheme( $theme->preview_url ); $theme->compatible_wp = is_wp_version_compatible( $theme->requires ); $theme->compatible_php = is_php_version_compatible( $theme->requires_php ); } wp_send_json_success( $api ); } /** * Applies [embed] Ajax handlers to a string. * * @since 4.0.0 * * @global WP_Post $post Global post object. * @global WP_Embed $wp_embed WordPress Embed object. * @global WP_Scripts $wp_scripts * @global int $content_width */ function wp_ajax_parse_embed() { global $post, $wp_embed, $content_width; if ( empty( $_POST['shortcode'] ) ) { wp_send_json_error(); } $post_id = isset( $_POST['post_ID'] ) ? (int) $_POST['post_ID'] : 0; if ( $post_id > 0 ) { $post = get_post( $post_id ); if ( ! $post || ! current_user_can( 'edit_post', $post->ID ) ) { wp_send_json_error(); } setup_postdata( $post ); } elseif ( ! current_user_can( 'edit_posts' ) ) { // See WP_oEmbed_Controller::get_proxy_item_permissions_check(). wp_send_json_error(); } $shortcode = wp_unslash( $_POST['shortcode'] ); preg_match( '/' . get_shortcode_regex() . '/s', $shortcode, $matches ); $atts = shortcode_parse_atts( $matches[3] ); if ( ! empty( $matches[5] ) ) { $url = $matches[5]; } elseif ( ! empty( $atts['src'] ) ) { $url = $atts['src']; } else { $url = ''; } $parsed = false; $wp_embed->return_false_on_fail = true; if ( 0 === $post_id ) { /* * Refresh oEmbeds cached outside of posts that are past their TTL. * Posts are excluded because they have separate logic for refreshing * their post meta caches. See WP_Embed::cache_oembed(). */ $wp_embed->usecache = false; } if ( is_ssl() && str_starts_with( $url, 'http://' ) ) { /* * Admin is ssl and the user pasted non-ssl URL. * Check if the provider supports ssl embeds and use that for the preview. */ $ssl_shortcode = preg_replace( '%^(\\[embed[^\\]]*\\])http://%i', '$1https://', $shortcode ); $parsed = $wp_embed->run_shortcode( $ssl_shortcode ); if ( ! $parsed ) { $no_ssl_support = true; } } // Set $content_width so any embeds fit in the destination iframe. if ( isset( $_POST['maxwidth'] ) && is_numeric( $_POST['maxwidth'] ) && $_POST['maxwidth'] > 0 ) { if ( ! isset( $content_width ) ) { $content_width = (int) $_POST['maxwidth']; } else { $content_width = min( $content_width, (int) $_POST['maxwidth'] ); } } if ( $url && ! $parsed ) { $parsed = $wp_embed->run_shortcode( $shortcode ); } if ( ! $parsed ) { wp_send_json_error( array( 'type' => 'not-embeddable', /* translators: %s: URL that could not be embedded. */ 'message' => sprintf( __( '%s failed to embed.' ), '' . esc_html( $url ) . '' ), ) ); } if ( has_shortcode( $parsed, 'audio' ) || has_shortcode( $parsed, 'video' ) ) { $styles = ''; $mce_styles = wpview_media_sandbox_styles(); foreach ( $mce_styles as $style ) { $styles .= sprintf( '', $style ); } $html = do_shortcode( $parsed ); global $wp_scripts; if ( ! empty( $wp_scripts ) ) { $wp_scripts->done = array(); } ob_start(); wp_print_scripts( array( 'mediaelement-vimeo', 'wp-mediaelement' ) ); $scripts = ob_get_clean(); $parsed = $styles . $html . $scripts; } if ( ! empty( $no_ssl_support ) || ( is_ssl() && ( preg_match( '%<(iframe|script|embed) [^>]*src="http://%', $parsed ) || preg_match( '%]*href="http://%', $parsed ) ) ) ) { // Admin is ssl and the embed is not. Iframes, scripts, and other "active content" will be blocked. wp_send_json_error( array( 'type' => 'not-ssl', 'message' => __( 'This preview is unavailable in the editor.' ), ) ); } $return = array( 'body' => $parsed, 'attr' => $wp_embed->last_attr, ); if ( str_contains( $parsed, 'class="wp-embedded-content' ) ) { if ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) { $script_src = includes_url( 'js/wp-embed.js' ); } else { $script_src = includes_url( 'js/wp-embed.min.js' ); } $return['head'] = ''; $return['sandbox'] = true; } wp_send_json_success( $return ); } /** * @since 4.0.0 * * @global WP_Post $post Global post object. * @global WP_Scripts $wp_scripts */ function wp_ajax_parse_media_shortcode() { global $post, $wp_scripts; if ( empty( $_POST['shortcode'] ) ) { wp_send_json_error(); } $shortcode = wp_unslash( $_POST['shortcode'] ); // Only process previews for media related shortcodes: $found_shortcodes = get_shortcode_tags_in_content( $shortcode ); $media_shortcodes = array( 'audio', 'embed', 'playlist', 'video', 'gallery', ); $other_shortcodes = array_diff( $found_shortcodes, $media_shortcodes ); if ( ! empty( $other_shortcodes ) ) { wp_send_json_error(); } if ( ! empty( $_POST['post_ID'] ) ) { $post = get_post( (int) $_POST['post_ID'] ); } // The embed shortcode requires a post. if ( ! $post || ! current_user_can( 'edit_post', $post->ID ) ) { if ( in_array( 'embed', $found_shortcodes, true ) ) { wp_send_json_error(); } } else { setup_postdata( $post ); } $parsed = do_shortcode( $shortcode ); if ( empty( $parsed ) ) { wp_send_json_error( array( 'type' => 'no-items', 'message' => __( 'No items found.' ), ) ); } $head = ''; $styles = wpview_media_sandbox_styles(); foreach ( $styles as $style ) { $head .= ''; } if ( ! empty( $wp_scripts ) ) { $wp_scripts->done = array(); } ob_start(); echo $parsed; if ( 'playlist' === $_REQUEST['type'] ) { wp_underscore_playlist_templates(); wp_print_scripts( 'wp-playlist' ); } else { wp_print_scripts( array( 'mediaelement-vimeo', 'wp-mediaelement' ) ); } wp_send_json_success( array( 'head' => $head, 'body' => ob_get_clean(), ) ); } /** * Handles destroying multiple open sessions for a user via AJAX. * * @since 4.1.0 */ function wp_ajax_destroy_sessions() { $user = get_userdata( (int) $_POST['user_id'] ); if ( $user ) { if ( ! current_user_can( 'edit_user', $user->ID ) ) { $user = false; } elseif ( ! wp_verify_nonce( $_POST['nonce'], 'update-user_' . $user->ID ) ) { $user = false; } } if ( ! $user ) { wp_send_json_error( array( 'message' => __( 'Could not log out user sessions. Please try again.' ), ) ); } $sessions = WP_Session_Tokens::get_instance( $user->ID ); if ( get_current_user_id() === $user->ID ) { $sessions->destroy_others( wp_get_session_token() ); $message = __( 'You are now logged out everywhere else.' ); } else { $sessions->destroy_all(); /* translators: %s: User's display name. */ $message = sprintf( __( '%s has been logged out.' ), $user->display_name ); } wp_send_json_success( array( 'message' => $message ) ); } /** * Handles cropping an image via AJAX. * * @since 4.3.0 */ function wp_ajax_crop_image() { $attachment_id = absint( $_POST['id'] ); check_ajax_referer( 'image_editor-' . $attachment_id, 'nonce' ); if ( empty( $attachment_id ) || ! current_user_can( 'edit_post', $attachment_id ) ) { wp_send_json_error(); } $context = str_replace( '_', '-', $_POST['context'] ); $data = array_map( 'absint', $_POST['cropDetails'] ); $cropped = wp_crop_image( $attachment_id, $data['x1'], $data['y1'], $data['width'], $data['height'], $data['dst_width'], $data['dst_height'] ); if ( ! $cropped || is_wp_error( $cropped ) ) { wp_send_json_error( array( 'message' => __( 'Image could not be processed.' ) ) ); } switch ( $context ) { case 'site-icon': require_once ABSPATH . 'wp-admin/includes/class-wp-site-icon.php'; $wp_site_icon = new WP_Site_Icon(); // Skip creating a new attachment if the attachment is a Site Icon. if ( get_post_meta( $attachment_id, '_wp_attachment_context', true ) === $context ) { // Delete the temporary cropped file, we don't need it. wp_delete_file( $cropped ); // Additional sizes in wp_prepare_attachment_for_js(). add_filter( 'image_size_names_choose', array( $wp_site_icon, 'additional_sizes' ) ); break; } /** This filter is documented in wp-admin/includes/class-custom-image-header.php */ $cropped = apply_filters( 'wp_create_file_in_uploads', $cropped, $attachment_id ); // For replication. // Copy attachment properties. $attachment = wp_copy_parent_attachment_properties( $cropped, $attachment_id, $context ); // Update the attachment. add_filter( 'intermediate_image_sizes_advanced', array( $wp_site_icon, 'additional_sizes' ) ); $attachment_id = $wp_site_icon->insert_attachment( $attachment, $cropped ); remove_filter( 'intermediate_image_sizes_advanced', array( $wp_site_icon, 'additional_sizes' ) ); // Additional sizes in wp_prepare_attachment_for_js(). add_filter( 'image_size_names_choose', array( $wp_site_icon, 'additional_sizes' ) ); break; default: /** * Fires before a cropped image is saved. * * Allows to add filters to modify the way a cropped image is saved. * * @since 4.3.0 * * @param string $context The Customizer control requesting the cropped image. * @param int $attachment_id The attachment ID of the original image. * @param string $cropped Path to the cropped image file. */ do_action( 'wp_ajax_crop_image_pre_save', $context, $attachment_id, $cropped ); /** This filter is documented in wp-admin/includes/class-custom-image-header.php */ $cropped = apply_filters( 'wp_create_file_in_uploads', $cropped, $attachment_id ); // For replication. // Copy attachment properties. $attachment = wp_copy_parent_attachment_properties( $cropped, $attachment_id, $context ); $attachment_id = wp_insert_attachment( $attachment, $cropped ); $metadata = wp_generate_attachment_metadata( $attachment_id, $cropped ); /** * Filters the cropped image attachment metadata. * * @since 4.3.0 * * @see wp_generate_attachment_metadata() * * @param array $metadata Attachment metadata. */ $metadata = apply_filters( 'wp_ajax_cropped_attachment_metadata', $metadata ); wp_update_attachment_metadata( $attachment_id, $metadata ); /** * Filters the attachment ID for a cropped image. * * @since 4.3.0 * * @param int $attachment_id The attachment ID of the cropped image. * @param string $context The Customizer control requesting the cropped image. */ $attachment_id = apply_filters( 'wp_ajax_cropped_attachment_id', $attachment_id, $context ); } wp_send_json_success( wp_prepare_attachment_for_js( $attachment_id ) ); } /** * Handles generating a password via AJAX. * * @since 4.4.0 */ function wp_ajax_generate_password() { wp_send_json_success( wp_generate_password( 24 ) ); } /** * Handles generating a password in the no-privilege context via AJAX. * * @since 5.7.0 */ function wp_ajax_nopriv_generate_password() { wp_send_json_success( wp_generate_password( 24 ) ); } /** * Handles saving the user's WordPress.org username via AJAX. * * @since 4.4.0 */ function wp_ajax_save_wporg_username() { if ( ! current_user_can( 'install_themes' ) && ! current_user_can( 'install_plugins' ) ) { wp_send_json_error(); } check_ajax_referer( 'save_wporg_username_' . get_current_user_id() ); $username = isset( $_REQUEST['username'] ) ? wp_unslash( $_REQUEST['username'] ) : false; if ( ! $username ) { wp_send_json_error(); } wp_send_json_success( update_user_meta( get_current_user_id(), 'wporg_favorites', $username ) ); } /** * Handles installing a theme via AJAX. * * @since 4.6.0 * * @see Theme_Upgrader * * @global WP_Filesystem_Base $wp_filesystem WordPress filesystem subclass. */ function wp_ajax_install_theme() { check_ajax_referer( 'updates' ); if ( empty( $_POST['slug'] ) ) { wp_send_json_error( array( 'slug' => '', 'errorCode' => 'no_theme_specified', 'errorMessage' => __( 'No theme specified.' ), ) ); } $slug = sanitize_key( wp_unslash( $_POST['slug'] ) ); $status = array( 'install' => 'theme', 'slug' => $slug, ); if ( ! current_user_can( 'install_themes' ) ) { $status['errorMessage'] = __( 'Sorry, you are not allowed to install themes on this site.' ); wp_send_json_error( $status ); } require_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php'; require_once ABSPATH . 'wp-admin/includes/theme.php'; $api = themes_api( 'theme_information', array( 'slug' => $slug, 'fields' => array( 'sections' => false ), ) ); if ( is_wp_error( $api ) ) { $status['errorMessage'] = $api->get_error_message(); wp_send_json_error( $status ); } $skin = new WP_Ajax_Upgrader_Skin(); $upgrader = new Theme_Upgrader( $skin ); $result = $upgrader->install( $api->download_link ); if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) { $status['debug'] = $skin->get_upgrade_messages(); } if ( is_wp_error( $result ) ) { $status['errorCode'] = $result->get_error_code(); $status['errorMessage'] = $result->get_error_message(); wp_send_json_error( $status ); } elseif ( is_wp_error( $skin->result ) ) { $status['errorCode'] = $skin->result->get_error_code(); $status['errorMessage'] = $skin->result->get_error_message(); wp_send_json_error( $status ); } elseif ( $skin->get_errors()->has_errors() ) { $status['errorMessage'] = $skin->get_error_messages(); wp_send_json_error( $status ); } elseif ( is_null( $result ) ) { global $wp_filesystem; $status['errorCode'] = 'unable_to_connect_to_filesystem'; $status['errorMessage'] = __( 'Unable to connect to the filesystem. Please confirm your credentials.' ); // Pass through the error from WP_Filesystem if one was raised. if ( $wp_filesystem instanceof WP_Filesystem_Base && is_wp_error( $wp_filesystem->errors ) && $wp_filesystem->errors->has_errors() ) { $status['errorMessage'] = esc_html( $wp_filesystem->errors->get_error_message() ); } wp_send_json_error( $status ); } $status['themeName'] = wp_get_theme( $slug )->get( 'Name' ); if ( current_user_can( 'switch_themes' ) ) { if ( is_multisite() ) { $status['activateUrl'] = add_query_arg( array( 'action' => 'enable', '_wpnonce' => wp_create_nonce( 'enable-theme_' . $slug ), 'theme' => $slug, ), network_admin_url( 'themes.php' ) ); } else { $status['activateUrl'] = add_query_arg( array( 'action' => 'activate', '_wpnonce' => wp_create_nonce( 'switch-theme_' . $slug ), 'stylesheet' => $slug, ), admin_url( 'themes.php' ) ); } } $theme = wp_get_theme( $slug ); $status['blockTheme'] = $theme->is_block_theme(); if ( ! is_multisite() && current_user_can( 'edit_theme_options' ) && current_user_can( 'customize' ) ) { $status['customizeUrl'] = add_query_arg( array( 'return' => urlencode( network_admin_url( 'theme-install.php', 'relative' ) ), ), wp_customize_url( $slug ) ); } /* * See WP_Theme_Install_List_Table::_get_theme_status() if we wanted to check * on post-installation status. */ wp_send_json_success( $status ); } /** * Handles updating a theme via AJAX. * * @since 4.6.0 * * @see Theme_Upgrader * * @global WP_Filesystem_Base $wp_filesystem WordPress filesystem subclass. */ function wp_ajax_update_theme() { check_ajax_referer( 'updates' ); if ( empty( $_POST['slug'] ) ) { wp_send_json_error( array( 'slug' => '', 'errorCode' => 'no_theme_specified', 'errorMessage' => __( 'No theme specified.' ), ) ); } $stylesheet = preg_replace( '/[^A-z0-9_\-]/', '', wp_unslash( $_POST['slug'] ) ); $status = array( 'update' => 'theme', 'slug' => $stylesheet, 'oldVersion' => '', 'newVersion' => '', ); if ( ! current_user_can( 'update_themes' ) ) { $status['errorMessage'] = __( 'Sorry, you are not allowed to update themes for this site.' ); wp_send_json_error( $status ); } $theme = wp_get_theme( $stylesheet ); if ( $theme->exists() ) { $status['oldVersion'] = $theme->get( 'Version' ); } require_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php'; $current = get_site_transient( 'update_themes' ); if ( empty( $current ) ) { wp_update_themes(); } $skin = new WP_Ajax_Upgrader_Skin(); $upgrader = new Theme_Upgrader( $skin ); $result = $upgrader->bulk_upgrade( array( $stylesheet ) ); if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) { $status['debug'] = $skin->get_upgrade_messages(); } if ( is_wp_error( $skin->result ) ) { $status['errorCode'] = $skin->result->get_error_code(); $status['errorMessage'] = $skin->result->get_error_message(); wp_send_json_error( $status ); } elseif ( $skin->get_errors()->has_errors() ) { $status['errorMessage'] = $skin->get_error_messages(); wp_send_json_error( $status ); } elseif ( is_array( $result ) && ! empty( $result[ $stylesheet ] ) ) { // Theme is already at the latest version. if ( true === $result[ $stylesheet ] ) { $status['errorMessage'] = $upgrader->strings['up_to_date']; wp_send_json_error( $status ); } $theme = wp_get_theme( $stylesheet ); if ( $theme->exists() ) { $status['newVersion'] = $theme->get( 'Version' ); } wp_send_json_success( $status ); } elseif ( false === $result ) { global $wp_filesystem; $status['errorCode'] = 'unable_to_connect_to_filesystem'; $status['errorMessage'] = __( 'Unable to connect to the filesystem. Please confirm your credentials.' ); // Pass through the error from WP_Filesystem if one was raised. if ( $wp_filesystem instanceof WP_Filesystem_Base && is_wp_error( $wp_filesystem->errors ) && $wp_filesystem->errors->has_errors() ) { $status['errorMessage'] = esc_html( $wp_filesystem->errors->get_error_message() ); } wp_send_json_error( $status ); } // An unhandled error occurred. $status['errorMessage'] = __( 'Theme update failed.' ); wp_send_json_error( $status ); } /** * Handles deleting a theme via AJAX. * * @since 4.6.0 * * @see delete_theme() * * @global WP_Filesystem_Base $wp_filesystem WordPress filesystem subclass. */ function wp_ajax_delete_theme() { check_ajax_referer( 'updates' ); if ( empty( $_POST['slug'] ) ) { wp_send_json_error( array( 'slug' => '', 'errorCode' => 'no_theme_specified', 'errorMessage' => __( 'No theme specified.' ), ) ); } $stylesheet = preg_replace( '/[^A-z0-9_\-]/', '', wp_unslash( $_POST['slug'] ) ); $status = array( 'delete' => 'theme', 'slug' => $stylesheet, ); if ( ! current_user_can( 'delete_themes' ) ) { $status['errorMessage'] = __( 'Sorry, you are not allowed to delete themes on this site.' ); wp_send_json_error( $status ); } if ( ! wp_get_theme( $stylesheet )->exists() ) { $status['errorMessage'] = __( 'The requested theme does not exist.' ); wp_send_json_error( $status ); } // Check filesystem credentials. `delete_theme()` will bail otherwise. $url = wp_nonce_url( 'themes.php?action=delete&stylesheet=' . urlencode( $stylesheet ), 'delete-theme_' . $stylesheet ); ob_start(); $credentials = request_filesystem_credentials( $url ); ob_end_clean(); if ( false === $credentials || ! WP_Filesystem( $credentials ) ) { global $wp_filesystem; $status['errorCode'] = 'unable_to_connect_to_filesystem'; $status['errorMessage'] = __( 'Unable to connect to the filesystem. Please confirm your credentials.' ); // Pass through the error from WP_Filesystem if one was raised. if ( $wp_filesystem instanceof WP_Filesystem_Base && is_wp_error( $wp_filesystem->errors ) && $wp_filesystem->errors->has_errors() ) { $status['errorMessage'] = esc_html( $wp_filesystem->errors->get_error_message() ); } wp_send_json_error( $status ); } require_once ABSPATH . 'wp-admin/includes/theme.php'; $result = delete_theme( $stylesheet ); if ( is_wp_error( $result ) ) { $status['errorMessage'] = $result->get_error_message(); wp_send_json_error( $status ); } elseif ( false === $result ) { $status['errorMessage'] = __( 'Theme could not be deleted.' ); wp_send_json_error( $status ); } wp_send_json_success( $status ); } /** * Handles installing a plugin via AJAX. * * @since 4.6.0 * * @see Plugin_Upgrader * * @global WP_Filesystem_Base $wp_filesystem WordPress filesystem subclass. */ function wp_ajax_install_plugin() { check_ajax_referer( 'updates' ); if ( empty( $_POST['slug'] ) ) { wp_send_json_error( array( 'slug' => '', 'errorCode' => 'no_plugin_specified', 'errorMessage' => __( 'No plugin specified.' ), ) ); } $status = array( 'install' => 'plugin', 'slug' => sanitize_key( wp_unslash( $_POST['slug'] ) ), ); if ( ! current_user_can( 'install_plugins' ) ) { $status['errorMessage'] = __( 'Sorry, you are not allowed to install plugins on this site.' ); wp_send_json_error( $status ); } require_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php'; require_once ABSPATH . 'wp-admin/includes/plugin-install.php'; $api = plugins_api( 'plugin_information', array( 'slug' => sanitize_key( wp_unslash( $_POST['slug'] ) ), 'fields' => array( 'sections' => false, ), ) ); if ( is_wp_error( $api ) ) { $status['errorMessage'] = $api->get_error_message(); wp_send_json_error( $status ); } $status['pluginName'] = $api->name; $skin = new WP_Ajax_Upgrader_Skin(); $upgrader = new Plugin_Upgrader( $skin ); $result = $upgrader->install( $api->download_link ); if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) { $status['debug'] = $skin->get_upgrade_messages(); } if ( is_wp_error( $result ) ) { $status['errorCode'] = $result->get_error_code(); $status['errorMessage'] = $result->get_error_message(); wp_send_json_error( $status ); } elseif ( is_wp_error( $skin->result ) ) { $status['errorCode'] = $skin->result->get_error_code(); $status['errorMessage'] = $skin->result->get_error_message(); wp_send_json_error( $status ); } elseif ( $skin->get_errors()->has_errors() ) { $status['errorMessage'] = $skin->get_error_messages(); wp_send_json_error( $status ); } elseif ( is_null( $result ) ) { global $wp_filesystem; $status['errorCode'] = 'unable_to_connect_to_filesystem'; $status['errorMessage'] = __( 'Unable to connect to the filesystem. Please confirm your credentials.' ); // Pass through the error from WP_Filesystem if one was raised. if ( $wp_filesystem instanceof WP_Filesystem_Base && is_wp_error( $wp_filesystem->errors ) && $wp_filesystem->errors->has_errors() ) { $status['errorMessage'] = esc_html( $wp_filesystem->errors->get_error_message() ); } wp_send_json_error( $status ); } $install_status = install_plugin_install_status( $api ); $pagenow = isset( $_POST['pagenow'] ) ? sanitize_key( $_POST['pagenow'] ) : ''; // If installation request is coming from import page, do not return network activation link. $plugins_url = ( 'import' === $pagenow ) ? admin_url( 'plugins.php' ) : network_admin_url( 'plugins.php' ); if ( current_user_can( 'activate_plugin', $install_status['file'] ) && is_plugin_inactive( $install_status['file'] ) ) { $status['activateUrl'] = add_query_arg( array( '_wpnonce' => wp_create_nonce( 'activate-plugin_' . $install_status['file'] ), 'action' => 'activate', 'plugin' => $install_status['file'], ), $plugins_url ); } if ( is_multisite() && current_user_can( 'manage_network_plugins' ) && 'import' !== $pagenow ) { $status['activateUrl'] = add_query_arg( array( 'networkwide' => 1 ), $status['activateUrl'] ); } wp_send_json_success( $status ); } /** * Handles activating a plugin via AJAX. * * @since 6.5.0 */ function wp_ajax_activate_plugin() { check_ajax_referer( 'updates' ); if ( empty( $_POST['name'] ) || empty( $_POST['slug'] ) || empty( $_POST['plugin'] ) ) { wp_send_json_error( array( 'slug' => '', 'pluginName' => '', 'plugin' => '', 'errorCode' => 'no_plugin_specified', 'errorMessage' => __( 'No plugin specified.' ), ) ); } $status = array( 'activate' => 'plugin', 'slug' => wp_unslash( $_POST['slug'] ), 'pluginName' => wp_unslash( $_POST['name'] ), 'plugin' => wp_unslash( $_POST['plugin'] ), ); if ( ! current_user_can( 'activate_plugin', $status['plugin'] ) ) { $status['errorMessage'] = __( 'Sorry, you are not allowed to activate plugins on this site.' ); wp_send_json_error( $status ); } if ( is_plugin_active( $status['plugin'] ) ) { $status['errorMessage'] = sprintf( /* translators: %s: Plugin name. */ __( '%s is already active.' ), $status['pluginName'] ); } $activated = activate_plugin( $status['plugin'] ); if ( is_wp_error( $activated ) ) { $status['errorMessage'] = $activated->get_error_message(); wp_send_json_error( $status ); } wp_send_json_success( $status ); } /** * Handles updating a plugin via AJAX. * * @since 4.2.0 * * @see Plugin_Upgrader * * @global WP_Filesystem_Base $wp_filesystem WordPress filesystem subclass. */ function wp_ajax_update_plugin() { check_ajax_referer( 'updates' ); if ( empty( $_POST['plugin'] ) || empty( $_POST['slug'] ) ) { wp_send_json_error( array( 'slug' => '', 'errorCode' => 'no_plugin_specified', 'errorMessage' => __( 'No plugin specified.' ), ) ); } $plugin = plugin_basename( sanitize_text_field( wp_unslash( $_POST['plugin'] ) ) ); $status = array( 'update' => 'plugin', 'slug' => sanitize_key( wp_unslash( $_POST['slug'] ) ), 'oldVersion' => '', 'newVersion' => '', ); if ( ! current_user_can( 'update_plugins' ) || 0 !== validate_file( $plugin ) ) { $status['errorMessage'] = __( 'Sorry, you are not allowed to update plugins for this site.' ); wp_send_json_error( $status ); } $plugin_data = get_plugin_data( WP_PLUGIN_DIR . '/' . $plugin ); $status['plugin'] = $plugin; $status['pluginName'] = $plugin_data['Name']; if ( $plugin_data['Version'] ) { /* translators: %s: Plugin version. */ $status['oldVersion'] = sprintf( __( 'Version %s' ), $plugin_data['Version'] ); } require_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php'; wp_update_plugins(); $skin = new WP_Ajax_Upgrader_Skin(); $upgrader = new Plugin_Upgrader( $skin ); $result = $upgrader->bulk_upgrade( array( $plugin ) ); if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) { $status['debug'] = $skin->get_upgrade_messages(); } if ( is_wp_error( $skin->result ) ) { $status['errorCode'] = $skin->result->get_error_code(); $status['errorMessage'] = $skin->result->get_error_message(); wp_send_json_error( $status ); } elseif ( $skin->get_errors()->has_errors() ) { $status['errorMessage'] = $skin->get_error_messages(); wp_send_json_error( $status ); } elseif ( is_array( $result ) && ! empty( $result[ $plugin ] ) ) { /* * Plugin is already at the latest version. * * This may also be the return value if the `update_plugins` site transient is empty, * e.g. when you update two plugins in quick succession before the transient repopulates. * * Preferably something can be done to ensure `update_plugins` isn't empty. * For now, surface some sort of error here. */ if ( true === $result[ $plugin ] ) { $status['errorMessage'] = $upgrader->strings['up_to_date']; wp_send_json_error( $status ); } $plugin_data = get_plugins( '/' . $result[ $plugin ]['destination_name'] ); $plugin_data = reset( $plugin_data ); if ( $plugin_data['Version'] ) { /* translators: %s: Plugin version. */ $status['newVersion'] = sprintf( __( 'Version %s' ), $plugin_data['Version'] ); } wp_send_json_success( $status ); } elseif ( false === $result ) { global $wp_filesystem; $status['errorCode'] = 'unable_to_connect_to_filesystem'; $status['errorMessage'] = __( 'Unable to connect to the filesystem. Please confirm your credentials.' ); // Pass through the error from WP_Filesystem if one was raised. if ( $wp_filesystem instanceof WP_Filesystem_Base && is_wp_error( $wp_filesystem->errors ) && $wp_filesystem->errors->has_errors() ) { $status['errorMessage'] = esc_html( $wp_filesystem->errors->get_error_message() ); } wp_send_json_error( $status ); } // An unhandled error occurred. $status['errorMessage'] = __( 'Plugin update failed.' ); wp_send_json_error( $status ); } /** * Handles deleting a plugin via AJAX. * * @since 4.6.0 * * @see delete_plugins() * * @global WP_Filesystem_Base $wp_filesystem WordPress filesystem subclass. */ function wp_ajax_delete_plugin() { check_ajax_referer( 'updates' ); if ( empty( $_POST['slug'] ) || empty( $_POST['plugin'] ) ) { wp_send_json_error( array( 'slug' => '', 'errorCode' => 'no_plugin_specified', 'errorMessage' => __( 'No plugin specified.' ), ) ); } $plugin = plugin_basename( sanitize_text_field( wp_unslash( $_POST['plugin'] ) ) ); $status = array( 'delete' => 'plugin', 'slug' => sanitize_key( wp_unslash( $_POST['slug'] ) ), ); if ( ! current_user_can( 'delete_plugins' ) || 0 !== validate_file( $plugin ) ) { $status['errorMessage'] = __( 'Sorry, you are not allowed to delete plugins for this site.' ); wp_send_json_error( $status ); } $plugin_data = get_plugin_data( WP_PLUGIN_DIR . '/' . $plugin ); $status['plugin'] = $plugin; $status['pluginName'] = $plugin_data['Name']; if ( is_plugin_active( $plugin ) ) { $status['errorMessage'] = __( 'You cannot delete a plugin while it is active on the main site.' ); wp_send_json_error( $status ); } // Check filesystem credentials. `delete_plugins()` will bail otherwise. $url = wp_nonce_url( 'plugins.php?action=delete-selected&verify-delete=1&checked[]=' . $plugin, 'bulk-plugins' ); ob_start(); $credentials = request_filesystem_credentials( $url ); ob_end_clean(); if ( false === $credentials || ! WP_Filesystem( $credentials ) ) { global $wp_filesystem; $status['errorCode'] = 'unable_to_connect_to_filesystem'; $status['errorMessage'] = __( 'Unable to connect to the filesystem. Please confirm your credentials.' ); // Pass through the error from WP_Filesystem if one was raised. if ( $wp_filesystem instanceof WP_Filesystem_Base && is_wp_error( $wp_filesystem->errors ) && $wp_filesystem->errors->has_errors() ) { $status['errorMessage'] = esc_html( $wp_filesystem->errors->get_error_message() ); } wp_send_json_error( $status ); } $result = delete_plugins( array( $plugin ) ); if ( is_wp_error( $result ) ) { $status['errorMessage'] = $result->get_error_message(); wp_send_json_error( $status ); } elseif ( false === $result ) { $status['errorMessage'] = __( 'Plugin could not be deleted.' ); wp_send_json_error( $status ); } wp_send_json_success( $status ); } /** * Handles searching plugins via AJAX. * * @since 4.6.0 * * @global string $s Search term. */ function wp_ajax_search_plugins() { check_ajax_referer( 'updates' ); // Ensure after_plugin_row_{$plugin_file} gets hooked. wp_plugin_update_rows(); $pagenow = isset( $_POST['pagenow'] ) ? sanitize_key( $_POST['pagenow'] ) : ''; if ( 'plugins-network' === $pagenow || 'plugins' === $pagenow ) { set_current_screen( $pagenow ); } /** @var WP_Plugins_List_Table $wp_list_table */ $wp_list_table = _get_list_table( 'WP_Plugins_List_Table', array( 'screen' => get_current_screen(), ) ); $status = array(); if ( ! $wp_list_table->ajax_user_can() ) { $status['errorMessage'] = __( 'Sorry, you are not allowed to manage plugins for this site.' ); wp_send_json_error( $status ); } // Set the correct requester, so pagination works. $_SERVER['REQUEST_URI'] = add_query_arg( array_diff_key( $_POST, array( '_ajax_nonce' => null, 'action' => null, ) ), network_admin_url( 'plugins.php', 'relative' ) ); $GLOBALS['s'] = wp_unslash( $_POST['s'] ); $wp_list_table->prepare_items(); ob_start(); $wp_list_table->display(); $status['count'] = count( $wp_list_table->items ); $status['items'] = ob_get_clean(); wp_send_json_success( $status ); } /** * Handles searching plugins to install via AJAX. * * @since 4.6.0 */ function wp_ajax_search_install_plugins() { check_ajax_referer( 'updates' ); $pagenow = isset( $_POST['pagenow'] ) ? sanitize_key( $_POST['pagenow'] ) : ''; if ( 'plugin-install-network' === $pagenow || 'plugin-install' === $pagenow ) { set_current_screen( $pagenow ); } /** @var WP_Plugin_Install_List_Table $wp_list_table */ $wp_list_table = _get_list_table( 'WP_Plugin_Install_List_Table', array( 'screen' => get_current_screen(), ) ); $status = array(); if ( ! $wp_list_table->ajax_user_can() ) { $status['errorMessage'] = __( 'Sorry, you are not allowed to manage plugins for this site.' ); wp_send_json_error( $status ); } // Set the correct requester, so pagination works. $_SERVER['REQUEST_URI'] = add_query_arg( array_diff_key( $_POST, array( '_ajax_nonce' => null, 'action' => null, ) ), network_admin_url( 'plugin-install.php', 'relative' ) ); $wp_list_table->prepare_items(); ob_start(); $wp_list_table->display(); $status['count'] = (int) $wp_list_table->get_pagination_arg( 'total_items' ); $status['items'] = ob_get_clean(); wp_send_json_success( $status ); } /** * Handles editing a theme or plugin file via AJAX. * * @since 4.9.0 * * @see wp_edit_theme_plugin_file() */ function wp_ajax_edit_theme_plugin_file() { $r = wp_edit_theme_plugin_file( wp_unslash( $_POST ) ); // Validation of args is done in wp_edit_theme_plugin_file(). if ( is_wp_error( $r ) ) { wp_send_json_error( array_merge( array( 'code' => $r->get_error_code(), 'message' => $r->get_error_message(), ), (array) $r->get_error_data() ) ); } else { wp_send_json_success( array( 'message' => __( 'File edited successfully.' ), ) ); } } /** * Handles exporting a user's personal data via AJAX. * * @since 4.9.6 */ function wp_ajax_wp_privacy_export_personal_data() { if ( empty( $_POST['id'] ) ) { wp_send_json_error( __( 'Missing request ID.' ) ); } $request_id = (int) $_POST['id']; if ( $request_id < 1 ) { wp_send_json_error( __( 'Invalid request ID.' ) ); } if ( ! current_user_can( 'export_others_personal_data' ) ) { wp_send_json_error( __( 'Sorry, you are not allowed to perform this action.' ) ); } check_ajax_referer( 'wp-privacy-export-personal-data-' . $request_id, 'security' ); // Get the request. $request = wp_get_user_request( $request_id ); if ( ! $request || 'export_personal_data' !== $request->action_name ) { wp_send_json_error( __( 'Invalid request type.' ) ); } $email_address = $request->email; if ( ! is_email( $email_address ) ) { wp_send_json_error( __( 'A valid email address must be given.' ) ); } if ( ! isset( $_POST['exporter'] ) ) { wp_send_json_error( __( 'Missing exporter index.' ) ); } $exporter_index = (int) $_POST['exporter']; if ( ! isset( $_POST['page'] ) ) { wp_send_json_error( __( 'Missing page index.' ) ); } $page = (int) $_POST['page']; $send_as_email = isset( $_POST['sendAsEmail'] ) ? ( 'true' === $_POST['sendAsEmail'] ) : false; /** * Filters the array of exporter callbacks. * * @since 4.9.6 * * @param array $args { * An array of callable exporters of personal data. Default empty array. * * @type array ...$0 { * Array of personal data exporters. * * @type callable $callback Callable exporter function that accepts an * email address and a page number and returns an * array of name => value pairs of personal data. * @type string $exporter_friendly_name Translated user facing friendly name for the * exporter. * } * } */ $exporters = apply_filters( 'wp_privacy_personal_data_exporters', array() ); if ( ! is_array( $exporters ) ) { wp_send_json_error( __( 'An exporter has improperly used the registration filter.' ) ); } // Do we have any registered exporters? if ( 0 < count( $exporters ) ) { if ( $exporter_index < 1 ) { wp_send_json_error( __( 'Exporter index cannot be negative.' ) ); } if ( $exporter_index > count( $exporters ) ) { wp_send_json_error( __( 'Exporter index is out of range.' ) ); } if ( $page < 1 ) { wp_send_json_error( __( 'Page index cannot be less than one.' ) ); } $exporter_keys = array_keys( $exporters ); $exporter_key = $exporter_keys[ $exporter_index - 1 ]; $exporter = $exporters[ $exporter_key ]; if ( ! is_array( $exporter ) ) { wp_send_json_error( /* translators: %s: Exporter array index. */ sprintf( __( 'Expected an array describing the exporter at index %s.' ), $exporter_key ) ); } if ( ! array_key_exists( 'exporter_friendly_name', $exporter ) ) { wp_send_json_error( /* translators: %s: Exporter array index. */ sprintf( __( 'Exporter array at index %s does not include a friendly name.' ), $exporter_key ) ); } $exporter_friendly_name = $exporter['exporter_friendly_name']; if ( ! array_key_exists( 'callback', $exporter ) ) { wp_send_json_error( /* translators: %s: Exporter friendly name. */ sprintf( __( 'Exporter does not include a callback: %s.' ), esc_html( $exporter_friendly_name ) ) ); } if ( ! is_callable( $exporter['callback'] ) ) { wp_send_json_error( /* translators: %s: Exporter friendly name. */ sprintf( __( 'Exporter callback is not a valid callback: %s.' ), esc_html( $exporter_friendly_name ) ) ); } $callback = $exporter['callback']; $response = call_user_func( $callback, $email_address, $page ); if ( is_wp_error( $response ) ) { wp_send_json_error( $response ); } if ( ! is_array( $response ) ) { wp_send_json_error( /* translators: %s: Exporter friendly name. */ sprintf( __( 'Expected response as an array from exporter: %s.' ), esc_html( $exporter_friendly_name ) ) ); } if ( ! array_key_exists( 'data', $response ) ) { wp_send_json_error( /* translators: %s: Exporter friendly name. */ sprintf( __( 'Expected data in response array from exporter: %s.' ), esc_html( $exporter_friendly_name ) ) ); } if ( ! is_array( $response['data'] ) ) { wp_send_json_error( /* translators: %s: Exporter friendly name. */ sprintf( __( 'Expected data array in response array from exporter: %s.' ), esc_html( $exporter_friendly_name ) ) ); } if ( ! array_key_exists( 'done', $response ) ) { wp_send_json_error( /* translators: %s: Exporter friendly name. */ sprintf( __( 'Expected done (boolean) in response array from exporter: %s.' ), esc_html( $exporter_friendly_name ) ) ); } } else { // No exporters, so we're done. $exporter_key = ''; $response = array( 'data' => array(), 'done' => true, ); } /** * Filters a page of personal data exporter data. Used to build the export report. * * Allows the export response to be consumed by destinations in addition to Ajax. * * @since 4.9.6 * * @param array $response The personal data for the given exporter and page number. * @param int $exporter_index The index of the exporter that provided this data. * @param string $email_address The email address associated with this personal data. * @param int $page The page number for this response. * @param int $request_id The privacy request post ID associated with this request. * @param bool $send_as_email Whether the final results of the export should be emailed to the user. * @param string $exporter_key The key (slug) of the exporter that provided this data. */ $response = apply_filters( 'wp_privacy_personal_data_export_page', $response, $exporter_index, $email_address, $page, $request_id, $send_as_email, $exporter_key ); if ( is_wp_error( $response ) ) { wp_send_json_error( $response ); } wp_send_json_success( $response ); } /** * Handles erasing personal data via AJAX. * * @since 4.9.6 */ function wp_ajax_wp_privacy_erase_personal_data() { if ( empty( $_POST['id'] ) ) { wp_send_json_error( __( 'Missing request ID.' ) ); } $request_id = (int) $_POST['id']; if ( $request_id < 1 ) { wp_send_json_error( __( 'Invalid request ID.' ) ); } // Both capabilities are required to avoid confusion, see `_wp_personal_data_removal_page()`. if ( ! current_user_can( 'erase_others_personal_data' ) || ! current_user_can( 'delete_users' ) ) { wp_send_json_error( __( 'Sorry, you are not allowed to perform this action.' ) ); } check_ajax_referer( 'wp-privacy-erase-personal-data-' . $request_id, 'security' ); // Get the request. $request = wp_get_user_request( $request_id ); if ( ! $request || 'remove_personal_data' !== $request->action_name ) { wp_send_json_error( __( 'Invalid request type.' ) ); } $email_address = $request->email; if ( ! is_email( $email_address ) ) { wp_send_json_error( __( 'Invalid email address in request.' ) ); } if ( ! isset( $_POST['eraser'] ) ) { wp_send_json_error( __( 'Missing eraser index.' ) ); } $eraser_index = (int) $_POST['eraser']; if ( ! isset( $_POST['page'] ) ) { wp_send_json_error( __( 'Missing page index.' ) ); } $page = (int) $_POST['page']; /** * Filters the array of personal data eraser callbacks. * * @since 4.9.6 * * @param array $args { * An array of callable erasers of personal data. Default empty array. * * @type array ...$0 { * Array of personal data exporters. * * @type callable $callback Callable eraser that accepts an email address and a page * number, and returns an array with boolean values for * whether items were removed or retained and any messages * from the eraser, as well as if additional pages are * available. * @type string $exporter_friendly_name Translated user facing friendly name for the eraser. * } * } */ $erasers = apply_filters( 'wp_privacy_personal_data_erasers', array() ); // Do we have any registered erasers? if ( 0 < count( $erasers ) ) { if ( $eraser_index < 1 ) { wp_send_json_error( __( 'Eraser index cannot be less than one.' ) ); } if ( $eraser_index > count( $erasers ) ) { wp_send_json_error( __( 'Eraser index is out of range.' ) ); } if ( $page < 1 ) { wp_send_json_error( __( 'Page index cannot be less than one.' ) ); } $eraser_keys = array_keys( $erasers ); $eraser_key = $eraser_keys[ $eraser_index - 1 ]; $eraser = $erasers[ $eraser_key ]; if ( ! is_array( $eraser ) ) { /* translators: %d: Eraser array index. */ wp_send_json_error( sprintf( __( 'Expected an array describing the eraser at index %d.' ), $eraser_index ) ); } if ( ! array_key_exists( 'eraser_friendly_name', $eraser ) ) { /* translators: %d: Eraser array index. */ wp_send_json_error( sprintf( __( 'Eraser array at index %d does not include a friendly name.' ), $eraser_index ) ); } $eraser_friendly_name = $eraser['eraser_friendly_name']; if ( ! array_key_exists( 'callback', $eraser ) ) { wp_send_json_error( sprintf( /* translators: %s: Eraser friendly name. */ __( 'Eraser does not include a callback: %s.' ), esc_html( $eraser_friendly_name ) ) ); } if ( ! is_callable( $eraser['callback'] ) ) { wp_send_json_error( sprintf( /* translators: %s: Eraser friendly name. */ __( 'Eraser callback is not valid: %s.' ), esc_html( $eraser_friendly_name ) ) ); } $callback = $eraser['callback']; $response = call_user_func( $callback, $email_address, $page ); if ( is_wp_error( $response ) ) { wp_send_json_error( $response ); } if ( ! is_array( $response ) ) { wp_send_json_error( sprintf( /* translators: 1: Eraser friendly name, 2: Eraser array index. */ __( 'Did not receive array from %1$s eraser (index %2$d).' ), esc_html( $eraser_friendly_name ), $eraser_index ) ); } if ( ! array_key_exists( 'items_removed', $response ) ) { wp_send_json_error( sprintf( /* translators: 1: Eraser friendly name, 2: Eraser array index. */ __( 'Expected items_removed key in response array from %1$s eraser (index %2$d).' ), esc_html( $eraser_friendly_name ), $eraser_index ) ); } if ( ! array_key_exists( 'items_retained', $response ) ) { wp_send_json_error( sprintf( /* translators: 1: Eraser friendly name, 2: Eraser array index. */ __( 'Expected items_retained key in response array from %1$s eraser (index %2$d).' ), esc_html( $eraser_friendly_name ), $eraser_index ) ); } if ( ! array_key_exists( 'messages', $response ) ) { wp_send_json_error( sprintf( /* translators: 1: Eraser friendly name, 2: Eraser array index. */ __( 'Expected messages key in response array from %1$s eraser (index %2$d).' ), esc_html( $eraser_friendly_name ), $eraser_index ) ); } if ( ! is_array( $response['messages'] ) ) { wp_send_json_error( sprintf( /* translators: 1: Eraser friendly name, 2: Eraser array index. */ __( 'Expected messages key to reference an array in response array from %1$s eraser (index %2$d).' ), esc_html( $eraser_friendly_name ), $eraser_index ) ); } if ( ! array_key_exists( 'done', $response ) ) { wp_send_json_error( sprintf( /* translators: 1: Eraser friendly name, 2: Eraser array index. */ __( 'Expected done flag in response array from %1$s eraser (index %2$d).' ), esc_html( $eraser_friendly_name ), $eraser_index ) ); } } else { // No erasers, so we're done. $eraser_key = ''; $response = array( 'items_removed' => false, 'items_retained' => false, 'messages' => array(), 'done' => true, ); } /** * Filters a page of personal data eraser data. * * Allows the erasure response to be consumed by destinations in addition to Ajax. * * @since 4.9.6 * * @param array $response { * The personal data for the given exporter and page number. * * @type bool $items_removed Whether items were actually removed or not. * @type bool $items_retained Whether items were retained or not. * @type string[] $messages An array of messages to add to the personal data export file. * @type bool $done Whether the eraser is finished or not. * } * @param int $eraser_index The index of the eraser that provided this data. * @param string $email_address The email address associated with this personal data. * @param int $page The page number for this response. * @param int $request_id The privacy request post ID associated with this request. * @param string $eraser_key The key (slug) of the eraser that provided this data. */ $response = apply_filters( 'wp_privacy_personal_data_erasure_page', $response, $eraser_index, $email_address, $page, $request_id, $eraser_key ); if ( is_wp_error( $response ) ) { wp_send_json_error( $response ); } wp_send_json_success( $response ); } /** * Handles site health checks on server communication via AJAX. * * @since 5.2.0 * @deprecated 5.6.0 Use WP_REST_Site_Health_Controller::test_dotorg_communication() * @see WP_REST_Site_Health_Controller::test_dotorg_communication() */ function wp_ajax_health_check_dotorg_communication() { _doing_it_wrong( 'wp_ajax_health_check_dotorg_communication', sprintf( // translators: 1: The Site Health action that is no longer used by core. 2: The new function that replaces it. __( 'The Site Health check for %1$s has been replaced with %2$s.' ), 'wp_ajax_health_check_dotorg_communication', 'WP_REST_Site_Health_Controller::test_dotorg_communication' ), '5.6.0' ); check_ajax_referer( 'health-check-site-status' ); if ( ! current_user_can( 'view_site_health_checks' ) ) { wp_send_json_error(); } if ( ! class_exists( 'WP_Site_Health' ) ) { require_once ABSPATH . 'wp-admin/includes/class-wp-site-health.php'; } $site_health = WP_Site_Health::get_instance(); wp_send_json_success( $site_health->get_test_dotorg_communication() ); } /** * Handles site health checks on background updates via AJAX. * * @since 5.2.0 * @deprecated 5.6.0 Use WP_REST_Site_Health_Controller::test_background_updates() * @see WP_REST_Site_Health_Controller::test_background_updates() */ function wp_ajax_health_check_background_updates() { _doing_it_wrong( 'wp_ajax_health_check_background_updates', sprintf( // translators: 1: The Site Health action that is no longer used by core. 2: The new function that replaces it. __( 'The Site Health check for %1$s has been replaced with %2$s.' ), 'wp_ajax_health_check_background_updates', 'WP_REST_Site_Health_Controller::test_background_updates' ), '5.6.0' ); check_ajax_referer( 'health-check-site-status' ); if ( ! current_user_can( 'view_site_health_checks' ) ) { wp_send_json_error(); } if ( ! class_exists( 'WP_Site_Health' ) ) { require_once ABSPATH . 'wp-admin/includes/class-wp-site-health.php'; } $site_health = WP_Site_Health::get_instance(); wp_send_json_success( $site_health->get_test_background_updates() ); } /** * Handles site health checks on loopback requests via AJAX. * * @since 5.2.0 * @deprecated 5.6.0 Use WP_REST_Site_Health_Controller::test_loopback_requests() * @see WP_REST_Site_Health_Controller::test_loopback_requests() */ function wp_ajax_health_check_loopback_requests() { _doing_it_wrong( 'wp_ajax_health_check_loopback_requests', sprintf( // translators: 1: The Site Health action that is no longer used by core. 2: The new function that replaces it. __( 'The Site Health check for %1$s has been replaced with %2$s.' ), 'wp_ajax_health_check_loopback_requests', 'WP_REST_Site_Health_Controller::test_loopback_requests' ), '5.6.0' ); check_ajax_referer( 'health-check-site-status' ); if ( ! current_user_can( 'view_site_health_checks' ) ) { wp_send_json_error(); } if ( ! class_exists( 'WP_Site_Health' ) ) { require_once ABSPATH . 'wp-admin/includes/class-wp-site-health.php'; } $site_health = WP_Site_Health::get_instance(); wp_send_json_success( $site_health->get_test_loopback_requests() ); } /** * Handles site health check to update the result status via AJAX. * * @since 5.2.0 */ function wp_ajax_health_check_site_status_result() { check_ajax_referer( 'health-check-site-status-result' ); if ( ! current_user_can( 'view_site_health_checks' ) ) { wp_send_json_error(); } set_transient( 'health-check-site-status-result', wp_json_encode( $_POST['counts'] ) ); wp_send_json_success(); } /** * Handles site health check to get directories and database sizes via AJAX. * * @since 5.2.0 * @deprecated 5.6.0 Use WP_REST_Site_Health_Controller::get_directory_sizes() * @see WP_REST_Site_Health_Controller::get_directory_sizes() */ function wp_ajax_health_check_get_sizes() { _doing_it_wrong( 'wp_ajax_health_check_get_sizes', sprintf( // translators: 1: The Site Health action that is no longer used by core. 2: The new function that replaces it. __( 'The Site Health check for %1$s has been replaced with %2$s.' ), 'wp_ajax_health_check_get_sizes', 'WP_REST_Site_Health_Controller::get_directory_sizes' ), '5.6.0' ); check_ajax_referer( 'health-check-site-status-result' ); if ( ! current_user_can( 'view_site_health_checks' ) || is_multisite() ) { wp_send_json_error(); } if ( ! class_exists( 'WP_Debug_Data' ) ) { require_once ABSPATH . 'wp-admin/includes/class-wp-debug-data.php'; } $sizes_data = WP_Debug_Data::get_sizes(); $all_sizes = array( 'raw' => 0 ); foreach ( $sizes_data as $name => $value ) { $name = sanitize_text_field( $name ); $data = array(); if ( isset( $value['size'] ) ) { if ( is_string( $value['size'] ) ) { $data['size'] = sanitize_text_field( $value['size'] ); } else { $data['size'] = (int) $value['size']; } } if ( isset( $value['debug'] ) ) { if ( is_string( $value['debug'] ) ) { $data['debug'] = sanitize_text_field( $value['debug'] ); } else { $data['debug'] = (int) $value['debug']; } } if ( ! empty( $value['raw'] ) ) { $data['raw'] = (int) $value['raw']; } $all_sizes[ $name ] = $data; } if ( isset( $all_sizes['total_size']['debug'] ) && 'not available' === $all_sizes['total_size']['debug'] ) { wp_send_json_error( $all_sizes ); } wp_send_json_success( $all_sizes ); } /** * Handles renewing the REST API nonce via AJAX. * * @since 5.3.0 */ function wp_ajax_rest_nonce() { exit( wp_create_nonce( 'wp_rest' ) ); } /** * Handles enabling or disable plugin and theme auto-updates via AJAX. * * @since 5.5.0 */ function wp_ajax_toggle_auto_updates() { check_ajax_referer( 'updates' ); if ( empty( $_POST['type'] ) || empty( $_POST['asset'] ) || empty( $_POST['state'] ) ) { wp_send_json_error( array( 'error' => __( 'Invalid data. No selected item.' ) ) ); } $asset = sanitize_text_field( urldecode( $_POST['asset'] ) ); if ( 'enable' !== $_POST['state'] && 'disable' !== $_POST['state'] ) { wp_send_json_error( array( 'error' => __( 'Invalid data. Unknown state.' ) ) ); } $state = $_POST['state']; if ( 'plugin' !== $_POST['type'] && 'theme' !== $_POST['type'] ) { wp_send_json_error( array( 'error' => __( 'Invalid data. Unknown type.' ) ) ); } $type = $_POST['type']; switch ( $type ) { case 'plugin': if ( ! current_user_can( 'update_plugins' ) ) { $error_message = __( 'Sorry, you are not allowed to modify plugins.' ); wp_send_json_error( array( 'error' => $error_message ) ); } $option = 'auto_update_plugins'; /** This filter is documented in wp-admin/includes/class-wp-plugins-list-table.php */ $all_items = apply_filters( 'all_plugins', get_plugins() ); break; case 'theme': if ( ! current_user_can( 'update_themes' ) ) { $error_message = __( 'Sorry, you are not allowed to modify themes.' ); wp_send_json_error( array( 'error' => $error_message ) ); } $option = 'auto_update_themes'; $all_items = wp_get_themes(); break; default: wp_send_json_error( array( 'error' => __( 'Invalid data. Unknown type.' ) ) ); } if ( ! array_key_exists( $asset, $all_items ) ) { $error_message = __( 'Invalid data. The item does not exist.' ); wp_send_json_error( array( 'error' => $error_message ) ); } $auto_updates = (array) get_site_option( $option, array() ); if ( 'disable' === $state ) { $auto_updates = array_diff( $auto_updates, array( $asset ) ); } else { $auto_updates[] = $asset; $auto_updates = array_unique( $auto_updates ); } // Remove items that have been deleted since the site option was last updated. $auto_updates = array_intersect( $auto_updates, array_keys( $all_items ) ); update_site_option( $option, $auto_updates ); wp_send_json_success(); } /** * Handles sending a password reset link via AJAX. * * @since 5.7.0 */ function wp_ajax_send_password_reset() { // Validate the nonce for this action. $user_id = isset( $_POST['user_id'] ) ? (int) $_POST['user_id'] : 0; check_ajax_referer( 'reset-password-for-' . $user_id, 'nonce' ); // Verify user capabilities. if ( ! current_user_can( 'edit_user', $user_id ) ) { wp_send_json_error( __( 'Cannot send password reset, permission denied.' ) ); } // Send the password reset link. $user = get_userdata( $user_id ); $results = retrieve_password( $user->user_login ); if ( true === $results ) { wp_send_json_success( /* translators: %s: User's display name. */ sprintf( __( 'A password reset link was emailed to %s.' ), $user->display_name ) ); } else { wp_send_json_error( $results->get_error_message() ); } } continents-cities.php000064400000050074147206365750010744 0ustar00 false, 'test_type' => false, ); $file = wp_handle_upload( $_FILES[ $form ], $overrides ); if ( isset( $file['error'] ) ) { wp_die( $file['error'] ); } if ( 'pluginzip' === $form || 'themezip' === $form ) { if ( ! wp_zip_file_is_valid( $file['file'] ) ) { wp_delete_file( $file['file'] ); if ( 'pluginzip' === $form ) { $plugins_page = sprintf( '%s', self_admin_url( 'plugin-install.php' ), __( 'Return to the Plugin Installer' ) ); wp_die( __( 'Incompatible Archive.' ) . '
    ' . $plugins_page ); } if ( 'themezip' === $form ) { $themes_page = sprintf( '%s', self_admin_url( 'theme-install.php' ), __( 'Return to the Theme Installer' ) ); wp_die( __( 'Incompatible Archive.' ) . '
    ' . $themes_page ); } } } $this->filename = $_FILES[ $form ]['name']; $this->package = $file['file']; // Construct the attachment array. $attachment = array( 'post_title' => $this->filename, 'post_content' => $file['url'], 'post_mime_type' => $file['type'], 'guid' => $file['url'], 'context' => 'upgrader', 'post_status' => 'private', ); // Save the data. $this->id = wp_insert_attachment( $attachment, $file['file'] ); // Schedule a cleanup for 2 hours from now in case of failed installation. wp_schedule_single_event( time() + 2 * HOUR_IN_SECONDS, 'upgrader_scheduled_cleanup', array( $this->id ) ); } elseif ( is_numeric( $_GET[ $urlholder ] ) ) { // Numeric Package = previously uploaded file, see above. $this->id = (int) $_GET[ $urlholder ]; $attachment = get_post( $this->id ); if ( empty( $attachment ) ) { wp_die( __( 'Please select a file' ) ); } $this->filename = $attachment->post_title; $this->package = get_attached_file( $attachment->ID ); } else { // Else, It's set to something, Back compat for plugins using the old (pre-3.3) File_Uploader handler. $uploads = wp_upload_dir(); if ( ! ( $uploads && false === $uploads['error'] ) ) { wp_die( $uploads['error'] ); } $this->filename = sanitize_file_name( $_GET[ $urlholder ] ); $this->package = $uploads['basedir'] . '/' . $this->filename; if ( ! str_starts_with( realpath( $this->package ), realpath( $uploads['basedir'] ) ) ) { wp_die( __( 'Please select a file' ) ); } } } /** * Deletes the attachment/uploaded file. * * @since 3.2.2 * * @return bool Whether the cleanup was successful. */ public function cleanup() { if ( $this->id ) { wp_delete_attachment( $this->id ); } elseif ( file_exists( $this->package ) ) { return @unlink( $this->package ); } return true; } } privacy-tools.php000064400000101266147206365750010115 0ustar00post_type ) { return new WP_Error( 'privacy_request_error', __( 'Invalid personal data request.' ) ); } $result = wp_send_user_request( $request_id ); if ( is_wp_error( $result ) ) { return $result; } elseif ( ! $result ) { return new WP_Error( 'privacy_request_error', __( 'Unable to initiate confirmation for personal data request.' ) ); } return true; } /** * Marks a request as completed by the admin and logs the current timestamp. * * @since 4.9.6 * @access private * * @param int $request_id Request ID. * @return int|WP_Error Request ID on success, or a WP_Error on failure. */ function _wp_privacy_completed_request( $request_id ) { // Get the request. $request_id = absint( $request_id ); $request = wp_get_user_request( $request_id ); if ( ! $request ) { return new WP_Error( 'privacy_request_error', __( 'Invalid personal data request.' ) ); } update_post_meta( $request_id, '_wp_user_request_completed_timestamp', time() ); $result = wp_update_post( array( 'ID' => $request_id, 'post_status' => 'request-completed', ) ); return $result; } /** * Handle list table actions. * * @since 4.9.6 * @access private */ function _wp_personal_data_handle_actions() { if ( isset( $_POST['privacy_action_email_retry'] ) ) { check_admin_referer( 'bulk-privacy_requests' ); $request_id = absint( current( array_keys( (array) wp_unslash( $_POST['privacy_action_email_retry'] ) ) ) ); $result = _wp_privacy_resend_request( $request_id ); if ( is_wp_error( $result ) ) { add_settings_error( 'privacy_action_email_retry', 'privacy_action_email_retry', $result->get_error_message(), 'error' ); } else { add_settings_error( 'privacy_action_email_retry', 'privacy_action_email_retry', __( 'Confirmation request sent again successfully.' ), 'success' ); } } elseif ( isset( $_POST['action'] ) ) { $action = ! empty( $_POST['action'] ) ? sanitize_key( wp_unslash( $_POST['action'] ) ) : ''; switch ( $action ) { case 'add_export_personal_data_request': case 'add_remove_personal_data_request': check_admin_referer( 'personal-data-request' ); if ( ! isset( $_POST['type_of_action'], $_POST['username_or_email_for_privacy_request'] ) ) { add_settings_error( 'action_type', 'action_type', __( 'Invalid personal data action.' ), 'error' ); } $action_type = sanitize_text_field( wp_unslash( $_POST['type_of_action'] ) ); $username_or_email_address = sanitize_text_field( wp_unslash( $_POST['username_or_email_for_privacy_request'] ) ); $email_address = ''; $status = 'pending'; if ( ! isset( $_POST['send_confirmation_email'] ) ) { $status = 'confirmed'; } if ( ! in_array( $action_type, _wp_privacy_action_request_types(), true ) ) { add_settings_error( 'action_type', 'action_type', __( 'Invalid personal data action.' ), 'error' ); } if ( ! is_email( $username_or_email_address ) ) { $user = get_user_by( 'login', $username_or_email_address ); if ( ! $user instanceof WP_User ) { add_settings_error( 'username_or_email_for_privacy_request', 'username_or_email_for_privacy_request', __( 'Unable to add this request. A valid email address or username must be supplied.' ), 'error' ); } else { $email_address = $user->user_email; } } else { $email_address = $username_or_email_address; } if ( empty( $email_address ) ) { break; } $request_id = wp_create_user_request( $email_address, $action_type, array(), $status ); $message = ''; if ( is_wp_error( $request_id ) ) { $message = $request_id->get_error_message(); } elseif ( ! $request_id ) { $message = __( 'Unable to initiate confirmation request.' ); } if ( $message ) { add_settings_error( 'username_or_email_for_privacy_request', 'username_or_email_for_privacy_request', $message, 'error' ); break; } if ( 'pending' === $status ) { wp_send_user_request( $request_id ); $message = __( 'Confirmation request initiated successfully.' ); } elseif ( 'confirmed' === $status ) { $message = __( 'Request added successfully.' ); } if ( $message ) { add_settings_error( 'username_or_email_for_privacy_request', 'username_or_email_for_privacy_request', $message, 'success' ); break; } } } } /** * Cleans up failed and expired requests before displaying the list table. * * @since 4.9.6 * @access private */ function _wp_personal_data_cleanup_requests() { /** This filter is documented in wp-includes/user.php */ $expires = (int) apply_filters( 'user_request_key_expiration', DAY_IN_SECONDS ); $requests_query = new WP_Query( array( 'post_type' => 'user_request', 'posts_per_page' => -1, 'post_status' => 'request-pending', 'fields' => 'ids', 'date_query' => array( array( 'column' => 'post_modified_gmt', 'before' => $expires . ' seconds ago', ), ), ) ); $request_ids = $requests_query->posts; foreach ( $request_ids as $request_id ) { wp_update_post( array( 'ID' => $request_id, 'post_status' => 'request-failed', 'post_password' => '', ) ); } } /** * Generate a single group for the personal data export report. * * @since 4.9.6 * @since 5.4.0 Added the `$group_id` and `$groups_count` parameters. * * @param array $group_data { * The group data to render. * * @type string $group_label The user-facing heading for the group, e.g. 'Comments'. * @type array $items { * An array of group items. * * @type array $group_item_data { * An array of name-value pairs for the item. * * @type string $name The user-facing name of an item name-value pair, e.g. 'IP Address'. * @type string $value The user-facing value of an item data pair, e.g. '50.60.70.0'. * } * } * } * @param string $group_id The group identifier. * @param int $groups_count The number of all groups * @return string The HTML for this group and its items. */ function wp_privacy_generate_personal_data_export_group_html( $group_data, $group_id = '', $groups_count = 1 ) { $group_id_attr = sanitize_title_with_dashes( $group_data['group_label'] . '-' . $group_id ); $group_html = '

    '; $group_html .= esc_html( $group_data['group_label'] ); $items_count = count( (array) $group_data['items'] ); if ( $items_count > 1 ) { $group_html .= sprintf( ' (%d)', $items_count ); } $group_html .= '

    '; if ( ! empty( $group_data['group_description'] ) ) { $group_html .= '

    ' . esc_html( $group_data['group_description'] ) . '

    '; } $group_html .= '
    '; foreach ( (array) $group_data['items'] as $group_item_id => $group_item_data ) { $group_html .= ''; $group_html .= ''; foreach ( (array) $group_item_data as $group_item_datum ) { $value = $group_item_datum['value']; // If it looks like a link, make it a link. if ( ! str_contains( $value, ' ' ) && ( str_starts_with( $value, 'http://' ) || str_starts_with( $value, 'https://' ) ) ) { $value = '' . esc_html( $value ) . ''; } $group_html .= ''; $group_html .= ''; $group_html .= ''; $group_html .= ''; } $group_html .= ''; $group_html .= '
    ' . esc_html( $group_item_datum['name'] ) . '' . wp_kses( $value, 'personal_data_export' ) . '
    '; } if ( $groups_count > 1 ) { $group_html .= '
    '; $group_html .= ' ' . esc_html__( 'Go to top' ) . ''; $group_html .= '
    '; } $group_html .= '
    '; return $group_html; } /** * Generate the personal data export file. * * @since 4.9.6 * * @param int $request_id The export request ID. */ function wp_privacy_generate_personal_data_export_file( $request_id ) { if ( ! class_exists( 'ZipArchive' ) ) { wp_send_json_error( __( 'Unable to generate personal data export file. ZipArchive not available.' ) ); } // Get the request. $request = wp_get_user_request( $request_id ); if ( ! $request || 'export_personal_data' !== $request->action_name ) { wp_send_json_error( __( 'Invalid request ID when generating personal data export file.' ) ); } $email_address = $request->email; if ( ! is_email( $email_address ) ) { wp_send_json_error( __( 'Invalid email address when generating personal data export file.' ) ); } // Create the exports folder if needed. $exports_dir = wp_privacy_exports_dir(); $exports_url = wp_privacy_exports_url(); if ( ! wp_mkdir_p( $exports_dir ) ) { wp_send_json_error( __( 'Unable to create personal data export folder.' ) ); } // Protect export folder from browsing. $index_pathname = $exports_dir . 'index.php'; if ( ! file_exists( $index_pathname ) ) { $file = fopen( $index_pathname, 'w' ); if ( false === $file ) { wp_send_json_error( __( 'Unable to protect personal data export folder from browsing.' ) ); } fwrite( $file, " _x( 'About', 'personal data group label' ), /* translators: Description for the About section in a personal data export. */ 'group_description' => _x( 'Overview of export report.', 'personal data group description' ), 'items' => array( 'about-1' => array( array( 'name' => _x( 'Report generated for', 'email address' ), 'value' => $email_address, ), array( 'name' => _x( 'For site', 'website name' ), 'value' => get_bloginfo( 'name' ), ), array( 'name' => _x( 'At URL', 'website URL' ), 'value' => get_bloginfo( 'url' ), ), array( 'name' => _x( 'On', 'date/time' ), 'value' => current_time( 'mysql' ), ), ), ), ); // And now, all the Groups. $groups = get_post_meta( $request_id, '_export_data_grouped', true ); if ( is_array( $groups ) ) { // Merge in the special "About" group. $groups = array_merge( array( 'about' => $about_group ), $groups ); $groups_count = count( $groups ); } else { if ( false !== $groups ) { _doing_it_wrong( __FUNCTION__, /* translators: %s: Post meta key. */ sprintf( __( 'The %s post meta must be an array.' ), '_export_data_grouped' ), '5.8.0' ); } $groups = null; $groups_count = 0; } // Convert the groups to JSON format. $groups_json = wp_json_encode( $groups ); if ( false === $groups_json ) { $error_message = sprintf( /* translators: %s: Error message. */ __( 'Unable to encode the personal data for export. Error: %s' ), json_last_error_msg() ); wp_send_json_error( $error_message ); } /* * Handle the JSON export. */ $file = fopen( $json_report_pathname, 'w' ); if ( false === $file ) { wp_send_json_error( __( 'Unable to open personal data export file (JSON report) for writing.' ) ); } fwrite( $file, '{' ); fwrite( $file, '"' . $title . '":' ); fwrite( $file, $groups_json ); fwrite( $file, '}' ); fclose( $file ); /* * Handle the HTML export. */ $file = fopen( $html_report_pathname, 'w' ); if ( false === $file ) { wp_send_json_error( __( 'Unable to open personal data export (HTML report) for writing.' ) ); } fwrite( $file, "\n" ); fwrite( $file, "\n" ); fwrite( $file, "\n" ); fwrite( $file, "\n" ); fwrite( $file, "' ); fwrite( $file, '' ); fwrite( $file, esc_html( $title ) ); fwrite( $file, '' ); fwrite( $file, "\n" ); fwrite( $file, "\n" ); fwrite( $file, '

    ' . esc_html__( 'Personal Data Export' ) . '

    ' ); // Create TOC. if ( $groups_count > 1 ) { fwrite( $file, '
    ' ); fwrite( $file, '

    ' . esc_html__( 'Table of Contents' ) . '

    ' ); fwrite( $file, '
      ' ); foreach ( (array) $groups as $group_id => $group_data ) { $group_label = esc_html( $group_data['group_label'] ); $group_id_attr = sanitize_title_with_dashes( $group_data['group_label'] . '-' . $group_id ); $group_items_count = count( (array) $group_data['items'] ); if ( $group_items_count > 1 ) { $group_label .= sprintf( ' (%d)', $group_items_count ); } fwrite( $file, '
    • ' ); fwrite( $file, '' . $group_label . '' ); fwrite( $file, '
    • ' ); } fwrite( $file, '
    ' ); fwrite( $file, '
    ' ); } // Now, iterate over every group in $groups and have the formatter render it in HTML. foreach ( (array) $groups as $group_id => $group_data ) { fwrite( $file, wp_privacy_generate_personal_data_export_group_html( $group_data, $group_id, $groups_count ) ); } fwrite( $file, "\n" ); fwrite( $file, "\n" ); fclose( $file ); /* * Now, generate the ZIP. * * If an archive has already been generated, then remove it and reuse the filename, * to avoid breaking any URLs that may have been previously sent via email. */ $error = false; // This meta value is used from version 5.5. $archive_filename = get_post_meta( $request_id, '_export_file_name', true ); // This one stored an absolute path and is used for backward compatibility. $archive_pathname = get_post_meta( $request_id, '_export_file_path', true ); // If a filename meta exists, use it. if ( ! empty( $archive_filename ) ) { $archive_pathname = $exports_dir . $archive_filename; } elseif ( ! empty( $archive_pathname ) ) { // If a full path meta exists, use it and create the new meta value. $archive_filename = basename( $archive_pathname ); update_post_meta( $request_id, '_export_file_name', $archive_filename ); // Remove the back-compat meta values. delete_post_meta( $request_id, '_export_file_url' ); delete_post_meta( $request_id, '_export_file_path' ); } else { // If there's no filename or full path stored, create a new file. $archive_filename = $file_basename . '.zip'; $archive_pathname = $exports_dir . $archive_filename; update_post_meta( $request_id, '_export_file_name', $archive_filename ); } $archive_url = $exports_url . $archive_filename; if ( ! empty( $archive_pathname ) && file_exists( $archive_pathname ) ) { wp_delete_file( $archive_pathname ); } $zip = new ZipArchive(); if ( true === $zip->open( $archive_pathname, ZipArchive::CREATE ) ) { if ( ! $zip->addFile( $json_report_pathname, 'export.json' ) ) { $error = __( 'Unable to archive the personal data export file (JSON format).' ); } if ( ! $zip->addFile( $html_report_pathname, 'index.html' ) ) { $error = __( 'Unable to archive the personal data export file (HTML format).' ); } $zip->close(); if ( ! $error ) { /** * Fires right after all personal data has been written to the export file. * * @since 4.9.6 * @since 5.4.0 Added the `$json_report_pathname` parameter. * * @param string $archive_pathname The full path to the export file on the filesystem. * @param string $archive_url The URL of the archive file. * @param string $html_report_pathname The full path to the HTML personal data report on the filesystem. * @param int $request_id The export request ID. * @param string $json_report_pathname The full path to the JSON personal data report on the filesystem. */ do_action( 'wp_privacy_personal_data_export_file_created', $archive_pathname, $archive_url, $html_report_pathname, $request_id, $json_report_pathname ); } } else { $error = __( 'Unable to open personal data export file (archive) for writing.' ); } // Remove the JSON file. unlink( $json_report_pathname ); // Remove the HTML file. unlink( $html_report_pathname ); if ( $error ) { wp_send_json_error( $error ); } } /** * Send an email to the user with a link to the personal data export file * * @since 4.9.6 * * @param int $request_id The request ID for this personal data export. * @return true|WP_Error True on success or `WP_Error` on failure. */ function wp_privacy_send_personal_data_export_email( $request_id ) { // Get the request. $request = wp_get_user_request( $request_id ); if ( ! $request || 'export_personal_data' !== $request->action_name ) { return new WP_Error( 'invalid_request', __( 'Invalid request ID when sending personal data export email.' ) ); } // Localize message content for user; fallback to site default for visitors. if ( ! empty( $request->user_id ) ) { $switched_locale = switch_to_user_locale( $request->user_id ); } else { $switched_locale = switch_to_locale( get_locale() ); } /** This filter is documented in wp-includes/functions.php */ $expiration = apply_filters( 'wp_privacy_export_expiration', 3 * DAY_IN_SECONDS ); $expiration_date = date_i18n( get_option( 'date_format' ), time() + $expiration ); $exports_url = wp_privacy_exports_url(); $export_file_name = get_post_meta( $request_id, '_export_file_name', true ); $export_file_url = $exports_url . $export_file_name; $site_name = wp_specialchars_decode( get_option( 'blogname' ), ENT_QUOTES ); $site_url = home_url(); /** * Filters the recipient of the personal data export email notification. * Should be used with great caution to avoid sending the data export link to wrong emails. * * @since 5.3.0 * * @param string $request_email The email address of the notification recipient. * @param WP_User_Request $request The request that is initiating the notification. */ $request_email = apply_filters( 'wp_privacy_personal_data_email_to', $request->email, $request ); $email_data = array( 'request' => $request, 'expiration' => $expiration, 'expiration_date' => $expiration_date, 'message_recipient' => $request_email, 'export_file_url' => $export_file_url, 'sitename' => $site_name, 'siteurl' => $site_url, ); /* translators: Personal data export notification email subject. %s: Site title. */ $subject = sprintf( __( '[%s] Personal Data Export' ), $site_name ); /** * Filters the subject of the email sent when an export request is completed. * * @since 5.3.0 * * @param string $subject The email subject. * @param string $sitename The name of the site. * @param array $email_data { * Data relating to the account action email. * * @type WP_User_Request $request User request object. * @type int $expiration The time in seconds until the export file expires. * @type string $expiration_date The localized date and time when the export file expires. * @type string $message_recipient The address that the email will be sent to. Defaults * to the value of `$request->email`, but can be changed * by the `wp_privacy_personal_data_email_to` filter. * @type string $export_file_url The export file URL. * @type string $sitename The site name sending the mail. * @type string $siteurl The site URL sending the mail. * } */ $subject = apply_filters( 'wp_privacy_personal_data_email_subject', $subject, $site_name, $email_data ); /* translators: Do not translate EXPIRATION, LINK, SITENAME, SITEURL: those are placeholders. */ $email_text = __( 'Howdy, Your request for an export of personal data has been completed. You may download your personal data by clicking on the link below. For privacy and security, we will automatically delete the file on ###EXPIRATION###, so please download it before then. ###LINK### Regards, All at ###SITENAME### ###SITEURL###' ); /** * Filters the text of the email sent with a personal data export file. * * The following strings have a special meaning and will get replaced dynamically: * ###EXPIRATION### The date when the URL will be automatically deleted. * ###LINK### URL of the personal data export file for the user. * ###SITENAME### The name of the site. * ###SITEURL### The URL to the site. * * @since 4.9.6 * @since 5.3.0 Introduced the `$email_data` array. * * @param string $email_text Text in the email. * @param int $request_id The request ID for this personal data export. * @param array $email_data { * Data relating to the account action email. * * @type WP_User_Request $request User request object. * @type int $expiration The time in seconds until the export file expires. * @type string $expiration_date The localized date and time when the export file expires. * @type string $message_recipient The address that the email will be sent to. Defaults * to the value of `$request->email`, but can be changed * by the `wp_privacy_personal_data_email_to` filter. * @type string $export_file_url The export file URL. * @type string $sitename The site name sending the mail. * @type string $siteurl The site URL sending the mail. */ $content = apply_filters( 'wp_privacy_personal_data_email_content', $email_text, $request_id, $email_data ); $content = str_replace( '###EXPIRATION###', $expiration_date, $content ); $content = str_replace( '###LINK###', sanitize_url( $export_file_url ), $content ); $content = str_replace( '###EMAIL###', $request_email, $content ); $content = str_replace( '###SITENAME###', $site_name, $content ); $content = str_replace( '###SITEURL###', sanitize_url( $site_url ), $content ); $headers = ''; /** * Filters the headers of the email sent with a personal data export file. * * @since 5.4.0 * * @param string|array $headers The email headers. * @param string $subject The email subject. * @param string $content The email content. * @param int $request_id The request ID. * @param array $email_data { * Data relating to the account action email. * * @type WP_User_Request $request User request object. * @type int $expiration The time in seconds until the export file expires. * @type string $expiration_date The localized date and time when the export file expires. * @type string $message_recipient The address that the email will be sent to. Defaults * to the value of `$request->email`, but can be changed * by the `wp_privacy_personal_data_email_to` filter. * @type string $export_file_url The export file URL. * @type string $sitename The site name sending the mail. * @type string $siteurl The site URL sending the mail. * } */ $headers = apply_filters( 'wp_privacy_personal_data_email_headers', $headers, $subject, $content, $request_id, $email_data ); $mail_success = wp_mail( $request_email, $subject, $content, $headers ); if ( $switched_locale ) { restore_previous_locale(); } if ( ! $mail_success ) { return new WP_Error( 'privacy_email_error', __( 'Unable to send personal data export email.' ) ); } return true; } /** * Intercept personal data exporter page Ajax responses in order to assemble the personal data export file. * * @since 4.9.6 * * @see 'wp_privacy_personal_data_export_page' * * @param array $response The response from the personal data exporter for the given page. * @param int $exporter_index The index of the personal data exporter. Begins at 1. * @param string $email_address The email address of the user whose personal data this is. * @param int $page The page of personal data for this exporter. Begins at 1. * @param int $request_id The request ID for this personal data export. * @param bool $send_as_email Whether the final results of the export should be emailed to the user. * @param string $exporter_key The slug (key) of the exporter. * @return array The filtered response. */ function wp_privacy_process_personal_data_export_page( $response, $exporter_index, $email_address, $page, $request_id, $send_as_email, $exporter_key ) { /* Do some simple checks on the shape of the response from the exporter. * If the exporter response is malformed, don't attempt to consume it - let it * pass through to generate a warning to the user by default Ajax processing. */ if ( ! is_array( $response ) ) { return $response; } if ( ! array_key_exists( 'done', $response ) ) { return $response; } if ( ! array_key_exists( 'data', $response ) ) { return $response; } if ( ! is_array( $response['data'] ) ) { return $response; } // Get the request. $request = wp_get_user_request( $request_id ); if ( ! $request || 'export_personal_data' !== $request->action_name ) { wp_send_json_error( __( 'Invalid request ID when merging personal data to export.' ) ); } $export_data = array(); // First exporter, first page? Reset the report data accumulation array. if ( 1 === $exporter_index && 1 === $page ) { update_post_meta( $request_id, '_export_data_raw', $export_data ); } else { $accumulated_data = get_post_meta( $request_id, '_export_data_raw', true ); if ( $accumulated_data ) { $export_data = $accumulated_data; } } // Now, merge the data from the exporter response into the data we have accumulated already. $export_data = array_merge( $export_data, $response['data'] ); update_post_meta( $request_id, '_export_data_raw', $export_data ); // If we are not yet on the last page of the last exporter, return now. /** This filter is documented in wp-admin/includes/ajax-actions.php */ $exporters = apply_filters( 'wp_privacy_personal_data_exporters', array() ); $is_last_exporter = count( $exporters ) === $exporter_index; $exporter_done = $response['done']; if ( ! $is_last_exporter || ! $exporter_done ) { return $response; } // Last exporter, last page - let's prepare the export file. // First we need to re-organize the raw data hierarchically in groups and items. $groups = array(); foreach ( (array) $export_data as $export_datum ) { $group_id = $export_datum['group_id']; $group_label = $export_datum['group_label']; $group_description = ''; if ( ! empty( $export_datum['group_description'] ) ) { $group_description = $export_datum['group_description']; } if ( ! array_key_exists( $group_id, $groups ) ) { $groups[ $group_id ] = array( 'group_label' => $group_label, 'group_description' => $group_description, 'items' => array(), ); } $item_id = $export_datum['item_id']; if ( ! array_key_exists( $item_id, $groups[ $group_id ]['items'] ) ) { $groups[ $group_id ]['items'][ $item_id ] = array(); } $old_item_data = $groups[ $group_id ]['items'][ $item_id ]; $merged_item_data = array_merge( $export_datum['data'], $old_item_data ); $groups[ $group_id ]['items'][ $item_id ] = $merged_item_data; } // Then save the grouped data into the request. delete_post_meta( $request_id, '_export_data_raw' ); update_post_meta( $request_id, '_export_data_grouped', $groups ); /** * Generate the export file from the collected, grouped personal data. * * @since 4.9.6 * * @param int $request_id The export request ID. */ do_action( 'wp_privacy_personal_data_export_file', $request_id ); // Clear the grouped data now that it is no longer needed. delete_post_meta( $request_id, '_export_data_grouped' ); // If the destination is email, send it now. if ( $send_as_email ) { $mail_success = wp_privacy_send_personal_data_export_email( $request_id ); if ( is_wp_error( $mail_success ) ) { wp_send_json_error( $mail_success->get_error_message() ); } // Update the request to completed state when the export email is sent. _wp_privacy_completed_request( $request_id ); } else { // Modify the response to include the URL of the export file so the browser can fetch it. $exports_url = wp_privacy_exports_url(); $export_file_name = get_post_meta( $request_id, '_export_file_name', true ); $export_file_url = $exports_url . $export_file_name; if ( ! empty( $export_file_url ) ) { $response['url'] = $export_file_url; } } return $response; } /** * Mark erasure requests as completed after processing is finished. * * This intercepts the Ajax responses to personal data eraser page requests, and * monitors the status of a request. Once all of the processing has finished, the * request is marked as completed. * * @since 4.9.6 * * @see 'wp_privacy_personal_data_erasure_page' * * @param array $response The response from the personal data eraser for * the given page. * @param int $eraser_index The index of the personal data eraser. Begins * at 1. * @param string $email_address The email address of the user whose personal * data this is. * @param int $page The page of personal data for this eraser. * Begins at 1. * @param int $request_id The request ID for this personal data erasure. * @return array The filtered response. */ function wp_privacy_process_personal_data_erasure_page( $response, $eraser_index, $email_address, $page, $request_id ) { /* * If the eraser response is malformed, don't attempt to consume it; let it * pass through, so that the default Ajax processing will generate a warning * to the user. */ if ( ! is_array( $response ) ) { return $response; } if ( ! array_key_exists( 'done', $response ) ) { return $response; } if ( ! array_key_exists( 'items_removed', $response ) ) { return $response; } if ( ! array_key_exists( 'items_retained', $response ) ) { return $response; } if ( ! array_key_exists( 'messages', $response ) ) { return $response; } // Get the request. $request = wp_get_user_request( $request_id ); if ( ! $request || 'remove_personal_data' !== $request->action_name ) { wp_send_json_error( __( 'Invalid request ID when processing personal data to erase.' ) ); } /** This filter is documented in wp-admin/includes/ajax-actions.php */ $erasers = apply_filters( 'wp_privacy_personal_data_erasers', array() ); $is_last_eraser = count( $erasers ) === $eraser_index; $eraser_done = $response['done']; if ( ! $is_last_eraser || ! $eraser_done ) { return $response; } _wp_privacy_completed_request( $request_id ); /** * Fires immediately after a personal data erasure request has been marked completed. * * @since 4.9.6 * * @param int $request_id The privacy request post ID associated with this request. */ do_action( 'wp_privacy_personal_data_erased', $request_id ); return $response; } nav-menu.php000064400000137411147206365750007031 0ustar00 $object_id, 'post_title' => get_the_title( $object_id ), 'post_type' => get_post_type( $object_id ), ) ); echo "\n"; } } } elseif ( taxonomy_exists( $object_type ) ) { if ( isset( $request['ID'] ) ) { $object_id = (int) $request['ID']; if ( 'markup' === $response_format ) { echo walk_nav_menu_tree( array_map( 'wp_setup_nav_menu_item', array( get_term( $object_id, $object_type ) ) ), 0, (object) $args ); } elseif ( 'json' === $response_format ) { $post_obj = get_term( $object_id, $object_type ); echo wp_json_encode( array( 'ID' => $object_id, 'post_title' => $post_obj->name, 'post_type' => $object_type, ) ); echo "\n"; } } } } elseif ( preg_match( '/quick-search-(posttype|taxonomy)-([a-zA-Z_-]*\b)/', $type, $matches ) ) { if ( 'posttype' === $matches[1] && get_post_type_object( $matches[2] ) ) { $post_type_obj = _wp_nav_menu_meta_box_object( get_post_type_object( $matches[2] ) ); $args = array_merge( $args, array( 'no_found_rows' => true, 'update_post_meta_cache' => false, 'update_post_term_cache' => false, 'posts_per_page' => 10, 'post_type' => $matches[2], 's' => $query, ) ); if ( isset( $post_type_obj->_default_query ) ) { $args = array_merge( $args, (array) $post_type_obj->_default_query ); } $search_results_query = new WP_Query( $args ); if ( ! $search_results_query->have_posts() ) { return; } while ( $search_results_query->have_posts() ) { $post = $search_results_query->next_post(); if ( 'markup' === $response_format ) { $var_by_ref = $post->ID; echo walk_nav_menu_tree( array_map( 'wp_setup_nav_menu_item', array( get_post( $var_by_ref ) ) ), 0, (object) $args ); } elseif ( 'json' === $response_format ) { echo wp_json_encode( array( 'ID' => $post->ID, 'post_title' => get_the_title( $post->ID ), 'post_type' => $matches[2], ) ); echo "\n"; } } } elseif ( 'taxonomy' === $matches[1] ) { $terms = get_terms( array( 'taxonomy' => $matches[2], 'name__like' => $query, 'number' => 10, 'hide_empty' => false, ) ); if ( empty( $terms ) || is_wp_error( $terms ) ) { return; } foreach ( (array) $terms as $term ) { if ( 'markup' === $response_format ) { echo walk_nav_menu_tree( array_map( 'wp_setup_nav_menu_item', array( $term ) ), 0, (object) $args ); } elseif ( 'json' === $response_format ) { echo wp_json_encode( array( 'ID' => $term->term_id, 'post_title' => $term->name, 'post_type' => $matches[2], ) ); echo "\n"; } } } } } /** * Register nav menu meta boxes and advanced menu items. * * @since 3.0.0 */ function wp_nav_menu_setup() { // Register meta boxes. wp_nav_menu_post_type_meta_boxes(); add_meta_box( 'add-custom-links', __( 'Custom Links' ), 'wp_nav_menu_item_link_meta_box', 'nav-menus', 'side', 'default' ); wp_nav_menu_taxonomy_meta_boxes(); // Register advanced menu items (columns). add_filter( 'manage_nav-menus_columns', 'wp_nav_menu_manage_columns' ); // If first time editing, disable advanced items by default. if ( false === get_user_option( 'managenav-menuscolumnshidden' ) ) { $user = wp_get_current_user(); update_user_meta( $user->ID, 'managenav-menuscolumnshidden', array( 0 => 'link-target', 1 => 'css-classes', 2 => 'xfn', 3 => 'description', 4 => 'title-attribute', ) ); } } /** * Limit the amount of meta boxes to pages, posts, links, and categories for first time users. * * @since 3.0.0 * * @global array $wp_meta_boxes Global meta box state. */ function wp_initial_nav_menu_meta_boxes() { global $wp_meta_boxes; if ( get_user_option( 'metaboxhidden_nav-menus' ) !== false || ! is_array( $wp_meta_boxes ) ) { return; } $initial_meta_boxes = array( 'add-post-type-page', 'add-post-type-post', 'add-custom-links', 'add-category' ); $hidden_meta_boxes = array(); foreach ( array_keys( $wp_meta_boxes['nav-menus'] ) as $context ) { foreach ( array_keys( $wp_meta_boxes['nav-menus'][ $context ] ) as $priority ) { foreach ( $wp_meta_boxes['nav-menus'][ $context ][ $priority ] as $box ) { if ( in_array( $box['id'], $initial_meta_boxes, true ) ) { unset( $box['id'] ); } else { $hidden_meta_boxes[] = $box['id']; } } } } $user = wp_get_current_user(); update_user_meta( $user->ID, 'metaboxhidden_nav-menus', $hidden_meta_boxes ); } /** * Creates meta boxes for any post type menu item.. * * @since 3.0.0 */ function wp_nav_menu_post_type_meta_boxes() { $post_types = get_post_types( array( 'show_in_nav_menus' => true ), 'object' ); if ( ! $post_types ) { return; } foreach ( $post_types as $post_type ) { /** * Filters whether a menu items meta box will be added for the current * object type. * * If a falsey value is returned instead of an object, the menu items * meta box for the current meta box object will not be added. * * @since 3.0.0 * * @param WP_Post_Type|false $post_type The current object to add a menu items * meta box for. */ $post_type = apply_filters( 'nav_menu_meta_box_object', $post_type ); if ( $post_type ) { $id = $post_type->name; // Give pages a higher priority. $priority = ( 'page' === $post_type->name ? 'core' : 'default' ); add_meta_box( "add-post-type-{$id}", $post_type->labels->name, 'wp_nav_menu_item_post_type_meta_box', 'nav-menus', 'side', $priority, $post_type ); } } } /** * Creates meta boxes for any taxonomy menu item. * * @since 3.0.0 */ function wp_nav_menu_taxonomy_meta_boxes() { $taxonomies = get_taxonomies( array( 'show_in_nav_menus' => true ), 'object' ); if ( ! $taxonomies ) { return; } foreach ( $taxonomies as $tax ) { /** This filter is documented in wp-admin/includes/nav-menu.php */ $tax = apply_filters( 'nav_menu_meta_box_object', $tax ); if ( $tax ) { $id = $tax->name; add_meta_box( "add-{$id}", $tax->labels->name, 'wp_nav_menu_item_taxonomy_meta_box', 'nav-menus', 'side', 'default', $tax ); } } } /** * Check whether to disable the Menu Locations meta box submit button and inputs. * * @since 3.6.0 * @since 5.3.1 The `$display` parameter was added. * * @global bool $one_theme_location_no_menus to determine if no menus exist * * @param int|string $nav_menu_selected_id ID, name, or slug of the currently selected menu. * @param bool $display Whether to display or just return the string. * @return string|false Disabled attribute if at least one menu exists, false if not. */ function wp_nav_menu_disabled_check( $nav_menu_selected_id, $display = true ) { global $one_theme_location_no_menus; if ( $one_theme_location_no_menus ) { return false; } return disabled( $nav_menu_selected_id, 0, $display ); } /** * Displays a meta box for the custom links menu item. * * @since 3.0.0 * * @global int $_nav_menu_placeholder * @global int|string $nav_menu_selected_id */ function wp_nav_menu_item_link_meta_box() { global $_nav_menu_placeholder, $nav_menu_selected_id; $_nav_menu_placeholder = 0 > $_nav_menu_placeholder ? $_nav_menu_placeholder - 1 : -1; ?>

    class="button submit-add-to-menu right" value="" />

    name; $post_type = get_post_type_object( $post_type_name ); $tab_name = $post_type_name . '-tab'; // Paginate browsing for large numbers of post objects. $per_page = 50; $pagenum = isset( $_REQUEST[ $tab_name ] ) && isset( $_REQUEST['paged'] ) ? absint( $_REQUEST['paged'] ) : 1; $offset = 0 < $pagenum ? $per_page * ( $pagenum - 1 ) : 0; $args = array( 'offset' => $offset, 'order' => 'ASC', 'orderby' => 'title', 'posts_per_page' => $per_page, 'post_type' => $post_type_name, 'suppress_filters' => true, 'update_post_term_cache' => false, 'update_post_meta_cache' => false, ); if ( isset( $box['args']->_default_query ) ) { $args = array_merge( $args, (array) $box['args']->_default_query ); } /* * If we're dealing with pages, let's prioritize the Front Page, * Posts Page and Privacy Policy Page at the top of the list. */ $important_pages = array(); if ( 'page' === $post_type_name ) { $suppress_page_ids = array(); // Insert Front Page or custom Home link. $front_page = 'page' === get_option( 'show_on_front' ) ? (int) get_option( 'page_on_front' ) : 0; $front_page_obj = null; if ( ! empty( $front_page ) ) { $front_page_obj = get_post( $front_page ); } if ( $front_page_obj ) { $front_page_obj->front_or_home = true; $important_pages[] = $front_page_obj; $suppress_page_ids[] = $front_page_obj->ID; } else { $_nav_menu_placeholder = ( 0 > $_nav_menu_placeholder ) ? (int) $_nav_menu_placeholder - 1 : -1; $front_page_obj = (object) array( 'front_or_home' => true, 'ID' => 0, 'object_id' => $_nav_menu_placeholder, 'post_content' => '', 'post_excerpt' => '', 'post_parent' => '', 'post_title' => _x( 'Home', 'nav menu home label' ), 'post_type' => 'nav_menu_item', 'type' => 'custom', 'url' => home_url( '/' ), ); $important_pages[] = $front_page_obj; } // Insert Posts Page. $posts_page = 'page' === get_option( 'show_on_front' ) ? (int) get_option( 'page_for_posts' ) : 0; if ( ! empty( $posts_page ) ) { $posts_page_obj = get_post( $posts_page ); if ( $posts_page_obj ) { $front_page_obj->posts_page = true; $important_pages[] = $posts_page_obj; $suppress_page_ids[] = $posts_page_obj->ID; } } // Insert Privacy Policy Page. $privacy_policy_page_id = (int) get_option( 'wp_page_for_privacy_policy' ); if ( ! empty( $privacy_policy_page_id ) ) { $privacy_policy_page = get_post( $privacy_policy_page_id ); if ( $privacy_policy_page instanceof WP_Post && 'publish' === $privacy_policy_page->post_status ) { $privacy_policy_page->privacy_policy_page = true; $important_pages[] = $privacy_policy_page; $suppress_page_ids[] = $privacy_policy_page->ID; } } // Add suppression array to arguments for WP_Query. if ( ! empty( $suppress_page_ids ) ) { $args['post__not_in'] = $suppress_page_ids; } } // @todo Transient caching of these results with proper invalidation on updating of a post of this type. $get_posts = new WP_Query(); $posts = $get_posts->query( $args ); // Only suppress and insert when more than just suppression pages available. if ( ! $get_posts->post_count ) { if ( ! empty( $suppress_page_ids ) ) { unset( $args['post__not_in'] ); $get_posts = new WP_Query(); $posts = $get_posts->query( $args ); } else { echo '

    ' . __( 'No items.' ) . '

    '; return; } } elseif ( ! empty( $important_pages ) ) { $posts = array_merge( $important_pages, $posts ); } $num_pages = $get_posts->max_num_pages; $page_links = paginate_links( array( 'base' => add_query_arg( array( $tab_name => 'all', 'paged' => '%#%', 'item-type' => 'post_type', 'item-object' => $post_type_name, ) ), 'format' => '', 'prev_text' => '' . __( '«' ) . '', 'next_text' => '' . __( '»' ) . '', /* translators: Hidden accessibility text. */ 'before_page_number' => '' . __( 'Page' ) . ' ', 'total' => $num_pages, 'current' => $pagenum, ) ); $db_fields = false; if ( is_post_type_hierarchical( $post_type_name ) ) { $db_fields = array( 'parent' => 'post_parent', 'id' => 'ID', ); } $walker = new Walker_Nav_Menu_Checklist( $db_fields ); $current_tab = 'most-recent'; if ( isset( $_REQUEST[ $tab_name ] ) && in_array( $_REQUEST[ $tab_name ], array( 'all', 'search' ), true ) ) { $current_tab = $_REQUEST[ $tab_name ]; } if ( ! empty( $_REQUEST[ "quick-search-posttype-{$post_type_name}" ] ) ) { $current_tab = 'search'; } $removed_args = array( 'action', 'customlink-tab', 'edit-menu-item', 'menu-item', 'page-tab', '_wpnonce', ); $most_recent_url = ''; $view_all_url = ''; $search_url = ''; if ( $nav_menu_selected_id ) { $most_recent_url = add_query_arg( $tab_name, 'most-recent', remove_query_arg( $removed_args ) ); $view_all_url = add_query_arg( $tab_name, 'all', remove_query_arg( $removed_args ) ); $search_url = add_query_arg( $tab_name, 'search', remove_query_arg( $removed_args ) ); } ?>
    " class="posttypediv">
    " class="tabs-panel " role="region" aria-label="" tabindex="0" >
      " class="categorychecklist form-no-clear" > 'post_date', 'order' => 'DESC', 'posts_per_page' => 15, ) ); $most_recent = $get_posts->query( $recent_args ); $args['walker'] = $walker; /** * Filters the posts displayed in the 'Most Recent' tab of the current * post type's menu items meta box. * * The dynamic portion of the hook name, `$post_type_name`, refers to the post type name. * * Possible hook names include: * * - `nav_menu_items_post_recent` * - `nav_menu_items_page_recent` * * @since 4.3.0 * @since 4.9.0 Added the `$recent_args` parameter. * * @param WP_Post[] $most_recent An array of post objects being listed. * @param array $args An array of `WP_Query` arguments for the meta box. * @param array $box Arguments passed to `wp_nav_menu_item_post_type_meta_box()`. * @param array $recent_args An array of `WP_Query` arguments for 'Most Recent' tab. */ $most_recent = apply_filters( "nav_menu_items_{$post_type_name}_recent", $most_recent, $args, $box, $recent_args ); echo walk_nav_menu_tree( array_map( 'wp_setup_nav_menu_item', $most_recent ), 0, (object) $args ); ?>
    " class="tabs-panel " role="region" aria-label="labels->search_items ); ?>" tabindex="0" > $searched, 'post_type' => $post_type_name, 'fields' => 'all', 'order' => 'DESC', ) ); } else { $searched = ''; $search_results = array(); } ?>

    class="quick-search" value="" name="" id="" /> "submit-quick-search-posttype-{$post_type_name}" ) ); ?>

      " data-wp-lists="" class="categorychecklist form-no-clear" >
    • get_error_message(); ?>
    " class="tabs-panel tabs-panel-view-all " role="region" aria-label="labels->all_items ); ?>" tabindex="0" >
      " data-wp-lists="" class="categorychecklist form-no-clear" > has_archive ) { $_nav_menu_placeholder = ( 0 > $_nav_menu_placeholder ) ? (int) $_nav_menu_placeholder - 1 : -1; array_unshift( $posts, (object) array( 'ID' => 0, 'object_id' => $_nav_menu_placeholder, 'object' => $post_type_name, 'post_content' => '', 'post_excerpt' => '', 'post_title' => $post_type->labels->archives, 'post_type' => 'nav_menu_item', 'type' => 'post_type_archive', 'url' => get_post_type_archive_link( $post_type_name ), ) ); } /** * Filters the posts displayed in the 'View All' tab of the current * post type's menu items meta box. * * The dynamic portion of the hook name, `$post_type_name`, refers * to the slug of the current post type. * * Possible hook names include: * * - `nav_menu_items_post` * - `nav_menu_items_page` * * @since 3.2.0 * @since 4.6.0 Converted the `$post_type` parameter to accept a WP_Post_Type object. * * @see WP_Query::query() * * @param object[] $posts The posts for the current post type. Mostly `WP_Post` objects, but * can also contain "fake" post objects to represent other menu items. * @param array $args An array of `WP_Query` arguments. * @param WP_Post_Type $post_type The current post type object for this menu item meta box. */ $posts = apply_filters( "nav_menu_items_{$post_type_name}", $posts, $args, $post_type ); $checkbox_items = walk_nav_menu_tree( array_map( 'wp_setup_nav_menu_item', $posts ), 0, (object) $args ); echo $checkbox_items; ?>

    "> id="" class="select-all" /> class="button submit-add-to-menu right" value="" name="add-post-type-menu-item" id="" />

    name; $taxonomy = get_taxonomy( $taxonomy_name ); $tab_name = $taxonomy_name . '-tab'; // Paginate browsing for large numbers of objects. $per_page = 50; $pagenum = isset( $_REQUEST[ $tab_name ] ) && isset( $_REQUEST['paged'] ) ? absint( $_REQUEST['paged'] ) : 1; $offset = 0 < $pagenum ? $per_page * ( $pagenum - 1 ) : 0; $args = array( 'taxonomy' => $taxonomy_name, 'child_of' => 0, 'exclude' => '', 'hide_empty' => false, 'hierarchical' => 1, 'include' => '', 'number' => $per_page, 'offset' => $offset, 'order' => 'ASC', 'orderby' => 'name', 'pad_counts' => false, ); $terms = get_terms( $args ); if ( ! $terms || is_wp_error( $terms ) ) { echo '

    ' . __( 'No items.' ) . '

    '; return; } $num_pages = (int) ceil( wp_count_terms( array_merge( $args, array( 'number' => '', 'offset' => '', ) ) ) / $per_page ); $page_links = paginate_links( array( 'base' => add_query_arg( array( $tab_name => 'all', 'paged' => '%#%', 'item-type' => 'taxonomy', 'item-object' => $taxonomy_name, ) ), 'format' => '', 'prev_text' => '' . __( '«' ) . '', 'next_text' => '' . __( '»' ) . '', /* translators: Hidden accessibility text. */ 'before_page_number' => '' . __( 'Page' ) . ' ', 'total' => $num_pages, 'current' => $pagenum, ) ); $db_fields = false; if ( is_taxonomy_hierarchical( $taxonomy_name ) ) { $db_fields = array( 'parent' => 'parent', 'id' => 'term_id', ); } $walker = new Walker_Nav_Menu_Checklist( $db_fields ); $current_tab = 'most-used'; if ( isset( $_REQUEST[ $tab_name ] ) && in_array( $_REQUEST[ $tab_name ], array( 'all', 'most-used', 'search' ), true ) ) { $current_tab = $_REQUEST[ $tab_name ]; } if ( ! empty( $_REQUEST[ "quick-search-taxonomy-{$taxonomy_name}" ] ) ) { $current_tab = 'search'; } $removed_args = array( 'action', 'customlink-tab', 'edit-menu-item', 'menu-item', 'page-tab', '_wpnonce', ); $most_used_url = ''; $view_all_url = ''; $search_url = ''; if ( $nav_menu_selected_id ) { $most_used_url = add_query_arg( $tab_name, 'most-used', remove_query_arg( $removed_args ) ); $view_all_url = add_query_arg( $tab_name, 'all', remove_query_arg( $removed_args ) ); $search_url = add_query_arg( $tab_name, 'search', remove_query_arg( $removed_args ) ); } ?>
    " class="taxonomydiv">
    " class="tabs-panel " role="region" aria-label="labels->most_used ); ?>" tabindex="0" >
      " class="categorychecklist form-no-clear" > $taxonomy_name, 'orderby' => 'count', 'order' => 'DESC', 'number' => 10, 'hierarchical' => false, ) ); $args['walker'] = $walker; echo walk_nav_menu_tree( array_map( 'wp_setup_nav_menu_item', $popular_terms ), 0, (object) $args ); ?>
    " class="tabs-panel tabs-panel-view-all " role="region" aria-label="labels->all_items ); ?>" tabindex="0" >
      " data-wp-lists="" class="categorychecklist form-no-clear" >
    " class="tabs-panel " role="region" aria-label="labels->search_items ); ?>" tabindex="0"> $taxonomy_name, 'name__like' => $searched, 'fields' => 'all', 'orderby' => 'count', 'order' => 'DESC', 'hierarchical' => false, ) ); } else { $searched = ''; $search_results = array(); } ?>

    " id="" /> "submit-quick-search-taxonomy-{$taxonomy_name}" ) ); ?>

      " data-wp-lists="" class="categorychecklist form-no-clear" >
    • get_error_message(); ?>

    "> id="" class="select-all" /> class="button submit-add-to-menu right" value="" name="add-taxonomy-menu-item" id="" />

    $_item_object_data ) { if ( // Checkbox is not checked. empty( $_item_object_data['menu-item-object-id'] ) && ( // And item type either isn't set. ! isset( $_item_object_data['menu-item-type'] ) || // Or URL is the default. in_array( $_item_object_data['menu-item-url'], array( 'https://', 'http://', '' ), true ) || // Or it's not a custom menu item (but not the custom home page). ! ( 'custom' === $_item_object_data['menu-item-type'] && ! isset( $_item_object_data['menu-item-db-id'] ) ) || // Or it *is* a custom menu item that already exists. ! empty( $_item_object_data['menu-item-db-id'] ) ) ) { // Then this potential menu item is not getting added to this menu. continue; } // If this possible menu item doesn't actually have a menu database ID yet. if ( empty( $_item_object_data['menu-item-db-id'] ) || ( 0 > $_possible_db_id ) || $_possible_db_id !== (int) $_item_object_data['menu-item-db-id'] ) { $_actual_db_id = 0; } else { $_actual_db_id = (int) $_item_object_data['menu-item-db-id']; } $args = array( 'menu-item-db-id' => ( isset( $_item_object_data['menu-item-db-id'] ) ? $_item_object_data['menu-item-db-id'] : '' ), 'menu-item-object-id' => ( isset( $_item_object_data['menu-item-object-id'] ) ? $_item_object_data['menu-item-object-id'] : '' ), 'menu-item-object' => ( isset( $_item_object_data['menu-item-object'] ) ? $_item_object_data['menu-item-object'] : '' ), 'menu-item-parent-id' => ( isset( $_item_object_data['menu-item-parent-id'] ) ? $_item_object_data['menu-item-parent-id'] : '' ), 'menu-item-position' => ( isset( $_item_object_data['menu-item-position'] ) ? $_item_object_data['menu-item-position'] : '' ), 'menu-item-type' => ( isset( $_item_object_data['menu-item-type'] ) ? $_item_object_data['menu-item-type'] : '' ), 'menu-item-title' => ( isset( $_item_object_data['menu-item-title'] ) ? $_item_object_data['menu-item-title'] : '' ), 'menu-item-url' => ( isset( $_item_object_data['menu-item-url'] ) ? $_item_object_data['menu-item-url'] : '' ), 'menu-item-description' => ( isset( $_item_object_data['menu-item-description'] ) ? $_item_object_data['menu-item-description'] : '' ), 'menu-item-attr-title' => ( isset( $_item_object_data['menu-item-attr-title'] ) ? $_item_object_data['menu-item-attr-title'] : '' ), 'menu-item-target' => ( isset( $_item_object_data['menu-item-target'] ) ? $_item_object_data['menu-item-target'] : '' ), 'menu-item-classes' => ( isset( $_item_object_data['menu-item-classes'] ) ? $_item_object_data['menu-item-classes'] : '' ), 'menu-item-xfn' => ( isset( $_item_object_data['menu-item-xfn'] ) ? $_item_object_data['menu-item-xfn'] : '' ), ); $items_saved[] = wp_update_nav_menu_item( $menu_id, $_actual_db_id, $args ); } } return $items_saved; } /** * Adds custom arguments to some of the meta box object types. * * @since 3.0.0 * * @access private * * @param object $data_object The post type or taxonomy meta-object. * @return object The post type or taxonomy object. */ function _wp_nav_menu_meta_box_object( $data_object = null ) { if ( isset( $data_object->name ) ) { if ( 'page' === $data_object->name ) { $data_object->_default_query = array( 'orderby' => 'menu_order title', 'post_status' => 'publish', ); // Posts should show only published items. } elseif ( 'post' === $data_object->name ) { $data_object->_default_query = array( 'post_status' => 'publish', ); // Categories should be in reverse chronological order. } elseif ( 'category' === $data_object->name ) { $data_object->_default_query = array( 'orderby' => 'id', 'order' => 'DESC', ); // Custom post types should show only published items. } else { $data_object->_default_query = array( 'post_status' => 'publish', ); } } return $data_object; } /** * Returns the menu formatted to edit. * * @since 3.0.0 * * @param int $menu_id Optional. The ID of the menu to format. Default 0. * @return string|WP_Error The menu formatted to edit or error object on failure. */ function wp_get_nav_menu_to_edit( $menu_id = 0 ) { $menu = wp_get_nav_menu_object( $menu_id ); // If the menu exists, get its items. if ( is_nav_menu( $menu ) ) { $menu_items = wp_get_nav_menu_items( $menu->term_id, array( 'post_status' => 'any' ) ); $result = '
    ' : '">'; $result .= '

    ' . __( 'Add menu items from the column on the left.' ) . '

    '; $result .= '
    '; if ( empty( $menu_items ) ) { return $result . ' '; } /** * Filters the Walker class used when adding nav menu items. * * @since 3.0.0 * * @param string $class The walker class to use. Default 'Walker_Nav_Menu_Edit'. * @param int $menu_id ID of the menu being rendered. */ $walker_class_name = apply_filters( 'wp_edit_nav_menu_walker', 'Walker_Nav_Menu_Edit', $menu_id ); if ( class_exists( $walker_class_name ) ) { $walker = new $walker_class_name(); } else { return new WP_Error( 'menu_walker_not_exist', sprintf( /* translators: %s: Walker class name. */ __( 'The Walker class named %s does not exist.' ), '' . $walker_class_name . '' ) ); } $some_pending_menu_items = false; $some_invalid_menu_items = false; foreach ( (array) $menu_items as $menu_item ) { if ( isset( $menu_item->post_status ) && 'draft' === $menu_item->post_status ) { $some_pending_menu_items = true; } if ( ! empty( $menu_item->_invalid ) ) { $some_invalid_menu_items = true; } } if ( $some_pending_menu_items ) { $message = __( 'Click Save Menu to make pending menu items public.' ); $notice_args = array( 'type' => 'info', 'additional_classes' => array( 'notice-alt', 'inline' ), ); $result .= wp_get_admin_notice( $message, $notice_args ); } if ( $some_invalid_menu_items ) { $message = __( 'There are some invalid menu items. Please check or delete them.' ); $notice_args = array( 'type' => 'error', 'additional_classes' => array( 'notice-alt', 'inline' ), ); $result .= wp_get_admin_notice( $message, $notice_args ); } $result .= ' '; return $result; } elseif ( is_wp_error( $menu ) ) { return $menu; } } /** * Returns the columns for the nav menus page. * * @since 3.0.0 * * @return string[] Array of column titles keyed by their column name. */ function wp_nav_menu_manage_columns() { return array( '_title' => __( 'Show advanced menu properties' ), 'cb' => '', 'link-target' => __( 'Link Target' ), 'title-attribute' => __( 'Title Attribute' ), 'css-classes' => __( 'CSS Classes' ), 'xfn' => __( 'Link Relationship (XFN)' ), 'description' => __( 'Description' ), ); } /** * Deletes orphaned draft menu items * * @access private * @since 3.0.0 * * @global wpdb $wpdb WordPress database abstraction object. */ function _wp_delete_orphaned_draft_menu_items() { global $wpdb; $delete_timestamp = time() - ( DAY_IN_SECONDS * EMPTY_TRASH_DAYS ); // Delete orphaned draft menu items. $menu_items_to_delete = $wpdb->get_col( $wpdb->prepare( "SELECT ID FROM $wpdb->posts AS p LEFT JOIN $wpdb->postmeta AS m ON p.ID = m.post_id WHERE post_type = 'nav_menu_item' AND post_status = 'draft' AND meta_key = '_menu_item_orphaned' AND meta_value < %d", $delete_timestamp ) ); foreach ( (array) $menu_items_to_delete as $menu_item_id ) { wp_delete_post( $menu_item_id, true ); } } /** * Saves nav menu items. * * @since 3.6.0 * * @param int|string $nav_menu_selected_id ID, slug, or name of the currently-selected menu. * @param string $nav_menu_selected_title Title of the currently-selected menu. * @return string[] The menu updated messages. */ function wp_nav_menu_update_menu_items( $nav_menu_selected_id, $nav_menu_selected_title ) { $unsorted_menu_items = wp_get_nav_menu_items( $nav_menu_selected_id, array( 'orderby' => 'ID', 'output' => ARRAY_A, 'output_key' => 'ID', 'post_status' => 'draft,publish', ) ); $messages = array(); $menu_items = array(); // Index menu items by DB ID. foreach ( $unsorted_menu_items as $_item ) { $menu_items[ $_item->db_id ] = $_item; } $post_fields = array( 'menu-item-db-id', 'menu-item-object-id', 'menu-item-object', 'menu-item-parent-id', 'menu-item-position', 'menu-item-type', 'menu-item-title', 'menu-item-url', 'menu-item-description', 'menu-item-attr-title', 'menu-item-target', 'menu-item-classes', 'menu-item-xfn', ); wp_defer_term_counting( true ); // Loop through all the menu items' POST variables. if ( ! empty( $_POST['menu-item-db-id'] ) ) { foreach ( (array) $_POST['menu-item-db-id'] as $_key => $k ) { // Menu item title can't be blank. if ( ! isset( $_POST['menu-item-title'][ $_key ] ) || '' === $_POST['menu-item-title'][ $_key ] ) { continue; } $args = array(); foreach ( $post_fields as $field ) { $args[ $field ] = isset( $_POST[ $field ][ $_key ] ) ? $_POST[ $field ][ $_key ] : ''; } $menu_item_db_id = wp_update_nav_menu_item( $nav_menu_selected_id, ( (int) $_POST['menu-item-db-id'][ $_key ] !== $_key ? 0 : $_key ), $args ); if ( is_wp_error( $menu_item_db_id ) ) { $messages[] = wp_get_admin_notice( $menu_item_db_id->get_error_message(), array( 'id' => 'message', 'additional_classes' => array( 'error' ), ) ); } else { unset( $menu_items[ $menu_item_db_id ] ); } } } // Remove menu items from the menu that weren't in $_POST. if ( ! empty( $menu_items ) ) { foreach ( array_keys( $menu_items ) as $menu_item_id ) { if ( is_nav_menu_item( $menu_item_id ) ) { wp_delete_post( $menu_item_id ); } } } // Store 'auto-add' pages. $auto_add = ! empty( $_POST['auto-add-pages'] ); $nav_menu_option = (array) get_option( 'nav_menu_options' ); if ( ! isset( $nav_menu_option['auto_add'] ) ) { $nav_menu_option['auto_add'] = array(); } if ( $auto_add ) { if ( ! in_array( $nav_menu_selected_id, $nav_menu_option['auto_add'], true ) ) { $nav_menu_option['auto_add'][] = $nav_menu_selected_id; } } else { $key = array_search( $nav_menu_selected_id, $nav_menu_option['auto_add'], true ); if ( false !== $key ) { unset( $nav_menu_option['auto_add'][ $key ] ); } } // Remove non-existent/deleted menus. $nav_menu_option['auto_add'] = array_intersect( $nav_menu_option['auto_add'], wp_get_nav_menus( array( 'fields' => 'ids' ) ) ); update_option( 'nav_menu_options', $nav_menu_option, false ); wp_defer_term_counting( false ); /** This action is documented in wp-includes/nav-menu.php */ do_action( 'wp_update_nav_menu', $nav_menu_selected_id ); /* translators: %s: Nav menu title. */ $message = sprintf( __( '%s has been updated.' ), '' . $nav_menu_selected_title . '' ); $notice_args = array( 'id' => 'message', 'dismissible' => true, 'additional_classes' => array( 'updated' ), ); $messages[] = wp_get_admin_notice( $message, $notice_args ); unset( $menu_items, $unsorted_menu_items ); return $messages; } /** * If a JSON blob of navigation menu data is in POST data, expand it and inject * it into `$_POST` to avoid PHP `max_input_vars` limitations. See #14134. * * @ignore * @since 4.5.3 * @access private */ function _wp_expand_nav_menu_post_data() { if ( ! isset( $_POST['nav-menu-data'] ) ) { return; } $data = json_decode( stripslashes( $_POST['nav-menu-data'] ) ); if ( ! is_null( $data ) && $data ) { foreach ( $data as $post_input_data ) { /* * For input names that are arrays (e.g. `menu-item-db-id[3][4][5]`), * derive the array path keys via regex and set the value in $_POST. */ preg_match( '#([^\[]*)(\[(.+)\])?#', $post_input_data->name, $matches ); $array_bits = array( $matches[1] ); if ( isset( $matches[3] ) ) { $array_bits = array_merge( $array_bits, explode( '][', $matches[3] ) ); } $new_post_data = array(); // Build the new array value from leaf to trunk. for ( $i = count( $array_bits ) - 1; $i >= 0; $i-- ) { if ( count( $array_bits ) - 1 === $i ) { $new_post_data[ $array_bits[ $i ] ] = wp_slash( $post_input_data->value ); } else { $new_post_data = array( $array_bits[ $i ] => $new_post_data ); } } $_POST = array_replace_recursive( $_POST, $new_post_data ); } } } class-wp-users-list-table.php000064400000045162147206365750012232 0ustar00 'user', 'plural' => 'users', 'screen' => isset( $args['screen'] ) ? $args['screen'] : null, ) ); $this->is_site_users = 'site-users-network' === $this->screen->id; if ( $this->is_site_users ) { $this->site_id = isset( $_REQUEST['id'] ) ? (int) $_REQUEST['id'] : 0; } } /** * Checks the current user's permissions. * * @since 3.1.0 * * @return bool */ public function ajax_user_can() { if ( $this->is_site_users ) { return current_user_can( 'manage_sites' ); } else { return current_user_can( 'list_users' ); } } /** * Prepares the users list for display. * * @since 3.1.0 * * @global string $role * @global string $usersearch */ public function prepare_items() { global $role, $usersearch; $usersearch = isset( $_REQUEST['s'] ) ? wp_unslash( trim( $_REQUEST['s'] ) ) : ''; $role = isset( $_REQUEST['role'] ) ? $_REQUEST['role'] : ''; $per_page = ( $this->is_site_users ) ? 'site_users_network_per_page' : 'users_per_page'; $users_per_page = $this->get_items_per_page( $per_page ); $paged = $this->get_pagenum(); if ( 'none' === $role ) { $args = array( 'number' => $users_per_page, 'offset' => ( $paged - 1 ) * $users_per_page, 'include' => wp_get_users_with_no_role( $this->site_id ), 'search' => $usersearch, 'fields' => 'all_with_meta', ); } else { $args = array( 'number' => $users_per_page, 'offset' => ( $paged - 1 ) * $users_per_page, 'role' => $role, 'search' => $usersearch, 'fields' => 'all_with_meta', ); } if ( '' !== $args['search'] ) { $args['search'] = '*' . $args['search'] . '*'; } if ( $this->is_site_users ) { $args['blog_id'] = $this->site_id; } if ( isset( $_REQUEST['orderby'] ) ) { $args['orderby'] = $_REQUEST['orderby']; } if ( isset( $_REQUEST['order'] ) ) { $args['order'] = $_REQUEST['order']; } /** * Filters the query arguments used to retrieve users for the current users list table. * * @since 4.4.0 * * @param array $args Arguments passed to WP_User_Query to retrieve items for the current * users list table. */ $args = apply_filters( 'users_list_table_query_args', $args ); // Query the user IDs for this page. $wp_user_search = new WP_User_Query( $args ); $this->items = $wp_user_search->get_results(); $this->set_pagination_args( array( 'total_items' => $wp_user_search->get_total(), 'per_page' => $users_per_page, ) ); } /** * Outputs 'no users' message. * * @since 3.1.0 */ public function no_items() { _e( 'No users found.' ); } /** * Returns an associative array listing all the views that can be used * with this table. * * Provides a list of roles and user count for that role for easy * filtering of the user table. * * @since 3.1.0 * * @global string $role * * @return string[] An array of HTML links keyed by their view. */ protected function get_views() { global $role; $wp_roles = wp_roles(); $count_users = ! wp_is_large_user_count(); if ( $this->is_site_users ) { $url = 'site-users.php?id=' . $this->site_id; } else { $url = 'users.php'; } $role_links = array(); $avail_roles = array(); $all_text = __( 'All' ); if ( $count_users ) { if ( $this->is_site_users ) { switch_to_blog( $this->site_id ); $users_of_blog = count_users( 'time', $this->site_id ); restore_current_blog(); } else { $users_of_blog = count_users(); } $total_users = $users_of_blog['total_users']; $avail_roles =& $users_of_blog['avail_roles']; unset( $users_of_blog ); $all_text = sprintf( /* translators: %s: Number of users. */ _nx( 'All (%s)', 'All (%s)', $total_users, 'users' ), number_format_i18n( $total_users ) ); } $role_links['all'] = array( 'url' => $url, 'label' => $all_text, 'current' => empty( $role ), ); foreach ( $wp_roles->get_names() as $this_role => $name ) { if ( $count_users && ! isset( $avail_roles[ $this_role ] ) ) { continue; } $name = translate_user_role( $name ); if ( $count_users ) { $name = sprintf( /* translators: 1: User role name, 2: Number of users. */ __( '%1$s (%2$s)' ), $name, number_format_i18n( $avail_roles[ $this_role ] ) ); } $role_links[ $this_role ] = array( 'url' => esc_url( add_query_arg( 'role', $this_role, $url ) ), 'label' => $name, 'current' => $this_role === $role, ); } if ( ! empty( $avail_roles['none'] ) ) { $name = __( 'No role' ); $name = sprintf( /* translators: 1: User role name, 2: Number of users. */ __( '%1$s (%2$s)' ), $name, number_format_i18n( $avail_roles['none'] ) ); $role_links['none'] = array( 'url' => esc_url( add_query_arg( 'role', 'none', $url ) ), 'label' => $name, 'current' => 'none' === $role, ); } return $this->get_views_links( $role_links ); } /** * Retrieves an associative array of bulk actions available on this table. * * @since 3.1.0 * * @return array Array of bulk action labels keyed by their action. */ protected function get_bulk_actions() { $actions = array(); if ( is_multisite() ) { if ( current_user_can( 'remove_users' ) ) { $actions['remove'] = __( 'Remove' ); } } else { if ( current_user_can( 'delete_users' ) ) { $actions['delete'] = __( 'Delete' ); } } // Add a password reset link to the bulk actions dropdown. if ( current_user_can( 'edit_users' ) ) { $actions['resetpassword'] = __( 'Send password reset' ); } return $actions; } /** * Outputs the controls to allow user roles to be changed in bulk. * * @since 3.1.0 * * @param string $which Whether this is being invoked above ("top") * or below the table ("bottom"). */ protected function extra_tablenav( $which ) { $id = 'bottom' === $which ? 'new_role2' : 'new_role'; $button_id = 'bottom' === $which ? 'changeit2' : 'changeit'; ?>
    has_items() ) : ?>
    '', 'username' => __( 'Username' ), 'name' => __( 'Name' ), 'email' => __( 'Email' ), 'role' => __( 'Role' ), 'posts' => _x( 'Posts', 'post type general name' ), ); if ( $this->is_site_users ) { unset( $columns['posts'] ); } return $columns; } /** * Gets a list of sortable columns for the list table. * * @since 3.1.0 * * @return array Array of sortable columns. */ protected function get_sortable_columns() { $columns = array( 'username' => array( 'login', false, __( 'Username' ), __( 'Table ordered by Username.' ), 'asc' ), 'email' => array( 'email', false, __( 'E-mail' ), __( 'Table ordered by E-mail.' ) ), ); return $columns; } /** * Generates the list table rows. * * @since 3.1.0 */ public function display_rows() { // Query the post counts for this page. if ( ! $this->is_site_users ) { $post_counts = count_many_users_posts( array_keys( $this->items ) ); } foreach ( $this->items as $userid => $user_object ) { echo "\n\t" . $this->single_row( $user_object, '', '', isset( $post_counts ) ? $post_counts[ $userid ] : 0 ); } } /** * Generates HTML for a single row on the users.php admin panel. * * @since 3.1.0 * @since 4.2.0 The `$style` parameter was deprecated. * @since 4.4.0 The `$role` parameter was deprecated. * * @param WP_User $user_object The current user object. * @param string $style Deprecated. Not used. * @param string $role Deprecated. Not used. * @param int $numposts Optional. Post count to display for this user. Defaults * to zero, as in, a new user has made zero posts. * @return string Output for a single row. */ public function single_row( $user_object, $style = '', $role = '', $numposts = 0 ) { if ( ! ( $user_object instanceof WP_User ) ) { $user_object = get_userdata( (int) $user_object ); } $user_object->filter = 'display'; $email = $user_object->user_email; if ( $this->is_site_users ) { $url = "site-users.php?id={$this->site_id}&"; } else { $url = 'users.php?'; } $user_roles = $this->get_role_list( $user_object ); // Set up the hover actions for this user. $actions = array(); $checkbox = ''; $super_admin = ''; if ( is_multisite() && current_user_can( 'manage_network_users' ) ) { if ( in_array( $user_object->user_login, get_super_admins(), true ) ) { $super_admin = ' — ' . __( 'Super Admin' ); } } // Check if the user for this row is editable. if ( current_user_can( 'list_users' ) ) { // Set up the user editing link. $edit_link = esc_url( add_query_arg( 'wp_http_referer', urlencode( wp_unslash( $_SERVER['REQUEST_URI'] ) ), get_edit_user_link( $user_object->ID ) ) ); if ( current_user_can( 'edit_user', $user_object->ID ) ) { $edit = "{$user_object->user_login}{$super_admin}
    "; $actions['edit'] = '' . __( 'Edit' ) . ''; } else { $edit = "{$user_object->user_login}{$super_admin}
    "; } if ( ! is_multisite() && get_current_user_id() !== $user_object->ID && current_user_can( 'delete_user', $user_object->ID ) ) { $actions['delete'] = "" . __( 'Delete' ) . ''; } if ( is_multisite() && current_user_can( 'remove_user', $user_object->ID ) ) { $actions['remove'] = "" . __( 'Remove' ) . ''; } // Add a link to the user's author archive, if not empty. $author_posts_url = get_author_posts_url( $user_object->ID ); if ( $author_posts_url ) { $actions['view'] = sprintf( '%s', esc_url( $author_posts_url ), /* translators: %s: Author's display name. */ esc_attr( sprintf( __( 'View posts by %s' ), $user_object->display_name ) ), __( 'View' ) ); } // Add a link to send the user a reset password link by email. if ( get_current_user_id() !== $user_object->ID && current_user_can( 'edit_user', $user_object->ID ) && true === wp_is_password_reset_allowed_for_user( $user_object ) ) { $actions['resetpassword'] = "" . __( 'Send password reset' ) . ''; } /** * Filters the action links displayed under each user in the Users list table. * * @since 2.8.0 * * @param string[] $actions An array of action links to be displayed. * Default 'Edit', 'Delete' for single site, and * 'Edit', 'Remove' for Multisite. * @param WP_User $user_object WP_User object for the currently listed user. */ $actions = apply_filters( 'user_row_actions', $actions, $user_object ); // Role classes. $role_classes = esc_attr( implode( ' ', array_keys( $user_roles ) ) ); // Set up the checkbox (because the user is editable, otherwise it's empty). $checkbox = sprintf( '' . '', $user_object->ID, $role_classes, /* translators: Hidden accessibility text. %s: User login. */ sprintf( __( 'Select %s' ), $user_object->user_login ) ); } else { $edit = "{$user_object->user_login}{$super_admin}"; } $avatar = get_avatar( $user_object->ID, 32 ); // Comma-separated list of user roles. $roles_list = implode( ', ', $user_roles ); $row = ""; list( $columns, $hidden, $sortable, $primary ) = $this->get_column_info(); foreach ( $columns as $column_name => $column_display_name ) { $classes = "$column_name column-$column_name"; if ( $primary === $column_name ) { $classes .= ' has-row-actions column-primary'; } if ( 'posts' === $column_name ) { $classes .= ' num'; // Special case for that column. } if ( in_array( $column_name, $hidden, true ) ) { $classes .= ' hidden'; } $data = 'data-colname="' . esc_attr( wp_strip_all_tags( $column_display_name ) ) . '"'; $attributes = "class='$classes' $data"; if ( 'cb' === $column_name ) { $row .= "$checkbox"; } else { $row .= ""; switch ( $column_name ) { case 'username': $row .= "$avatar $edit"; break; case 'name': if ( $user_object->first_name && $user_object->last_name ) { $row .= sprintf( /* translators: 1: User's first name, 2: Last name. */ _x( '%1$s %2$s', 'Display name based on first name and last name' ), $user_object->first_name, $user_object->last_name ); } elseif ( $user_object->first_name ) { $row .= $user_object->first_name; } elseif ( $user_object->last_name ) { $row .= $user_object->last_name; } else { $row .= sprintf( '%s', /* translators: Hidden accessibility text. */ _x( 'Unknown', 'name' ) ); } break; case 'email': $row .= "$email"; break; case 'role': $row .= esc_html( $roles_list ); break; case 'posts': if ( $numposts > 0 ) { $row .= sprintf( '%s', "edit.php?author={$user_object->ID}", $numposts, sprintf( /* translators: Hidden accessibility text. %s: Number of posts. */ _n( '%s post by this author', '%s posts by this author', $numposts ), number_format_i18n( $numposts ) ) ); } else { $row .= 0; } break; default: /** * Filters the display output of custom columns in the Users list table. * * @since 2.8.0 * * @param string $output Custom column output. Default empty. * @param string $column_name Column name. * @param int $user_id ID of the currently-listed user. */ $row .= apply_filters( 'manage_users_custom_column', '', $column_name, $user_object->ID ); } if ( $primary === $column_name ) { $row .= $this->row_actions( $actions ); } $row .= ''; } } $row .= ''; return $row; } /** * Gets the name of the default primary column. * * @since 4.3.0 * * @return string Name of the default primary column, in this case, 'username'. */ protected function get_default_primary_column_name() { return 'username'; } /** * Returns an array of translated user role names for a given user object. * * @since 4.4.0 * * @param WP_User $user_object The WP_User object. * @return string[] An array of user role names keyed by role. */ protected function get_role_list( $user_object ) { $wp_roles = wp_roles(); $role_list = array(); foreach ( $user_object->roles as $role ) { if ( isset( $wp_roles->role_names[ $role ] ) ) { $role_list[ $role ] = translate_user_role( $wp_roles->role_names[ $role ] ); } } if ( empty( $role_list ) ) { $role_list['none'] = _x( 'None', 'no user roles' ); } /** * Filters the returned array of translated role names for a user. * * @since 4.4.0 * * @param string[] $role_list An array of translated user role names keyed by role. * @param WP_User $user_object A WP_User object. */ return apply_filters( 'get_role_list', $role_list, $user_object ); } } class-walker-category-checklist.php000064400000011743147206365750013454 0ustar00 'parent', 'id' => 'term_id', ); // TODO: Decouple this. /** * Starts the list before the elements are added. * * @see Walker:start_lvl() * * @since 2.5.1 * * @param string $output Used to append additional content (passed by reference). * @param int $depth Depth of category. Used for tab indentation. * @param array $args An array of arguments. See {@see wp_terms_checklist()}. */ public function start_lvl( &$output, $depth = 0, $args = array() ) { $indent = str_repeat( "\t", $depth ); $output .= "$indent\n"; } /** * Start the element output. * * @see Walker::start_el() * * @since 2.5.1 * @since 5.9.0 Renamed `$category` to `$data_object` and `$id` to `$current_object_id` * to match parent class for PHP 8 named parameter support. * * @param string $output Used to append additional content (passed by reference). * @param WP_Term $data_object The current term object. * @param int $depth Depth of the term in reference to parents. Default 0. * @param array $args An array of arguments. See {@see wp_terms_checklist()}. * @param int $current_object_id Optional. ID of the current term. Default 0. */ public function start_el( &$output, $data_object, $depth = 0, $args = array(), $current_object_id = 0 ) { // Restores the more descriptive, specific name for use within this method. $category = $data_object; if ( empty( $args['taxonomy'] ) ) { $taxonomy = 'category'; } else { $taxonomy = $args['taxonomy']; } if ( 'category' === $taxonomy ) { $name = 'post_category'; } else { $name = 'tax_input[' . $taxonomy . ']'; } $args['popular_cats'] = ! empty( $args['popular_cats'] ) ? array_map( 'intval', $args['popular_cats'] ) : array(); $class = in_array( $category->term_id, $args['popular_cats'], true ) ? ' class="popular-category"' : ''; $args['selected_cats'] = ! empty( $args['selected_cats'] ) ? array_map( 'intval', $args['selected_cats'] ) : array(); if ( ! empty( $args['list_only'] ) ) { $aria_checked = 'false'; $inner_class = 'category'; if ( in_array( $category->term_id, $args['selected_cats'], true ) ) { $inner_class .= ' selected'; $aria_checked = 'true'; } $output .= "\n" . '' . ''; } else { $is_selected = in_array( $category->term_id, $args['selected_cats'], true ); $is_disabled = ! empty( $args['disabled'] ); $li_element_id = wp_unique_prefixed_id( "in-{$taxonomy}-{$category->term_id}-" ); $checkbox_element_id = wp_unique_prefixed_id( "in-{$taxonomy}-{$category->term_id}-" ); $output .= "\n
  • " . ''; } } /** * Ends the element output, if needed. * * @see Walker::end_el() * * @since 2.5.1 * @since 5.9.0 Renamed `$category` to `$data_object` to match parent class for PHP 8 named parameter support. * * @param string $output Used to append additional content (passed by reference). * @param WP_Term $data_object The current term object. * @param int $depth Depth of the term in reference to parents. Default 0. * @param array $args An array of arguments. See {@see wp_terms_checklist()}. */ public function end_el( &$output, $data_object, $depth = 0, $args = array() ) { $output .= "
  • \n"; } } class-wp-links-list-table.php000064400000022031147206365750012177 0ustar00 'bookmarks', 'screen' => isset( $args['screen'] ) ? $args['screen'] : null, ) ); } /** * @return bool */ public function ajax_user_can() { return current_user_can( 'manage_links' ); } /** * @global int $cat_id * @global string $s * @global string $orderby * @global string $order */ public function prepare_items() { global $cat_id, $s, $orderby, $order; $cat_id = ! empty( $_REQUEST['cat_id'] ) ? absint( $_REQUEST['cat_id'] ) : 0; $orderby = ! empty( $_REQUEST['orderby'] ) ? sanitize_text_field( $_REQUEST['orderby'] ) : ''; $order = ! empty( $_REQUEST['order'] ) ? sanitize_text_field( $_REQUEST['order'] ) : ''; $s = ! empty( $_REQUEST['s'] ) ? sanitize_text_field( $_REQUEST['s'] ) : ''; $args = array( 'hide_invisible' => 0, 'hide_empty' => 0, ); if ( 'all' !== $cat_id ) { $args['category'] = $cat_id; } if ( ! empty( $s ) ) { $args['search'] = $s; } if ( ! empty( $orderby ) ) { $args['orderby'] = $orderby; } if ( ! empty( $order ) ) { $args['order'] = $order; } $this->items = get_bookmarks( $args ); } /** */ public function no_items() { _e( 'No links found.' ); } /** * @return array */ protected function get_bulk_actions() { $actions = array(); $actions['delete'] = __( 'Delete' ); return $actions; } /** * @global int $cat_id * @param string $which */ protected function extra_tablenav( $which ) { global $cat_id; if ( 'top' !== $which ) { return; } ?>
    $cat_id, 'name' => 'cat_id', 'taxonomy' => 'link_category', 'show_option_all' => get_taxonomy( 'link_category' )->labels->all_items, 'hide_empty' => true, 'hierarchical' => 1, 'show_count' => 0, 'orderby' => 'name', ); echo ''; wp_dropdown_categories( $dropdown_options ); submit_button( __( 'Filter' ), '', 'filter_action', false, array( 'id' => 'post-query-submit' ) ); ?>
    '', 'name' => _x( 'Name', 'link name' ), 'url' => __( 'URL' ), 'categories' => __( 'Categories' ), 'rel' => __( 'Relationship' ), 'visible' => __( 'Visible' ), 'rating' => __( 'Rating' ), ); } /** * @return array */ protected function get_sortable_columns() { return array( 'name' => array( 'name', false, _x( 'Name', 'link name' ), __( 'Table ordered by Name.' ), 'asc' ), 'url' => array( 'url', false, __( 'URL' ), __( 'Table ordered by URL.' ) ), 'visible' => array( 'visible', false, __( 'Visible' ), __( 'Table ordered by Visibility.' ) ), 'rating' => array( 'rating', false, __( 'Rating' ), __( 'Table ordered by Rating.' ) ), ); } /** * Gets the name of the default primary column. * * @since 4.3.0 * * @return string Name of the default primary column, in this case, 'name'. */ protected function get_default_primary_column_name() { return 'name'; } /** * Handles the checkbox column output. * * @since 4.3.0 * @since 5.9.0 Renamed `$link` to `$item` to match parent class for PHP 8 named parameter support. * * @param object $item The current link object. */ public function column_cb( $item ) { // Restores the more descriptive, specific name for use within this method. $link = $item; ?> %s', $edit_link, /* translators: %s: Link name. */ esc_attr( sprintf( __( 'Edit “%s”' ), $link->link_name ) ), $link->link_name ); } /** * Handles the link URL column output. * * @since 4.3.0 * * @param object $link The current link object. */ public function column_url( $link ) { $short_url = url_shorten( $link->link_url ); echo "$short_url"; } /** * Handles the link categories column output. * * @since 4.3.0 * * @global int $cat_id * * @param object $link The current link object. */ public function column_categories( $link ) { global $cat_id; $cat_names = array(); foreach ( $link->link_category as $category ) { $cat = get_term( $category, 'link_category', OBJECT, 'display' ); if ( is_wp_error( $cat ) ) { echo $cat->get_error_message(); } $cat_name = $cat->name; if ( (int) $cat_id !== $category ) { $cat_name = "$cat_name"; } $cat_names[] = $cat_name; } echo implode( ', ', $cat_names ); } /** * Handles the link relation column output. * * @since 4.3.0 * * @param object $link The current link object. */ public function column_rel( $link ) { echo empty( $link->link_rel ) ? '
    ' : $link->link_rel; } /** * Handles the link visibility column output. * * @since 4.3.0 * * @param object $link The current link object. */ public function column_visible( $link ) { if ( 'Y' === $link->link_visible ) { _e( 'Yes' ); } else { _e( 'No' ); } } /** * Handles the link rating column output. * * @since 4.3.0 * * @param object $link The current link object. */ public function column_rating( $link ) { echo $link->link_rating; } /** * Handles the default column output. * * @since 4.3.0 * @since 5.9.0 Renamed `$link` to `$item` to match parent class for PHP 8 named parameter support. * * @param object $item Link object. * @param string $column_name Current column name. */ public function column_default( $item, $column_name ) { // Restores the more descriptive, specific name for use within this method. $link = $item; /** * Fires for each registered custom link column. * * @since 2.1.0 * * @param string $column_name Name of the custom column. * @param int $link_id Link ID. */ do_action( 'manage_link_custom_column', $column_name, $link->link_id ); } /** * Generates the list table rows. * * @since 3.1.0 */ public function display_rows() { foreach ( $this->items as $link ) { $link = sanitize_bookmark( $link ); $link->link_name = esc_attr( $link->link_name ); $link->link_category = wp_get_link_cats( $link->link_id ); ?> single_row_columns( $link ); ?> ' . __( 'Edit' ) . ''; $actions['delete'] = sprintf( '%s', wp_nonce_url( "link.php?action=delete&link_id=$link->link_id", 'delete-bookmark_' . $link->link_id ), /* translators: %s: Link name. */ esc_js( sprintf( __( "You are about to delete this link '%s'\n 'Cancel' to stop, 'OK' to delete." ), $link->link_name ) ), __( 'Delete' ) ); return $this->row_actions( $actions ); } } file.php000064400000276277147206365750006240 0ustar00 __( 'Theme Functions' ), 'header.php' => __( 'Theme Header' ), 'footer.php' => __( 'Theme Footer' ), 'sidebar.php' => __( 'Sidebar' ), 'comments.php' => __( 'Comments' ), 'searchform.php' => __( 'Search Form' ), '404.php' => __( '404 Template' ), 'link.php' => __( 'Links Template' ), 'theme.json' => __( 'Theme Styles & Block Settings' ), // Archives. 'index.php' => __( 'Main Index Template' ), 'archive.php' => __( 'Archives' ), 'author.php' => __( 'Author Template' ), 'taxonomy.php' => __( 'Taxonomy Template' ), 'category.php' => __( 'Category Template' ), 'tag.php' => __( 'Tag Template' ), 'home.php' => __( 'Posts Page' ), 'search.php' => __( 'Search Results' ), 'date.php' => __( 'Date Template' ), // Content. 'singular.php' => __( 'Singular Template' ), 'single.php' => __( 'Single Post' ), 'page.php' => __( 'Single Page' ), 'front-page.php' => __( 'Homepage' ), 'privacy-policy.php' => __( 'Privacy Policy Page' ), // Attachments. 'attachment.php' => __( 'Attachment Template' ), 'image.php' => __( 'Image Attachment Template' ), 'video.php' => __( 'Video Attachment Template' ), 'audio.php' => __( 'Audio Attachment Template' ), 'application.php' => __( 'Application Attachment Template' ), // Embeds. 'embed.php' => __( 'Embed Template' ), 'embed-404.php' => __( 'Embed 404 Template' ), 'embed-content.php' => __( 'Embed Content Template' ), 'header-embed.php' => __( 'Embed Header Template' ), 'footer-embed.php' => __( 'Embed Footer Template' ), // Stylesheets. 'style.css' => __( 'Stylesheet' ), 'editor-style.css' => __( 'Visual Editor Stylesheet' ), 'editor-style-rtl.css' => __( 'Visual Editor RTL Stylesheet' ), 'rtl.css' => __( 'RTL Stylesheet' ), // Other. 'my-hacks.php' => __( 'my-hacks.php (legacy hacks support)' ), '.htaccess' => __( '.htaccess (for rewrite rules )' ), // Deprecated files. 'wp-layout.css' => __( 'Stylesheet' ), 'wp-comments.php' => __( 'Comments Template' ), 'wp-comments-popup.php' => __( 'Popup Comments Template' ), 'comments-popup.php' => __( 'Popup Comments' ), ); /** * Gets the description for standard WordPress theme files. * * @since 1.5.0 * * @global array $wp_file_descriptions Theme file descriptions. * @global array $allowed_files List of allowed files. * * @param string $file Filesystem path or filename. * @return string Description of file from $wp_file_descriptions or basename of $file if description doesn't exist. * Appends 'Page Template' to basename of $file if the file is a page template. */ function get_file_description( $file ) { global $wp_file_descriptions, $allowed_files; $dirname = pathinfo( $file, PATHINFO_DIRNAME ); $file_path = $allowed_files[ $file ]; if ( isset( $wp_file_descriptions[ basename( $file ) ] ) && '.' === $dirname ) { return $wp_file_descriptions[ basename( $file ) ]; } elseif ( file_exists( $file_path ) && is_file( $file_path ) ) { $template_data = implode( '', file( $file_path ) ); if ( preg_match( '|Template Name:(.*)$|mi', $template_data, $name ) ) { /* translators: %s: Template name. */ return sprintf( __( '%s Page Template' ), _cleanup_header_comment( $name[1] ) ); } } return trim( basename( $file ) ); } /** * Gets the absolute filesystem path to the root of the WordPress installation. * * @since 1.5.0 * * @return string Full filesystem path to the root of the WordPress installation. */ function get_home_path() { $home = set_url_scheme( get_option( 'home' ), 'http' ); $siteurl = set_url_scheme( get_option( 'siteurl' ), 'http' ); if ( ! empty( $home ) && 0 !== strcasecmp( $home, $siteurl ) ) { $wp_path_rel_to_home = str_ireplace( $home, '', $siteurl ); /* $siteurl - $home */ $pos = strripos( str_replace( '\\', '/', $_SERVER['SCRIPT_FILENAME'] ), trailingslashit( $wp_path_rel_to_home ) ); $home_path = substr( $_SERVER['SCRIPT_FILENAME'], 0, $pos ); $home_path = trailingslashit( $home_path ); } else { $home_path = ABSPATH; } return str_replace( '\\', '/', $home_path ); } /** * Returns a listing of all files in the specified folder and all subdirectories up to 100 levels deep. * * The depth of the recursiveness can be controlled by the $levels param. * * @since 2.6.0 * @since 4.9.0 Added the `$exclusions` parameter. * @since 6.3.0 Added the `$include_hidden` parameter. * * @param string $folder Optional. Full path to folder. Default empty. * @param int $levels Optional. Levels of folders to follow, Default 100 (PHP Loop limit). * @param string[] $exclusions Optional. List of folders and files to skip. * @param bool $include_hidden Optional. Whether to include details of hidden ("." prefixed) files. * Default false. * @return string[]|false Array of files on success, false on failure. */ function list_files( $folder = '', $levels = 100, $exclusions = array(), $include_hidden = false ) { if ( empty( $folder ) ) { return false; } $folder = trailingslashit( $folder ); if ( ! $levels ) { return false; } $files = array(); $dir = @opendir( $folder ); if ( $dir ) { while ( ( $file = readdir( $dir ) ) !== false ) { // Skip current and parent folder links. if ( in_array( $file, array( '.', '..' ), true ) ) { continue; } // Skip hidden and excluded files. if ( ( ! $include_hidden && '.' === $file[0] ) || in_array( $file, $exclusions, true ) ) { continue; } if ( is_dir( $folder . $file ) ) { $files2 = list_files( $folder . $file, $levels - 1, array(), $include_hidden ); if ( $files2 ) { $files = array_merge( $files, $files2 ); } else { $files[] = $folder . $file . '/'; } } else { $files[] = $folder . $file; } } closedir( $dir ); } return $files; } /** * Gets the list of file extensions that are editable in plugins. * * @since 4.9.0 * * @param string $plugin Path to the plugin file relative to the plugins directory. * @return string[] Array of editable file extensions. */ function wp_get_plugin_file_editable_extensions( $plugin ) { $default_types = array( 'bash', 'conf', 'css', 'diff', 'htm', 'html', 'http', 'inc', 'include', 'js', 'json', 'jsx', 'less', 'md', 'patch', 'php', 'php3', 'php4', 'php5', 'php7', 'phps', 'phtml', 'sass', 'scss', 'sh', 'sql', 'svg', 'text', 'txt', 'xml', 'yaml', 'yml', ); /** * Filters the list of file types allowed for editing in the plugin file editor. * * @since 2.8.0 * @since 4.9.0 Added the `$plugin` parameter. * * @param string[] $default_types An array of editable plugin file extensions. * @param string $plugin Path to the plugin file relative to the plugins directory. */ $file_types = (array) apply_filters( 'editable_extensions', $default_types, $plugin ); return $file_types; } /** * Gets the list of file extensions that are editable for a given theme. * * @since 4.9.0 * * @param WP_Theme $theme Theme object. * @return string[] Array of editable file extensions. */ function wp_get_theme_file_editable_extensions( $theme ) { $default_types = array( 'bash', 'conf', 'css', 'diff', 'htm', 'html', 'http', 'inc', 'include', 'js', 'json', 'jsx', 'less', 'md', 'patch', 'php', 'php3', 'php4', 'php5', 'php7', 'phps', 'phtml', 'sass', 'scss', 'sh', 'sql', 'svg', 'text', 'txt', 'xml', 'yaml', 'yml', ); /** * Filters the list of file types allowed for editing in the theme file editor. * * @since 4.4.0 * * @param string[] $default_types An array of editable theme file extensions. * @param WP_Theme $theme The active theme object. */ $file_types = apply_filters( 'wp_theme_editor_filetypes', $default_types, $theme ); // Ensure that default types are still there. return array_unique( array_merge( $file_types, $default_types ) ); } /** * Prints file editor templates (for plugins and themes). * * @since 4.9.0 */ function wp_print_file_editor_templates() { ?> exists() ) { return new WP_Error( 'non_existent_theme', __( 'The requested theme does not exist.' ) ); } if ( ! wp_verify_nonce( $args['nonce'], 'edit-theme_' . $stylesheet . '_' . $file ) ) { return new WP_Error( 'nonce_failure' ); } if ( $theme->errors() && 'theme_no_stylesheet' === $theme->errors()->get_error_code() ) { return new WP_Error( 'theme_no_stylesheet', __( 'The requested theme does not exist.' ) . ' ' . $theme->errors()->get_error_message() ); } $editable_extensions = wp_get_theme_file_editable_extensions( $theme ); $allowed_files = array(); foreach ( $editable_extensions as $type ) { switch ( $type ) { case 'php': $allowed_files = array_merge( $allowed_files, $theme->get_files( 'php', -1 ) ); break; case 'css': $style_files = $theme->get_files( 'css', -1 ); $allowed_files['style.css'] = $style_files['style.css']; $allowed_files = array_merge( $allowed_files, $style_files ); break; default: $allowed_files = array_merge( $allowed_files, $theme->get_files( $type, -1 ) ); break; } } // Compare based on relative paths. if ( 0 !== validate_file( $file, array_keys( $allowed_files ) ) ) { return new WP_Error( 'disallowed_theme_file', __( 'Sorry, that file cannot be edited.' ) ); } $real_file = $theme->get_stylesheet_directory() . '/' . $file; $is_active = ( get_stylesheet() === $stylesheet || get_template() === $stylesheet ); } else { return new WP_Error( 'missing_theme_or_plugin' ); } // Ensure file is real. if ( ! is_file( $real_file ) ) { return new WP_Error( 'file_does_not_exist', __( 'File does not exist! Please double check the name and try again.' ) ); } // Ensure file extension is allowed. $extension = null; if ( preg_match( '/\.([^.]+)$/', $real_file, $matches ) ) { $extension = strtolower( $matches[1] ); if ( ! in_array( $extension, $editable_extensions, true ) ) { return new WP_Error( 'illegal_file_type', __( 'Files of this type are not editable.' ) ); } } $previous_content = file_get_contents( $real_file ); if ( ! is_writable( $real_file ) ) { return new WP_Error( 'file_not_writable' ); } $f = fopen( $real_file, 'w+' ); if ( false === $f ) { return new WP_Error( 'file_not_writable' ); } $written = fwrite( $f, $content ); fclose( $f ); if ( false === $written ) { return new WP_Error( 'unable_to_write', __( 'Unable to write to file.' ) ); } wp_opcache_invalidate( $real_file, true ); if ( $is_active && 'php' === $extension ) { $scrape_key = md5( rand() ); $transient = 'scrape_key_' . $scrape_key; $scrape_nonce = (string) rand(); // It shouldn't take more than 60 seconds to make the two loopback requests. set_transient( $transient, $scrape_nonce, 60 ); $cookies = wp_unslash( $_COOKIE ); $scrape_params = array( 'wp_scrape_key' => $scrape_key, 'wp_scrape_nonce' => $scrape_nonce, ); $headers = array( 'Cache-Control' => 'no-cache', ); /** This filter is documented in wp-includes/class-wp-http-streams.php */ $sslverify = apply_filters( 'https_local_ssl_verify', false ); // Include Basic auth in loopback requests. if ( isset( $_SERVER['PHP_AUTH_USER'] ) && isset( $_SERVER['PHP_AUTH_PW'] ) ) { $headers['Authorization'] = 'Basic ' . base64_encode( wp_unslash( $_SERVER['PHP_AUTH_USER'] ) . ':' . wp_unslash( $_SERVER['PHP_AUTH_PW'] ) ); } // Make sure PHP process doesn't die before loopback requests complete. if ( function_exists( 'set_time_limit' ) ) { set_time_limit( 5 * MINUTE_IN_SECONDS ); } // Time to wait for loopback requests to finish. $timeout = 100; // 100 seconds. $needle_start = "###### wp_scraping_result_start:$scrape_key ######"; $needle_end = "###### wp_scraping_result_end:$scrape_key ######"; // Attempt loopback request to editor to see if user just whitescreened themselves. if ( $plugin ) { $url = add_query_arg( compact( 'plugin', 'file' ), admin_url( 'plugin-editor.php' ) ); } elseif ( isset( $stylesheet ) ) { $url = add_query_arg( array( 'theme' => $stylesheet, 'file' => $file, ), admin_url( 'theme-editor.php' ) ); } else { $url = admin_url(); } if ( function_exists( 'session_status' ) && PHP_SESSION_ACTIVE === session_status() ) { /* * Close any active session to prevent HTTP requests from timing out * when attempting to connect back to the site. */ session_write_close(); } $url = add_query_arg( $scrape_params, $url ); $r = wp_remote_get( $url, compact( 'cookies', 'headers', 'timeout', 'sslverify' ) ); $body = wp_remote_retrieve_body( $r ); $scrape_result_position = strpos( $body, $needle_start ); $loopback_request_failure = array( 'code' => 'loopback_request_failed', 'message' => __( 'Unable to communicate back with site to check for fatal errors, so the PHP change was reverted. You will need to upload your PHP file change by some other means, such as by using SFTP.' ), ); $json_parse_failure = array( 'code' => 'json_parse_error', ); $result = null; if ( false === $scrape_result_position ) { $result = $loopback_request_failure; } else { $error_output = substr( $body, $scrape_result_position + strlen( $needle_start ) ); $error_output = substr( $error_output, 0, strpos( $error_output, $needle_end ) ); $result = json_decode( trim( $error_output ), true ); if ( empty( $result ) ) { $result = $json_parse_failure; } } // Try making request to homepage as well to see if visitors have been whitescreened. if ( true === $result ) { $url = home_url( '/' ); $url = add_query_arg( $scrape_params, $url ); $r = wp_remote_get( $url, compact( 'cookies', 'headers', 'timeout', 'sslverify' ) ); $body = wp_remote_retrieve_body( $r ); $scrape_result_position = strpos( $body, $needle_start ); if ( false === $scrape_result_position ) { $result = $loopback_request_failure; } else { $error_output = substr( $body, $scrape_result_position + strlen( $needle_start ) ); $error_output = substr( $error_output, 0, strpos( $error_output, $needle_end ) ); $result = json_decode( trim( $error_output ), true ); if ( empty( $result ) ) { $result = $json_parse_failure; } } } delete_transient( $transient ); if ( true !== $result ) { // Roll-back file change. file_put_contents( $real_file, $previous_content ); wp_opcache_invalidate( $real_file, true ); if ( ! isset( $result['message'] ) ) { $message = __( 'Something went wrong.' ); } else { $message = $result['message']; unset( $result['message'] ); } return new WP_Error( 'php_error', $message, $result ); } } if ( $theme instanceof WP_Theme ) { $theme->cache_delete(); } return true; } /** * Returns a filename of a temporary unique file. * * Please note that the calling function must delete or move the file. * * The filename is based off the passed parameter or defaults to the current unix timestamp, * while the directory can either be passed as well, or by leaving it blank, default to a writable * temporary directory. * * @since 2.6.0 * * @param string $filename Optional. Filename to base the Unique file off. Default empty. * @param string $dir Optional. Directory to store the file in. Default empty. * @return string A writable filename. */ function wp_tempnam( $filename = '', $dir = '' ) { if ( empty( $dir ) ) { $dir = get_temp_dir(); } if ( empty( $filename ) || in_array( $filename, array( '.', '/', '\\' ), true ) ) { $filename = uniqid(); } // Use the basename of the given file without the extension as the name for the temporary directory. $temp_filename = basename( $filename ); $temp_filename = preg_replace( '|\.[^.]*$|', '', $temp_filename ); // If the folder is falsey, use its parent directory name instead. if ( ! $temp_filename ) { return wp_tempnam( dirname( $filename ), $dir ); } // Suffix some random data to avoid filename conflicts. $temp_filename .= '-' . wp_generate_password( 6, false ); $temp_filename .= '.tmp'; $temp_filename = wp_unique_filename( $dir, $temp_filename ); /* * Filesystems typically have a limit of 255 characters for a filename. * * If the generated unique filename exceeds this, truncate the initial * filename and try again. * * As it's possible that the truncated filename may exist, producing a * suffix of "-1" or "-10" which could exceed the limit again, truncate * it to 252 instead. */ $characters_over_limit = strlen( $temp_filename ) - 252; if ( $characters_over_limit > 0 ) { $filename = substr( $filename, 0, -$characters_over_limit ); return wp_tempnam( $filename, $dir ); } $temp_filename = $dir . $temp_filename; $fp = @fopen( $temp_filename, 'x' ); if ( ! $fp && is_writable( $dir ) && file_exists( $temp_filename ) ) { return wp_tempnam( $filename, $dir ); } if ( $fp ) { fclose( $fp ); } return $temp_filename; } /** * Makes sure that the file that was requested to be edited is allowed to be edited. * * Function will die if you are not allowed to edit the file. * * @since 1.5.0 * * @param string $file File the user is attempting to edit. * @param string[] $allowed_files Optional. Array of allowed files to edit. * `$file` must match an entry exactly. * @return string|void Returns the file name on success, dies on failure. */ function validate_file_to_edit( $file, $allowed_files = array() ) { $code = validate_file( $file, $allowed_files ); if ( ! $code ) { return $file; } switch ( $code ) { case 1: wp_die( __( 'Sorry, that file cannot be edited.' ) ); // case 2 : // wp_die( __('Sorry, cannot call files with their real path.' )); case 3: wp_die( __( 'Sorry, that file cannot be edited.' ) ); } } /** * Handles PHP uploads in WordPress. * * Sanitizes file names, checks extensions for mime type, and moves the file * to the appropriate directory within the uploads directory. * * @access private * @since 4.0.0 * * @see wp_handle_upload_error * * @param array $file { * Reference to a single element from `$_FILES`. Call the function once for each uploaded file. * * @type string $name The original name of the file on the client machine. * @type string $type The mime type of the file, if the browser provided this information. * @type string $tmp_name The temporary filename of the file in which the uploaded file was stored on the server. * @type int $size The size, in bytes, of the uploaded file. * @type int $error The error code associated with this file upload. * } * @param array|false $overrides { * An array of override parameters for this file, or boolean false if none are provided. * * @type callable $upload_error_handler Function to call when there is an error during the upload process. * See {@see wp_handle_upload_error()}. * @type callable $unique_filename_callback Function to call when determining a unique file name for the file. * See {@see wp_unique_filename()}. * @type string[] $upload_error_strings The strings that describe the error indicated in * `$_FILES[{form field}]['error']`. * @type bool $test_form Whether to test that the `$_POST['action']` parameter is as expected. * @type bool $test_size Whether to test that the file size is greater than zero bytes. * @type bool $test_type Whether to test that the mime type of the file is as expected. * @type string[] $mimes Array of allowed mime types keyed by their file extension regex. * } * @param string $time Time formatted in 'yyyy/mm'. * @param string $action Expected value for `$_POST['action']`. * @return array { * On success, returns an associative array of file attributes. * On failure, returns `$overrides['upload_error_handler']( &$file, $message )` * or `array( 'error' => $message )`. * * @type string $file Filename of the newly-uploaded file. * @type string $url URL of the newly-uploaded file. * @type string $type Mime type of the newly-uploaded file. * } */ function _wp_handle_upload( &$file, $overrides, $time, $action ) { // The default error handler. if ( ! function_exists( 'wp_handle_upload_error' ) ) { function wp_handle_upload_error( &$file, $message ) { return array( 'error' => $message ); } } /** * Filters the data for a file before it is uploaded to WordPress. * * The dynamic portion of the hook name, `$action`, refers to the post action. * * Possible hook names include: * * - `wp_handle_sideload_prefilter` * - `wp_handle_upload_prefilter` * * @since 2.9.0 as 'wp_handle_upload_prefilter'. * @since 4.0.0 Converted to a dynamic hook with `$action`. * * @param array $file { * Reference to a single element from `$_FILES`. * * @type string $name The original name of the file on the client machine. * @type string $type The mime type of the file, if the browser provided this information. * @type string $tmp_name The temporary filename of the file in which the uploaded file was stored on the server. * @type int $size The size, in bytes, of the uploaded file. * @type int $error The error code associated with this file upload. * } */ $file = apply_filters( "{$action}_prefilter", $file ); /** * Filters the override parameters for a file before it is uploaded to WordPress. * * The dynamic portion of the hook name, `$action`, refers to the post action. * * Possible hook names include: * * - `wp_handle_sideload_overrides` * - `wp_handle_upload_overrides` * * @since 5.7.0 * * @param array|false $overrides An array of override parameters for this file. Boolean false if none are * provided. See {@see _wp_handle_upload()}. * @param array $file { * Reference to a single element from `$_FILES`. * * @type string $name The original name of the file on the client machine. * @type string $type The mime type of the file, if the browser provided this information. * @type string $tmp_name The temporary filename of the file in which the uploaded file was stored on the server. * @type int $size The size, in bytes, of the uploaded file. * @type int $error The error code associated with this file upload. * } */ $overrides = apply_filters( "{$action}_overrides", $overrides, $file ); // You may define your own function and pass the name in $overrides['upload_error_handler']. $upload_error_handler = 'wp_handle_upload_error'; if ( isset( $overrides['upload_error_handler'] ) ) { $upload_error_handler = $overrides['upload_error_handler']; } // You may have had one or more 'wp_handle_upload_prefilter' functions error out the file. Handle that gracefully. if ( isset( $file['error'] ) && ! is_numeric( $file['error'] ) && $file['error'] ) { return call_user_func_array( $upload_error_handler, array( &$file, $file['error'] ) ); } // Install user overrides. Did we mention that this voids your warranty? // You may define your own function and pass the name in $overrides['unique_filename_callback']. $unique_filename_callback = null; if ( isset( $overrides['unique_filename_callback'] ) ) { $unique_filename_callback = $overrides['unique_filename_callback']; } /* * This may not have originally been intended to be overridable, * but historically has been. */ if ( isset( $overrides['upload_error_strings'] ) ) { $upload_error_strings = $overrides['upload_error_strings']; } else { // Courtesy of php.net, the strings that describe the error indicated in $_FILES[{form field}]['error']. $upload_error_strings = array( false, sprintf( /* translators: 1: upload_max_filesize, 2: php.ini */ __( 'The uploaded file exceeds the %1$s directive in %2$s.' ), 'upload_max_filesize', 'php.ini' ), sprintf( /* translators: %s: MAX_FILE_SIZE */ __( 'The uploaded file exceeds the %s directive that was specified in the HTML form.' ), 'MAX_FILE_SIZE' ), __( 'The uploaded file was only partially uploaded.' ), __( 'No file was uploaded.' ), '', __( 'Missing a temporary folder.' ), __( 'Failed to write file to disk.' ), __( 'File upload stopped by extension.' ), ); } // All tests are on by default. Most can be turned off by $overrides[{test_name}] = false; $test_form = isset( $overrides['test_form'] ) ? $overrides['test_form'] : true; $test_size = isset( $overrides['test_size'] ) ? $overrides['test_size'] : true; // If you override this, you must provide $ext and $type!! $test_type = isset( $overrides['test_type'] ) ? $overrides['test_type'] : true; $mimes = isset( $overrides['mimes'] ) ? $overrides['mimes'] : null; // A correct form post will pass this test. if ( $test_form && ( ! isset( $_POST['action'] ) || $_POST['action'] !== $action ) ) { return call_user_func_array( $upload_error_handler, array( &$file, __( 'Invalid form submission.' ) ) ); } // A successful upload will pass this test. It makes no sense to override this one. if ( isset( $file['error'] ) && $file['error'] > 0 ) { return call_user_func_array( $upload_error_handler, array( &$file, $upload_error_strings[ $file['error'] ] ) ); } // A properly uploaded file will pass this test. There should be no reason to override this one. $test_uploaded_file = 'wp_handle_upload' === $action ? is_uploaded_file( $file['tmp_name'] ) : @is_readable( $file['tmp_name'] ); if ( ! $test_uploaded_file ) { return call_user_func_array( $upload_error_handler, array( &$file, __( 'Specified file failed upload test.' ) ) ); } $test_file_size = 'wp_handle_upload' === $action ? $file['size'] : filesize( $file['tmp_name'] ); // A non-empty file will pass this test. if ( $test_size && ! ( $test_file_size > 0 ) ) { if ( is_multisite() ) { $error_msg = __( 'File is empty. Please upload something more substantial.' ); } else { $error_msg = sprintf( /* translators: 1: php.ini, 2: post_max_size, 3: upload_max_filesize */ __( 'File is empty. Please upload something more substantial. This error could also be caused by uploads being disabled in your %1$s file or by %2$s being defined as smaller than %3$s in %1$s.' ), 'php.ini', 'post_max_size', 'upload_max_filesize' ); } return call_user_func_array( $upload_error_handler, array( &$file, $error_msg ) ); } // A correct MIME type will pass this test. Override $mimes or use the upload_mimes filter. if ( $test_type ) { $wp_filetype = wp_check_filetype_and_ext( $file['tmp_name'], $file['name'], $mimes ); $ext = empty( $wp_filetype['ext'] ) ? '' : $wp_filetype['ext']; $type = empty( $wp_filetype['type'] ) ? '' : $wp_filetype['type']; $proper_filename = empty( $wp_filetype['proper_filename'] ) ? '' : $wp_filetype['proper_filename']; // Check to see if wp_check_filetype_and_ext() determined the filename was incorrect. if ( $proper_filename ) { $file['name'] = $proper_filename; } if ( ( ! $type || ! $ext ) && ! current_user_can( 'unfiltered_upload' ) ) { return call_user_func_array( $upload_error_handler, array( &$file, __( 'Sorry, you are not allowed to upload this file type.' ) ) ); } if ( ! $type ) { $type = $file['type']; } } else { $type = ''; } /* * A writable uploads dir will pass this test. Again, there's no point * overriding this one. */ $uploads = wp_upload_dir( $time ); if ( ! ( $uploads && false === $uploads['error'] ) ) { return call_user_func_array( $upload_error_handler, array( &$file, $uploads['error'] ) ); } $filename = wp_unique_filename( $uploads['path'], $file['name'], $unique_filename_callback ); // Move the file to the uploads dir. $new_file = $uploads['path'] . "/$filename"; /** * Filters whether to short-circuit moving the uploaded file after passing all checks. * * If a non-null value is returned from the filter, moving the file and any related * error reporting will be completely skipped. * * @since 4.9.0 * * @param mixed $move_new_file If null (default) move the file after the upload. * @param array $file { * Reference to a single element from `$_FILES`. * * @type string $name The original name of the file on the client machine. * @type string $type The mime type of the file, if the browser provided this information. * @type string $tmp_name The temporary filename of the file in which the uploaded file was stored on the server. * @type int $size The size, in bytes, of the uploaded file. * @type int $error The error code associated with this file upload. * } * @param string $new_file Filename of the newly-uploaded file. * @param string $type Mime type of the newly-uploaded file. */ $move_new_file = apply_filters( 'pre_move_uploaded_file', null, $file, $new_file, $type ); if ( null === $move_new_file ) { if ( 'wp_handle_upload' === $action ) { $move_new_file = @move_uploaded_file( $file['tmp_name'], $new_file ); } else { // Use copy and unlink because rename breaks streams. // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged $move_new_file = @copy( $file['tmp_name'], $new_file ); unlink( $file['tmp_name'] ); } if ( false === $move_new_file ) { if ( str_starts_with( $uploads['basedir'], ABSPATH ) ) { $error_path = str_replace( ABSPATH, '', $uploads['basedir'] ) . $uploads['subdir']; } else { $error_path = basename( $uploads['basedir'] ) . $uploads['subdir']; } return $upload_error_handler( $file, sprintf( /* translators: %s: Destination file path. */ __( 'The uploaded file could not be moved to %s.' ), $error_path ) ); } } // Set correct file permissions. $stat = stat( dirname( $new_file ) ); $perms = $stat['mode'] & 0000666; chmod( $new_file, $perms ); // Compute the URL. $url = $uploads['url'] . "/$filename"; if ( is_multisite() ) { clean_dirsize_cache( $new_file ); } /** * Filters the data array for the uploaded file. * * @since 2.1.0 * * @param array $upload { * Array of upload data. * * @type string $file Filename of the newly-uploaded file. * @type string $url URL of the newly-uploaded file. * @type string $type Mime type of the newly-uploaded file. * } * @param string $context The type of upload action. Values include 'upload' or 'sideload'. */ return apply_filters( 'wp_handle_upload', array( 'file' => $new_file, 'url' => $url, 'type' => $type, ), 'wp_handle_sideload' === $action ? 'sideload' : 'upload' ); } /** * Wrapper for _wp_handle_upload(). * * Passes the {@see 'wp_handle_upload'} action. * * @since 2.0.0 * * @see _wp_handle_upload() * * @param array $file Reference to a single element of `$_FILES`. * Call the function once for each uploaded file. * See _wp_handle_upload() for accepted values. * @param array|false $overrides Optional. An associative array of names => values * to override default variables. Default false. * See _wp_handle_upload() for accepted values. * @param string|null $time Optional. Time formatted in 'yyyy/mm'. Default null. * @return array See _wp_handle_upload() for return value. */ function wp_handle_upload( &$file, $overrides = false, $time = null ) { /* * $_POST['action'] must be set and its value must equal $overrides['action'] * or this: */ $action = 'wp_handle_upload'; if ( isset( $overrides['action'] ) ) { $action = $overrides['action']; } return _wp_handle_upload( $file, $overrides, $time, $action ); } /** * Wrapper for _wp_handle_upload(). * * Passes the {@see 'wp_handle_sideload'} action. * * @since 2.6.0 * * @see _wp_handle_upload() * * @param array $file Reference to a single element of `$_FILES`. * Call the function once for each uploaded file. * See _wp_handle_upload() for accepted values. * @param array|false $overrides Optional. An associative array of names => values * to override default variables. Default false. * See _wp_handle_upload() for accepted values. * @param string|null $time Optional. Time formatted in 'yyyy/mm'. Default null. * @return array See _wp_handle_upload() for return value. */ function wp_handle_sideload( &$file, $overrides = false, $time = null ) { /* * $_POST['action'] must be set and its value must equal $overrides['action'] * or this: */ $action = 'wp_handle_sideload'; if ( isset( $overrides['action'] ) ) { $action = $overrides['action']; } return _wp_handle_upload( $file, $overrides, $time, $action ); } /** * Downloads a URL to a local temporary file using the WordPress HTTP API. * * Please note that the calling function must delete or move the file. * * @since 2.5.0 * @since 5.2.0 Signature Verification with SoftFail was added. * @since 5.9.0 Support for Content-Disposition filename was added. * * @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. * @param bool $signature_verification Whether to perform Signature Verification. * Default false. * @return string|WP_Error Filename on success, WP_Error on failure. */ function download_url( $url, $timeout = 300, $signature_verification = false ) { // WARNING: The file is not automatically deleted, the script must delete or move the file. if ( ! $url ) { return new WP_Error( 'http_no_url', __( 'No URL Provided.' ) ); } $url_path = parse_url( $url, PHP_URL_PATH ); $url_filename = ''; if ( is_string( $url_path ) && '' !== $url_path ) { $url_filename = basename( $url_path ); } $tmpfname = wp_tempnam( $url_filename ); 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; } $response_code = wp_remote_retrieve_response_code( $response ); if ( 200 !== $response_code ) { $data = array( 'code' => $response_code, ); // Retrieve a sample of the response body for debugging purposes. $tmpf = fopen( $tmpfname, 'rb' ); if ( $tmpf ) { /** * Filters the maximum error response body size in `download_url()`. * * @since 5.1.0 * * @see download_url() * * @param int $size The maximum error response body size. Default 1 KB. */ $response_size = apply_filters( 'download_url_error_max_body_size', KB_IN_BYTES ); $data['body'] = fread( $tmpf, $response_size ); fclose( $tmpf ); } unlink( $tmpfname ); return new WP_Error( 'http_404', trim( wp_remote_retrieve_response_message( $response ) ), $data ); } $content_disposition = wp_remote_retrieve_header( $response, 'Content-Disposition' ); if ( $content_disposition ) { $content_disposition = strtolower( $content_disposition ); if ( str_starts_with( $content_disposition, 'attachment; filename=' ) ) { $tmpfname_disposition = sanitize_file_name( substr( $content_disposition, 21 ) ); } else { $tmpfname_disposition = ''; } // Potential file name must be valid string. if ( $tmpfname_disposition && is_string( $tmpfname_disposition ) && ( 0 === validate_file( $tmpfname_disposition ) ) ) { $tmpfname_disposition = dirname( $tmpfname ) . '/' . $tmpfname_disposition; if ( rename( $tmpfname, $tmpfname_disposition ) ) { $tmpfname = $tmpfname_disposition; } if ( ( $tmpfname !== $tmpfname_disposition ) && file_exists( $tmpfname_disposition ) ) { unlink( $tmpfname_disposition ); } } } $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; } } // If the caller expects signature verification to occur, check to see if this URL supports it. if ( $signature_verification ) { /** * Filters the list of hosts which should have Signature Verification attempted on. * * @since 5.2.0 * * @param string[] $hostnames List of hostnames. */ $signed_hostnames = apply_filters( 'wp_signature_hosts', array( 'wordpress.org', 'downloads.wordpress.org', 's.w.org' ) ); $signature_verification = in_array( parse_url( $url, PHP_URL_HOST ), $signed_hostnames, true ); } // Perform signature validation if supported. if ( $signature_verification ) { $signature = wp_remote_retrieve_header( $response, 'X-Content-Signature' ); if ( ! $signature ) { /* * Retrieve signatures from a file if the header wasn't included. * WordPress.org stores signatures at $package_url.sig. */ $signature_url = false; if ( is_string( $url_path ) && ( str_ends_with( $url_path, '.zip' ) || str_ends_with( $url_path, '.tar.gz' ) ) ) { $signature_url = str_replace( $url_path, $url_path . '.sig', $url ); } /** * Filters the URL where the signature for a file is located. * * @since 5.2.0 * * @param false|string $signature_url The URL where signatures can be found for a file, or false if none are known. * @param string $url The URL being verified. */ $signature_url = apply_filters( 'wp_signature_url', $signature_url, $url ); if ( $signature_url ) { $signature_request = wp_safe_remote_get( $signature_url, array( 'limit_response_size' => 10 * KB_IN_BYTES, // 10KB should be large enough for quite a few signatures. ) ); if ( ! is_wp_error( $signature_request ) && 200 === wp_remote_retrieve_response_code( $signature_request ) ) { $signature = explode( "\n", wp_remote_retrieve_body( $signature_request ) ); } } } // Perform the checks. $signature_verification = verify_file_signature( $tmpfname, $signature, $url_filename ); } if ( is_wp_error( $signature_verification ) ) { if ( /** * Filters whether Signature Verification failures should be allowed to soft fail. * * WARNING: This may be removed from a future release. * * @since 5.2.0 * * @param bool $signature_softfail If a softfail is allowed. * @param string $url The url being accessed. */ apply_filters( 'wp_signature_softfail', true, $url ) ) { $signature_verification->add_data( $tmpfname, 'softfail-filename' ); } else { // Hard-fail. unlink( $tmpfname ); } return $signature_verification; } return $tmpfname; } /** * Calculates and compares the MD5 of a file to its expected value. * * @since 3.7.0 * * @param string $filename The filename to check the MD5 of. * @param string $expected_md5 The expected MD5 of the file, either a base64-encoded raw md5, * or a hex-encoded md5. * @return bool|WP_Error True on success, false when the MD5 format is unknown/unexpected, * WP_Error on failure. */ function verify_file_md5( $filename, $expected_md5 ) { if ( 32 === strlen( $expected_md5 ) ) { $expected_raw_md5 = pack( 'H*', $expected_md5 ); } elseif ( 24 === strlen( $expected_md5 ) ) { $expected_raw_md5 = base64_decode( $expected_md5 ); } else { return false; // Unknown format. } $file_md5 = md5_file( $filename, true ); if ( $file_md5 === $expected_raw_md5 ) { return true; } return new WP_Error( 'md5_mismatch', sprintf( /* translators: 1: File checksum, 2: Expected checksum value. */ __( 'The checksum of the file (%1$s) does not match the expected checksum value (%2$s).' ), bin2hex( $file_md5 ), bin2hex( $expected_raw_md5 ) ) ); } /** * Verifies the contents of a file against its ED25519 signature. * * @since 5.2.0 * * @param string $filename The file to validate. * @param string|array $signatures A Signature provided for the file. * @param string|false $filename_for_errors Optional. A friendly filename for errors. * @return bool|WP_Error True on success, false if verification not attempted, * or WP_Error describing an error condition. */ function verify_file_signature( $filename, $signatures, $filename_for_errors = false ) { if ( ! $filename_for_errors ) { $filename_for_errors = wp_basename( $filename ); } // Check we can process signatures. if ( ! function_exists( 'sodium_crypto_sign_verify_detached' ) || ! in_array( 'sha384', array_map( 'strtolower', hash_algos() ), true ) ) { return new WP_Error( 'signature_verification_unsupported', sprintf( /* translators: %s: The filename of the package. */ __( 'The authenticity of %s could not be verified as signature verification is unavailable on this system.' ), '' . esc_html( $filename_for_errors ) . '' ), ( ! function_exists( 'sodium_crypto_sign_verify_detached' ) ? 'sodium_crypto_sign_verify_detached' : 'sha384' ) ); } // Verify runtime speed of Sodium_Compat is acceptable. if ( ! extension_loaded( 'sodium' ) && ! ParagonIE_Sodium_Compat::polyfill_is_fast() ) { $sodium_compat_is_fast = false; // Allow for an old version of Sodium_Compat being loaded before the bundled WordPress one. if ( method_exists( 'ParagonIE_Sodium_Compat', 'runtime_speed_test' ) ) { /* * Run `ParagonIE_Sodium_Compat::runtime_speed_test()` in optimized integer mode, * as that's what WordPress utilizes during signing verifications. */ // phpcs:disable WordPress.NamingConventions.ValidVariableName $old_fastMult = ParagonIE_Sodium_Compat::$fastMult; ParagonIE_Sodium_Compat::$fastMult = true; $sodium_compat_is_fast = ParagonIE_Sodium_Compat::runtime_speed_test( 100, 10 ); ParagonIE_Sodium_Compat::$fastMult = $old_fastMult; // phpcs:enable } /* * This cannot be performed in a reasonable amount of time. * https://github.com/paragonie/sodium_compat#help-sodium_compat-is-slow-how-can-i-make-it-fast */ if ( ! $sodium_compat_is_fast ) { return new WP_Error( 'signature_verification_unsupported', sprintf( /* translators: %s: The filename of the package. */ __( 'The authenticity of %s could not be verified as signature verification is unavailable on this system.' ), '' . esc_html( $filename_for_errors ) . '' ), array( 'php' => PHP_VERSION, 'sodium' => defined( 'SODIUM_LIBRARY_VERSION' ) ? SODIUM_LIBRARY_VERSION : ( defined( 'ParagonIE_Sodium_Compat::VERSION_STRING' ) ? ParagonIE_Sodium_Compat::VERSION_STRING : false ), 'polyfill_is_fast' => false, 'max_execution_time' => ini_get( 'max_execution_time' ), ) ); } } if ( ! $signatures ) { return new WP_Error( 'signature_verification_no_signature', sprintf( /* translators: %s: The filename of the package. */ __( 'The authenticity of %s could not be verified as no signature was found.' ), '' . esc_html( $filename_for_errors ) . '' ), array( 'filename' => $filename_for_errors, ) ); } $trusted_keys = wp_trusted_keys(); $file_hash = hash_file( 'sha384', $filename, true ); mbstring_binary_safe_encoding(); $skipped_key = 0; $skipped_signature = 0; foreach ( (array) $signatures as $signature ) { $signature_raw = base64_decode( $signature ); // Ensure only valid-length signatures are considered. if ( SODIUM_CRYPTO_SIGN_BYTES !== strlen( $signature_raw ) ) { ++$skipped_signature; continue; } foreach ( (array) $trusted_keys as $key ) { $key_raw = base64_decode( $key ); // Only pass valid public keys through. if ( SODIUM_CRYPTO_SIGN_PUBLICKEYBYTES !== strlen( $key_raw ) ) { ++$skipped_key; continue; } if ( sodium_crypto_sign_verify_detached( $signature_raw, $file_hash, $key_raw ) ) { reset_mbstring_encoding(); return true; } } } reset_mbstring_encoding(); return new WP_Error( 'signature_verification_failed', sprintf( /* translators: %s: The filename of the package. */ __( 'The authenticity of %s could not be verified.' ), '' . esc_html( $filename_for_errors ) . '' ), // Error data helpful for debugging: array( 'filename' => $filename_for_errors, 'keys' => $trusted_keys, 'signatures' => $signatures, 'hash' => bin2hex( $file_hash ), 'skipped_key' => $skipped_key, 'skipped_sig' => $skipped_signature, 'php' => PHP_VERSION, 'sodium' => defined( 'SODIUM_LIBRARY_VERSION' ) ? SODIUM_LIBRARY_VERSION : ( defined( 'ParagonIE_Sodium_Compat::VERSION_STRING' ) ? ParagonIE_Sodium_Compat::VERSION_STRING : false ), ) ); } /** * Retrieves the list of signing keys trusted by WordPress. * * @since 5.2.0 * * @return string[] Array of base64-encoded signing keys. */ function wp_trusted_keys() { $trusted_keys = array(); if ( time() < 1617235200 ) { // WordPress.org Key #1 - This key is only valid before April 1st, 2021. $trusted_keys[] = 'fRPyrxb/MvVLbdsYi+OOEv4xc+Eqpsj+kkAS6gNOkI0='; } // TODO: Add key #2 with longer expiration. /** * Filters the valid signing keys used to verify the contents of files. * * @since 5.2.0 * * @param string[] $trusted_keys The trusted keys that may sign packages. */ return apply_filters( 'wp_trusted_keys', $trusted_keys ); } /** * Determines whether the given file is a valid ZIP file. * * This function does not test to ensure that a file exists. Non-existent files * are not valid ZIPs, so those will also return false. * * @since 6.4.4 * * @param string $file Full path to the ZIP file. * @return bool Whether the file is a valid ZIP file. */ function wp_zip_file_is_valid( $file ) { /** This filter is documented in wp-admin/includes/file.php */ if ( class_exists( 'ZipArchive', false ) && apply_filters( 'unzip_file_use_ziparchive', true ) ) { $archive = new ZipArchive(); $archive_is_valid = $archive->open( $file, ZipArchive::CHECKCONS ); if ( true === $archive_is_valid ) { $archive->close(); return true; } } // Fall through to PclZip if ZipArchive is not available, or encountered an error opening the file. require_once ABSPATH . 'wp-admin/includes/class-pclzip.php'; $archive = new PclZip( $file ); $archive_is_valid = is_array( $archive->properties() ); return $archive_is_valid; } /** * Unzips a specified ZIP file to a location on the filesystem via the WordPress * Filesystem Abstraction. * * Assumes that WP_Filesystem() has already been called and set up. Does not extract * a root-level __MACOSX directory, if present. * * Attempts to increase the PHP memory limit to 256M before uncompressing. However, * the most memory required shouldn't be much larger than the archive itself. * * @since 2.5.0 * * @global WP_Filesystem_Base $wp_filesystem WordPress filesystem subclass. * * @param string $file Full path and filename of ZIP archive. * @param string $to Full path on the filesystem to extract archive to. * @return true|WP_Error True on success, WP_Error on failure. */ function unzip_file( $file, $to ) { global $wp_filesystem; if ( ! $wp_filesystem || ! is_object( $wp_filesystem ) ) { return new WP_Error( 'fs_unavailable', __( 'Could not access filesystem.' ) ); } // Unzip can use a lot of memory, but not this much hopefully. wp_raise_memory_limit( 'admin' ); $needed_dirs = array(); $to = trailingslashit( $to ); // Determine any parent directories needed (of the upgrade directory). if ( ! $wp_filesystem->is_dir( $to ) ) { // Only do parents if no children exist. $path = preg_split( '![/\\\]!', untrailingslashit( $to ) ); for ( $i = count( $path ); $i >= 0; $i-- ) { if ( empty( $path[ $i ] ) ) { continue; } $dir = implode( '/', array_slice( $path, 0, $i + 1 ) ); if ( preg_match( '!^[a-z]:$!i', $dir ) ) { // Skip it if it looks like a Windows Drive letter. continue; } if ( ! $wp_filesystem->is_dir( $dir ) ) { $needed_dirs[] = $dir; } else { break; // A folder exists, therefore we don't need to check the levels below this. } } } /** * Filters whether to use ZipArchive to unzip archives. * * @since 3.0.0 * * @param bool $ziparchive Whether to use ZipArchive. Default true. */ if ( class_exists( 'ZipArchive', false ) && apply_filters( 'unzip_file_use_ziparchive', true ) ) { $result = _unzip_file_ziparchive( $file, $to, $needed_dirs ); if ( true === $result ) { return $result; } elseif ( is_wp_error( $result ) ) { if ( 'incompatible_archive' !== $result->get_error_code() ) { return $result; } } } // Fall through to PclZip if ZipArchive is not available, or encountered an error opening the file. return _unzip_file_pclzip( $file, $to, $needed_dirs ); } /** * Attempts to unzip an archive using the ZipArchive class. * * This function should not be called directly, use `unzip_file()` instead. * * Assumes that WP_Filesystem() has already been called and set up. * * @since 3.0.0 * @access private * * @see unzip_file() * * @global WP_Filesystem_Base $wp_filesystem WordPress filesystem subclass. * * @param string $file Full path and filename of ZIP archive. * @param string $to Full path on the filesystem to extract archive to. * @param string[] $needed_dirs A partial list of required folders needed to be created. * @return true|WP_Error True on success, WP_Error on failure. */ function _unzip_file_ziparchive( $file, $to, $needed_dirs = array() ) { global $wp_filesystem; $z = new ZipArchive(); $zopen = $z->open( $file, ZIPARCHIVE::CHECKCONS ); if ( true !== $zopen ) { return new WP_Error( 'incompatible_archive', __( 'Incompatible Archive.' ), array( 'ziparchive_error' => $zopen ) ); } $uncompressed_size = 0; for ( $i = 0; $i < $z->numFiles; $i++ ) { $info = $z->statIndex( $i ); if ( ! $info ) { $z->close(); return new WP_Error( 'stat_failed_ziparchive', __( 'Could not retrieve file from archive.' ) ); } if ( str_starts_with( $info['name'], '__MACOSX/' ) ) { // Skip the OS X-created __MACOSX directory. continue; } // Don't extract invalid files: if ( 0 !== validate_file( $info['name'] ) ) { continue; } $uncompressed_size += $info['size']; $dirname = dirname( $info['name'] ); if ( str_ends_with( $info['name'], '/' ) ) { // Directory. $needed_dirs[] = $to . untrailingslashit( $info['name'] ); } elseif ( '.' !== $dirname ) { // Path to a file. $needed_dirs[] = $to . untrailingslashit( $dirname ); } } // Enough space to unzip the file and copy its contents, with a 10% buffer. $required_space = $uncompressed_size * 2.1; /* * disk_free_space() could return false. Assume that any falsey value is an error. * A disk that has zero free bytes has bigger problems. * Require we have enough space to unzip the file and copy its contents, with a 10% buffer. */ if ( wp_doing_cron() ) { $available_space = function_exists( 'disk_free_space' ) ? @disk_free_space( WP_CONTENT_DIR ) : false; if ( $available_space && ( $required_space > $available_space ) ) { $z->close(); return new WP_Error( 'disk_full_unzip_file', __( 'Could not copy files. You may have run out of disk space.' ), compact( 'uncompressed_size', 'available_space' ) ); } } $needed_dirs = array_unique( $needed_dirs ); foreach ( $needed_dirs as $dir ) { // Check the parent folders of the folders all exist within the creation array. if ( untrailingslashit( $to ) === $dir ) { // Skip over the working directory, we know this exists (or will exist). continue; } if ( ! str_contains( $dir, $to ) ) { // If the directory is not within the working directory, skip it. continue; } $parent_folder = dirname( $dir ); while ( ! empty( $parent_folder ) && untrailingslashit( $to ) !== $parent_folder && ! in_array( $parent_folder, $needed_dirs, true ) ) { $needed_dirs[] = $parent_folder; $parent_folder = dirname( $parent_folder ); } } asort( $needed_dirs ); // Create those directories if need be: foreach ( $needed_dirs as $_dir ) { // Only check to see if the Dir exists upon creation failure. Less I/O this way. if ( ! $wp_filesystem->mkdir( $_dir, FS_CHMOD_DIR ) && ! $wp_filesystem->is_dir( $_dir ) ) { $z->close(); return new WP_Error( 'mkdir_failed_ziparchive', __( 'Could not create directory.' ), $_dir ); } } /** * Filters archive unzipping to override with a custom process. * * @since 6.4.0 * * @param null|true|WP_Error $result The result of the override. True on success, otherwise WP Error. Default null. * @param string $file Full path and filename of ZIP archive. * @param string $to Full path on the filesystem to extract archive to. * @param string[] $needed_dirs A full list of required folders that need to be created. * @param float $required_space The space required to unzip the file and copy its contents, with a 10% buffer. */ $pre = apply_filters( 'pre_unzip_file', null, $file, $to, $needed_dirs, $required_space ); if ( null !== $pre ) { // Ensure the ZIP file archive has been closed. $z->close(); return $pre; } for ( $i = 0; $i < $z->numFiles; $i++ ) { $info = $z->statIndex( $i ); if ( ! $info ) { $z->close(); return new WP_Error( 'stat_failed_ziparchive', __( 'Could not retrieve file from archive.' ) ); } if ( str_ends_with( $info['name'], '/' ) ) { // Directory. continue; } if ( str_starts_with( $info['name'], '__MACOSX/' ) ) { // Don't extract the OS X-created __MACOSX directory files. continue; } // Don't extract invalid files: if ( 0 !== validate_file( $info['name'] ) ) { continue; } $contents = $z->getFromIndex( $i ); if ( false === $contents ) { $z->close(); return new WP_Error( 'extract_failed_ziparchive', __( 'Could not extract file from archive.' ), $info['name'] ); } if ( ! $wp_filesystem->put_contents( $to . $info['name'], $contents, FS_CHMOD_FILE ) ) { $z->close(); return new WP_Error( 'copy_failed_ziparchive', __( 'Could not copy file.' ), $info['name'] ); } } $z->close(); /** * Filters the result of unzipping an archive. * * @since 6.4.0 * * @param true|WP_Error $result The result of unzipping the archive. True on success, otherwise WP_Error. Default true. * @param string $file Full path and filename of ZIP archive. * @param string $to Full path on the filesystem the archive was extracted to. * @param string[] $needed_dirs A full list of required folders that were created. * @param float $required_space The space required to unzip the file and copy its contents, with a 10% buffer. */ $result = apply_filters( 'unzip_file', true, $file, $to, $needed_dirs, $required_space ); unset( $needed_dirs ); return $result; } /** * Attempts to unzip an archive using the PclZip library. * * This function should not be called directly, use `unzip_file()` instead. * * Assumes that WP_Filesystem() has already been called and set up. * * @since 3.0.0 * @access private * * @see unzip_file() * * @global WP_Filesystem_Base $wp_filesystem WordPress filesystem subclass. * * @param string $file Full path and filename of ZIP archive. * @param string $to Full path on the filesystem to extract archive to. * @param string[] $needed_dirs A partial list of required folders needed to be created. * @return true|WP_Error True on success, WP_Error on failure. */ function _unzip_file_pclzip( $file, $to, $needed_dirs = array() ) { global $wp_filesystem; mbstring_binary_safe_encoding(); require_once ABSPATH . 'wp-admin/includes/class-pclzip.php'; $archive = new PclZip( $file ); $archive_files = $archive->extract( PCLZIP_OPT_EXTRACT_AS_STRING ); reset_mbstring_encoding(); // Is the archive valid? if ( ! is_array( $archive_files ) ) { return new WP_Error( 'incompatible_archive', __( 'Incompatible Archive.' ), $archive->errorInfo( true ) ); } if ( 0 === count( $archive_files ) ) { return new WP_Error( 'empty_archive_pclzip', __( 'Empty archive.' ) ); } $uncompressed_size = 0; // Determine any children directories needed (From within the archive). foreach ( $archive_files as $file ) { if ( str_starts_with( $file['filename'], '__MACOSX/' ) ) { // Skip the OS X-created __MACOSX directory. continue; } $uncompressed_size += $file['size']; $needed_dirs[] = $to . untrailingslashit( $file['folder'] ? $file['filename'] : dirname( $file['filename'] ) ); } // Enough space to unzip the file and copy its contents, with a 10% buffer. $required_space = $uncompressed_size * 2.1; /* * disk_free_space() could return false. Assume that any falsey value is an error. * A disk that has zero free bytes has bigger problems. * Require we have enough space to unzip the file and copy its contents, with a 10% buffer. */ if ( wp_doing_cron() ) { $available_space = function_exists( 'disk_free_space' ) ? @disk_free_space( WP_CONTENT_DIR ) : false; if ( $available_space && ( $required_space > $available_space ) ) { return new WP_Error( 'disk_full_unzip_file', __( 'Could not copy files. You may have run out of disk space.' ), compact( 'uncompressed_size', 'available_space' ) ); } } $needed_dirs = array_unique( $needed_dirs ); foreach ( $needed_dirs as $dir ) { // Check the parent folders of the folders all exist within the creation array. if ( untrailingslashit( $to ) === $dir ) { // Skip over the working directory, we know this exists (or will exist). continue; } if ( ! str_contains( $dir, $to ) ) { // If the directory is not within the working directory, skip it. continue; } $parent_folder = dirname( $dir ); while ( ! empty( $parent_folder ) && untrailingslashit( $to ) !== $parent_folder && ! in_array( $parent_folder, $needed_dirs, true ) ) { $needed_dirs[] = $parent_folder; $parent_folder = dirname( $parent_folder ); } } asort( $needed_dirs ); // Create those directories if need be: foreach ( $needed_dirs as $_dir ) { // Only check to see if the dir exists upon creation failure. Less I/O this way. if ( ! $wp_filesystem->mkdir( $_dir, FS_CHMOD_DIR ) && ! $wp_filesystem->is_dir( $_dir ) ) { return new WP_Error( 'mkdir_failed_pclzip', __( 'Could not create directory.' ), $_dir ); } } /** This filter is documented in src/wp-admin/includes/file.php */ $pre = apply_filters( 'pre_unzip_file', null, $file, $to, $needed_dirs, $required_space ); if ( null !== $pre ) { return $pre; } // Extract the files from the zip. foreach ( $archive_files as $file ) { if ( $file['folder'] ) { continue; } if ( str_starts_with( $file['filename'], '__MACOSX/' ) ) { // Don't extract the OS X-created __MACOSX directory files. continue; } // Don't extract invalid files: if ( 0 !== validate_file( $file['filename'] ) ) { continue; } if ( ! $wp_filesystem->put_contents( $to . $file['filename'], $file['content'], FS_CHMOD_FILE ) ) { return new WP_Error( 'copy_failed_pclzip', __( 'Could not copy file.' ), $file['filename'] ); } } /** This action is documented in src/wp-admin/includes/file.php */ $result = apply_filters( 'unzip_file', true, $file, $to, $needed_dirs, $required_space ); unset( $needed_dirs ); return $result; } /** * Copies a directory from one location to another via the WordPress Filesystem * Abstraction. * * Assumes that WP_Filesystem() has already been called and setup. * * @since 2.5.0 * * @global WP_Filesystem_Base $wp_filesystem WordPress filesystem subclass. * * @param string $from Source directory. * @param string $to Destination directory. * @param string[] $skip_list An array of files/folders to skip copying. * @return true|WP_Error True on success, WP_Error on failure. */ function copy_dir( $from, $to, $skip_list = array() ) { global $wp_filesystem; $dirlist = $wp_filesystem->dirlist( $from ); if ( false === $dirlist ) { return new WP_Error( 'dirlist_failed_copy_dir', __( 'Directory listing failed.' ), basename( $from ) ); } $from = trailingslashit( $from ); $to = trailingslashit( $to ); if ( ! $wp_filesystem->exists( $to ) && ! $wp_filesystem->mkdir( $to ) ) { return new WP_Error( 'mkdir_destination_failed_copy_dir', __( 'Could not create the destination directory.' ), basename( $to ) ); } foreach ( (array) $dirlist as $filename => $fileinfo ) { if ( in_array( $filename, $skip_list, true ) ) { continue; } if ( 'f' === $fileinfo['type'] ) { if ( ! $wp_filesystem->copy( $from . $filename, $to . $filename, true, FS_CHMOD_FILE ) ) { // If copy failed, chmod file to 0644 and try again. $wp_filesystem->chmod( $to . $filename, FS_CHMOD_FILE ); if ( ! $wp_filesystem->copy( $from . $filename, $to . $filename, true, FS_CHMOD_FILE ) ) { return new WP_Error( 'copy_failed_copy_dir', __( 'Could not copy file.' ), $to . $filename ); } } wp_opcache_invalidate( $to . $filename ); } elseif ( 'd' === $fileinfo['type'] ) { if ( ! $wp_filesystem->is_dir( $to . $filename ) ) { if ( ! $wp_filesystem->mkdir( $to . $filename, FS_CHMOD_DIR ) ) { return new WP_Error( 'mkdir_failed_copy_dir', __( 'Could not create directory.' ), $to . $filename ); } } // Generate the $sub_skip_list for the subdirectory as a sub-set of the existing $skip_list. $sub_skip_list = array(); foreach ( $skip_list as $skip_item ) { if ( str_starts_with( $skip_item, $filename . '/' ) ) { $sub_skip_list[] = preg_replace( '!^' . preg_quote( $filename, '!' ) . '/!i', '', $skip_item ); } } $result = copy_dir( $from . $filename, $to . $filename, $sub_skip_list ); if ( is_wp_error( $result ) ) { return $result; } } } return true; } /** * Moves a directory from one location to another. * * Recursively invalidates OPcache on success. * * If the renaming failed, falls back to copy_dir(). * * Assumes that WP_Filesystem() has already been called and setup. * * This function is not designed to merge directories, copy_dir() should be used instead. * * @since 6.2.0 * * @global WP_Filesystem_Base $wp_filesystem WordPress filesystem subclass. * * @param string $from Source directory. * @param string $to Destination directory. * @param bool $overwrite Optional. Whether to overwrite the destination directory if it exists. * Default false. * @return true|WP_Error True on success, WP_Error on failure. */ function move_dir( $from, $to, $overwrite = false ) { global $wp_filesystem; if ( trailingslashit( strtolower( $from ) ) === trailingslashit( strtolower( $to ) ) ) { return new WP_Error( 'source_destination_same_move_dir', __( 'The source and destination are the same.' ) ); } if ( $wp_filesystem->exists( $to ) ) { if ( ! $overwrite ) { return new WP_Error( 'destination_already_exists_move_dir', __( 'The destination folder already exists.' ), $to ); } elseif ( ! $wp_filesystem->delete( $to, true ) ) { // Can't overwrite if the destination couldn't be deleted. return new WP_Error( 'destination_not_deleted_move_dir', __( 'The destination directory already exists and could not be removed.' ) ); } } if ( $wp_filesystem->move( $from, $to ) ) { /* * When using an environment with shared folders, * there is a delay in updating the filesystem's cache. * * This is a known issue in environments with a VirtualBox provider. * * A 200ms delay gives time for the filesystem to update its cache, * prevents "Operation not permitted", and "No such file or directory" warnings. * * This delay is used in other projects, including Composer. * @link https://github.com/composer/composer/blob/2.5.1/src/Composer/Util/Platform.php#L228-L233 */ usleep( 200000 ); wp_opcache_invalidate_directory( $to ); return true; } // Fall back to a recursive copy. if ( ! $wp_filesystem->is_dir( $to ) ) { if ( ! $wp_filesystem->mkdir( $to, FS_CHMOD_DIR ) ) { return new WP_Error( 'mkdir_failed_move_dir', __( 'Could not create directory.' ), $to ); } } $result = copy_dir( $from, $to, array( basename( $to ) ) ); // Clear the source directory. if ( true === $result ) { $wp_filesystem->delete( $from, true ); } return $result; } /** * Initializes and connects the WordPress Filesystem Abstraction classes. * * This function will include the chosen transport and attempt connecting. * * Plugins may add extra transports, And force WordPress to use them by returning * the filename via the {@see 'filesystem_method_file'} filter. * * @since 2.5.0 * * @global WP_Filesystem_Base $wp_filesystem WordPress filesystem subclass. * * @param array|false $args Optional. Connection args, These are passed * directly to the `WP_Filesystem_*()` classes. * Default false. * @param string|false $context Optional. Context for get_filesystem_method(). * Default false. * @param bool $allow_relaxed_file_ownership Optional. Whether to allow Group/World writable. * Default false. * @return bool|null True on success, false on failure, * null if the filesystem method class file does not exist. */ function WP_Filesystem( $args = false, $context = false, $allow_relaxed_file_ownership = false ) { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.FunctionNameInvalid global $wp_filesystem; require_once ABSPATH . 'wp-admin/includes/class-wp-filesystem-base.php'; $method = get_filesystem_method( $args, $context, $allow_relaxed_file_ownership ); if ( ! $method ) { return false; } if ( ! class_exists( "WP_Filesystem_$method" ) ) { /** * Filters the path for a specific filesystem method class file. * * @since 2.6.0 * * @see get_filesystem_method() * * @param string $path Path to the specific filesystem method class file. * @param string $method The filesystem method to use. */ $abstraction_file = apply_filters( 'filesystem_method_file', ABSPATH . 'wp-admin/includes/class-wp-filesystem-' . $method . '.php', $method ); if ( ! file_exists( $abstraction_file ) ) { return; } require_once $abstraction_file; } $method = "WP_Filesystem_$method"; $wp_filesystem = new $method( $args ); /* * Define the timeouts for the connections. Only available after the constructor is called * to allow for per-transport overriding of the default. */ if ( ! defined( 'FS_CONNECT_TIMEOUT' ) ) { define( 'FS_CONNECT_TIMEOUT', 30 ); // 30 seconds. } if ( ! defined( 'FS_TIMEOUT' ) ) { define( 'FS_TIMEOUT', 30 ); // 30 seconds. } if ( is_wp_error( $wp_filesystem->errors ) && $wp_filesystem->errors->has_errors() ) { return false; } if ( ! $wp_filesystem->connect() ) { return false; // There was an error connecting to the server. } // Set the permission constants if not already set. if ( ! defined( 'FS_CHMOD_DIR' ) ) { define( 'FS_CHMOD_DIR', ( fileperms( ABSPATH ) & 0777 | 0755 ) ); } if ( ! defined( 'FS_CHMOD_FILE' ) ) { define( 'FS_CHMOD_FILE', ( fileperms( ABSPATH . 'index.php' ) & 0777 | 0644 ) ); } return true; } /** * Determines which method to use for reading, writing, modifying, or deleting * files on the filesystem. * * The priority of the transports are: Direct, SSH2, FTP PHP Extension, FTP Sockets * (Via Sockets class, or `fsockopen()`). Valid values for these are: 'direct', 'ssh2', * 'ftpext' or 'ftpsockets'. * * The return value can be overridden by defining the `FS_METHOD` constant in `wp-config.php`, * or filtering via {@see 'filesystem_method'}. * * @link https://developer.wordpress.org/advanced-administration/wordpress/wp-config/#wordpress-upgrade-constants * * Plugins may define a custom transport handler, See WP_Filesystem(). * * @since 2.5.0 * * @global callable $_wp_filesystem_direct_method * * @param array $args Optional. Connection details. Default empty array. * @param string $context Optional. Full path to the directory that is tested * for being writable. Default empty. * @param bool $allow_relaxed_file_ownership Optional. Whether to allow Group/World writable. * Default false. * @return string The transport to use, see description for valid return values. */ function get_filesystem_method( $args = array(), $context = '', $allow_relaxed_file_ownership = false ) { // Please ensure that this is either 'direct', 'ssh2', 'ftpext', or 'ftpsockets'. $method = defined( 'FS_METHOD' ) ? FS_METHOD : false; if ( ! $context ) { $context = WP_CONTENT_DIR; } // If the directory doesn't exist (wp-content/languages) then use the parent directory as we'll create it. if ( WP_LANG_DIR === $context && ! is_dir( $context ) ) { $context = dirname( $context ); } $context = trailingslashit( $context ); if ( ! $method ) { $temp_file_name = $context . 'temp-write-test-' . str_replace( '.', '-', uniqid( '', true ) ); $temp_handle = @fopen( $temp_file_name, 'w' ); if ( $temp_handle ) { // Attempt to determine the file owner of the WordPress files, and that of newly created files. $wp_file_owner = false; $temp_file_owner = false; if ( function_exists( 'fileowner' ) ) { $wp_file_owner = @fileowner( __FILE__ ); $temp_file_owner = @fileowner( $temp_file_name ); } if ( false !== $wp_file_owner && $wp_file_owner === $temp_file_owner ) { /* * WordPress is creating files as the same owner as the WordPress files, * this means it's safe to modify & create new files via PHP. */ $method = 'direct'; $GLOBALS['_wp_filesystem_direct_method'] = 'file_owner'; } elseif ( $allow_relaxed_file_ownership ) { /* * The $context directory is writable, and $allow_relaxed_file_ownership is set, * this means we can modify files safely in this directory. * This mode doesn't create new files, only alter existing ones. */ $method = 'direct'; $GLOBALS['_wp_filesystem_direct_method'] = 'relaxed_ownership'; } fclose( $temp_handle ); @unlink( $temp_file_name ); } } if ( ! $method && isset( $args['connection_type'] ) && 'ssh' === $args['connection_type'] && extension_loaded( 'ssh2' ) ) { $method = 'ssh2'; } if ( ! $method && extension_loaded( 'ftp' ) ) { $method = 'ftpext'; } if ( ! $method && ( extension_loaded( 'sockets' ) || function_exists( 'fsockopen' ) ) ) { $method = 'ftpsockets'; // Sockets: Socket extension; PHP Mode: FSockopen / fwrite / fread. } /** * Filters the filesystem method to use. * * @since 2.6.0 * * @param string $method Filesystem method to return. * @param array $args An array of connection details for the method. * @param string $context Full path to the directory that is tested for being writable. * @param bool $allow_relaxed_file_ownership Whether to allow Group/World writable. */ return apply_filters( 'filesystem_method', $method, $args, $context, $allow_relaxed_file_ownership ); } /** * Displays a form to the user to request for their FTP/SSH details in order * to connect to the filesystem. * * All chosen/entered details are saved, excluding the password. * * Hostnames may be in the form of hostname:portnumber (eg: wordpress.org:2467) * to specify an alternate FTP/SSH port. * * Plugins may override this form by returning true|false via the {@see 'request_filesystem_credentials'} filter. * * @since 2.5.0 * @since 4.6.0 The `$context` parameter default changed from `false` to an empty string. * * @global string $pagenow The filename of the current screen. * * @param string $form_post The URL to post the form to. * @param string $type Optional. Chosen type of filesystem. Default empty. * @param bool|WP_Error $error Optional. Whether the current request has failed * to connect, or an error object. Default false. * @param string $context Optional. Full path to the directory that is tested * for being writable. Default empty. * @param array $extra_fields Optional. Extra `POST` fields to be checked * for inclusion in the post. Default null. * @param bool $allow_relaxed_file_ownership Optional. Whether to allow Group/World writable. * Default false. * @return bool|array True if no filesystem credentials are required, * false if they are required but have not been provided, * array of credentials if they are required and have been provided. */ function request_filesystem_credentials( $form_post, $type = '', $error = false, $context = '', $extra_fields = null, $allow_relaxed_file_ownership = false ) { global $pagenow; /** * Filters the filesystem credentials. * * Returning anything other than an empty string will effectively short-circuit * output of the filesystem credentials form, returning that value instead. * * A filter should return true if no filesystem credentials are required, false if they are required but have not been * provided, or an array of credentials if they are required and have been provided. * * @since 2.5.0 * @since 4.6.0 The `$context` parameter default changed from `false` to an empty string. * * @param mixed $credentials Credentials to return instead. Default empty string. * @param string $form_post The URL to post the form to. * @param string $type Chosen type of filesystem. * @param bool|WP_Error $error Whether the current request has failed to connect, * or an error object. * @param string $context Full path to the directory that is tested for * being writable. * @param array $extra_fields Extra POST fields. * @param bool $allow_relaxed_file_ownership Whether to allow Group/World writable. */ $req_cred = apply_filters( 'request_filesystem_credentials', '', $form_post, $type, $error, $context, $extra_fields, $allow_relaxed_file_ownership ); if ( '' !== $req_cred ) { return $req_cred; } if ( empty( $type ) ) { $type = get_filesystem_method( array(), $context, $allow_relaxed_file_ownership ); } if ( 'direct' === $type ) { return true; } if ( is_null( $extra_fields ) ) { $extra_fields = array( 'version', 'locale' ); } $credentials = get_option( 'ftp_credentials', array( 'hostname' => '', 'username' => '', ) ); $submitted_form = wp_unslash( $_POST ); // Verify nonce, or unset submitted form field values on failure. if ( ! isset( $_POST['_fs_nonce'] ) || ! wp_verify_nonce( $_POST['_fs_nonce'], 'filesystem-credentials' ) ) { unset( $submitted_form['hostname'], $submitted_form['username'], $submitted_form['password'], $submitted_form['public_key'], $submitted_form['private_key'], $submitted_form['connection_type'] ); } $ftp_constants = array( 'hostname' => 'FTP_HOST', 'username' => 'FTP_USER', 'password' => 'FTP_PASS', 'public_key' => 'FTP_PUBKEY', 'private_key' => 'FTP_PRIKEY', ); /* * If defined, set it to that. Else, if POST'd, set it to that. If not, set it to an empty string. * Otherwise, keep it as it previously was (saved details in option). */ foreach ( $ftp_constants as $key => $constant ) { if ( defined( $constant ) ) { $credentials[ $key ] = constant( $constant ); } elseif ( ! empty( $submitted_form[ $key ] ) ) { $credentials[ $key ] = $submitted_form[ $key ]; } elseif ( ! isset( $credentials[ $key ] ) ) { $credentials[ $key ] = ''; } } // Sanitize the hostname, some people might pass in odd data. $credentials['hostname'] = preg_replace( '|\w+://|', '', $credentials['hostname'] ); // Strip any schemes off. if ( strpos( $credentials['hostname'], ':' ) ) { list( $credentials['hostname'], $credentials['port'] ) = explode( ':', $credentials['hostname'], 2 ); if ( ! is_numeric( $credentials['port'] ) ) { unset( $credentials['port'] ); } } else { unset( $credentials['port'] ); } if ( ( defined( 'FTP_SSH' ) && FTP_SSH ) || ( defined( 'FS_METHOD' ) && 'ssh2' === FS_METHOD ) ) { $credentials['connection_type'] = 'ssh'; } elseif ( ( defined( 'FTP_SSL' ) && FTP_SSL ) && 'ftpext' === $type ) { // Only the FTP Extension understands SSL. $credentials['connection_type'] = 'ftps'; } elseif ( ! empty( $submitted_form['connection_type'] ) ) { $credentials['connection_type'] = $submitted_form['connection_type']; } elseif ( ! isset( $credentials['connection_type'] ) ) { // All else fails (and it's not defaulted to something else saved), default to FTP. $credentials['connection_type'] = 'ftp'; } if ( ! $error && ( ! empty( $credentials['hostname'] ) && ! empty( $credentials['username'] ) && ! empty( $credentials['password'] ) || 'ssh' === $credentials['connection_type'] && ! empty( $credentials['public_key'] ) && ! empty( $credentials['private_key'] ) ) ) { $stored_credentials = $credentials; if ( ! empty( $stored_credentials['port'] ) ) { // Save port as part of hostname to simplify above code. $stored_credentials['hostname'] .= ':' . $stored_credentials['port']; } unset( $stored_credentials['password'], $stored_credentials['port'], $stored_credentials['private_key'], $stored_credentials['public_key'] ); if ( ! wp_installing() ) { update_option( 'ftp_credentials', $stored_credentials, false ); } return $credentials; } $hostname = isset( $credentials['hostname'] ) ? $credentials['hostname'] : ''; $username = isset( $credentials['username'] ) ? $credentials['username'] : ''; $public_key = isset( $credentials['public_key'] ) ? $credentials['public_key'] : ''; $private_key = isset( $credentials['private_key'] ) ? $credentials['private_key'] : ''; $port = isset( $credentials['port'] ) ? $credentials['port'] : ''; $connection_type = isset( $credentials['connection_type'] ) ? $credentials['connection_type'] : ''; if ( $error ) { $error_string = __( 'Error: Could not connect to the server. Please verify the settings are correct.' ); if ( is_wp_error( $error ) ) { $error_string = esc_html( $error->get_error_message() ); } wp_admin_notice( $error_string, array( 'id' => 'message', 'additional_classes' => array( 'error' ), ) ); } $types = array(); if ( extension_loaded( 'ftp' ) || extension_loaded( 'sockets' ) || function_exists( 'fsockopen' ) ) { $types['ftp'] = __( 'FTP' ); } if ( extension_loaded( 'ftp' ) ) { // Only this supports FTPS. $types['ftps'] = __( 'FTPS (SSL)' ); } if ( extension_loaded( 'ssh2' ) ) { $types['ssh'] = __( 'SSH2' ); } /** * Filters the connection types to output to the filesystem credentials form. * * @since 2.9.0 * @since 4.6.0 The `$context` parameter default changed from `false` to an empty string. * * @param string[] $types Types of connections. * @param array $credentials Credentials to connect with. * @param string $type Chosen filesystem method. * @param bool|WP_Error $error Whether the current request has failed to connect, * or an error object. * @param string $context Full path to the directory that is tested for being writable. */ $types = apply_filters( 'fs_ftp_connection_types', $types, $credentials, $type, $error, $context ); ?>
    " . __( 'Connection Information' ) . ""; ?>

    $text ) : ?>
    >

    '; } } /* * Make sure the `submit_button()` function is available during the REST API call * from WP_Site_Health_Auto_Updates::test_check_wp_filesystem_method(). */ if ( ! function_exists( 'submit_button' ) ) { require_once ABSPATH . 'wp-admin/includes/template.php'; } ?>

    wp_opcache_invalidate_directory()' ); wp_trigger_error( '', $error_message ); } return; } $dirlist = $wp_filesystem->dirlist( $dir, false, true ); if ( empty( $dirlist ) ) { return; } /* * Recursively invalidate opcache of files in a directory. * * WP_Filesystem_*::dirlist() returns an array of file and directory information. * * This does not include a path to the file or directory. * To invalidate files within sub-directories, recursion is needed * to prepend an absolute path containing the sub-directory's name. * * @param array $dirlist Array of file/directory information from WP_Filesystem_Base::dirlist(), * with sub-directories represented as nested arrays. * @param string $path Absolute path to the directory. */ $invalidate_directory = static function ( $dirlist, $path ) use ( &$invalidate_directory ) { $path = trailingslashit( $path ); foreach ( $dirlist as $name => $details ) { if ( 'f' === $details['type'] ) { wp_opcache_invalidate( $path . $name, true ); } elseif ( is_array( $details['files'] ) && ! empty( $details['files'] ) ) { $invalidate_directory( $details['files'], $path . $name ); } } }; $invalidate_directory( $dirlist, $dir ); } class-wp-privacy-requests-table.php000064400000033226147206365750013444 0ustar00 '', 'email' => __( 'Requester' ), 'status' => __( 'Status' ), 'created_timestamp' => __( 'Requested' ), 'next_steps' => __( 'Next steps' ), ); return $columns; } /** * Normalizes the admin URL to the current page (by request_type). * * @since 5.3.0 * * @return string URL to the current admin page. */ protected function get_admin_url() { $pagenow = str_replace( '_', '-', $this->request_type ); if ( 'remove-personal-data' === $pagenow ) { $pagenow = 'erase-personal-data'; } return admin_url( $pagenow . '.php' ); } /** * Gets a list of sortable columns. * * @since 4.9.6 * * @return array Default sortable columns. */ protected function get_sortable_columns() { /* * The initial sorting is by 'Requested' (post_date) and descending. * With initial sorting, the first click on 'Requested' should be ascending. * With 'Requester' sorting active, the next click on 'Requested' should be descending. */ $desc_first = isset( $_GET['orderby'] ); return array( 'email' => 'requester', 'created_timestamp' => array( 'requested', $desc_first ), ); } /** * Returns the default primary column. * * @since 4.9.6 * * @return string Default primary column name. */ protected function get_default_primary_column_name() { return 'email'; } /** * Counts the number of requests for each status. * * @since 4.9.6 * * @global wpdb $wpdb WordPress database abstraction object. * * @return object Number of posts for each status. */ protected function get_request_counts() { global $wpdb; $cache_key = $this->post_type . '-' . $this->request_type; $counts = wp_cache_get( $cache_key, 'counts' ); if ( false !== $counts ) { return $counts; } $query = " SELECT post_status, COUNT( * ) AS num_posts FROM {$wpdb->posts} WHERE post_type = %s AND post_name = %s GROUP BY post_status"; $results = (array) $wpdb->get_results( $wpdb->prepare( $query, $this->post_type, $this->request_type ), ARRAY_A ); $counts = array_fill_keys( get_post_stati(), 0 ); foreach ( $results as $row ) { $counts[ $row['post_status'] ] = $row['num_posts']; } $counts = (object) $counts; wp_cache_set( $cache_key, $counts, 'counts' ); return $counts; } /** * Gets an associative array ( id => link ) with the list of views available on this table. * * @since 4.9.6 * * @return string[] An array of HTML links keyed by their view. */ protected function get_views() { $current_status = isset( $_REQUEST['filter-status'] ) ? sanitize_text_field( $_REQUEST['filter-status'] ) : ''; $statuses = _wp_privacy_statuses(); $views = array(); $counts = $this->get_request_counts(); $total_requests = absint( array_sum( (array) $counts ) ); // Normalized admin URL. $admin_url = $this->get_admin_url(); $status_label = sprintf( /* translators: %s: Number of requests. */ _nx( 'All (%s)', 'All (%s)', $total_requests, 'requests' ), number_format_i18n( $total_requests ) ); $views['all'] = array( 'url' => esc_url( $admin_url ), 'label' => $status_label, 'current' => empty( $current_status ), ); foreach ( $statuses as $status => $label ) { $post_status = get_post_status_object( $status ); if ( ! $post_status ) { continue; } $total_status_requests = absint( $counts->{$status} ); if ( ! $total_status_requests ) { continue; } $status_label = sprintf( translate_nooped_plural( $post_status->label_count, $total_status_requests ), number_format_i18n( $total_status_requests ) ); $status_link = add_query_arg( 'filter-status', $status, $admin_url ); $views[ $status ] = array( 'url' => esc_url( $status_link ), 'label' => $status_label, 'current' => $status === $current_status, ); } return $this->get_views_links( $views ); } /** * Gets bulk actions. * * @since 4.9.6 * * @return array Array of bulk action labels keyed by their action. */ protected function get_bulk_actions() { return array( 'resend' => __( 'Resend confirmation requests' ), 'complete' => __( 'Mark requests as completed' ), 'delete' => __( 'Delete requests' ), ); } /** * Process bulk actions. * * @since 4.9.6 * @since 5.6.0 Added support for the `complete` action. */ public function process_bulk_action() { $action = $this->current_action(); $request_ids = isset( $_REQUEST['request_id'] ) ? wp_parse_id_list( wp_unslash( $_REQUEST['request_id'] ) ) : array(); if ( empty( $request_ids ) ) { return; } $count = 0; $failures = 0; check_admin_referer( 'bulk-privacy_requests' ); switch ( $action ) { case 'resend': foreach ( $request_ids as $request_id ) { $resend = _wp_privacy_resend_request( $request_id ); if ( $resend && ! is_wp_error( $resend ) ) { ++$count; } else { ++$failures; } } if ( $failures ) { add_settings_error( 'bulk_action', 'bulk_action', sprintf( /* translators: %d: Number of requests. */ _n( '%d confirmation request failed to resend.', '%d confirmation requests failed to resend.', $failures ), $failures ), 'error' ); } if ( $count ) { add_settings_error( 'bulk_action', 'bulk_action', sprintf( /* translators: %d: Number of requests. */ _n( '%d confirmation request re-sent successfully.', '%d confirmation requests re-sent successfully.', $count ), $count ), 'success' ); } break; case 'complete': foreach ( $request_ids as $request_id ) { $result = _wp_privacy_completed_request( $request_id ); if ( $result && ! is_wp_error( $result ) ) { ++$count; } } add_settings_error( 'bulk_action', 'bulk_action', sprintf( /* translators: %d: Number of requests. */ _n( '%d request marked as complete.', '%d requests marked as complete.', $count ), $count ), 'success' ); break; case 'delete': foreach ( $request_ids as $request_id ) { if ( wp_delete_post( $request_id, true ) ) { ++$count; } else { ++$failures; } } if ( $failures ) { add_settings_error( 'bulk_action', 'bulk_action', sprintf( /* translators: %d: Number of requests. */ _n( '%d request failed to delete.', '%d requests failed to delete.', $failures ), $failures ), 'error' ); } if ( $count ) { add_settings_error( 'bulk_action', 'bulk_action', sprintf( /* translators: %d: Number of requests. */ _n( '%d request deleted successfully.', '%d requests deleted successfully.', $count ), $count ), 'success' ); } break; } } /** * Prepares items to output. * * @since 4.9.6 * @since 5.1.0 Added support for column sorting. */ public function prepare_items() { $this->items = array(); $posts_per_page = $this->get_items_per_page( $this->request_type . '_requests_per_page' ); $args = array( 'post_type' => $this->post_type, 'post_name__in' => array( $this->request_type ), 'posts_per_page' => $posts_per_page, 'offset' => isset( $_REQUEST['paged'] ) ? max( 0, absint( $_REQUEST['paged'] ) - 1 ) * $posts_per_page : 0, 'post_status' => 'any', 's' => isset( $_REQUEST['s'] ) ? sanitize_text_field( $_REQUEST['s'] ) : '', ); $orderby_mapping = array( 'requester' => 'post_title', 'requested' => 'post_date', ); if ( isset( $_REQUEST['orderby'] ) && isset( $orderby_mapping[ $_REQUEST['orderby'] ] ) ) { $args['orderby'] = $orderby_mapping[ $_REQUEST['orderby'] ]; } if ( isset( $_REQUEST['order'] ) && in_array( strtoupper( $_REQUEST['order'] ), array( 'ASC', 'DESC' ), true ) ) { $args['order'] = strtoupper( $_REQUEST['order'] ); } if ( ! empty( $_REQUEST['filter-status'] ) ) { $filter_status = isset( $_REQUEST['filter-status'] ) ? sanitize_text_field( $_REQUEST['filter-status'] ) : ''; $args['post_status'] = $filter_status; } $requests_query = new WP_Query( $args ); $requests = $requests_query->posts; foreach ( $requests as $request ) { $this->items[] = wp_get_user_request( $request->ID ); } $this->items = array_filter( $this->items ); $this->set_pagination_args( array( 'total_items' => $requests_query->found_posts, 'per_page' => $posts_per_page, ) ); } /** * Returns the markup for the Checkbox column. * * @since 4.9.6 * * @param WP_User_Request $item Item being shown. * @return string Checkbox column markup. */ public function column_cb( $item ) { return sprintf( '' . '', esc_attr( $item->ID ), /* translators: Hidden accessibility text. %s: Email address. */ sprintf( __( 'Select %s' ), $item->email ) ); } /** * Status column. * * @since 4.9.6 * * @param WP_User_Request $item Item being shown. * @return string Status column markup. */ public function column_status( $item ) { $status = get_post_status( $item->ID ); $status_object = get_post_status_object( $status ); if ( ! $status_object || empty( $status_object->label ) ) { return '-'; } $timestamp = false; switch ( $status ) { case 'request-confirmed': $timestamp = $item->confirmed_timestamp; break; case 'request-completed': $timestamp = $item->completed_timestamp; break; } echo ''; echo esc_html( $status_object->label ); if ( $timestamp ) { echo ' (' . $this->get_timestamp_as_date( $timestamp ) . ')'; } echo ''; } /** * Converts a timestamp for display. * * @since 4.9.6 * * @param int $timestamp Event timestamp. * @return string Human readable date. */ protected function get_timestamp_as_date( $timestamp ) { if ( empty( $timestamp ) ) { return ''; } $time_diff = time() - $timestamp; if ( $time_diff >= 0 && $time_diff < DAY_IN_SECONDS ) { /* translators: %s: Human-readable time difference. */ return sprintf( __( '%s ago' ), human_time_diff( $timestamp ) ); } return date_i18n( get_option( 'date_format' ), $timestamp ); } /** * Handles the default column. * * @since 4.9.6 * @since 5.7.0 Added `manage_{$this->screen->id}_custom_column` action. * * @param WP_User_Request $item Item being shown. * @param string $column_name Name of column being shown. */ public function column_default( $item, $column_name ) { /** * Fires for each custom column of a specific request type in the Requests list table. * * Custom columns are registered using the {@see 'manage_export-personal-data_columns'} * and the {@see 'manage_erase-personal-data_columns'} filters. * * @since 5.7.0 * * @param string $column_name The name of the column to display. * @param WP_User_Request $item The item being shown. */ do_action( "manage_{$this->screen->id}_custom_column", $column_name, $item ); } /** * Returns the markup for the Created timestamp column. Overridden by children. * * @since 5.7.0 * * @param WP_User_Request $item Item being shown. * @return string Human readable date. */ public function column_created_timestamp( $item ) { return $this->get_timestamp_as_date( $item->created_timestamp ); } /** * Actions column. Overridden by children. * * @since 4.9.6 * * @param WP_User_Request $item Item being shown. * @return string Email column markup. */ public function column_email( $item ) { return sprintf( '%2$s %3$s', esc_url( 'mailto:' . $item->email ), $item->email, $this->row_actions( array() ) ); } /** * Returns the markup for the next steps column. Overridden by children. * * @since 4.9.6 * * @param WP_User_Request $item Item being shown. */ public function column_next_steps( $item ) {} /** * Generates content for a single row of the table, * * @since 4.9.6 * * @param WP_User_Request $item The current item. */ public function single_row( $item ) { $status = $item->status; echo ''; $this->single_row_columns( $item ); echo ''; } /** * Embeds scripts used to perform actions. Overridden by children. * * @since 4.9.6 */ public function embed_scripts() {} } class-plugin-upgrader.php000064400000055313147206365750011513 0ustar00strings['up_to_date'] = __( 'The plugin is at the latest version.' ); $this->strings['no_package'] = __( 'Update package not available.' ); /* translators: %s: Package URL. */ $this->strings['downloading_package'] = sprintf( __( 'Downloading update from %s…' ), '%s' ); $this->strings['unpack_package'] = __( 'Unpacking the update…' ); $this->strings['remove_old'] = __( 'Removing the old version of the plugin…' ); $this->strings['remove_old_failed'] = __( 'Could not remove the old plugin.' ); $this->strings['process_failed'] = __( 'Plugin update failed.' ); $this->strings['process_success'] = __( 'Plugin updated successfully.' ); $this->strings['process_bulk_success'] = __( 'Plugins updated successfully.' ); } /** * Initializes the installation strings. * * @since 2.8.0 */ public function install_strings() { $this->strings['no_package'] = __( 'Installation package not available.' ); /* translators: %s: Package URL. */ $this->strings['downloading_package'] = sprintf( __( 'Downloading installation package from %s…' ), '%s' ); $this->strings['unpack_package'] = __( 'Unpacking the package…' ); $this->strings['installing_package'] = __( 'Installing the plugin…' ); $this->strings['remove_old'] = __( 'Removing the current plugin…' ); $this->strings['remove_old_failed'] = __( 'Could not remove the current plugin.' ); $this->strings['no_files'] = __( 'The plugin contains no files.' ); $this->strings['process_failed'] = __( 'Plugin installation failed.' ); $this->strings['process_success'] = __( 'Plugin installed successfully.' ); /* translators: 1: Plugin name, 2: Plugin version. */ $this->strings['process_success_specific'] = __( 'Successfully installed the plugin %1$s %2$s.' ); if ( ! empty( $this->skin->overwrite ) ) { if ( 'update-plugin' === $this->skin->overwrite ) { $this->strings['installing_package'] = __( 'Updating the plugin…' ); $this->strings['process_failed'] = __( 'Plugin update failed.' ); $this->strings['process_success'] = __( 'Plugin updated successfully.' ); } if ( 'downgrade-plugin' === $this->skin->overwrite ) { $this->strings['installing_package'] = __( 'Downgrading the plugin…' ); $this->strings['process_failed'] = __( 'Plugin downgrade failed.' ); $this->strings['process_success'] = __( 'Plugin downgraded successfully.' ); } } } /** * Install a plugin package. * * @since 2.8.0 * @since 3.7.0 The `$args` parameter was added, making clearing the plugin update cache optional. * * @param string $package The full local path or URI of the package. * @param array $args { * Optional. Other arguments for installing a plugin package. Default empty array. * * @type bool $clear_update_cache Whether to clear the plugin updates cache if successful. * Default true. * } * @return bool|WP_Error True if the installation was successful, false or a WP_Error otherwise. */ public function install( $package, $args = array() ) { $defaults = array( 'clear_update_cache' => true, 'overwrite_package' => false, // Do not overwrite files. ); $parsed_args = wp_parse_args( $args, $defaults ); $this->init(); $this->install_strings(); add_filter( 'upgrader_source_selection', array( $this, 'check_package' ) ); if ( $parsed_args['clear_update_cache'] ) { // Clear cache so wp_update_plugins() knows about the new plugin. add_action( 'upgrader_process_complete', 'wp_clean_plugins_cache', 9, 0 ); } $this->run( array( 'package' => $package, 'destination' => WP_PLUGIN_DIR, 'clear_destination' => $parsed_args['overwrite_package'], 'clear_working' => true, 'hook_extra' => array( 'type' => 'plugin', 'action' => 'install', ), ) ); remove_action( 'upgrader_process_complete', 'wp_clean_plugins_cache', 9 ); remove_filter( 'upgrader_source_selection', array( $this, 'check_package' ) ); if ( ! $this->result || is_wp_error( $this->result ) ) { return $this->result; } // Force refresh of plugin update information. wp_clean_plugins_cache( $parsed_args['clear_update_cache'] ); if ( $parsed_args['overwrite_package'] ) { /** * Fires when the upgrader has successfully overwritten a currently installed * plugin or theme with an uploaded zip package. * * @since 5.5.0 * * @param string $package The package file. * @param array $data The new plugin or theme data. * @param string $package_type The package type ('plugin' or 'theme'). */ do_action( 'upgrader_overwrote_package', $package, $this->new_plugin_data, 'plugin' ); } return true; } /** * Upgrades a plugin. * * @since 2.8.0 * @since 3.7.0 The `$args` parameter was added, making clearing the plugin update cache optional. * * @param string $plugin Path to the plugin file relative to the plugins directory. * @param array $args { * Optional. Other arguments for upgrading a plugin package. Default empty array. * * @type bool $clear_update_cache Whether to clear the plugin updates cache if successful. * Default true. * } * @return bool|WP_Error True if the upgrade was successful, false or a WP_Error object otherwise. */ public function upgrade( $plugin, $args = array() ) { $defaults = array( 'clear_update_cache' => true, ); $parsed_args = wp_parse_args( $args, $defaults ); $this->init(); $this->upgrade_strings(); $current = get_site_transient( 'update_plugins' ); if ( ! isset( $current->response[ $plugin ] ) ) { $this->skin->before(); $this->skin->set_result( false ); $this->skin->error( 'up_to_date' ); $this->skin->after(); return false; } // Get the URL to the zip file. $r = $current->response[ $plugin ]; add_filter( 'upgrader_pre_install', array( $this, 'deactivate_plugin_before_upgrade' ), 10, 2 ); add_filter( 'upgrader_pre_install', array( $this, 'active_before' ), 10, 2 ); add_filter( 'upgrader_clear_destination', array( $this, 'delete_old_plugin' ), 10, 4 ); add_filter( 'upgrader_post_install', array( $this, 'active_after' ), 10, 2 ); /* * There's a Trac ticket to move up the directory for zips which are made a bit differently, useful for non-.org plugins. * 'source_selection' => array( $this, 'source_selection' ), */ if ( $parsed_args['clear_update_cache'] ) { // Clear cache so wp_update_plugins() knows about the new plugin. add_action( 'upgrader_process_complete', 'wp_clean_plugins_cache', 9, 0 ); } $this->run( array( 'package' => $r->package, 'destination' => WP_PLUGIN_DIR, 'clear_destination' => true, 'clear_working' => true, 'hook_extra' => array( 'plugin' => $plugin, 'type' => 'plugin', 'action' => 'update', 'temp_backup' => array( 'slug' => dirname( $plugin ), 'src' => WP_PLUGIN_DIR, 'dir' => 'plugins', ), ), ) ); // Cleanup our hooks, in case something else does an upgrade on this connection. remove_action( 'upgrader_process_complete', 'wp_clean_plugins_cache', 9 ); remove_filter( 'upgrader_pre_install', array( $this, 'deactivate_plugin_before_upgrade' ) ); remove_filter( 'upgrader_pre_install', array( $this, 'active_before' ) ); remove_filter( 'upgrader_clear_destination', array( $this, 'delete_old_plugin' ) ); remove_filter( 'upgrader_post_install', array( $this, 'active_after' ) ); if ( ! $this->result || is_wp_error( $this->result ) ) { return $this->result; } // Force refresh of plugin update information. wp_clean_plugins_cache( $parsed_args['clear_update_cache'] ); /* * Ensure any future auto-update failures trigger a failure email by removing * the last failure notification from the list when plugins update successfully. */ $past_failure_emails = get_option( 'auto_plugin_theme_update_emails', array() ); if ( isset( $past_failure_emails[ $plugin ] ) ) { unset( $past_failure_emails[ $plugin ] ); update_option( 'auto_plugin_theme_update_emails', $past_failure_emails ); } return true; } /** * Upgrades several plugins at once. * * @since 2.8.0 * @since 3.7.0 The `$args` parameter was added, making clearing the plugin update cache optional. * * @param string[] $plugins Array of paths to plugin files relative to the plugins directory. * @param array $args { * Optional. Other arguments for upgrading several plugins at once. * * @type bool $clear_update_cache Whether to clear the plugin updates cache if successful. Default true. * } * @return array|false An array of results indexed by plugin file, or false if unable to connect to the filesystem. */ public function bulk_upgrade( $plugins, $args = array() ) { $wp_version = wp_get_wp_version(); $defaults = array( 'clear_update_cache' => true, ); $parsed_args = wp_parse_args( $args, $defaults ); $this->init(); $this->bulk = true; $this->upgrade_strings(); $current = get_site_transient( 'update_plugins' ); add_filter( 'upgrader_clear_destination', array( $this, 'delete_old_plugin' ), 10, 4 ); $this->skin->header(); // Connect to the filesystem first. $res = $this->fs_connect( array( WP_CONTENT_DIR, WP_PLUGIN_DIR ) ); if ( ! $res ) { $this->skin->footer(); return false; } $this->skin->bulk_header(); /* * Only start maintenance mode if: * - running Multisite and there are one or more plugins specified, OR * - a plugin with an update available is currently active. * @todo For multisite, maintenance mode should only kick in for individual sites if at all possible. */ $maintenance = ( is_multisite() && ! empty( $plugins ) ); foreach ( $plugins as $plugin ) { $maintenance = $maintenance || ( is_plugin_active( $plugin ) && isset( $current->response[ $plugin ] ) ); } if ( $maintenance ) { $this->maintenance_mode( true ); } $results = array(); $this->update_count = count( $plugins ); $this->update_current = 0; foreach ( $plugins as $plugin ) { ++$this->update_current; $this->skin->plugin_info = get_plugin_data( WP_PLUGIN_DIR . '/' . $plugin, false, true ); if ( ! isset( $current->response[ $plugin ] ) ) { $this->skin->set_result( 'up_to_date' ); $this->skin->before(); $this->skin->feedback( 'up_to_date' ); $this->skin->after(); $results[ $plugin ] = true; continue; } // Get the URL to the zip file. $r = $current->response[ $plugin ]; $this->skin->plugin_active = is_plugin_active( $plugin ); if ( isset( $r->requires ) && ! is_wp_version_compatible( $r->requires ) ) { $result = new WP_Error( 'incompatible_wp_required_version', sprintf( /* translators: 1: Current WordPress version, 2: WordPress version required by the new plugin version. */ __( 'Your WordPress version is %1$s, however the new plugin version requires %2$s.' ), $wp_version, $r->requires ) ); $this->skin->before( $result ); $this->skin->error( $result ); $this->skin->after(); } elseif ( isset( $r->requires_php ) && ! is_php_version_compatible( $r->requires_php ) ) { $result = new WP_Error( 'incompatible_php_required_version', sprintf( /* translators: 1: Current PHP version, 2: PHP version required by the new plugin version. */ __( 'The PHP version on your server is %1$s, however the new plugin version requires %2$s.' ), PHP_VERSION, $r->requires_php ) ); $this->skin->before( $result ); $this->skin->error( $result ); $this->skin->after(); } else { add_filter( 'upgrader_source_selection', array( $this, 'check_package' ) ); $result = $this->run( array( 'package' => $r->package, 'destination' => WP_PLUGIN_DIR, 'clear_destination' => true, 'clear_working' => true, 'is_multi' => true, 'hook_extra' => array( 'plugin' => $plugin, 'temp_backup' => array( 'slug' => dirname( $plugin ), 'src' => WP_PLUGIN_DIR, 'dir' => 'plugins', ), ), ) ); remove_filter( 'upgrader_source_selection', array( $this, 'check_package' ) ); } $results[ $plugin ] = $result; // Prevent credentials auth screen from displaying multiple times. if ( false === $result ) { break; } } // End foreach $plugins. $this->maintenance_mode( false ); // Force refresh of plugin update information. wp_clean_plugins_cache( $parsed_args['clear_update_cache'] ); /** This action is documented in wp-admin/includes/class-wp-upgrader.php */ do_action( 'upgrader_process_complete', $this, array( 'action' => 'update', 'type' => 'plugin', 'bulk' => true, 'plugins' => $plugins, ) ); $this->skin->bulk_footer(); $this->skin->footer(); // Cleanup our hooks, in case something else does an upgrade on this connection. remove_filter( 'upgrader_clear_destination', array( $this, 'delete_old_plugin' ) ); /* * Ensure any future auto-update failures trigger a failure email by removing * the last failure notification from the list when plugins update successfully. */ $past_failure_emails = get_option( 'auto_plugin_theme_update_emails', array() ); foreach ( $results as $plugin => $result ) { // Maintain last failure notification when plugins failed to update manually. if ( ! $result || is_wp_error( $result ) || ! isset( $past_failure_emails[ $plugin ] ) ) { continue; } unset( $past_failure_emails[ $plugin ] ); } update_option( 'auto_plugin_theme_update_emails', $past_failure_emails ); return $results; } /** * Checks that the source package contains a valid plugin. * * Hooked to the {@see 'upgrader_source_selection'} filter by Plugin_Upgrader::install(). * * @since 3.3.0 * * @global WP_Filesystem_Base $wp_filesystem WordPress filesystem subclass. * * @param string $source The path to the downloaded package source. * @return string|WP_Error The source as passed, or a WP_Error object on failure. */ public function check_package( $source ) { global $wp_filesystem; $wp_version = wp_get_wp_version(); $this->new_plugin_data = array(); if ( is_wp_error( $source ) ) { return $source; } $working_directory = str_replace( $wp_filesystem->wp_content_dir(), trailingslashit( WP_CONTENT_DIR ), $source ); if ( ! is_dir( $working_directory ) ) { // Confidence check, if the above fails, let's not prevent installation. return $source; } // Check that the folder contains at least 1 valid plugin. $files = glob( $working_directory . '*.php' ); if ( $files ) { foreach ( $files as $file ) { $info = get_plugin_data( $file, false, false ); if ( ! empty( $info['Name'] ) ) { $this->new_plugin_data = $info; break; } } } if ( empty( $this->new_plugin_data ) ) { return new WP_Error( 'incompatible_archive_no_plugins', $this->strings['incompatible_archive'], __( 'No valid plugins were found.' ) ); } $requires_php = isset( $info['RequiresPHP'] ) ? $info['RequiresPHP'] : null; $requires_wp = isset( $info['RequiresWP'] ) ? $info['RequiresWP'] : null; if ( ! is_php_version_compatible( $requires_php ) ) { $error = sprintf( /* translators: 1: Current PHP version, 2: Version required by the uploaded plugin. */ __( 'The PHP version on your server is %1$s, however the uploaded plugin requires %2$s.' ), PHP_VERSION, $requires_php ); return new WP_Error( 'incompatible_php_required_version', $this->strings['incompatible_archive'], $error ); } if ( ! is_wp_version_compatible( $requires_wp ) ) { $error = sprintf( /* translators: 1: Current WordPress version, 2: Version required by the uploaded plugin. */ __( 'Your WordPress version is %1$s, however the uploaded plugin requires %2$s.' ), $wp_version, $requires_wp ); return new WP_Error( 'incompatible_wp_required_version', $this->strings['incompatible_archive'], $error ); } return $source; } /** * Retrieves the path to the file that contains the plugin info. * * This isn't used internally in the class, but is called by the skins. * * @since 2.8.0 * * @return string|false The full path to the main plugin file, or false. */ public function plugin_info() { if ( ! is_array( $this->result ) ) { return false; } if ( empty( $this->result['destination_name'] ) ) { return false; } // Ensure to pass with leading slash. $plugin = get_plugins( '/' . $this->result['destination_name'] ); if ( empty( $plugin ) ) { return false; } // Assume the requested plugin is the first in the list. $pluginfiles = array_keys( $plugin ); return $this->result['destination_name'] . '/' . $pluginfiles[0]; } /** * Deactivates a plugin before it is upgraded. * * Hooked to the {@see 'upgrader_pre_install'} filter by Plugin_Upgrader::upgrade(). * * @since 2.8.0 * @since 4.1.0 Added a return value. * * @param bool|WP_Error $response The installation response before the installation has started. * @param array $plugin Plugin package arguments. * @return bool|WP_Error The original `$response` parameter or WP_Error. */ public function deactivate_plugin_before_upgrade( $response, $plugin ) { if ( is_wp_error( $response ) ) { // Bypass. return $response; } // When in cron (background updates) don't deactivate the plugin, as we require a browser to reactivate it. if ( wp_doing_cron() ) { return $response; } $plugin = isset( $plugin['plugin'] ) ? $plugin['plugin'] : ''; if ( empty( $plugin ) ) { return new WP_Error( 'bad_request', $this->strings['bad_request'] ); } if ( is_plugin_active( $plugin ) ) { // Deactivate the plugin silently, Prevent deactivation hooks from running. deactivate_plugins( $plugin, true ); } return $response; } /** * Turns on maintenance mode before attempting to background update an active plugin. * * Hooked to the {@see 'upgrader_pre_install'} filter by Plugin_Upgrader::upgrade(). * * @since 5.4.0 * * @param bool|WP_Error $response The installation response before the installation has started. * @param array $plugin Plugin package arguments. * @return bool|WP_Error The original `$response` parameter or WP_Error. */ public function active_before( $response, $plugin ) { if ( is_wp_error( $response ) ) { return $response; } // Only enable maintenance mode when in cron (background update). if ( ! wp_doing_cron() ) { return $response; } $plugin = isset( $plugin['plugin'] ) ? $plugin['plugin'] : ''; // Only run if plugin is active. if ( ! is_plugin_active( $plugin ) ) { return $response; } // Change to maintenance mode. Bulk edit handles this separately. if ( ! $this->bulk ) { $this->maintenance_mode( true ); } return $response; } /** * Turns off maintenance mode after upgrading an active plugin. * * Hooked to the {@see 'upgrader_post_install'} filter by Plugin_Upgrader::upgrade(). * * @since 5.4.0 * * @param bool|WP_Error $response The installation response after the installation has finished. * @param array $plugin Plugin package arguments. * @return bool|WP_Error The original `$response` parameter or WP_Error. */ public function active_after( $response, $plugin ) { if ( is_wp_error( $response ) ) { return $response; } // Only disable maintenance mode when in cron (background update). if ( ! wp_doing_cron() ) { return $response; } $plugin = isset( $plugin['plugin'] ) ? $plugin['plugin'] : ''; // Only run if plugin is active. if ( ! is_plugin_active( $plugin ) ) { return $response; } // Time to remove maintenance mode. Bulk edit handles this separately. if ( ! $this->bulk ) { $this->maintenance_mode( false ); } return $response; } /** * Deletes the old plugin during an upgrade. * * Hooked to the {@see 'upgrader_clear_destination'} filter by * Plugin_Upgrader::upgrade() and Plugin_Upgrader::bulk_upgrade(). * * @since 2.8.0 * * @global WP_Filesystem_Base $wp_filesystem WordPress filesystem subclass. * * @param bool|WP_Error $removed Whether the destination was cleared. * True on success, WP_Error on failure. * @param string $local_destination The local package destination. * @param string $remote_destination The remote package destination. * @param array $plugin Extra arguments passed to hooked filters. * @return bool|WP_Error */ public function delete_old_plugin( $removed, $local_destination, $remote_destination, $plugin ) { global $wp_filesystem; if ( is_wp_error( $removed ) ) { return $removed; // Pass errors through. } $plugin = isset( $plugin['plugin'] ) ? $plugin['plugin'] : ''; if ( empty( $plugin ) ) { return new WP_Error( 'bad_request', $this->strings['bad_request'] ); } $plugins_dir = $wp_filesystem->wp_plugins_dir(); $this_plugin_dir = trailingslashit( dirname( $plugins_dir . $plugin ) ); if ( ! $wp_filesystem->exists( $this_plugin_dir ) ) { // If it's already vanished. return $removed; } /* * If plugin is in its own directory, recursively delete the directory. * Base check on if plugin includes directory separator AND that it's not the root plugin folder. */ if ( strpos( $plugin, '/' ) && $this_plugin_dir !== $plugins_dir ) { $deleted = $wp_filesystem->delete( $this_plugin_dir, true ); } else { $deleted = $wp_filesystem->delete( $plugins_dir . $plugin ); } if ( ! $deleted ) { return new WP_Error( 'remove_old_failed', $this->strings['remove_old_failed'] ); } return true; } } schema.php000064400000123243147206365750006541 0ustar00get_charset_collate(); /** * Retrieve the SQL for creating database tables. * * @since 3.3.0 * * @global wpdb $wpdb WordPress database abstraction object. * * @param string $scope Optional. The tables for which to retrieve SQL. Can be all, global, ms_global, or blog tables. Defaults to all. * @param int $blog_id Optional. The site ID for which to retrieve SQL. Default is the current site ID. * @return string The SQL needed to create the requested tables. */ function wp_get_db_schema( $scope = 'all', $blog_id = null ) { global $wpdb; $charset_collate = $wpdb->get_charset_collate(); if ( $blog_id && (int) $blog_id !== $wpdb->blogid ) { $old_blog_id = $wpdb->set_blog_id( $blog_id ); } // Engage multisite if in the middle of turning it on from network.php. $is_multisite = is_multisite() || ( defined( 'WP_INSTALLING_NETWORK' ) && WP_INSTALLING_NETWORK ); /* * Indexes have a maximum size of 767 bytes. Historically, we haven't need to be concerned about that. * As of 4.2, however, we moved to utf8mb4, which uses 4 bytes per character. This means that an index which * used to have room for floor(767/3) = 255 characters, now only has room for floor(767/4) = 191 characters. */ $max_index_length = 191; // Blog-specific tables. $blog_tables = "CREATE TABLE $wpdb->termmeta ( meta_id bigint(20) unsigned NOT NULL auto_increment, term_id bigint(20) unsigned NOT NULL default '0', meta_key varchar(255) default NULL, meta_value longtext, PRIMARY KEY (meta_id), KEY term_id (term_id), KEY meta_key (meta_key($max_index_length)) ) $charset_collate; CREATE TABLE $wpdb->terms ( term_id bigint(20) unsigned NOT NULL auto_increment, name varchar(200) NOT NULL default '', slug varchar(200) NOT NULL default '', term_group bigint(10) NOT NULL default 0, PRIMARY KEY (term_id), KEY slug (slug($max_index_length)), KEY name (name($max_index_length)) ) $charset_collate; CREATE TABLE $wpdb->term_taxonomy ( term_taxonomy_id bigint(20) unsigned NOT NULL auto_increment, term_id bigint(20) unsigned NOT NULL default 0, taxonomy varchar(32) NOT NULL default '', description longtext NOT NULL, parent bigint(20) unsigned NOT NULL default 0, count bigint(20) NOT NULL default 0, PRIMARY KEY (term_taxonomy_id), UNIQUE KEY term_id_taxonomy (term_id,taxonomy), KEY taxonomy (taxonomy) ) $charset_collate; CREATE TABLE $wpdb->term_relationships ( object_id bigint(20) unsigned NOT NULL default 0, term_taxonomy_id bigint(20) unsigned NOT NULL default 0, term_order int(11) NOT NULL default 0, PRIMARY KEY (object_id,term_taxonomy_id), KEY term_taxonomy_id (term_taxonomy_id) ) $charset_collate; CREATE TABLE $wpdb->commentmeta ( meta_id bigint(20) unsigned NOT NULL auto_increment, comment_id bigint(20) unsigned NOT NULL default '0', meta_key varchar(255) default NULL, meta_value longtext, PRIMARY KEY (meta_id), KEY comment_id (comment_id), KEY meta_key (meta_key($max_index_length)) ) $charset_collate; CREATE TABLE $wpdb->comments ( comment_ID bigint(20) unsigned NOT NULL auto_increment, comment_post_ID bigint(20) unsigned NOT NULL default '0', comment_author tinytext NOT NULL, comment_author_email varchar(100) NOT NULL default '', comment_author_url varchar(200) NOT NULL default '', comment_author_IP varchar(100) NOT NULL default '', comment_date datetime NOT NULL default '0000-00-00 00:00:00', comment_date_gmt datetime NOT NULL default '0000-00-00 00:00:00', comment_content text NOT NULL, comment_karma int(11) NOT NULL default '0', comment_approved varchar(20) NOT NULL default '1', comment_agent varchar(255) NOT NULL default '', comment_type varchar(20) NOT NULL default 'comment', comment_parent bigint(20) unsigned NOT NULL default '0', user_id bigint(20) unsigned NOT NULL default '0', PRIMARY KEY (comment_ID), KEY comment_post_ID (comment_post_ID), KEY comment_approved_date_gmt (comment_approved,comment_date_gmt), KEY comment_date_gmt (comment_date_gmt), KEY comment_parent (comment_parent), KEY comment_author_email (comment_author_email(10)) ) $charset_collate; CREATE TABLE $wpdb->links ( link_id bigint(20) unsigned NOT NULL auto_increment, link_url varchar(255) NOT NULL default '', link_name varchar(255) NOT NULL default '', link_image varchar(255) NOT NULL default '', link_target varchar(25) NOT NULL default '', link_description varchar(255) NOT NULL default '', link_visible varchar(20) NOT NULL default 'Y', link_owner bigint(20) unsigned NOT NULL default '1', link_rating int(11) NOT NULL default '0', link_updated datetime NOT NULL default '0000-00-00 00:00:00', link_rel varchar(255) NOT NULL default '', link_notes mediumtext NOT NULL, link_rss varchar(255) NOT NULL default '', PRIMARY KEY (link_id), KEY link_visible (link_visible) ) $charset_collate; CREATE TABLE $wpdb->options ( option_id bigint(20) unsigned NOT NULL auto_increment, option_name varchar(191) NOT NULL default '', option_value longtext NOT NULL, autoload varchar(20) NOT NULL default 'yes', PRIMARY KEY (option_id), UNIQUE KEY option_name (option_name), KEY autoload (autoload) ) $charset_collate; CREATE TABLE $wpdb->postmeta ( meta_id bigint(20) unsigned NOT NULL auto_increment, post_id bigint(20) unsigned NOT NULL default '0', meta_key varchar(255) default NULL, meta_value longtext, PRIMARY KEY (meta_id), KEY post_id (post_id), KEY meta_key (meta_key($max_index_length)) ) $charset_collate; CREATE TABLE $wpdb->posts ( ID bigint(20) unsigned NOT NULL auto_increment, post_author bigint(20) unsigned NOT NULL default '0', post_date datetime NOT NULL default '0000-00-00 00:00:00', post_date_gmt datetime NOT NULL default '0000-00-00 00:00:00', post_content longtext NOT NULL, post_title text NOT NULL, post_excerpt text NOT NULL, post_status varchar(20) NOT NULL default 'publish', comment_status varchar(20) NOT NULL default 'open', ping_status varchar(20) NOT NULL default 'open', post_password varchar(255) NOT NULL default '', post_name varchar(200) NOT NULL default '', to_ping text NOT NULL, pinged text NOT NULL, post_modified datetime NOT NULL default '0000-00-00 00:00:00', post_modified_gmt datetime NOT NULL default '0000-00-00 00:00:00', post_content_filtered longtext NOT NULL, post_parent bigint(20) unsigned NOT NULL default '0', guid varchar(255) NOT NULL default '', menu_order int(11) NOT NULL default '0', post_type varchar(20) NOT NULL default 'post', post_mime_type varchar(100) NOT NULL default '', comment_count bigint(20) NOT NULL default '0', PRIMARY KEY (ID), KEY post_name (post_name($max_index_length)), KEY type_status_date (post_type,post_status,post_date,ID), KEY post_parent (post_parent), KEY post_author (post_author) ) $charset_collate;\n"; // Single site users table. The multisite flavor of the users table is handled below. $users_single_table = "CREATE TABLE $wpdb->users ( ID bigint(20) unsigned NOT NULL auto_increment, user_login varchar(60) NOT NULL default '', user_pass varchar(255) NOT NULL default '', user_nicename varchar(50) NOT NULL default '', user_email varchar(100) NOT NULL default '', user_url varchar(100) NOT NULL default '', user_registered datetime NOT NULL default '0000-00-00 00:00:00', user_activation_key varchar(255) NOT NULL default '', user_status int(11) NOT NULL default '0', display_name varchar(250) NOT NULL default '', PRIMARY KEY (ID), KEY user_login_key (user_login), KEY user_nicename (user_nicename), KEY user_email (user_email) ) $charset_collate;\n"; // Multisite users table. $users_multi_table = "CREATE TABLE $wpdb->users ( ID bigint(20) unsigned NOT NULL auto_increment, user_login varchar(60) NOT NULL default '', user_pass varchar(255) NOT NULL default '', user_nicename varchar(50) NOT NULL default '', user_email varchar(100) NOT NULL default '', user_url varchar(100) NOT NULL default '', user_registered datetime NOT NULL default '0000-00-00 00:00:00', user_activation_key varchar(255) NOT NULL default '', user_status int(11) NOT NULL default '0', display_name varchar(250) NOT NULL default '', spam tinyint(2) NOT NULL default '0', deleted tinyint(2) NOT NULL default '0', PRIMARY KEY (ID), KEY user_login_key (user_login), KEY user_nicename (user_nicename), KEY user_email (user_email) ) $charset_collate;\n"; // Usermeta. $usermeta_table = "CREATE TABLE $wpdb->usermeta ( umeta_id bigint(20) unsigned NOT NULL auto_increment, user_id bigint(20) unsigned NOT NULL default '0', meta_key varchar(255) default NULL, meta_value longtext, PRIMARY KEY (umeta_id), KEY user_id (user_id), KEY meta_key (meta_key($max_index_length)) ) $charset_collate;\n"; // Global tables. if ( $is_multisite ) { $global_tables = $users_multi_table . $usermeta_table; } else { $global_tables = $users_single_table . $usermeta_table; } // Multisite global tables. $ms_global_tables = "CREATE TABLE $wpdb->blogs ( blog_id bigint(20) NOT NULL auto_increment, site_id bigint(20) NOT NULL default '0', domain varchar(200) NOT NULL default '', path varchar(100) NOT NULL default '', registered datetime NOT NULL default '0000-00-00 00:00:00', last_updated datetime NOT NULL default '0000-00-00 00:00:00', public tinyint(2) NOT NULL default '1', archived tinyint(2) NOT NULL default '0', mature tinyint(2) NOT NULL default '0', spam tinyint(2) NOT NULL default '0', deleted tinyint(2) NOT NULL default '0', lang_id int(11) NOT NULL default '0', PRIMARY KEY (blog_id), KEY domain (domain(50),path(5)), KEY lang_id (lang_id) ) $charset_collate; CREATE TABLE $wpdb->blogmeta ( meta_id bigint(20) unsigned NOT NULL auto_increment, blog_id bigint(20) NOT NULL default '0', meta_key varchar(255) default NULL, meta_value longtext, PRIMARY KEY (meta_id), KEY meta_key (meta_key($max_index_length)), KEY blog_id (blog_id) ) $charset_collate; CREATE TABLE $wpdb->registration_log ( ID bigint(20) NOT NULL auto_increment, email varchar(255) NOT NULL default '', IP varchar(30) NOT NULL default '', blog_id bigint(20) NOT NULL default '0', date_registered datetime NOT NULL default '0000-00-00 00:00:00', PRIMARY KEY (ID), KEY IP (IP) ) $charset_collate; CREATE TABLE $wpdb->site ( id bigint(20) NOT NULL auto_increment, domain varchar(200) NOT NULL default '', path varchar(100) NOT NULL default '', PRIMARY KEY (id), KEY domain (domain(140),path(51)) ) $charset_collate; CREATE TABLE $wpdb->sitemeta ( meta_id bigint(20) NOT NULL auto_increment, site_id bigint(20) NOT NULL default '0', meta_key varchar(255) default NULL, meta_value longtext, PRIMARY KEY (meta_id), KEY meta_key (meta_key($max_index_length)), KEY site_id (site_id) ) $charset_collate; CREATE TABLE $wpdb->signups ( signup_id bigint(20) NOT NULL auto_increment, domain varchar(200) NOT NULL default '', path varchar(100) NOT NULL default '', title longtext NOT NULL, user_login varchar(60) NOT NULL default '', user_email varchar(100) NOT NULL default '', registered datetime NOT NULL default '0000-00-00 00:00:00', activated datetime NOT NULL default '0000-00-00 00:00:00', active tinyint(1) NOT NULL default '0', activation_key varchar(50) NOT NULL default '', meta longtext, PRIMARY KEY (signup_id), KEY activation_key (activation_key), KEY user_email (user_email), KEY user_login_email (user_login,user_email), KEY domain_path (domain(140),path(51)) ) $charset_collate;"; switch ( $scope ) { case 'blog': $queries = $blog_tables; break; case 'global': $queries = $global_tables; if ( $is_multisite ) { $queries .= $ms_global_tables; } break; case 'ms_global': $queries = $ms_global_tables; break; case 'all': default: $queries = $global_tables . $blog_tables; if ( $is_multisite ) { $queries .= $ms_global_tables; } break; } if ( isset( $old_blog_id ) ) { $wpdb->set_blog_id( $old_blog_id ); } return $queries; } // Populate for back compat. $wp_queries = wp_get_db_schema( 'all' ); /** * Create WordPress options and set the default values. * * @since 1.5.0 * @since 5.1.0 The $options parameter has been added. * * @global wpdb $wpdb WordPress database abstraction object. * @global int $wp_db_version WordPress database version. * @global int $wp_current_db_version The old (current) database version. * * @param array $options Optional. Custom option $key => $value pairs to use. Default empty array. */ function populate_options( array $options = array() ) { global $wpdb, $wp_db_version, $wp_current_db_version; $guessurl = wp_guess_url(); /** * Fires before creating WordPress options and populating their default values. * * @since 2.6.0 */ do_action( 'populate_options' ); // If WP_DEFAULT_THEME doesn't exist, fall back to the latest core default theme. $stylesheet = WP_DEFAULT_THEME; $template = WP_DEFAULT_THEME; $theme = wp_get_theme( WP_DEFAULT_THEME ); if ( ! $theme->exists() ) { $theme = WP_Theme::get_core_default_theme(); } // If we can't find a core default theme, WP_DEFAULT_THEME is the best we can do. if ( $theme ) { $stylesheet = $theme->get_stylesheet(); $template = $theme->get_template(); } $timezone_string = ''; $gmt_offset = 0; /* * translators: default GMT offset or timezone string. Must be either a valid offset (-12 to 14) * or a valid timezone string (America/New_York). See https://www.php.net/manual/en/timezones.php * for all timezone strings currently supported by PHP. * * Important: When a previous timezone string, like `Europe/Kiev`, has been superseded by an * updated one, like `Europe/Kyiv`, as a rule of thumb, the **old** timezone name should be used * in the "translation" to allow for the default timezone setting to be PHP cross-version compatible, * as old timezone names will be recognized in new PHP versions, while new timezone names cannot * be recognized in old PHP versions. * * To verify which timezone strings are available in the _oldest_ PHP version supported, you can * use https://3v4l.org/6YQAt#v5.6.20 and replace the "BR" (Brazil) in the code line with the * country code for which you want to look up the supported timezone names. */ $offset_or_tz = _x( '0', 'default GMT offset or timezone string' ); if ( is_numeric( $offset_or_tz ) ) { $gmt_offset = $offset_or_tz; } elseif ( $offset_or_tz && in_array( $offset_or_tz, timezone_identifiers_list( DateTimeZone::ALL_WITH_BC ), true ) ) { $timezone_string = $offset_or_tz; } $defaults = array( 'siteurl' => $guessurl, 'home' => $guessurl, 'blogname' => __( 'My Site' ), 'blogdescription' => '', 'users_can_register' => 0, 'admin_email' => 'you@example.com', /* translators: Default start of the week. 0 = Sunday, 1 = Monday. */ 'start_of_week' => _x( '1', 'start of week' ), 'use_balanceTags' => 0, 'use_smilies' => 1, 'require_name_email' => 1, 'comments_notify' => 1, 'posts_per_rss' => 10, 'rss_use_excerpt' => 0, 'mailserver_url' => 'mail.example.com', 'mailserver_login' => 'login@example.com', 'mailserver_pass' => '', 'mailserver_port' => 110, 'default_category' => 1, 'default_comment_status' => 'open', 'default_ping_status' => 'open', 'default_pingback_flag' => 1, 'posts_per_page' => 10, /* translators: Default date format, see https://www.php.net/manual/datetime.format.php */ 'date_format' => __( 'F j, Y' ), /* translators: Default time format, see https://www.php.net/manual/datetime.format.php */ 'time_format' => __( 'g:i a' ), /* translators: Links last updated date format, see https://www.php.net/manual/datetime.format.php */ 'links_updated_date_format' => __( 'F j, Y g:i a' ), 'comment_moderation' => 0, 'moderation_notify' => 1, 'permalink_structure' => '', 'rewrite_rules' => '', 'hack_file' => 0, 'blog_charset' => 'UTF-8', 'moderation_keys' => '', 'active_plugins' => array(), 'category_base' => '', 'ping_sites' => 'http://rpc.pingomatic.com/', 'comment_max_links' => 2, 'gmt_offset' => $gmt_offset, // 1.5.0 'default_email_category' => 1, 'recently_edited' => '', 'template' => $template, 'stylesheet' => $stylesheet, 'comment_registration' => 0, 'html_type' => 'text/html', // 1.5.1 'use_trackback' => 0, // 2.0.0 'default_role' => 'subscriber', 'db_version' => $wp_db_version, // 2.0.1 'uploads_use_yearmonth_folders' => 1, 'upload_path' => '', // 2.1.0 'blog_public' => '1', 'default_link_category' => 2, 'show_on_front' => 'posts', // 2.2.0 'tag_base' => '', // 2.5.0 'show_avatars' => '1', 'avatar_rating' => 'G', 'upload_url_path' => '', 'thumbnail_size_w' => 150, 'thumbnail_size_h' => 150, 'thumbnail_crop' => 1, 'medium_size_w' => 300, 'medium_size_h' => 300, // 2.6.0 'avatar_default' => 'mystery', // 2.7.0 'large_size_w' => 1024, 'large_size_h' => 1024, 'image_default_link_type' => 'none', 'image_default_size' => '', 'image_default_align' => '', 'close_comments_for_old_posts' => 0, 'close_comments_days_old' => 14, 'thread_comments' => 1, 'thread_comments_depth' => 5, 'page_comments' => 0, 'comments_per_page' => 50, 'default_comments_page' => 'newest', 'comment_order' => 'asc', 'sticky_posts' => array(), 'widget_categories' => array(), 'widget_text' => array(), 'widget_rss' => array(), 'uninstall_plugins' => array(), // 2.8.0 'timezone_string' => $timezone_string, // 3.0.0 'page_for_posts' => 0, 'page_on_front' => 0, // 3.1.0 'default_post_format' => 0, // 3.5.0 'link_manager_enabled' => 0, // 4.3.0 'finished_splitting_shared_terms' => 1, 'site_icon' => 0, // 4.4.0 'medium_large_size_w' => 768, 'medium_large_size_h' => 0, // 4.9.6 'wp_page_for_privacy_policy' => 0, // 4.9.8 'show_comments_cookies_opt_in' => 1, // 5.3.0 'admin_email_lifespan' => ( time() + 6 * MONTH_IN_SECONDS ), // 5.5.0 'disallowed_keys' => '', 'comment_previously_approved' => 1, 'auto_plugin_theme_update_emails' => array(), // 5.6.0 'auto_update_core_dev' => 'enabled', 'auto_update_core_minor' => 'enabled', /* * Default to enabled for new installs. * See https://core.trac.wordpress.org/ticket/51742. */ 'auto_update_core_major' => 'enabled', // 5.8.0 'wp_force_deactivated_plugins' => array(), // 6.4.0 'wp_attachment_pages_enabled' => 0, ); // 3.3.0 if ( ! is_multisite() ) { $defaults['initial_db_version'] = ! empty( $wp_current_db_version ) && $wp_current_db_version < $wp_db_version ? $wp_current_db_version : $wp_db_version; } // 3.0.0 multisite. if ( is_multisite() ) { $defaults['permalink_structure'] = '/%year%/%monthnum%/%day%/%postname%/'; } $options = wp_parse_args( $options, $defaults ); // Set autoload to no for these options. $fat_options = array( 'moderation_keys', 'recently_edited', 'disallowed_keys', 'uninstall_plugins', 'auto_plugin_theme_update_emails', ); $keys = "'" . implode( "', '", array_keys( $options ) ) . "'"; $existing_options = $wpdb->get_col( "SELECT option_name FROM $wpdb->options WHERE option_name in ( $keys )" ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared $insert = ''; foreach ( $options as $option => $value ) { if ( in_array( $option, $existing_options, true ) ) { continue; } if ( in_array( $option, $fat_options, true ) ) { $autoload = 'off'; } else { $autoload = 'on'; } if ( ! empty( $insert ) ) { $insert .= ', '; } $value = maybe_serialize( sanitize_option( $option, $value ) ); $insert .= $wpdb->prepare( '(%s, %s, %s)', $option, $value, $autoload ); } if ( ! empty( $insert ) ) { $wpdb->query( "INSERT INTO $wpdb->options (option_name, option_value, autoload) VALUES " . $insert ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared } // In case it is set, but blank, update "home". if ( ! __get_option( 'home' ) ) { update_option( 'home', $guessurl ); } // Delete unused options. $unusedoptions = array( 'blodotgsping_url', 'bodyterminator', 'emailtestonly', 'phoneemail_separator', 'smilies_directory', 'subjectprefix', 'use_bbcode', 'use_blodotgsping', 'use_phoneemail', 'use_quicktags', 'use_weblogsping', 'weblogs_cache_file', 'use_preview', 'use_htmltrans', 'smilies_directory', 'fileupload_allowedusers', 'use_phoneemail', 'default_post_status', 'default_post_category', 'archive_mode', 'time_difference', 'links_minadminlevel', 'links_use_adminlevels', 'links_rating_type', 'links_rating_char', 'links_rating_ignore_zero', 'links_rating_single_image', 'links_rating_image0', 'links_rating_image1', 'links_rating_image2', 'links_rating_image3', 'links_rating_image4', 'links_rating_image5', 'links_rating_image6', 'links_rating_image7', 'links_rating_image8', 'links_rating_image9', 'links_recently_updated_time', 'links_recently_updated_prepend', 'links_recently_updated_append', 'weblogs_cacheminutes', 'comment_allowed_tags', 'search_engine_friendly_urls', 'default_geourl_lat', 'default_geourl_lon', 'use_default_geourl', 'weblogs_xml_url', 'new_users_can_blog', '_wpnonce', '_wp_http_referer', 'Update', 'action', 'rich_editing', 'autosave_interval', 'deactivated_plugins', 'can_compress_scripts', 'page_uris', 'update_core', 'update_plugins', 'update_themes', 'doing_cron', 'random_seed', 'rss_excerpt_length', 'secret', 'use_linksupdate', 'default_comment_status_page', 'wporg_popular_tags', 'what_to_show', 'rss_language', 'language', 'enable_xmlrpc', 'enable_app', 'embed_autourls', 'default_post_edit_rows', 'gzipcompression', 'advanced_edit', ); foreach ( $unusedoptions as $option ) { delete_option( $option ); } // Delete obsolete magpie stuff. $wpdb->query( "DELETE FROM $wpdb->options WHERE option_name REGEXP '^rss_[0-9a-f]{32}(_ts)?$'" ); // Clear expired transients. delete_expired_transients( true ); } /** * Execute WordPress role creation for the various WordPress versions. * * @since 2.0.0 */ function populate_roles() { populate_roles_160(); populate_roles_210(); populate_roles_230(); populate_roles_250(); populate_roles_260(); populate_roles_270(); populate_roles_280(); populate_roles_300(); } /** * Create the roles for WordPress 2.0 * * @since 2.0.0 */ function populate_roles_160() { // Add roles. add_role( 'administrator', 'Administrator' ); add_role( 'editor', 'Editor' ); add_role( 'author', 'Author' ); add_role( 'contributor', 'Contributor' ); add_role( 'subscriber', 'Subscriber' ); // Add caps for Administrator role. $role = get_role( 'administrator' ); $role->add_cap( 'switch_themes' ); $role->add_cap( 'edit_themes' ); $role->add_cap( 'activate_plugins' ); $role->add_cap( 'edit_plugins' ); $role->add_cap( 'edit_users' ); $role->add_cap( 'edit_files' ); $role->add_cap( 'manage_options' ); $role->add_cap( 'moderate_comments' ); $role->add_cap( 'manage_categories' ); $role->add_cap( 'manage_links' ); $role->add_cap( 'upload_files' ); $role->add_cap( 'import' ); $role->add_cap( 'unfiltered_html' ); $role->add_cap( 'edit_posts' ); $role->add_cap( 'edit_others_posts' ); $role->add_cap( 'edit_published_posts' ); $role->add_cap( 'publish_posts' ); $role->add_cap( 'edit_pages' ); $role->add_cap( 'read' ); $role->add_cap( 'level_10' ); $role->add_cap( 'level_9' ); $role->add_cap( 'level_8' ); $role->add_cap( 'level_7' ); $role->add_cap( 'level_6' ); $role->add_cap( 'level_5' ); $role->add_cap( 'level_4' ); $role->add_cap( 'level_3' ); $role->add_cap( 'level_2' ); $role->add_cap( 'level_1' ); $role->add_cap( 'level_0' ); // Add caps for Editor role. $role = get_role( 'editor' ); $role->add_cap( 'moderate_comments' ); $role->add_cap( 'manage_categories' ); $role->add_cap( 'manage_links' ); $role->add_cap( 'upload_files' ); $role->add_cap( 'unfiltered_html' ); $role->add_cap( 'edit_posts' ); $role->add_cap( 'edit_others_posts' ); $role->add_cap( 'edit_published_posts' ); $role->add_cap( 'publish_posts' ); $role->add_cap( 'edit_pages' ); $role->add_cap( 'read' ); $role->add_cap( 'level_7' ); $role->add_cap( 'level_6' ); $role->add_cap( 'level_5' ); $role->add_cap( 'level_4' ); $role->add_cap( 'level_3' ); $role->add_cap( 'level_2' ); $role->add_cap( 'level_1' ); $role->add_cap( 'level_0' ); // Add caps for Author role. $role = get_role( 'author' ); $role->add_cap( 'upload_files' ); $role->add_cap( 'edit_posts' ); $role->add_cap( 'edit_published_posts' ); $role->add_cap( 'publish_posts' ); $role->add_cap( 'read' ); $role->add_cap( 'level_2' ); $role->add_cap( 'level_1' ); $role->add_cap( 'level_0' ); // Add caps for Contributor role. $role = get_role( 'contributor' ); $role->add_cap( 'edit_posts' ); $role->add_cap( 'read' ); $role->add_cap( 'level_1' ); $role->add_cap( 'level_0' ); // Add caps for Subscriber role. $role = get_role( 'subscriber' ); $role->add_cap( 'read' ); $role->add_cap( 'level_0' ); } /** * Create and modify WordPress roles for WordPress 2.1. * * @since 2.1.0 */ function populate_roles_210() { $roles = array( 'administrator', 'editor' ); foreach ( $roles as $role ) { $role = get_role( $role ); if ( empty( $role ) ) { continue; } $role->add_cap( 'edit_others_pages' ); $role->add_cap( 'edit_published_pages' ); $role->add_cap( 'publish_pages' ); $role->add_cap( 'delete_pages' ); $role->add_cap( 'delete_others_pages' ); $role->add_cap( 'delete_published_pages' ); $role->add_cap( 'delete_posts' ); $role->add_cap( 'delete_others_posts' ); $role->add_cap( 'delete_published_posts' ); $role->add_cap( 'delete_private_posts' ); $role->add_cap( 'edit_private_posts' ); $role->add_cap( 'read_private_posts' ); $role->add_cap( 'delete_private_pages' ); $role->add_cap( 'edit_private_pages' ); $role->add_cap( 'read_private_pages' ); } $role = get_role( 'administrator' ); if ( ! empty( $role ) ) { $role->add_cap( 'delete_users' ); $role->add_cap( 'create_users' ); } $role = get_role( 'author' ); if ( ! empty( $role ) ) { $role->add_cap( 'delete_posts' ); $role->add_cap( 'delete_published_posts' ); } $role = get_role( 'contributor' ); if ( ! empty( $role ) ) { $role->add_cap( 'delete_posts' ); } } /** * Create and modify WordPress roles for WordPress 2.3. * * @since 2.3.0 */ function populate_roles_230() { $role = get_role( 'administrator' ); if ( ! empty( $role ) ) { $role->add_cap( 'unfiltered_upload' ); } } /** * Create and modify WordPress roles for WordPress 2.5. * * @since 2.5.0 */ function populate_roles_250() { $role = get_role( 'administrator' ); if ( ! empty( $role ) ) { $role->add_cap( 'edit_dashboard' ); } } /** * Create and modify WordPress roles for WordPress 2.6. * * @since 2.6.0 */ function populate_roles_260() { $role = get_role( 'administrator' ); if ( ! empty( $role ) ) { $role->add_cap( 'update_plugins' ); $role->add_cap( 'delete_plugins' ); } } /** * Create and modify WordPress roles for WordPress 2.7. * * @since 2.7.0 */ function populate_roles_270() { $role = get_role( 'administrator' ); if ( ! empty( $role ) ) { $role->add_cap( 'install_plugins' ); $role->add_cap( 'update_themes' ); } } /** * Create and modify WordPress roles for WordPress 2.8. * * @since 2.8.0 */ function populate_roles_280() { $role = get_role( 'administrator' ); if ( ! empty( $role ) ) { $role->add_cap( 'install_themes' ); } } /** * Create and modify WordPress roles for WordPress 3.0. * * @since 3.0.0 */ function populate_roles_300() { $role = get_role( 'administrator' ); if ( ! empty( $role ) ) { $role->add_cap( 'update_core' ); $role->add_cap( 'list_users' ); $role->add_cap( 'remove_users' ); $role->add_cap( 'promote_users' ); $role->add_cap( 'edit_theme_options' ); $role->add_cap( 'delete_themes' ); $role->add_cap( 'export' ); } } if ( ! function_exists( 'install_network' ) ) : /** * Install Network. * * @since 3.0.0 */ function install_network() { if ( ! defined( 'WP_INSTALLING_NETWORK' ) ) { define( 'WP_INSTALLING_NETWORK', true ); } dbDelta( wp_get_db_schema( 'global' ) ); } endif; /** * Populate network settings. * * @since 3.0.0 * * @global wpdb $wpdb WordPress database abstraction object. * @global object $current_site * @global WP_Rewrite $wp_rewrite WordPress rewrite component. * * @param int $network_id ID of network to populate. * @param string $domain The domain name for the network. Example: "example.com". * @param string $email Email address for the network administrator. * @param string $site_name The name of the network. * @param string $path Optional. The path to append to the network's domain name. Default '/'. * @param bool $subdomain_install Optional. Whether the network is a subdomain installation or a subdirectory installation. * Default false, meaning the network is a subdirectory installation. * @return true|WP_Error True on success, or WP_Error on warning (with the installation otherwise successful, * so the error code must be checked) or failure. */ function populate_network( $network_id = 1, $domain = '', $email = '', $site_name = '', $path = '/', $subdomain_install = false ) { global $wpdb, $current_site, $wp_rewrite; $network_id = (int) $network_id; $errors = new WP_Error(); if ( '' === $domain ) { $errors->add( 'empty_domain', __( 'You must provide a domain name.' ) ); } if ( '' === $site_name ) { $errors->add( 'empty_sitename', __( 'You must provide a name for your network of sites.' ) ); } // Check for network collision. $network_exists = false; if ( is_multisite() ) { if ( get_network( $network_id ) ) { $errors->add( 'siteid_exists', __( 'The network already exists.' ) ); } } else { if ( $network_id === (int) $wpdb->get_var( $wpdb->prepare( "SELECT id FROM $wpdb->site WHERE id = %d", $network_id ) ) ) { $errors->add( 'siteid_exists', __( 'The network already exists.' ) ); } } if ( ! is_email( $email ) ) { $errors->add( 'invalid_email', __( 'You must provide a valid email address.' ) ); } if ( $errors->has_errors() ) { return $errors; } if ( 1 === $network_id ) { $wpdb->insert( $wpdb->site, array( 'domain' => $domain, 'path' => $path, ) ); $network_id = $wpdb->insert_id; } else { $wpdb->insert( $wpdb->site, array( 'domain' => $domain, 'path' => $path, 'id' => $network_id, ) ); } populate_network_meta( $network_id, array( 'admin_email' => $email, 'site_name' => $site_name, 'subdomain_install' => $subdomain_install, ) ); /* * When upgrading from single to multisite, assume the current site will * become the main site of the network. When using populate_network() * to create another network in an existing multisite environment, skip * these steps since the main site of the new network has not yet been * created. */ if ( ! is_multisite() ) { $current_site = new stdClass(); $current_site->domain = $domain; $current_site->path = $path; $current_site->site_name = ucfirst( $domain ); $wpdb->insert( $wpdb->blogs, array( 'site_id' => $network_id, 'blog_id' => 1, 'domain' => $domain, 'path' => $path, 'registered' => current_time( 'mysql' ), ) ); $current_site->blog_id = $wpdb->insert_id; $site_user_id = (int) $wpdb->get_var( $wpdb->prepare( "SELECT meta_value FROM $wpdb->sitemeta WHERE meta_key = %s AND site_id = %d", 'admin_user_id', $network_id ) ); update_user_meta( $site_user_id, 'source_domain', $domain ); update_user_meta( $site_user_id, 'primary_blog', $current_site->blog_id ); // Unable to use update_network_option() while populating the network. $wpdb->insert( $wpdb->sitemeta, array( 'site_id' => $network_id, 'meta_key' => 'main_site', 'meta_value' => $current_site->blog_id, ) ); if ( $subdomain_install ) { $wp_rewrite->set_permalink_structure( '/%year%/%monthnum%/%day%/%postname%/' ); } else { $wp_rewrite->set_permalink_structure( '/blog/%year%/%monthnum%/%day%/%postname%/' ); } flush_rewrite_rules(); if ( ! $subdomain_install ) { return true; } $vhost_ok = false; $errstr = ''; $hostname = substr( md5( time() ), 0, 6 ) . '.' . $domain; // Very random hostname! $page = wp_remote_get( 'http://' . $hostname, array( 'timeout' => 5, 'httpversion' => '1.1', ) ); if ( is_wp_error( $page ) ) { $errstr = $page->get_error_message(); } elseif ( 200 === wp_remote_retrieve_response_code( $page ) ) { $vhost_ok = true; } if ( ! $vhost_ok ) { $msg = '

    ' . __( 'Warning! Wildcard DNS may not be configured correctly!' ) . '

    '; $msg .= '

    ' . sprintf( /* translators: %s: Host name. */ __( 'The installer attempted to contact a random hostname (%s) on your domain.' ), '' . $hostname . '' ); if ( ! empty( $errstr ) ) { /* translators: %s: Error message. */ $msg .= ' ' . sprintf( __( 'This resulted in an error message: %s' ), '' . $errstr . '' ); } $msg .= '

    '; $msg .= '

    ' . sprintf( /* translators: %s: Asterisk symbol (*). */ __( 'To use a subdomain configuration, you must have a wildcard entry in your DNS. This usually means adding a %s hostname record pointing at your web server in your DNS configuration tool.' ), '*' ) . '

    '; $msg .= '

    ' . __( 'You can still use your site but any subdomain you create may not be accessible. If you know your DNS is correct, ignore this message.' ) . '

    '; return new WP_Error( 'no_wildcard_dns', $msg ); } } return true; } /** * Creates WordPress network meta and sets the default values. * * @since 5.1.0 * * @global wpdb $wpdb WordPress database abstraction object. * @global int $wp_db_version WordPress database version. * * @param int $network_id Network ID to populate meta for. * @param array $meta Optional. Custom meta $key => $value pairs to use. Default empty array. */ function populate_network_meta( $network_id, array $meta = array() ) { global $wpdb, $wp_db_version; $network_id = (int) $network_id; $email = ! empty( $meta['admin_email'] ) ? $meta['admin_email'] : ''; $subdomain_install = isset( $meta['subdomain_install'] ) ? (int) $meta['subdomain_install'] : 0; // If a user with the provided email does not exist, default to the current user as the new network admin. $site_user = ! empty( $email ) ? get_user_by( 'email', $email ) : false; if ( false === $site_user ) { $site_user = wp_get_current_user(); } if ( empty( $email ) ) { $email = $site_user->user_email; } $template = get_option( 'template' ); $stylesheet = get_option( 'stylesheet' ); $allowed_themes = array( $stylesheet => true ); if ( $template !== $stylesheet ) { $allowed_themes[ $template ] = true; } if ( WP_DEFAULT_THEME !== $stylesheet && WP_DEFAULT_THEME !== $template ) { $allowed_themes[ WP_DEFAULT_THEME ] = true; } // If WP_DEFAULT_THEME doesn't exist, also include the latest core default theme. if ( ! wp_get_theme( WP_DEFAULT_THEME )->exists() ) { $core_default = WP_Theme::get_core_default_theme(); if ( $core_default ) { $allowed_themes[ $core_default->get_stylesheet() ] = true; } } if ( function_exists( 'clean_network_cache' ) ) { clean_network_cache( $network_id ); } else { wp_cache_delete( $network_id, 'networks' ); } if ( ! is_multisite() ) { $site_admins = array( $site_user->user_login ); $users = get_users( array( 'fields' => array( 'user_login' ), 'role' => 'administrator', ) ); if ( $users ) { foreach ( $users as $user ) { $site_admins[] = $user->user_login; } $site_admins = array_unique( $site_admins ); } } else { $site_admins = get_site_option( 'site_admins' ); } /* translators: Do not translate USERNAME, SITE_NAME, BLOG_URL, PASSWORD: those are placeholders. */ $welcome_email = __( 'Howdy USERNAME, Your new SITE_NAME site has been successfully set up at: BLOG_URL You can log in to the administrator account with the following information: Username: USERNAME Password: PASSWORD Log in here: BLOG_URLwp-login.php We hope you enjoy your new site. Thanks! --The Team @ SITE_NAME' ); $allowed_file_types = array(); $all_mime_types = get_allowed_mime_types(); foreach ( $all_mime_types as $ext => $mime ) { array_push( $allowed_file_types, ...explode( '|', $ext ) ); } $upload_filetypes = array_unique( $allowed_file_types ); $sitemeta = array( 'site_name' => __( 'My Network' ), 'admin_email' => $email, 'admin_user_id' => $site_user->ID, 'registration' => 'none', 'upload_filetypes' => implode( ' ', $upload_filetypes ), 'blog_upload_space' => 100, 'fileupload_maxk' => 1500, 'site_admins' => $site_admins, 'allowedthemes' => $allowed_themes, 'illegal_names' => array( 'www', 'web', 'root', 'admin', 'main', 'invite', 'administrator', 'files' ), 'wpmu_upgrade_site' => $wp_db_version, 'welcome_email' => $welcome_email, /* translators: %s: Site link. */ 'first_post' => __( 'Welcome to %s. This is your first post. Edit or delete it, then start writing!' ), // @todo - Network admins should have a method of editing the network siteurl (used for cookie hash). 'siteurl' => get_option( 'siteurl' ) . '/', 'add_new_users' => '0', 'upload_space_check_disabled' => is_multisite() ? get_site_option( 'upload_space_check_disabled' ) : '1', 'subdomain_install' => $subdomain_install, 'ms_files_rewriting' => is_multisite() ? get_site_option( 'ms_files_rewriting' ) : '0', 'user_count' => get_site_option( 'user_count' ), 'initial_db_version' => get_option( 'initial_db_version' ), 'active_sitewide_plugins' => array(), 'WPLANG' => get_locale(), ); if ( ! $subdomain_install ) { $sitemeta['illegal_names'][] = 'blog'; } $sitemeta = wp_parse_args( $meta, $sitemeta ); /** * Filters meta for a network on creation. * * @since 3.7.0 * * @param array $sitemeta Associative array of network meta keys and values to be inserted. * @param int $network_id ID of network to populate. */ $sitemeta = apply_filters( 'populate_network_meta', $sitemeta, $network_id ); $insert = ''; foreach ( $sitemeta as $meta_key => $meta_value ) { if ( is_array( $meta_value ) ) { $meta_value = serialize( $meta_value ); } if ( ! empty( $insert ) ) { $insert .= ', '; } $insert .= $wpdb->prepare( '( %d, %s, %s)', $network_id, $meta_key, $meta_value ); } $wpdb->query( "INSERT INTO $wpdb->sitemeta ( site_id, meta_key, meta_value ) VALUES " . $insert ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared } /** * Creates WordPress site meta and sets the default values. * * @since 5.1.0 * * @global wpdb $wpdb WordPress database abstraction object. * * @param int $site_id Site ID to populate meta for. * @param array $meta Optional. Custom meta $key => $value pairs to use. Default empty array. */ function populate_site_meta( $site_id, array $meta = array() ) { global $wpdb; $site_id = (int) $site_id; if ( ! is_site_meta_supported() ) { return; } if ( empty( $meta ) ) { return; } /** * Filters meta for a site on creation. * * @since 5.2.0 * * @param array $meta Associative array of site meta keys and values to be inserted. * @param int $site_id ID of site to populate. */ $site_meta = apply_filters( 'populate_site_meta', $meta, $site_id ); $insert = ''; foreach ( $site_meta as $meta_key => $meta_value ) { if ( is_array( $meta_value ) ) { $meta_value = serialize( $meta_value ); } if ( ! empty( $insert ) ) { $insert .= ', '; } $insert .= $wpdb->prepare( '( %d, %s, %s)', $site_id, $meta_key, $meta_value ); } $wpdb->query( "INSERT INTO $wpdb->blogmeta ( blog_id, meta_key, meta_value ) VALUES " . $insert ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared wp_cache_delete( $site_id, 'blog_meta' ); wp_cache_set_sites_last_changed(); } bookmark.php000064400000026537147206365750007116 0ustar00' . __( 'You need a higher level of permission.' ) . '' . '

    ' . __( 'Sorry, you are not allowed to edit the links for this site.' ) . '

    ', 403 ); } $_POST['link_url'] = esc_url( $_POST['link_url'] ); $_POST['link_name'] = esc_html( $_POST['link_name'] ); $_POST['link_image'] = esc_html( $_POST['link_image'] ); $_POST['link_rss'] = esc_url( $_POST['link_rss'] ); if ( ! isset( $_POST['link_visible'] ) || 'N' !== $_POST['link_visible'] ) { $_POST['link_visible'] = 'Y'; } if ( ! empty( $link_id ) ) { $_POST['link_id'] = $link_id; return wp_update_link( $_POST ); } else { return wp_insert_link( $_POST ); } } /** * Retrieves the default link for editing. * * @since 2.0.0 * * @return stdClass Default link object. */ function get_default_link_to_edit() { $link = new stdClass(); if ( isset( $_GET['linkurl'] ) ) { $link->link_url = esc_url( wp_unslash( $_GET['linkurl'] ) ); } else { $link->link_url = ''; } if ( isset( $_GET['name'] ) ) { $link->link_name = esc_attr( wp_unslash( $_GET['name'] ) ); } else { $link->link_name = ''; } $link->link_visible = 'Y'; return $link; } /** * Deletes a specified link from the database. * * @since 2.0.0 * * @global wpdb $wpdb WordPress database abstraction object. * * @param int $link_id ID of the link to delete. * @return true Always true. */ function wp_delete_link( $link_id ) { global $wpdb; /** * Fires before a link is deleted. * * @since 2.0.0 * * @param int $link_id ID of the link to delete. */ do_action( 'delete_link', $link_id ); wp_delete_object_term_relationships( $link_id, 'link_category' ); $wpdb->delete( $wpdb->links, array( 'link_id' => $link_id ) ); /** * Fires after a link has been deleted. * * @since 2.2.0 * * @param int $link_id ID of the deleted link. */ do_action( 'deleted_link', $link_id ); clean_bookmark_cache( $link_id ); return true; } /** * Retrieves the link category IDs associated with the link specified. * * @since 2.1.0 * * @param int $link_id Link ID to look up. * @return int[] The IDs of the requested link's categories. */ function wp_get_link_cats( $link_id = 0 ) { $cats = wp_get_object_terms( $link_id, 'link_category', array( 'fields' => 'ids' ) ); return array_unique( $cats ); } /** * Retrieves link data based on its ID. * * @since 2.0.0 * * @param int|stdClass $link Link ID or object to retrieve. * @return object Link object for editing. */ function get_link_to_edit( $link ) { return get_bookmark( $link, OBJECT, 'edit' ); } /** * Inserts a link into the database, or updates an existing link. * * Runs all the necessary sanitizing, provides default values if arguments are missing, * and finally saves the link. * * @since 2.0.0 * * @global wpdb $wpdb WordPress database abstraction object. * * @param array $linkdata { * Elements that make up the link to insert. * * @type int $link_id Optional. The ID of the existing link if updating. * @type string $link_url The URL the link points to. * @type string $link_name The title of the link. * @type string $link_image Optional. A URL of an image. * @type string $link_target Optional. The target element for the anchor tag. * @type string $link_description Optional. A short description of the link. * @type string $link_visible Optional. 'Y' means visible, anything else means not. * @type int $link_owner Optional. A user ID. * @type int $link_rating Optional. A rating for the link. * @type string $link_rel Optional. A relationship of the link to you. * @type string $link_notes Optional. An extended description of or notes on the link. * @type string $link_rss Optional. A URL of an associated RSS feed. * @type int $link_category Optional. The term ID of the link category. * If empty, uses default link category. * } * @param bool $wp_error Optional. Whether to return a WP_Error object on failure. Default false. * @return int|WP_Error Value 0 or WP_Error on failure. The link ID on success. */ function wp_insert_link( $linkdata, $wp_error = false ) { global $wpdb; $defaults = array( 'link_id' => 0, 'link_name' => '', 'link_url' => '', 'link_rating' => 0, ); $parsed_args = wp_parse_args( $linkdata, $defaults ); $parsed_args = wp_unslash( sanitize_bookmark( $parsed_args, 'db' ) ); $link_id = $parsed_args['link_id']; $link_name = $parsed_args['link_name']; $link_url = $parsed_args['link_url']; $update = false; if ( ! empty( $link_id ) ) { $update = true; } if ( '' === trim( $link_name ) ) { if ( '' !== trim( $link_url ) ) { $link_name = $link_url; } else { return 0; } } if ( '' === trim( $link_url ) ) { return 0; } $link_rating = ( ! empty( $parsed_args['link_rating'] ) ) ? $parsed_args['link_rating'] : 0; $link_image = ( ! empty( $parsed_args['link_image'] ) ) ? $parsed_args['link_image'] : ''; $link_target = ( ! empty( $parsed_args['link_target'] ) ) ? $parsed_args['link_target'] : ''; $link_visible = ( ! empty( $parsed_args['link_visible'] ) ) ? $parsed_args['link_visible'] : 'Y'; $link_owner = ( ! empty( $parsed_args['link_owner'] ) ) ? $parsed_args['link_owner'] : get_current_user_id(); $link_notes = ( ! empty( $parsed_args['link_notes'] ) ) ? $parsed_args['link_notes'] : ''; $link_description = ( ! empty( $parsed_args['link_description'] ) ) ? $parsed_args['link_description'] : ''; $link_rss = ( ! empty( $parsed_args['link_rss'] ) ) ? $parsed_args['link_rss'] : ''; $link_rel = ( ! empty( $parsed_args['link_rel'] ) ) ? $parsed_args['link_rel'] : ''; $link_category = ( ! empty( $parsed_args['link_category'] ) ) ? $parsed_args['link_category'] : array(); // Make sure we set a valid category. if ( ! is_array( $link_category ) || 0 === count( $link_category ) ) { $link_category = array( get_option( 'default_link_category' ) ); } if ( $update ) { if ( false === $wpdb->update( $wpdb->links, compact( 'link_url', 'link_name', 'link_image', 'link_target', 'link_description', 'link_visible', 'link_owner', 'link_rating', 'link_rel', 'link_notes', 'link_rss' ), compact( 'link_id' ) ) ) { if ( $wp_error ) { return new WP_Error( 'db_update_error', __( 'Could not update link in the database.' ), $wpdb->last_error ); } else { return 0; } } } else { if ( false === $wpdb->insert( $wpdb->links, compact( 'link_url', 'link_name', 'link_image', 'link_target', 'link_description', 'link_visible', 'link_owner', 'link_rating', 'link_rel', 'link_notes', 'link_rss' ) ) ) { if ( $wp_error ) { return new WP_Error( 'db_insert_error', __( 'Could not insert link into the database.' ), $wpdb->last_error ); } else { return 0; } } $link_id = (int) $wpdb->insert_id; } wp_set_link_cats( $link_id, $link_category ); if ( $update ) { /** * Fires after a link was updated in the database. * * @since 2.0.0 * * @param int $link_id ID of the link that was updated. */ do_action( 'edit_link', $link_id ); } else { /** * Fires after a link was added to the database. * * @since 2.0.0 * * @param int $link_id ID of the link that was added. */ do_action( 'add_link', $link_id ); } clean_bookmark_cache( $link_id ); return $link_id; } /** * Updates link with the specified link categories. * * @since 2.1.0 * * @param int $link_id ID of the link to update. * @param int[] $link_categories Array of link category IDs to add the link to. */ function wp_set_link_cats( $link_id = 0, $link_categories = array() ) { // If $link_categories isn't already an array, make it one: if ( ! is_array( $link_categories ) || 0 === count( $link_categories ) ) { $link_categories = array( get_option( 'default_link_category' ) ); } $link_categories = array_map( 'intval', $link_categories ); $link_categories = array_unique( $link_categories ); wp_set_object_terms( $link_id, $link_categories, 'link_category' ); clean_bookmark_cache( $link_id ); } /** * Updates a link in the database. * * @since 2.0.0 * * @param array $linkdata Link data to update. See wp_insert_link() for accepted arguments. * @return int|WP_Error Value 0 or WP_Error on failure. The updated link ID on success. */ function wp_update_link( $linkdata ) { $link_id = (int) $linkdata['link_id']; $link = get_bookmark( $link_id, ARRAY_A ); // Escape data pulled from DB. $link = wp_slash( $link ); // Passed link category list overwrites existing category list if not empty. if ( isset( $linkdata['link_category'] ) && is_array( $linkdata['link_category'] ) && count( $linkdata['link_category'] ) > 0 ) { $link_cats = $linkdata['link_category']; } else { $link_cats = $link['link_category']; } // Merge old and new fields with new fields overwriting old ones. $linkdata = array_merge( $link, $linkdata ); $linkdata['link_category'] = $link_cats; return wp_insert_link( $linkdata ); } /** * Outputs the 'disabled' message for the WordPress Link Manager. * * @since 3.5.0 * @access private * * @global string $pagenow The filename of the current screen. */ function wp_link_manager_disabled_message() { global $pagenow; if ( ! in_array( $pagenow, array( 'link-manager.php', 'link-add.php', 'link.php' ), true ) ) { return; } add_filter( 'pre_option_link_manager_enabled', '__return_true', 100 ); $really_can_manage_links = current_user_can( 'manage_links' ); remove_filter( 'pre_option_link_manager_enabled', '__return_true', 100 ); if ( $really_can_manage_links ) { $plugins = get_plugins(); if ( empty( $plugins['link-manager/link-manager.php'] ) ) { if ( current_user_can( 'install_plugins' ) ) { $install_url = wp_nonce_url( self_admin_url( 'update.php?action=install-plugin&plugin=link-manager' ), 'install-plugin_link-manager' ); wp_die( sprintf( /* translators: %s: A link to install the Link Manager plugin. */ __( 'If you are looking to use the link manager, please install the Link Manager plugin.' ), esc_url( $install_url ) ) ); } } elseif ( is_plugin_inactive( 'link-manager/link-manager.php' ) ) { if ( current_user_can( 'activate_plugins' ) ) { $activate_url = wp_nonce_url( self_admin_url( 'plugins.php?action=activate&plugin=link-manager/link-manager.php' ), 'activate-plugin_link-manager/link-manager.php' ); wp_die( sprintf( /* translators: %s: A link to activate the Link Manager plugin. */ __( 'Please activate the Link Manager plugin to use the link manager.' ), esc_url( $activate_url ) ) ); } } } wp_die( __( 'Sorry, you are not allowed to edit the links for this site.' ) ); } class-wp-ms-sites-list-table.php000064400000053012147206365750012626 0ustar00status_list = array( 'archived' => array( 'site-archived', __( 'Archived' ) ), 'spam' => array( 'site-spammed', _x( 'Spam', 'site' ) ), 'deleted' => array( 'site-deleted', __( 'Deleted' ) ), 'mature' => array( 'site-mature', __( 'Mature' ) ), ); parent::__construct( array( 'plural' => 'sites', 'screen' => isset( $args['screen'] ) ? $args['screen'] : null, ) ); } /** * @return bool */ public function ajax_user_can() { return current_user_can( 'manage_sites' ); } /** * Prepares the list of sites for display. * * @since 3.1.0 * * @global string $mode List table view mode. * @global string $s * @global wpdb $wpdb WordPress database abstraction object. */ public function prepare_items() { global $mode, $s, $wpdb; if ( ! empty( $_REQUEST['mode'] ) ) { $mode = 'excerpt' === $_REQUEST['mode'] ? 'excerpt' : 'list'; set_user_setting( 'sites_list_mode', $mode ); } else { $mode = get_user_setting( 'sites_list_mode', 'list' ); } $per_page = $this->get_items_per_page( 'sites_network_per_page' ); $pagenum = $this->get_pagenum(); $s = isset( $_REQUEST['s'] ) ? wp_unslash( trim( $_REQUEST['s'] ) ) : ''; $wild = ''; if ( str_contains( $s, '*' ) ) { $wild = '*'; $s = trim( $s, '*' ); } /* * If the network is large and a search is not being performed, show only * the latest sites with no paging in order to avoid expensive count queries. */ if ( ! $s && wp_is_large_network() ) { if ( ! isset( $_REQUEST['orderby'] ) ) { $_GET['orderby'] = ''; $_REQUEST['orderby'] = ''; } if ( ! isset( $_REQUEST['order'] ) ) { $_GET['order'] = 'DESC'; $_REQUEST['order'] = 'DESC'; } } $args = array( 'number' => (int) $per_page, 'offset' => (int) ( ( $pagenum - 1 ) * $per_page ), 'network_id' => get_current_network_id(), ); if ( empty( $s ) ) { // Nothing to do. } elseif ( preg_match( '/^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$/', $s ) || preg_match( '/^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.?$/', $s ) || preg_match( '/^[0-9]{1,3}\.[0-9]{1,3}\.?$/', $s ) || preg_match( '/^[0-9]{1,3}\.$/', $s ) ) { // IPv4 address. $sql = $wpdb->prepare( "SELECT blog_id FROM {$wpdb->registration_log} WHERE {$wpdb->registration_log}.IP LIKE %s", $wpdb->esc_like( $s ) . ( ! empty( $wild ) ? '%' : '' ) ); $reg_blog_ids = $wpdb->get_col( $sql ); if ( $reg_blog_ids ) { $args['site__in'] = $reg_blog_ids; } } elseif ( is_numeric( $s ) && empty( $wild ) ) { $args['ID'] = $s; } else { $args['search'] = $s; if ( ! is_subdomain_install() ) { $args['search_columns'] = array( 'path' ); } } $order_by = isset( $_REQUEST['orderby'] ) ? $_REQUEST['orderby'] : ''; if ( 'registered' === $order_by ) { // 'registered' is a valid field name. } elseif ( 'lastupdated' === $order_by ) { $order_by = 'last_updated'; } elseif ( 'blogname' === $order_by ) { if ( is_subdomain_install() ) { $order_by = 'domain'; } else { $order_by = 'path'; } } elseif ( 'blog_id' === $order_by ) { $order_by = 'id'; } elseif ( ! $order_by ) { $order_by = false; } $args['orderby'] = $order_by; if ( $order_by ) { $args['order'] = ( isset( $_REQUEST['order'] ) && 'DESC' === strtoupper( $_REQUEST['order'] ) ) ? 'DESC' : 'ASC'; } if ( wp_is_large_network() ) { $args['no_found_rows'] = true; } else { $args['no_found_rows'] = false; } // Take into account the role the user has selected. $status = isset( $_REQUEST['status'] ) ? wp_unslash( trim( $_REQUEST['status'] ) ) : ''; if ( in_array( $status, array( 'public', 'archived', 'mature', 'spam', 'deleted' ), true ) ) { $args[ $status ] = 1; } /** * Filters the arguments for the site query in the sites list table. * * @since 4.6.0 * * @param array $args An array of get_sites() arguments. */ $args = apply_filters( 'ms_sites_list_table_query_args', $args ); $_sites = get_sites( $args ); if ( is_array( $_sites ) ) { update_site_cache( $_sites ); $this->items = array_slice( $_sites, 0, $per_page ); } $total_sites = get_sites( array_merge( $args, array( 'count' => true, 'offset' => 0, 'number' => 0, ) ) ); $this->set_pagination_args( array( 'total_items' => $total_sites, 'per_page' => $per_page, ) ); } /** */ public function no_items() { _e( 'No sites found.' ); } /** * Gets links to filter sites by status. * * @since 5.3.0 * * @return array */ protected function get_views() { $counts = wp_count_sites(); $statuses = array( /* translators: %s: Number of sites. */ 'all' => _nx_noop( 'All (%s)', 'All (%s)', 'sites' ), /* translators: %s: Number of sites. */ 'public' => _n_noop( 'Public (%s)', 'Public (%s)' ), /* translators: %s: Number of sites. */ 'archived' => _n_noop( 'Archived (%s)', 'Archived (%s)' ), /* translators: %s: Number of sites. */ 'mature' => _n_noop( 'Mature (%s)', 'Mature (%s)' ), /* translators: %s: Number of sites. */ 'spam' => _nx_noop( 'Spam (%s)', 'Spam (%s)', 'sites' ), /* translators: %s: Number of sites. */ 'deleted' => _n_noop( 'Deleted (%s)', 'Deleted (%s)' ), ); $view_links = array(); $requested_status = isset( $_REQUEST['status'] ) ? wp_unslash( trim( $_REQUEST['status'] ) ) : ''; $url = 'sites.php'; foreach ( $statuses as $status => $label_count ) { if ( (int) $counts[ $status ] > 0 ) { $label = sprintf( translate_nooped_plural( $label_count, $counts[ $status ] ), number_format_i18n( $counts[ $status ] ) ); $full_url = 'all' === $status ? $url : add_query_arg( 'status', $status, $url ); $view_links[ $status ] = array( 'url' => esc_url( $full_url ), 'label' => $label, 'current' => $requested_status === $status || ( '' === $requested_status && 'all' === $status ), ); } } return $this->get_views_links( $view_links ); } /** * @return array */ protected function get_bulk_actions() { $actions = array(); if ( current_user_can( 'delete_sites' ) ) { $actions['delete'] = __( 'Delete' ); } $actions['spam'] = _x( 'Mark as spam', 'site' ); $actions['notspam'] = _x( 'Not spam', 'site' ); return $actions; } /** * @global string $mode List table view mode. * * @param string $which The location of the pagination nav markup: Either 'top' or 'bottom'. */ protected function pagination( $which ) { global $mode; parent::pagination( $which ); if ( 'top' === $which ) { $this->view_switcher( $mode ); } } /** * Displays extra controls between bulk actions and pagination. * * @since 5.3.0 * * @param string $which The location of the extra table nav markup: Either 'top' or 'bottom'. */ protected function extra_tablenav( $which ) { ?>
    'site-query-submit' ) ); } } ?>
    '', 'blogname' => __( 'URL' ), 'lastupdated' => __( 'Last Updated' ), 'registered' => _x( 'Registered', 'site' ), 'users' => __( 'Users' ), ); if ( has_filter( 'wpmublogsaction' ) ) { $sites_columns['plugins'] = __( 'Actions' ); } /** * Filters the displayed site columns in Sites list table. * * @since MU (3.0.0) * * @param string[] $sites_columns An array of displayed site columns. Default 'cb', * 'blogname', 'lastupdated', 'registered', 'users'. */ return apply_filters( 'wpmu_blogs_columns', $sites_columns ); } /** * @return array */ protected function get_sortable_columns() { if ( is_subdomain_install() ) { $blogname_abbr = __( 'Domain' ); $blogname_orderby_text = __( 'Table ordered by Site Domain Name.' ); } else { $blogname_abbr = __( 'Path' ); $blogname_orderby_text = __( 'Table ordered by Site Path.' ); } return array( 'blogname' => array( 'blogname', false, $blogname_abbr, $blogname_orderby_text ), 'lastupdated' => array( 'lastupdated', true, __( 'Last Updated' ), __( 'Table ordered by Last Updated.' ) ), 'registered' => array( 'blog_id', true, _x( 'Registered', 'site' ), __( 'Table ordered by Site Registered Date.' ), 'desc' ), ); } /** * Handles the checkbox column output. * * @since 4.3.0 * @since 5.9.0 Renamed `$blog` to `$item` to match parent class for PHP 8 named parameter support. * * @param array $item Current site. */ public function column_cb( $item ) { // Restores the more descriptive, specific name for use within this method. $blog = $item; if ( ! is_main_site( $blog['blog_id'] ) ) : $blogname = untrailingslashit( $blog['domain'] . $blog['path'] ); ?> %2$s', esc_url( network_admin_url( 'site-info.php?id=' . $blog['blog_id'] ) ), $blogname ); $this->site_states( $blog ); ?> '; printf( /* translators: 1: Site title, 2: Site tagline. */ __( '%1$s – %2$s' ), get_option( 'blogname' ), '' . get_option( 'blogdescription' ) . '' ); echo '

    '; restore_current_blog(); } } /** * Handles the lastupdated column output. * * @since 4.3.0 * * @global string $mode List table view mode. * * @param array $blog Current site. */ public function column_lastupdated( $blog ) { global $mode; if ( 'list' === $mode ) { $date = __( 'Y/m/d' ); } else { $date = __( 'Y/m/d g:i:s a' ); } if ( '0000-00-00 00:00:00' === $blog['last_updated'] ) { _e( 'Never' ); } else { echo mysql2date( $date, $blog['last_updated'] ); } } /** * Handles the registered column output. * * @since 4.3.0 * * @global string $mode List table view mode. * * @param array $blog Current site. */ public function column_registered( $blog ) { global $mode; if ( 'list' === $mode ) { $date = __( 'Y/m/d' ); } else { $date = __( 'Y/m/d g:i:s a' ); } if ( '0000-00-00 00:00:00' === $blog['registered'] ) { echo '—'; } else { echo mysql2date( $date, $blog['registered'] ); } } /** * Handles the users column output. * * @since 4.3.0 * * @param array $blog Current site. */ public function column_users( $blog ) { $user_count = wp_cache_get( $blog['blog_id'] . '_user_count', 'blog-details' ); if ( ! $user_count ) { $blog_users = new WP_User_Query( array( 'blog_id' => $blog['blog_id'], 'fields' => 'ID', 'number' => 1, 'count_total' => true, ) ); $user_count = $blog_users->get_total(); wp_cache_set( $blog['blog_id'] . '_user_count', $user_count, 'blog-details', 12 * HOUR_IN_SECONDS ); } printf( '%2$s', esc_url( network_admin_url( 'site-users.php?id=' . $blog['blog_id'] ) ), number_format_i18n( $user_count ) ); } /** * Handles the plugins column output. * * @since 4.3.0 * * @param array $blog Current site. */ public function column_plugins( $blog ) { if ( has_filter( 'wpmublogsaction' ) ) { /** * Fires inside the auxiliary 'Actions' column of the Sites list table. * * By default this column is hidden unless something is hooked to the action. * * @since MU (3.0.0) * * @param int $blog_id The site ID. */ do_action( 'wpmublogsaction', $blog['blog_id'] ); } } /** * Handles output for the default column. * * @since 4.3.0 * @since 5.9.0 Renamed `$blog` to `$item` to match parent class for PHP 8 named parameter support. * * @param array $item Current site. * @param string $column_name Current column name. */ public function column_default( $item, $column_name ) { // Restores the more descriptive, specific name for use within this method. $blog = $item; /** * Fires for each registered custom column in the Sites list table. * * @since 3.1.0 * * @param string $column_name The name of the column to display. * @param int $blog_id The site ID. */ do_action( 'manage_sites_custom_column', $column_name, $blog['blog_id'] ); } /** * Generates the list table rows. * * @since 3.1.0 */ public function display_rows() { foreach ( $this->items as $blog ) { $blog = $blog->to_array(); $class = ''; reset( $this->status_list ); foreach ( $this->status_list as $status => $col ) { if ( '1' === $blog[ $status ] ) { $class = " class='{$col[0]}'"; } } echo ""; $this->single_row_columns( $blog ); echo ''; } } /** * Determines whether to output comma-separated site states. * * @since 5.3.0 * * @param array $site */ protected function site_states( $site ) { $site_states = array(); // $site is still an array, so get the object. $_site = WP_Site::get_instance( $site['blog_id'] ); if ( is_main_site( $_site->id ) ) { $site_states['main'] = __( 'Main' ); } reset( $this->status_list ); $site_status = isset( $_REQUEST['status'] ) ? wp_unslash( trim( $_REQUEST['status'] ) ) : ''; foreach ( $this->status_list as $status => $col ) { if ( '1' === $_site->{$status} && $site_status !== $status ) { $site_states[ $col[0] ] = $col[1]; } } /** * Filters the default site display states for items in the Sites list table. * * @since 5.3.0 * * @param string[] $site_states An array of site states. Default 'Main', * 'Archived', 'Mature', 'Spam', 'Deleted'. * @param WP_Site $site The current site object. */ $site_states = apply_filters( 'display_site_states', $site_states, $_site ); if ( ! empty( $site_states ) ) { $state_count = count( $site_states ); $i = 0; echo ' — '; foreach ( $site_states as $state ) { ++$i; $separator = ( $i < $state_count ) ? ', ' : ''; echo "{$state}{$separator}"; } } } /** * Gets the name of the default primary column. * * @since 4.3.0 * * @return string Name of the default primary column, in this case, 'blogname'. */ protected function get_default_primary_column_name() { return 'blogname'; } /** * Generates and displays row action links. * * @since 4.3.0 * @since 5.9.0 Renamed `$blog` to `$item` to match parent class for PHP 8 named parameter support. * * @param array $item Site being acted upon. * @param string $column_name Current column name. * @param string $primary Primary column name. * @return string Row actions output for sites in Multisite, or an empty string * if the current column is not the primary column. */ protected function handle_row_actions( $item, $column_name, $primary ) { if ( $primary !== $column_name ) { return ''; } // Restores the more descriptive, specific name for use within this method. $blog = $item; $blogname = untrailingslashit( $blog['domain'] . $blog['path'] ); // Preordered. $actions = array( 'edit' => '', 'backend' => '', 'activate' => '', 'deactivate' => '', 'archive' => '', 'unarchive' => '', 'spam' => '', 'unspam' => '', 'delete' => '', 'visit' => '', ); $actions['edit'] = sprintf( '%2$s', esc_url( network_admin_url( 'site-info.php?id=' . $blog['blog_id'] ) ), __( 'Edit' ) ); $actions['backend'] = sprintf( '%2$s', esc_url( get_admin_url( $blog['blog_id'] ) ), __( 'Dashboard' ) ); if ( ! is_main_site( $blog['blog_id'] ) ) { if ( '1' === $blog['deleted'] ) { $actions['activate'] = sprintf( '%2$s', esc_url( wp_nonce_url( network_admin_url( 'sites.php?action=confirm&action2=activateblog&id=' . $blog['blog_id'] ), 'activateblog_' . $blog['blog_id'] ) ), _x( 'Activate', 'site' ) ); } else { $actions['deactivate'] = sprintf( '%2$s', esc_url( wp_nonce_url( network_admin_url( 'sites.php?action=confirm&action2=deactivateblog&id=' . $blog['blog_id'] ), 'deactivateblog_' . $blog['blog_id'] ) ), __( 'Deactivate' ) ); } if ( '1' === $blog['archived'] ) { $actions['unarchive'] = sprintf( '%2$s', esc_url( wp_nonce_url( network_admin_url( 'sites.php?action=confirm&action2=unarchiveblog&id=' . $blog['blog_id'] ), 'unarchiveblog_' . $blog['blog_id'] ) ), __( 'Unarchive' ) ); } else { $actions['archive'] = sprintf( '%2$s', esc_url( wp_nonce_url( network_admin_url( 'sites.php?action=confirm&action2=archiveblog&id=' . $blog['blog_id'] ), 'archiveblog_' . $blog['blog_id'] ) ), _x( 'Archive', 'verb; site' ) ); } if ( '1' === $blog['spam'] ) { $actions['unspam'] = sprintf( '%2$s', esc_url( wp_nonce_url( network_admin_url( 'sites.php?action=confirm&action2=unspamblog&id=' . $blog['blog_id'] ), 'unspamblog_' . $blog['blog_id'] ) ), _x( 'Not Spam', 'site' ) ); } else { $actions['spam'] = sprintf( '%2$s', esc_url( wp_nonce_url( network_admin_url( 'sites.php?action=confirm&action2=spamblog&id=' . $blog['blog_id'] ), 'spamblog_' . $blog['blog_id'] ) ), _x( 'Spam', 'site' ) ); } if ( current_user_can( 'delete_site', $blog['blog_id'] ) ) { $actions['delete'] = sprintf( '%2$s', esc_url( wp_nonce_url( network_admin_url( 'sites.php?action=confirm&action2=deleteblog&id=' . $blog['blog_id'] ), 'deleteblog_' . $blog['blog_id'] ) ), __( 'Delete' ) ); } } $actions['visit'] = sprintf( '%2$s', esc_url( get_home_url( $blog['blog_id'], '/' ) ), __( 'Visit' ) ); /** * Filters the action links displayed for each site in the Sites list table. * * The 'Edit', 'Dashboard', 'Delete', and 'Visit' links are displayed by * default for each site. The site's status determines whether to show the * 'Activate' or 'Deactivate' link, 'Unarchive' or 'Archive' links, and * 'Not Spam' or 'Spam' link for each site. * * @since 3.1.0 * * @param string[] $actions An array of action links to be displayed. * @param int $blog_id The site ID. * @param string $blogname Site path, formatted depending on whether it is a sub-domain * or subdirectory multisite installation. */ $actions = apply_filters( 'manage_sites_action_links', array_filter( $actions ), $blog['blog_id'], $blogname ); return $this->row_actions( $actions ); } } class-language-pack-upgrader.php000064400000036311147206365750012711 0ustar00is_vcs_checkout( WP_CONTENT_DIR ) ) { return; } foreach ( $language_updates as $key => $language_update ) { $update = ! empty( $language_update->autoupdate ); /** * Filters whether to asynchronously update translation for core, a plugin, or a theme. * * @since 4.0.0 * * @param bool $update Whether to update. * @param object $language_update The update offer. */ $update = apply_filters( 'async_update_translation', $update, $language_update ); if ( ! $update ) { unset( $language_updates[ $key ] ); } } if ( empty( $language_updates ) ) { return; } // Re-use the automatic upgrader skin if the parent upgrader is using it. if ( $upgrader && $upgrader->skin instanceof Automatic_Upgrader_Skin ) { $skin = $upgrader->skin; } else { $skin = new Language_Pack_Upgrader_Skin( array( 'skip_header_footer' => true, ) ); } $lp_upgrader = new Language_Pack_Upgrader( $skin ); $lp_upgrader->bulk_upgrade( $language_updates ); } /** * Initializes the upgrade strings. * * @since 3.7.0 */ public function upgrade_strings() { $this->strings['starting_upgrade'] = __( 'Some of your translations need updating. Sit tight for a few more seconds while they are updated as well.' ); $this->strings['up_to_date'] = __( 'Your translations are all up to date.' ); $this->strings['no_package'] = __( 'Update package not available.' ); /* translators: %s: Package URL. */ $this->strings['downloading_package'] = sprintf( __( 'Downloading translation from %s…' ), '%s' ); $this->strings['unpack_package'] = __( 'Unpacking the update…' ); $this->strings['process_failed'] = __( 'Translation update failed.' ); $this->strings['process_success'] = __( 'Translation updated successfully.' ); $this->strings['remove_old'] = __( 'Removing the old version of the translation…' ); $this->strings['remove_old_failed'] = __( 'Could not remove the old translation.' ); } /** * Upgrades a language pack. * * @since 3.7.0 * * @param string|false $update Optional. Whether an update offer is available. Default false. * @param array $args Optional. Other optional arguments, see * Language_Pack_Upgrader::bulk_upgrade(). Default empty array. * @return array|bool|WP_Error The result of the upgrade, or a WP_Error object instead. */ public function upgrade( $update = false, $args = array() ) { if ( $update ) { $update = array( $update ); } $results = $this->bulk_upgrade( $update, $args ); if ( ! is_array( $results ) ) { return $results; } return $results[0]; } /** * Upgrades several language packs at once. * * @since 3.7.0 * * @global WP_Filesystem_Base $wp_filesystem WordPress filesystem subclass. * * @param object[] $language_updates Optional. Array of language packs to update. See {@see wp_get_translation_updates()}. * Default empty array. * @param array $args { * Other arguments for upgrading multiple language packs. Default empty array. * * @type bool $clear_update_cache Whether to clear the update cache when done. * Default true. * } * @return array|bool|WP_Error Will return an array of results, or true if there are no updates, * false or WP_Error for initial errors. */ public function bulk_upgrade( $language_updates = array(), $args = array() ) { global $wp_filesystem; $defaults = array( 'clear_update_cache' => true, ); $parsed_args = wp_parse_args( $args, $defaults ); $this->init(); $this->upgrade_strings(); if ( ! $language_updates ) { $language_updates = wp_get_translation_updates(); } if ( empty( $language_updates ) ) { $this->skin->header(); $this->skin->set_result( true ); $this->skin->feedback( 'up_to_date' ); $this->skin->bulk_footer(); $this->skin->footer(); return true; } if ( 'upgrader_process_complete' === current_filter() ) { $this->skin->feedback( 'starting_upgrade' ); } // Remove any existing upgrade filters from the plugin/theme upgraders #WP29425 & #WP29230. remove_all_filters( 'upgrader_pre_install' ); remove_all_filters( 'upgrader_clear_destination' ); remove_all_filters( 'upgrader_post_install' ); remove_all_filters( 'upgrader_source_selection' ); add_filter( 'upgrader_source_selection', array( $this, 'check_package' ), 10, 2 ); $this->skin->header(); // Connect to the filesystem first. $res = $this->fs_connect( array( WP_CONTENT_DIR, WP_LANG_DIR ) ); if ( ! $res ) { $this->skin->footer(); return false; } $results = array(); $this->update_count = count( $language_updates ); $this->update_current = 0; /* * The filesystem's mkdir() is not recursive. Make sure WP_LANG_DIR exists, * as we then may need to create a /plugins or /themes directory inside of it. */ $remote_destination = $wp_filesystem->find_folder( WP_LANG_DIR ); if ( ! $wp_filesystem->exists( $remote_destination ) ) { if ( ! $wp_filesystem->mkdir( $remote_destination, FS_CHMOD_DIR ) ) { return new WP_Error( 'mkdir_failed_lang_dir', $this->strings['mkdir_failed'], $remote_destination ); } } $language_updates_results = array(); foreach ( $language_updates as $language_update ) { $this->skin->language_update = $language_update; $destination = WP_LANG_DIR; if ( 'plugin' === $language_update->type ) { $destination .= '/plugins'; } elseif ( 'theme' === $language_update->type ) { $destination .= '/themes'; } ++$this->update_current; $options = array( 'package' => $language_update->package, 'destination' => $destination, 'clear_destination' => true, 'abort_if_destination_exists' => false, // We expect the destination to exist. 'clear_working' => true, 'is_multi' => true, 'hook_extra' => array( 'language_update_type' => $language_update->type, 'language_update' => $language_update, ), ); $result = $this->run( $options ); $results[] = $this->result; // Prevent credentials auth screen from displaying multiple times. if ( false === $result ) { break; } $language_updates_results[] = array( 'language' => $language_update->language, 'type' => $language_update->type, 'slug' => isset( $language_update->slug ) ? $language_update->slug : 'default', 'version' => $language_update->version, ); } // Remove upgrade hooks which are not required for translation updates. remove_action( 'upgrader_process_complete', array( 'Language_Pack_Upgrader', 'async_upgrade' ), 20 ); remove_action( 'upgrader_process_complete', 'wp_version_check' ); remove_action( 'upgrader_process_complete', 'wp_update_plugins' ); remove_action( 'upgrader_process_complete', 'wp_update_themes' ); /** This action is documented in wp-admin/includes/class-wp-upgrader.php */ do_action( 'upgrader_process_complete', $this, array( 'action' => 'update', 'type' => 'translation', 'bulk' => true, 'translations' => $language_updates_results, ) ); // Re-add upgrade hooks. add_action( 'upgrader_process_complete', array( 'Language_Pack_Upgrader', 'async_upgrade' ), 20 ); add_action( 'upgrader_process_complete', 'wp_version_check', 10, 0 ); add_action( 'upgrader_process_complete', 'wp_update_plugins', 10, 0 ); add_action( 'upgrader_process_complete', 'wp_update_themes', 10, 0 ); $this->skin->bulk_footer(); $this->skin->footer(); // Clean up our hooks, in case something else does an upgrade on this connection. remove_filter( 'upgrader_source_selection', array( $this, 'check_package' ) ); if ( $parsed_args['clear_update_cache'] ) { wp_clean_update_cache(); } return $results; } /** * Checks that the package source contains .mo and .po files. * * Hooked to the {@see 'upgrader_source_selection'} filter by * Language_Pack_Upgrader::bulk_upgrade(). * * @since 3.7.0 * * @global WP_Filesystem_Base $wp_filesystem WordPress filesystem subclass. * * @param string|WP_Error $source The path to the downloaded package source. * @param string $remote_source Remote file source location. * @return string|WP_Error The source as passed, or a WP_Error object on failure. */ public function check_package( $source, $remote_source ) { global $wp_filesystem; if ( is_wp_error( $source ) ) { return $source; } // Check that the folder contains a valid language. $files = $wp_filesystem->dirlist( $remote_source ); // Check to see if the expected files exist in the folder. $po = false; $mo = false; $php = false; foreach ( (array) $files as $file => $filedata ) { if ( str_ends_with( $file, '.po' ) ) { $po = true; } elseif ( str_ends_with( $file, '.mo' ) ) { $mo = true; } elseif ( str_ends_with( $file, '.l10n.php' ) ) { $php = true; } } if ( $php ) { return $source; } if ( ! $mo || ! $po ) { return new WP_Error( 'incompatible_archive_pomo', $this->strings['incompatible_archive'], sprintf( /* translators: 1: .po, 2: .mo, 3: .l10n.php */ __( 'The language pack is missing either the %1$s, %2$s, or %3$s files.' ), '.po', '.mo', '.l10n.php' ) ); } return $source; } /** * Gets the name of an item being updated. * * @since 3.7.0 * * @param object $update The data for an update. * @return string The name of the item being updated. */ public function get_name_for_update( $update ) { switch ( $update->type ) { case 'core': return 'WordPress'; // Not translated. case 'theme': $theme = wp_get_theme( $update->slug ); if ( $theme->exists() ) { return $theme->Get( 'Name' ); } break; case 'plugin': $plugin_data = get_plugins( '/' . $update->slug ); $plugin_data = reset( $plugin_data ); if ( $plugin_data ) { return $plugin_data['Name']; } break; } return ''; } /** * Clears existing translations where this item is going to be installed into. * * @since 5.1.0 * * @global WP_Filesystem_Base $wp_filesystem WordPress filesystem subclass. * * @param string $remote_destination The location on the remote filesystem to be cleared. * @return bool|WP_Error True upon success, WP_Error on failure. */ public function clear_destination( $remote_destination ) { global $wp_filesystem; $language_update = $this->skin->language_update; $language_directory = WP_LANG_DIR . '/'; // Local path for use with glob(). if ( 'core' === $language_update->type ) { $files = array( $remote_destination . $language_update->language . '.po', $remote_destination . $language_update->language . '.mo', $remote_destination . $language_update->language . '.l10n.php', $remote_destination . 'admin-' . $language_update->language . '.po', $remote_destination . 'admin-' . $language_update->language . '.mo', $remote_destination . 'admin-' . $language_update->language . '.l10n.php', $remote_destination . 'admin-network-' . $language_update->language . '.po', $remote_destination . 'admin-network-' . $language_update->language . '.mo', $remote_destination . 'admin-network-' . $language_update->language . '.l10n.php', $remote_destination . 'continents-cities-' . $language_update->language . '.po', $remote_destination . 'continents-cities-' . $language_update->language . '.mo', $remote_destination . 'continents-cities-' . $language_update->language . '.l10n.php', ); $json_translation_files = glob( $language_directory . $language_update->language . '-*.json' ); if ( $json_translation_files ) { foreach ( $json_translation_files as $json_translation_file ) { $files[] = str_replace( $language_directory, $remote_destination, $json_translation_file ); } } } else { $files = array( $remote_destination . $language_update->slug . '-' . $language_update->language . '.po', $remote_destination . $language_update->slug . '-' . $language_update->language . '.mo', $remote_destination . $language_update->slug . '-' . $language_update->language . '.l10n.php', ); $language_directory = $language_directory . $language_update->type . 's/'; $json_translation_files = glob( $language_directory . $language_update->slug . '-' . $language_update->language . '-*.json' ); if ( $json_translation_files ) { foreach ( $json_translation_files as $json_translation_file ) { $files[] = str_replace( $language_directory, $remote_destination, $json_translation_file ); } } } $files = array_filter( $files, array( $wp_filesystem, 'exists' ) ); // No files to delete. if ( ! $files ) { return true; } // Check all files are writable before attempting to clear the destination. $unwritable_files = array(); // Check writability. foreach ( $files as $file ) { if ( ! $wp_filesystem->is_writable( $file ) ) { // Attempt to alter permissions to allow writes and try again. $wp_filesystem->chmod( $file, FS_CHMOD_FILE ); if ( ! $wp_filesystem->is_writable( $file ) ) { $unwritable_files[] = $file; } } } if ( ! empty( $unwritable_files ) ) { return new WP_Error( 'files_not_writable', $this->strings['files_not_writable'], implode( ', ', $unwritable_files ) ); } foreach ( $files as $file ) { if ( ! $wp_filesystem->delete( $file ) ) { return new WP_Error( 'remove_old_failed', $this->strings['remove_old_failed'] ); } } return true; } } comment.php000064400000013751147206365750006745 0ustar00get_var( $wpdb->prepare( "SELECT comment_post_ID FROM $wpdb->comments WHERE comment_author = %s AND $date_field = %s", stripslashes( $comment_author ), stripslashes( $comment_date ) ) ); } /** * Updates a comment with values provided in $_POST. * * @since 2.0.0 * @since 5.5.0 A return value was added. * * @return int|WP_Error The value 1 if the comment was updated, 0 if not updated. * A WP_Error object on failure. */ function edit_comment() { if ( ! current_user_can( 'edit_comment', (int) $_POST['comment_ID'] ) ) { wp_die( __( 'Sorry, you are not allowed to edit comments on this post.' ) ); } if ( isset( $_POST['newcomment_author'] ) ) { $_POST['comment_author'] = $_POST['newcomment_author']; } if ( isset( $_POST['newcomment_author_email'] ) ) { $_POST['comment_author_email'] = $_POST['newcomment_author_email']; } if ( isset( $_POST['newcomment_author_url'] ) ) { $_POST['comment_author_url'] = $_POST['newcomment_author_url']; } if ( isset( $_POST['comment_status'] ) ) { $_POST['comment_approved'] = $_POST['comment_status']; } if ( isset( $_POST['content'] ) ) { $_POST['comment_content'] = $_POST['content']; } if ( isset( $_POST['comment_ID'] ) ) { $_POST['comment_ID'] = (int) $_POST['comment_ID']; } foreach ( array( 'aa', 'mm', 'jj', 'hh', 'mn' ) as $timeunit ) { if ( ! empty( $_POST[ 'hidden_' . $timeunit ] ) && $_POST[ 'hidden_' . $timeunit ] !== $_POST[ $timeunit ] ) { $_POST['edit_date'] = '1'; break; } } if ( ! empty( $_POST['edit_date'] ) ) { $aa = $_POST['aa']; $mm = $_POST['mm']; $jj = $_POST['jj']; $hh = $_POST['hh']; $mn = $_POST['mn']; $ss = $_POST['ss']; $jj = ( $jj > 31 ) ? 31 : $jj; $hh = ( $hh > 23 ) ? $hh - 24 : $hh; $mn = ( $mn > 59 ) ? $mn - 60 : $mn; $ss = ( $ss > 59 ) ? $ss - 60 : $ss; $_POST['comment_date'] = "$aa-$mm-$jj $hh:$mn:$ss"; } return wp_update_comment( $_POST, true ); } /** * Returns a WP_Comment object based on comment ID. * * @since 2.0.0 * * @param int $id ID of comment to retrieve. * @return WP_Comment|false Comment if found. False on failure. */ function get_comment_to_edit( $id ) { $comment = get_comment( $id ); if ( ! $comment ) { return false; } $comment->comment_ID = (int) $comment->comment_ID; $comment->comment_post_ID = (int) $comment->comment_post_ID; $comment->comment_content = format_to_edit( $comment->comment_content ); /** * Filters the comment content before editing. * * @since 2.0.0 * * @param string $comment_content Comment content. */ $comment->comment_content = apply_filters( 'comment_edit_pre', $comment->comment_content ); $comment->comment_author = format_to_edit( $comment->comment_author ); $comment->comment_author_email = format_to_edit( $comment->comment_author_email ); $comment->comment_author_url = format_to_edit( $comment->comment_author_url ); $comment->comment_author_url = esc_url( $comment->comment_author_url ); return $comment; } /** * Gets the number of pending comments on a post or posts. * * @since 2.3.0 * * @global wpdb $wpdb WordPress database abstraction object. * * @param int|int[] $post_id Either a single Post ID or an array of Post IDs * @return int|int[] Either a single Posts pending comments as an int or an array of ints keyed on the Post IDs */ function get_pending_comments_num( $post_id ) { global $wpdb; $single = false; if ( ! is_array( $post_id ) ) { $post_id_array = (array) $post_id; $single = true; } else { $post_id_array = $post_id; } $post_id_array = array_map( 'intval', $post_id_array ); $post_id_in = "'" . implode( "', '", $post_id_array ) . "'"; $pending = $wpdb->get_results( "SELECT comment_post_ID, COUNT(comment_ID) as num_comments FROM $wpdb->comments WHERE comment_post_ID IN ( $post_id_in ) AND comment_approved = '0' GROUP BY comment_post_ID", ARRAY_A ); if ( $single ) { if ( empty( $pending ) ) { return 0; } else { return absint( $pending[0]['num_comments'] ); } } $pending_keyed = array(); // Default to zero pending for all posts in request. foreach ( $post_id_array as $id ) { $pending_keyed[ $id ] = 0; } if ( ! empty( $pending ) ) { foreach ( $pending as $pend ) { $pending_keyed[ $pend['comment_post_ID'] ] = absint( $pend['num_comments'] ); } } return $pending_keyed; } /** * Adds avatars to relevant places in admin. * * @since 2.5.0 * * @param string $name User name. * @return string Avatar with the user name. */ function floated_admin_avatar( $name ) { $avatar = get_avatar( get_comment(), 32, 'mystery' ); return "$avatar $name"; } /** * Enqueues comment shortcuts jQuery script. * * @since 2.7.0 */ function enqueue_comment_hotkeys_js() { if ( 'true' === get_user_option( 'comment_shortcuts' ) ) { wp_enqueue_script( 'jquery-table-hotkeys' ); } } /** * Displays error message at bottom of comments. * * @param string $msg Error Message. Assumed to contain HTML and be sanitized. */ function comment_footer_die( $msg ) { echo "

    $msg

    "; require_once ABSPATH . 'wp-admin/admin-footer.php'; die; } class-theme-installer-skin.php000064400000030676147206365750012452 0ustar00 'web', 'url' => '', 'theme' => '', 'nonce' => '', 'title' => '', 'overwrite' => '', ); $args = wp_parse_args( $args, $defaults ); $this->type = $args['type']; $this->url = $args['url']; $this->api = isset( $args['api'] ) ? $args['api'] : array(); $this->overwrite = $args['overwrite']; parent::__construct( $args ); } /** * Performs an action before installing a theme. * * @since 2.8.0 */ public function before() { if ( ! empty( $this->api ) ) { $this->upgrader->strings['process_success'] = sprintf( $this->upgrader->strings['process_success_specific'], $this->api->name, $this->api->version ); } } /** * Hides the `process_failed` error when updating a theme by uploading a zip file. * * @since 5.5.0 * * @param WP_Error $wp_error WP_Error object. * @return bool True if the error should be hidden, false otherwise. */ public function hide_process_failed( $wp_error ) { if ( 'upload' === $this->type && '' === $this->overwrite && $wp_error->get_error_code() === 'folder_exists' ) { return true; } return false; } /** * Performs an action following a single theme install. * * @since 2.8.0 */ public function after() { if ( $this->do_overwrite() ) { return; } if ( empty( $this->upgrader->result['destination_name'] ) ) { return; } $theme_info = $this->upgrader->theme_info(); if ( empty( $theme_info ) ) { return; } $name = $theme_info->display( 'Name' ); $stylesheet = $this->upgrader->result['destination_name']; $template = $theme_info->get_template(); $activate_link = add_query_arg( array( 'action' => 'activate', 'template' => urlencode( $template ), 'stylesheet' => urlencode( $stylesheet ), ), admin_url( 'themes.php' ) ); $activate_link = wp_nonce_url( $activate_link, 'switch-theme_' . $stylesheet ); $install_actions = array(); if ( current_user_can( 'edit_theme_options' ) && current_user_can( 'customize' ) && ! $theme_info->is_block_theme() ) { $customize_url = add_query_arg( array( 'theme' => urlencode( $stylesheet ), 'return' => urlencode( admin_url( 'web' === $this->type ? 'theme-install.php' : 'themes.php' ) ), ), admin_url( 'customize.php' ) ); $install_actions['preview'] = sprintf( '' . '%s', esc_url( $customize_url ), __( 'Live Preview' ), /* translators: Hidden accessibility text. %s: Theme name. */ sprintf( __( 'Live Preview “%s”' ), $name ) ); } $install_actions['activate'] = sprintf( '' . '%s', esc_url( $activate_link ), _x( 'Activate', 'theme' ), /* translators: Hidden accessibility text. %s: Theme name. */ sprintf( _x( 'Activate “%s”', 'theme' ), $name ) ); if ( is_network_admin() && current_user_can( 'manage_network_themes' ) ) { $install_actions['network_enable'] = sprintf( '%s', esc_url( wp_nonce_url( 'themes.php?action=enable&theme=' . urlencode( $stylesheet ), 'enable-theme_' . $stylesheet ) ), __( 'Network Enable' ) ); } if ( 'web' === $this->type ) { $install_actions['themes_page'] = sprintf( '%s', self_admin_url( 'theme-install.php' ), __( 'Go to Theme Installer' ) ); } elseif ( current_user_can( 'switch_themes' ) || current_user_can( 'edit_theme_options' ) ) { $install_actions['themes_page'] = sprintf( '%s', self_admin_url( 'themes.php' ), __( 'Go to Themes page' ) ); } if ( ! $this->result || is_wp_error( $this->result ) || is_network_admin() || ! current_user_can( 'switch_themes' ) ) { unset( $install_actions['activate'], $install_actions['preview'] ); } elseif ( get_option( 'template' ) === $stylesheet ) { unset( $install_actions['activate'] ); } /** * Filters the list of action links available following a single theme installation. * * @since 2.8.0 * * @param string[] $install_actions Array of theme action links. * @param object $api Object containing WordPress.org API theme data. * @param string $stylesheet Theme directory name. * @param WP_Theme $theme_info Theme object. */ $install_actions = apply_filters( 'install_theme_complete_actions', $install_actions, $this->api, $stylesheet, $theme_info ); if ( ! empty( $install_actions ) ) { $this->feedback( implode( ' | ', (array) $install_actions ) ); } } /** * Checks if the theme can be overwritten and outputs the HTML for overwriting a theme on upload. * * @since 5.5.0 * * @return bool Whether the theme can be overwritten and HTML was outputted. */ private function do_overwrite() { if ( 'upload' !== $this->type || ! is_wp_error( $this->result ) || 'folder_exists' !== $this->result->get_error_code() ) { return false; } $folder = $this->result->get_error_data( 'folder_exists' ); $folder = rtrim( $folder, '/' ); $current_theme_data = false; $all_themes = wp_get_themes( array( 'errors' => null ) ); foreach ( $all_themes as $theme ) { $stylesheet_dir = wp_normalize_path( $theme->get_stylesheet_directory() ); if ( rtrim( $stylesheet_dir, '/' ) !== $folder ) { continue; } $current_theme_data = $theme; } $new_theme_data = $this->upgrader->new_theme_data; if ( ! $current_theme_data || ! $new_theme_data ) { return false; } echo '

    ' . esc_html__( 'This theme is already installed.' ) . '

    '; // Check errors for active theme. if ( is_wp_error( $current_theme_data->errors() ) ) { $this->feedback( 'current_theme_has_errors', $current_theme_data->errors()->get_error_message() ); } $this->is_downgrading = version_compare( $current_theme_data['Version'], $new_theme_data['Version'], '>' ); $is_invalid_parent = false; if ( ! empty( $new_theme_data['Template'] ) ) { $is_invalid_parent = ! in_array( $new_theme_data['Template'], array_keys( $all_themes ), true ); } $rows = array( 'Name' => __( 'Theme name' ), 'Version' => __( 'Version' ), 'Author' => __( 'Author' ), 'RequiresWP' => __( 'Required WordPress version' ), 'RequiresPHP' => __( 'Required PHP version' ), 'Template' => __( 'Parent theme' ), ); $table = ''; $table .= ''; $is_same_theme = true; // Let's consider only these rows. foreach ( $rows as $field => $label ) { $old_value = $current_theme_data->display( $field, false ); $old_value = $old_value ? (string) $old_value : '-'; $new_value = ! empty( $new_theme_data[ $field ] ) ? (string) $new_theme_data[ $field ] : '-'; if ( $old_value === $new_value && '-' === $new_value && 'Template' === $field ) { continue; } $is_same_theme = $is_same_theme && ( $old_value === $new_value ); $diff_field = ( 'Version' !== $field && $new_value !== $old_value ); $diff_version = ( 'Version' === $field && $this->is_downgrading ); $invalid_parent = false; if ( 'Template' === $field && $is_invalid_parent ) { $invalid_parent = true; $new_value .= ' ' . __( '(not found)' ); } $table .= ''; $table .= ( $diff_field || $diff_version || $invalid_parent ) ? ''; } $table .= '
    ' . esc_html_x( 'Active', 'theme' ) . '' . esc_html_x( 'Uploaded', 'theme' ) . '
    ' . $label . '' . wp_strip_all_tags( $old_value ) . '' : ''; $table .= wp_strip_all_tags( $new_value ) . '
    '; /** * Filters the compare table output for overwriting a theme package on upload. * * @since 5.5.0 * * @param string $table The output table with Name, Version, Author, RequiresWP, and RequiresPHP info. * @param WP_Theme $current_theme_data Active theme data. * @param array $new_theme_data Array with uploaded theme data. */ echo apply_filters( 'install_theme_overwrite_comparison', $table, $current_theme_data, $new_theme_data ); $install_actions = array(); $can_update = true; $blocked_message = '

    ' . esc_html__( 'The theme cannot be updated due to the following:' ) . '

    '; $blocked_message .= '
      '; $requires_php = isset( $new_theme_data['RequiresPHP'] ) ? $new_theme_data['RequiresPHP'] : null; $requires_wp = isset( $new_theme_data['RequiresWP'] ) ? $new_theme_data['RequiresWP'] : null; if ( ! is_php_version_compatible( $requires_php ) ) { $error = sprintf( /* translators: 1: Current PHP version, 2: Version required by the uploaded theme. */ __( 'The PHP version on your server is %1$s, however the uploaded theme requires %2$s.' ), PHP_VERSION, $requires_php ); $blocked_message .= '
    • ' . esc_html( $error ) . '
    • '; $can_update = false; } if ( ! is_wp_version_compatible( $requires_wp ) ) { $error = sprintf( /* translators: 1: Current WordPress version, 2: Version required by the uploaded theme. */ __( 'Your WordPress version is %1$s, however the uploaded theme requires %2$s.' ), esc_html( wp_get_wp_version() ), $requires_wp ); $blocked_message .= '
    • ' . esc_html( $error ) . '
    • '; $can_update = false; } $blocked_message .= '
    '; if ( $can_update ) { if ( $this->is_downgrading ) { $warning = sprintf( /* translators: %s: Documentation URL. */ __( 'You are uploading an older version of the active theme. You can continue to install the older version, but be sure to back up your database and files first.' ), __( 'https://developer.wordpress.org/advanced-administration/security/backup/' ) ); } else { $warning = sprintf( /* translators: %s: Documentation URL. */ __( 'You are updating a theme. Be sure to back up your database and files first.' ), __( 'https://developer.wordpress.org/advanced-administration/security/backup/' ) ); } echo '

    ' . $warning . '

    '; $overwrite = $this->is_downgrading ? 'downgrade-theme' : 'update-theme'; $install_actions['overwrite_theme'] = sprintf( '%s', wp_nonce_url( add_query_arg( 'overwrite', $overwrite, $this->url ), 'theme-upload' ), _x( 'Replace active with uploaded', 'theme' ) ); } else { echo $blocked_message; } $cancel_url = add_query_arg( 'action', 'upload-theme-cancel-overwrite', $this->url ); $install_actions['themes_page'] = sprintf( '%s', wp_nonce_url( $cancel_url, 'theme-upload-cancel-overwrite' ), __( 'Cancel and go back' ) ); /** * Filters the list of action links available following a single theme installation failure * when overwriting is allowed. * * @since 5.5.0 * * @param string[] $install_actions Array of theme action links. * @param object $api Object containing WordPress.org API theme data. * @param array $new_theme_data Array with uploaded theme data. */ $install_actions = apply_filters( 'install_theme_overwrite_actions', $install_actions, $this->api, $new_theme_data ); if ( ! empty( $install_actions ) ) { printf( '', __( 'The uploaded file has expired. Please go back and upload it again.' ) ); echo '

    ' . implode( ' ', (array) $install_actions ) . '

    '; } return true; } } class-wp-screen.php000064400000110717147206365750010311 0ustar00post_type; /** This filter is documented in wp-admin/post.php */ $replace_editor = apply_filters( 'replace_editor', false, $post ); if ( ! $replace_editor ) { $is_block_editor = use_block_editor_for_post( $post ); } } } break; case 'edit-tags': case 'term': if ( null === $post_type && is_object_in_taxonomy( 'post', $taxonomy ? $taxonomy : 'post_tag' ) ) { $post_type = 'post'; } break; case 'upload': $post_type = 'attachment'; break; } } switch ( $base ) { case 'post': if ( null === $post_type ) { $post_type = 'post'; } // When creating a new post, use the default block editor support value for the post type. if ( empty( $post_id ) ) { $is_block_editor = use_block_editor_for_post_type( $post_type ); } $id = $post_type; break; case 'edit': if ( null === $post_type ) { $post_type = 'post'; } $id .= '-' . $post_type; break; case 'edit-tags': case 'term': if ( null === $taxonomy ) { $taxonomy = 'post_tag'; } // The edit-tags ID does not contain the post type. Look for it in the request. if ( null === $post_type ) { $post_type = 'post'; if ( isset( $_REQUEST['post_type'] ) && post_type_exists( $_REQUEST['post_type'] ) ) { $post_type = $_REQUEST['post_type']; } } $id = 'edit-' . $taxonomy; break; } if ( 'network' === $in_admin ) { $id .= '-network'; $base .= '-network'; } elseif ( 'user' === $in_admin ) { $id .= '-user'; $base .= '-user'; } if ( isset( self::$_registry[ $id ] ) ) { $screen = self::$_registry[ $id ]; if ( get_current_screen() === $screen ) { return $screen; } } else { $screen = new self(); $screen->id = $id; } $screen->base = $base; $screen->action = $action; $screen->post_type = (string) $post_type; $screen->taxonomy = (string) $taxonomy; $screen->is_user = ( 'user' === $in_admin ); $screen->is_network = ( 'network' === $in_admin ); $screen->in_admin = $in_admin; $screen->is_block_editor = $is_block_editor; self::$_registry[ $id ] = $screen; return $screen; } /** * Makes the screen object the current screen. * * @see set_current_screen() * @since 3.3.0 * * @global WP_Screen $current_screen WordPress current screen object. * @global string $typenow The post type of the current screen. * @global string $taxnow The taxonomy of the current screen. */ public function set_current_screen() { global $current_screen, $taxnow, $typenow; $current_screen = $this; $typenow = $this->post_type; $taxnow = $this->taxonomy; /** * Fires after the current screen has been set. * * @since 3.0.0 * * @param WP_Screen $current_screen Current WP_Screen object. */ do_action( 'current_screen', $current_screen ); } /** * Constructor * * @since 3.3.0 */ private function __construct() {} /** * Indicates whether the screen is in a particular admin. * * @since 3.5.0 * * @param string $admin The admin to check against (network | user | site). * If empty any of the three admins will result in true. * @return bool True if the screen is in the indicated admin, false otherwise. */ public function in_admin( $admin = null ) { if ( empty( $admin ) ) { return (bool) $this->in_admin; } return ( $admin === $this->in_admin ); } /** * Sets or returns whether the block editor is loading on the current screen. * * @since 5.0.0 * * @param bool $set Optional. Sets whether the block editor is loading on the current screen or not. * @return bool True if the block editor is being loaded, false otherwise. */ public function is_block_editor( $set = null ) { if ( null !== $set ) { $this->is_block_editor = (bool) $set; } return $this->is_block_editor; } /** * Sets the old string-based contextual help for the screen for backward compatibility. * * @since 3.3.0 * * @param WP_Screen $screen A screen object. * @param string $help Help text. */ public static function add_old_compat_help( $screen, $help ) { self::$_old_compat_help[ $screen->id ] = $help; } /** * Sets the parent information for the screen. * * This is called in admin-header.php after the menu parent for the screen has been determined. * * @since 3.3.0 * * @param string $parent_file The parent file of the screen. Typically the $parent_file global. */ public function set_parentage( $parent_file ) { $this->parent_file = $parent_file; list( $this->parent_base ) = explode( '?', $parent_file ); $this->parent_base = str_replace( '.php', '', $this->parent_base ); } /** * Adds an option for the screen. * * Call this in template files after admin.php is loaded and before admin-header.php is loaded * to add screen options. * * @since 3.3.0 * * @param string $option Option ID. * @param mixed $args Option-dependent arguments. */ public function add_option( $option, $args = array() ) { $this->_options[ $option ] = $args; } /** * Removes an option from the screen. * * @since 3.8.0 * * @param string $option Option ID. */ public function remove_option( $option ) { unset( $this->_options[ $option ] ); } /** * Removes all options from the screen. * * @since 3.8.0 */ public function remove_options() { $this->_options = array(); } /** * Gets the options registered for the screen. * * @since 3.8.0 * * @return array Options with arguments. */ public function get_options() { return $this->_options; } /** * Gets the arguments for an option for the screen. * * @since 3.3.0 * * @param string $option Option name. * @param string|false $key Optional. Specific array key for when the option is an array. * Default false. * @return string The option value if set, null otherwise. */ public function get_option( $option, $key = false ) { if ( ! isset( $this->_options[ $option ] ) ) { return null; } if ( $key ) { if ( isset( $this->_options[ $option ][ $key ] ) ) { return $this->_options[ $option ][ $key ]; } return null; } return $this->_options[ $option ]; } /** * Gets the help tabs registered for the screen. * * @since 3.4.0 * @since 4.4.0 Help tabs are ordered by their priority. * * @return array Help tabs with arguments. */ public function get_help_tabs() { $help_tabs = $this->_help_tabs; $priorities = array(); foreach ( $help_tabs as $help_tab ) { if ( isset( $priorities[ $help_tab['priority'] ] ) ) { $priorities[ $help_tab['priority'] ][] = $help_tab; } else { $priorities[ $help_tab['priority'] ] = array( $help_tab ); } } ksort( $priorities ); $sorted = array(); foreach ( $priorities as $list ) { foreach ( $list as $tab ) { $sorted[ $tab['id'] ] = $tab; } } return $sorted; } /** * Gets the arguments for a help tab. * * @since 3.4.0 * * @param string $id Help Tab ID. * @return array Help tab arguments. */ public function get_help_tab( $id ) { if ( ! isset( $this->_help_tabs[ $id ] ) ) { return null; } return $this->_help_tabs[ $id ]; } /** * Adds a help tab to the contextual help for the screen. * * Call this on the `load-$pagenow` hook for the relevant screen, * or fetch the `$current_screen` object, or use get_current_screen() * and then call the method from the object. * * You may need to filter `$current_screen` using an if or switch statement * to prevent new help tabs from being added to ALL admin screens. * * @since 3.3.0 * @since 4.4.0 The `$priority` argument was added. * * @param array $args { * Array of arguments used to display the help tab. * * @type string $title Title for the tab. Default false. * @type string $id Tab ID. Must be HTML-safe and should be unique for this menu. * It is NOT allowed to contain any empty spaces. Default false. * @type string $content Optional. Help tab content in plain text or HTML. Default empty string. * @type callable $callback Optional. A callback to generate the tab content. Default false. * @type int $priority Optional. The priority of the tab, used for ordering. Default 10. * } */ public function add_help_tab( $args ) { $defaults = array( 'title' => false, 'id' => false, 'content' => '', 'callback' => false, 'priority' => 10, ); $args = wp_parse_args( $args, $defaults ); $args['id'] = sanitize_html_class( $args['id'] ); // Ensure we have an ID and title. if ( ! $args['id'] || ! $args['title'] ) { return; } // Allows for overriding an existing tab with that ID. $this->_help_tabs[ $args['id'] ] = $args; } /** * Removes a help tab from the contextual help for the screen. * * @since 3.3.0 * * @param string $id The help tab ID. */ public function remove_help_tab( $id ) { unset( $this->_help_tabs[ $id ] ); } /** * Removes all help tabs from the contextual help for the screen. * * @since 3.3.0 */ public function remove_help_tabs() { $this->_help_tabs = array(); } /** * Gets the content from a contextual help sidebar. * * @since 3.4.0 * * @return string Contents of the help sidebar. */ public function get_help_sidebar() { return $this->_help_sidebar; } /** * Adds a sidebar to the contextual help for the screen. * * Call this in template files after admin.php is loaded and before admin-header.php is loaded * to add a sidebar to the contextual help. * * @since 3.3.0 * * @param string $content Sidebar content in plain text or HTML. */ public function set_help_sidebar( $content ) { $this->_help_sidebar = $content; } /** * Gets the number of layout columns the user has selected. * * The layout_columns option controls the max number and default number of * columns. This method returns the number of columns within that range selected * by the user via Screen Options. If no selection has been made, the default * provisioned in layout_columns is returned. If the screen does not support * selecting the number of layout columns, 0 is returned. * * @since 3.4.0 * * @return int Number of columns to display. */ public function get_columns() { return $this->columns; } /** * Gets the accessible hidden headings and text used in the screen. * * @since 4.4.0 * * @see set_screen_reader_content() For more information on the array format. * * @return string[] An associative array of screen reader text strings. */ public function get_screen_reader_content() { return $this->_screen_reader_content; } /** * Gets a screen reader text string. * * @since 4.4.0 * * @param string $key Screen reader text array named key. * @return string Screen reader text string. */ public function get_screen_reader_text( $key ) { if ( ! isset( $this->_screen_reader_content[ $key ] ) ) { return null; } return $this->_screen_reader_content[ $key ]; } /** * Adds accessible hidden headings and text for the screen. * * @since 4.4.0 * * @param array $content { * An associative array of screen reader text strings. * * @type string $heading_views Screen reader text for the filter links heading. * Default 'Filter items list'. * @type string $heading_pagination Screen reader text for the pagination heading. * Default 'Items list navigation'. * @type string $heading_list Screen reader text for the items list heading. * Default 'Items list'. * } */ public function set_screen_reader_content( $content = array() ) { $defaults = array( 'heading_views' => __( 'Filter items list' ), 'heading_pagination' => __( 'Items list navigation' ), 'heading_list' => __( 'Items list' ), ); $content = wp_parse_args( $content, $defaults ); $this->_screen_reader_content = $content; } /** * Removes all the accessible hidden headings and text for the screen. * * @since 4.4.0 */ public function remove_screen_reader_content() { $this->_screen_reader_content = array(); } /** * Renders the screen's help section. * * This will trigger the deprecated filters for backward compatibility. * * @since 3.3.0 * * @global string $screen_layout_columns */ public function render_screen_meta() { /** * Filters the legacy contextual help list. * * @since 2.7.0 * @deprecated 3.3.0 Use {@see get_current_screen()->add_help_tab()} or * {@see get_current_screen()->remove_help_tab()} instead. * * @param array $old_compat_help Old contextual help. * @param WP_Screen $screen Current WP_Screen instance. */ self::$_old_compat_help = apply_filters_deprecated( 'contextual_help_list', array( self::$_old_compat_help, $this ), '3.3.0', 'get_current_screen()->add_help_tab(), get_current_screen()->remove_help_tab()' ); $old_help = isset( self::$_old_compat_help[ $this->id ] ) ? self::$_old_compat_help[ $this->id ] : ''; /** * Filters the legacy contextual help text. * * @since 2.7.0 * @deprecated 3.3.0 Use {@see get_current_screen()->add_help_tab()} or * {@see get_current_screen()->remove_help_tab()} instead. * * @param string $old_help Help text that appears on the screen. * @param string $screen_id Screen ID. * @param WP_Screen $screen Current WP_Screen instance. */ $old_help = apply_filters_deprecated( 'contextual_help', array( $old_help, $this->id, $this ), '3.3.0', 'get_current_screen()->add_help_tab(), get_current_screen()->remove_help_tab()' ); // Default help only if there is no old-style block of text and no new-style help tabs. if ( empty( $old_help ) && ! $this->get_help_tabs() ) { /** * Filters the default legacy contextual help text. * * @since 2.8.0 * @deprecated 3.3.0 Use {@see get_current_screen()->add_help_tab()} or * {@see get_current_screen()->remove_help_tab()} instead. * * @param string $old_help_default Default contextual help text. */ $default_help = apply_filters_deprecated( 'default_contextual_help', array( '' ), '3.3.0', 'get_current_screen()->add_help_tab(), get_current_screen()->remove_help_tab()' ); if ( $default_help ) { $old_help = '

    ' . $default_help . '

    '; } } if ( $old_help ) { $this->add_help_tab( array( 'id' => 'old-contextual-help', 'title' => __( 'Overview' ), 'content' => $old_help, ) ); } $help_sidebar = $this->get_help_sidebar(); $help_class = 'hidden'; if ( ! $help_sidebar ) { $help_class .= ' no-sidebar'; } // Time to render! ?>
      get_help_tabs() as $tab ) : $link_id = "tab-link-{$tab['id']}"; $panel_id = "tab-panel-{$tab['id']}"; ?>
    get_help_tabs() as $tab ) : $panel_id = "tab-panel-{$tab['id']}"; ?>
    id, $this ); if ( ! empty( $columns ) && isset( $columns[ $this->id ] ) ) { $this->add_option( 'layout_columns', array( 'max' => $columns[ $this->id ] ) ); } if ( $this->get_option( 'layout_columns' ) ) { $this->columns = (int) get_user_option( "screen_layout_$this->id" ); if ( ! $this->columns && $this->get_option( 'layout_columns', 'default' ) ) { $this->columns = $this->get_option( 'layout_columns', 'default' ); } } $GLOBALS['screen_layout_columns'] = $this->columns; // Set the global for back-compat. // Add screen options. if ( $this->show_screen_options() ) { $this->render_screen_options(); } ?>
    get_help_tabs() && ! $this->show_screen_options() ) { return; } ?> _show_screen_options ) ) { return $this->_show_screen_options; } $columns = get_column_headers( $this ); $show_screen = ! empty( $wp_meta_boxes[ $this->id ] ) || $columns || $this->get_option( 'per_page' ); $this->_screen_settings = ''; if ( 'post' === $this->base ) { $expand = ''; $this->_screen_settings = $expand; } /** * Filters the screen settings text displayed in the Screen Options tab. * * @since 3.0.0 * * @param string $screen_settings Screen settings. * @param WP_Screen $screen WP_Screen object. */ $this->_screen_settings = apply_filters( 'screen_settings', $this->_screen_settings, $this ); if ( $this->_screen_settings || $this->_options ) { $show_screen = true; } /** * Filters whether to show the Screen Options tab. * * @since 3.2.0 * * @param bool $show_screen Whether to show Screen Options tab. * Default true. * @param WP_Screen $screen Current WP_Screen instance. */ $this->_show_screen_options = apply_filters( 'screen_options_show_screen', $show_screen, $this ); return $this->_show_screen_options; } /** * Renders the screen options tab. * * @since 3.3.0 * * @param array $options { * Options for the tab. * * @type bool $wrap Whether the screen-options-wrap div will be included. Defaults to true. * } */ public function render_screen_options( $options = array() ) { $options = wp_parse_args( $options, array( 'wrap' => true, ) ); $wrapper_start = ''; $wrapper_end = ''; $form_start = ''; $form_end = ''; // Output optional wrapper. if ( $options['wrap'] ) { $wrapper_start = ''; } // Don't output the form and nonce for the widgets accessibility mode links. if ( 'widgets' !== $this->base ) { $form_start = "\n
    \n"; $form_end = "\n" . wp_nonce_field( 'screen-options-nonce', 'screenoptionnonce', false, false ) . "\n
    \n"; } echo $wrapper_start . $form_start; $this->render_meta_boxes_preferences(); $this->render_list_table_columns_preferences(); $this->render_screen_layout(); $this->render_per_page_options(); $this->render_view_mode(); echo $this->_screen_settings; /** * Filters whether to show the Screen Options submit button. * * @since 4.4.0 * * @param bool $show_button Whether to show Screen Options submit button. * Default false. * @param WP_Screen $screen Current WP_Screen instance. */ $show_button = apply_filters( 'screen_options_show_submit', false, $this ); if ( $show_button ) { submit_button( __( 'Apply' ), 'primary', 'screen-options-apply', true ); } echo $form_end . $wrapper_end; } /** * Renders the meta boxes preferences. * * @since 4.4.0 * * @global array $wp_meta_boxes Global meta box state. */ public function render_meta_boxes_preferences() { global $wp_meta_boxes; if ( ! isset( $wp_meta_boxes[ $this->id ] ) ) { return; } ?>

    id && has_action( 'welcome_panel' ) && current_user_can( 'edit_theme_options' ) ) { if ( isset( $_GET['welcome'] ) ) { $welcome_checked = empty( $_GET['welcome'] ) ? 0 : 1; update_user_meta( get_current_user_id(), 'show_welcome_panel', $welcome_checked ); } else { $welcome_checked = (int) get_user_meta( get_current_user_id(), 'show_welcome_panel', true ); if ( 2 === $welcome_checked && wp_get_current_user()->user_email !== get_option( 'admin_email' ) ) { $welcome_checked = false; } } echo '\n"; } ?>
    $title ) { // Can't hide these for they are special. if ( in_array( $column, $special, true ) ) { continue; } if ( empty( $title ) ) { continue; } /* * The Comments column uses HTML in the display name with some screen * reader text. Make sure to strip tags from the Comments column * title and any other custom column title plugins might add. */ $title = wp_strip_all_tags( $title ); $id = "$column-hide"; echo '\n"; } ?>
    get_option( 'layout_columns' ) ) { return; } $screen_layout_columns = $this->get_columns(); $num = $this->get_option( 'layout_columns', 'max' ); ?>
    get_option( 'per_page' ) ) { return; } $per_page_label = $this->get_option( 'per_page', 'label' ); if ( null === $per_page_label ) { $per_page_label = __( 'Number of items per page:' ); } $option = $this->get_option( 'per_page', 'option' ); if ( ! $option ) { $option = str_replace( '-', '_', "{$this->id}_per_page" ); } $per_page = (int) get_user_option( $option ); if ( empty( $per_page ) || $per_page < 1 ) { $per_page = $this->get_option( 'per_page', 'default' ); if ( ! $per_page ) { $per_page = 20; } } if ( 'edit_comments_per_page' === $option ) { $comment_status = isset( $_REQUEST['comment_status'] ) ? $_REQUEST['comment_status'] : 'all'; /** This filter is documented in wp-admin/includes/class-wp-comments-list-table.php */ $per_page = apply_filters( 'comments_per_page', $per_page, $comment_status ); } elseif ( 'categories_per_page' === $option ) { /** This filter is documented in wp-admin/includes/class-wp-terms-list-table.php */ $per_page = apply_filters( 'edit_categories_per_page', $per_page ); } else { /** This filter is documented in wp-admin/includes/class-wp-list-table.php */ $per_page = apply_filters( "{$option}", $per_page ); } // Back compat. if ( isset( $this->post_type ) ) { /** This filter is documented in wp-admin/includes/post.php */ $per_page = apply_filters( 'edit_posts_per_page', $per_page, $this->post_type ); } // This needs a submit button. add_filter( 'screen_options_show_submit', '__return_true' ); ?>
    base && 'edit-comments' !== $screen->base ) { return; } $view_mode_post_types = get_post_types( array( 'show_ui' => true ) ); /** * Filters the post types that have different view mode options. * * @since 4.4.0 * * @param string[] $view_mode_post_types Array of post types that can change view modes. * Default post types with show_ui on. */ $view_mode_post_types = apply_filters( 'view_mode_post_types', $view_mode_post_types ); if ( 'edit' === $screen->base && ! in_array( $this->post_type, $view_mode_post_types, true ) ) { return; } if ( ! isset( $mode ) ) { $mode = get_user_setting( 'posts_list_mode', 'list' ); } // This needs a submit button. add_filter( 'screen_options_show_submit', '__return_true' ); ?>
    _screen_reader_content[ $key ] ) ) { return; } echo "<$tag class='screen-reader-text'>" . $this->_screen_reader_content[ $key ] . ""; } } class-wp-filesystem-ftpext.php000064400000055075147206365750012533 0ustar00method = 'ftpext'; $this->errors = new WP_Error(); // Check if possible to use ftp functions. if ( ! extension_loaded( 'ftp' ) ) { $this->errors->add( 'no_ftp_ext', __( 'The ftp PHP extension is not available' ) ); return; } // This class uses the timeout on a per-connection basis, others use it on a per-action basis. if ( ! defined( 'FS_TIMEOUT' ) ) { define( 'FS_TIMEOUT', 4 * MINUTE_IN_SECONDS ); } if ( empty( $opt['port'] ) ) { $this->options['port'] = 21; } else { $this->options['port'] = $opt['port']; } if ( empty( $opt['hostname'] ) ) { $this->errors->add( 'empty_hostname', __( 'FTP hostname is required' ) ); } else { $this->options['hostname'] = $opt['hostname']; } // Check if the options provided are OK. if ( empty( $opt['username'] ) ) { $this->errors->add( 'empty_username', __( 'FTP username is required' ) ); } else { $this->options['username'] = $opt['username']; } if ( empty( $opt['password'] ) ) { $this->errors->add( 'empty_password', __( 'FTP password is required' ) ); } else { $this->options['password'] = $opt['password']; } $this->options['ssl'] = false; if ( isset( $opt['connection_type'] ) && 'ftps' === $opt['connection_type'] ) { $this->options['ssl'] = true; } } /** * Connects filesystem. * * @since 2.5.0 * * @return bool True on success, false on failure. */ public function connect() { if ( isset( $this->options['ssl'] ) && $this->options['ssl'] && function_exists( 'ftp_ssl_connect' ) ) { $this->link = @ftp_ssl_connect( $this->options['hostname'], $this->options['port'], FS_CONNECT_TIMEOUT ); } else { $this->link = @ftp_connect( $this->options['hostname'], $this->options['port'], FS_CONNECT_TIMEOUT ); } if ( ! $this->link ) { $this->errors->add( 'connect', sprintf( /* translators: %s: hostname:port */ __( 'Failed to connect to FTP Server %s' ), $this->options['hostname'] . ':' . $this->options['port'] ) ); return false; } if ( ! @ftp_login( $this->link, $this->options['username'], $this->options['password'] ) ) { $this->errors->add( 'auth', sprintf( /* translators: %s: Username. */ __( 'Username/Password incorrect for %s' ), $this->options['username'] ) ); return false; } // Set the connection to use Passive FTP. ftp_pasv( $this->link, true ); if ( @ftp_get_option( $this->link, FTP_TIMEOUT_SEC ) < FS_TIMEOUT ) { @ftp_set_option( $this->link, FTP_TIMEOUT_SEC, FS_TIMEOUT ); } return true; } /** * Reads entire file into a string. * * @since 2.5.0 * * @param string $file Name of the file to read. * @return string|false Read data on success, false if no temporary file could be opened, * or if the file couldn't be retrieved. */ public function get_contents( $file ) { $tempfile = wp_tempnam( $file ); $temphandle = fopen( $tempfile, 'w+' ); if ( ! $temphandle ) { unlink( $tempfile ); return false; } if ( ! ftp_fget( $this->link, $temphandle, $file, FTP_BINARY ) ) { fclose( $temphandle ); unlink( $tempfile ); return false; } fseek( $temphandle, 0 ); // Skip back to the start of the file being written to. $contents = ''; while ( ! feof( $temphandle ) ) { $contents .= fread( $temphandle, 8 * KB_IN_BYTES ); } fclose( $temphandle ); unlink( $tempfile ); return $contents; } /** * Reads entire file into an array. * * @since 2.5.0 * * @param string $file Path to the file. * @return array|false File contents in an array on success, false on failure. */ public function get_contents_array( $file ) { return explode( "\n", $this->get_contents( $file ) ); } /** * Writes a string to a file. * * @since 2.5.0 * * @param string $file Remote path to the file where to write the data. * @param string $contents The data to write. * @param int|false $mode Optional. The file permissions as octal number, usually 0644. * Default false. * @return bool True on success, false on failure. */ public function put_contents( $file, $contents, $mode = false ) { $tempfile = wp_tempnam( $file ); $temphandle = fopen( $tempfile, 'wb+' ); if ( ! $temphandle ) { unlink( $tempfile ); return false; } mbstring_binary_safe_encoding(); $data_length = strlen( $contents ); $bytes_written = fwrite( $temphandle, $contents ); reset_mbstring_encoding(); if ( $data_length !== $bytes_written ) { fclose( $temphandle ); unlink( $tempfile ); return false; } fseek( $temphandle, 0 ); // Skip back to the start of the file being written to. $ret = ftp_fput( $this->link, $file, $temphandle, FTP_BINARY ); fclose( $temphandle ); unlink( $tempfile ); $this->chmod( $file, $mode ); return $ret; } /** * Gets the current working directory. * * @since 2.5.0 * * @return string|false The current working directory on success, false on failure. */ public function cwd() { $cwd = ftp_pwd( $this->link ); if ( $cwd ) { $cwd = trailingslashit( $cwd ); } return $cwd; } /** * Changes current directory. * * @since 2.5.0 * * @param string $dir The new current directory. * @return bool True on success, false on failure. */ public function chdir( $dir ) { return @ftp_chdir( $this->link, $dir ); } /** * Changes filesystem permissions. * * @since 2.5.0 * * @param string $file Path to the file. * @param int|false $mode Optional. The permissions as octal number, usually 0644 for files, * 0755 for directories. Default false. * @param bool $recursive Optional. If set to true, changes file permissions recursively. * Default false. * @return bool True on success, false on failure. */ public function chmod( $file, $mode = false, $recursive = false ) { if ( ! $mode ) { if ( $this->is_file( $file ) ) { $mode = FS_CHMOD_FILE; } elseif ( $this->is_dir( $file ) ) { $mode = FS_CHMOD_DIR; } else { return false; } } // chmod any sub-objects if recursive. if ( $recursive && $this->is_dir( $file ) ) { $filelist = $this->dirlist( $file ); foreach ( (array) $filelist as $filename => $filemeta ) { $this->chmod( $file . '/' . $filename, $mode, $recursive ); } } // chmod the file or directory. if ( ! function_exists( 'ftp_chmod' ) ) { return (bool) ftp_site( $this->link, sprintf( 'CHMOD %o %s', $mode, $file ) ); } return (bool) ftp_chmod( $this->link, $mode, $file ); } /** * Gets the file owner. * * @since 2.5.0 * * @param string $file Path to the file. * @return string|false Username of the owner on success, false on failure. */ public function owner( $file ) { $dir = $this->dirlist( $file ); return $dir[ $file ]['owner']; } /** * Gets the permissions of the specified file or filepath in their octal format. * * @since 2.5.0 * * @param string $file Path to the file. * @return string Mode of the file (the last 3 digits). */ public function getchmod( $file ) { $dir = $this->dirlist( $file ); return $dir[ $file ]['permsn']; } /** * Gets the file's group. * * @since 2.5.0 * * @param string $file Path to the file. * @return string|false The group on success, false on failure. */ public function group( $file ) { $dir = $this->dirlist( $file ); return $dir[ $file ]['group']; } /** * Copies a file. * * @since 2.5.0 * * @param string $source Path to the source file. * @param string $destination Path to the destination file. * @param bool $overwrite Optional. Whether to overwrite the destination file if it exists. * Default false. * @param int|false $mode Optional. The permissions as octal number, usually 0644 for files, * 0755 for dirs. Default false. * @return bool True on success, false on failure. */ public function copy( $source, $destination, $overwrite = false, $mode = false ) { if ( ! $overwrite && $this->exists( $destination ) ) { return false; } $content = $this->get_contents( $source ); if ( false === $content ) { return false; } return $this->put_contents( $destination, $content, $mode ); } /** * Moves a file or directory. * * After moving files or directories, OPcache will need to be invalidated. * * If moving a directory fails, `copy_dir()` can be used for a recursive copy. * * Use `move_dir()` for moving directories with OPcache invalidation and a * fallback to `copy_dir()`. * * @since 2.5.0 * * @param string $source Path to the source file or directory. * @param string $destination Path to the destination file or directory. * @param bool $overwrite Optional. Whether to overwrite the destination if it exists. * Default false. * @return bool True on success, false on failure. */ public function move( $source, $destination, $overwrite = false ) { return ftp_rename( $this->link, $source, $destination ); } /** * Deletes a file or directory. * * @since 2.5.0 * * @param string $file Path to the file or directory. * @param bool $recursive Optional. If set to true, deletes files and folders recursively. * Default false. * @param string|false $type Type of resource. 'f' for file, 'd' for directory. * Default false. * @return bool True on success, false on failure. */ public function delete( $file, $recursive = false, $type = false ) { if ( empty( $file ) ) { return false; } if ( 'f' === $type || $this->is_file( $file ) ) { return ftp_delete( $this->link, $file ); } if ( ! $recursive ) { return ftp_rmdir( $this->link, $file ); } $filelist = $this->dirlist( trailingslashit( $file ) ); if ( ! empty( $filelist ) ) { foreach ( $filelist as $delete_file ) { $this->delete( trailingslashit( $file ) . $delete_file['name'], $recursive, $delete_file['type'] ); } } return ftp_rmdir( $this->link, $file ); } /** * Checks if a file or directory exists. * * @since 2.5.0 * @since 6.3.0 Returns false for an empty path. * * @param string $path Path to file or directory. * @return bool Whether $path exists or not. */ public function exists( $path ) { /* * Check for empty path. If ftp_nlist() receives an empty path, * it checks the current working directory and may return true. * * See https://core.trac.wordpress.org/ticket/33058. */ if ( '' === $path ) { return false; } $list = ftp_nlist( $this->link, $path ); if ( empty( $list ) && $this->is_dir( $path ) ) { return true; // File is an empty directory. } return ! empty( $list ); // Empty list = no file, so invert. } /** * Checks if resource is a file. * * @since 2.5.0 * * @param string $file File path. * @return bool Whether $file is a file. */ public function is_file( $file ) { return $this->exists( $file ) && ! $this->is_dir( $file ); } /** * Checks if resource is a directory. * * @since 2.5.0 * * @param string $path Directory path. * @return bool Whether $path is a directory. */ public function is_dir( $path ) { $cwd = $this->cwd(); $result = @ftp_chdir( $this->link, trailingslashit( $path ) ); if ( $result && $path === $this->cwd() || $this->cwd() !== $cwd ) { @ftp_chdir( $this->link, $cwd ); return true; } return false; } /** * Checks if a file is readable. * * @since 2.5.0 * * @param string $file Path to file. * @return bool Whether $file is readable. */ public function is_readable( $file ) { return true; } /** * Checks if a file or directory is writable. * * @since 2.5.0 * * @param string $path Path to file or directory. * @return bool Whether $path is writable. */ public function is_writable( $path ) { return true; } /** * Gets the file's last access time. * * @since 2.5.0 * * @param string $file Path to file. * @return int|false Unix timestamp representing last access time, false on failure. */ public function atime( $file ) { return false; } /** * Gets the file modification time. * * @since 2.5.0 * * @param string $file Path to file. * @return int|false Unix timestamp representing modification time, false on failure. */ public function mtime( $file ) { return ftp_mdtm( $this->link, $file ); } /** * Gets the file size (in bytes). * * @since 2.5.0 * * @param string $file Path to file. * @return int|false Size of the file in bytes on success, false on failure. */ public function size( $file ) { $size = ftp_size( $this->link, $file ); return ( $size > -1 ) ? $size : false; } /** * Sets the access and modification times of a file. * * Note: If $file doesn't exist, it will be created. * * @since 2.5.0 * * @param string $file Path to file. * @param int $time Optional. Modified time to set for file. * Default 0. * @param int $atime Optional. Access time to set for file. * Default 0. * @return bool True on success, false on failure. */ public function touch( $file, $time = 0, $atime = 0 ) { return false; } /** * Creates a directory. * * @since 2.5.0 * * @param string $path Path for new directory. * @param int|false $chmod Optional. The permissions as octal number (or false to skip chmod). * Default false. * @param string|int|false $chown Optional. A user name or number (or false to skip chown). * Default false. * @param string|int|false $chgrp Optional. A group name or number (or false to skip chgrp). * Default false. * @return bool True on success, false on failure. */ public function mkdir( $path, $chmod = false, $chown = false, $chgrp = false ) { $path = untrailingslashit( $path ); if ( empty( $path ) ) { return false; } if ( ! ftp_mkdir( $this->link, $path ) ) { return false; } $this->chmod( $path, $chmod ); return true; } /** * Deletes a directory. * * @since 2.5.0 * * @param string $path Path to directory. * @param bool $recursive Optional. Whether to recursively remove files/directories. * Default false. * @return bool True on success, false on failure. */ public function rmdir( $path, $recursive = false ) { return $this->delete( $path, $recursive ); } /** * @param string $line * @return array { * Array of file information. * * @type string $name Name of the file or directory. * @type string $perms *nix representation of permissions. * @type string $permsn Octal representation of permissions. * @type string|false $number File number as a string, or false if not available. * @type string|false $owner Owner name or ID, or false if not available. * @type string|false $group File permissions group, or false if not available. * @type string|false $size Size of file in bytes as a string, or false if not available. * @type string|false $lastmodunix Last modified unix timestamp as a string, or false if not available. * @type string|false $lastmod Last modified month (3 letters) and day (without leading 0), or * false if not available. * @type string|false $time Last modified time, or false if not available. * @type string $type Type of resource. 'f' for file, 'd' for directory, 'l' for link. * @type array|false $files If a directory and `$recursive` is true, contains another array of files. * False if unable to list directory contents. * } */ public function parselisting( $line ) { static $is_windows = null; if ( is_null( $is_windows ) ) { $is_windows = stripos( ftp_systype( $this->link ), 'win' ) !== false; } if ( $is_windows && preg_match( '/([0-9]{2})-([0-9]{2})-([0-9]{2}) +([0-9]{2}):([0-9]{2})(AM|PM) +([0-9]+|) +(.+)/', $line, $lucifer ) ) { $b = array(); if ( $lucifer[3] < 70 ) { $lucifer[3] += 2000; } else { $lucifer[3] += 1900; // 4-digit year fix. } $b['isdir'] = ( '' === $lucifer[7] ); if ( $b['isdir'] ) { $b['type'] = 'd'; } else { $b['type'] = 'f'; } $b['size'] = $lucifer[7]; $b['month'] = $lucifer[1]; $b['day'] = $lucifer[2]; $b['year'] = $lucifer[3]; $b['hour'] = $lucifer[4]; $b['minute'] = $lucifer[5]; $b['time'] = mktime( $lucifer[4] + ( strcasecmp( $lucifer[6], 'PM' ) === 0 ? 12 : 0 ), $lucifer[5], 0, $lucifer[1], $lucifer[2], $lucifer[3] ); $b['am/pm'] = $lucifer[6]; $b['name'] = $lucifer[8]; } elseif ( ! $is_windows ) { $lucifer = preg_split( '/[ ]/', $line, 9, PREG_SPLIT_NO_EMPTY ); if ( $lucifer ) { // echo $line."\n"; $lcount = count( $lucifer ); if ( $lcount < 8 ) { return ''; } $b = array(); $b['isdir'] = 'd' === $lucifer[0][0]; $b['islink'] = 'l' === $lucifer[0][0]; if ( $b['isdir'] ) { $b['type'] = 'd'; } elseif ( $b['islink'] ) { $b['type'] = 'l'; } else { $b['type'] = 'f'; } $b['perms'] = $lucifer[0]; $b['permsn'] = $this->getnumchmodfromh( $b['perms'] ); $b['number'] = $lucifer[1]; $b['owner'] = $lucifer[2]; $b['group'] = $lucifer[3]; $b['size'] = $lucifer[4]; if ( 8 === $lcount ) { sscanf( $lucifer[5], '%d-%d-%d', $b['year'], $b['month'], $b['day'] ); sscanf( $lucifer[6], '%d:%d', $b['hour'], $b['minute'] ); $b['time'] = mktime( $b['hour'], $b['minute'], 0, $b['month'], $b['day'], $b['year'] ); $b['name'] = $lucifer[7]; } else { $b['month'] = $lucifer[5]; $b['day'] = $lucifer[6]; if ( preg_match( '/([0-9]{2}):([0-9]{2})/', $lucifer[7], $l2 ) ) { $b['year'] = gmdate( 'Y' ); $b['hour'] = $l2[1]; $b['minute'] = $l2[2]; } else { $b['year'] = $lucifer[7]; $b['hour'] = 0; $b['minute'] = 0; } $b['time'] = strtotime( sprintf( '%d %s %d %02d:%02d', $b['day'], $b['month'], $b['year'], $b['hour'], $b['minute'] ) ); $b['name'] = $lucifer[8]; } } } // Replace symlinks formatted as "source -> target" with just the source name. if ( isset( $b['islink'] ) && $b['islink'] ) { $b['name'] = preg_replace( '/(\s*->\s*.*)$/', '', $b['name'] ); } return $b; } /** * Gets details for files in a directory or a specific file. * * @since 2.5.0 * * @param string $path Path to directory or file. * @param bool $include_hidden Optional. Whether to include details of hidden ("." prefixed) files. * Default true. * @param bool $recursive Optional. Whether to recursively include file details in nested directories. * Default false. * @return array|false { * Array of arrays containing file information. False if unable to list directory contents. * * @type array ...$0 { * Array of file information. Note that some elements may not be available on all filesystems. * * @type string $name Name of the file or directory. * @type string $perms *nix representation of permissions. * @type string $permsn Octal representation of permissions. * @type int|string|false $number File number. May be a numeric string. False if not available. * @type string|false $owner Owner name or ID, or false if not available. * @type string|false $group File permissions group, or false if not available. * @type int|string|false $size Size of file in bytes. May be a numeric string. * False if not available. * @type int|string|false $lastmodunix Last modified unix timestamp. May be a numeric string. * False if not available. * @type string|false $lastmod Last modified month (3 letters) and day (without leading 0), or * false if not available. * @type string|false $time Last modified time, or false if not available. * @type string $type Type of resource. 'f' for file, 'd' for directory, 'l' for link. * @type array|false $files If a directory and `$recursive` is true, contains another array of * files. False if unable to list directory contents. * } * } */ public function dirlist( $path = '.', $include_hidden = true, $recursive = false ) { if ( $this->is_file( $path ) ) { $limit_file = basename( $path ); $path = dirname( $path ) . '/'; } else { $limit_file = false; } $pwd = ftp_pwd( $this->link ); if ( ! @ftp_chdir( $this->link, $path ) ) { // Can't change to folder = folder doesn't exist. return false; } $list = ftp_rawlist( $this->link, '-a', false ); @ftp_chdir( $this->link, $pwd ); if ( empty( $list ) ) { // Empty array = non-existent folder (real folder will show . at least). return false; } $dirlist = array(); foreach ( $list as $k => $v ) { $entry = $this->parselisting( $v ); if ( empty( $entry ) ) { continue; } if ( '.' === $entry['name'] || '..' === $entry['name'] ) { continue; } if ( ! $include_hidden && '.' === $entry['name'][0] ) { continue; } if ( $limit_file && $entry['name'] !== $limit_file ) { continue; } $dirlist[ $entry['name'] ] = $entry; } $path = trailingslashit( $path ); $ret = array(); foreach ( (array) $dirlist as $struc ) { if ( 'd' === $struc['type'] ) { if ( $recursive ) { $struc['files'] = $this->dirlist( $path . $struc['name'], $include_hidden, $recursive ); } else { $struc['files'] = array(); } } $ret[ $struc['name'] ] = $struc; } return $ret; } /** * Destructor. * * @since 2.5.0 */ public function __destruct() { if ( $this->link ) { ftp_close( $this->link ); } } } widgets.php000064400000025240147206365750006745 0ustar00 $widget['id'], 'widget_name' => $widget['name'], '_display' => 'template', ); if ( isset( $wp_registered_widget_controls[ $widget['id'] ]['id_base'] ) && isset( $widget['params'][0]['number'] ) ) { $id_base = $wp_registered_widget_controls[ $widget['id'] ]['id_base']; $args['_temp_id'] = "$id_base-__i__"; $args['_multi_num'] = next_widget_id_number( $id_base ); $args['_add'] = 'multi'; } else { $args['_add'] = 'single'; if ( $sidebar ) { $args['_hide'] = '1'; } } $control_args = array( 0 => $args, 1 => $widget['params'][0], ); $sidebar_args = wp_list_widget_controls_dynamic_sidebar( $control_args ); wp_widget_control( ...$sidebar_args ); } } /** * Callback to sort array by a 'name' key. * * @since 3.1.0 * @access private * * @param array $a First array. * @param array $b Second array. * @return int */ function _sort_name_callback( $a, $b ) { return strnatcasecmp( $a['name'], $b['name'] ); } /** * Show the widgets and their settings for a sidebar. * Used in the admin widget config screen. * * @since 2.5.0 * * @param string $sidebar Sidebar ID. * @param string $sidebar_name Optional. Sidebar name. Default empty. */ function wp_list_widget_controls( $sidebar, $sidebar_name = '' ) { add_filter( 'dynamic_sidebar_params', 'wp_list_widget_controls_dynamic_sidebar' ); $description = wp_sidebar_description( $sidebar ); echo '
    '; if ( $sidebar_name ) { $add_to = sprintf( /* translators: %s: Widgets sidebar name. */ __( 'Add to: %s' ), $sidebar_name ); ?> '; } /** * Retrieves the widget control arguments. * * @since 2.5.0 * * @global array $wp_registered_widgets * * @param array $params * @return array */ function wp_list_widget_controls_dynamic_sidebar( $params ) { global $wp_registered_widgets; static $i = 0; ++$i; $widget_id = $params[0]['widget_id']; $id = isset( $params[0]['_temp_id'] ) ? $params[0]['_temp_id'] : $widget_id; $hidden = isset( $params[0]['_hide'] ) ? ' style="display:none;"' : ''; $params[0]['before_widget'] = "
    "; $params[0]['after_widget'] = '
    '; $params[0]['before_title'] = '%BEG_OF_TITLE%'; // Deprecated. $params[0]['after_title'] = '%END_OF_TITLE%'; // Deprecated. if ( is_callable( $wp_registered_widgets[ $widget_id ]['callback'] ) ) { $wp_registered_widgets[ $widget_id ]['_callback'] = $wp_registered_widgets[ $widget_id ]['callback']; $wp_registered_widgets[ $widget_id ]['callback'] = 'wp_widget_control'; } return $params; } /** * @global array $wp_registered_widgets * * @param string $id_base * @return int */ function next_widget_id_number( $id_base ) { global $wp_registered_widgets; $number = 1; foreach ( $wp_registered_widgets as $widget_id => $widget ) { if ( preg_match( '/' . preg_quote( $id_base, '/' ) . '-([0-9]+)$/', $widget_id, $matches ) ) { $number = max( $number, $matches[1] ); } } ++$number; return $number; } /** * Meta widget used to display the control form for a widget. * * Called from dynamic_sidebar(). * * @since 2.5.0 * * @global array $wp_registered_widgets * @global array $wp_registered_widget_controls * @global array $sidebars_widgets * * @param array $sidebar_args * @return array */ function wp_widget_control( $sidebar_args ) { global $wp_registered_widgets, $wp_registered_widget_controls, $sidebars_widgets; $widget_id = $sidebar_args['widget_id']; $sidebar_id = isset( $sidebar_args['id'] ) ? $sidebar_args['id'] : false; $key = $sidebar_id ? array_search( $widget_id, $sidebars_widgets[ $sidebar_id ], true ) : '-1'; // Position of widget in sidebar. $control = isset( $wp_registered_widget_controls[ $widget_id ] ) ? $wp_registered_widget_controls[ $widget_id ] : array(); $widget = $wp_registered_widgets[ $widget_id ]; $id_format = $widget['id']; $widget_number = isset( $control['params'][0]['number'] ) ? $control['params'][0]['number'] : ''; $id_base = isset( $control['id_base'] ) ? $control['id_base'] : $widget_id; $width = isset( $control['width'] ) ? $control['width'] : ''; $height = isset( $control['height'] ) ? $control['height'] : ''; $multi_number = isset( $sidebar_args['_multi_num'] ) ? $sidebar_args['_multi_num'] : ''; $add_new = isset( $sidebar_args['_add'] ) ? $sidebar_args['_add'] : ''; $before_form = isset( $sidebar_args['before_form'] ) ? $sidebar_args['before_form'] : '
    '; $after_form = isset( $sidebar_args['after_form'] ) ? $sidebar_args['after_form'] : '
    '; $before_widget_content = isset( $sidebar_args['before_widget_content'] ) ? $sidebar_args['before_widget_content'] : '
    '; $after_widget_content = isset( $sidebar_args['after_widget_content'] ) ? $sidebar_args['after_widget_content'] : '
    '; $query_arg = array( 'editwidget' => $widget['id'] ); if ( $add_new ) { $query_arg['addnew'] = 1; if ( $multi_number ) { $query_arg['num'] = $multi_number; $query_arg['base'] = $id_base; } } else { $query_arg['sidebar'] = $sidebar_id; $query_arg['key'] = $key; } /* * We aren't showing a widget control, we're outputting a template * for a multi-widget control. */ if ( isset( $sidebar_args['_display'] ) && 'template' === $sidebar_args['_display'] && $widget_number ) { // number == -1 implies a template where id numbers are replaced by a generic '__i__'. $control['params'][0]['number'] = -1; // With id_base widget ID's are constructed like {$id_base}-{$id_number}. if ( isset( $control['id_base'] ) ) { $id_format = $control['id_base'] . '-__i__'; } } $wp_registered_widgets[ $widget_id ]['callback'] = $wp_registered_widgets[ $widget_id ]['_callback']; unset( $wp_registered_widgets[ $widget_id ]['_callback'] ); $widget_title = esc_html( strip_tags( $sidebar_args['widget_name'] ) ); $has_form = 'noform'; echo $sidebar_args['before_widget']; ?>
    " . __( 'There are no options for this widget.' ) . "

    \n"; } $noform_class = ''; if ( 'noform' === $has_form ) { $noform_class = ' widget-control-noform'; } ?>
    |
    'widget-' . esc_attr( $id_format ) . '-savewidget' ) ); ?>

    $plugin_name, 'policy_text' => $policy_text, ); if ( ! in_array( $data, self::$policy_content, true ) ) { self::$policy_content[] = $data; } } /** * Performs a quick check to determine whether any privacy info has changed. * * @since 4.9.6 */ public static function text_change_check() { $policy_page_id = (int) get_option( 'wp_page_for_privacy_policy' ); // The site doesn't have a privacy policy. if ( empty( $policy_page_id ) ) { return false; } if ( ! current_user_can( 'edit_post', $policy_page_id ) ) { return false; } $old = (array) get_post_meta( $policy_page_id, '_wp_suggested_privacy_policy_content' ); // Updates are not relevant if the user has not reviewed any suggestions yet. if ( empty( $old ) ) { return false; } $cached = get_option( '_wp_suggested_policy_text_has_changed' ); /* * When this function is called before `admin_init`, `self::$policy_content` * has not been populated yet, so use the cached result from the last * execution instead. */ if ( ! did_action( 'admin_init' ) ) { return 'changed' === $cached; } $new = self::$policy_content; // Remove the extra values added to the meta. foreach ( $old as $key => $data ) { if ( ! is_array( $data ) || ! empty( $data['removed'] ) ) { unset( $old[ $key ] ); continue; } $old[ $key ] = array( 'plugin_name' => $data['plugin_name'], 'policy_text' => $data['policy_text'], ); } // Normalize the order of texts, to facilitate comparison. sort( $old ); sort( $new ); /* * The == operator (equal, not identical) was used intentionally. * See https://www.php.net/manual/en/language.operators.array.php */ if ( $new != $old ) { /* * A plugin was activated or deactivated, or some policy text has changed. * Show a notice on the relevant screens to inform the admin. */ add_action( 'admin_notices', array( 'WP_Privacy_Policy_Content', 'policy_text_changed_notice' ) ); $state = 'changed'; } else { $state = 'not-changed'; } // Cache the result for use before `admin_init` (see above). if ( $cached !== $state ) { update_option( '_wp_suggested_policy_text_has_changed', $state, false ); } return 'changed' === $state; } /** * Outputs a warning when some privacy info has changed. * * @since 4.9.6 */ public static function policy_text_changed_notice() { $screen = get_current_screen()->id; if ( 'privacy' !== $screen ) { return; } $privacy_message = sprintf( /* translators: %s: Privacy Policy Guide URL. */ __( 'The suggested privacy policy text has changed. Please review the guide and update your privacy policy.' ), esc_url( admin_url( 'privacy-policy-guide.php?tab=policyguide' ) ) ); wp_admin_notice( $privacy_message, array( 'type' => 'warning', 'additional_classes' => array( 'policy-text-updated' ), 'dismissible' => true, ) ); } /** * Updates the cached policy info when the policy page is updated. * * @since 4.9.6 * @access private * * @param int $post_id The ID of the updated post. */ public static function _policy_page_updated( $post_id ) { $policy_page_id = (int) get_option( 'wp_page_for_privacy_policy' ); if ( ! $policy_page_id || $policy_page_id !== (int) $post_id ) { return; } // Remove updated|removed status. $old = (array) get_post_meta( $policy_page_id, '_wp_suggested_privacy_policy_content' ); $done = array(); $update_cache = false; foreach ( $old as $old_key => $old_data ) { if ( ! empty( $old_data['removed'] ) ) { // Remove the old policy text. $update_cache = true; continue; } if ( ! empty( $old_data['updated'] ) ) { // 'updated' is now 'added'. $done[] = array( 'plugin_name' => $old_data['plugin_name'], 'policy_text' => $old_data['policy_text'], 'added' => $old_data['updated'], ); $update_cache = true; } else { $done[] = $old_data; } } if ( $update_cache ) { delete_post_meta( $policy_page_id, '_wp_suggested_privacy_policy_content' ); // Update the cache. foreach ( $done as $data ) { add_post_meta( $policy_page_id, '_wp_suggested_privacy_policy_content', $data ); } } } /** * Checks for updated, added or removed privacy policy information from plugins. * * Caches the current info in post_meta of the policy page. * * @since 4.9.6 * * @return array The privacy policy text/information added by core and plugins. */ public static function get_suggested_policy_text() { $policy_page_id = (int) get_option( 'wp_page_for_privacy_policy' ); $checked = array(); $time = time(); $update_cache = false; $new = self::$policy_content; $old = array(); if ( $policy_page_id ) { $old = (array) get_post_meta( $policy_page_id, '_wp_suggested_privacy_policy_content' ); } // Check for no-changes and updates. foreach ( $new as $new_key => $new_data ) { foreach ( $old as $old_key => $old_data ) { $found = false; if ( $new_data['policy_text'] === $old_data['policy_text'] ) { // Use the new plugin name in case it was changed, translated, etc. if ( $old_data['plugin_name'] !== $new_data['plugin_name'] ) { $old_data['plugin_name'] = $new_data['plugin_name']; $update_cache = true; } // A plugin was re-activated. if ( ! empty( $old_data['removed'] ) ) { unset( $old_data['removed'] ); $old_data['added'] = $time; $update_cache = true; } $checked[] = $old_data; $found = true; } elseif ( $new_data['plugin_name'] === $old_data['plugin_name'] ) { // The info for the policy was updated. $checked[] = array( 'plugin_name' => $new_data['plugin_name'], 'policy_text' => $new_data['policy_text'], 'updated' => $time, ); $found = true; $update_cache = true; } if ( $found ) { unset( $new[ $new_key ], $old[ $old_key ] ); continue 2; } } } if ( ! empty( $new ) ) { // A plugin was activated. foreach ( $new as $new_data ) { if ( ! empty( $new_data['plugin_name'] ) && ! empty( $new_data['policy_text'] ) ) { $new_data['added'] = $time; $checked[] = $new_data; } } $update_cache = true; } if ( ! empty( $old ) ) { // A plugin was deactivated. foreach ( $old as $old_data ) { if ( ! empty( $old_data['plugin_name'] ) && ! empty( $old_data['policy_text'] ) ) { $data = array( 'plugin_name' => $old_data['plugin_name'], 'policy_text' => $old_data['policy_text'], 'removed' => $time, ); $checked[] = $data; } } $update_cache = true; } if ( $update_cache && $policy_page_id ) { delete_post_meta( $policy_page_id, '_wp_suggested_privacy_policy_content' ); // Update the cache. foreach ( $checked as $data ) { add_post_meta( $policy_page_id, '_wp_suggested_privacy_policy_content', $data ); } } return $checked; } /** * Adds a notice with a link to the guide when editing the privacy policy page. * * @since 4.9.6 * @since 5.0.0 The `$post` parameter was made optional. * * @global WP_Post $post Global post object. * * @param WP_Post|null $post The currently edited post. Default null. */ public static function notice( $post = null ) { if ( is_null( $post ) ) { global $post; } else { $post = get_post( $post ); } if ( ! ( $post instanceof WP_Post ) ) { return; } if ( ! current_user_can( 'manage_privacy_options' ) ) { return; } $current_screen = get_current_screen(); $policy_page_id = (int) get_option( 'wp_page_for_privacy_policy' ); if ( 'post' !== $current_screen->base || $policy_page_id !== $post->ID ) { return; } $message = __( 'Need help putting together your new Privacy Policy page? Check out our guide for recommendations on what content to include, along with policies suggested by your plugins and theme.' ); $url = esc_url( admin_url( 'options-privacy.php?tab=policyguide' ) ); $label = __( 'View Privacy Policy Guide.' ); if ( get_current_screen()->is_block_editor() ) { wp_enqueue_script( 'wp-notices' ); $action = array( 'url' => $url, 'label' => $label, ); wp_add_inline_script( 'wp-notices', sprintf( 'wp.data.dispatch( "core/notices" ).createWarningNotice( "%s", { actions: [ %s ], isDismissible: false } )', $message, wp_json_encode( $action ) ), 'after' ); } else { $message .= sprintf( ' %s %s', $url, $label, /* translators: Hidden accessibility text. */ __( '(opens in a new tab)' ) ); wp_admin_notice( $message, array( 'type' => 'warning', 'additional_classes' => array( 'inline', 'wp-pp-notice' ), ) ); } } /** * Outputs the privacy policy guide together with content from the theme and plugins. * * @since 4.9.6 */ public static function privacy_policy_guide() { $content_array = self::get_suggested_policy_text(); $content = ''; $date_format = __( 'F j, Y' ); foreach ( $content_array as $section ) { $class = ''; $meta = ''; $removed = ''; if ( ! empty( $section['removed'] ) ) { $badge_class = ' red'; $date = date_i18n( $date_format, $section['removed'] ); /* translators: %s: Date of plugin deactivation. */ $badge_title = sprintf( __( 'Removed %s.' ), $date ); /* translators: %s: Date of plugin deactivation. */ $removed = sprintf( __( 'You deactivated this plugin on %s and may no longer need this policy.' ), $date ); $removed = wp_get_admin_notice( $removed, array( 'type' => 'info', 'additional_classes' => array( 'inline' ), ) ); } elseif ( ! empty( $section['updated'] ) ) { $badge_class = ' blue'; $date = date_i18n( $date_format, $section['updated'] ); /* translators: %s: Date of privacy policy text update. */ $badge_title = sprintf( __( 'Updated %s.' ), $date ); } $plugin_name = esc_html( $section['plugin_name'] ); $sanitized_policy_name = sanitize_title_with_dashes( $plugin_name ); ?>

    ' . __( 'Suggested text:' ) . ' '; $content = ''; $strings = array(); // Start of the suggested privacy policy text. if ( $description ) { $strings[] = '
    '; } /* translators: Default privacy policy heading. */ $strings[] = '

    ' . __( 'Who we are' ) . '

    '; if ( $description ) { /* translators: Privacy policy tutorial. */ $strings[] = '

    ' . __( 'In this section you should note your site URL, as well as the name of the company, organization, or individual behind it, and some accurate contact information.' ) . '

    '; /* translators: Privacy policy tutorial. */ $strings[] = '

    ' . __( 'The amount of information you may be required to show will vary depending on your local or national business regulations. You may, for example, be required to display a physical address, a registered address, or your company registration number.' ) . '

    '; } else { /* translators: Default privacy policy text. %s: Site URL. */ $strings[] = '

    ' . $suggested_text . sprintf( __( 'Our website address is: %s.' ), get_bloginfo( 'url', 'display' ) ) . '

    '; } if ( $description ) { /* translators: Default privacy policy heading. */ $strings[] = '

    ' . __( 'What personal data we collect and why we collect it' ) . '

    '; /* translators: Privacy policy tutorial. */ $strings[] = '

    ' . __( 'In this section you should note what personal data you collect from users and site visitors. This may include personal data, such as name, email address, personal account preferences; transactional data, such as purchase information; and technical data, such as information about cookies.' ) . '

    '; /* translators: Privacy policy tutorial. */ $strings[] = '

    ' . __( 'You should also note any collection and retention of sensitive personal data, such as data concerning health.' ) . '

    '; /* translators: Privacy policy tutorial. */ $strings[] = '

    ' . __( 'In addition to listing what personal data you collect, you need to note why you collect it. These explanations must note either the legal basis for your data collection and retention or the active consent the user has given.' ) . '

    '; /* translators: Privacy policy tutorial. */ $strings[] = '

    ' . __( 'Personal data is not just created by a user’s interactions with your site. Personal data is also generated from technical processes such as contact forms, comments, cookies, analytics, and third party embeds.' ) . '

    '; /* translators: Privacy policy tutorial. */ $strings[] = '

    ' . __( 'By default WordPress does not collect any personal data about visitors, and only collects the data shown on the User Profile screen from registered users. However some of your plugins may collect personal data. You should add the relevant information below.' ) . '

    '; } /* translators: Default privacy policy heading. */ $strings[] = '

    ' . __( 'Comments' ) . '

    '; if ( $description ) { /* translators: Privacy policy tutorial. */ $strings[] = '

    ' . __( 'In this subsection you should note what information is captured through comments. We have noted the data which WordPress collects by default.' ) . '

    '; } else { /* translators: Default privacy policy text. */ $strings[] = '

    ' . $suggested_text . __( 'When visitors leave comments on the site we collect the data shown in the comments form, and also the visitor’s IP address and browser user agent string to help spam detection.' ) . '

    '; /* translators: Default privacy policy text. */ $strings[] = '

    ' . __( 'An anonymized string created from your email address (also called a hash) may be provided to the Gravatar service to see if you are using it. The Gravatar service privacy policy is available here: https://automattic.com/privacy/. After approval of your comment, your profile picture is visible to the public in the context of your comment.' ) . '

    '; } /* translators: Default privacy policy heading. */ $strings[] = '

    ' . __( 'Media' ) . '

    '; if ( $description ) { /* translators: Privacy policy tutorial. */ $strings[] = '

    ' . __( 'In this subsection you should note what information may be disclosed by users who can upload media files. All uploaded files are usually publicly accessible.' ) . '

    '; } else { /* translators: Default privacy policy text. */ $strings[] = '

    ' . $suggested_text . __( 'If you upload images to the website, you should avoid uploading images with embedded location data (EXIF GPS) included. Visitors to the website can download and extract any location data from images on the website.' ) . '

    '; } if ( $description ) { /* translators: Default privacy policy heading. */ $strings[] = '

    ' . __( 'Contact forms' ) . '

    '; /* translators: Privacy policy tutorial. */ $strings[] = '

    ' . __( 'By default, WordPress does not include a contact form. If you use a contact form plugin, use this subsection to note what personal data is captured when someone submits a contact form, and how long you keep it. For example, you may note that you keep contact form submissions for a certain period for customer service purposes, but you do not use the information submitted through them for marketing purposes.' ) . '

    '; } /* translators: Default privacy policy heading. */ $strings[] = '

    ' . __( 'Cookies' ) . '

    '; if ( $description ) { /* translators: Privacy policy tutorial. */ $strings[] = '

    ' . __( 'In this subsection you should list the cookies your website uses, including those set by your plugins, social media, and analytics. We have provided the cookies which WordPress installs by default.' ) . '

    '; } else { /* translators: Default privacy policy text. */ $strings[] = '

    ' . $suggested_text . __( 'If you leave a comment on our site you may opt-in to saving your name, email address and website in cookies. These are for your convenience so that you do not have to fill in your details again when you leave another comment. These cookies will last for one year.' ) . '

    '; /* translators: Default privacy policy text. */ $strings[] = '

    ' . __( 'If you visit our login page, we will set a temporary cookie to determine if your browser accepts cookies. This cookie contains no personal data and is discarded when you close your browser.' ) . '

    '; /* translators: Default privacy policy text. */ $strings[] = '

    ' . __( 'When you log in, we will also set up several cookies to save your login information and your screen display choices. Login cookies last for two days, and screen options cookies last for a year. If you select "Remember Me", your login will persist for two weeks. If you log out of your account, the login cookies will be removed.' ) . '

    '; /* translators: Default privacy policy text. */ $strings[] = '

    ' . __( 'If you edit or publish an article, an additional cookie will be saved in your browser. This cookie includes no personal data and simply indicates the post ID of the article you just edited. It expires after 1 day.' ) . '

    '; } if ( ! $description ) { /* translators: Default privacy policy heading. */ $strings[] = '

    ' . __( 'Embedded content from other websites' ) . '

    '; /* translators: Default privacy policy text. */ $strings[] = '

    ' . $suggested_text . __( 'Articles on this site may include embedded content (e.g. videos, images, articles, etc.). Embedded content from other websites behaves in the exact same way as if the visitor has visited the other website.' ) . '

    '; /* translators: Default privacy policy text. */ $strings[] = '

    ' . __( 'These websites may collect data about you, use cookies, embed additional third-party tracking, and monitor your interaction with that embedded content, including tracking your interaction with the embedded content if you have an account and are logged in to that website.' ) . '

    '; } if ( $description ) { /* translators: Default privacy policy heading. */ $strings[] = '

    ' . __( 'Analytics' ) . '

    '; /* translators: Privacy policy tutorial. */ $strings[] = '

    ' . __( 'In this subsection you should note what analytics package you use, how users can opt out of analytics tracking, and a link to your analytics provider’s privacy policy, if any.' ) . '

    '; /* translators: Privacy policy tutorial. */ $strings[] = '

    ' . __( 'By default WordPress does not collect any analytics data. However, many web hosting accounts collect some anonymous analytics data. You may also have installed a WordPress plugin that provides analytics services. In that case, add information from that plugin here.' ) . '

    '; } /* translators: Default privacy policy heading. */ $strings[] = '

    ' . __( 'Who we share your data with' ) . '

    '; if ( $description ) { /* translators: Privacy policy tutorial. */ $strings[] = '

    ' . __( 'In this section you should name and list all third party providers with whom you share site data, including partners, cloud-based services, payment processors, and third party service providers, and note what data you share with them and why. Link to their own privacy policies if possible.' ) . '

    '; /* translators: Privacy policy tutorial. */ $strings[] = '

    ' . __( 'By default WordPress does not share any personal data with anyone.' ) . '

    '; } else { /* translators: Default privacy policy text. */ $strings[] = '

    ' . $suggested_text . __( 'If you request a password reset, your IP address will be included in the reset email.' ) . '

    '; } /* translators: Default privacy policy heading. */ $strings[] = '

    ' . __( 'How long we retain your data' ) . '

    '; if ( $description ) { /* translators: Privacy policy tutorial. */ $strings[] = '

    ' . __( 'In this section you should explain how long you retain personal data collected or processed by the website. While it is your responsibility to come up with the schedule of how long you keep each dataset for and why you keep it, that information does need to be listed here. For example, you may want to say that you keep contact form entries for six months, analytics records for a year, and customer purchase records for ten years.' ) . '

    '; } else { /* translators: Default privacy policy text. */ $strings[] = '

    ' . $suggested_text . __( 'If you leave a comment, the comment and its metadata are retained indefinitely. This is so we can recognize and approve any follow-up comments automatically instead of holding them in a moderation queue.' ) . '

    '; /* translators: Default privacy policy text. */ $strings[] = '

    ' . __( 'For users that register on our website (if any), we also store the personal information they provide in their user profile. All users can see, edit, or delete their personal information at any time (except they cannot change their username). Website administrators can also see and edit that information.' ) . '

    '; } /* translators: Default privacy policy heading. */ $strings[] = '

    ' . __( 'What rights you have over your data' ) . '

    '; if ( $description ) { /* translators: Privacy policy tutorial. */ $strings[] = '

    ' . __( 'In this section you should explain what rights your users have over their data and how they can invoke those rights.' ) . '

    '; } else { /* translators: Default privacy policy text. */ $strings[] = '

    ' . $suggested_text . __( 'If you have an account on this site, or have left comments, you can request to receive an exported file of the personal data we hold about you, including any data you have provided to us. You can also request that we erase any personal data we hold about you. This does not include any data we are obliged to keep for administrative, legal, or security purposes.' ) . '

    '; } /* translators: Default privacy policy heading. */ $strings[] = '

    ' . __( 'Where your data is sent' ) . '

    '; if ( $description ) { /* translators: Privacy policy tutorial. */ $strings[] = '

    ' . __( 'In this section you should list all transfers of your site data outside the European Union and describe the means by which that data is safeguarded to European data protection standards. This could include your web hosting, cloud storage, or other third party services.' ) . '

    '; /* translators: Privacy policy tutorial. */ $strings[] = '

    ' . __( 'European data protection law requires data about European residents which is transferred outside the European Union to be safeguarded to the same standards as if the data was in Europe. So in addition to listing where data goes, you should describe how you ensure that these standards are met either by yourself or by your third party providers, whether that is through an agreement such as Privacy Shield, model clauses in your contracts, or binding corporate rules.' ) . '

    '; } else { /* translators: Default privacy policy text. */ $strings[] = '

    ' . $suggested_text . __( 'Visitor comments may be checked through an automated spam detection service.' ) . '

    '; } if ( $description ) { /* translators: Default privacy policy heading. */ $strings[] = '

    ' . __( 'Contact information' ) . '

    '; /* translators: Privacy policy tutorial. */ $strings[] = '

    ' . __( 'In this section you should provide a contact method for privacy-specific concerns. If you are required to have a Data Protection Officer, list their name and full contact details here as well.' ) . '

    '; } if ( $description ) { /* translators: Default privacy policy heading. */ $strings[] = '

    ' . __( 'Additional information' ) . '

    '; /* translators: Privacy policy tutorial. */ $strings[] = '

    ' . __( 'If you use your site for commercial purposes and you engage in more complex collection or processing of personal data, you should note the following information in your privacy policy in addition to the information we have already discussed.' ) . '

    '; } if ( $description ) { /* translators: Default privacy policy heading. */ $strings[] = '

    ' . __( 'How we protect your data' ) . '

    '; /* translators: Privacy policy tutorial. */ $strings[] = '

    ' . __( 'In this section you should explain what measures you have taken to protect your users’ data. This could include technical measures such as encryption; security measures such as two factor authentication; and measures such as staff training in data protection. If you have carried out a Privacy Impact Assessment, you can mention it here too.' ) . '

    '; } if ( $description ) { /* translators: Default privacy policy heading. */ $strings[] = '

    ' . __( 'What data breach procedures we have in place' ) . '

    '; /* translators: Privacy policy tutorial. */ $strings[] = '

    ' . __( 'In this section you should explain what procedures you have in place to deal with data breaches, either potential or real, such as internal reporting systems, contact mechanisms, or bug bounties.' ) . '

    '; } if ( $description ) { /* translators: Default privacy policy heading. */ $strings[] = '

    ' . __( 'What third parties we receive data from' ) . '

    '; /* translators: Privacy policy tutorial. */ $strings[] = '

    ' . __( 'If your website receives data about users from third parties, including advertisers, this information must be included within the section of your privacy policy dealing with third party data.' ) . '

    '; } if ( $description ) { /* translators: Default privacy policy heading. */ $strings[] = '

    ' . __( 'What automated decision making and/or profiling we do with user data' ) . '

    '; /* translators: Privacy policy tutorial. */ $strings[] = '

    ' . __( 'If your website provides a service which includes automated decision making - for example, allowing customers to apply for credit, or aggregating their data into an advertising profile - you must note that this is taking place, and include information about how that information is used, what decisions are made with that aggregated data, and what rights users have over decisions made without human intervention.' ) . '

    '; } if ( $description ) { /* translators: Default privacy policy heading. */ $strings[] = '

    ' . __( 'Industry regulatory disclosure requirements' ) . '

    '; /* translators: Privacy policy tutorial. */ $strings[] = '

    ' . __( 'If you are a member of a regulated industry, or if you are subject to additional privacy laws, you may be required to disclose that information here.' ) . '

    '; $strings[] = '
    '; } if ( $blocks ) { foreach ( $strings as $key => $string ) { if ( str_starts_with( $string, '

    ' ) ) { $strings[ $key ] = "\n" . $string . "\n\n"; } if ( str_starts_with( $string, '

    \n"; } } } $content = implode( '', $strings ); // End of the suggested privacy policy text. /** * Filters the default content suggested for inclusion in a privacy policy. * * @since 4.9.6 * @since 5.0.0 Added the `$strings`, `$description`, and `$blocks` parameters. * @deprecated 5.7.0 Use wp_add_privacy_policy_content() instead. * * @param string $content The default policy content. * @param string[] $strings An array of privacy policy content strings. * @param bool $description Whether policy descriptions should be included. * @param bool $blocks Whether the content should be formatted for the block editor. */ return apply_filters_deprecated( 'wp_get_default_privacy_policy_content', array( $content, $strings, $description, $blocks ), '5.7.0', 'wp_add_privacy_policy_content()' ); } /** * Adds the suggested privacy policy text to the policy postbox. * * @since 4.9.6 */ public static function add_suggested_content() { $content = self::get_default_content( false, false ); wp_add_privacy_policy_content( __( 'WordPress' ), $content ); } } class-ftp-sockets.php000064400000020437147206365750010647 0ustar00 // // function _settimeout($sock) { if(!@socket_set_option($sock, SOL_SOCKET, SO_RCVTIMEO, array("sec"=>$this->_timeout, "usec"=>0))) { $this->PushError('_connect','socket set receive timeout',socket_strerror(socket_last_error($sock))); @socket_close($sock); return FALSE; } if(!@socket_set_option($sock, SOL_SOCKET , SO_SNDTIMEO, array("sec"=>$this->_timeout, "usec"=>0))) { $this->PushError('_connect','socket set send timeout',socket_strerror(socket_last_error($sock))); @socket_close($sock); return FALSE; } return true; } function _connect($host, $port) { $this->SendMSG("Creating socket"); if(!($sock = @socket_create(AF_INET, SOCK_STREAM, SOL_TCP))) { $this->PushError('_connect','socket create failed',socket_strerror(socket_last_error($sock))); return FALSE; } if(!$this->_settimeout($sock)) return FALSE; $this->SendMSG("Connecting to \"".$host.":".$port."\""); if (!($res = @socket_connect($sock, $host, $port))) { $this->PushError('_connect','socket connect failed',socket_strerror(socket_last_error($sock))); @socket_close($sock); return FALSE; } $this->_connected=true; return $sock; } function _readmsg($fnction="_readmsg"){ if(!$this->_connected) { $this->PushError($fnction,'Connect first'); return FALSE; } $result=true; $this->_message=""; $this->_code=0; $go=true; do { $tmp=@socket_read($this->_ftp_control_sock, 4096, PHP_BINARY_READ); if($tmp===false) { $go=$result=false; $this->PushError($fnction,'Read failed', socket_strerror(socket_last_error($this->_ftp_control_sock))); } else { $this->_message.=$tmp; $go = !preg_match("/^([0-9]{3})(-.+\\1)? [^".CRLF."]+".CRLF."$/Us", $this->_message, $regs); } } while($go); if($this->LocalEcho) echo "GET < ".rtrim($this->_message, CRLF).CRLF; $this->_code=(int)$regs[1]; return $result; } function _exec($cmd, $fnction="_exec") { if(!$this->_ready) { $this->PushError($fnction,'Connect first'); return FALSE; } if($this->LocalEcho) echo "PUT > ",$cmd,CRLF; $status=@socket_write($this->_ftp_control_sock, $cmd.CRLF); if($status===false) { $this->PushError($fnction,'socket write failed', socket_strerror(socket_last_error($this->stream))); return FALSE; } $this->_lastaction=time(); if(!$this->_readmsg($fnction)) return FALSE; return TRUE; } function _data_prepare($mode=FTP_ASCII) { if(!$this->_settype($mode)) return FALSE; $this->SendMSG("Creating data socket"); $this->_ftp_data_sock = @socket_create(AF_INET, SOCK_STREAM, SOL_TCP); if ($this->_ftp_data_sock < 0) { $this->PushError('_data_prepare','socket create failed',socket_strerror(socket_last_error($this->_ftp_data_sock))); return FALSE; } if(!$this->_settimeout($this->_ftp_data_sock)) { $this->_data_close(); return FALSE; } if($this->_passive) { if(!$this->_exec("PASV", "pasv")) { $this->_data_close(); return FALSE; } if(!$this->_checkCode()) { $this->_data_close(); return FALSE; } $ip_port = explode(",", preg_replace("/^.+ \\(?([0-9]{1,3},[0-9]{1,3},[0-9]{1,3},[0-9]{1,3},[0-9]+,[0-9]+)\\)?.*$/s", "\\1", $this->_message)); $this->_datahost=$ip_port[0].".".$ip_port[1].".".$ip_port[2].".".$ip_port[3]; $this->_dataport=(((int)$ip_port[4])<<8) + ((int)$ip_port[5]); $this->SendMSG("Connecting to ".$this->_datahost.":".$this->_dataport); if(!@socket_connect($this->_ftp_data_sock, $this->_datahost, $this->_dataport)) { $this->PushError("_data_prepare","socket_connect", socket_strerror(socket_last_error($this->_ftp_data_sock))); $this->_data_close(); return FALSE; } else $this->_ftp_temp_sock=$this->_ftp_data_sock; } else { if(!@socket_getsockname($this->_ftp_control_sock, $addr, $port)) { $this->PushError("_data_prepare","cannot get control socket information", socket_strerror(socket_last_error($this->_ftp_control_sock))); $this->_data_close(); return FALSE; } if(!@socket_bind($this->_ftp_data_sock,$addr)){ $this->PushError("_data_prepare","cannot bind data socket", socket_strerror(socket_last_error($this->_ftp_data_sock))); $this->_data_close(); return FALSE; } if(!@socket_listen($this->_ftp_data_sock)) { $this->PushError("_data_prepare","cannot listen data socket", socket_strerror(socket_last_error($this->_ftp_data_sock))); $this->_data_close(); return FALSE; } if(!@socket_getsockname($this->_ftp_data_sock, $this->_datahost, $this->_dataport)) { $this->PushError("_data_prepare","cannot get data socket information", socket_strerror(socket_last_error($this->_ftp_data_sock))); $this->_data_close(); return FALSE; } if(!$this->_exec('PORT '.str_replace('.',',',$this->_datahost.'.'.($this->_dataport>>8).'.'.($this->_dataport&0x00FF)), "_port")) { $this->_data_close(); return FALSE; } if(!$this->_checkCode()) { $this->_data_close(); return FALSE; } } return TRUE; } function _data_read($mode=FTP_ASCII, $fp=NULL) { $NewLine=$this->_eol_code[$this->OS_local]; if(is_resource($fp)) $out=0; else $out=""; if(!$this->_passive) { $this->SendMSG("Connecting to ".$this->_datahost.":".$this->_dataport); $this->_ftp_temp_sock=socket_accept($this->_ftp_data_sock); if($this->_ftp_temp_sock===FALSE) { $this->PushError("_data_read","socket_accept", socket_strerror(socket_last_error($this->_ftp_temp_sock))); $this->_data_close(); return FALSE; } } while(($block=@socket_read($this->_ftp_temp_sock, $this->_ftp_buff_size, PHP_BINARY_READ))!==false) { if($block==="") break; if($mode!=FTP_BINARY) $block=preg_replace("/\r\n|\r|\n/", $this->_eol_code[$this->OS_local], $block); if(is_resource($fp)) $out+=fwrite($fp, $block, strlen($block)); else $out.=$block; } return $out; } function _data_write($mode=FTP_ASCII, $fp=NULL) { $NewLine=$this->_eol_code[$this->OS_local]; if(is_resource($fp)) $out=0; else $out=""; if(!$this->_passive) { $this->SendMSG("Connecting to ".$this->_datahost.":".$this->_dataport); $this->_ftp_temp_sock=socket_accept($this->_ftp_data_sock); if($this->_ftp_temp_sock===FALSE) { $this->PushError("_data_write","socket_accept", socket_strerror(socket_last_error($this->_ftp_temp_sock))); $this->_data_close(); return false; } } if(is_resource($fp)) { while(!feof($fp)) { $block=fread($fp, $this->_ftp_buff_size); if(!$this->_data_write_block($mode, $block)) return false; } } elseif(!$this->_data_write_block($mode, $fp)) return false; return true; } function _data_write_block($mode, $block) { if($mode!=FTP_BINARY) $block=preg_replace("/\r\n|\r|\n/", $this->_eol_code[$this->OS_remote], $block); do { if(($t=@socket_write($this->_ftp_temp_sock, $block))===FALSE) { $this->PushError("_data_write","socket_write", socket_strerror(socket_last_error($this->_ftp_temp_sock))); $this->_data_close(); return FALSE; } $block=substr($block, $t); } while(!empty($block)); return true; } function _data_close() { @socket_close($this->_ftp_temp_sock); @socket_close($this->_ftp_data_sock); $this->SendMSG("Disconnected data from remote host"); return TRUE; } function _quit() { if($this->_connected) { @socket_close($this->_ftp_control_sock); $this->_connected=false; $this->SendMSG("Socket closed"); } } } ?> export.php000064400000061735147206365750006631 0ustar00 'all', 'author' => false, 'category' => false, 'start_date' => false, 'end_date' => false, 'status' => false, ); $args = wp_parse_args( $args, $defaults ); /** * Fires at the beginning of an export, before any headers are sent. * * @since 2.3.0 * * @param array $args An array of export arguments. */ do_action( 'export_wp', $args ); $sitename = sanitize_key( get_bloginfo( 'name' ) ); if ( ! empty( $sitename ) ) { $sitename .= '.'; } $date = gmdate( 'Y-m-d' ); $wp_filename = $sitename . 'WordPress.' . $date . '.xml'; /** * Filters the export filename. * * @since 4.4.0 * * @param string $wp_filename The name of the file for download. * @param string $sitename The site name. * @param string $date Today's date, formatted. */ $filename = apply_filters( 'export_wp_filename', $wp_filename, $sitename, $date ); header( 'Content-Description: File Transfer' ); header( 'Content-Disposition: attachment; filename=' . $filename ); header( 'Content-Type: text/xml; charset=' . get_option( 'blog_charset' ), true ); if ( 'all' !== $args['content'] && post_type_exists( $args['content'] ) ) { $ptype = get_post_type_object( $args['content'] ); if ( ! $ptype->can_export ) { $args['content'] = 'post'; } $where = $wpdb->prepare( "{$wpdb->posts}.post_type = %s", $args['content'] ); } else { $post_types = get_post_types( array( 'can_export' => true ) ); $esses = array_fill( 0, count( $post_types ), '%s' ); // phpcs:ignore WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare $where = $wpdb->prepare( "{$wpdb->posts}.post_type IN (" . implode( ',', $esses ) . ')', $post_types ); } if ( $args['status'] && ( 'post' === $args['content'] || 'page' === $args['content'] ) ) { $where .= $wpdb->prepare( " AND {$wpdb->posts}.post_status = %s", $args['status'] ); } else { $where .= " AND {$wpdb->posts}.post_status != 'auto-draft'"; } $join = ''; if ( $args['category'] && 'post' === $args['content'] ) { $term = term_exists( $args['category'], 'category' ); if ( $term ) { $join = "INNER JOIN {$wpdb->term_relationships} ON ({$wpdb->posts}.ID = {$wpdb->term_relationships}.object_id)"; $where .= $wpdb->prepare( " AND {$wpdb->term_relationships}.term_taxonomy_id = %d", $term['term_taxonomy_id'] ); } } if ( in_array( $args['content'], array( 'post', 'page', 'attachment' ), true ) ) { if ( $args['author'] ) { $where .= $wpdb->prepare( " AND {$wpdb->posts}.post_author = %d", $args['author'] ); } if ( $args['start_date'] ) { $where .= $wpdb->prepare( " AND {$wpdb->posts}.post_date >= %s", gmdate( 'Y-m-d', strtotime( $args['start_date'] ) ) ); } if ( $args['end_date'] ) { $where .= $wpdb->prepare( " AND {$wpdb->posts}.post_date < %s", gmdate( 'Y-m-d', strtotime( '+1 month', strtotime( $args['end_date'] ) ) ) ); } } // Grab a snapshot of post IDs, just in case it changes during the export. $post_ids = $wpdb->get_col( "SELECT ID FROM {$wpdb->posts} $join WHERE $where" ); // Get IDs for the attachments of each post, unless all content is already being exported. if ( ! in_array( $args['content'], array( 'all', 'attachment' ), true ) ) { // Array to hold all additional IDs (attachments and thumbnails). $additional_ids = array(); // Create a copy of the post IDs array to avoid modifying the original array. $processing_ids = $post_ids; while ( $next_posts = array_splice( $processing_ids, 0, 20 ) ) { $posts_in = array_map( 'absint', $next_posts ); $placeholders = array_fill( 0, count( $posts_in ), '%d' ); // Create a string for the placeholders. $in_placeholder = implode( ',', $placeholders ); // Prepare the SQL statement for attachment ids. $attachment_ids = $wpdb->get_col( $wpdb->prepare( " SELECT ID FROM $wpdb->posts WHERE post_parent IN ($in_placeholder) AND post_type = 'attachment' ", $posts_in ) ); $thumbnails_ids = $wpdb->get_col( $wpdb->prepare( " SELECT meta_value FROM $wpdb->postmeta WHERE $wpdb->postmeta.post_id IN ($in_placeholder) AND $wpdb->postmeta.meta_key = '_thumbnail_id' ", $posts_in ) ); $additional_ids = array_merge( $additional_ids, $attachment_ids, $thumbnails_ids ); } // Merge the additional IDs back with the original post IDs after processing all posts $post_ids = array_unique( array_merge( $post_ids, $additional_ids ) ); } /* * Get the requested terms ready, empty unless posts filtered by category * or all content. */ $cats = array(); $tags = array(); $terms = array(); if ( isset( $term ) && $term ) { $cat = get_term( $term['term_id'], 'category' ); $cats = array( $cat->term_id => $cat ); unset( $term, $cat ); } elseif ( 'all' === $args['content'] ) { $categories = (array) get_categories( array( 'get' => 'all' ) ); $tags = (array) get_tags( array( 'get' => 'all' ) ); $custom_taxonomies = get_taxonomies( array( '_builtin' => false ) ); $custom_terms = (array) get_terms( array( 'taxonomy' => $custom_taxonomies, 'get' => 'all', ) ); // Put categories in order with no child going before its parent. while ( $cat = array_shift( $categories ) ) { if ( ! $cat->parent || isset( $cats[ $cat->parent ] ) ) { $cats[ $cat->term_id ] = $cat; } else { $categories[] = $cat; } } // Put terms in order with no child going before its parent. while ( $t = array_shift( $custom_terms ) ) { if ( ! $t->parent || isset( $terms[ $t->parent ] ) ) { $terms[ $t->term_id ] = $t; } else { $custom_terms[] = $t; } } unset( $categories, $custom_taxonomies, $custom_terms ); } /** * Wraps given string in XML CDATA tag. * * @since 2.1.0 * * @param string $str String to wrap in XML CDATA tag. * @return string */ function wxr_cdata( $str ) { if ( ! seems_utf8( $str ) ) { $str = utf8_encode( $str ); } // $str = ent2ncr(esc_html($str)); $str = '', ']]]]>', $str ) . ']]>'; return $str; } /** * Returns the URL of the site. * * @since 2.5.0 * * @return string Site URL. */ function wxr_site_url() { if ( is_multisite() ) { // Multisite: the base URL. return network_home_url(); } else { // WordPress (single site): the site URL. return get_bloginfo_rss( 'url' ); } } /** * Outputs a cat_name XML tag from a given category object. * * @since 2.1.0 * * @param WP_Term $category Category Object. */ function wxr_cat_name( $category ) { if ( empty( $category->name ) ) { return; } echo '' . wxr_cdata( $category->name ) . "\n"; } /** * Outputs a category_description XML tag from a given category object. * * @since 2.1.0 * * @param WP_Term $category Category Object. */ function wxr_category_description( $category ) { if ( empty( $category->description ) ) { return; } echo '' . wxr_cdata( $category->description ) . "\n"; } /** * Outputs a tag_name XML tag from a given tag object. * * @since 2.3.0 * * @param WP_Term $tag Tag Object. */ function wxr_tag_name( $tag ) { if ( empty( $tag->name ) ) { return; } echo '' . wxr_cdata( $tag->name ) . "\n"; } /** * Outputs a tag_description XML tag from a given tag object. * * @since 2.3.0 * * @param WP_Term $tag Tag Object. */ function wxr_tag_description( $tag ) { if ( empty( $tag->description ) ) { return; } echo '' . wxr_cdata( $tag->description ) . "\n"; } /** * Outputs a term_name XML tag from a given term object. * * @since 2.9.0 * * @param WP_Term $term Term Object. */ function wxr_term_name( $term ) { if ( empty( $term->name ) ) { return; } echo '' . wxr_cdata( $term->name ) . "\n"; } /** * Outputs a term_description XML tag from a given term object. * * @since 2.9.0 * * @param WP_Term $term Term Object. */ function wxr_term_description( $term ) { if ( empty( $term->description ) ) { return; } echo "\t\t" . wxr_cdata( $term->description ) . "\n"; } /** * Outputs term meta XML tags for a given term object. * * @since 4.6.0 * * @global wpdb $wpdb WordPress database abstraction object. * * @param WP_Term $term Term object. */ function wxr_term_meta( $term ) { global $wpdb; $termmeta = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM $wpdb->termmeta WHERE term_id = %d", $term->term_id ) ); foreach ( $termmeta as $meta ) { /** * Filters whether to selectively skip term meta used for WXR exports. * * Returning a truthy value from the filter will skip the current meta * object from being exported. * * @since 4.6.0 * * @param bool $skip Whether to skip the current piece of term meta. Default false. * @param string $meta_key Current meta key. * @param object $meta Current meta object. */ if ( ! apply_filters( 'wxr_export_skip_termmeta', false, $meta->meta_key, $meta ) ) { printf( "\t\t\n\t\t\t%s\n\t\t\t%s\n\t\t\n", wxr_cdata( $meta->meta_key ), wxr_cdata( $meta->meta_value ) ); } } } /** * Outputs list of authors with posts. * * @since 3.1.0 * * @global wpdb $wpdb WordPress database abstraction object. * * @param int[] $post_ids Optional. Array of post IDs to filter the query by. */ function wxr_authors_list( ?array $post_ids = null ) { global $wpdb; if ( ! empty( $post_ids ) ) { $post_ids = array_map( 'absint', $post_ids ); $and = 'AND ID IN ( ' . implode( ', ', $post_ids ) . ')'; } else { $and = ''; } $authors = array(); $results = $wpdb->get_results( "SELECT DISTINCT post_author FROM $wpdb->posts WHERE post_status != 'auto-draft' $and" ); foreach ( (array) $results as $result ) { $authors[] = get_userdata( $result->post_author ); } $authors = array_filter( $authors ); foreach ( $authors as $author ) { echo "\t"; echo '' . (int) $author->ID . ''; echo '' . wxr_cdata( $author->user_login ) . ''; echo '' . wxr_cdata( $author->user_email ) . ''; echo '' . wxr_cdata( $author->display_name ) . ''; echo '' . wxr_cdata( $author->first_name ) . ''; echo '' . wxr_cdata( $author->last_name ) . ''; echo "\n"; } } /** * Outputs all navigation menu terms. * * @since 3.1.0 */ function wxr_nav_menu_terms() { $nav_menus = wp_get_nav_menus(); if ( empty( $nav_menus ) || ! is_array( $nav_menus ) ) { return; } foreach ( $nav_menus as $menu ) { echo "\t"; echo '' . (int) $menu->term_id . ''; echo 'nav_menu'; echo '' . wxr_cdata( $menu->slug ) . ''; wxr_term_name( $menu ); echo "\n"; } } /** * Outputs list of taxonomy terms, in XML tag format, associated with a post. * * @since 2.3.0 */ function wxr_post_taxonomy() { $post = get_post(); $taxonomies = get_object_taxonomies( $post->post_type ); if ( empty( $taxonomies ) ) { return; } $terms = wp_get_object_terms( $post->ID, $taxonomies ); foreach ( (array) $terms as $term ) { echo "\t\ttaxonomy}\" nicename=\"{$term->slug}\">" . wxr_cdata( $term->name ) . "\n"; } } /** * Determines whether to selectively skip post meta used for WXR exports. * * @since 3.3.0 * * @param bool $return_me Whether to skip the current post meta. Default false. * @param string $meta_key Meta key. * @return bool */ function wxr_filter_postmeta( $return_me, $meta_key ) { if ( '_edit_lock' === $meta_key ) { $return_me = true; } return $return_me; } add_filter( 'wxr_export_skip_postmeta', 'wxr_filter_postmeta', 10, 2 ); echo '\n"; ?> <?php bloginfo_rss( 'name' ); ?> term_id; ?> slug ); ?> parent ? $cats[ $c->parent ]->slug : '' ); ?> term_id; ?> slug ); ?> term_id; ?> taxonomy ); ?> slug ); ?> parent ? $terms[ $t->parent ]->slug : '' ); ?> in_the_loop = true; // Fetch 20 posts at a time rather than loading the entire table into memory. while ( $next_posts = array_splice( $post_ids, 0, 20 ) ) { $where = 'WHERE ID IN (' . implode( ',', $next_posts ) . ')'; $posts = $wpdb->get_results( "SELECT * FROM {$wpdb->posts} $where" ); // Begin Loop. foreach ( $posts as $post ) { setup_postdata( $post ); /** * Filters the post title used for WXR exports. * * @since 5.7.0 * * @param string $post_title Title of the current post. */ $title = wxr_cdata( apply_filters( 'the_title_export', $post->post_title ) ); /** * Filters the post content used for WXR exports. * * @since 2.5.0 * * @param string $post_content Content of the current post. */ $content = wxr_cdata( apply_filters( 'the_content_export', $post->post_content ) ); /** * Filters the post excerpt used for WXR exports. * * @since 2.6.0 * * @param string $post_excerpt Excerpt for the current post. */ $excerpt = wxr_cdata( apply_filters( 'the_excerpt_export', $post->post_excerpt ) ); $is_sticky = is_sticky( $post->ID ) ? 1 : 0; ?> <?php echo $title; ?> ID; ?> post_date ); ?> post_date_gmt ); ?> post_modified ); ?> post_modified_gmt ); ?> comment_status ); ?> ping_status ); ?> post_name ); ?> post_status ); ?> post_parent; ?> menu_order; ?> post_type ); ?> post_password ); ?> post_type ) : ?> ID ) ); ?> get_results( $wpdb->prepare( "SELECT * FROM $wpdb->postmeta WHERE post_id = %d", $post->ID ) ); foreach ( $postmeta as $meta ) : /** * Filters whether to selectively skip post meta used for WXR exports. * * Returning a truthy value from the filter will skip the current meta * object from being exported. * * @since 3.3.0 * * @param bool $skip Whether to skip the current post meta. Default false. * @param string $meta_key Current meta key. * @param object $meta Current meta object. */ if ( apply_filters( 'wxr_export_skip_postmeta', false, $meta->meta_key, $meta ) ) { continue; } ?> meta_key ); ?> meta_value ); ?> get_results( $wpdb->prepare( "SELECT * FROM $wpdb->comments WHERE comment_post_ID = %d AND comment_approved <> 'spam'", $post->ID ) ); $comments = array_map( 'get_comment', $_comments ); foreach ( $comments as $c ) : ?> comment_ID; ?> comment_author ); ?> comment_author_email ); ?> comment_author_url ); ?> comment_author_IP ); ?> comment_date ); ?> comment_date_gmt ); ?> comment_content ); ?> comment_approved ); ?> comment_type ); ?> comment_parent; ?> user_id; ?> get_results( $wpdb->prepare( "SELECT * FROM $wpdb->commentmeta WHERE comment_id = %d", $c->comment_ID ) ); foreach ( $c_meta as $meta ) : /** * Filters whether to selectively skip comment meta used for WXR exports. * * Returning a truthy value from the filter will skip the current meta * object from being exported. * * @since 4.0.0 * * @param bool $skip Whether to skip the current comment meta. Default false. * @param string $meta_key Current meta key. * @param object $meta Current meta object. */ if ( apply_filters( 'wxr_export_skip_commentmeta', false, $meta->meta_key, $meta ) ) { continue; } ?> meta_key ); ?> meta_value ); ?> maybe_create_scheduled_event(); // Save memory limit before it's affected by wp_raise_memory_limit( 'admin' ). $this->php_memory_limit = ini_get( 'memory_limit' ); $this->timeout_late_cron = 0; $this->timeout_missed_cron = - 5 * MINUTE_IN_SECONDS; if ( defined( 'DISABLE_WP_CRON' ) && DISABLE_WP_CRON ) { $this->timeout_late_cron = - 15 * MINUTE_IN_SECONDS; $this->timeout_missed_cron = - 1 * HOUR_IN_SECONDS; } add_filter( 'admin_body_class', array( $this, 'admin_body_class' ) ); add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_scripts' ) ); add_action( 'wp_site_health_scheduled_check', array( $this, 'wp_cron_scheduled_check' ) ); add_action( 'site_health_tab_content', array( $this, 'show_site_health_tab' ) ); } /** * Outputs the content of a tab in the Site Health screen. * * @since 5.8.0 * * @param string $tab Slug of the current tab being displayed. */ public function show_site_health_tab( $tab ) { if ( 'debug' === $tab ) { require_once ABSPATH . 'wp-admin/site-health-info.php'; } } /** * Returns an instance of the WP_Site_Health class, or create one if none exist yet. * * @since 5.4.0 * * @return WP_Site_Health|null */ public static function get_instance() { if ( null === self::$instance ) { self::$instance = new WP_Site_Health(); } return self::$instance; } /** * Enqueues the site health scripts. * * @since 5.2.0 */ public function enqueue_scripts() { $screen = get_current_screen(); if ( 'site-health' !== $screen->id && 'dashboard' !== $screen->id ) { return; } $health_check_js_variables = array( 'screen' => $screen->id, 'nonce' => array( 'site_status' => wp_create_nonce( 'health-check-site-status' ), 'site_status_result' => wp_create_nonce( 'health-check-site-status-result' ), ), 'site_status' => array( 'direct' => array(), 'async' => array(), 'issues' => array( 'good' => 0, 'recommended' => 0, 'critical' => 0, ), ), ); $issue_counts = get_transient( 'health-check-site-status-result' ); if ( false !== $issue_counts ) { $issue_counts = json_decode( $issue_counts ); $health_check_js_variables['site_status']['issues'] = $issue_counts; } if ( 'site-health' === $screen->id && ( ! isset( $_GET['tab'] ) || empty( $_GET['tab'] ) ) ) { $tests = WP_Site_Health::get_tests(); // Don't run https test on development environments. if ( $this->is_development_environment() ) { unset( $tests['async']['https_status'] ); } foreach ( $tests['direct'] as $test ) { if ( is_string( $test['test'] ) ) { $test_function = sprintf( 'get_test_%s', $test['test'] ); if ( method_exists( $this, $test_function ) && is_callable( array( $this, $test_function ) ) ) { $health_check_js_variables['site_status']['direct'][] = $this->perform_test( array( $this, $test_function ) ); continue; } } if ( is_callable( $test['test'] ) ) { $health_check_js_variables['site_status']['direct'][] = $this->perform_test( $test['test'] ); } } foreach ( $tests['async'] as $test ) { if ( is_string( $test['test'] ) ) { $health_check_js_variables['site_status']['async'][] = array( 'test' => $test['test'], 'has_rest' => ( isset( $test['has_rest'] ) ? $test['has_rest'] : false ), 'completed' => false, 'headers' => isset( $test['headers'] ) ? $test['headers'] : array(), ); } } } wp_localize_script( 'site-health', 'SiteHealth', $health_check_js_variables ); } /** * Runs a Site Health test directly. * * @since 5.4.0 * * @param callable $callback * @return mixed|void */ private function perform_test( $callback ) { /** * Filters the output of a finished Site Health test. * * @since 5.3.0 * * @param array $test_result { * An associative array of test result data. * * @type string $label A label describing the test, and is used as a header in the output. * @type string $status The status of the test, which can be a value of `good`, `recommended` or `critical`. * @type array $badge { * Tests are put into categories which have an associated badge shown, these can be modified and assigned here. * * @type string $label The test label, for example `Performance`. * @type string $color Default `blue`. A string representing a color to use for the label. * } * @type string $description A more descriptive explanation of what the test looks for, and why it is important for the end user. * @type string $actions An action to direct the user to where they can resolve the issue, if one exists. * @type string $test The name of the test being ran, used as a reference point. * } */ return apply_filters( 'site_status_test_result', call_user_func( $callback ) ); } /** * Runs the SQL version checks. * * These values are used in later tests, but the part of preparing them is more easily managed * early in the class for ease of access and discovery. * * @since 5.2.0 * * @global wpdb $wpdb WordPress database abstraction object. */ private function prepare_sql_data() { global $wpdb; $mysql_server_type = $wpdb->db_server_info(); $this->mysql_server_version = $wpdb->get_var( 'SELECT VERSION()' ); if ( stristr( $mysql_server_type, 'mariadb' ) ) { $this->is_mariadb = true; $this->mysql_recommended_version = $this->mariadb_recommended_version; } $this->is_acceptable_mysql_version = version_compare( $this->mysql_required_version, $this->mysql_server_version, '<=' ); $this->is_recommended_mysql_version = version_compare( $this->mysql_recommended_version, $this->mysql_server_version, '<=' ); } /** * Tests whether `wp_version_check` is blocked. * * It's possible to block updates with the `wp_version_check` filter, but this can't be checked * during an Ajax call, as the filter is never introduced then. * * This filter overrides a standard page request if it's made by an admin through the Ajax call * with the right query argument to check for this. * * @since 5.2.0 */ public function check_wp_version_check_exists() { if ( ! is_admin() || ! is_user_logged_in() || ! current_user_can( 'update_core' ) || ! isset( $_GET['health-check-test-wp_version_check'] ) ) { return; } echo ( has_filter( 'wp_version_check', 'wp_version_check' ) ? 'yes' : 'no' ); die(); } /** * Tests for WordPress version and outputs it. * * Gives various results depending on what kind of updates are available, if any, to encourage * the user to install security updates as a priority. * * @since 5.2.0 * * @return array The test result. */ public function get_test_wordpress_version() { $result = array( 'label' => '', 'status' => '', 'badge' => array( 'label' => __( 'Performance' ), 'color' => 'blue', ), 'description' => '', 'actions' => '', 'test' => 'wordpress_version', ); $core_current_version = wp_get_wp_version(); $core_updates = get_core_updates(); if ( ! is_array( $core_updates ) ) { $result['status'] = 'recommended'; $result['label'] = sprintf( /* translators: %s: Your current version of WordPress. */ __( 'WordPress version %s' ), $core_current_version ); $result['description'] = sprintf( '

    %s

    ', __( 'Unable to check if any new versions of WordPress are available.' ) ); $result['actions'] = sprintf( '%s', esc_url( admin_url( 'update-core.php?force-check=1' ) ), __( 'Check for updates manually' ) ); } else { foreach ( $core_updates as $core => $update ) { if ( 'upgrade' === $update->response ) { $current_version = explode( '.', $core_current_version ); $new_version = explode( '.', $update->version ); $current_major = $current_version[0] . '.' . $current_version[1]; $new_major = $new_version[0] . '.' . $new_version[1]; $result['label'] = sprintf( /* translators: %s: The latest version of WordPress available. */ __( 'WordPress update available (%s)' ), $update->version ); $result['actions'] = sprintf( '%s', esc_url( admin_url( 'update-core.php' ) ), __( 'Install the latest version of WordPress' ) ); if ( $current_major !== $new_major ) { // This is a major version mismatch. $result['status'] = 'recommended'; $result['description'] = sprintf( '

    %s

    ', __( 'A new version of WordPress is available.' ) ); } else { // This is a minor version, sometimes considered more critical. $result['status'] = 'critical'; $result['badge']['label'] = __( 'Security' ); $result['description'] = sprintf( '

    %s

    ', __( 'A new minor update is available for your site. Because minor updates often address security, it’s important to install them.' ) ); } } else { $result['status'] = 'good'; $result['label'] = sprintf( /* translators: %s: The current version of WordPress installed on this site. */ __( 'Your version of WordPress (%s) is up to date' ), $core_current_version ); $result['description'] = sprintf( '

    %s

    ', __( 'You are currently running the latest version of WordPress available, keep it up!' ) ); } } } return $result; } /** * Tests if plugins are outdated, or unnecessary. * * The test checks if your plugins are up to date, and encourages you to remove any * that are not in use. * * @since 5.2.0 * * @return array The test result. */ public function get_test_plugin_version() { $result = array( 'label' => __( 'Your plugins are all up to date' ), 'status' => 'good', 'badge' => array( 'label' => __( 'Security' ), 'color' => 'blue', ), 'description' => sprintf( '

    %s

    ', __( 'Plugins extend your site’s functionality with things like contact forms, ecommerce and much more. That means they have deep access to your site, so it’s vital to keep them up to date.' ) ), 'actions' => sprintf( '

    %s

    ', esc_url( admin_url( 'plugins.php' ) ), __( 'Manage your plugins' ) ), 'test' => 'plugin_version', ); $plugins = get_plugins(); $plugin_updates = get_plugin_updates(); $plugins_active = 0; $plugins_total = 0; $plugins_need_update = 0; // Loop over the available plugins and check their versions and active state. foreach ( $plugins as $plugin_path => $plugin ) { ++$plugins_total; if ( is_plugin_active( $plugin_path ) ) { ++$plugins_active; } if ( array_key_exists( $plugin_path, $plugin_updates ) ) { ++$plugins_need_update; } } // Add a notice if there are outdated plugins. if ( $plugins_need_update > 0 ) { $result['status'] = 'critical'; $result['label'] = __( 'You have plugins waiting to be updated' ); $result['description'] .= sprintf( '

    %s

    ', sprintf( /* translators: %d: The number of outdated plugins. */ _n( 'Your site has %d plugin waiting to be updated.', 'Your site has %d plugins waiting to be updated.', $plugins_need_update ), $plugins_need_update ) ); $result['actions'] .= sprintf( '

    %s

    ', esc_url( network_admin_url( 'plugins.php?plugin_status=upgrade' ) ), __( 'Update your plugins' ) ); } else { if ( 1 === $plugins_active ) { $result['description'] .= sprintf( '

    %s

    ', __( 'Your site has 1 active plugin, and it is up to date.' ) ); } elseif ( $plugins_active > 0 ) { $result['description'] .= sprintf( '

    %s

    ', sprintf( /* translators: %d: The number of active plugins. */ _n( 'Your site has %d active plugin, and it is up to date.', 'Your site has %d active plugins, and they are all up to date.', $plugins_active ), $plugins_active ) ); } else { $result['description'] .= sprintf( '

    %s

    ', __( 'Your site does not have any active plugins.' ) ); } } // Check if there are inactive plugins. if ( $plugins_total > $plugins_active && ! is_multisite() ) { $unused_plugins = $plugins_total - $plugins_active; $result['status'] = 'recommended'; $result['label'] = __( 'You should remove inactive plugins' ); $result['description'] .= sprintf( '

    %s %s

    ', sprintf( /* translators: %d: The number of inactive plugins. */ _n( 'Your site has %d inactive plugin.', 'Your site has %d inactive plugins.', $unused_plugins ), $unused_plugins ), __( 'Inactive plugins are tempting targets for attackers. If you are not going to use a plugin, you should consider removing it.' ) ); $result['actions'] .= sprintf( '

    %s

    ', esc_url( admin_url( 'plugins.php?plugin_status=inactive' ) ), __( 'Manage inactive plugins' ) ); } return $result; } /** * Tests if themes are outdated, or unnecessary. * * Checks if your site has a default theme (to fall back on if there is a need), * if your themes are up to date and, finally, encourages you to remove any themes * that are not needed. * * @since 5.2.0 * * @return array The test results. */ public function get_test_theme_version() { $result = array( 'label' => __( 'Your themes are all up to date' ), 'status' => 'good', 'badge' => array( 'label' => __( 'Security' ), 'color' => 'blue', ), 'description' => sprintf( '

    %s

    ', __( 'Themes add your site’s look and feel. It’s important to keep them up to date, to stay consistent with your brand and keep your site secure.' ) ), 'actions' => sprintf( '

    %s

    ', esc_url( admin_url( 'themes.php' ) ), __( 'Manage your themes' ) ), 'test' => 'theme_version', ); $theme_updates = get_theme_updates(); $themes_total = 0; $themes_need_updates = 0; $themes_inactive = 0; // This value is changed during processing to determine how many themes are considered a reasonable amount. $allowed_theme_count = 1; $has_default_theme = false; $has_unused_themes = false; $show_unused_themes = true; $using_default_theme = false; // Populate a list of all themes available in the install. $all_themes = wp_get_themes(); $active_theme = wp_get_theme(); // If WP_DEFAULT_THEME doesn't exist, fall back to the latest core default theme. $default_theme = wp_get_theme( WP_DEFAULT_THEME ); if ( ! $default_theme->exists() ) { $default_theme = WP_Theme::get_core_default_theme(); } if ( $default_theme ) { $has_default_theme = true; if ( $active_theme->get_stylesheet() === $default_theme->get_stylesheet() || is_child_theme() && $active_theme->get_template() === $default_theme->get_template() ) { $using_default_theme = true; } } foreach ( $all_themes as $theme_slug => $theme ) { ++$themes_total; if ( array_key_exists( $theme_slug, $theme_updates ) ) { ++$themes_need_updates; } } // If this is a child theme, increase the allowed theme count by one, to account for the parent. if ( is_child_theme() ) { ++$allowed_theme_count; } // If there's a default theme installed and not in use, we count that as allowed as well. if ( $has_default_theme && ! $using_default_theme ) { ++$allowed_theme_count; } if ( $themes_total > $allowed_theme_count ) { $has_unused_themes = true; $themes_inactive = ( $themes_total - $allowed_theme_count ); } // Check if any themes need to be updated. if ( $themes_need_updates > 0 ) { $result['status'] = 'critical'; $result['label'] = __( 'You have themes waiting to be updated' ); $result['description'] .= sprintf( '

    %s

    ', sprintf( /* translators: %d: The number of outdated themes. */ _n( 'Your site has %d theme waiting to be updated.', 'Your site has %d themes waiting to be updated.', $themes_need_updates ), $themes_need_updates ) ); } else { // Give positive feedback about the site being good about keeping things up to date. if ( 1 === $themes_total ) { $result['description'] .= sprintf( '

    %s

    ', __( 'Your site has 1 installed theme, and it is up to date.' ) ); } elseif ( $themes_total > 0 ) { $result['description'] .= sprintf( '

    %s

    ', sprintf( /* translators: %d: The number of themes. */ _n( 'Your site has %d installed theme, and it is up to date.', 'Your site has %d installed themes, and they are all up to date.', $themes_total ), $themes_total ) ); } else { $result['description'] .= sprintf( '

    %s

    ', __( 'Your site does not have any installed themes.' ) ); } } if ( $has_unused_themes && $show_unused_themes && ! is_multisite() ) { // This is a child theme, so we want to be a bit more explicit in our messages. if ( $active_theme->parent() ) { // Recommend removing inactive themes, except a default theme, your current one, and the parent theme. $result['status'] = 'recommended'; $result['label'] = __( 'You should remove inactive themes' ); if ( $using_default_theme ) { $result['description'] .= sprintf( '

    %s %s

    ', sprintf( /* translators: %d: The number of inactive themes. */ _n( 'Your site has %d inactive theme.', 'Your site has %d inactive themes.', $themes_inactive ), $themes_inactive ), sprintf( /* translators: 1: The currently active theme. 2: The active theme's parent theme. */ __( 'To enhance your site’s security, you should consider removing any themes you are not using. You should keep your active theme, %1$s, and %2$s, its parent theme.' ), $active_theme->name, $active_theme->parent()->name ) ); } else { $result['description'] .= sprintf( '

    %s %s

    ', sprintf( /* translators: %d: The number of inactive themes. */ _n( 'Your site has %d inactive theme.', 'Your site has %d inactive themes.', $themes_inactive ), $themes_inactive ), sprintf( /* translators: 1: The default theme for WordPress. 2: The currently active theme. 3: The active theme's parent theme. */ __( 'To enhance your site’s security, you should consider removing any themes you are not using. You should keep %1$s, the default WordPress theme, %2$s, your active theme, and %3$s, its parent theme.' ), $default_theme ? $default_theme->name : WP_DEFAULT_THEME, $active_theme->name, $active_theme->parent()->name ) ); } } else { // Recommend removing all inactive themes. $result['status'] = 'recommended'; $result['label'] = __( 'You should remove inactive themes' ); if ( $using_default_theme ) { $result['description'] .= sprintf( '

    %s %s

    ', sprintf( /* translators: 1: The amount of inactive themes. 2: The currently active theme. */ _n( 'Your site has %1$d inactive theme, other than %2$s, your active theme.', 'Your site has %1$d inactive themes, other than %2$s, your active theme.', $themes_inactive ), $themes_inactive, $active_theme->name ), __( 'You should consider removing any unused themes to enhance your site’s security.' ) ); } else { $result['description'] .= sprintf( '

    %s %s

    ', sprintf( /* translators: 1: The amount of inactive themes. 2: The default theme for WordPress. 3: The currently active theme. */ _n( 'Your site has %1$d inactive theme, other than %2$s, the default WordPress theme, and %3$s, your active theme.', 'Your site has %1$d inactive themes, other than %2$s, the default WordPress theme, and %3$s, your active theme.', $themes_inactive ), $themes_inactive, $default_theme ? $default_theme->name : WP_DEFAULT_THEME, $active_theme->name ), __( 'You should consider removing any unused themes to enhance your site’s security.' ) ); } } } // If no default Twenty* theme exists. if ( ! $has_default_theme ) { $result['status'] = 'recommended'; $result['label'] = __( 'Have a default theme available' ); $result['description'] .= sprintf( '

    %s

    ', __( 'Your site does not have any default theme. Default themes are used by WordPress automatically if anything is wrong with your chosen theme.' ) ); } return $result; } /** * Tests if the supplied PHP version is supported. * * @since 5.2.0 * * @return array The test results. */ public function get_test_php_version() { $response = wp_check_php_version(); $result = array( 'label' => sprintf( /* translators: %s: The recommended PHP version. */ __( 'Your site is running a recommended version of PHP (%s)' ), PHP_VERSION ), 'status' => 'good', 'badge' => array( 'label' => __( 'Performance' ), 'color' => 'blue', ), 'description' => sprintf( '

    %s

    ', sprintf( /* translators: %s: The minimum recommended PHP version. */ __( 'PHP is one of the programming languages used to build WordPress. Newer versions of PHP receive regular security updates and may increase your site’s performance. The minimum recommended version of PHP is %s.' ), $response ? $response['recommended_version'] : '' ) ), 'actions' => sprintf( '

    %s %s

    ', esc_url( wp_get_update_php_url() ), __( 'Learn more about updating PHP' ), /* translators: Hidden accessibility text. */ __( '(opens in a new tab)' ) ), 'test' => 'php_version', ); // PHP is up to date. if ( ! $response || version_compare( PHP_VERSION, $response['recommended_version'], '>=' ) ) { return $result; } // The PHP version is older than the recommended version, but still receiving active support. if ( $response['is_supported'] ) { $result['label'] = sprintf( /* translators: %s: The server PHP version. */ __( 'Your site is running on an older version of PHP (%s)' ), PHP_VERSION ); $result['status'] = 'recommended'; return $result; } /* * The PHP version is still receiving security fixes, but is lower than * the expected minimum version that will be required by WordPress in the near future. */ if ( $response['is_secure'] && $response['is_lower_than_future_minimum'] ) { // The `is_secure` array key name doesn't actually imply this is a secure version of PHP. It only means it receives security updates. $result['label'] = sprintf( /* translators: %s: The server PHP version. */ __( 'Your site is running on an outdated version of PHP (%s), which soon will not be supported by WordPress.' ), PHP_VERSION ); $result['status'] = 'critical'; $result['badge']['label'] = __( 'Requirements' ); return $result; } // The PHP version is only receiving security fixes. if ( $response['is_secure'] ) { $result['label'] = sprintf( /* translators: %s: The server PHP version. */ __( 'Your site is running on an older version of PHP (%s), which should be updated' ), PHP_VERSION ); $result['status'] = 'recommended'; return $result; } // No more security updates for the PHP version, and lower than the expected minimum version required by WordPress. if ( $response['is_lower_than_future_minimum'] ) { $message = sprintf( /* translators: %s: The server PHP version. */ __( 'Your site is running on an outdated version of PHP (%s), which does not receive security updates and soon will not be supported by WordPress.' ), PHP_VERSION ); } else { // No more security updates for the PHP version, must be updated. $message = sprintf( /* translators: %s: The server PHP version. */ __( 'Your site is running on an outdated version of PHP (%s), which does not receive security updates. It should be updated.' ), PHP_VERSION ); } $result['label'] = $message; $result['status'] = 'critical'; $result['badge']['label'] = __( 'Security' ); return $result; } /** * Checks if the passed extension or function are available. * * Make the check for available PHP modules into a simple boolean operator for a cleaner test runner. * * @since 5.2.0 * @since 5.3.0 The `$constant_name` and `$class_name` parameters were added. * * @param string $extension_name Optional. The extension name to test. Default null. * @param string $function_name Optional. The function name to test. Default null. * @param string $constant_name Optional. The constant name to test for. Default null. * @param string $class_name Optional. The class name to test for. Default null. * @return bool Whether or not the extension and function are available. */ private function test_php_extension_availability( $extension_name = null, $function_name = null, $constant_name = null, $class_name = null ) { // If no extension or function is passed, claim to fail testing, as we have nothing to test against. if ( ! $extension_name && ! $function_name && ! $constant_name && ! $class_name ) { return false; } if ( $extension_name && ! extension_loaded( $extension_name ) ) { return false; } if ( $function_name && ! function_exists( $function_name ) ) { return false; } if ( $constant_name && ! defined( $constant_name ) ) { return false; } if ( $class_name && ! class_exists( $class_name ) ) { return false; } return true; } /** * Tests if required PHP modules are installed on the host. * * This test builds on the recommendations made by the WordPress Hosting Team * as seen at https://make.wordpress.org/hosting/handbook/handbook/server-environment/#php-extensions * * @since 5.2.0 * * @return array */ public function get_test_php_extensions() { $result = array( 'label' => __( 'Required and recommended modules are installed' ), 'status' => 'good', 'badge' => array( 'label' => __( 'Performance' ), 'color' => 'blue', ), 'description' => sprintf( '

    %s

    %s

    ', __( 'PHP modules perform most of the tasks on the server that make your site run. Any changes to these must be made by your server administrator.' ), sprintf( /* translators: 1: Link to the hosting group page about recommended PHP modules. 2: Additional link attributes. 3: Accessibility text. */ __( 'The WordPress Hosting Team maintains a list of those modules, both recommended and required, in the team handbook%3$s.' ), /* translators: Localized team handbook, if one exists. */ esc_url( __( 'https://make.wordpress.org/hosting/handbook/handbook/server-environment/#php-extensions' ) ), 'target="_blank"', sprintf( ' %s', /* translators: Hidden accessibility text. */ __( '(opens in a new tab)' ) ) ) ), 'actions' => '', 'test' => 'php_extensions', ); $modules = array( 'curl' => array( 'function' => 'curl_version', 'required' => false, ), 'dom' => array( 'class' => 'DOMNode', 'required' => false, ), 'exif' => array( 'function' => 'exif_read_data', 'required' => false, ), 'fileinfo' => array( 'function' => 'finfo_file', 'required' => false, ), 'hash' => array( 'function' => 'hash', 'required' => false, ), 'imagick' => array( 'extension' => 'imagick', 'required' => false, ), 'json' => array( 'function' => 'json_last_error', 'required' => true, ), 'mbstring' => array( 'function' => 'mb_check_encoding', 'required' => false, ), 'mysqli' => array( 'function' => 'mysqli_connect', 'required' => false, ), 'libsodium' => array( 'constant' => 'SODIUM_LIBRARY_VERSION', 'required' => false, 'php_bundled_version' => '7.2.0', ), 'openssl' => array( 'function' => 'openssl_encrypt', 'required' => false, ), 'pcre' => array( 'function' => 'preg_match', 'required' => false, ), 'mod_xml' => array( 'extension' => 'libxml', 'required' => false, ), 'zip' => array( 'class' => 'ZipArchive', 'required' => false, ), 'filter' => array( 'function' => 'filter_list', 'required' => false, ), 'gd' => array( 'extension' => 'gd', 'required' => false, 'fallback_for' => 'imagick', ), 'iconv' => array( 'function' => 'iconv', 'required' => false, ), 'intl' => array( 'extension' => 'intl', 'required' => false, ), 'mcrypt' => array( 'extension' => 'mcrypt', 'required' => false, 'fallback_for' => 'libsodium', ), 'simplexml' => array( 'extension' => 'simplexml', 'required' => false, 'fallback_for' => 'mod_xml', ), 'xmlreader' => array( 'extension' => 'xmlreader', 'required' => false, 'fallback_for' => 'mod_xml', ), 'zlib' => array( 'extension' => 'zlib', 'required' => false, 'fallback_for' => 'zip', ), ); /** * Filters the array representing all the modules we wish to test for. * * @since 5.2.0 * @since 5.3.0 The `$constant` and `$class` parameters were added. * * @param array $modules { * An associative array of modules to test for. * * @type array ...$0 { * An associative array of module properties used during testing. * One of either `$function` or `$extension` must be provided, or they will fail by default. * * @type string $function Optional. A function name to test for the existence of. * @type string $extension Optional. An extension to check if is loaded in PHP. * @type string $constant Optional. A constant name to check for to verify an extension exists. * @type string $class Optional. A class name to check for to verify an extension exists. * @type bool $required Is this a required feature or not. * @type string $fallback_for Optional. The module this module replaces as a fallback. * } * } */ $modules = apply_filters( 'site_status_test_php_modules', $modules ); $failures = array(); foreach ( $modules as $library => $module ) { $extension_name = ( isset( $module['extension'] ) ? $module['extension'] : null ); $function_name = ( isset( $module['function'] ) ? $module['function'] : null ); $constant_name = ( isset( $module['constant'] ) ? $module['constant'] : null ); $class_name = ( isset( $module['class'] ) ? $module['class'] : null ); // If this module is a fallback for another function, check if that other function passed. if ( isset( $module['fallback_for'] ) ) { /* * If that other function has a failure, mark this module as required for usual operations. * If that other function hasn't failed, skip this test as it's only a fallback. */ if ( isset( $failures[ $module['fallback_for'] ] ) ) { $module['required'] = true; } else { continue; } } if ( ! $this->test_php_extension_availability( $extension_name, $function_name, $constant_name, $class_name ) && ( ! isset( $module['php_bundled_version'] ) || version_compare( PHP_VERSION, $module['php_bundled_version'], '<' ) ) ) { if ( $module['required'] ) { $result['status'] = 'critical'; $class = 'error'; /* translators: Hidden accessibility text. */ $screen_reader = __( 'Error' ); $message = sprintf( /* translators: %s: The module name. */ __( 'The required module, %s, is not installed, or has been disabled.' ), $library ); } else { $class = 'warning'; /* translators: Hidden accessibility text. */ $screen_reader = __( 'Warning' ); $message = sprintf( /* translators: %s: The module name. */ __( 'The optional module, %s, is not installed, or has been disabled.' ), $library ); } if ( ! $module['required'] && 'good' === $result['status'] ) { $result['status'] = 'recommended'; } $failures[ $library ] = "$screen_reader $message"; } } if ( ! empty( $failures ) ) { $output = '
      '; foreach ( $failures as $failure ) { $output .= sprintf( '
    • %s
    • ', $failure ); } $output .= '
    '; } if ( 'good' !== $result['status'] ) { if ( 'recommended' === $result['status'] ) { $result['label'] = __( 'One or more recommended modules are missing' ); } if ( 'critical' === $result['status'] ) { $result['label'] = __( 'One or more required modules are missing' ); } $result['description'] .= $output; } return $result; } /** * Tests if the PHP default timezone is set to UTC. * * @since 5.3.1 * * @return array The test results. */ public function get_test_php_default_timezone() { $result = array( 'label' => __( 'PHP default timezone is valid' ), 'status' => 'good', 'badge' => array( 'label' => __( 'Performance' ), 'color' => 'blue', ), 'description' => sprintf( '

    %s

    ', __( 'PHP default timezone was configured by WordPress on loading. This is necessary for correct calculations of dates and times.' ) ), 'actions' => '', 'test' => 'php_default_timezone', ); if ( 'UTC' !== date_default_timezone_get() ) { $result['status'] = 'critical'; $result['label'] = __( 'PHP default timezone is invalid' ); $result['description'] = sprintf( '

    %s

    ', sprintf( /* translators: %s: date_default_timezone_set() */ __( 'PHP default timezone was changed after WordPress loading by a %s function call. This interferes with correct calculations of dates and times.' ), 'date_default_timezone_set()' ) ); } return $result; } /** * Tests if there's an active PHP session that can affect loopback requests. * * @since 5.5.0 * * @return array The test results. */ public function get_test_php_sessions() { $result = array( 'label' => __( 'No PHP sessions detected' ), 'status' => 'good', 'badge' => array( 'label' => __( 'Performance' ), 'color' => 'blue', ), 'description' => sprintf( '

    %s

    ', sprintf( /* translators: 1: session_start(), 2: session_write_close() */ __( 'PHP sessions created by a %1$s function call may interfere with REST API and loopback requests. An active session should be closed by %2$s before making any HTTP requests.' ), 'session_start()', 'session_write_close()' ) ), 'test' => 'php_sessions', ); if ( function_exists( 'session_status' ) && PHP_SESSION_ACTIVE === session_status() ) { $result['status'] = 'critical'; $result['label'] = __( 'An active PHP session was detected' ); $result['description'] = sprintf( '

    %s

    ', sprintf( /* translators: 1: session_start(), 2: session_write_close() */ __( 'A PHP session was created by a %1$s function call. This interferes with REST API and loopback requests. The session should be closed by %2$s before making any HTTP requests.' ), 'session_start()', 'session_write_close()' ) ); } return $result; } /** * Tests if the SQL server is up to date. * * @since 5.2.0 * * @return array The test results. */ public function get_test_sql_server() { if ( ! $this->mysql_server_version ) { $this->prepare_sql_data(); } $result = array( 'label' => __( 'SQL server is up to date' ), 'status' => 'good', 'badge' => array( 'label' => __( 'Performance' ), 'color' => 'blue', ), 'description' => sprintf( '

    %s

    ', __( 'The SQL server is a required piece of software for the database WordPress uses to store all your site’s content and settings.' ) ), 'actions' => sprintf( '

    %s %s

    ', /* translators: Localized version of WordPress requirements if one exists. */ esc_url( __( 'https://wordpress.org/about/requirements/' ) ), __( 'Learn more about what WordPress requires to run.' ), /* translators: Hidden accessibility text. */ __( '(opens in a new tab)' ) ), 'test' => 'sql_server', ); $db_dropin = file_exists( WP_CONTENT_DIR . '/db.php' ); if ( ! $this->is_recommended_mysql_version ) { $result['status'] = 'recommended'; $result['label'] = __( 'Outdated SQL server' ); $result['description'] .= sprintf( '

    %s

    ', sprintf( /* translators: 1: The database engine in use (MySQL or MariaDB). 2: Database server recommended version number. */ __( 'For optimal performance and security reasons, you should consider running %1$s version %2$s or higher. Contact your web hosting company to correct this.' ), ( $this->is_mariadb ? 'MariaDB' : 'MySQL' ), $this->mysql_recommended_version ) ); } if ( ! $this->is_acceptable_mysql_version ) { $result['status'] = 'critical'; $result['label'] = __( 'Severely outdated SQL server' ); $result['badge']['label'] = __( 'Security' ); $result['description'] .= sprintf( '

    %s

    ', sprintf( /* translators: 1: The database engine in use (MySQL or MariaDB). 2: Database server minimum version number. */ __( 'WordPress requires %1$s version %2$s or higher. Contact your web hosting company to correct this.' ), ( $this->is_mariadb ? 'MariaDB' : 'MySQL' ), $this->mysql_required_version ) ); } if ( $db_dropin ) { $result['description'] .= sprintf( '

    %s

    ', wp_kses( sprintf( /* translators: 1: The name of the drop-in. 2: The name of the database engine. */ __( 'You are using a %1$s drop-in which might mean that a %2$s database is not being used.' ), 'wp-content/db.php', ( $this->is_mariadb ? 'MariaDB' : 'MySQL' ) ), array( 'code' => true, ) ) ); } return $result; } /** * Tests if the site can communicate with WordPress.org. * * @since 5.2.0 * * @return array The test results. */ public function get_test_dotorg_communication() { $result = array( 'label' => __( 'Can communicate with WordPress.org' ), 'status' => '', 'badge' => array( 'label' => __( 'Security' ), 'color' => 'blue', ), 'description' => sprintf( '

    %s

    ', __( 'Communicating with the WordPress servers is used to check for new versions, and to both install and update WordPress core, themes or plugins.' ) ), 'actions' => '', 'test' => 'dotorg_communication', ); $wp_dotorg = wp_remote_get( 'https://api.wordpress.org', array( 'timeout' => 10, ) ); if ( ! is_wp_error( $wp_dotorg ) ) { $result['status'] = 'good'; } else { $result['status'] = 'critical'; $result['label'] = __( 'Could not reach WordPress.org' ); $result['description'] .= sprintf( '

    %s

    ', sprintf( '%s %s', /* translators: Hidden accessibility text. */ __( 'Error' ), sprintf( /* translators: 1: The IP address WordPress.org resolves to. 2: The error returned by the lookup. */ __( 'Your site is unable to reach WordPress.org at %1$s, and returned the error: %2$s' ), gethostbyname( 'api.wordpress.org' ), $wp_dotorg->get_error_message() ) ) ); $result['actions'] = sprintf( '

    %s %s

    ', /* translators: Localized Support reference. */ esc_url( __( 'https://wordpress.org/support/forums/' ) ), __( 'Get help resolving this issue.' ), /* translators: Hidden accessibility text. */ __( '(opens in a new tab)' ) ); } return $result; } /** * Tests if debug information is enabled. * * When WP_DEBUG is enabled, errors and information may be disclosed to site visitors, * or logged to a publicly accessible file. * * Debugging is also frequently left enabled after looking for errors on a site, * as site owners do not understand the implications of this. * * @since 5.2.0 * * @return array The test results. */ public function get_test_is_in_debug_mode() { $result = array( 'label' => __( 'Your site is not set to output debug information' ), 'status' => 'good', 'badge' => array( 'label' => __( 'Security' ), 'color' => 'blue', ), 'description' => sprintf( '

    %s

    ', __( 'Debug mode is often enabled to gather more details about an error or site failure, but may contain sensitive information which should not be available on a publicly available website.' ) ), 'actions' => sprintf( '

    %s %s

    ', /* translators: Documentation explaining debugging in WordPress. */ esc_url( __( 'https://developer.wordpress.org/advanced-administration/debug/debug-wordpress/' ) ), __( 'Learn more about debugging in WordPress.' ), /* translators: Hidden accessibility text. */ __( '(opens in a new tab)' ) ), 'test' => 'is_in_debug_mode', ); if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) { if ( defined( 'WP_DEBUG_LOG' ) && WP_DEBUG_LOG ) { $result['label'] = __( 'Your site is set to log errors to a potentially public file' ); $result['status'] = str_starts_with( ini_get( 'error_log' ), ABSPATH ) ? 'critical' : 'recommended'; $result['description'] .= sprintf( '

    %s

    ', sprintf( /* translators: %s: WP_DEBUG_LOG */ __( 'The value, %s, has been added to this website’s configuration file. This means any errors on the site will be written to a file which is potentially available to all users.' ), 'WP_DEBUG_LOG' ) ); } if ( defined( 'WP_DEBUG_DISPLAY' ) && WP_DEBUG_DISPLAY ) { $result['label'] = __( 'Your site is set to display errors to site visitors' ); $result['status'] = 'critical'; // On development environments, set the status to recommended. if ( $this->is_development_environment() ) { $result['status'] = 'recommended'; } $result['description'] .= sprintf( '

    %s

    ', sprintf( /* translators: 1: WP_DEBUG_DISPLAY, 2: WP_DEBUG */ __( 'The value, %1$s, has either been enabled by %2$s or added to your configuration file. This will make errors display on the front end of your site.' ), 'WP_DEBUG_DISPLAY', 'WP_DEBUG' ) ); } } return $result; } /** * Tests if the site is serving content over HTTPS. * * Many sites have varying degrees of HTTPS support, the most common of which is sites that have it * enabled, but only if you visit the right site address. * * @since 5.2.0 * @since 5.7.0 Updated to rely on {@see wp_is_using_https()} and {@see wp_is_https_supported()}. * * @return array The test results. */ public function get_test_https_status() { /* * Check HTTPS detection results. */ $errors = wp_get_https_detection_errors(); $default_update_url = wp_get_default_update_https_url(); $result = array( 'label' => __( 'Your website is using an active HTTPS connection' ), 'status' => 'good', 'badge' => array( 'label' => __( 'Security' ), 'color' => 'blue', ), 'description' => sprintf( '

    %s

    ', __( 'An HTTPS connection is a more secure way of browsing the web. Many services now have HTTPS as a requirement. HTTPS allows you to take advantage of new features that can increase site speed, improve search rankings, and gain the trust of your visitors by helping to protect their online privacy.' ) ), 'actions' => sprintf( '

    %s %s

    ', esc_url( $default_update_url ), __( 'Learn more about why you should use HTTPS' ), /* translators: Hidden accessibility text. */ __( '(opens in a new tab)' ) ), 'test' => 'https_status', ); if ( ! wp_is_using_https() ) { /* * If the website is not using HTTPS, provide more information * about whether it is supported and how it can be enabled. */ $result['status'] = 'recommended'; $result['label'] = __( 'Your website does not use HTTPS' ); if ( wp_is_site_url_using_https() ) { if ( is_ssl() ) { $result['description'] = sprintf( '

    %s

    ', sprintf( /* translators: %s: URL to Settings > General > Site Address. */ __( 'You are accessing this website using HTTPS, but your Site Address is not set up to use HTTPS by default.' ), esc_url( admin_url( 'options-general.php' ) . '#home' ) ) ); } else { $result['description'] = sprintf( '

    %s

    ', sprintf( /* translators: %s: URL to Settings > General > Site Address. */ __( 'Your Site Address is not set up to use HTTPS.' ), esc_url( admin_url( 'options-general.php' ) . '#home' ) ) ); } } else { if ( is_ssl() ) { $result['description'] = sprintf( '

    %s

    ', sprintf( /* translators: 1: URL to Settings > General > WordPress Address, 2: URL to Settings > General > Site Address. */ __( 'You are accessing this website using HTTPS, but your WordPress Address and Site Address are not set up to use HTTPS by default.' ), esc_url( admin_url( 'options-general.php' ) . '#siteurl' ), esc_url( admin_url( 'options-general.php' ) . '#home' ) ) ); } else { $result['description'] = sprintf( '

    %s

    ', sprintf( /* translators: 1: URL to Settings > General > WordPress Address, 2: URL to Settings > General > Site Address. */ __( 'Your WordPress Address and Site Address are not set up to use HTTPS.' ), esc_url( admin_url( 'options-general.php' ) . '#siteurl' ), esc_url( admin_url( 'options-general.php' ) . '#home' ) ) ); } } if ( wp_is_https_supported() ) { $result['description'] .= sprintf( '

    %s

    ', __( 'HTTPS is already supported for your website.' ) ); if ( defined( 'WP_HOME' ) || defined( 'WP_SITEURL' ) ) { $result['description'] .= sprintf( '

    %s

    ', sprintf( /* translators: 1: wp-config.php, 2: WP_HOME, 3: WP_SITEURL */ __( 'However, your WordPress Address is currently controlled by a PHP constant and therefore cannot be updated. You need to edit your %1$s and remove or update the definitions of %2$s and %3$s.' ), 'wp-config.php', 'WP_HOME', 'WP_SITEURL' ) ); } elseif ( current_user_can( 'update_https' ) ) { $default_direct_update_url = add_query_arg( 'action', 'update_https', wp_nonce_url( admin_url( 'site-health.php' ), 'wp_update_https' ) ); $direct_update_url = wp_get_direct_update_https_url(); if ( ! empty( $direct_update_url ) ) { $result['actions'] = sprintf( '

    %2$s %3$s

    ', esc_url( $direct_update_url ), __( 'Update your site to use HTTPS' ), /* translators: Hidden accessibility text. */ __( '(opens in a new tab)' ) ); } else { $result['actions'] = sprintf( '

    %2$s

    ', esc_url( $default_direct_update_url ), __( 'Update your site to use HTTPS' ) ); } } } else { // If host-specific "Update HTTPS" URL is provided, include a link. $update_url = wp_get_update_https_url(); if ( $update_url !== $default_update_url ) { $result['description'] .= sprintf( '

    %s %s

    ', esc_url( $update_url ), __( 'Talk to your web host about supporting HTTPS for your website.' ), /* translators: Hidden accessibility text. */ __( '(opens in a new tab)' ) ); } else { $result['description'] .= sprintf( '

    %s

    ', __( 'Talk to your web host about supporting HTTPS for your website.' ) ); } } } return $result; } /** * Checks if the HTTP API can handle SSL/TLS requests. * * @since 5.2.0 * * @return array The test result. */ public function get_test_ssl_support() { $result = array( 'label' => '', 'status' => '', 'badge' => array( 'label' => __( 'Security' ), 'color' => 'blue', ), 'description' => sprintf( '

    %s

    ', __( 'Securely communicating between servers are needed for transactions such as fetching files, conducting sales on store sites, and much more.' ) ), 'actions' => '', 'test' => 'ssl_support', ); $supports_https = wp_http_supports( array( 'ssl' ) ); if ( $supports_https ) { $result['status'] = 'good'; $result['label'] = __( 'Your site can communicate securely with other services' ); } else { $result['status'] = 'critical'; $result['label'] = __( 'Your site is unable to communicate securely with other services' ); $result['description'] .= sprintf( '

    %s

    ', __( 'Talk to your web host about OpenSSL support for PHP.' ) ); } return $result; } /** * Tests if scheduled events run as intended. * * If scheduled events are not running, this may indicate something with WP_Cron is not working * as intended, or that there are orphaned events hanging around from older code. * * @since 5.2.0 * * @return array The test results. */ public function get_test_scheduled_events() { $result = array( 'label' => __( 'Scheduled events are running' ), 'status' => 'good', 'badge' => array( 'label' => __( 'Performance' ), 'color' => 'blue', ), 'description' => sprintf( '

    %s

    ', __( 'Scheduled events are what periodically looks for updates to plugins, themes and WordPress itself. It is also what makes sure scheduled posts are published on time. It may also be used by various plugins to make sure that planned actions are executed.' ) ), 'actions' => '', 'test' => 'scheduled_events', ); $this->wp_schedule_test_init(); if ( is_wp_error( $this->has_missed_cron() ) ) { $result['status'] = 'critical'; $result['label'] = __( 'It was not possible to check your scheduled events' ); $result['description'] = sprintf( '

    %s

    ', sprintf( /* translators: %s: The error message returned while from the cron scheduler. */ __( 'While trying to test your site’s scheduled events, the following error was returned: %s' ), $this->has_missed_cron()->get_error_message() ) ); } elseif ( $this->has_missed_cron() ) { $result['status'] = 'recommended'; $result['label'] = __( 'A scheduled event has failed' ); $result['description'] = sprintf( '

    %s

    ', sprintf( /* translators: %s: The name of the failed cron event. */ __( 'The scheduled event, %s, failed to run. Your site still works, but this may indicate that scheduling posts or automated updates may not work as intended.' ), $this->last_missed_cron ) ); } elseif ( $this->has_late_cron() ) { $result['status'] = 'recommended'; $result['label'] = __( 'A scheduled event is late' ); $result['description'] = sprintf( '

    %s

    ', sprintf( /* translators: %s: The name of the late cron event. */ __( 'The scheduled event, %s, is late to run. Your site still works, but this may indicate that scheduling posts or automated updates may not work as intended.' ), $this->last_late_cron ) ); } return $result; } /** * Tests if WordPress can run automated background updates. * * Background updates in WordPress are primarily used for minor releases and security updates. * It's important to either have these working, or be aware that they are intentionally disabled * for whatever reason. * * @since 5.2.0 * * @return array The test results. */ public function get_test_background_updates() { $result = array( 'label' => __( 'Background updates are working' ), 'status' => 'good', 'badge' => array( 'label' => __( 'Security' ), 'color' => 'blue', ), 'description' => sprintf( '

    %s

    ', __( 'Background updates ensure that WordPress can auto-update if a security update is released for the version you are currently using.' ) ), 'actions' => '', 'test' => 'background_updates', ); if ( ! class_exists( 'WP_Site_Health_Auto_Updates' ) ) { require_once ABSPATH . 'wp-admin/includes/class-wp-site-health-auto-updates.php'; } /* * Run the auto-update tests in a separate class, * as there are many considerations to be made. */ $automatic_updates = new WP_Site_Health_Auto_Updates(); $tests = $automatic_updates->run_tests(); $output = '
      '; foreach ( $tests as $test ) { /* translators: Hidden accessibility text. */ $severity_string = __( 'Passed' ); if ( 'fail' === $test->severity ) { $result['label'] = __( 'Background updates are not working as expected' ); $result['status'] = 'critical'; /* translators: Hidden accessibility text. */ $severity_string = __( 'Error' ); } if ( 'warning' === $test->severity && 'good' === $result['status'] ) { $result['label'] = __( 'Background updates may not be working properly' ); $result['status'] = 'recommended'; /* translators: Hidden accessibility text. */ $severity_string = __( 'Warning' ); } $output .= sprintf( '
    • %s %s
    • ', esc_attr( $test->severity ), $severity_string, $test->description ); } $output .= '
    '; if ( 'good' !== $result['status'] ) { $result['description'] .= $output; } return $result; } /** * Tests if plugin and theme auto-updates appear to be configured correctly. * * @since 5.5.0 * * @return array The test results. */ public function get_test_plugin_theme_auto_updates() { $result = array( 'label' => __( 'Plugin and theme auto-updates appear to be configured correctly' ), 'status' => 'good', 'badge' => array( 'label' => __( 'Security' ), 'color' => 'blue', ), 'description' => sprintf( '

    %s

    ', __( 'Plugin and theme auto-updates ensure that the latest versions are always installed.' ) ), 'actions' => '', 'test' => 'plugin_theme_auto_updates', ); $check_plugin_theme_updates = $this->detect_plugin_theme_auto_update_issues(); $result['status'] = $check_plugin_theme_updates->status; if ( 'good' !== $result['status'] ) { $result['label'] = __( 'Your site may have problems auto-updating plugins and themes' ); $result['description'] .= sprintf( '

    %s

    ', $check_plugin_theme_updates->message ); } return $result; } /** * Tests available disk space for updates. * * @since 6.3.0 * * @return array The test results. */ public function get_test_available_updates_disk_space() { $available_space = function_exists( 'disk_free_space' ) ? @disk_free_space( WP_CONTENT_DIR ) : false; $result = array( 'label' => __( 'Disk space available to safely perform updates' ), 'status' => 'good', 'badge' => array( 'label' => __( 'Security' ), 'color' => 'blue', ), 'description' => sprintf( /* translators: %s: Available disk space in MB or GB. */ '

    ' . __( '%s available disk space was detected, update routines can be performed safely.' ) . '

    ', size_format( $available_space ) ), 'actions' => '', 'test' => 'available_updates_disk_space', ); if ( false === $available_space ) { $result['description'] = __( 'Could not determine available disk space for updates.' ); $result['status'] = 'recommended'; } elseif ( $available_space < 20 * MB_IN_BYTES ) { $result['description'] = sprintf( /* translators: %s: Available disk space in MB or GB. */ __( 'Available disk space is critically low, less than %s available. Proceed with caution, updates may fail.' ), size_format( 20 * MB_IN_BYTES ) ); $result['status'] = 'critical'; } elseif ( $available_space < 100 * MB_IN_BYTES ) { $result['description'] = sprintf( /* translators: %s: Available disk space in MB or GB. */ __( 'Available disk space is low, less than %s available.' ), size_format( 100 * MB_IN_BYTES ) ); $result['status'] = 'recommended'; } return $result; } /** * Tests if plugin and theme temporary backup directories are writable or can be created. * * @since 6.3.0 * * @global WP_Filesystem_Base $wp_filesystem WordPress filesystem subclass. * * @return array The test results. */ public function get_test_update_temp_backup_writable() { global $wp_filesystem; $result = array( 'label' => __( 'Plugin and theme temporary backup directory is writable' ), 'status' => 'good', 'badge' => array( 'label' => __( 'Security' ), 'color' => 'blue', ), 'description' => sprintf( /* translators: %s: wp-content/upgrade-temp-backup */ '

    ' . __( 'The %s directory used to improve the stability of plugin and theme updates is writable.' ) . '

    ', 'wp-content/upgrade-temp-backup' ), 'actions' => '', 'test' => 'update_temp_backup_writable', ); 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 ) ) { $result['status'] = 'recommended'; $result['label'] = __( 'Could not access filesystem' ); $result['description'] = __( 'Unable to connect to the filesystem. Please confirm your credentials.' ); return $result; } $wp_content = $wp_filesystem->wp_content_dir(); if ( ! $wp_content ) { $result['status'] = 'critical'; $result['label'] = __( 'Unable to locate WordPress content directory' ); $result['description'] = sprintf( /* translators: %s: wp-content */ '

    ' . __( 'The %s directory cannot be located.' ) . '

    ', 'wp-content' ); return $result; } $upgrade_dir_exists = $wp_filesystem->is_dir( "$wp_content/upgrade" ); $upgrade_dir_is_writable = $wp_filesystem->is_writable( "$wp_content/upgrade" ); $backup_dir_exists = $wp_filesystem->is_dir( "$wp_content/upgrade-temp-backup" ); $backup_dir_is_writable = $wp_filesystem->is_writable( "$wp_content/upgrade-temp-backup" ); $plugins_dir_exists = $wp_filesystem->is_dir( "$wp_content/upgrade-temp-backup/plugins" ); $plugins_dir_is_writable = $wp_filesystem->is_writable( "$wp_content/upgrade-temp-backup/plugins" ); $themes_dir_exists = $wp_filesystem->is_dir( "$wp_content/upgrade-temp-backup/themes" ); $themes_dir_is_writable = $wp_filesystem->is_writable( "$wp_content/upgrade-temp-backup/themes" ); if ( $plugins_dir_exists && ! $plugins_dir_is_writable && $themes_dir_exists && ! $themes_dir_is_writable ) { $result['status'] = 'critical'; $result['label'] = __( 'Plugin and theme temporary backup directories exist but are not writable' ); $result['description'] = sprintf( /* translators: 1: wp-content/upgrade-temp-backup/plugins, 2: wp-content/upgrade-temp-backup/themes. */ '

    ' . __( 'The %1$s and %2$s directories exist but are not writable. These directories are used to improve the stability of plugin updates. Please make sure the server has write permissions to these directories.' ) . '

    ', 'wp-content/upgrade-temp-backup/plugins', 'wp-content/upgrade-temp-backup/themes' ); return $result; } if ( $plugins_dir_exists && ! $plugins_dir_is_writable ) { $result['status'] = 'critical'; $result['label'] = __( 'Plugin temporary backup directory exists but is not writable' ); $result['description'] = sprintf( /* translators: %s: wp-content/upgrade-temp-backup/plugins */ '

    ' . __( 'The %s directory exists but is not writable. This directory is used to improve the stability of plugin updates. Please make sure the server has write permissions to this directory.' ) . '

    ', 'wp-content/upgrade-temp-backup/plugins' ); return $result; } if ( $themes_dir_exists && ! $themes_dir_is_writable ) { $result['status'] = 'critical'; $result['label'] = __( 'Theme temporary backup directory exists but is not writable' ); $result['description'] = sprintf( /* translators: %s: wp-content/upgrade-temp-backup/themes */ '

    ' . __( 'The %s directory exists but is not writable. This directory is used to improve the stability of theme updates. Please make sure the server has write permissions to this directory.' ) . '

    ', 'wp-content/upgrade-temp-backup/themes' ); return $result; } if ( ( ! $plugins_dir_exists || ! $themes_dir_exists ) && $backup_dir_exists && ! $backup_dir_is_writable ) { $result['status'] = 'critical'; $result['label'] = __( 'The temporary backup directory exists but is not writable' ); $result['description'] = sprintf( /* translators: %s: wp-content/upgrade-temp-backup */ '

    ' . __( 'The %s directory exists but is not writable. This directory is used to improve the stability of plugin and theme updates. Please make sure the server has write permissions to this directory.' ) . '

    ', 'wp-content/upgrade-temp-backup' ); return $result; } if ( ! $backup_dir_exists && $upgrade_dir_exists && ! $upgrade_dir_is_writable ) { $result['status'] = 'critical'; $result['label'] = __( 'The upgrade directory exists but is not writable' ); $result['description'] = sprintf( /* translators: %s: wp-content/upgrade */ '

    ' . __( 'The %s directory exists but is not writable. This directory is used for plugin and theme updates. Please make sure the server has write permissions to this directory.' ) . '

    ', 'wp-content/upgrade' ); return $result; } if ( ! $upgrade_dir_exists && ! $wp_filesystem->is_writable( $wp_content ) ) { $result['status'] = 'critical'; $result['label'] = __( 'The upgrade directory cannot be created' ); $result['description'] = sprintf( /* translators: 1: wp-content/upgrade, 2: wp-content. */ '

    ' . __( 'The %1$s directory does not exist, and the server does not have write permissions in %2$s to create it. This directory is used for plugin and theme updates. Please make sure the server has write permissions in %2$s.' ) . '

    ', 'wp-content/upgrade', 'wp-content' ); return $result; } return $result; } /** * Tests if loopbacks work as expected. * * A loopback is when WordPress queries itself, for example to start a new WP_Cron instance, * or when editing a plugin or theme. This has shown itself to be a recurring issue, * as code can very easily break this interaction. * * @since 5.2.0 * * @return array The test results. */ public function get_test_loopback_requests() { $result = array( 'label' => __( 'Your site can perform loopback requests' ), 'status' => 'good', 'badge' => array( 'label' => __( 'Performance' ), 'color' => 'blue', ), 'description' => sprintf( '

    %s

    ', __( 'Loopback requests are used to run scheduled events, and are also used by the built-in editors for themes and plugins to verify code stability.' ) ), 'actions' => '', 'test' => 'loopback_requests', ); $check_loopback = $this->can_perform_loopback(); $result['status'] = $check_loopback->status; if ( 'good' !== $result['status'] ) { $result['label'] = __( 'Your site could not complete a loopback request' ); $result['description'] .= sprintf( '

    %s

    ', $check_loopback->message ); } return $result; } /** * Tests if HTTP requests are blocked. * * It's possible to block all outgoing communication (with the possibility of allowing certain * hosts) via the HTTP API. This may create problems for users as many features are running as * services these days. * * @since 5.2.0 * * @return array The test results. */ public function get_test_http_requests() { $result = array( 'label' => __( 'HTTP requests seem to be working as expected' ), 'status' => 'good', 'badge' => array( 'label' => __( 'Performance' ), 'color' => 'blue', ), 'description' => sprintf( '

    %s

    ', __( 'It is possible for site maintainers to block all, or some, communication to other sites and services. If set up incorrectly, this may prevent plugins and themes from working as intended.' ) ), 'actions' => '', 'test' => 'http_requests', ); $blocked = false; $hosts = array(); if ( defined( 'WP_HTTP_BLOCK_EXTERNAL' ) && WP_HTTP_BLOCK_EXTERNAL ) { $blocked = true; } if ( defined( 'WP_ACCESSIBLE_HOSTS' ) ) { $hosts = explode( ',', WP_ACCESSIBLE_HOSTS ); } if ( $blocked && 0 === count( $hosts ) ) { $result['status'] = 'critical'; $result['label'] = __( 'HTTP requests are blocked' ); $result['description'] .= sprintf( '

    %s

    ', sprintf( /* translators: %s: Name of the constant used. */ __( 'HTTP requests have been blocked by the %s constant, with no allowed hosts.' ), 'WP_HTTP_BLOCK_EXTERNAL' ) ); } if ( $blocked && 0 < count( $hosts ) ) { $result['status'] = 'recommended'; $result['label'] = __( 'HTTP requests are partially blocked' ); $result['description'] .= sprintf( '

    %s

    ', sprintf( /* translators: 1: Name of the constant used. 2: List of allowed hostnames. */ __( 'HTTP requests have been blocked by the %1$s constant, with some allowed hosts: %2$s.' ), 'WP_HTTP_BLOCK_EXTERNAL', implode( ',', $hosts ) ) ); } return $result; } /** * Tests if the REST API is accessible. * * Various security measures may block the REST API from working, or it may have been disabled in general. * This is required for the new block editor to work, so we explicitly test for this. * * @since 5.2.0 * * @return array The test results. */ public function get_test_rest_availability() { $result = array( 'label' => __( 'The REST API is available' ), 'status' => 'good', 'badge' => array( 'label' => __( 'Performance' ), 'color' => 'blue', ), 'description' => sprintf( '

    %s

    ', __( 'The REST API is one way that WordPress and other applications communicate with the server. For example, the block editor screen relies on the REST API to display and save your posts and pages.' ) ), 'actions' => '', 'test' => 'rest_availability', ); $cookies = wp_unslash( $_COOKIE ); $timeout = 10; // 10 seconds. $headers = array( 'Cache-Control' => 'no-cache', 'X-WP-Nonce' => wp_create_nonce( 'wp_rest' ), ); /** This filter is documented in wp-includes/class-wp-http-streams.php */ $sslverify = apply_filters( 'https_local_ssl_verify', false ); // Include Basic auth in loopback requests. if ( isset( $_SERVER['PHP_AUTH_USER'] ) && isset( $_SERVER['PHP_AUTH_PW'] ) ) { $headers['Authorization'] = 'Basic ' . base64_encode( wp_unslash( $_SERVER['PHP_AUTH_USER'] ) . ':' . wp_unslash( $_SERVER['PHP_AUTH_PW'] ) ); } $url = rest_url( 'wp/v2/types/post' ); // The context for this is editing with the new block editor. $url = add_query_arg( array( 'context' => 'edit', ), $url ); $r = wp_remote_get( $url, compact( 'cookies', 'headers', 'timeout', 'sslverify' ) ); if ( is_wp_error( $r ) ) { $result['status'] = 'critical'; $result['label'] = __( 'The REST API encountered an error' ); $result['description'] .= sprintf( '

    %s

    %s
    %s

    ', __( 'When testing the REST API, an error was encountered:' ), sprintf( // translators: %s: The REST API URL. __( 'REST API Endpoint: %s' ), $url ), sprintf( // translators: 1: The WordPress error code. 2: The WordPress error message. __( 'REST API Response: (%1$s) %2$s' ), $r->get_error_code(), $r->get_error_message() ) ); } elseif ( 200 !== wp_remote_retrieve_response_code( $r ) ) { $result['status'] = 'recommended'; $result['label'] = __( 'The REST API encountered an unexpected result' ); $result['description'] .= sprintf( '

    %s

    %s
    %s

    ', __( 'When testing the REST API, an unexpected result was returned:' ), sprintf( // translators: %s: The REST API URL. __( 'REST API Endpoint: %s' ), $url ), sprintf( // translators: 1: The WordPress error code. 2: The HTTP status code error message. __( 'REST API Response: (%1$s) %2$s' ), wp_remote_retrieve_response_code( $r ), wp_remote_retrieve_response_message( $r ) ) ); } else { $json = json_decode( wp_remote_retrieve_body( $r ), true ); if ( false !== $json && ! isset( $json['capabilities'] ) ) { $result['status'] = 'recommended'; $result['label'] = __( 'The REST API did not behave correctly' ); $result['description'] .= sprintf( '

    %s

    ', sprintf( /* translators: %s: The name of the query parameter being tested. */ __( 'The REST API did not process the %s query parameter correctly.' ), 'context' ) ); } } return $result; } /** * Tests if 'file_uploads' directive in PHP.ini is turned off. * * @since 5.5.0 * * @return array The test results. */ public function get_test_file_uploads() { $result = array( 'label' => __( 'Files can be uploaded' ), 'status' => 'good', 'badge' => array( 'label' => __( 'Performance' ), 'color' => 'blue', ), 'description' => sprintf( '

    %s

    ', sprintf( /* translators: 1: file_uploads, 2: php.ini */ __( 'The %1$s directive in %2$s determines if uploading files is allowed on your site.' ), 'file_uploads', 'php.ini' ) ), 'actions' => '', 'test' => 'file_uploads', ); if ( ! function_exists( 'ini_get' ) ) { $result['status'] = 'critical'; $result['description'] .= sprintf( /* translators: %s: ini_get() */ __( 'The %s function has been disabled, some media settings are unavailable because of this.' ), 'ini_get()' ); return $result; } if ( empty( ini_get( 'file_uploads' ) ) ) { $result['status'] = 'critical'; $result['description'] .= sprintf( '

    %s

    ', sprintf( /* translators: 1: file_uploads, 2: 0 */ __( '%1$s is set to %2$s. You won\'t be able to upload files on your site.' ), 'file_uploads', '0' ) ); return $result; } $post_max_size = ini_get( 'post_max_size' ); $upload_max_filesize = ini_get( 'upload_max_filesize' ); if ( wp_convert_hr_to_bytes( $post_max_size ) < wp_convert_hr_to_bytes( $upload_max_filesize ) ) { $result['label'] = sprintf( /* translators: 1: post_max_size, 2: upload_max_filesize */ __( 'The "%1$s" value is smaller than "%2$s"' ), 'post_max_size', 'upload_max_filesize' ); $result['status'] = 'recommended'; if ( 0 === wp_convert_hr_to_bytes( $post_max_size ) ) { $result['description'] = sprintf( '

    %s

    ', sprintf( /* translators: 1: post_max_size, 2: upload_max_filesize */ __( 'The setting for %1$s is currently configured as 0, this could cause some problems when trying to upload files through plugin or theme features that rely on various upload methods. It is recommended to configure this setting to a fixed value, ideally matching the value of %2$s, as some upload methods read the value 0 as either unlimited, or disabled.' ), 'post_max_size', 'upload_max_filesize' ) ); } else { $result['description'] = sprintf( '

    %s

    ', sprintf( /* translators: 1: post_max_size, 2: upload_max_filesize */ __( 'The setting for %1$s is smaller than %2$s, this could cause some problems when trying to upload files.' ), 'post_max_size', 'upload_max_filesize' ) ); } return $result; } return $result; } /** * Tests if the Authorization header has the expected values. * * @since 5.6.0 * * @return array */ public function get_test_authorization_header() { $result = array( 'label' => __( 'The Authorization header is working as expected' ), 'status' => 'good', 'badge' => array( 'label' => __( 'Security' ), 'color' => 'blue', ), 'description' => sprintf( '

    %s

    ', __( 'The Authorization header is used by third-party applications you have approved for this site. Without this header, those apps cannot connect to your site.' ) ), 'actions' => '', 'test' => 'authorization_header', ); if ( ! isset( $_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW'] ) ) { $result['label'] = __( 'The authorization header is missing' ); } elseif ( 'user' !== $_SERVER['PHP_AUTH_USER'] || 'pwd' !== $_SERVER['PHP_AUTH_PW'] ) { $result['label'] = __( 'The authorization header is invalid' ); } else { return $result; } $result['status'] = 'recommended'; $result['description'] .= sprintf( '

    %s

    ', __( 'If you are still seeing this warning after having tried the actions below, you may need to contact your hosting provider for further assistance.' ) ); if ( ! function_exists( 'got_mod_rewrite' ) ) { require_once ABSPATH . 'wp-admin/includes/misc.php'; } if ( got_mod_rewrite() ) { $result['actions'] .= sprintf( '

    %s

    ', esc_url( admin_url( 'options-permalink.php' ) ), __( 'Flush permalinks' ) ); } else { $result['actions'] .= sprintf( '

    %s %s

    ', __( 'https://developer.wordpress.org/rest-api/frequently-asked-questions/#why-is-authentication-not-working' ), __( 'Learn how to configure the Authorization header.' ), /* translators: Hidden accessibility text. */ __( '(opens in a new tab)' ) ); } return $result; } /** * Tests if a full page cache is available. * * @since 6.1.0 * * @return array The test result. */ public function get_test_page_cache() { $description = '

    ' . __( 'Page cache enhances the speed and performance of your site by saving and serving static pages instead of calling for a page every time a user visits.' ) . '

    '; $description .= '

    ' . __( 'Page cache is detected by looking for an active page cache plugin as well as making three requests to the homepage and looking for one or more of the following HTTP client caching response headers:' ) . '

    '; $description .= '' . implode( ', ', array_keys( $this->get_page_cache_headers() ) ) . '.'; $result = array( 'badge' => array( 'label' => __( 'Performance' ), 'color' => 'blue', ), 'description' => wp_kses_post( $description ), 'test' => 'page_cache', 'status' => 'good', 'label' => '', 'actions' => sprintf( '

    %2$s %3$s

    ', __( 'https://developer.wordpress.org/advanced-administration/performance/optimization/#caching' ), __( 'Learn more about page cache' ), /* translators: Hidden accessibility text. */ __( '(opens in a new tab)' ) ), ); $page_cache_detail = $this->get_page_cache_detail(); if ( is_wp_error( $page_cache_detail ) ) { $result['label'] = __( 'Unable to detect the presence of page cache' ); $result['status'] = 'recommended'; $error_info = sprintf( /* translators: 1: Error message, 2: Error code. */ __( 'Unable to detect page cache due to possible loopback request problem. Please verify that the loopback request test is passing. Error: %1$s (Code: %2$s)' ), $page_cache_detail->get_error_message(), $page_cache_detail->get_error_code() ); $result['description'] = wp_kses_post( "

    $error_info

    " ) . $result['description']; return $result; } $result['status'] = $page_cache_detail['status']; switch ( $page_cache_detail['status'] ) { case 'recommended': $result['label'] = __( 'Page cache is not detected but the server response time is OK' ); break; case 'good': $result['label'] = __( 'Page cache is detected and the server response time is good' ); break; default: if ( empty( $page_cache_detail['headers'] ) && ! $page_cache_detail['advanced_cache_present'] ) { $result['label'] = __( 'Page cache is not detected and the server response time is slow' ); } else { $result['label'] = __( 'Page cache is detected but the server response time is still slow' ); } } $page_cache_test_summary = array(); if ( empty( $page_cache_detail['response_time'] ) ) { $page_cache_test_summary[] = ' ' . __( 'Server response time could not be determined. Verify that loopback requests are working.' ); } else { $threshold = $this->get_good_response_time_threshold(); if ( $page_cache_detail['response_time'] < $threshold ) { $page_cache_test_summary[] = ' ' . sprintf( /* translators: 1: The response time in milliseconds, 2: The recommended threshold in milliseconds. */ __( 'Median server response time was %1$s milliseconds. This is less than the recommended %2$s milliseconds threshold.' ), number_format_i18n( $page_cache_detail['response_time'] ), number_format_i18n( $threshold ) ); } else { $page_cache_test_summary[] = ' ' . sprintf( /* translators: 1: The response time in milliseconds, 2: The recommended threshold in milliseconds. */ __( 'Median server response time was %1$s milliseconds. It should be less than the recommended %2$s milliseconds threshold.' ), number_format_i18n( $page_cache_detail['response_time'] ), number_format_i18n( $threshold ) ); } if ( empty( $page_cache_detail['headers'] ) ) { $page_cache_test_summary[] = ' ' . __( 'No client caching response headers were detected.' ); } else { $headers_summary = ''; $headers_summary .= ' ' . sprintf( /* translators: %d: Number of caching headers. */ _n( 'There was %d client caching response header detected:', 'There were %d client caching response headers detected:', count( $page_cache_detail['headers'] ) ), count( $page_cache_detail['headers'] ) ); $headers_summary .= ' ' . implode( ', ', $page_cache_detail['headers'] ) . '.'; $page_cache_test_summary[] = $headers_summary; } } if ( $page_cache_detail['advanced_cache_present'] ) { $page_cache_test_summary[] = ' ' . __( 'A page cache plugin was detected.' ); } elseif ( ! ( is_array( $page_cache_detail ) && ! empty( $page_cache_detail['headers'] ) ) ) { // Note: This message is not shown if client caching response headers were present since an external caching layer may be employed. $page_cache_test_summary[] = ' ' . __( 'A page cache plugin was not detected.' ); } $result['description'] .= '
    • ' . implode( '
    • ', $page_cache_test_summary ) . '
    '; return $result; } /** * Tests if the site uses persistent object cache and recommends to use it if not. * * @since 6.1.0 * * @return array The test result. */ public function get_test_persistent_object_cache() { /** * Filters the action URL for the persistent object cache health check. * * @since 6.1.0 * * @param string $action_url Learn more link for persistent object cache health check. */ $action_url = apply_filters( 'site_status_persistent_object_cache_url', /* translators: Localized Support reference. */ __( 'https://developer.wordpress.org/advanced-administration/performance/optimization/#persistent-object-cache' ) ); $result = array( 'test' => 'persistent_object_cache', 'status' => 'good', 'badge' => array( 'label' => __( 'Performance' ), 'color' => 'blue', ), 'label' => __( 'A persistent object cache is being used' ), 'description' => sprintf( '

    %s

    ', __( 'A persistent object cache makes your site’s database more efficient, resulting in faster load times because WordPress can retrieve your site’s content and settings much more quickly.' ) ), 'actions' => sprintf( '

    %s %s

    ', esc_url( $action_url ), __( 'Learn more about persistent object caching.' ), /* translators: Hidden accessibility text. */ __( '(opens in a new tab)' ) ), ); if ( wp_using_ext_object_cache() ) { return $result; } if ( ! $this->should_suggest_persistent_object_cache() ) { $result['label'] = __( 'A persistent object cache is not required' ); return $result; } $available_services = $this->available_object_cache_services(); $notes = __( 'Your hosting provider can tell you if a persistent object cache can be enabled on your site.' ); if ( ! empty( $available_services ) ) { $notes .= ' ' . sprintf( /* translators: Available object caching services. */ __( 'Your host appears to support the following object caching services: %s.' ), implode( ', ', $available_services ) ); } /** * Filters the second paragraph of the health check's description * when suggesting the use of a persistent object cache. * * Hosts may want to replace the notes to recommend their preferred object caching solution. * * Plugin authors may want to append notes (not replace) on why object caching is recommended for their plugin. * * @since 6.1.0 * * @param string $notes The notes appended to the health check description. * @param string[] $available_services The list of available persistent object cache services. */ $notes = apply_filters( 'site_status_persistent_object_cache_notes', $notes, $available_services ); $result['status'] = 'recommended'; $result['label'] = __( 'You should use a persistent object cache' ); $result['description'] .= sprintf( '

    %s

    ', wp_kses( $notes, array( 'a' => array( 'href' => true ), 'code' => true, 'em' => true, 'strong' => true, ) ) ); return $result; } /** * Calculates total amount of autoloaded data. * * @since 6.6.0 * * @return int Autoloaded data in bytes. */ public function get_autoloaded_options_size() { $alloptions = wp_load_alloptions(); $total_length = 0; foreach ( $alloptions as $option_value ) { if ( is_array( $option_value ) || is_object( $option_value ) ) { $option_value = maybe_serialize( $option_value ); } $total_length += strlen( (string) $option_value ); } return $total_length; } /** * Tests the number of autoloaded options. * * @since 6.6.0 * * @return array The test results. */ public function get_test_autoloaded_options() { $autoloaded_options_size = $this->get_autoloaded_options_size(); $autoloaded_options_count = count( wp_load_alloptions() ); $base_description = __( 'Autoloaded options are configuration settings for plugins and themes that are automatically loaded with every page load in WordPress. Having too many autoloaded options can slow down your site.' ); $result = array( 'label' => __( 'Autoloaded options are acceptable' ), 'status' => 'good', 'badge' => array( 'label' => __( 'Performance' ), 'color' => 'blue', ), 'description' => sprintf( /* translators: 1: Number of autoloaded options, 2: Autoloaded options size. */ '

    ' . esc_html( $base_description ) . ' ' . __( 'Your site has %1$s autoloaded options (size: %2$s) in the options table, which is acceptable.' ) . '

    ', $autoloaded_options_count, size_format( $autoloaded_options_size ) ), 'actions' => '', 'test' => 'autoloaded_options', ); /** * Filters max bytes threshold to trigger warning in Site Health. * * @since 6.6.0 * * @param int $limit Autoloaded options threshold size. Default 800000. */ $limit = apply_filters( 'site_status_autoloaded_options_size_limit', 800000 ); if ( $autoloaded_options_size < $limit ) { return $result; } $result['status'] = 'critical'; $result['label'] = __( 'Autoloaded options could affect performance' ); $result['description'] = sprintf( /* translators: 1: Number of autoloaded options, 2: Autoloaded options size. */ '

    ' . esc_html( $base_description ) . ' ' . __( 'Your site has %1$s autoloaded options (size: %2$s) in the options table, which could cause your site to be slow. You can review the options being autoloaded in your database and remove any options that are no longer needed by your site.' ) . '

    ', $autoloaded_options_count, size_format( $autoloaded_options_size ) ); /** * Filters description to be shown on Site Health warning when threshold is met. * * @since 6.6.0 * * @param string $description Description message when autoloaded options bigger than threshold. */ $result['description'] = apply_filters( 'site_status_autoloaded_options_limit_description', $result['description'] ); $result['actions'] = sprintf( /* translators: 1: HelpHub URL, 2: Link description. */ '

    %2$s

    ', esc_url( __( 'https://developer.wordpress.org/advanced-administration/performance/optimization/#autoloaded-options' ) ), __( 'More info about optimizing autoloaded options' ) ); /** * Filters actionable information to tackle the problem. It can be a link to an external guide. * * @since 6.6.0 * * @param string $actions Call to Action to be used to point to the right direction to solve the issue. */ $result['actions'] = apply_filters( 'site_status_autoloaded_options_action_to_perform', $result['actions'] ); return $result; } /** * Returns a set of tests that belong to the site status page. * * Each site status test is defined here, they may be `direct` tests, that run on page load, or `async` tests * which will run later down the line via JavaScript calls to improve page performance and hopefully also user * experiences. * * @since 5.2.0 * @since 5.6.0 Added support for `has_rest` and `permissions`. * * @return array The list of tests to run. */ public static function get_tests() { $tests = array( 'direct' => array( 'wordpress_version' => array( 'label' => __( 'WordPress Version' ), 'test' => 'wordpress_version', ), 'plugin_version' => array( 'label' => __( 'Plugin Versions' ), 'test' => 'plugin_version', ), 'theme_version' => array( 'label' => __( 'Theme Versions' ), 'test' => 'theme_version', ), 'php_version' => array( 'label' => __( 'PHP Version' ), 'test' => 'php_version', ), 'php_extensions' => array( 'label' => __( 'PHP Extensions' ), 'test' => 'php_extensions', ), 'php_default_timezone' => array( 'label' => __( 'PHP Default Timezone' ), 'test' => 'php_default_timezone', ), 'php_sessions' => array( 'label' => __( 'PHP Sessions' ), 'test' => 'php_sessions', ), 'sql_server' => array( 'label' => __( 'Database Server version' ), 'test' => 'sql_server', ), 'ssl_support' => array( 'label' => __( 'Secure communication' ), 'test' => 'ssl_support', ), 'scheduled_events' => array( 'label' => __( 'Scheduled events' ), 'test' => 'scheduled_events', ), 'http_requests' => array( 'label' => __( 'HTTP Requests' ), 'test' => 'http_requests', ), 'rest_availability' => array( 'label' => __( 'REST API availability' ), 'test' => 'rest_availability', 'skip_cron' => true, ), 'debug_enabled' => array( 'label' => __( 'Debugging enabled' ), 'test' => 'is_in_debug_mode', ), 'file_uploads' => array( 'label' => __( 'File uploads' ), 'test' => 'file_uploads', ), 'plugin_theme_auto_updates' => array( 'label' => __( 'Plugin and theme auto-updates' ), 'test' => 'plugin_theme_auto_updates', ), 'update_temp_backup_writable' => array( 'label' => __( 'Plugin and theme temporary backup directory access' ), 'test' => 'update_temp_backup_writable', ), 'available_updates_disk_space' => array( 'label' => __( 'Available disk space' ), 'test' => 'available_updates_disk_space', ), 'autoloaded_options' => array( 'label' => __( 'Autoloaded options' ), 'test' => 'autoloaded_options', ), ), 'async' => array( 'dotorg_communication' => array( 'label' => __( 'Communication with WordPress.org' ), 'test' => rest_url( 'wp-site-health/v1/tests/dotorg-communication' ), 'has_rest' => true, 'async_direct_test' => array( WP_Site_Health::get_instance(), 'get_test_dotorg_communication' ), ), 'background_updates' => array( 'label' => __( 'Background updates' ), 'test' => rest_url( 'wp-site-health/v1/tests/background-updates' ), 'has_rest' => true, 'async_direct_test' => array( WP_Site_Health::get_instance(), 'get_test_background_updates' ), ), 'loopback_requests' => array( 'label' => __( 'Loopback request' ), 'test' => rest_url( 'wp-site-health/v1/tests/loopback-requests' ), 'has_rest' => true, 'async_direct_test' => array( WP_Site_Health::get_instance(), 'get_test_loopback_requests' ), ), 'https_status' => array( 'label' => __( 'HTTPS status' ), 'test' => rest_url( 'wp-site-health/v1/tests/https-status' ), 'has_rest' => true, 'async_direct_test' => array( WP_Site_Health::get_instance(), 'get_test_https_status' ), ), ), ); // Conditionally include Authorization header test if the site isn't protected by Basic Auth. if ( ! wp_is_site_protected_by_basic_auth() ) { $tests['async']['authorization_header'] = array( 'label' => __( 'Authorization header' ), 'test' => rest_url( 'wp-site-health/v1/tests/authorization-header' ), 'has_rest' => true, 'headers' => array( 'Authorization' => 'Basic ' . base64_encode( 'user:pwd' ) ), 'skip_cron' => true, ); } // Only check for caches in production environments. if ( 'production' === wp_get_environment_type() ) { $tests['async']['page_cache'] = array( 'label' => __( 'Page cache' ), 'test' => rest_url( 'wp-site-health/v1/tests/page-cache' ), 'has_rest' => true, 'async_direct_test' => array( WP_Site_Health::get_instance(), 'get_test_page_cache' ), ); $tests['direct']['persistent_object_cache'] = array( 'label' => __( 'Persistent object cache' ), 'test' => 'persistent_object_cache', ); } /** * Filters which site status tests are run on a site. * * The site health is determined by a set of tests based on best practices from * both the WordPress Hosting Team and web standards in general. * * Some sites may not have the same requirements, for example the automatic update * checks may be handled by a host, and are therefore disabled in core. * Or maybe you want to introduce a new test, is caching enabled/disabled/stale for example. * * Tests may be added either as direct, or asynchronous ones. Any test that may require some time * to complete should run asynchronously, to avoid extended loading periods within wp-admin. * * @since 5.2.0 * @since 5.6.0 Added the `async_direct_test` array key for asynchronous tests. * Added the `skip_cron` array key for all tests. * * @param array[] $tests { * An associative array of direct and asynchronous tests. * * @type array[] $direct { * An array of direct tests. * * @type array ...$identifier { * `$identifier` should be a unique identifier for the test. Plugins and themes are encouraged to * prefix test identifiers with their slug to avoid collisions between tests. * * @type string $label The friendly label to identify the test. * @type callable $test The callback function that runs the test and returns its result. * @type bool $skip_cron Whether to skip this test when running as cron. * } * } * @type array[] $async { * An array of asynchronous tests. * * @type array ...$identifier { * `$identifier` should be a unique identifier for the test. Plugins and themes are encouraged to * prefix test identifiers with their slug to avoid collisions between tests. * * @type string $label The friendly label to identify the test. * @type string $test An admin-ajax.php action to be called to perform the test, or * if `$has_rest` is true, a URL to a REST API endpoint to perform * the test. * @type bool $has_rest Whether the `$test` property points to a REST API endpoint. * @type bool $skip_cron Whether to skip this test when running as cron. * @type callable $async_direct_test A manner of directly calling the test marked as asynchronous, * as the scheduled event can not authenticate, and endpoints * may require authentication. * } * } * } */ $tests = apply_filters( 'site_status_tests', $tests ); // Ensure that the filtered tests contain the required array keys. $tests = array_merge( array( 'direct' => array(), 'async' => array(), ), $tests ); return $tests; } /** * Adds a class to the body HTML tag. * * Filters the body class string for admin pages and adds our own class for easier styling. * * @since 5.2.0 * * @param string $body_class The body class string. * @return string The modified body class string. */ public function admin_body_class( $body_class ) { $screen = get_current_screen(); if ( 'site-health' !== $screen->id ) { return $body_class; } $body_class .= ' site-health'; return $body_class; } /** * Initiates the WP_Cron schedule test cases. * * @since 5.2.0 */ private function wp_schedule_test_init() { $this->schedules = wp_get_schedules(); $this->get_cron_tasks(); } /** * Populates the list of cron events and store them to a class-wide variable. * * @since 5.2.0 */ private function get_cron_tasks() { $cron_tasks = _get_cron_array(); if ( empty( $cron_tasks ) ) { $this->crons = new WP_Error( 'no_tasks', __( 'No scheduled events exist on this site.' ) ); return; } $this->crons = array(); foreach ( $cron_tasks as $time => $cron ) { foreach ( $cron as $hook => $dings ) { foreach ( $dings as $sig => $data ) { $this->crons[ "$hook-$sig-$time" ] = (object) array( 'hook' => $hook, 'time' => $time, 'sig' => $sig, 'args' => $data['args'], 'schedule' => $data['schedule'], 'interval' => isset( $data['interval'] ) ? $data['interval'] : null, ); } } } } /** * Checks if any scheduled tasks have been missed. * * Returns a boolean value of `true` if a scheduled task has been missed and ends processing. * * If the list of crons is an instance of WP_Error, returns the instance instead of a boolean value. * * @since 5.2.0 * * @return bool|WP_Error True if a cron was missed, false if not. WP_Error if the cron is set to that. */ public function has_missed_cron() { if ( is_wp_error( $this->crons ) ) { return $this->crons; } foreach ( $this->crons as $id => $cron ) { if ( ( $cron->time - time() ) < $this->timeout_missed_cron ) { $this->last_missed_cron = $cron->hook; return true; } } return false; } /** * Checks if any scheduled tasks are late. * * Returns a boolean value of `true` if a scheduled task is late and ends processing. * * If the list of crons is an instance of WP_Error, returns the instance instead of a boolean value. * * @since 5.3.0 * * @return bool|WP_Error True if a cron is late, false if not. WP_Error if the cron is set to that. */ public function has_late_cron() { if ( is_wp_error( $this->crons ) ) { return $this->crons; } foreach ( $this->crons as $id => $cron ) { $cron_offset = $cron->time - time(); if ( $cron_offset >= $this->timeout_missed_cron && $cron_offset < $this->timeout_late_cron ) { $this->last_late_cron = $cron->hook; return true; } } return false; } /** * Checks for potential issues with plugin and theme auto-updates. * * Though there is no way to 100% determine if plugin and theme auto-updates are configured * correctly, a few educated guesses could be made to flag any conditions that would * potentially cause unexpected behaviors. * * @since 5.5.0 * * @return object The test results. */ public function detect_plugin_theme_auto_update_issues() { $mock_plugin = (object) array( 'id' => 'w.org/plugins/a-fake-plugin', 'slug' => 'a-fake-plugin', 'plugin' => 'a-fake-plugin/a-fake-plugin.php', 'new_version' => '9.9', 'url' => 'https://wordpress.org/plugins/a-fake-plugin/', 'package' => 'https://downloads.wordpress.org/plugin/a-fake-plugin.9.9.zip', 'icons' => array( '2x' => 'https://ps.w.org/a-fake-plugin/assets/icon-256x256.png', '1x' => 'https://ps.w.org/a-fake-plugin/assets/icon-128x128.png', ), 'banners' => array( '2x' => 'https://ps.w.org/a-fake-plugin/assets/banner-1544x500.png', '1x' => 'https://ps.w.org/a-fake-plugin/assets/banner-772x250.png', ), 'banners_rtl' => array(), 'tested' => '5.5.0', 'requires_php' => '5.6.20', 'compatibility' => new stdClass(), ); $mock_theme = (object) array( 'theme' => 'a-fake-theme', 'new_version' => '9.9', 'url' => 'https://wordpress.org/themes/a-fake-theme/', 'package' => 'https://downloads.wordpress.org/theme/a-fake-theme.9.9.zip', 'requires' => '5.0.0', 'requires_php' => '5.6.20', ); $test_plugins_enabled = wp_is_auto_update_forced_for_item( 'plugin', true, $mock_plugin ); $test_themes_enabled = wp_is_auto_update_forced_for_item( 'theme', true, $mock_theme ); $ui_enabled_for_plugins = wp_is_auto_update_enabled_for_type( 'plugin' ); $ui_enabled_for_themes = wp_is_auto_update_enabled_for_type( 'theme' ); $plugin_filter_present = has_filter( 'auto_update_plugin' ); $theme_filter_present = has_filter( 'auto_update_theme' ); if ( ( ! $test_plugins_enabled && $ui_enabled_for_plugins ) || ( ! $test_themes_enabled && $ui_enabled_for_themes ) ) { return (object) array( 'status' => 'critical', 'message' => __( 'Auto-updates for plugins and/or themes appear to be disabled, but settings are still set to be displayed. This could cause auto-updates to not work as expected.' ), ); } if ( ( ! $test_plugins_enabled && $plugin_filter_present ) && ( ! $test_themes_enabled && $theme_filter_present ) ) { return (object) array( 'status' => 'recommended', 'message' => __( 'Auto-updates for plugins and themes appear to be disabled. This will prevent your site from receiving new versions automatically when available.' ), ); } elseif ( ! $test_plugins_enabled && $plugin_filter_present ) { return (object) array( 'status' => 'recommended', 'message' => __( 'Auto-updates for plugins appear to be disabled. This will prevent your site from receiving new versions automatically when available.' ), ); } elseif ( ! $test_themes_enabled && $theme_filter_present ) { return (object) array( 'status' => 'recommended', 'message' => __( 'Auto-updates for themes appear to be disabled. This will prevent your site from receiving new versions automatically when available.' ), ); } return (object) array( 'status' => 'good', 'message' => __( 'There appear to be no issues with plugin and theme auto-updates.' ), ); } /** * Runs a loopback test on the site. * * Loopbacks are what WordPress uses to communicate with itself to start up WP_Cron, scheduled posts, * make sure plugin or theme edits don't cause site failures and similar. * * @since 5.2.0 * * @return object The test results. */ public function can_perform_loopback() { $body = array( 'site-health' => 'loopback-test' ); $cookies = wp_unslash( $_COOKIE ); $timeout = 10; // 10 seconds. $headers = array( 'Cache-Control' => 'no-cache', ); /** This filter is documented in wp-includes/class-wp-http-streams.php */ $sslverify = apply_filters( 'https_local_ssl_verify', false ); // Include Basic auth in loopback requests. if ( isset( $_SERVER['PHP_AUTH_USER'] ) && isset( $_SERVER['PHP_AUTH_PW'] ) ) { $headers['Authorization'] = 'Basic ' . base64_encode( wp_unslash( $_SERVER['PHP_AUTH_USER'] ) . ':' . wp_unslash( $_SERVER['PHP_AUTH_PW'] ) ); } $url = site_url( 'wp-cron.php' ); /* * A post request is used for the wp-cron.php loopback test to cause the file * to finish early without triggering cron jobs. This has two benefits: * - cron jobs are not triggered a second time on the site health page, * - the loopback request finishes sooner providing a quicker result. * * Using a POST request causes the loopback to differ slightly to the standard * GET request WordPress uses for wp-cron.php loopback requests but is close * enough. See https://core.trac.wordpress.org/ticket/52547 */ $r = wp_remote_post( $url, compact( 'body', 'cookies', 'headers', 'timeout', 'sslverify' ) ); if ( is_wp_error( $r ) ) { return (object) array( 'status' => 'critical', 'message' => sprintf( '%s
    %s', __( 'The loopback request to your site failed, this means features relying on them are not currently working as expected.' ), sprintf( /* translators: 1: The WordPress error message. 2: The WordPress error code. */ __( 'Error: %1$s (%2$s)' ), $r->get_error_message(), $r->get_error_code() ) ), ); } if ( 200 !== wp_remote_retrieve_response_code( $r ) ) { return (object) array( 'status' => 'recommended', 'message' => sprintf( /* translators: %d: The HTTP response code returned. */ __( 'The loopback request returned an unexpected http status code, %d, it was not possible to determine if this will prevent features from working as expected.' ), wp_remote_retrieve_response_code( $r ) ), ); } return (object) array( 'status' => 'good', 'message' => __( 'The loopback request to your site completed successfully.' ), ); } /** * Creates a weekly cron event, if one does not already exist. * * @since 5.4.0 */ public function maybe_create_scheduled_event() { if ( ! wp_next_scheduled( 'wp_site_health_scheduled_check' ) && ! wp_installing() ) { wp_schedule_event( time() + DAY_IN_SECONDS, 'weekly', 'wp_site_health_scheduled_check' ); } } /** * Runs the scheduled event to check and update the latest site health status for the website. * * @since 5.4.0 */ public function wp_cron_scheduled_check() { // Bootstrap wp-admin, as WP_Cron doesn't do this for us. require_once trailingslashit( ABSPATH ) . 'wp-admin/includes/admin.php'; $tests = WP_Site_Health::get_tests(); $results = array(); $site_status = array( 'good' => 0, 'recommended' => 0, 'critical' => 0, ); // Don't run https test on development environments. if ( $this->is_development_environment() ) { unset( $tests['async']['https_status'] ); } foreach ( $tests['direct'] as $test ) { if ( ! empty( $test['skip_cron'] ) ) { continue; } if ( is_string( $test['test'] ) ) { $test_function = sprintf( 'get_test_%s', $test['test'] ); if ( method_exists( $this, $test_function ) && is_callable( array( $this, $test_function ) ) ) { $results[] = $this->perform_test( array( $this, $test_function ) ); continue; } } if ( is_callable( $test['test'] ) ) { $results[] = $this->perform_test( $test['test'] ); } } foreach ( $tests['async'] as $test ) { if ( ! empty( $test['skip_cron'] ) ) { continue; } // Local endpoints may require authentication, so asynchronous tests can pass a direct test runner as well. if ( ! empty( $test['async_direct_test'] ) && is_callable( $test['async_direct_test'] ) ) { // This test is callable, do so and continue to the next asynchronous check. $results[] = $this->perform_test( $test['async_direct_test'] ); continue; } if ( is_string( $test['test'] ) ) { // Check if this test has a REST API endpoint. if ( isset( $test['has_rest'] ) && $test['has_rest'] ) { $result_fetch = wp_remote_get( $test['test'], array( 'body' => array( '_wpnonce' => wp_create_nonce( 'wp_rest' ), ), ) ); } else { $result_fetch = wp_remote_post( admin_url( 'admin-ajax.php' ), array( 'body' => array( 'action' => $test['test'], '_wpnonce' => wp_create_nonce( 'health-check-site-status' ), ), ) ); } if ( ! is_wp_error( $result_fetch ) && 200 === wp_remote_retrieve_response_code( $result_fetch ) ) { $result = json_decode( wp_remote_retrieve_body( $result_fetch ), true ); } else { $result = false; } if ( is_array( $result ) ) { $results[] = $result; } else { $results[] = array( 'status' => 'recommended', 'label' => __( 'A test is unavailable' ), ); } } } foreach ( $results as $result ) { if ( 'critical' === $result['status'] ) { ++$site_status['critical']; } elseif ( 'recommended' === $result['status'] ) { ++$site_status['recommended']; } else { ++$site_status['good']; } } set_transient( 'health-check-site-status-result', wp_json_encode( $site_status ) ); } /** * Checks if the current environment type is set to 'development' or 'local'. * * @since 5.6.0 * * @return bool True if it is a development environment, false if not. */ public function is_development_environment() { return in_array( wp_get_environment_type(), array( 'development', 'local' ), true ); } /** * Returns a list of headers and its verification callback to verify if page cache is enabled or not. * * Note: key is header name and value could be callable function to verify header value. * Empty value mean existence of header detect page cache is enabled. * * @since 6.1.0 * * @return array List of client caching headers and their (optional) verification callbacks. */ public function get_page_cache_headers() { $cache_hit_callback = static function ( $header_value ) { return str_contains( strtolower( $header_value ), 'hit' ); }; $cache_headers = array( 'cache-control' => static function ( $header_value ) { return (bool) preg_match( '/max-age=[1-9]/', $header_value ); }, 'expires' => static function ( $header_value ) { return strtotime( $header_value ) > time(); }, 'age' => static function ( $header_value ) { return is_numeric( $header_value ) && $header_value > 0; }, 'last-modified' => '', 'etag' => '', 'x-cache-enabled' => static function ( $header_value ) { return 'true' === strtolower( $header_value ); }, 'x-cache-disabled' => static function ( $header_value ) { return ( 'on' !== strtolower( $header_value ) ); }, 'x-srcache-store-status' => $cache_hit_callback, 'x-srcache-fetch-status' => $cache_hit_callback, ); /** * Filters the list of cache headers supported by core. * * @since 6.1.0 * * @param array $cache_headers Array of supported cache headers. */ return apply_filters( 'site_status_page_cache_supported_cache_headers', $cache_headers ); } /** * Checks if site has page cache enabled or not. * * @since 6.1.0 * * @return WP_Error|array { * Page cache detection details or else error information. * * @type bool $advanced_cache_present Whether a page cache plugin is present. * @type array[] $page_caching_response_headers Sets of client caching headers for the responses. * @type float[] $response_timing Response timings. * } */ private function check_for_page_caching() { /** This filter is documented in wp-includes/class-wp-http-streams.php */ $sslverify = apply_filters( 'https_local_ssl_verify', false ); $headers = array(); /* * Include basic auth in loopback requests. Note that this will only pass along basic auth when user is * initiating the test. If a site requires basic auth, the test will fail when it runs in WP Cron as part of * wp_site_health_scheduled_check. This logic is copied from WP_Site_Health::can_perform_loopback(). */ if ( isset( $_SERVER['PHP_AUTH_USER'] ) && isset( $_SERVER['PHP_AUTH_PW'] ) ) { $headers['Authorization'] = 'Basic ' . base64_encode( wp_unslash( $_SERVER['PHP_AUTH_USER'] ) . ':' . wp_unslash( $_SERVER['PHP_AUTH_PW'] ) ); } $caching_headers = $this->get_page_cache_headers(); $page_caching_response_headers = array(); $response_timing = array(); for ( $i = 1; $i <= 3; $i++ ) { $start_time = microtime( true ); $http_response = wp_remote_get( home_url( '/' ), compact( 'sslverify', 'headers' ) ); $end_time = microtime( true ); if ( is_wp_error( $http_response ) ) { return $http_response; } if ( wp_remote_retrieve_response_code( $http_response ) !== 200 ) { return new WP_Error( 'http_' . wp_remote_retrieve_response_code( $http_response ), wp_remote_retrieve_response_message( $http_response ) ); } $response_headers = array(); foreach ( $caching_headers as $header => $callback ) { $header_values = wp_remote_retrieve_header( $http_response, $header ); if ( empty( $header_values ) ) { continue; } $header_values = (array) $header_values; if ( empty( $callback ) || ( is_callable( $callback ) && count( array_filter( $header_values, $callback ) ) > 0 ) ) { $response_headers[ $header ] = $header_values; } } $page_caching_response_headers[] = $response_headers; $response_timing[] = ( $end_time - $start_time ) * 1000; } return array( 'advanced_cache_present' => ( file_exists( WP_CONTENT_DIR . '/advanced-cache.php' ) && ( defined( 'WP_CACHE' ) && WP_CACHE ) && /** This filter is documented in wp-settings.php */ apply_filters( 'enable_loading_advanced_cache_dropin', true ) ), 'page_caching_response_headers' => $page_caching_response_headers, 'response_timing' => $response_timing, ); } /** * Gets page cache details. * * @since 6.1.0 * * @return WP_Error|array { * Page cache detail or else a WP_Error if unable to determine. * * @type string $status Page cache status. Good, Recommended or Critical. * @type bool $advanced_cache_present Whether page cache plugin is available or not. * @type string[] $headers Client caching response headers detected. * @type float $response_time Response time of site. * } */ private function get_page_cache_detail() { $page_cache_detail = $this->check_for_page_caching(); if ( is_wp_error( $page_cache_detail ) ) { return $page_cache_detail; } // Use the median server response time. $response_timings = $page_cache_detail['response_timing']; rsort( $response_timings ); $page_speed = $response_timings[ floor( count( $response_timings ) / 2 ) ]; // Obtain unique set of all client caching response headers. $headers = array(); foreach ( $page_cache_detail['page_caching_response_headers'] as $page_caching_response_headers ) { $headers = array_merge( $headers, array_keys( $page_caching_response_headers ) ); } $headers = array_unique( $headers ); // Page cache is detected if there are response headers or a page cache plugin is present. $has_page_caching = ( count( $headers ) > 0 || $page_cache_detail['advanced_cache_present'] ); if ( $page_speed && $page_speed < $this->get_good_response_time_threshold() ) { $result = $has_page_caching ? 'good' : 'recommended'; } else { $result = 'critical'; } return array( 'status' => $result, 'advanced_cache_present' => $page_cache_detail['advanced_cache_present'], 'headers' => $headers, 'response_time' => $page_speed, ); } /** * Gets the threshold below which a response time is considered good. * * @since 6.1.0 * * @return int Threshold in milliseconds. */ private function get_good_response_time_threshold() { /** * Filters the threshold below which a response time is considered good. * * The default is based on https://web.dev/time-to-first-byte/. * * @param int $threshold Threshold in milliseconds. Default 600. * * @since 6.1.0 */ return (int) apply_filters( 'site_status_good_response_time_threshold', 600 ); } /** * Determines whether to suggest using a persistent object cache. * * @since 6.1.0 * * @global wpdb $wpdb WordPress database abstraction object. * * @return bool Whether to suggest using a persistent object cache. */ public function should_suggest_persistent_object_cache() { global $wpdb; /** * Filters whether to suggest use of a persistent object cache and bypass default threshold checks. * * Using this filter allows to override the default logic, effectively short-circuiting the method. * * @since 6.1.0 * * @param bool|null $suggest Boolean to short-circuit, for whether to suggest using a persistent object cache. * Default null. */ $short_circuit = apply_filters( 'site_status_should_suggest_persistent_object_cache', null ); if ( is_bool( $short_circuit ) ) { return $short_circuit; } if ( is_multisite() ) { return true; } /** * Filters the thresholds used to determine whether to suggest the use of a persistent object cache. * * @since 6.1.0 * * @param int[] $thresholds The list of threshold numbers keyed by threshold name. */ $thresholds = apply_filters( 'site_status_persistent_object_cache_thresholds', array( 'alloptions_count' => 500, 'alloptions_bytes' => 100000, 'comments_count' => 1000, 'options_count' => 1000, 'posts_count' => 1000, 'terms_count' => 1000, 'users_count' => 1000, ) ); $alloptions = wp_load_alloptions(); if ( $thresholds['alloptions_count'] < count( $alloptions ) ) { return true; } if ( $thresholds['alloptions_bytes'] < strlen( serialize( $alloptions ) ) ) { return true; } $table_names = implode( "','", array( $wpdb->comments, $wpdb->options, $wpdb->posts, $wpdb->terms, $wpdb->users ) ); // With InnoDB the `TABLE_ROWS` are estimates, which are accurate enough and faster to retrieve than individual `COUNT()` queries. $results = $wpdb->get_results( $wpdb->prepare( // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- This query cannot use interpolation. "SELECT TABLE_NAME AS 'table', TABLE_ROWS AS 'rows', SUM(data_length + index_length) as 'bytes' FROM information_schema.TABLES WHERE TABLE_SCHEMA = %s AND TABLE_NAME IN ('$table_names') GROUP BY TABLE_NAME;", DB_NAME ), OBJECT_K ); $threshold_map = array( 'comments_count' => $wpdb->comments, 'options_count' => $wpdb->options, 'posts_count' => $wpdb->posts, 'terms_count' => $wpdb->terms, 'users_count' => $wpdb->users, ); foreach ( $threshold_map as $threshold => $table ) { if ( $thresholds[ $threshold ] <= $results[ $table ]->rows ) { return true; } } return false; } /** * Returns a list of available persistent object cache services. * * @since 6.1.0 * * @return string[] The list of available persistent object cache services. */ private function available_object_cache_services() { $extensions = array_map( 'extension_loaded', array( 'APCu' => 'apcu', 'Redis' => 'redis', 'Relay' => 'relay', 'Memcache' => 'memcache', 'Memcached' => 'memcached', ) ); $services = array_keys( array_filter( $extensions ) ); /** * Filters the persistent object cache services available to the user. * * This can be useful to hide or add services not included in the defaults. * * @since 6.1.0 * * @param string[] $services The list of available persistent object cache services. */ return apply_filters( 'site_status_available_object_cache_services', $services ); } } class-wp-ajax-upgrader-skin.php000064400000010141147206365750012514 0ustar00errors = new WP_Error(); } /** * Retrieves the list of errors. * * @since 4.6.0 * * @return WP_Error Errors during an upgrade. */ public function get_errors() { return $this->errors; } /** * Retrieves a string for error messages. * * @since 4.6.0 * * @return string Error messages during an upgrade. */ public function get_error_messages() { $messages = array(); foreach ( $this->errors->get_error_codes() as $error_code ) { $error_data = $this->errors->get_error_data( $error_code ); if ( $error_data && is_string( $error_data ) ) { $messages[] = $this->errors->get_error_message( $error_code ) . ' ' . esc_html( strip_tags( $error_data ) ); } else { $messages[] = $this->errors->get_error_message( $error_code ); } } return implode( ', ', $messages ); } /** * Stores an error message about the upgrade. * * @since 4.6.0 * @since 5.3.0 Formalized the existing `...$args` parameter by adding it * to the function signature. * * @param string|WP_Error $errors Errors. * @param mixed ...$args Optional text replacements. */ public function error( $errors, ...$args ) { if ( is_string( $errors ) ) { $string = $errors; if ( ! empty( $this->upgrader->strings[ $string ] ) ) { $string = $this->upgrader->strings[ $string ]; } if ( str_contains( $string, '%' ) ) { if ( ! empty( $args ) ) { $string = vsprintf( $string, $args ); } } // Count existing errors to generate a unique error code. $errors_count = count( $this->errors->get_error_codes() ); $this->errors->add( 'unknown_upgrade_error_' . ( $errors_count + 1 ), $string ); } elseif ( is_wp_error( $errors ) ) { foreach ( $errors->get_error_codes() as $error_code ) { $this->errors->add( $error_code, $errors->get_error_message( $error_code ), $errors->get_error_data( $error_code ) ); } } parent::error( $errors, ...$args ); } /** * Stores a message about the upgrade. * * @since 4.6.0 * @since 5.3.0 Formalized the existing `...$args` parameter by adding it * to the function signature. * @since 5.9.0 Renamed `$data` to `$feedback` for PHP 8 named parameter support. * * @param string|array|WP_Error $feedback Message data. * @param mixed ...$args Optional text replacements. */ public function feedback( $feedback, ...$args ) { if ( is_wp_error( $feedback ) ) { foreach ( $feedback->get_error_codes() as $error_code ) { $this->errors->add( $error_code, $feedback->get_error_message( $error_code ), $feedback->get_error_data( $error_code ) ); } } parent::feedback( $feedback, ...$args ); } } class-wp-themes-list-table.php000064400000024150147206365750012350 0ustar00 true, 'screen' => isset( $args['screen'] ) ? $args['screen'] : null, ) ); } /** * @return bool */ public function ajax_user_can() { // Do not check edit_theme_options here. Ajax calls for available themes require switch_themes. return current_user_can( 'switch_themes' ); } /** */ public function prepare_items() { $themes = wp_get_themes( array( 'allowed' => true ) ); if ( ! empty( $_REQUEST['s'] ) ) { $this->search_terms = array_unique( array_filter( array_map( 'trim', explode( ',', strtolower( wp_unslash( $_REQUEST['s'] ) ) ) ) ) ); } if ( ! empty( $_REQUEST['features'] ) ) { $this->features = $_REQUEST['features']; } if ( $this->search_terms || $this->features ) { foreach ( $themes as $key => $theme ) { if ( ! $this->search_theme( $theme ) ) { unset( $themes[ $key ] ); } } } unset( $themes[ get_option( 'stylesheet' ) ] ); WP_Theme::sort_by_name( $themes ); $per_page = 36; $page = $this->get_pagenum(); $start = ( $page - 1 ) * $per_page; $this->items = array_slice( $themes, $start, $per_page, true ); $this->set_pagination_args( array( 'total_items' => count( $themes ), 'per_page' => $per_page, 'infinite_scroll' => true, ) ); } /** */ public function no_items() { if ( $this->search_terms || $this->features ) { _e( 'No items found.' ); return; } $blog_id = get_current_blog_id(); if ( is_multisite() ) { if ( current_user_can( 'install_themes' ) && current_user_can( 'manage_network_themes' ) ) { printf( /* translators: 1: URL to Themes tab on Edit Site screen, 2: URL to Add Themes screen. */ __( 'You only have one theme enabled for this site right now. Visit the Network Admin to enable or install more themes.' ), network_admin_url( 'site-themes.php?id=' . $blog_id ), network_admin_url( 'theme-install.php' ) ); return; } elseif ( current_user_can( 'manage_network_themes' ) ) { printf( /* translators: %s: URL to Themes tab on Edit Site screen. */ __( 'You only have one theme enabled for this site right now. Visit the Network Admin to enable more themes.' ), network_admin_url( 'site-themes.php?id=' . $blog_id ) ); return; } // Else, fallthrough. install_themes doesn't help if you can't enable it. } else { if ( current_user_can( 'install_themes' ) ) { printf( /* translators: %s: URL to Add Themes screen. */ __( 'You only have one theme installed right now. Live a little! You can choose from over 1,000 free themes in the WordPress Theme Directory at any time: just click on the Install Themes tab above.' ), admin_url( 'theme-install.php' ) ); return; } } // Fallthrough. printf( /* translators: %s: Network title. */ __( 'Only the active theme is available to you. Contact the %s administrator for information about accessing additional themes.' ), get_site_option( 'site_name' ) ); } /** * @param string $which */ public function tablenav( $which = 'top' ) { if ( $this->get_pagination_arg( 'total_pages' ) <= 1 ) { return; } ?>
    pagination( $which ); ?>
    tablenav( 'top' ); ?>
    display_rows_or_placeholder(); ?>
    tablenav( 'bottom' ); ?> has_items() ) { $this->display_rows(); } else { echo '
    '; $this->no_items(); echo '
    '; } } /** * Generates the list table rows. * * @since 3.1.0 */ public function display_rows() { $themes = $this->items; foreach ( $themes as $theme ) : ?>
    get_template(); $stylesheet = $theme->get_stylesheet(); $title = $theme->display( 'Name' ); $version = $theme->display( 'Version' ); $author = $theme->display( 'Author' ); $activate_link = wp_nonce_url( 'themes.php?action=activate&template=' . urlencode( $template ) . '&stylesheet=' . urlencode( $stylesheet ), 'switch-theme_' . $stylesheet ); $actions = array(); $actions['activate'] = sprintf( '%s', $activate_link, /* translators: %s: Theme name. */ esc_attr( sprintf( _x( 'Activate “%s”', 'theme' ), $title ) ), _x( 'Activate', 'theme' ) ); if ( current_user_can( 'edit_theme_options' ) && current_user_can( 'customize' ) ) { $actions['preview'] .= sprintf( '%s', wp_customize_url( $stylesheet ), __( 'Live Preview' ) ); } if ( ! is_multisite() && current_user_can( 'delete_themes' ) ) { $actions['delete'] = sprintf( '%s', wp_nonce_url( 'themes.php?action=delete&stylesheet=' . urlencode( $stylesheet ), 'delete-theme_' . $stylesheet ), /* translators: %s: Theme name. */ esc_js( sprintf( __( "You are about to delete this theme '%s'\n 'Cancel' to stop, 'OK' to delete." ), $title ) ), __( 'Delete' ) ); } /** This filter is documented in wp-admin/includes/class-wp-ms-themes-list-table.php */ $actions = apply_filters( 'theme_action_links', $actions, $theme, 'all' ); /** This filter is documented in wp-admin/includes/class-wp-ms-themes-list-table.php */ $actions = apply_filters( "theme_action_links_{$stylesheet}", $actions, $theme, 'all' ); $delete_action = isset( $actions['delete'] ) ? '
    ' . $actions['delete'] . '
    ' : ''; unset( $actions['delete'] ); $screenshot = $theme->get_screenshot(); ?>

    display( 'Description' ); ?>

    parent() ) { printf( /* translators: 1: Link to documentation on child themes, 2: Name of parent theme. */ '

    ' . __( 'This child theme requires its parent theme, %2$s.' ) . '

    ', __( 'https://developer.wordpress.org/themes/advanced-topics/child-themes/' ), $theme->parent()->display( 'Name' ) ); } ?>
    features as $word ) { if ( ! in_array( $word, $theme->get( 'Tags' ), true ) ) { return false; } } // Match all phrases. foreach ( $this->search_terms as $word ) { if ( in_array( $word, $theme->get( 'Tags' ), true ) ) { continue; } foreach ( array( 'Name', 'Description', 'Author', 'AuthorURI' ) as $header ) { // Don't mark up; Do translate. if ( false !== stripos( strip_tags( $theme->display( $header, false, true ) ), $word ) ) { continue 2; } } if ( false !== stripos( $theme->get_stylesheet(), $word ) ) { continue; } if ( false !== stripos( $theme->get_template(), $word ) ) { continue; } return false; } return true; } /** * Send required variables to JavaScript land * * @since 3.4.0 * * @param array $extra_args */ public function _js_vars( $extra_args = array() ) { $search_string = isset( $_REQUEST['s'] ) ? esc_attr( wp_unslash( $_REQUEST['s'] ) ) : ''; $args = array( 'search' => $search_string, 'features' => $this->features, 'paged' => $this->get_pagenum(), 'total_pages' => ! empty( $this->_pagination_args['total_pages'] ) ? $this->_pagination_args['total_pages'] : 1, ); if ( is_array( $extra_args ) ) { $args = array_merge( $args, $extra_args ); } printf( "\n", wp_json_encode( $args ) ); parent::_js_vars(); } } class-wp-filesystem-base.php000064400000057532147206365750012133 0ustar00find_folder( ABSPATH ); /* * Perhaps the FTP folder is rooted at the WordPress install. * Check for wp-includes folder in root. Could have some false positives, but rare. */ if ( ! $folder && $this->is_dir( '/' . WPINC ) ) { $folder = '/'; } return $folder; } /** * Returns the path on the remote filesystem of WP_CONTENT_DIR. * * @since 2.7.0 * * @return string The location of the remote path. */ public function wp_content_dir() { return $this->find_folder( WP_CONTENT_DIR ); } /** * Returns the path on the remote filesystem of WP_PLUGIN_DIR. * * @since 2.7.0 * * @return string The location of the remote path. */ public function wp_plugins_dir() { return $this->find_folder( WP_PLUGIN_DIR ); } /** * Returns the path on the remote filesystem of the Themes Directory. * * @since 2.7.0 * * @param string|false $theme Optional. The theme stylesheet or template for the directory. * Default false. * @return string The location of the remote path. */ public function wp_themes_dir( $theme = false ) { $theme_root = get_theme_root( $theme ); // Account for relative theme roots. if ( '/themes' === $theme_root || ! is_dir( $theme_root ) ) { $theme_root = WP_CONTENT_DIR . $theme_root; } return $this->find_folder( $theme_root ); } /** * Returns the path on the remote filesystem of WP_LANG_DIR. * * @since 3.2.0 * * @return string The location of the remote path. */ public function wp_lang_dir() { return $this->find_folder( WP_LANG_DIR ); } /** * Locates a folder on the remote filesystem. * * @since 2.5.0 * @deprecated 2.7.0 use WP_Filesystem_Base::abspath() or WP_Filesystem_Base::wp_*_dir() instead. * @see WP_Filesystem_Base::abspath() * @see WP_Filesystem_Base::wp_content_dir() * @see WP_Filesystem_Base::wp_plugins_dir() * @see WP_Filesystem_Base::wp_themes_dir() * @see WP_Filesystem_Base::wp_lang_dir() * * @param string $base Optional. The folder to start searching from. Default '.'. * @param bool $verbose Optional. True to display debug information. Default false. * @return string The location of the remote path. */ public function find_base_dir( $base = '.', $verbose = false ) { _deprecated_function( __FUNCTION__, '2.7.0', 'WP_Filesystem_Base::abspath() or WP_Filesystem_Base::wp_*_dir()' ); $this->verbose = $verbose; return $this->abspath(); } /** * Locates a folder on the remote filesystem. * * @since 2.5.0 * @deprecated 2.7.0 use WP_Filesystem_Base::abspath() or WP_Filesystem_Base::wp_*_dir() methods instead. * @see WP_Filesystem_Base::abspath() * @see WP_Filesystem_Base::wp_content_dir() * @see WP_Filesystem_Base::wp_plugins_dir() * @see WP_Filesystem_Base::wp_themes_dir() * @see WP_Filesystem_Base::wp_lang_dir() * * @param string $base Optional. The folder to start searching from. Default '.'. * @param bool $verbose Optional. True to display debug information. Default false. * @return string The location of the remote path. */ public function get_base_dir( $base = '.', $verbose = false ) { _deprecated_function( __FUNCTION__, '2.7.0', 'WP_Filesystem_Base::abspath() or WP_Filesystem_Base::wp_*_dir()' ); $this->verbose = $verbose; return $this->abspath(); } /** * Locates a folder on the remote filesystem. * * Assumes that on Windows systems, Stripping off the Drive * letter is OK Sanitizes \\ to / in Windows filepaths. * * @since 2.7.0 * * @param string $folder the folder to locate. * @return string|false The location of the remote path, false on failure. */ public function find_folder( $folder ) { if ( isset( $this->cache[ $folder ] ) ) { return $this->cache[ $folder ]; } if ( stripos( $this->method, 'ftp' ) !== false ) { $constant_overrides = array( 'FTP_BASE' => ABSPATH, 'FTP_CONTENT_DIR' => WP_CONTENT_DIR, 'FTP_PLUGIN_DIR' => WP_PLUGIN_DIR, 'FTP_LANG_DIR' => WP_LANG_DIR, ); // Direct matches ( folder = CONSTANT/ ). foreach ( $constant_overrides as $constant => $dir ) { if ( ! defined( $constant ) ) { continue; } if ( $folder === $dir ) { return trailingslashit( constant( $constant ) ); } } // Prefix matches ( folder = CONSTANT/subdir ), foreach ( $constant_overrides as $constant => $dir ) { if ( ! defined( $constant ) ) { continue; } if ( 0 === stripos( $folder, $dir ) ) { // $folder starts with $dir. $potential_folder = preg_replace( '#^' . preg_quote( $dir, '#' ) . '/#i', trailingslashit( constant( $constant ) ), $folder ); $potential_folder = trailingslashit( $potential_folder ); if ( $this->is_dir( $potential_folder ) ) { $this->cache[ $folder ] = $potential_folder; return $potential_folder; } } } } elseif ( 'direct' === $this->method ) { $folder = str_replace( '\\', '/', $folder ); // Windows path sanitization. return trailingslashit( $folder ); } $folder = preg_replace( '|^([a-z]{1}):|i', '', $folder ); // Strip out Windows drive letter if it's there. $folder = str_replace( '\\', '/', $folder ); // Windows path sanitization. if ( isset( $this->cache[ $folder ] ) ) { return $this->cache[ $folder ]; } if ( $this->exists( $folder ) ) { // Folder exists at that absolute path. $folder = trailingslashit( $folder ); $this->cache[ $folder ] = $folder; return $folder; } $return = $this->search_for_folder( $folder ); if ( $return ) { $this->cache[ $folder ] = $return; } return $return; } /** * Locates a folder on the remote filesystem. * * Expects Windows sanitized path. * * @since 2.7.0 * * @param string $folder The folder to locate. * @param string $base The folder to start searching from. * @param bool $loop If the function has recursed. Internal use only. * @return string|false The location of the remote path, false to cease looping. */ public function search_for_folder( $folder, $base = '.', $loop = false ) { if ( empty( $base ) || '.' === $base ) { $base = trailingslashit( $this->cwd() ); } $folder = untrailingslashit( $folder ); if ( $this->verbose ) { /* translators: 1: Folder to locate, 2: Folder to start searching from. */ printf( "\n" . __( 'Looking for %1$s in %2$s' ) . "
    \n", $folder, $base ); } $folder_parts = explode( '/', $folder ); $folder_part_keys = array_keys( $folder_parts ); $last_index = array_pop( $folder_part_keys ); $last_path = $folder_parts[ $last_index ]; $files = $this->dirlist( $base ); foreach ( $folder_parts as $index => $key ) { if ( $index === $last_index ) { continue; // We want this to be caught by the next code block. } /* * Working from /home/ to /user/ to /wordpress/ see if that file exists within * the current folder, If it's found, change into it and follow through looking * for it. If it can't find WordPress down that route, it'll continue onto the next * folder level, and see if that matches, and so on. If it reaches the end, and still * can't find it, it'll return false for the entire function. */ if ( isset( $files[ $key ] ) ) { // Let's try that folder: $newdir = trailingslashit( path_join( $base, $key ) ); if ( $this->verbose ) { /* translators: %s: Directory name. */ printf( "\n" . __( 'Changing to %s' ) . "
    \n", $newdir ); } // Only search for the remaining path tokens in the directory, not the full path again. $newfolder = implode( '/', array_slice( $folder_parts, $index + 1 ) ); $ret = $this->search_for_folder( $newfolder, $newdir, $loop ); if ( $ret ) { return $ret; } } } /* * Only check this as a last resort, to prevent locating the incorrect install. * All above procedures will fail quickly if this is the right branch to take. */ if ( isset( $files[ $last_path ] ) ) { if ( $this->verbose ) { /* translators: %s: Directory name. */ printf( "\n" . __( 'Found %s' ) . "
    \n", $base . $last_path ); } return trailingslashit( $base . $last_path ); } /* * Prevent this function from looping again. * No need to proceed if we've just searched in `/`. */ if ( $loop || '/' === $base ) { return false; } /* * As an extra last resort, Change back to / if the folder wasn't found. * This comes into effect when the CWD is /home/user/ but WP is at /var/www/.... */ return $this->search_for_folder( $folder, '/', true ); } /** * Returns the *nix-style file permissions for a file. * * From the PHP documentation page for fileperms(). * * @link https://www.php.net/manual/en/function.fileperms.php * * @since 2.5.0 * * @param string $file String filename. * @return string The *nix-style representation of permissions. */ public function gethchmod( $file ) { $perms = intval( $this->getchmod( $file ), 8 ); if ( ( $perms & 0xC000 ) === 0xC000 ) { // Socket. $info = 's'; } elseif ( ( $perms & 0xA000 ) === 0xA000 ) { // Symbolic Link. $info = 'l'; } elseif ( ( $perms & 0x8000 ) === 0x8000 ) { // Regular. $info = '-'; } elseif ( ( $perms & 0x6000 ) === 0x6000 ) { // Block special. $info = 'b'; } elseif ( ( $perms & 0x4000 ) === 0x4000 ) { // Directory. $info = 'd'; } elseif ( ( $perms & 0x2000 ) === 0x2000 ) { // Character special. $info = 'c'; } elseif ( ( $perms & 0x1000 ) === 0x1000 ) { // FIFO pipe. $info = 'p'; } else { // Unknown. $info = 'u'; } // Owner. $info .= ( ( $perms & 0x0100 ) ? 'r' : '-' ); $info .= ( ( $perms & 0x0080 ) ? 'w' : '-' ); $info .= ( ( $perms & 0x0040 ) ? ( ( $perms & 0x0800 ) ? 's' : 'x' ) : ( ( $perms & 0x0800 ) ? 'S' : '-' ) ); // Group. $info .= ( ( $perms & 0x0020 ) ? 'r' : '-' ); $info .= ( ( $perms & 0x0010 ) ? 'w' : '-' ); $info .= ( ( $perms & 0x0008 ) ? ( ( $perms & 0x0400 ) ? 's' : 'x' ) : ( ( $perms & 0x0400 ) ? 'S' : '-' ) ); // World. $info .= ( ( $perms & 0x0004 ) ? 'r' : '-' ); $info .= ( ( $perms & 0x0002 ) ? 'w' : '-' ); $info .= ( ( $perms & 0x0001 ) ? ( ( $perms & 0x0200 ) ? 't' : 'x' ) : ( ( $perms & 0x0200 ) ? 'T' : '-' ) ); return $info; } /** * Gets the permissions of the specified file or filepath in their octal format. * * @since 2.5.0 * * @param string $file Path to the file. * @return string Mode of the file (the last 3 digits). */ public function getchmod( $file ) { return '777'; } /** * Converts *nix-style file permissions to an octal number. * * Converts '-rw-r--r--' to 0644 * From "info at rvgate dot nl"'s comment on the PHP documentation for chmod() * * @link https://www.php.net/manual/en/function.chmod.php#49614 * * @since 2.5.0 * * @param string $mode string The *nix-style file permissions. * @return string Octal representation of permissions. */ public function getnumchmodfromh( $mode ) { $realmode = ''; $legal = array( '', 'w', 'r', 'x', '-' ); $attarray = preg_split( '//', $mode ); for ( $i = 0, $c = count( $attarray ); $i < $c; $i++ ) { $key = array_search( $attarray[ $i ], $legal, true ); if ( $key ) { $realmode .= $legal[ $key ]; } } $mode = str_pad( $realmode, 10, '-', STR_PAD_LEFT ); $trans = array( '-' => '0', 'r' => '4', 'w' => '2', 'x' => '1', ); $mode = strtr( $mode, $trans ); $newmode = $mode[0]; $newmode .= $mode[1] + $mode[2] + $mode[3]; $newmode .= $mode[4] + $mode[5] + $mode[6]; $newmode .= $mode[7] + $mode[8] + $mode[9]; return $newmode; } /** * Determines if the string provided contains binary characters. * * @since 2.7.0 * * @param string $text String to test against. * @return bool True if string is binary, false otherwise. */ public function is_binary( $text ) { return (bool) preg_match( '|[^\x20-\x7E]|', $text ); // chr(32)..chr(127) } /** * Changes the owner of a file or directory. * * Default behavior is to do nothing, override this in your subclass, if desired. * * @since 2.5.0 * * @param string $file Path to the file or directory. * @param string|int $owner A user name or number. * @param bool $recursive Optional. If set to true, changes file owner recursively. * Default false. * @return bool True on success, false on failure. */ public function chown( $file, $owner, $recursive = false ) { return false; } /** * Connects filesystem. * * @since 2.5.0 * @abstract * * @return bool True on success, false on failure (always true for WP_Filesystem_Direct). */ public function connect() { return true; } /** * Reads entire file into a string. * * @since 2.5.0 * @abstract * * @param string $file Name of the file to read. * @return string|false Read data on success, false on failure. */ public function get_contents( $file ) { return false; } /** * Reads entire file into an array. * * @since 2.5.0 * @abstract * * @param string $file Path to the file. * @return array|false File contents in an array on success, false on failure. */ public function get_contents_array( $file ) { return false; } /** * Writes a string to a file. * * @since 2.5.0 * @abstract * * @param string $file Remote path to the file where to write the data. * @param string $contents The data to write. * @param int|false $mode Optional. The file permissions as octal number, usually 0644. * Default false. * @return bool True on success, false on failure. */ public function put_contents( $file, $contents, $mode = false ) { return false; } /** * Gets the current working directory. * * @since 2.5.0 * @abstract * * @return string|false The current working directory on success, false on failure. */ public function cwd() { return false; } /** * Changes current directory. * * @since 2.5.0 * @abstract * * @param string $dir The new current directory. * @return bool True on success, false on failure. */ public function chdir( $dir ) { return false; } /** * Changes the file group. * * @since 2.5.0 * @abstract * * @param string $file Path to the file. * @param string|int $group A group name or number. * @param bool $recursive Optional. If set to true, changes file group recursively. * Default false. * @return bool True on success, false on failure. */ public function chgrp( $file, $group, $recursive = false ) { return false; } /** * Changes filesystem permissions. * * @since 2.5.0 * @abstract * * @param string $file Path to the file. * @param int|false $mode Optional. The permissions as octal number, usually 0644 for files, * 0755 for directories. Default false. * @param bool $recursive Optional. If set to true, changes file permissions recursively. * Default false. * @return bool True on success, false on failure. */ public function chmod( $file, $mode = false, $recursive = false ) { return false; } /** * Gets the file owner. * * @since 2.5.0 * @abstract * * @param string $file Path to the file. * @return string|false Username of the owner on success, false on failure. */ public function owner( $file ) { return false; } /** * Gets the file's group. * * @since 2.5.0 * @abstract * * @param string $file Path to the file. * @return string|false The group on success, false on failure. */ public function group( $file ) { return false; } /** * Copies a file. * * @since 2.5.0 * @abstract * * @param string $source Path to the source file. * @param string $destination Path to the destination file. * @param bool $overwrite Optional. Whether to overwrite the destination file if it exists. * Default false. * @param int|false $mode Optional. The permissions as octal number, usually 0644 for files, * 0755 for dirs. Default false. * @return bool True on success, false on failure. */ public function copy( $source, $destination, $overwrite = false, $mode = false ) { return false; } /** * Moves a file. * * @since 2.5.0 * @abstract * * @param string $source Path to the source file. * @param string $destination Path to the destination file. * @param bool $overwrite Optional. Whether to overwrite the destination file if it exists. * Default false. * @return bool True on success, false on failure. */ public function move( $source, $destination, $overwrite = false ) { return false; } /** * Deletes a file or directory. * * @since 2.5.0 * @abstract * * @param string $file Path to the file or directory. * @param bool $recursive Optional. If set to true, deletes files and folders recursively. * Default false. * @param string|false $type Type of resource. 'f' for file, 'd' for directory. * Default false. * @return bool True on success, false on failure. */ public function delete( $file, $recursive = false, $type = false ) { return false; } /** * Checks if a file or directory exists. * * @since 2.5.0 * @abstract * * @param string $path Path to file or directory. * @return bool Whether $path exists or not. */ public function exists( $path ) { return false; } /** * Checks if resource is a file. * * @since 2.5.0 * @abstract * * @param string $file File path. * @return bool Whether $file is a file. */ public function is_file( $file ) { return false; } /** * Checks if resource is a directory. * * @since 2.5.0 * @abstract * * @param string $path Directory path. * @return bool Whether $path is a directory. */ public function is_dir( $path ) { return false; } /** * Checks if a file is readable. * * @since 2.5.0 * @abstract * * @param string $file Path to file. * @return bool Whether $file is readable. */ public function is_readable( $file ) { return false; } /** * Checks if a file or directory is writable. * * @since 2.5.0 * @abstract * * @param string $path Path to file or directory. * @return bool Whether $path is writable. */ public function is_writable( $path ) { return false; } /** * Gets the file's last access time. * * @since 2.5.0 * @abstract * * @param string $file Path to file. * @return int|false Unix timestamp representing last access time, false on failure. */ public function atime( $file ) { return false; } /** * Gets the file modification time. * * @since 2.5.0 * @abstract * * @param string $file Path to file. * @return int|false Unix timestamp representing modification time, false on failure. */ public function mtime( $file ) { return false; } /** * Gets the file size (in bytes). * * @since 2.5.0 * @abstract * * @param string $file Path to file. * @return int|false Size of the file in bytes on success, false on failure. */ public function size( $file ) { return false; } /** * Sets the access and modification times of a file. * * Note: If $file doesn't exist, it will be created. * * @since 2.5.0 * @abstract * * @param string $file Path to file. * @param int $time Optional. Modified time to set for file. * Default 0. * @param int $atime Optional. Access time to set for file. * Default 0. * @return bool True on success, false on failure. */ public function touch( $file, $time = 0, $atime = 0 ) { return false; } /** * Creates a directory. * * @since 2.5.0 * @abstract * * @param string $path Path for new directory. * @param int|false $chmod Optional. The permissions as octal number (or false to skip chmod). * Default false. * @param string|int|false $chown Optional. A user name or number (or false to skip chown). * Default false. * @param string|int|false $chgrp Optional. A group name or number (or false to skip chgrp). * Default false. * @return bool True on success, false on failure. */ public function mkdir( $path, $chmod = false, $chown = false, $chgrp = false ) { return false; } /** * Deletes a directory. * * @since 2.5.0 * @abstract * * @param string $path Path to directory. * @param bool $recursive Optional. Whether to recursively remove files/directories. * Default false. * @return bool True on success, false on failure. */ public function rmdir( $path, $recursive = false ) { return false; } /** * Gets details for files in a directory or a specific file. * * @since 2.5.0 * @abstract * * @param string $path Path to directory or file. * @param bool $include_hidden Optional. Whether to include details of hidden ("." prefixed) files. * Default true. * @param bool $recursive Optional. Whether to recursively include file details in nested directories. * Default false. * @return array|false { * Array of arrays containing file information. False if unable to list directory contents. * * @type array ...$0 { * Array of file information. Note that some elements may not be available on all filesystems. * * @type string $name Name of the file or directory. * @type string $perms *nix representation of permissions. * @type string $permsn Octal representation of permissions. * @type int|string|false $number File number. May be a numeric string. False if not available. * @type string|false $owner Owner name or ID, or false if not available. * @type string|false $group File permissions group, or false if not available. * @type int|string|false $size Size of file in bytes. May be a numeric string. * False if not available. * @type int|string|false $lastmodunix Last modified unix timestamp. May be a numeric string. * False if not available. * @type string|false $lastmod Last modified month (3 letters) and day (without leading 0), or * false if not available. * @type string|false $time Last modified time, or false if not available. * @type string $type Type of resource. 'f' for file, 'd' for directory, 'l' for link. * @type array|false $files If a directory and `$recursive` is true, contains another array of * files. False if unable to list directory contents. * } * } */ public function dirlist( $path, $include_hidden = true, $recursive = false ) { return false; } } template.php000064400000300502147206365750007107 0ustar00 'category', 'descendants_and_self' => $descendants_and_self, 'selected_cats' => $selected_cats, 'popular_cats' => $popular_cats, 'walker' => $walker, 'checked_ontop' => $checked_ontop, ) ); } /** * Outputs an unordered list of checkbox input elements labelled with term names. * * Taxonomy-independent version of wp_category_checklist(). * * @since 3.0.0 * @since 4.4.0 Introduced the `$echo` argument. * * @param int $post_id Optional. Post ID. Default 0. * @param array|string $args { * Optional. Array or string of arguments for generating a terms checklist. Default empty array. * * @type int $descendants_and_self ID of the category to output along with its descendants. * Default 0. * @type int[] $selected_cats Array of category IDs to mark as checked. Default false. * @type int[] $popular_cats Array of category IDs to receive the "popular-category" class. * Default false. * @type Walker $walker Walker object to use to build the output. Default empty which * results in a Walker_Category_Checklist instance being used. * @type string $taxonomy Taxonomy to generate the checklist for. Default 'category'. * @type bool $checked_ontop Whether to move checked items out of the hierarchy and to * the top of the list. Default true. * @type bool $echo Whether to echo the generated markup. False to return the markup instead * of echoing it. Default true. * } * @return string HTML list of input elements. */ function wp_terms_checklist( $post_id = 0, $args = array() ) { $defaults = array( 'descendants_and_self' => 0, 'selected_cats' => false, 'popular_cats' => false, 'walker' => null, 'taxonomy' => 'category', 'checked_ontop' => true, 'echo' => true, ); /** * Filters the taxonomy terms checklist arguments. * * @since 3.4.0 * * @see wp_terms_checklist() * * @param array|string $args An array or string of arguments. * @param int $post_id The post ID. */ $params = apply_filters( 'wp_terms_checklist_args', $args, $post_id ); $parsed_args = wp_parse_args( $params, $defaults ); if ( empty( $parsed_args['walker'] ) || ! ( $parsed_args['walker'] instanceof Walker ) ) { $walker = new Walker_Category_Checklist(); } else { $walker = $parsed_args['walker']; } $taxonomy = $parsed_args['taxonomy']; $descendants_and_self = (int) $parsed_args['descendants_and_self']; $args = array( 'taxonomy' => $taxonomy ); $tax = get_taxonomy( $taxonomy ); $args['disabled'] = ! current_user_can( $tax->cap->assign_terms ); $args['list_only'] = ! empty( $parsed_args['list_only'] ); if ( is_array( $parsed_args['selected_cats'] ) ) { $args['selected_cats'] = array_map( 'intval', $parsed_args['selected_cats'] ); } elseif ( $post_id ) { $args['selected_cats'] = wp_get_object_terms( $post_id, $taxonomy, array_merge( $args, array( 'fields' => 'ids' ) ) ); } else { $args['selected_cats'] = array(); } if ( is_array( $parsed_args['popular_cats'] ) ) { $args['popular_cats'] = array_map( 'intval', $parsed_args['popular_cats'] ); } else { $args['popular_cats'] = get_terms( array( 'taxonomy' => $taxonomy, 'fields' => 'ids', 'orderby' => 'count', 'order' => 'DESC', 'number' => 10, 'hierarchical' => false, ) ); } if ( $descendants_and_self ) { $categories = (array) get_terms( array( 'taxonomy' => $taxonomy, 'child_of' => $descendants_and_self, 'hierarchical' => 0, 'hide_empty' => 0, ) ); $self = get_term( $descendants_and_self, $taxonomy ); array_unshift( $categories, $self ); } else { $categories = (array) get_terms( array( 'taxonomy' => $taxonomy, 'get' => 'all', ) ); } $output = ''; if ( $parsed_args['checked_ontop'] ) { /* * Post-process $categories rather than adding an exclude to the get_terms() query * to keep the query the same across all posts (for any query cache). */ $checked_categories = array(); $keys = array_keys( $categories ); foreach ( $keys as $k ) { if ( in_array( $categories[ $k ]->term_id, $args['selected_cats'], true ) ) { $checked_categories[] = $categories[ $k ]; unset( $categories[ $k ] ); } } // Put checked categories on top. $output .= $walker->walk( $checked_categories, 0, $args ); } // Then the rest of them. $output .= $walker->walk( $categories, 0, $args ); if ( $parsed_args['echo'] ) { echo $output; } return $output; } /** * Retrieves a list of the most popular terms from the specified taxonomy. * * If the `$display` argument is true then the elements for a list of checkbox * `` elements labelled with the names of the selected terms is output. * If the `$post_ID` global is not empty then the terms associated with that * post will be marked as checked. * * @since 2.5.0 * * @param string $taxonomy Taxonomy to retrieve terms from. * @param int $default_term Optional. Not used. * @param int $number Optional. Number of terms to retrieve. Default 10. * @param bool $display Optional. Whether to display the list as well. Default true. * @return int[] Array of popular term IDs. */ function wp_popular_terms_checklist( $taxonomy, $default_term = 0, $number = 10, $display = true ) { $post = get_post(); if ( $post && $post->ID ) { $checked_terms = wp_get_object_terms( $post->ID, $taxonomy, array( 'fields' => 'ids' ) ); } else { $checked_terms = array(); } $terms = get_terms( array( 'taxonomy' => $taxonomy, 'orderby' => 'count', 'order' => 'DESC', 'number' => $number, 'hierarchical' => false, ) ); $tax = get_taxonomy( $taxonomy ); $popular_ids = array(); foreach ( (array) $terms as $term ) { $popular_ids[] = $term->term_id; if ( ! $display ) { // Hack for Ajax use. continue; } $id = "popular-$taxonomy-$term->term_id"; $checked = in_array( $term->term_id, $checked_terms, true ) ? 'checked="checked"' : ''; ?> 'link_category', 'orderby' => 'name', 'hide_empty' => 0, ) ); if ( empty( $categories ) ) { return; } foreach ( $categories as $category ) { $cat_id = $category->term_id; /** This filter is documented in wp-includes/category-template.php */ $name = esc_html( apply_filters( 'the_category', $category->name, '', '' ) ); $checked = in_array( $cat_id, $checked_categories, true ) ? ' checked="checked"' : ''; echo ''; } } /** * Adds hidden fields with the data for use in the inline editor for posts and pages. * * @since 2.7.0 * * @param WP_Post $post Post object. */ function get_inline_data( $post ) { $post_type_object = get_post_type_object( $post->post_type ); if ( ! current_user_can( 'edit_post', $post->ID ) ) { return; } $title = esc_textarea( trim( $post->post_title ) ); echo ' '; } /** * Outputs the in-line comment reply-to form in the Comments list table. * * @since 2.7.0 * * @global WP_List_Table $wp_list_table * * @param int $position Optional. The value of the 'position' input field. Default 1. * @param bool $checkbox Optional. The value of the 'checkbox' input field. Default false. * @param string $mode Optional. If set to 'single', will use WP_Post_Comments_List_Table, * otherwise WP_Comments_List_Table. Default 'single'. * @param bool $table_row Optional. Whether to use a table instead of a div element. Default true. */ function wp_comment_reply( $position = 1, $checkbox = false, $mode = 'single', $table_row = true ) { global $wp_list_table; /** * Filters the in-line comment reply-to form output in the Comments * list table. * * Returning a non-empty value here will short-circuit display * of the in-line comment-reply form in the Comments list table, * echoing the returned value instead. * * @since 2.7.0 * * @see wp_comment_reply() * * @param string $content The reply-to form content. * @param array $args An array of default args. */ $content = apply_filters( 'wp_comment_reply', '', array( 'position' => $position, 'checkbox' => $checkbox, 'mode' => $mode, ) ); if ( ! empty( $content ) ) { echo $content; return; } if ( ! $wp_list_table ) { if ( 'single' === $mode ) { $wp_list_table = _get_list_table( 'WP_Post_Comments_List_Table' ); } else { $wp_list_table = _get_list_table( 'WP_Comments_List_Table' ); } } ?>

    ' . _x( 'Name', 'meta name' ) . ' ' . __( 'Value' ) . ' '; // TBODY needed for list-manipulation JS. return; } $count = 0; ?>
    . $entry['meta_id'] = (int) $entry['meta_id']; $delete_nonce = wp_create_nonce( 'delete-meta_' . $entry['meta_id'] ); $r .= "\n\t"; $r .= "\n\t\t"; $r .= "\n\t\t
    "; $r .= get_submit_button( __( 'Delete' ), 'deletemeta small', "deletemeta[{$entry['meta_id']}]", false, array( 'data-wp-lists' => "delete:the-list:meta-{$entry['meta_id']}::_ajax_nonce=$delete_nonce" ) ); $r .= "\n\t\t"; $r .= get_submit_button( __( 'Update' ), 'updatemeta small', "meta-{$entry['meta_id']}-submit", false, array( 'data-wp-lists' => "add:the-list:meta-{$entry['meta_id']}::_ajax_nonce-add-meta=$update_nonce" ) ); $r .= '
    '; $r .= wp_nonce_field( 'change-meta', '_ajax_nonce', false, false ); $r .= ''; $r .= "\n\t\t\n\t"; return $r; } /** * Prints the form in the Custom Fields meta box. * * @since 1.2.0 * * @global wpdb $wpdb WordPress database abstraction object. * * @param WP_Post $post Optional. The post being edited. */ function meta_form( $post = null ) { global $wpdb; $post = get_post( $post ); /** * Filters values for the meta key dropdown in the Custom Fields meta box. * * Returning a non-null value will effectively short-circuit and avoid a * potentially expensive query against postmeta. * * @since 4.4.0 * * @param array|null $keys Pre-defined meta keys to be used in place of a postmeta query. Default null. * @param WP_Post $post The current post object. */ $keys = apply_filters( 'postmeta_form_keys', null, $post ); if ( null === $keys ) { /** * Filters the number of custom fields to retrieve for the drop-down * in the Custom Fields meta box. * * @since 2.1.0 * * @param int $limit Number of custom fields to retrieve. Default 30. */ $limit = apply_filters( 'postmeta_form_limit', 30 ); $keys = $wpdb->get_col( $wpdb->prepare( "SELECT DISTINCT meta_key FROM $wpdb->postmeta WHERE meta_key NOT BETWEEN '_' AND '_z' HAVING meta_key NOT LIKE %s ORDER BY meta_key LIMIT %d", $wpdb->esc_like( '_' ) . '%', $limit ) ); } if ( $keys ) { natcasesort( $keys ); } ?>

    'newmeta-submit', 'data-wp-lists' => 'add:the-list:newmeta', ) ); ?>
    post_status, array( 'draft', 'pending' ), true ) && ( ! $post->post_date_gmt || '0000-00-00 00:00:00' === $post->post_date_gmt ) ); } $tab_index_attribute = ''; if ( (int) $tab_index > 0 ) { $tab_index_attribute = " tabindex=\"$tab_index\""; } // @todo Remove this? // echo '
    '; $post_date = ( $for_post ) ? $post->post_date : get_comment()->comment_date; $jj = ( $edit ) ? mysql2date( 'd', $post_date, false ) : current_time( 'd' ); $mm = ( $edit ) ? mysql2date( 'm', $post_date, false ) : current_time( 'm' ); $aa = ( $edit ) ? mysql2date( 'Y', $post_date, false ) : current_time( 'Y' ); $hh = ( $edit ) ? mysql2date( 'H', $post_date, false ) : current_time( 'H' ); $mn = ( $edit ) ? mysql2date( 'i', $post_date, false ) : current_time( 'i' ); $ss = ( $edit ) ? mysql2date( 's', $post_date, false ) : current_time( 's' ); $cur_jj = current_time( 'd' ); $cur_mm = current_time( 'm' ); $cur_aa = current_time( 'Y' ); $cur_hh = current_time( 'H' ); $cur_mn = current_time( 'i' ); $month = ''; $day = ''; $year = ''; $hour = ''; $minute = ''; echo '
    '; /* translators: 1: Month, 2: Day, 3: Year, 4: Hour, 5: Minute. */ printf( __( '%1$s %2$s, %3$s at %4$s:%5$s' ), $month, $day, $year, $hour, $minute ); echo '
    '; if ( $multi ) { return; } echo "\n\n"; $map = array( 'mm' => array( $mm, $cur_mm ), 'jj' => array( $jj, $cur_jj ), 'aa' => array( $aa, $cur_aa ), 'hh' => array( $hh, $cur_hh ), 'mn' => array( $mn, $cur_mn ), ); foreach ( $map as $timeunit => $value ) { list( $unit, $curr ) = $value; echo '' . "\n"; $cur_timeunit = 'cur_' . $timeunit; echo '' . "\n"; } ?>

    " . esc_html( $template ) . ''; } } /** * Prints out option HTML elements for the page parents drop-down. * * @since 1.5.0 * @since 4.4.0 `$post` argument was added. * * @global wpdb $wpdb WordPress database abstraction object. * * @param int $default_page Optional. The default page ID to be pre-selected. Default 0. * @param int $parent_page Optional. The parent page ID. Default 0. * @param int $level Optional. Page depth level. Default 0. * @param int|WP_Post $post Post ID or WP_Post object. * @return void|false Void on success, false if the page has no children. */ function parent_dropdown( $default_page = 0, $parent_page = 0, $level = 0, $post = null ) { global $wpdb; $post = get_post( $post ); $items = $wpdb->get_results( $wpdb->prepare( "SELECT ID, post_parent, post_title FROM $wpdb->posts WHERE post_parent = %d AND post_type = 'page' ORDER BY menu_order", $parent_page ) ); if ( $items ) { foreach ( $items as $item ) { // A page cannot be its own parent. if ( $post && $post->ID && (int) $item->ID === $post->ID ) { continue; } $pad = str_repeat( ' ', $level * 3 ); $selected = selected( $default_page, $item->ID, false ); echo "\n\t'; parent_dropdown( $default_page, $item->ID, $level + 1 ); } } else { return false; } } /** * Prints out option HTML elements for role selectors. * * @since 2.1.0 * * @param string $selected Slug for the role that should be already selected. */ function wp_dropdown_roles( $selected = '' ) { $r = ''; $editable_roles = array_reverse( get_editable_roles() ); foreach ( $editable_roles as $role => $details ) { $name = translate_user_role( $details['name'] ); // Preselect specified role. if ( $selected === $role ) { $r .= "\n\t"; } else { $r .= "\n\t"; } } echo $r; } /** * Outputs the form used by the importers to accept the data to be imported. * * @since 2.0.0 * * @param string $action The action attribute for the form. */ function wp_import_upload_form( $action ) { /** * Filters the maximum allowed upload size for import files. * * @since 2.3.0 * * @see wp_max_upload_size() * * @param int $max_upload_size Allowed upload size. Default 1 MB. */ $bytes = apply_filters( 'import_upload_size_limit', wp_max_upload_size() ); $size = size_format( $bytes ); $upload_dir = wp_upload_dir(); if ( ! empty( $upload_dir['error'] ) ) : $upload_directory_error = '

    ' . __( 'Before you can upload your import file, you will need to fix the following error:' ) . '

    '; $upload_directory_error .= '

    ' . $upload_dir['error'] . '

    '; wp_admin_notice( $upload_directory_error, array( 'additional_classes' => array( 'error' ), 'paragraph_wrap' => false, ) ); else : ?>

    %s (%s)', __( 'Choose a file from your computer:' ), /* translators: %s: Maximum allowed file size. */ sprintf( __( 'Maximum size: %s' ), $size ) ); ?>

    id ) ) { return; } $page = $screen->id; if ( ! isset( $wp_meta_boxes ) ) { $wp_meta_boxes = array(); } if ( ! isset( $wp_meta_boxes[ $page ] ) ) { $wp_meta_boxes[ $page ] = array(); } if ( ! isset( $wp_meta_boxes[ $page ][ $context ] ) ) { $wp_meta_boxes[ $page ][ $context ] = array(); } foreach ( array_keys( $wp_meta_boxes[ $page ] ) as $a_context ) { foreach ( array( 'high', 'core', 'default', 'low' ) as $a_priority ) { if ( ! isset( $wp_meta_boxes[ $page ][ $a_context ][ $a_priority ][ $id ] ) ) { continue; } // If a core box was previously removed, don't add. if ( ( 'core' === $priority || 'sorted' === $priority ) && false === $wp_meta_boxes[ $page ][ $a_context ][ $a_priority ][ $id ] ) { return; } // If a core box was previously added by a plugin, don't add. if ( 'core' === $priority ) { /* * If the box was added with default priority, give it core priority * to maintain sort order. */ if ( 'default' === $a_priority ) { $wp_meta_boxes[ $page ][ $a_context ]['core'][ $id ] = $wp_meta_boxes[ $page ][ $a_context ]['default'][ $id ]; unset( $wp_meta_boxes[ $page ][ $a_context ]['default'][ $id ] ); } return; } // If no priority given and ID already present, use existing priority. if ( empty( $priority ) ) { $priority = $a_priority; /* * Else, if we're adding to the sorted priority, we don't know the title * or callback. Grab them from the previously added context/priority. */ } elseif ( 'sorted' === $priority ) { $title = $wp_meta_boxes[ $page ][ $a_context ][ $a_priority ][ $id ]['title']; $callback = $wp_meta_boxes[ $page ][ $a_context ][ $a_priority ][ $id ]['callback']; $callback_args = $wp_meta_boxes[ $page ][ $a_context ][ $a_priority ][ $id ]['args']; } // An ID can be in only one priority and one context. if ( $priority !== $a_priority || $context !== $a_context ) { unset( $wp_meta_boxes[ $page ][ $a_context ][ $a_priority ][ $id ] ); } } } if ( empty( $priority ) ) { $priority = 'low'; } if ( ! isset( $wp_meta_boxes[ $page ][ $context ][ $priority ] ) ) { $wp_meta_boxes[ $page ][ $context ][ $priority ] = array(); } $wp_meta_boxes[ $page ][ $context ][ $priority ][ $id ] = array( 'id' => $id, 'title' => $title, 'callback' => $callback, 'args' => $callback_args, ); } /** * Renders a "fake" meta box with an information message, * shown on the block editor, when an incompatible meta box is found. * * @since 5.0.0 * * @param mixed $data_object The data object being rendered on this screen. * @param array $box { * Custom formats meta box arguments. * * @type string $id Meta box 'id' attribute. * @type string $title Meta box title. * @type callable $old_callback The original callback for this meta box. * @type array $args Extra meta box arguments. * } */ function do_block_editor_incompatible_meta_box( $data_object, $box ) { $plugin = _get_plugin_from_callback( $box['old_callback'] ); $plugins = get_plugins(); echo '

    '; if ( $plugin ) { /* translators: %s: The name of the plugin that generated this meta box. */ printf( __( 'This meta box, from the %s plugin, is not compatible with the block editor.' ), "{$plugin['Name']}" ); } else { _e( 'This meta box is not compatible with the block editor.' ); } echo '

    '; if ( empty( $plugins['classic-editor/classic-editor.php'] ) ) { if ( current_user_can( 'install_plugins' ) ) { $install_url = wp_nonce_url( self_admin_url( 'plugin-install.php?tab=favorites&user=wordpressdotorg&save=0' ), 'save_wporg_username_' . get_current_user_id() ); echo '

    '; /* translators: %s: A link to install the Classic Editor plugin. */ printf( __( 'Please install the Classic Editor plugin to use this meta box.' ), esc_url( $install_url ) ); echo '

    '; } } elseif ( is_plugin_inactive( 'classic-editor/classic-editor.php' ) ) { if ( current_user_can( 'activate_plugins' ) ) { $activate_url = wp_nonce_url( self_admin_url( 'plugins.php?action=activate&plugin=classic-editor/classic-editor.php' ), 'activate-plugin_classic-editor/classic-editor.php' ); echo '

    '; /* translators: %s: A link to activate the Classic Editor plugin. */ printf( __( 'Please activate the Classic Editor plugin to use this meta box.' ), esc_url( $activate_url ) ); echo '

    '; } } elseif ( $data_object instanceof WP_Post ) { $edit_url = add_query_arg( array( 'classic-editor' => '', 'classic-editor__forget' => '', ), get_edit_post_link( $data_object ) ); echo '

    '; /* translators: %s: A link to use the Classic Editor plugin. */ printf( __( 'Please open the classic editor to use this meta box.' ), esc_url( $edit_url ) ); echo '

    '; } } /** * Internal helper function to find the plugin from a meta box callback. * * @since 5.0.0 * * @access private * * @param callable $callback The callback function to check. * @return array|null The plugin that the callback belongs to, or null if it doesn't belong to a plugin. */ function _get_plugin_from_callback( $callback ) { try { if ( is_array( $callback ) ) { $reflection = new ReflectionMethod( $callback[0], $callback[1] ); } elseif ( is_string( $callback ) && str_contains( $callback, '::' ) ) { $reflection = new ReflectionMethod( $callback ); } else { $reflection = new ReflectionFunction( $callback ); } } catch ( ReflectionException $exception ) { // We could not properly reflect on the callable, so we abort here. return null; } // Don't show an error if it's an internal PHP function. if ( ! $reflection->isInternal() ) { // Only show errors if the meta box was registered by a plugin. $filename = wp_normalize_path( $reflection->getFileName() ); $plugin_dir = wp_normalize_path( WP_PLUGIN_DIR ); if ( str_starts_with( $filename, $plugin_dir ) ) { $filename = str_replace( $plugin_dir, '', $filename ); $filename = preg_replace( '|^/([^/]*/).*$|', '\\1', $filename ); $plugins = get_plugins(); foreach ( $plugins as $name => $plugin ) { if ( str_starts_with( $name, $filename ) ) { return $plugin; } } } } return null; } /** * Meta-Box template function. * * @since 2.5.0 * * @global array $wp_meta_boxes Global meta box state. * * @param string|WP_Screen $screen The screen identifier. If you have used add_menu_page() or * add_submenu_page() to create a new screen (and hence screen_id) * make sure your menu slug conforms to the limits of sanitize_key() * otherwise the 'screen' menu may not correctly render on your page. * @param string $context The screen context for which to display meta boxes. * @param mixed $data_object Gets passed to the meta box callback function as the first parameter. * Often this is the object that's the focus of the current screen, * for example a `WP_Post` or `WP_Comment` object. * @return int Number of meta_boxes. */ function do_meta_boxes( $screen, $context, $data_object ) { global $wp_meta_boxes; static $already_sorted = false; if ( empty( $screen ) ) { $screen = get_current_screen(); } elseif ( is_string( $screen ) ) { $screen = convert_to_screen( $screen ); } $page = $screen->id; $hidden = get_hidden_meta_boxes( $screen ); printf( '
    ', esc_attr( $context ) ); /* * Grab the ones the user has manually sorted. * Pull them out of their previous context/priority and into the one the user chose. */ $sorted = get_user_option( "meta-box-order_$page" ); if ( ! $already_sorted && $sorted ) { foreach ( $sorted as $box_context => $ids ) { foreach ( explode( ',', $ids ) as $id ) { if ( $id && 'dashboard_browser_nag' !== $id ) { add_meta_box( $id, null, null, $screen, $box_context, 'sorted' ); } } } } $already_sorted = true; $i = 0; if ( isset( $wp_meta_boxes[ $page ][ $context ] ) ) { foreach ( array( 'high', 'sorted', 'core', 'default', 'low' ) as $priority ) { if ( isset( $wp_meta_boxes[ $page ][ $context ][ $priority ] ) ) { foreach ( (array) $wp_meta_boxes[ $page ][ $context ][ $priority ] as $box ) { if ( false === $box || ! $box['title'] ) { continue; } $block_compatible = true; if ( is_array( $box['args'] ) ) { // If a meta box is just here for back compat, don't show it in the block editor. if ( $screen->is_block_editor() && isset( $box['args']['__back_compat_meta_box'] ) && $box['args']['__back_compat_meta_box'] ) { continue; } if ( isset( $box['args']['__block_editor_compatible_meta_box'] ) ) { $block_compatible = (bool) $box['args']['__block_editor_compatible_meta_box']; unset( $box['args']['__block_editor_compatible_meta_box'] ); } // If the meta box is declared as incompatible with the block editor, override the callback function. if ( ! $block_compatible && $screen->is_block_editor() ) { $box['old_callback'] = $box['callback']; $box['callback'] = 'do_block_editor_incompatible_meta_box'; } if ( isset( $box['args']['__back_compat_meta_box'] ) ) { $block_compatible = $block_compatible || (bool) $box['args']['__back_compat_meta_box']; unset( $box['args']['__back_compat_meta_box'] ); } } ++$i; // get_hidden_meta_boxes() doesn't apply in the block editor. $hidden_class = ( ! $screen->is_block_editor() && in_array( $box['id'], $hidden, true ) ) ? ' hide-if-js' : ''; echo '
    ' . "\n"; echo '
    '; echo '

    '; if ( 'dashboard_php_nag' === $box['id'] ) { echo ''; echo '' . /* translators: Hidden accessibility text. */ __( 'Warning:' ) . ' '; } echo $box['title']; echo "

    \n"; if ( 'dashboard_browser_nag' !== $box['id'] ) { $widget_title = $box['title']; if ( is_array( $box['args'] ) && isset( $box['args']['__widget_basename'] ) ) { $widget_title = $box['args']['__widget_basename']; // Do not pass this parameter to the user callback function. unset( $box['args']['__widget_basename'] ); } echo '
    '; echo ''; echo ''; echo ''; echo ''; echo ''; echo '
    '; } echo '
    '; echo '
    ' . "\n"; if ( WP_DEBUG && ! $block_compatible && 'edit' === $screen->parent_base && ! $screen->is_block_editor() && ! isset( $_GET['meta-box-loader'] ) ) { $plugin = _get_plugin_from_callback( $box['callback'] ); if ( $plugin ) { $meta_box_not_compatible_message = sprintf( /* translators: %s: The name of the plugin that generated this meta box. */ __( 'This meta box, from the %s plugin, is not compatible with the block editor.' ), "{$plugin['Name']}" ); wp_admin_notice( $meta_box_not_compatible_message, array( 'additional_classes' => array( 'error', 'inline' ), ) ); } } call_user_func( $box['callback'], $data_object, $box ); echo "
    \n"; echo "
    \n"; } } } } echo '
    '; return $i; } /** * Removes a meta box from one or more screens. * * @since 2.6.0 * @since 4.4.0 The `$screen` parameter now accepts an array of screen IDs. * * @global array $wp_meta_boxes Global meta box state. * * @param string $id Meta box ID (used in the 'id' attribute for the meta box). * @param string|array|WP_Screen $screen The screen or screens on which the meta box is shown (such as a * post type, 'link', or 'comment'). Accepts a single screen ID, * WP_Screen object, or array of screen IDs. * @param string $context The context within the screen where the box is set to display. * Contexts vary from screen to screen. Post edit screen contexts * include 'normal', 'side', and 'advanced'. Comments screen contexts * include 'normal' and 'side'. Menus meta boxes (accordion sections) * all use the 'side' context. */ function remove_meta_box( $id, $screen, $context ) { global $wp_meta_boxes; if ( empty( $screen ) ) { $screen = get_current_screen(); } elseif ( is_string( $screen ) ) { $screen = convert_to_screen( $screen ); } elseif ( is_array( $screen ) ) { foreach ( $screen as $single_screen ) { remove_meta_box( $id, $single_screen, $context ); } } if ( ! isset( $screen->id ) ) { return; } $page = $screen->id; if ( ! isset( $wp_meta_boxes ) ) { $wp_meta_boxes = array(); } if ( ! isset( $wp_meta_boxes[ $page ] ) ) { $wp_meta_boxes[ $page ] = array(); } if ( ! isset( $wp_meta_boxes[ $page ][ $context ] ) ) { $wp_meta_boxes[ $page ][ $context ] = array(); } foreach ( array( 'high', 'core', 'default', 'low' ) as $priority ) { $wp_meta_boxes[ $page ][ $context ][ $priority ][ $id ] = false; } } /** * Meta Box Accordion Template Function. * * Largely made up of abstracted code from do_meta_boxes(), this * function serves to build meta boxes as list items for display as * a collapsible accordion. * * @since 3.6.0 * * @uses global $wp_meta_boxes Used to retrieve registered meta boxes. * * @param string|object $screen The screen identifier. * @param string $context The screen context for which to display accordion sections. * @param mixed $data_object Gets passed to the section callback function as the first parameter. * @return int Number of meta boxes as accordion sections. */ function do_accordion_sections( $screen, $context, $data_object ) { global $wp_meta_boxes; wp_enqueue_script( 'accordion' ); if ( empty( $screen ) ) { $screen = get_current_screen(); } elseif ( is_string( $screen ) ) { $screen = convert_to_screen( $screen ); } $page = $screen->id; $hidden = get_hidden_meta_boxes( $screen ); ?>
    $id, 'title' => $title, 'callback' => $callback, 'before_section' => '', 'after_section' => '', 'section_class' => '', ); $section = wp_parse_args( $args, $defaults ); if ( 'misc' === $page ) { _deprecated_argument( __FUNCTION__, '3.0.0', sprintf( /* translators: %s: misc */ __( 'The "%s" options group has been removed. Use another settings group.' ), 'misc' ) ); $page = 'general'; } if ( 'privacy' === $page ) { _deprecated_argument( __FUNCTION__, '3.5.0', sprintf( /* translators: %s: privacy */ __( 'The "%s" options group has been removed. Use another settings group.' ), 'privacy' ) ); $page = 'reading'; } $wp_settings_sections[ $page ][ $id ] = $section; } /** * Adds a new field to a section of a settings page. * * Part of the Settings API. Use this to define a settings field that will show * as part of a settings section inside a settings page. The fields are shown using * do_settings_fields() in do_settings_sections(). * * The $callback argument should be the name of a function that echoes out the * HTML input tags for this setting field. Use get_option() to retrieve existing * values to show. * * @since 2.7.0 * @since 4.2.0 The `$class` argument was added. * * @global array $wp_settings_fields Storage array of settings fields and info about their pages/sections. * * @param string $id Slug-name to identify the field. Used in the 'id' attribute of tags. * @param string $title Formatted title of the field. Shown as the label for the field * during output. * @param callable $callback Function that fills the field with the desired form inputs. The * function should echo its output. * @param string $page The slug-name of the settings page on which to show the section * (general, reading, writing, ...). * @param string $section Optional. The slug-name of the section of the settings page * in which to show the box. Default 'default'. * @param array $args { * Optional. Extra arguments that get passed to the callback function. * * @type string $label_for When supplied, the setting title will be wrapped * in a `