' . __( 'Add menu items from the column on the left.' ) . '
'; $result .= 'screen.php 0000644 00000014352 14720636575 0006560 0 ustar 00 id ] ) ) {
/**
* 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.php 0000644 00000177410 14720636575 0011032 0 ustar 00 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.php 0000644 00000207323 14720636575 0007513 0 ustar 00 '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( '
' ); show_message( ' ' ); 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" ), '%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() { ?>' . __( '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
' . __( '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() { ?>
admin_image_div_callback ) {
call_user_func( $this->admin_image_div_callback );
} else {
$background_styles = '';
$bgcolor = get_background_color();
if ( $bgcolor ) {
$background_styles .= 'background-color: #' . $bgcolor . ';';
}
$background_image_thumb = get_background_image();
if ( $background_image_thumb ) {
$background_image_thumb = esc_url( set_url_scheme( get_theme_mod( 'background_image_thumb', str_replace( '%', '%%', $background_image_thumb ) ) ) );
$background_position_x = get_theme_mod( 'background_position_x', get_theme_support( 'custom-background', 'default-position-x' ) );
$background_position_y = get_theme_mod( 'background_position_y', get_theme_support( 'custom-background', 'default-position-y' ) );
$background_size = get_theme_mod( 'background_size', get_theme_support( 'custom-background', 'default-size' ) );
$background_repeat = get_theme_mod( 'background_repeat', get_theme_support( 'custom-background', 'default-repeat' ) );
$background_attachment = get_theme_mod( 'background_attachment', get_theme_support( 'custom-background', 'default-attachment' ) );
// Background-image URL must be single quote, see below.
$background_styles .= " background-image: url('$background_image_thumb');"
. " background-size: $background_size;"
. " background-position: $background_position_x $background_position_y;"
. " background-repeat: $background_repeat;"
. " background-attachment: $background_attachment;";
}
?>
|
|
' . __( '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 'admin_image_div_callback ) { call_user_func( $this->admin_image_div_callback ); } else { $custom_header = get_custom_header(); $header_image = get_header_image(); if ( $header_image ) { $header_image_style = 'background-image:url(' . esc_url( $header_image ) . ');'; } else { $header_image_style = ''; } if ( $custom_header->width ) { $header_image_style .= 'max-width:' . $custom_header->width . 'px;'; } if ( $custom_header->height ) { $header_image_style .= 'height:' . $custom_header->height . 'px;'; } ?> | |
|
' . __( '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; } ?>' . __( '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( '' . __( '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.php 0000644 00000014731 14720636575 0006614 0 ustar 00 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.php 0000644 00000012673 14720636575 0016646 0 ustar 00 status; $request_id = $item->ID; $nonce = wp_create_nonce( 'wp-privacy-export-personal-data-' . $request_id ); $download_data_markup = ''; $download_data_markup .= '' . ''; $row_actions['download-data'] = $download_data_markup; if ( 'request-completed' !== $status ) { $complete_request_markup = ' ' . '' . ' '; $download_data_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 '$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:' ) . ' 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.php 0000644 00000102246 14720636575 0005720 0 ustar 00 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 );
?>
' . 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 .= '{$blog->blogname} | "; $output .= '' . __( 'Visit Dashboard' ) . ' | ' . '' . __( 'View Site' ) . ' | '; $output .= '
1 ) { $found = false; ?> userblog_id ); } } elseif ( 1 === count( $all_blogs ) ) { $blog = reset( $all_blogs ); echo esc_url( get_home_url( $blog->userblog_id ) ); if ( $blog->userblog_id !== $primary_blog ) { // Set the primary blog again if it's out of sync with blog list. update_user_meta( get_current_user_id(), 'primary_blog', $blog->userblog_id ); } } else { _e( 'Not available' ); } ?> |
' . __( '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.php 0000644 00000013123 14720636575 0016761 0 ustar 00 status; $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 .= '' . ''; $row_actions['remove-data'] = $remove_data_markup; } if ( 'request-completed' !== $status ) { $complete_request_markup = ' ' . ' ' . ' '; $remove_data_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 '' . esc_html_x( 'Current', 'plugin' ) . ' | '; $table .= '' . esc_html_x( 'Uploaded', 'plugin' ) . ' | ||
---|---|---|---|
' . $label . ' | ' . wp_strip_all_tags( $old_value ) . ' | '; $table .= ( $diff_field || $diff_version ) ? '' : ' | '; $table .= wp_strip_all_tags( $new_value ) . ' |
' . esc_html__( 'The plugin cannot be updated due to the following:' ) . '
'; $blocked_message .= '' . $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.php 0000644 00000060322 14720636575 0014026 0 ustar 00 no_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' ); ?>', '', 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; } ?>%s
%s$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, '' . __( 'Title' ) . ' | ' . __( 'Type' ) . ' | ' . __( 'Date' ) . ' | ' . __( 'Status' ) . ' | |
---|---|---|---|---|
'; $html .= ' | ' . esc_html( $post_types[ $post->post_type ]->labels->singular_name ) . ' | ' . esc_html( $time ) . ' | ' . esc_html( $stat ) . ' |
' . __( '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.php 0000644 00000050074 14720636575 0010744 0 ustar 00 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.' ) . '' . esc_html( $group_data['group_description'] ) . '
'; } $group_html .= '' . esc_html( $group_item_datum['name'] ) . ' | '; $group_html .= '' . wp_kses( $value, 'personal_data_export' ) . ' | '; $group_html .= '
---|
_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, '' . __( '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="quick-search" value="" name="" id="" /> "submit-quick-search-posttype-{$post_type_name}" ) ); ?>
' . __( '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 ) ); } ?>" id="" /> "submit-quick-search-taxonomy-{$taxonomy_name}" ) ); ?>
' . __( '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 .= '
' . 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.' ),
'*
'
) . '
' . __( '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.php 0000644 00000026537 14720636575 0007116 0 ustar 00 ' . __( '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.php 0000644 00000053012 14720636575 0012626 0 ustar 00 status_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 ) { ?>.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.php 0000644 00000013751 14720636575 0006745 0 ustar 00 get_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
' . esc_html_x( 'Active', 'theme' ) . ' | ' . esc_html_x( 'Uploaded', 'theme' ) . ' | ||
---|---|---|---|
' . $label . ' | ' . wp_strip_all_tags( $old_value ) . ' | '; $table .= ( $diff_field || $diff_version || $invalid_parent ) ? '' : ' | '; $table .= wp_strip_all_tags( $new_value ) . ' |
' . esc_html__( 'The theme cannot be updated due to the following:' ) . '
'; $blocked_message .= '' . $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.php 0000644 00000110717 14720636575 0010311 0 ustar 00 post_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() && ! $this->show_screen_options() ) { return; } ?>
" . 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 : ?> 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( ' '; 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 ); ?>