This commit is contained in:
2024-05-20 15:37:46 +03:00
commit 00b7dbd0b7
10404 changed files with 3285853 additions and 0 deletions

View File

@ -0,0 +1,174 @@
<?php
/**
* Administration API: Default admin hooks
*
* @package WordPress
* @subpackage Administration
* @since 4.3.0
*/
// Bookmark hooks.
add_action( 'admin_page_access_denied', 'wp_link_manager_disabled_message' );
// Dashboard hooks.
add_action( 'activity_box_end', 'wp_dashboard_quota' );
add_action( 'welcome_panel', 'wp_welcome_panel' );
// Media hooks.
add_action( 'attachment_submitbox_misc_actions', 'attachment_submitbox_metadata' );
add_filter( 'plupload_init', 'wp_show_heic_upload_error' );
add_action( 'media_upload_image', 'wp_media_upload_handler' );
add_action( 'media_upload_audio', 'wp_media_upload_handler' );
add_action( 'media_upload_video', 'wp_media_upload_handler' );
add_action( 'media_upload_file', 'wp_media_upload_handler' );
add_action( 'post-plupload-upload-ui', 'media_upload_flash_bypass' );
add_action( 'post-html-upload-ui', 'media_upload_html_bypass' );
add_filter( 'async_upload_image', 'get_media_item', 10, 2 );
add_filter( 'async_upload_audio', 'get_media_item', 10, 2 );
add_filter( 'async_upload_video', 'get_media_item', 10, 2 );
add_filter( 'async_upload_file', 'get_media_item', 10, 2 );
add_filter( 'media_upload_gallery', 'media_upload_gallery' );
add_filter( 'media_upload_library', 'media_upload_library' );
add_filter( 'media_upload_tabs', 'update_gallery_tab' );
// Admin color schemes.
add_action( 'admin_init', 'register_admin_color_schemes', 1 );
add_action( 'admin_head', 'wp_color_scheme_settings' );
add_action( 'admin_color_scheme_picker', 'admin_color_scheme_picker' );
// Misc hooks.
add_action( 'admin_init', 'wp_admin_headers' );
add_action( 'login_init', 'wp_admin_headers' );
add_action( 'admin_init', 'send_frame_options_header', 10, 0 );
add_action( 'admin_head', 'wp_admin_canonical_url' );
add_action( 'admin_head', 'wp_site_icon' );
add_action( 'admin_head', 'wp_admin_viewport_meta' );
add_action( 'customize_controls_head', 'wp_admin_viewport_meta' );
add_filter( 'nav_menu_meta_box_object', '_wp_nav_menu_meta_box_object' );
// Prerendering.
if ( ! is_customize_preview() ) {
add_filter( 'admin_print_styles', 'wp_resource_hints', 1 );
}
add_action( 'admin_print_scripts', 'print_emoji_detection_script' );
add_action( 'admin_print_scripts', 'print_head_scripts', 20 );
add_action( 'admin_print_footer_scripts', '_wp_footer_scripts' );
add_action( 'admin_enqueue_scripts', 'wp_enqueue_emoji_styles' );
add_action( 'admin_print_styles', 'print_emoji_styles' ); // Retained for backwards-compatibility. Unhooked by wp_enqueue_emoji_styles().
add_action( 'admin_print_styles', 'print_admin_styles', 20 );
add_action( 'admin_print_scripts-index.php', 'wp_localize_community_events' );
add_action( 'admin_print_scripts-post.php', 'wp_page_reload_on_back_button_js' );
add_action( 'admin_print_scripts-post-new.php', 'wp_page_reload_on_back_button_js' );
add_action( 'update_option_home', 'update_home_siteurl', 10, 2 );
add_action( 'update_option_siteurl', 'update_home_siteurl', 10, 2 );
add_action( 'update_option_page_on_front', 'update_home_siteurl', 10, 2 );
add_action( 'update_option_admin_email', 'wp_site_admin_email_change_notification', 10, 3 );
add_action( 'add_option_new_admin_email', 'update_option_new_admin_email', 10, 2 );
add_action( 'update_option_new_admin_email', 'update_option_new_admin_email', 10, 2 );
add_filter( 'heartbeat_received', 'wp_check_locked_posts', 10, 3 );
add_filter( 'heartbeat_received', 'wp_refresh_post_lock', 10, 3 );
add_filter( 'heartbeat_received', 'heartbeat_autosave', 500, 2 );
add_filter( 'wp_refresh_nonces', 'wp_refresh_post_nonces', 10, 3 );
add_filter( 'wp_refresh_nonces', 'wp_refresh_metabox_loader_nonces', 10, 2 );
add_filter( 'wp_refresh_nonces', 'wp_refresh_heartbeat_nonces' );
add_filter( 'heartbeat_settings', 'wp_heartbeat_set_suspension' );
add_action( 'use_block_editor_for_post_type', '_disable_block_editor_for_navigation_post_type', 10, 2 );
add_action( 'edit_form_after_title', '_disable_content_editor_for_navigation_post_type' );
add_action( 'edit_form_after_editor', '_enable_content_editor_for_navigation_post_type' );
// Nav Menu hooks.
add_action( 'admin_head-nav-menus.php', '_wp_delete_orphaned_draft_menu_items' );
// Plugin hooks.
add_filter( 'allowed_options', 'option_update_filter' );
// Plugin Install hooks.
add_action( 'install_plugins_featured', 'install_dashboard' );
add_action( 'install_plugins_upload', 'install_plugins_upload' );
add_action( 'install_plugins_search', 'display_plugins_table' );
add_action( 'install_plugins_popular', 'display_plugins_table' );
add_action( 'install_plugins_recommended', 'display_plugins_table' );
add_action( 'install_plugins_new', 'display_plugins_table' );
add_action( 'install_plugins_beta', 'display_plugins_table' );
add_action( 'install_plugins_favorites', 'display_plugins_table' );
add_action( 'install_plugins_pre_plugin-information', 'install_plugin_information' );
// Template hooks.
add_action( 'admin_enqueue_scripts', array( 'WP_Internal_Pointers', 'enqueue_scripts' ) );
add_action( 'user_register', array( 'WP_Internal_Pointers', 'dismiss_pointers_for_new_users' ) );
// Theme hooks.
add_action( 'customize_controls_print_footer_scripts', 'customize_themes_print_templates' );
// Theme Install hooks.
add_action( 'install_themes_pre_theme-information', 'install_theme_information' );
// User hooks.
add_action( 'admin_init', 'default_password_nag_handler' );
add_action( 'admin_notices', 'default_password_nag' );
add_action( 'admin_notices', 'new_user_email_admin_notice' );
add_action( 'profile_update', 'default_password_nag_edit_user', 10, 2 );
add_action( 'personal_options_update', 'send_confirmation_on_profile_email' );
// Update hooks.
add_action( 'load-plugins.php', 'wp_plugin_update_rows', 20 ); // After wp_update_plugins() is called.
add_action( 'load-themes.php', 'wp_theme_update_rows', 20 ); // After wp_update_themes() is called.
add_action( 'admin_notices', 'update_nag', 3 );
add_action( 'admin_notices', 'deactivated_plugins_notice', 5 );
add_action( 'admin_notices', 'paused_plugins_notice', 5 );
add_action( 'admin_notices', 'paused_themes_notice', 5 );
add_action( 'admin_notices', 'maintenance_nag', 10 );
add_action( 'admin_notices', 'wp_recovery_mode_nag', 1 );
add_filter( 'update_footer', 'core_update_footer' );
// Update Core hooks.
add_action( '_core_updated_successfully', '_redirect_to_about_wordpress' );
// Upgrade hooks.
add_action( 'upgrader_process_complete', array( 'Language_Pack_Upgrader', 'async_upgrade' ), 20 );
add_action( 'upgrader_process_complete', 'wp_version_check', 10, 0 );
add_action( 'upgrader_process_complete', 'wp_update_plugins', 10, 0 );
add_action( 'upgrader_process_complete', 'wp_update_themes', 10, 0 );
// Privacy hooks.
add_filter( 'wp_privacy_personal_data_erasure_page', 'wp_privacy_process_personal_data_erasure_page', 10, 5 );
add_filter( 'wp_privacy_personal_data_export_page', 'wp_privacy_process_personal_data_export_page', 10, 7 );
add_action( 'wp_privacy_personal_data_export_file', 'wp_privacy_generate_personal_data_export_file', 10 );
add_action( 'wp_privacy_personal_data_erased', '_wp_privacy_send_erasure_fulfillment_notification', 10 );
// Privacy policy text changes check.
add_action( 'admin_init', array( 'WP_Privacy_Policy_Content', 'text_change_check' ), 100 );
// Show a "postbox" with the text suggestions for a privacy policy.
add_action( 'admin_notices', array( 'WP_Privacy_Policy_Content', 'notice' ) );
// Add the suggested policy text from WordPress.
add_action( 'admin_init', array( 'WP_Privacy_Policy_Content', 'add_suggested_content' ), 1 );
// Update the cached policy info when the policy page is updated.
add_action( 'post_updated', array( 'WP_Privacy_Policy_Content', '_policy_page_updated' ) );
// Append '(Draft)' to draft page titles in the privacy page dropdown.
add_filter( 'list_pages', '_wp_privacy_settings_filter_draft_page_titles', 10, 2 );
// Font management.
add_action( 'admin_print_styles', 'wp_print_font_faces', 50 );

101
wp-admin/includes/admin.php Normal file
View File

@ -0,0 +1,101 @@
<?php
/**
* Core Administration API
*
* @package WordPress
* @subpackage Administration
* @since 2.3.0
*/
if ( ! defined( 'WP_ADMIN' ) ) {
/*
* This file is being included from a file other than wp-admin/admin.php, so
* some setup was skipped. Make sure the admin message catalog is loaded since
* load_default_textdomain() will not have done so in this context.
*/
$admin_locale = get_locale();
load_textdomain( 'default', WP_LANG_DIR . '/admin-' . $admin_locale . '.mo', $admin_locale );
unset( $admin_locale );
}
/** WordPress Administration Hooks */
require_once ABSPATH . 'wp-admin/includes/admin-filters.php';
/** WordPress Bookmark Administration API */
require_once ABSPATH . 'wp-admin/includes/bookmark.php';
/** WordPress Comment Administration API */
require_once ABSPATH . 'wp-admin/includes/comment.php';
/** WordPress Administration File API */
require_once ABSPATH . 'wp-admin/includes/file.php';
/** WordPress Image Administration API */
require_once ABSPATH . 'wp-admin/includes/image.php';
/** WordPress Media Administration API */
require_once ABSPATH . 'wp-admin/includes/media.php';
/** WordPress Import Administration API */
require_once ABSPATH . 'wp-admin/includes/import.php';
/** WordPress Misc Administration API */
require_once ABSPATH . 'wp-admin/includes/misc.php';
/** WordPress Misc Administration API */
require_once ABSPATH . 'wp-admin/includes/class-wp-privacy-policy-content.php';
/** WordPress Options Administration API */
require_once ABSPATH . 'wp-admin/includes/options.php';
/** WordPress Plugin Administration API */
require_once ABSPATH . 'wp-admin/includes/plugin.php';
/** WordPress Post Administration API */
require_once ABSPATH . 'wp-admin/includes/post.php';
/** WordPress Administration Screen API */
require_once ABSPATH . 'wp-admin/includes/class-wp-screen.php';
require_once ABSPATH . 'wp-admin/includes/screen.php';
/** WordPress Taxonomy Administration API */
require_once ABSPATH . 'wp-admin/includes/taxonomy.php';
/** WordPress Template Administration API */
require_once ABSPATH . 'wp-admin/includes/template.php';
/** WordPress List Table Administration API and base class */
require_once ABSPATH . 'wp-admin/includes/class-wp-list-table.php';
require_once ABSPATH . 'wp-admin/includes/class-wp-list-table-compat.php';
require_once ABSPATH . 'wp-admin/includes/list-table.php';
/** WordPress Theme Administration API */
require_once ABSPATH . 'wp-admin/includes/theme.php';
/** WordPress Privacy Functions */
require_once ABSPATH . 'wp-admin/includes/privacy-tools.php';
/** WordPress Privacy List Table classes. */
// Previously in wp-admin/includes/user.php. Need to be loaded for backward compatibility.
require_once ABSPATH . 'wp-admin/includes/class-wp-privacy-requests-table.php';
require_once ABSPATH . 'wp-admin/includes/class-wp-privacy-data-export-requests-list-table.php';
require_once ABSPATH . 'wp-admin/includes/class-wp-privacy-data-removal-requests-list-table.php';
/** WordPress User Administration API */
require_once ABSPATH . 'wp-admin/includes/user.php';
/** WordPress Site Icon API */
require_once ABSPATH . 'wp-admin/includes/class-wp-site-icon.php';
/** WordPress Update Administration API */
require_once ABSPATH . 'wp-admin/includes/update.php';
/** WordPress Deprecated Administration API */
require_once ABSPATH . 'wp-admin/includes/deprecated.php';
/** WordPress Multisite support API */
if ( is_multisite() ) {
require_once ABSPATH . 'wp-admin/includes/ms-admin-filters.php';
require_once ABSPATH . 'wp-admin/includes/ms.php';
require_once ABSPATH . 'wp-admin/includes/ms-deprecated.php';
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,379 @@
<?php
/**
* WordPress Bookmark Administration API
*
* @package WordPress
* @subpackage Administration
*/
/**
* Adds a link using values provided in $_POST.
*
* @since 2.0.0
*
* @return int|WP_Error Value 0 or WP_Error on failure. The link ID on success.
*/
function add_link() {
return edit_link();
}
/**
* Updates or inserts a link using values provided in $_POST.
*
* @since 2.0.0
*
* @param int $link_id Optional. ID of the link to edit. Default 0.
* @return int|WP_Error Value 0 or WP_Error on failure. The link ID on success.
*/
function edit_link( $link_id = 0 ) {
if ( ! current_user_can( 'manage_links' ) ) {
wp_die(
'<h1>' . __( 'You need a higher level of permission.' ) . '</h1>' .
'<p>' . __( 'Sorry, you are not allowed to edit the links for this site.' ) . '</p>',
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 <a href="%s">Link Manager plugin</a>.' ),
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 <a href="%s">Link Manager plugin</a> to use the link manager.' ),
esc_url( $activate_url )
)
);
}
}
}
wp_die( __( 'Sorry, you are not allowed to edit the links for this site.' ) );
}

View File

@ -0,0 +1,135 @@
<?php
/**
* Upgrader API: Automatic_Upgrader_Skin class
*
* @package WordPress
* @subpackage Upgrader
* @since 4.6.0
*/
/**
* Upgrader Skin for Automatic WordPress Upgrades.
*
* This skin is designed to be used when no output is intended, all output
* is captured and stored for the caller to process and log/email/discard.
*
* @since 3.7.0
* @since 4.6.0 Moved to its own file from wp-admin/includes/class-wp-upgrader-skins.php.
*
* @see Bulk_Upgrader_Skin
*/
class Automatic_Upgrader_Skin extends WP_Upgrader_Skin {
protected $messages = array();
/**
* Determines whether the upgrader needs FTP/SSH details in order to connect
* to the filesystem.
*
* @since 3.7.0
* @since 4.6.0 The `$context` parameter default changed from `false` to an empty string.
*
* @see request_filesystem_credentials()
*
* @param bool|WP_Error $error Optional. Whether the current request has failed to connect,
* or an error object. Default false.
* @param string $context Optional. Full path to the directory that is tested
* for being writable. Default empty.
* @param bool $allow_relaxed_file_ownership Optional. Whether to allow Group/World writable. Default false.
* @return bool True on success, false on failure.
*/
public function request_filesystem_credentials( $error = false, $context = '', $allow_relaxed_file_ownership = false ) {
if ( $context ) {
$this->options['context'] = $context;
}
/*
* TODO: Fix up request_filesystem_credentials(), or split it, to allow us to request a no-output version.
* This will output a credentials form in event of failure. We don't want that, so just hide with a buffer.
*/
ob_start();
$result = parent::request_filesystem_credentials( $error, $context, $allow_relaxed_file_ownership );
ob_end_clean();
return $result;
}
/**
* Retrieves the upgrade messages.
*
* @since 3.7.0
*
* @return string[] Messages during an upgrade.
*/
public function get_upgrade_messages() {
return $this->messages;
}
/**
* Stores a message about the upgrade.
*
* @since 3.7.0
* @since 5.9.0 Renamed `$data` to `$feedback` for PHP 8 named parameter support.
*
* @param string|array|WP_Error $feedback Message data.
* @param mixed ...$args Optional text replacements.
*/
public function feedback( $feedback, ...$args ) {
if ( is_wp_error( $feedback ) ) {
$string = $feedback->get_error_message();
} elseif ( is_array( $feedback ) ) {
return;
} else {
$string = $feedback;
}
if ( ! empty( $this->upgrader->strings[ $string ] ) ) {
$string = $this->upgrader->strings[ $string ];
}
if ( str_contains( $string, '%' ) ) {
if ( ! empty( $args ) ) {
$string = vsprintf( $string, $args );
}
}
$string = trim( $string );
// Only allow basic HTML in the messages, as it'll be used in emails/logs rather than direct browser output.
$string = wp_kses(
$string,
array(
'a' => array(
'href' => true,
),
'br' => true,
'em' => true,
'strong' => true,
)
);
if ( empty( $string ) ) {
return;
}
$this->messages[] = $string;
}
/**
* Creates a new output buffer.
*
* @since 3.7.0
*/
public function header() {
ob_start();
}
/**
* Retrieves the buffered content, deletes the buffer, and processes the output.
*
* @since 3.7.0
*/
public function footer() {
$output = ob_get_clean();
if ( ! empty( $output ) ) {
$this->feedback( $output );
}
}
}

View File

@ -0,0 +1,87 @@
<?php
/**
* Upgrader API: Bulk_Plugin_Upgrader_Skin class
*
* @package WordPress
* @subpackage Upgrader
* @since 4.6.0
*/
/**
* Bulk Plugin Upgrader Skin for WordPress Plugin Upgrades.
*
* @since 3.0.0
* @since 4.6.0 Moved to its own file from wp-admin/includes/class-wp-upgrader-skins.php.
*
* @see Bulk_Upgrader_Skin
*/
class Bulk_Plugin_Upgrader_Skin extends Bulk_Upgrader_Skin {
/**
* Plugin info.
*
* The Plugin_Upgrader::bulk_upgrade() method will fill this in
* with info retrieved from the get_plugin_data() function.
*
* @var array Plugin data. Values will be empty if not supplied by the plugin.
*/
public $plugin_info = array();
public function add_strings() {
parent::add_strings();
/* translators: 1: Plugin name, 2: Number of the plugin, 3: Total number of plugins being updated. */
$this->upgrader->strings['skin_before_update_header'] = __( 'Updating Plugin %1$s (%2$d/%3$d)' );
}
/**
* @param string $title
*/
public function before( $title = '' ) {
parent::before( $this->plugin_info['Title'] );
}
/**
* @param string $title
*/
public function after( $title = '' ) {
parent::after( $this->plugin_info['Title'] );
$this->decrement_update_count( 'plugin' );
}
/**
*/
public function bulk_footer() {
parent::bulk_footer();
$update_actions = array(
'plugins_page' => sprintf(
'<a href="%s" target="_parent">%s</a>',
self_admin_url( 'plugins.php' ),
__( 'Go to Plugins page' )
),
'updates_page' => sprintf(
'<a href="%s" target="_parent">%s</a>',
self_admin_url( 'update-core.php' ),
__( 'Go to WordPress Updates page' )
),
);
if ( ! current_user_can( 'activate_plugins' ) ) {
unset( $update_actions['plugins_page'] );
}
/**
* Filters the list of action links available following bulk plugin updates.
*
* @since 3.0.0
*
* @param string[] $update_actions Array of plugin action links.
* @param array $plugin_info Array of information for the last-updated plugin.
*/
$update_actions = apply_filters( 'update_bulk_plugins_complete_actions', $update_actions, $this->plugin_info );
if ( ! empty( $update_actions ) ) {
$this->feedback( implode( ' | ', (array) $update_actions ) );
}
}
}

View File

@ -0,0 +1,88 @@
<?php
/**
* Upgrader API: Bulk_Plugin_Upgrader_Skin class
*
* @package WordPress
* @subpackage Upgrader
* @since 4.6.0
*/
/**
* Bulk Theme Upgrader Skin for WordPress Theme Upgrades.
*
* @since 3.0.0
* @since 4.6.0 Moved to its own file from wp-admin/includes/class-wp-upgrader-skins.php.
*
* @see Bulk_Upgrader_Skin
*/
class Bulk_Theme_Upgrader_Skin extends Bulk_Upgrader_Skin {
/**
* Theme info.
*
* The Theme_Upgrader::bulk_upgrade() method will fill this in
* with info retrieved from the Theme_Upgrader::theme_info() method,
* which in turn calls the wp_get_theme() function.
*
* @var WP_Theme|false The theme's info object, or false.
*/
public $theme_info = false;
public function add_strings() {
parent::add_strings();
/* translators: 1: Theme name, 2: Number of the theme, 3: Total number of themes being updated. */
$this->upgrader->strings['skin_before_update_header'] = __( 'Updating Theme %1$s (%2$d/%3$d)' );
}
/**
* @param string $title
*/
public function before( $title = '' ) {
parent::before( $this->theme_info->display( 'Name' ) );
}
/**
* @param string $title
*/
public function after( $title = '' ) {
parent::after( $this->theme_info->display( 'Name' ) );
$this->decrement_update_count( 'theme' );
}
/**
*/
public function bulk_footer() {
parent::bulk_footer();
$update_actions = array(
'themes_page' => sprintf(
'<a href="%s" target="_parent">%s</a>',
self_admin_url( 'themes.php' ),
__( 'Go to Themes page' )
),
'updates_page' => sprintf(
'<a href="%s" target="_parent">%s</a>',
self_admin_url( 'update-core.php' ),
__( 'Go to WordPress Updates page' )
),
);
if ( ! current_user_can( 'switch_themes' ) && ! current_user_can( 'edit_theme_options' ) ) {
unset( $update_actions['themes_page'] );
}
/**
* Filters the list of action links available following bulk theme updates.
*
* @since 3.0.0
*
* @param string[] $update_actions Array of theme action links.
* @param WP_Theme $theme_info Theme object for the last-updated theme.
*/
$update_actions = apply_filters( 'update_bulk_theme_complete_actions', $update_actions, $this->theme_info );
if ( ! empty( $update_actions ) ) {
$this->feedback( implode( ' | ', (array) $update_actions ) );
}
}
}

View File

@ -0,0 +1,187 @@
<?php
/**
* Upgrader API: Bulk_Upgrader_Skin class
*
* @package WordPress
* @subpackage Upgrader
* @since 4.6.0
*/
/**
* Generic Bulk Upgrader Skin for WordPress Upgrades.
*
* @since 3.0.0
* @since 4.6.0 Moved to its own file from wp-admin/includes/class-wp-upgrader-skins.php.
*
* @see WP_Upgrader_Skin
*/
class Bulk_Upgrader_Skin extends WP_Upgrader_Skin {
public $in_loop = false;
/**
* @var string|false
*/
public $error = false;
/**
* @param array $args
*/
public function __construct( $args = array() ) {
$defaults = array(
'url' => '',
'nonce' => '',
);
$args = wp_parse_args( $args, $defaults );
parent::__construct( $args );
}
/**
*/
public function add_strings() {
$this->upgrader->strings['skin_upgrade_start'] = __( 'The update process is starting. This process may take a while on some hosts, so please be patient.' );
/* translators: 1: Title of an update, 2: Error message. */
$this->upgrader->strings['skin_update_failed_error'] = __( 'An error occurred while updating %1$s: %2$s' );
/* translators: %s: Title of an update. */
$this->upgrader->strings['skin_update_failed'] = __( 'The update of %s failed.' );
/* translators: %s: Title of an update. */
$this->upgrader->strings['skin_update_successful'] = __( '%s updated successfully.' );
$this->upgrader->strings['skin_upgrade_end'] = __( 'All updates have been completed.' );
}
/**
* @since 5.9.0 Renamed `$string` (a PHP reserved keyword) to `$feedback` for PHP 8 named parameter support.
*
* @param string $feedback Message data.
* @param mixed ...$args Optional text replacements.
*/
public function feedback( $feedback, ...$args ) {
if ( isset( $this->upgrader->strings[ $feedback ] ) ) {
$feedback = $this->upgrader->strings[ $feedback ];
}
if ( str_contains( $feedback, '%' ) ) {
if ( $args ) {
$args = array_map( 'strip_tags', $args );
$args = array_map( 'esc_html', $args );
$feedback = vsprintf( $feedback, $args );
}
}
if ( empty( $feedback ) ) {
return;
}
if ( $this->in_loop ) {
echo "$feedback<br />\n";
} else {
echo "<p>$feedback</p>\n";
}
}
/**
*/
public function header() {
// Nothing. This will be displayed within an iframe.
}
/**
*/
public function footer() {
// Nothing. This will be displayed within an iframe.
}
/**
* @since 5.9.0 Renamed `$error` to `$errors` for PHP 8 named parameter support.
*
* @param string|WP_Error $errors Errors.
*/
public function error( $errors ) {
if ( is_string( $errors ) && isset( $this->upgrader->strings[ $errors ] ) ) {
$this->error = $this->upgrader->strings[ $errors ];
}
if ( is_wp_error( $errors ) ) {
$messages = array();
foreach ( $errors->get_error_messages() as $emessage ) {
if ( $errors->get_error_data() && is_string( $errors->get_error_data() ) ) {
$messages[] = $emessage . ' ' . esc_html( strip_tags( $errors->get_error_data() ) );
} else {
$messages[] = $emessage;
}
}
$this->error = implode( ', ', $messages );
}
echo '<script type="text/javascript">jQuery(\'.waiting-' . esc_js( $this->upgrader->update_current ) . '\').hide();</script>';
}
/**
*/
public function bulk_header() {
$this->feedback( 'skin_upgrade_start' );
}
/**
*/
public function bulk_footer() {
$this->feedback( 'skin_upgrade_end' );
}
/**
* @param string $title
*/
public function before( $title = '' ) {
$this->in_loop = true;
printf( '<h2>' . $this->upgrader->strings['skin_before_update_header'] . ' <span class="spinner waiting-' . $this->upgrader->update_current . '"></span></h2>', $title, $this->upgrader->update_current, $this->upgrader->update_count );
echo '<script type="text/javascript">jQuery(\'.waiting-' . esc_js( $this->upgrader->update_current ) . '\').css("display", "inline-block");</script>';
// This progress messages div gets moved via JavaScript when clicking on "More details.".
echo '<div class="update-messages hide-if-js" id="progress-' . esc_attr( $this->upgrader->update_current ) . '"><p>';
$this->flush_output();
}
/**
* @param string $title
*/
public function after( $title = '' ) {
echo '</p></div>';
if ( $this->error || ! $this->result ) {
if ( $this->error ) {
$after_error_message = sprintf( $this->upgrader->strings['skin_update_failed_error'], $title, '<strong>' . $this->error . '</strong>' );
} else {
$after_error_message = sprintf( $this->upgrader->strings['skin_update_failed'], $title );
}
wp_admin_notice(
$after_error_message,
array(
'additional_classes' => array( 'error' ),
)
);
echo '<script type="text/javascript">jQuery(\'#progress-' . esc_js( $this->upgrader->update_current ) . '\').show();</script>';
}
if ( $this->result && ! is_wp_error( $this->result ) ) {
if ( ! $this->error ) {
echo '<div class="updated js-update-details" data-update-details="progress-' . esc_attr( $this->upgrader->update_current ) . '">' .
'<p>' . sprintf( $this->upgrader->strings['skin_update_successful'], $title ) .
' <button type="button" class="hide-if-no-js button-link js-update-details-toggle" aria-expanded="false">' . __( 'More details.' ) . '<span class="dashicons dashicons-arrow-down" aria-hidden="true"></span></button>' .
'</p></div>';
}
echo '<script type="text/javascript">jQuery(\'.waiting-' . esc_js( $this->upgrader->update_current ) . '\').hide();</script>';
}
$this->reset();
$this->flush_output();
}
/**
*/
public function reset() {
$this->in_loop = false;
$this->error = false;
}
/**
*/
public function flush_output() {
wp_ob_end_flush_all();
flush();
}
}

View File

@ -0,0 +1,420 @@
<?php
/**
* Upgrade API: Core_Upgrader class
*
* @package WordPress
* @subpackage Upgrader
* @since 4.6.0
*/
/**
* Core class used for updating core.
*
* It allows for WordPress to upgrade itself in combination with
* the wp-admin/includes/update-core.php file.
*
* @since 2.8.0
* @since 4.6.0 Moved to its own file from wp-admin/includes/class-wp-upgrader.php.
*
* @see WP_Upgrader
*/
class Core_Upgrader extends WP_Upgrader {
/**
* Initializes the upgrade strings.
*
* @since 2.8.0
*/
public function upgrade_strings() {
$this->strings['up_to_date'] = __( 'WordPress is at the latest version.' );
$this->strings['locked'] = __( 'Another update is currently in progress.' );
$this->strings['no_package'] = __( 'Update package not available.' );
/* translators: %s: Package URL. */
$this->strings['downloading_package'] = sprintf( __( 'Downloading update from %s&#8230;' ), '<span class="code pre">%s</span>' );
$this->strings['unpack_package'] = __( 'Unpacking the update&#8230;' );
$this->strings['copy_failed'] = __( 'Could not copy files.' );
$this->strings['copy_failed_space'] = __( 'Could not copy files. You may have run out of disk space.' );
$this->strings['start_rollback'] = __( 'Attempting to restore the previous version.' );
$this->strings['rollback_was_required'] = __( 'Due to an error during updating, WordPress has been restored to your previous version.' );
}
/**
* Upgrades WordPress core.
*
* @since 2.8.0
*
* @global WP_Filesystem_Base $wp_filesystem WordPress filesystem subclass.
* @global callable $_wp_filesystem_direct_method
*
* @param object $current Response object for whether WordPress is current.
* @param array $args {
* Optional. Arguments for upgrading WordPress core. Default empty array.
*
* @type bool $pre_check_md5 Whether to check the file checksums before
* attempting the upgrade. Default true.
* @type bool $attempt_rollback Whether to attempt to rollback the chances if
* there is a problem. Default false.
* @type bool $do_rollback Whether to perform this "upgrade" as a rollback.
* Default false.
* }
* @return string|false|WP_Error New WordPress version on success, false or WP_Error on failure.
*/
public function upgrade( $current, $args = array() ) {
global $wp_filesystem;
require ABSPATH . WPINC . '/version.php'; // $wp_version;
$start_time = time();
$defaults = array(
'pre_check_md5' => true,
'attempt_rollback' => false,
'do_rollback' => false,
'allow_relaxed_file_ownership' => false,
);
$parsed_args = wp_parse_args( $args, $defaults );
$this->init();
$this->upgrade_strings();
// Is an update available?
if ( ! isset( $current->response ) || 'latest' === $current->response ) {
return new WP_Error( 'up_to_date', $this->strings['up_to_date'] );
}
$res = $this->fs_connect( array( ABSPATH, WP_CONTENT_DIR ), $parsed_args['allow_relaxed_file_ownership'] );
if ( ! $res || is_wp_error( $res ) ) {
return $res;
}
$wp_dir = trailingslashit( $wp_filesystem->abspath() );
$partial = true;
if ( $parsed_args['do_rollback'] ) {
$partial = false;
} elseif ( $parsed_args['pre_check_md5'] && ! $this->check_files() ) {
$partial = false;
}
/*
* If partial update is returned from the API, use that, unless we're doing
* a reinstallation. If we cross the new_bundled version number, then use
* the new_bundled zip. Don't though if the constant is set to skip bundled items.
* If the API returns a no_content zip, go with it. Finally, default to the full zip.
*/
if ( $parsed_args['do_rollback'] && $current->packages->rollback ) {
$to_download = 'rollback';
} elseif ( $current->packages->partial && 'reinstall' !== $current->response && $wp_version === $current->partial_version && $partial ) {
$to_download = 'partial';
} elseif ( $current->packages->new_bundled && version_compare( $wp_version, $current->new_bundled, '<' )
&& ( ! defined( 'CORE_UPGRADE_SKIP_NEW_BUNDLED' ) || ! CORE_UPGRADE_SKIP_NEW_BUNDLED ) ) {
$to_download = 'new_bundled';
} elseif ( $current->packages->no_content ) {
$to_download = 'no_content';
} else {
$to_download = 'full';
}
// Lock to prevent multiple Core Updates occurring.
$lock = WP_Upgrader::create_lock( 'core_updater', 15 * MINUTE_IN_SECONDS );
if ( ! $lock ) {
return new WP_Error( 'locked', $this->strings['locked'] );
}
$download = $this->download_package( $current->packages->$to_download, true );
/*
* Allow for signature soft-fail.
* WARNING: This may be removed in the future.
*/
if ( is_wp_error( $download ) && $download->get_error_data( 'softfail-filename' ) ) {
// Output the failure error as a normal feedback, and not as an error:
/** This filter is documented in wp-admin/includes/update-core.php */
apply_filters( 'update_feedback', $download->get_error_message() );
// Report this failure back to WordPress.org for debugging purposes.
wp_version_check(
array(
'signature_failure_code' => $download->get_error_code(),
'signature_failure_data' => $download->get_error_data(),
)
);
// Pretend this error didn't happen.
$download = $download->get_error_data( 'softfail-filename' );
}
if ( is_wp_error( $download ) ) {
WP_Upgrader::release_lock( 'core_updater' );
return $download;
}
$working_dir = $this->unpack_package( $download );
if ( is_wp_error( $working_dir ) ) {
WP_Upgrader::release_lock( 'core_updater' );
return $working_dir;
}
// Copy update-core.php from the new version into place.
if ( ! $wp_filesystem->copy( $working_dir . '/wordpress/wp-admin/includes/update-core.php', $wp_dir . 'wp-admin/includes/update-core.php', true ) ) {
$wp_filesystem->delete( $working_dir, true );
WP_Upgrader::release_lock( 'core_updater' );
return new WP_Error( 'copy_failed_for_update_core_file', __( 'The update cannot be installed because some files could not be copied. This is usually due to inconsistent file permissions.' ), 'wp-admin/includes/update-core.php' );
}
$wp_filesystem->chmod( $wp_dir . 'wp-admin/includes/update-core.php', FS_CHMOD_FILE );
wp_opcache_invalidate( ABSPATH . 'wp-admin/includes/update-core.php' );
require_once ABSPATH . 'wp-admin/includes/update-core.php';
if ( ! function_exists( 'update_core' ) ) {
WP_Upgrader::release_lock( 'core_updater' );
return new WP_Error( 'copy_failed_space', $this->strings['copy_failed_space'] );
}
$result = update_core( $working_dir, $wp_dir );
// In the event of an issue, we may be able to roll back.
if ( $parsed_args['attempt_rollback'] && $current->packages->rollback && ! $parsed_args['do_rollback'] ) {
$try_rollback = false;
if ( is_wp_error( $result ) ) {
$error_code = $result->get_error_code();
/*
* Not all errors are equal. These codes are critical: copy_failed__copy_dir,
* mkdir_failed__copy_dir, copy_failed__copy_dir_retry, and disk_full.
* do_rollback allows for update_core() to trigger a rollback if needed.
*/
if ( str_contains( $error_code, 'do_rollback' ) ) {
$try_rollback = true;
} elseif ( str_contains( $error_code, '__copy_dir' ) ) {
$try_rollback = true;
} elseif ( 'disk_full' === $error_code ) {
$try_rollback = true;
}
}
if ( $try_rollback ) {
/** This filter is documented in wp-admin/includes/update-core.php */
apply_filters( 'update_feedback', $result );
/** This filter is documented in wp-admin/includes/update-core.php */
apply_filters( 'update_feedback', $this->strings['start_rollback'] );
$rollback_result = $this->upgrade( $current, array_merge( $parsed_args, array( 'do_rollback' => true ) ) );
$original_result = $result;
$result = new WP_Error(
'rollback_was_required',
$this->strings['rollback_was_required'],
(object) array(
'update' => $original_result,
'rollback' => $rollback_result,
)
);
}
}
/** This action is documented in wp-admin/includes/class-wp-upgrader.php */
do_action(
'upgrader_process_complete',
$this,
array(
'action' => 'update',
'type' => 'core',
)
);
// Clear the current updates.
delete_site_transient( 'update_core' );
if ( ! $parsed_args['do_rollback'] ) {
$stats = array(
'update_type' => $current->response,
'success' => true,
'fs_method' => $wp_filesystem->method,
'fs_method_forced' => defined( 'FS_METHOD' ) || has_filter( 'filesystem_method' ),
'fs_method_direct' => ! empty( $GLOBALS['_wp_filesystem_direct_method'] ) ? $GLOBALS['_wp_filesystem_direct_method'] : '',
'time_taken' => time() - $start_time,
'reported' => $wp_version,
'attempted' => $current->version,
);
if ( is_wp_error( $result ) ) {
$stats['success'] = false;
// Did a rollback occur?
if ( ! empty( $try_rollback ) ) {
$stats['error_code'] = $original_result->get_error_code();
$stats['error_data'] = $original_result->get_error_data();
// Was the rollback successful? If not, collect its error too.
$stats['rollback'] = ! is_wp_error( $rollback_result );
if ( is_wp_error( $rollback_result ) ) {
$stats['rollback_code'] = $rollback_result->get_error_code();
$stats['rollback_data'] = $rollback_result->get_error_data();
}
} else {
$stats['error_code'] = $result->get_error_code();
$stats['error_data'] = $result->get_error_data();
}
}
wp_version_check( $stats );
}
WP_Upgrader::release_lock( 'core_updater' );
return $result;
}
/**
* Determines if this WordPress Core version should update to an offered version or not.
*
* @since 3.7.0
*
* @param string $offered_ver The offered version, of the format x.y.z.
* @return bool True if we should update to the offered version, otherwise false.
*/
public static function should_update_to_version( $offered_ver ) {
require ABSPATH . WPINC . '/version.php'; // $wp_version; // x.y.z
$current_branch = implode( '.', array_slice( preg_split( '/[.-]/', $wp_version ), 0, 2 ) ); // x.y
$new_branch = implode( '.', array_slice( preg_split( '/[.-]/', $offered_ver ), 0, 2 ) ); // x.y
$current_is_development_version = (bool) strpos( $wp_version, '-' );
// Defaults:
$upgrade_dev = get_site_option( 'auto_update_core_dev', 'enabled' ) === 'enabled';
$upgrade_minor = get_site_option( 'auto_update_core_minor', 'enabled' ) === 'enabled';
$upgrade_major = get_site_option( 'auto_update_core_major', 'unset' ) === 'enabled';
// WP_AUTO_UPDATE_CORE = true (all), 'beta', 'rc', 'development', 'branch-development', 'minor', false.
if ( defined( 'WP_AUTO_UPDATE_CORE' ) ) {
if ( false === WP_AUTO_UPDATE_CORE ) {
// Defaults to turned off, unless a filter allows it.
$upgrade_dev = false;
$upgrade_minor = false;
$upgrade_major = false;
} elseif ( true === WP_AUTO_UPDATE_CORE
|| in_array( WP_AUTO_UPDATE_CORE, array( 'beta', 'rc', 'development', 'branch-development' ), true )
) {
// ALL updates for core.
$upgrade_dev = true;
$upgrade_minor = true;
$upgrade_major = true;
} elseif ( 'minor' === WP_AUTO_UPDATE_CORE ) {
// Only minor updates for core.
$upgrade_dev = false;
$upgrade_minor = true;
$upgrade_major = false;
}
}
// 1: If we're already on that version, not much point in updating?
if ( $offered_ver === $wp_version ) {
return false;
}
// 2: If we're running a newer version, that's a nope.
if ( version_compare( $wp_version, $offered_ver, '>' ) ) {
return false;
}
$failure_data = get_site_option( 'auto_core_update_failed' );
if ( $failure_data ) {
// If this was a critical update failure, cannot update.
if ( ! empty( $failure_data['critical'] ) ) {
return false;
}
// Don't claim we can update on update-core.php if we have a non-critical failure logged.
if ( $wp_version === $failure_data['current'] && str_contains( $offered_ver, '.1.next.minor' ) ) {
return false;
}
/*
* Cannot update if we're retrying the same A to B update that caused a non-critical failure.
* Some non-critical failures do allow retries, like download_failed.
* 3.7.1 => 3.7.2 resulted in files_not_writable, if we are still on 3.7.1 and still trying to update to 3.7.2.
*/
if ( empty( $failure_data['retry'] ) && $wp_version === $failure_data['current'] && $offered_ver === $failure_data['attempted'] ) {
return false;
}
}
// 3: 3.7-alpha-25000 -> 3.7-alpha-25678 -> 3.7-beta1 -> 3.7-beta2.
if ( $current_is_development_version ) {
/**
* Filters whether to enable automatic core updates for development versions.
*
* @since 3.7.0
*
* @param bool $upgrade_dev Whether to enable automatic updates for
* development versions.
*/
if ( ! apply_filters( 'allow_dev_auto_core_updates', $upgrade_dev ) ) {
return false;
}
// Else fall through to minor + major branches below.
}
// 4: Minor in-branch updates (3.7.0 -> 3.7.1 -> 3.7.2 -> 3.7.4).
if ( $current_branch === $new_branch ) {
/**
* Filters whether to enable minor automatic core updates.
*
* @since 3.7.0
*
* @param bool $upgrade_minor Whether to enable minor automatic core updates.
*/
return apply_filters( 'allow_minor_auto_core_updates', $upgrade_minor );
}
// 5: Major version updates (3.7.0 -> 3.8.0 -> 3.9.1).
if ( version_compare( $new_branch, $current_branch, '>' ) ) {
/**
* Filters whether to enable major automatic core updates.
*
* @since 3.7.0
*
* @param bool $upgrade_major Whether to enable major automatic core updates.
*/
return apply_filters( 'allow_major_auto_core_updates', $upgrade_major );
}
// If we're not sure, we don't want it.
return false;
}
/**
* Compares the disk file checksums against the expected checksums.
*
* @since 3.7.0
*
* @global string $wp_version The WordPress version string.
* @global string $wp_local_package Locale code of the package.
*
* @return bool True if the checksums match, otherwise false.
*/
public function check_files() {
global $wp_version, $wp_local_package;
$checksums = get_core_checksums( $wp_version, isset( $wp_local_package ) ? $wp_local_package : 'en_US' );
if ( ! is_array( $checksums ) ) {
return false;
}
foreach ( $checksums as $file => $checksum ) {
// Skip files which get updated.
if ( str_starts_with( $file, 'wp-content' ) ) {
continue;
}
if ( ! file_exists( ABSPATH . $file ) || md5_file( ABSPATH . $file ) !== $checksum ) {
return false;
}
}
return true;
}
}

View File

@ -0,0 +1,669 @@
<?php
/**
* The custom background script.
*
* @package WordPress
* @subpackage Administration
*/
/**
* The custom background class.
*
* @since 3.0.0
*/
#[AllowDynamicProperties]
class Custom_Background {
/**
* Callback for administration header.
*
* @var callable
* @since 3.0.0
*/
public $admin_header_callback;
/**
* Callback for header div.
*
* @var callable
* @since 3.0.0
*/
public $admin_image_div_callback;
/**
* Used to trigger a success message when settings updated and set to true.
*
* @since 3.0.0
* @var bool
*/
private $updated;
/**
* Constructor - Registers administration header callback.
*
* @since 3.0.0
*
* @param callable $admin_header_callback Optional. Administration header callback.
* Default empty string.
* @param callable $admin_image_div_callback Optional. Custom image div output callback.
* Default empty string.
*/
public function __construct( $admin_header_callback = '', $admin_image_div_callback = '' ) {
$this->admin_header_callback = $admin_header_callback;
$this->admin_image_div_callback = $admin_image_div_callback;
add_action( 'admin_menu', array( $this, 'init' ) );
add_action( 'wp_ajax_custom-background-add', array( $this, 'ajax_background_add' ) );
// Unused since 3.5.0.
add_action( 'wp_ajax_set-background-image', array( $this, 'wp_set_background_image' ) );
}
/**
* Sets up the hooks for the Custom Background admin page.
*
* @since 3.0.0
*/
public function init() {
$page = add_theme_page(
_x( 'Background', 'custom background' ),
_x( 'Background', 'custom background' ),
'edit_theme_options',
'custom-background',
array( $this, 'admin_page' )
);
if ( ! $page ) {
return;
}
add_action( "load-{$page}", array( $this, 'admin_load' ) );
add_action( "load-{$page}", array( $this, 'take_action' ), 49 );
add_action( "load-{$page}", array( $this, 'handle_upload' ), 49 );
if ( $this->admin_header_callback ) {
add_action( "admin_head-{$page}", $this->admin_header_callback, 51 );
}
}
/**
* Sets up the enqueue for the CSS & JavaScript files.
*
* @since 3.0.0
*/
public function admin_load() {
get_current_screen()->add_help_tab(
array(
'id' => 'overview',
'title' => __( 'Overview' ),
'content' =>
'<p>' . __( 'You can customize the look of your site without touching any of your theme&#8217;s code by using a custom background. Your background can be an image or a color.' ) . '</p>' .
'<p>' . __( 'To use a background image, simply upload it or choose an image that has already been uploaded to your Media Library by clicking the &#8220;Choose Image&#8221; 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.' ) . '</p>' .
'<p>' . __( 'You can also choose a background color by clicking the Select Color button and either typing in a legitimate HTML hex value, e.g. &#8220;#ff0000&#8221; for red, or by choosing a color using the color picker.' ) . '</p>' .
'<p>' . __( 'Do not forget to click on the Save Changes button when you are finished.' ) . '</p>',
)
);
get_current_screen()->set_help_sidebar(
'<p><strong>' . __( 'For more information:' ) . '</strong></p>' .
'<p>' . __( '<a href="https://codex.wordpress.org/Appearance_Background_Screen">Documentation on Custom Background</a>' ) . '</p>' .
'<p>' . __( '<a href="https://wordpress.org/support/forums/">Support forums</a>' ) . '</p>'
);
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() {
?>
<div class="wrap" id="custom-background">
<h1><?php _e( 'Custom Background' ); ?></h1>
<?php
if ( current_user_can( 'customize' ) ) {
$message = sprintf(
/* translators: %s: URL to background image configuration in Customizer. */
__( 'You can now manage and live-preview Custom Backgrounds in the <a href="%s">Customizer</a>.' ),
admin_url( 'customize.php?autofocus[control]=background_image' )
);
wp_admin_notice(
$message,
array(
'type' => 'info',
'additional_classes' => array( 'hide-if-no-customize' ),
)
);
}
if ( ! empty( $this->updated ) ) {
$updated_message = sprintf(
/* translators: %s: Home URL. */
__( 'Background updated. <a href="%s">Visit your site</a> to see how it looks.' ),
esc_url( home_url( '/' ) )
);
wp_admin_notice(
$updated_message,
array(
'id' => 'message',
'additional_classes' => array( 'updated' ),
)
);
}
?>
<h2><?php _e( 'Background Image' ); ?></h2>
<table class="form-table" role="presentation">
<tbody>
<tr>
<th scope="row"><?php _e( 'Preview' ); ?></th>
<td>
<?php
if ( $this->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;";
}
?>
<div id="custom-background-image" style="<?php echo $background_styles; ?>"><?php // Must be double quote, see above. ?>
<?php if ( $background_image_thumb ) { ?>
<img class="custom-background-image" src="<?php echo $background_image_thumb; ?>" style="visibility:hidden;" alt="" /><br />
<img class="custom-background-image" src="<?php echo $background_image_thumb; ?>" style="visibility:hidden;" alt="" />
<?php } ?>
</div>
<?php } ?>
</td>
</tr>
<?php if ( get_background_image() ) : ?>
<tr>
<th scope="row"><?php _e( 'Remove Image' ); ?></th>
<td>
<form method="post">
<?php wp_nonce_field( 'custom-background-remove', '_wpnonce-custom-background-remove' ); ?>
<?php submit_button( __( 'Remove Background Image' ), '', 'remove-background', false ); ?><br />
<?php _e( 'This will remove the background image. You will not be able to restore any customizations.' ); ?>
</form>
</td>
</tr>
<?php endif; ?>
<?php $default_image = get_theme_support( 'custom-background', 'default-image' ); ?>
<?php if ( $default_image && get_background_image() !== $default_image ) : ?>
<tr>
<th scope="row"><?php _e( 'Restore Original Image' ); ?></th>
<td>
<form method="post">
<?php wp_nonce_field( 'custom-background-reset', '_wpnonce-custom-background-reset' ); ?>
<?php submit_button( __( 'Restore Original Image' ), '', 'reset-background', false ); ?><br />
<?php _e( 'This will restore the original background image. You will not be able to restore any customizations.' ); ?>
</form>
</td>
</tr>
<?php endif; ?>
<?php if ( current_user_can( 'upload_files' ) ) : ?>
<tr>
<th scope="row"><?php _e( 'Select Image' ); ?></th>
<td><form enctype="multipart/form-data" id="upload-form" class="wp-upload-form" method="post">
<p>
<label for="upload"><?php _e( 'Choose an image from your computer:' ); ?></label><br />
<input type="file" id="upload" name="import" />
<input type="hidden" name="action" value="save" />
<?php wp_nonce_field( 'custom-background-upload', '_wpnonce-custom-background-upload' ); ?>
<?php submit_button( __( 'Upload' ), '', 'submit', false ); ?>
</p>
<p>
<label for="choose-from-library-link"><?php _e( 'Or choose an image from your media library:' ); ?></label><br />
<button id="choose-from-library-link" class="button"
data-choose="<?php esc_attr_e( 'Choose a Background Image' ); ?>"
data-update="<?php esc_attr_e( 'Set as background' ); ?>"><?php _e( 'Choose Image' ); ?></button>
</p>
</form>
</td>
</tr>
<?php endif; ?>
</tbody>
</table>
<h2><?php _e( 'Display Options' ); ?></h2>
<form method="post">
<table class="form-table" role="presentation">
<tbody>
<?php if ( get_background_image() ) : ?>
<input name="background-preset" type="hidden" value="custom">
<?php
$background_position = sprintf(
'%s %s',
get_theme_mod( 'background_position_x', get_theme_support( 'custom-background', 'default-position-x' ) ),
get_theme_mod( 'background_position_y', get_theme_support( 'custom-background', 'default-position-y' ) )
);
$background_position_options = array(
array(
'left top' => array(
'label' => __( 'Top Left' ),
'icon' => 'dashicons dashicons-arrow-left-alt',
),
'center top' => array(
'label' => __( 'Top' ),
'icon' => 'dashicons dashicons-arrow-up-alt',
),
'right top' => array(
'label' => __( 'Top Right' ),
'icon' => 'dashicons dashicons-arrow-right-alt',
),
),
array(
'left center' => array(
'label' => __( 'Left' ),
'icon' => 'dashicons dashicons-arrow-left-alt',
),
'center center' => array(
'label' => __( 'Center' ),
'icon' => 'background-position-center-icon',
),
'right center' => array(
'label' => __( 'Right' ),
'icon' => 'dashicons dashicons-arrow-right-alt',
),
),
array(
'left bottom' => array(
'label' => __( 'Bottom Left' ),
'icon' => 'dashicons dashicons-arrow-left-alt',
),
'center bottom' => array(
'label' => __( 'Bottom' ),
'icon' => 'dashicons dashicons-arrow-down-alt',
),
'right bottom' => array(
'label' => __( 'Bottom Right' ),
'icon' => 'dashicons dashicons-arrow-right-alt',
),
),
);
?>
<tr>
<th scope="row"><?php _e( 'Image Position' ); ?></th>
<td><fieldset><legend class="screen-reader-text"><span>
<?php
/* translators: Hidden accessibility text. */
_e( 'Image Position' );
?>
</span></legend>
<div class="background-position-control">
<?php foreach ( $background_position_options as $group ) : ?>
<div class="button-group">
<?php foreach ( $group as $value => $input ) : ?>
<label>
<input class="ui-helper-hidden-accessible" name="background-position" type="radio" value="<?php echo esc_attr( $value ); ?>"<?php checked( $value, $background_position ); ?>>
<span class="button display-options position"><span class="<?php echo esc_attr( $input['icon'] ); ?>" aria-hidden="true"></span></span>
<span class="screen-reader-text"><?php echo $input['label']; ?></span>
</label>
<?php endforeach; ?>
</div>
<?php endforeach; ?>
</div>
</fieldset></td>
</tr>
<tr>
<th scope="row"><label for="background-size"><?php _e( 'Image Size' ); ?></label></th>
<td><fieldset><legend class="screen-reader-text"><span>
<?php
/* translators: Hidden accessibility text. */
_e( 'Image Size' );
?>
</span></legend>
<select id="background-size" name="background-size">
<option value="auto"<?php selected( 'auto', get_theme_mod( 'background_size', get_theme_support( 'custom-background', 'default-size' ) ) ); ?>><?php _ex( 'Original', 'Original Size' ); ?></option>
<option value="contain"<?php selected( 'contain', get_theme_mod( 'background_size', get_theme_support( 'custom-background', 'default-size' ) ) ); ?>><?php _e( 'Fit to Screen' ); ?></option>
<option value="cover"<?php selected( 'cover', get_theme_mod( 'background_size', get_theme_support( 'custom-background', 'default-size' ) ) ); ?>><?php _e( 'Fill Screen' ); ?></option>
</select>
</fieldset></td>
</tr>
<tr>
<th scope="row"><?php _ex( 'Repeat', 'Background Repeat' ); ?></th>
<td><fieldset><legend class="screen-reader-text"><span>
<?php
/* translators: Hidden accessibility text. */
_ex( 'Repeat', 'Background Repeat' );
?>
</span></legend>
<input name="background-repeat" type="hidden" value="no-repeat">
<label><input type="checkbox" name="background-repeat" value="repeat"<?php checked( 'repeat', get_theme_mod( 'background_repeat', get_theme_support( 'custom-background', 'default-repeat' ) ) ); ?>> <?php _e( 'Repeat Background Image' ); ?></label>
</fieldset></td>
</tr>
<tr>
<th scope="row"><?php _ex( 'Scroll', 'Background Scroll' ); ?></th>
<td><fieldset><legend class="screen-reader-text"><span>
<?php
/* translators: Hidden accessibility text. */
_ex( 'Scroll', 'Background Scroll' );
?>
</span></legend>
<input name="background-attachment" type="hidden" value="fixed">
<label><input name="background-attachment" type="checkbox" value="scroll" <?php checked( 'scroll', get_theme_mod( 'background_attachment', get_theme_support( 'custom-background', 'default-attachment' ) ) ); ?>> <?php _e( 'Scroll with Page' ); ?></label>
</fieldset></td>
</tr>
<?php endif; // get_background_image() ?>
<tr>
<th scope="row"><?php _e( 'Background Color' ); ?></th>
<td><fieldset><legend class="screen-reader-text"><span>
<?php
/* translators: Hidden accessibility text. */
_e( 'Background Color' );
?>
</span></legend>
<?php
$default_color = '';
if ( current_theme_supports( 'custom-background', 'default-color' ) ) {
$default_color = ' data-default-color="#' . esc_attr( get_theme_support( 'custom-background', 'default-color' ) ) . '"';
}
?>
<input type="text" name="background-color" id="background-color" value="#<?php echo esc_attr( get_background_color() ); ?>"<?php echo $default_color; ?>>
</fieldset></td>
</tr>
</tbody>
</table>
<?php wp_nonce_field( 'custom-background' ); ?>
<?php submit_button( null, 'primary', 'save-background-options' ); ?>
</form>
</div>
<?php
}
/**
* Handles an Image upload for the background image.
*
* @since 3.0.0
*/
public function handle_upload() {
if ( empty( $_FILES ) ) {
return;
}
check_admin_referer( 'custom-background-upload', '_wpnonce-custom-background-upload' );
$overrides = array( 'test_form' => false );
$uploaded_file = $_FILES['import'];
$wp_filetype = wp_check_filetype_and_ext( $uploaded_file['tmp_name'], $uploaded_file['name'] );
if ( ! wp_match_mime_types( 'image', $wp_filetype['type'] ) ) {
wp_die( __( 'The uploaded file is not a valid image. Please try again.' ) );
}
$file = wp_handle_upload( $uploaded_file, $overrides );
if ( isset( $file['error'] ) ) {
wp_die( $file['error'] );
}
$url = $file['url'];
$type = $file['type'];
$file = $file['file'];
$filename = wp_basename( $file );
// Construct the attachment array.
$attachment = array(
'post_title' => $filename,
'post_content' => $url,
'post_mime_type' => $type,
'guid' => $url,
'context' => 'custom-background',
);
// Save the data.
$id = wp_insert_attachment( $attachment, $file );
// Add the metadata.
wp_update_attachment_metadata( $id, wp_generate_attachment_metadata( $id, $file ) );
update_post_meta( $id, '_wp_attachment_is_custom_background', get_option( 'stylesheet' ) );
set_theme_mod( 'background_image', sanitize_url( $url ) );
$thumbnail = wp_get_attachment_image_src( $id, 'thumbnail' );
set_theme_mod( 'background_image_thumb', sanitize_url( $thumbnail[0] ) );
/** This filter is documented in wp-admin/includes/class-custom-image-header.php */
$file = apply_filters( 'wp_create_file_in_uploads', $file, $id ); // For replication.
$this->updated = true;
}
/**
* Handles Ajax request for adding custom background context to an attachment.
*
* Triggers when the user adds a new background image from the
* Media Manager.
*
* @since 4.1.0
*/
public function ajax_background_add() {
check_ajax_referer( 'background-add', 'nonce' );
if ( ! current_user_can( 'edit_theme_options' ) ) {
wp_send_json_error();
}
$attachment_id = absint( $_POST['attachment_id'] );
if ( $attachment_id < 1 ) {
wp_send_json_error();
}
update_post_meta( $attachment_id, '_wp_attachment_is_custom_background', get_stylesheet() );
wp_send_json_success();
}
/**
* @since 3.4.0
* @deprecated 3.5.0
*
* @param array $form_fields
* @return array $form_fields
*/
public function attachment_fields_to_edit( $form_fields ) {
return $form_fields;
}
/**
* @since 3.4.0
* @deprecated 3.5.0
*
* @param array $tabs
* @return array $tabs
*/
public function filter_upload_tabs( $tabs ) {
return $tabs;
}
/**
* @since 3.4.0
* @deprecated 3.5.0
*/
public function wp_set_background_image() {
check_ajax_referer( 'custom-background' );
if ( ! current_user_can( 'edit_theme_options' ) || ! isset( $_POST['attachment_id'] ) ) {
exit;
}
$attachment_id = absint( $_POST['attachment_id'] );
$sizes = array_keys(
/** This filter is documented in wp-admin/includes/media.php */
apply_filters(
'image_size_names_choose',
array(
'thumbnail' => __( 'Thumbnail' ),
'medium' => __( 'Medium' ),
'large' => __( 'Large' ),
'full' => __( 'Full Size' ),
)
)
);
$size = 'thumbnail';
if ( in_array( $_POST['size'], $sizes, true ) ) {
$size = esc_attr( $_POST['size'] );
}
update_post_meta( $attachment_id, '_wp_attachment_is_custom_background', get_option( 'stylesheet' ) );
$url = wp_get_attachment_image_src( $attachment_id, $size );
$thumbnail = wp_get_attachment_image_src( $attachment_id, 'thumbnail' );
set_theme_mod( 'background_image', sanitize_url( $url[0] ) );
set_theme_mod( 'background_image_thumb', sanitize_url( $thumbnail[0] ) );
exit;
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,141 @@
<?php
/**
* Upgrade API: File_Upload_Upgrader class
*
* @package WordPress
* @subpackage Upgrader
* @since 4.6.0
*/
/**
* Core class used for handling file uploads.
*
* This class handles the upload process and passes it as if it's a local file
* to the Upgrade/Installer functions.
*
* @since 2.8.0
* @since 4.6.0 Moved to its own file from wp-admin/includes/class-wp-upgrader.php.
*/
#[AllowDynamicProperties]
class File_Upload_Upgrader {
/**
* The full path to the file package.
*
* @since 2.8.0
* @var string $package
*/
public $package;
/**
* The name of the file.
*
* @since 2.8.0
* @var string $filename
*/
public $filename;
/**
* The ID of the attachment post for this file.
*
* @since 3.3.0
* @var int $id
*/
public $id = 0;
/**
* Construct the upgrader for a form.
*
* @since 2.8.0
*
* @param string $form The name of the form the file was uploaded from.
* @param string $urlholder The name of the `GET` parameter that holds the filename.
*/
public function __construct( $form, $urlholder ) {
if ( empty( $_FILES[ $form ]['name'] ) && empty( $_GET[ $urlholder ] ) ) {
wp_die( __( 'Please select a file' ) );
}
// Handle a newly uploaded file. Else, assume it's already been uploaded.
if ( ! empty( $_FILES ) ) {
$overrides = array(
'test_form' => 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'] );
wp_die( __( 'Incompatible Archive.' ) );
}
}
$this->filename = $_FILES[ $form ]['name'];
$this->package = $file['file'];
// Construct the attachment array.
$attachment = array(
'post_title' => $this->filename,
'post_content' => $file['url'],
'post_mime_type' => $file['type'],
'guid' => $file['url'],
'context' => 'upgrader',
'post_status' => 'private',
);
// Save the data.
$this->id = wp_insert_attachment( $attachment, $file['file'] );
// Schedule a cleanup for 2 hours from now in case of failed installation.
wp_schedule_single_event( time() + 2 * HOUR_IN_SECONDS, 'upgrader_scheduled_cleanup', array( $this->id ) );
} elseif ( is_numeric( $_GET[ $urlholder ] ) ) {
// Numeric Package = previously uploaded file, see above.
$this->id = (int) $_GET[ $urlholder ];
$attachment = get_post( $this->id );
if ( empty( $attachment ) ) {
wp_die( __( 'Please select a file' ) );
}
$this->filename = $attachment->post_title;
$this->package = get_attached_file( $attachment->ID );
} else {
// Else, It's set to something, Back compat for plugins using the old (pre-3.3) File_Uploader handler.
$uploads = wp_upload_dir();
if ( ! ( $uploads && false === $uploads['error'] ) ) {
wp_die( $uploads['error'] );
}
$this->filename = sanitize_file_name( $_GET[ $urlholder ] );
$this->package = $uploads['basedir'] . '/' . $this->filename;
if ( ! str_starts_with( realpath( $this->package ), realpath( $uploads['basedir'] ) ) ) {
wp_die( __( 'Please select a file' ) );
}
}
}
/**
* Deletes the attachment/uploaded file.
*
* @since 3.2.2
*
* @return bool Whether the cleanup was successful.
*/
public function cleanup() {
if ( $this->id ) {
wp_delete_attachment( $this->id );
} elseif ( file_exists( $this->package ) ) {
return @unlink( $this->package );
}
return true;
}
}

View File

@ -0,0 +1,186 @@
<?php
/**
* PemFTP - An Ftp implementation in pure PHP
*
* @package PemFTP
* @since 2.5.0
*
* @version 1.0
* @copyright Alexey Dotsenko
* @author Alexey Dotsenko
* @link https://www.phpclasses.org/package/1743-PHP-FTP-client-in-pure-PHP.html
* @license LGPL https://opensource.org/licenses/lgpl-license.html
*/
/**
* FTP implementation using fsockopen to connect.
*
* @package PemFTP
* @subpackage Pure
* @since 2.5.0
*
* @version 1.0
* @copyright Alexey Dotsenko
* @author Alexey Dotsenko
* @link https://www.phpclasses.org/package/1743-PHP-FTP-client-in-pure-PHP.html
* @license LGPL https://opensource.org/licenses/lgpl-license.html
*/
class ftp_pure extends ftp_base {
function __construct($verb=FALSE, $le=FALSE) {
parent::__construct(false, $verb, $le);
}
// <!-- --------------------------------------------------------------------------------------- -->
// <!-- Private functions -->
// <!-- --------------------------------------------------------------------------------------- -->
function _settimeout($sock) {
if(!@stream_set_timeout($sock, $this->_timeout)) {
$this->PushError('_settimeout','socket set send timeout');
$this->_quit();
return FALSE;
}
return TRUE;
}
function _connect($host, $port) {
$this->SendMSG("Creating socket");
$sock = @fsockopen($host, $port, $errno, $errstr, $this->_timeout);
if (!$sock) {
$this->PushError('_connect','socket connect failed', $errstr." (".$errno.")");
return FALSE;
}
$this->_connected=true;
return $sock;
}
function _readmsg($fnction="_readmsg"){
if(!$this->_connected) {
$this->PushError($fnction, 'Connect first');
return FALSE;
}
$result=true;
$this->_message="";
$this->_code=0;
$go=true;
do {
$tmp=@fgets($this->_ftp_control_sock, 512);
if($tmp===false) {
$go=$result=false;
$this->PushError($fnction,'Read failed');
} else {
$this->_message.=$tmp;
if(preg_match("/^([0-9]{3})(-(.*[".CRLF."]{1,2})+\\1)? [^".CRLF."]+[".CRLF."]{1,2}$/", $this->_message, $regs)) $go=false;
}
} while($go);
if($this->LocalEcho) echo "GET < ".rtrim($this->_message, CRLF).CRLF;
$this->_code=(int)$regs[1];
return $result;
}
function _exec($cmd, $fnction="_exec") {
if(!$this->_ready) {
$this->PushError($fnction,'Connect first');
return FALSE;
}
if($this->LocalEcho) echo "PUT > ",$cmd,CRLF;
$status=@fputs($this->_ftp_control_sock, $cmd.CRLF);
if($status===false) {
$this->PushError($fnction,'socket write failed');
return FALSE;
}
$this->_lastaction=time();
if(!$this->_readmsg($fnction)) return FALSE;
return TRUE;
}
function _data_prepare($mode=FTP_ASCII) {
if(!$this->_settype($mode)) return FALSE;
if($this->_passive) {
if(!$this->_exec("PASV", "pasv")) {
$this->_data_close();
return FALSE;
}
if(!$this->_checkCode()) {
$this->_data_close();
return FALSE;
}
$ip_port = explode(",", preg_replace("/^.+ \\(?([0-9]{1,3},[0-9]{1,3},[0-9]{1,3},[0-9]{1,3},[0-9]+,[0-9]+)\\)?.*$/s", "\\1", $this->_message));
$this->_datahost=$ip_port[0].".".$ip_port[1].".".$ip_port[2].".".$ip_port[3];
$this->_dataport=(((int)$ip_port[4])<<8) + ((int)$ip_port[5]);
$this->SendMSG("Connecting to ".$this->_datahost.":".$this->_dataport);
$this->_ftp_data_sock=@fsockopen($this->_datahost, $this->_dataport, $errno, $errstr, $this->_timeout);
if(!$this->_ftp_data_sock) {
$this->PushError("_data_prepare","fsockopen fails", $errstr." (".$errno.")");
$this->_data_close();
return FALSE;
}
else $this->_ftp_data_sock;
} else {
$this->SendMSG("Only passive connections available!");
return FALSE;
}
return TRUE;
}
function _data_read($mode=FTP_ASCII, $fp=NULL) {
if(is_resource($fp)) $out=0;
else $out="";
if(!$this->_passive) {
$this->SendMSG("Only passive connections available!");
return FALSE;
}
while (!feof($this->_ftp_data_sock)) {
$block=fread($this->_ftp_data_sock, $this->_ftp_buff_size);
if($mode!=FTP_BINARY) $block=preg_replace("/\r\n|\r|\n/", $this->_eol_code[$this->OS_local], $block);
if(is_resource($fp)) $out+=fwrite($fp, $block, strlen($block));
else $out.=$block;
}
return $out;
}
function _data_write($mode=FTP_ASCII, $fp=NULL) {
if(is_resource($fp)) $out=0;
else $out="";
if(!$this->_passive) {
$this->SendMSG("Only passive connections available!");
return FALSE;
}
if(is_resource($fp)) {
while(!feof($fp)) {
$block=fread($fp, $this->_ftp_buff_size);
if(!$this->_data_write_block($mode, $block)) return false;
}
} elseif(!$this->_data_write_block($mode, $fp)) return false;
return TRUE;
}
function _data_write_block($mode, $block) {
if($mode!=FTP_BINARY) $block=preg_replace("/\r\n|\r|\n/", $this->_eol_code[$this->OS_remote], $block);
do {
if(($t=@fwrite($this->_ftp_data_sock, $block))===FALSE) {
$this->PushError("_data_write","Can't write to socket");
return FALSE;
}
$block=substr($block, $t);
} while(!empty($block));
return true;
}
function _data_close() {
@fclose($this->_ftp_data_sock);
$this->SendMSG("Disconnected data from remote host");
return TRUE;
}
function _quit($force=FALSE) {
if($this->_connected or $force) {
@fclose($this->_ftp_control_sock);
$this->_connected=false;
$this->SendMSG("Socket closed");
}
}
}
?>

View File

@ -0,0 +1,246 @@
<?php
/**
* PemFTP - An Ftp implementation in pure PHP
*
* @package PemFTP
* @since 2.5.0
*
* @version 1.0
* @copyright Alexey Dotsenko
* @author Alexey Dotsenko
* @link https://www.phpclasses.org/package/1743-PHP-FTP-client-in-pure-PHP.html
* @license LGPL https://opensource.org/licenses/lgpl-license.html
*/
/**
* Socket Based FTP implementation
*
* @package PemFTP
* @subpackage Socket
* @since 2.5.0
*
* @version 1.0
* @copyright Alexey Dotsenko
* @author Alexey Dotsenko
* @link https://www.phpclasses.org/package/1743-PHP-FTP-client-in-pure-PHP.html
* @license LGPL https://opensource.org/licenses/lgpl-license.html
*/
class ftp_sockets extends ftp_base {
function __construct($verb=FALSE, $le=FALSE) {
parent::__construct(true, $verb, $le);
}
// <!-- --------------------------------------------------------------------------------------- -->
// <!-- Private functions -->
// <!-- --------------------------------------------------------------------------------------- -->
function _settimeout($sock) {
if(!@socket_set_option($sock, SOL_SOCKET, SO_RCVTIMEO, array("sec"=>$this->_timeout, "usec"=>0))) {
$this->PushError('_connect','socket set receive timeout',socket_strerror(socket_last_error($sock)));
@socket_close($sock);
return FALSE;
}
if(!@socket_set_option($sock, SOL_SOCKET , SO_SNDTIMEO, array("sec"=>$this->_timeout, "usec"=>0))) {
$this->PushError('_connect','socket set send timeout',socket_strerror(socket_last_error($sock)));
@socket_close($sock);
return FALSE;
}
return true;
}
function _connect($host, $port) {
$this->SendMSG("Creating socket");
if(!($sock = @socket_create(AF_INET, SOCK_STREAM, SOL_TCP))) {
$this->PushError('_connect','socket create failed',socket_strerror(socket_last_error($sock)));
return FALSE;
}
if(!$this->_settimeout($sock)) return FALSE;
$this->SendMSG("Connecting to \"".$host.":".$port."\"");
if (!($res = @socket_connect($sock, $host, $port))) {
$this->PushError('_connect','socket connect failed',socket_strerror(socket_last_error($sock)));
@socket_close($sock);
return FALSE;
}
$this->_connected=true;
return $sock;
}
function _readmsg($fnction="_readmsg"){
if(!$this->_connected) {
$this->PushError($fnction,'Connect first');
return FALSE;
}
$result=true;
$this->_message="";
$this->_code=0;
$go=true;
do {
$tmp=@socket_read($this->_ftp_control_sock, 4096, PHP_BINARY_READ);
if($tmp===false) {
$go=$result=false;
$this->PushError($fnction,'Read failed', socket_strerror(socket_last_error($this->_ftp_control_sock)));
} else {
$this->_message.=$tmp;
$go = !preg_match("/^([0-9]{3})(-.+\\1)? [^".CRLF."]+".CRLF."$/Us", $this->_message, $regs);
}
} while($go);
if($this->LocalEcho) echo "GET < ".rtrim($this->_message, CRLF).CRLF;
$this->_code=(int)$regs[1];
return $result;
}
function _exec($cmd, $fnction="_exec") {
if(!$this->_ready) {
$this->PushError($fnction,'Connect first');
return FALSE;
}
if($this->LocalEcho) echo "PUT > ",$cmd,CRLF;
$status=@socket_write($this->_ftp_control_sock, $cmd.CRLF);
if($status===false) {
$this->PushError($fnction,'socket write failed', socket_strerror(socket_last_error($this->stream)));
return FALSE;
}
$this->_lastaction=time();
if(!$this->_readmsg($fnction)) return FALSE;
return TRUE;
}
function _data_prepare($mode=FTP_ASCII) {
if(!$this->_settype($mode)) return FALSE;
$this->SendMSG("Creating data socket");
$this->_ftp_data_sock = @socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($this->_ftp_data_sock < 0) {
$this->PushError('_data_prepare','socket create failed',socket_strerror(socket_last_error($this->_ftp_data_sock)));
return FALSE;
}
if(!$this->_settimeout($this->_ftp_data_sock)) {
$this->_data_close();
return FALSE;
}
if($this->_passive) {
if(!$this->_exec("PASV", "pasv")) {
$this->_data_close();
return FALSE;
}
if(!$this->_checkCode()) {
$this->_data_close();
return FALSE;
}
$ip_port = explode(",", preg_replace("/^.+ \\(?([0-9]{1,3},[0-9]{1,3},[0-9]{1,3},[0-9]{1,3},[0-9]+,[0-9]+)\\)?.*$/s", "\\1", $this->_message));
$this->_datahost=$ip_port[0].".".$ip_port[1].".".$ip_port[2].".".$ip_port[3];
$this->_dataport=(((int)$ip_port[4])<<8) + ((int)$ip_port[5]);
$this->SendMSG("Connecting to ".$this->_datahost.":".$this->_dataport);
if(!@socket_connect($this->_ftp_data_sock, $this->_datahost, $this->_dataport)) {
$this->PushError("_data_prepare","socket_connect", socket_strerror(socket_last_error($this->_ftp_data_sock)));
$this->_data_close();
return FALSE;
}
else $this->_ftp_temp_sock=$this->_ftp_data_sock;
} else {
if(!@socket_getsockname($this->_ftp_control_sock, $addr, $port)) {
$this->PushError("_data_prepare","cannot get control socket information", socket_strerror(socket_last_error($this->_ftp_control_sock)));
$this->_data_close();
return FALSE;
}
if(!@socket_bind($this->_ftp_data_sock,$addr)){
$this->PushError("_data_prepare","cannot bind data socket", socket_strerror(socket_last_error($this->_ftp_data_sock)));
$this->_data_close();
return FALSE;
}
if(!@socket_listen($this->_ftp_data_sock)) {
$this->PushError("_data_prepare","cannot listen data socket", socket_strerror(socket_last_error($this->_ftp_data_sock)));
$this->_data_close();
return FALSE;
}
if(!@socket_getsockname($this->_ftp_data_sock, $this->_datahost, $this->_dataport)) {
$this->PushError("_data_prepare","cannot get data socket information", socket_strerror(socket_last_error($this->_ftp_data_sock)));
$this->_data_close();
return FALSE;
}
if(!$this->_exec('PORT '.str_replace('.',',',$this->_datahost.'.'.($this->_dataport>>8).'.'.($this->_dataport&0x00FF)), "_port")) {
$this->_data_close();
return FALSE;
}
if(!$this->_checkCode()) {
$this->_data_close();
return FALSE;
}
}
return TRUE;
}
function _data_read($mode=FTP_ASCII, $fp=NULL) {
$NewLine=$this->_eol_code[$this->OS_local];
if(is_resource($fp)) $out=0;
else $out="";
if(!$this->_passive) {
$this->SendMSG("Connecting to ".$this->_datahost.":".$this->_dataport);
$this->_ftp_temp_sock=socket_accept($this->_ftp_data_sock);
if($this->_ftp_temp_sock===FALSE) {
$this->PushError("_data_read","socket_accept", socket_strerror(socket_last_error($this->_ftp_temp_sock)));
$this->_data_close();
return FALSE;
}
}
while(($block=@socket_read($this->_ftp_temp_sock, $this->_ftp_buff_size, PHP_BINARY_READ))!==false) {
if($block==="") break;
if($mode!=FTP_BINARY) $block=preg_replace("/\r\n|\r|\n/", $this->_eol_code[$this->OS_local], $block);
if(is_resource($fp)) $out+=fwrite($fp, $block, strlen($block));
else $out.=$block;
}
return $out;
}
function _data_write($mode=FTP_ASCII, $fp=NULL) {
$NewLine=$this->_eol_code[$this->OS_local];
if(is_resource($fp)) $out=0;
else $out="";
if(!$this->_passive) {
$this->SendMSG("Connecting to ".$this->_datahost.":".$this->_dataport);
$this->_ftp_temp_sock=socket_accept($this->_ftp_data_sock);
if($this->_ftp_temp_sock===FALSE) {
$this->PushError("_data_write","socket_accept", socket_strerror(socket_last_error($this->_ftp_temp_sock)));
$this->_data_close();
return false;
}
}
if(is_resource($fp)) {
while(!feof($fp)) {
$block=fread($fp, $this->_ftp_buff_size);
if(!$this->_data_write_block($mode, $block)) return false;
}
} elseif(!$this->_data_write_block($mode, $fp)) return false;
return true;
}
function _data_write_block($mode, $block) {
if($mode!=FTP_BINARY) $block=preg_replace("/\r\n|\r|\n/", $this->_eol_code[$this->OS_remote], $block);
do {
if(($t=@socket_write($this->_ftp_temp_sock, $block))===FALSE) {
$this->PushError("_data_write","socket_write", socket_strerror(socket_last_error($this->_ftp_temp_sock)));
$this->_data_close();
return FALSE;
}
$block=substr($block, $t);
} while(!empty($block));
return true;
}
function _data_close() {
@socket_close($this->_ftp_temp_sock);
@socket_close($this->_ftp_data_sock);
$this->SendMSG("Disconnected data from remote host");
return TRUE;
}
function _quit() {
if($this->_connected) {
@socket_close($this->_ftp_control_sock);
$this->_connected=false;
$this->SendMSG("Socket closed");
}
}
}
?>

View File

@ -0,0 +1,913 @@
<?php
/**
* PemFTP - An Ftp implementation in pure PHP
*
* @package PemFTP
* @since 2.5.0
*
* @version 1.0
* @copyright Alexey Dotsenko
* @author Alexey Dotsenko
* @link https://www.phpclasses.org/package/1743-PHP-FTP-client-in-pure-PHP.html
* @license LGPL https://opensource.org/licenses/lgpl-license.html
*/
/**
* Defines the newline characters, if not defined already.
*
* This can be redefined.
*
* @since 2.5.0
* @var string
*/
if(!defined('CRLF')) define('CRLF',"\r\n");
/**
* Sets whatever to autodetect ASCII mode.
*
* This can be redefined.
*
* @since 2.5.0
* @var int
*/
if(!defined("FTP_AUTOASCII")) define("FTP_AUTOASCII", -1);
/**
*
* This can be redefined.
* @since 2.5.0
* @var int
*/
if(!defined("FTP_BINARY")) define("FTP_BINARY", 1);
/**
*
* This can be redefined.
* @since 2.5.0
* @var int
*/
if(!defined("FTP_ASCII")) define("FTP_ASCII", 0);
/**
* Whether to force FTP.
*
* This can be redefined.
*
* @since 2.5.0
* @var bool
*/
if(!defined('FTP_FORCE')) define('FTP_FORCE', true);
/**
* @since 2.5.0
* @var string
*/
define('FTP_OS_Unix','u');
/**
* @since 2.5.0
* @var string
*/
define('FTP_OS_Windows','w');
/**
* @since 2.5.0
* @var string
*/
define('FTP_OS_Mac','m');
/**
* PemFTP base class
*
*/
class ftp_base {
/* Public variables */
var $LocalEcho;
var $Verbose;
var $OS_local;
var $OS_remote;
/* Private variables */
var $_lastaction;
var $_errors;
var $_type;
var $_umask;
var $_timeout;
var $_passive;
var $_host;
var $_fullhost;
var $_port;
var $_datahost;
var $_dataport;
var $_ftp_control_sock;
var $_ftp_data_sock;
var $_ftp_temp_sock;
var $_ftp_buff_size;
var $_login;
var $_password;
var $_connected;
var $_ready;
var $_code;
var $_message;
var $_can_restore;
var $_port_available;
var $_curtype;
var $_features;
var $_error_array;
var $AuthorizedTransferMode;
var $OS_FullName;
var $_eol_code;
var $AutoAsciiExt;
/* Constructor */
function __construct($port_mode=FALSE, $verb=FALSE, $le=FALSE) {
$this->LocalEcho=$le;
$this->Verbose=$verb;
$this->_lastaction=NULL;
$this->_error_array=array();
$this->_eol_code=array(FTP_OS_Unix=>"\n", FTP_OS_Mac=>"\r", FTP_OS_Windows=>"\r\n");
$this->AuthorizedTransferMode=array(FTP_AUTOASCII, FTP_ASCII, FTP_BINARY);
$this->OS_FullName=array(FTP_OS_Unix => 'UNIX', FTP_OS_Windows => 'WINDOWS', FTP_OS_Mac => 'MACOS');
$this->AutoAsciiExt=array("ASP","BAT","C","CPP","CSS","CSV","JS","H","HTM","HTML","SHTML","INI","LOG","PHP3","PHTML","PL","PERL","SH","SQL","TXT");
$this->_port_available=($port_mode==TRUE);
$this->SendMSG("Staring FTP client class".($this->_port_available?"":" without PORT mode support"));
$this->_connected=FALSE;
$this->_ready=FALSE;
$this->_can_restore=FALSE;
$this->_code=0;
$this->_message="";
$this->_ftp_buff_size=4096;
$this->_curtype=NULL;
$this->SetUmask(0022);
$this->SetType(FTP_AUTOASCII);
$this->SetTimeout(30);
$this->Passive(!$this->_port_available);
$this->_login="anonymous";
$this->_password="anon@ftp.com";
$this->_features=array();
$this->OS_local=FTP_OS_Unix;
$this->OS_remote=FTP_OS_Unix;
$this->features=array();
if(strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') $this->OS_local=FTP_OS_Windows;
elseif(strtoupper(substr(PHP_OS, 0, 3)) === 'MAC') $this->OS_local=FTP_OS_Mac;
}
function ftp_base($port_mode=FALSE) {
$this->__construct($port_mode);
}
// <!-- --------------------------------------------------------------------------------------- -->
// <!-- Public functions -->
// <!-- --------------------------------------------------------------------------------------- -->
function parselisting($line) {
$is_windows = ($this->OS_remote == FTP_OS_Windows);
if ($is_windows && preg_match("/([0-9]{2})-([0-9]{2})-([0-9]{2}) +([0-9]{2}):([0-9]{2})(AM|PM) +([0-9]+|<DIR>) +(.+)/",$line,$lucifer)) {
$b = array();
if ($lucifer[3]<70) { $lucifer[3]+=2000; } else { $lucifer[3]+=1900; } // 4digit year fix
$b['isdir'] = ($lucifer[7]=="<DIR>");
if ( $b['isdir'] )
$b['type'] = 'd';
else
$b['type'] = 'f';
$b['size'] = $lucifer[7];
$b['month'] = $lucifer[1];
$b['day'] = $lucifer[2];
$b['year'] = $lucifer[3];
$b['hour'] = $lucifer[4];
$b['minute'] = $lucifer[5];
$b['time'] = @mktime($lucifer[4]+(strcasecmp($lucifer[6],"PM")==0?12:0),$lucifer[5],0,$lucifer[1],$lucifer[2],$lucifer[3]);
$b['am/pm'] = $lucifer[6];
$b['name'] = $lucifer[8];
} else if (!$is_windows && $lucifer=preg_split("/[ ]/",$line,9,PREG_SPLIT_NO_EMPTY)) {
//echo $line."\n";
$lcount=count($lucifer);
if ($lcount<8) return '';
$b = array();
$b['isdir'] = $lucifer[0][0] === "d";
$b['islink'] = $lucifer[0][0] === "l";
if ( $b['isdir'] )
$b['type'] = 'd';
elseif ( $b['islink'] )
$b['type'] = 'l';
else
$b['type'] = 'f';
$b['perms'] = $lucifer[0];
$b['number'] = $lucifer[1];
$b['owner'] = $lucifer[2];
$b['group'] = $lucifer[3];
$b['size'] = $lucifer[4];
if ($lcount==8) {
sscanf($lucifer[5],"%d-%d-%d",$b['year'],$b['month'],$b['day']);
sscanf($lucifer[6],"%d:%d",$b['hour'],$b['minute']);
$b['time'] = @mktime($b['hour'],$b['minute'],0,$b['month'],$b['day'],$b['year']);
$b['name'] = $lucifer[7];
} else {
$b['month'] = $lucifer[5];
$b['day'] = $lucifer[6];
if (preg_match("/([0-9]{2}):([0-9]{2})/",$lucifer[7],$l2)) {
$b['year'] = gmdate("Y");
$b['hour'] = $l2[1];
$b['minute'] = $l2[2];
} else {
$b['year'] = $lucifer[7];
$b['hour'] = 0;
$b['minute'] = 0;
}
$b['time'] = strtotime(sprintf("%d %s %d %02d:%02d",$b['day'],$b['month'],$b['year'],$b['hour'],$b['minute']));
$b['name'] = $lucifer[8];
}
}
return $b;
}
function SendMSG($message = "", $crlf=true) {
if ($this->Verbose) {
echo $message.($crlf?CRLF:"");
flush();
}
return TRUE;
}
function SetType($mode=FTP_AUTOASCII) {
if(!in_array($mode, $this->AuthorizedTransferMode)) {
$this->SendMSG("Wrong type");
return FALSE;
}
$this->_type=$mode;
$this->SendMSG("Transfer type: ".($this->_type==FTP_BINARY?"binary":($this->_type==FTP_ASCII?"ASCII":"auto ASCII") ) );
return TRUE;
}
function _settype($mode=FTP_ASCII) {
if($this->_ready) {
if($mode==FTP_BINARY) {
if($this->_curtype!=FTP_BINARY) {
if(!$this->_exec("TYPE I", "SetType")) return FALSE;
$this->_curtype=FTP_BINARY;
}
} elseif($this->_curtype!=FTP_ASCII) {
if(!$this->_exec("TYPE A", "SetType")) return FALSE;
$this->_curtype=FTP_ASCII;
}
} else return FALSE;
return TRUE;
}
function Passive($pasv=NULL) {
if(is_null($pasv)) $this->_passive=!$this->_passive;
else $this->_passive=$pasv;
if(!$this->_port_available and !$this->_passive) {
$this->SendMSG("Only passive connections available!");
$this->_passive=TRUE;
return FALSE;
}
$this->SendMSG("Passive mode ".($this->_passive?"on":"off"));
return TRUE;
}
function SetServer($host, $port=21, $reconnect=true) {
if(!is_long($port)) {
$this->verbose=true;
$this->SendMSG("Incorrect port syntax");
return FALSE;
} else {
$ip=@gethostbyname($host);
$dns=@gethostbyaddr($host);
if(!$ip) $ip=$host;
if(!$dns) $dns=$host;
// Validate the IPAddress PHP4 returns -1 for invalid, PHP5 false
// -1 === "255.255.255.255" which is the broadcast address which is also going to be invalid
$ipaslong = ip2long($ip);
if ( ($ipaslong == false) || ($ipaslong === -1) ) {
$this->SendMSG("Wrong host name/address \"".$host."\"");
return FALSE;
}
$this->_host=$ip;
$this->_fullhost=$dns;
$this->_port=$port;
$this->_dataport=$port-1;
}
$this->SendMSG("Host \"".$this->_fullhost."(".$this->_host."):".$this->_port."\"");
if($reconnect){
if($this->_connected) {
$this->SendMSG("Reconnecting");
if(!$this->quit(FTP_FORCE)) return FALSE;
if(!$this->connect()) return FALSE;
}
}
return TRUE;
}
function SetUmask($umask=0022) {
$this->_umask=$umask;
umask($this->_umask);
$this->SendMSG("UMASK 0".decoct($this->_umask));
return TRUE;
}
function SetTimeout($timeout=30) {
$this->_timeout=$timeout;
$this->SendMSG("Timeout ".$this->_timeout);
if($this->_connected)
if(!$this->_settimeout($this->_ftp_control_sock)) return FALSE;
return TRUE;
}
function connect($server=NULL) {
if(!empty($server)) {
if(!$this->SetServer($server)) return false;
}
if($this->_ready) return true;
$this->SendMsg('Local OS : '.$this->OS_FullName[$this->OS_local]);
if(!($this->_ftp_control_sock = $this->_connect($this->_host, $this->_port))) {
$this->SendMSG("Error : Cannot connect to remote host \"".$this->_fullhost." :".$this->_port."\"");
return FALSE;
}
$this->SendMSG("Connected to remote host \"".$this->_fullhost.":".$this->_port."\". Waiting for greeting.");
do {
if(!$this->_readmsg()) return FALSE;
if(!$this->_checkCode()) return FALSE;
$this->_lastaction=time();
} while($this->_code<200);
$this->_ready=true;
$syst=$this->systype();
if(!$syst) $this->SendMSG("Cannot detect remote OS");
else {
if(preg_match("/win|dos|novell/i", $syst[0])) $this->OS_remote=FTP_OS_Windows;
elseif(preg_match("/os/i", $syst[0])) $this->OS_remote=FTP_OS_Mac;
elseif(preg_match("/(li|u)nix/i", $syst[0])) $this->OS_remote=FTP_OS_Unix;
else $this->OS_remote=FTP_OS_Mac;
$this->SendMSG("Remote OS: ".$this->OS_FullName[$this->OS_remote]);
}
if(!$this->features()) $this->SendMSG("Cannot get features list. All supported - disabled");
else $this->SendMSG("Supported features: ".implode(", ", array_keys($this->_features)));
return TRUE;
}
function quit($force=false) {
if($this->_ready) {
if(!$this->_exec("QUIT") and !$force) return FALSE;
if(!$this->_checkCode() and !$force) return FALSE;
$this->_ready=false;
$this->SendMSG("Session finished");
}
$this->_quit();
return TRUE;
}
function login($user=NULL, $pass=NULL) {
if(!is_null($user)) $this->_login=$user;
else $this->_login="anonymous";
if(!is_null($pass)) $this->_password=$pass;
else $this->_password="anon@anon.com";
if(!$this->_exec("USER ".$this->_login, "login")) return FALSE;
if(!$this->_checkCode()) return FALSE;
if($this->_code!=230) {
if(!$this->_exec((($this->_code==331)?"PASS ":"ACCT ").$this->_password, "login")) return FALSE;
if(!$this->_checkCode()) return FALSE;
}
$this->SendMSG("Authentication succeeded");
if(empty($this->_features)) {
if(!$this->features()) $this->SendMSG("Cannot get features list. All supported - disabled");
else $this->SendMSG("Supported features: ".implode(", ", array_keys($this->_features)));
}
return TRUE;
}
function pwd() {
if(!$this->_exec("PWD", "pwd")) return FALSE;
if(!$this->_checkCode()) return FALSE;
return preg_replace("/^[0-9]{3} \"(.+)\".*$/s", "\\1", $this->_message);
}
function cdup() {
if(!$this->_exec("CDUP", "cdup")) return FALSE;
if(!$this->_checkCode()) return FALSE;
return true;
}
function chdir($pathname) {
if(!$this->_exec("CWD ".$pathname, "chdir")) return FALSE;
if(!$this->_checkCode()) return FALSE;
return TRUE;
}
function rmdir($pathname) {
if(!$this->_exec("RMD ".$pathname, "rmdir")) return FALSE;
if(!$this->_checkCode()) return FALSE;
return TRUE;
}
function mkdir($pathname) {
if(!$this->_exec("MKD ".$pathname, "mkdir")) return FALSE;
if(!$this->_checkCode()) return FALSE;
return TRUE;
}
function rename($from, $to) {
if(!$this->_exec("RNFR ".$from, "rename")) return FALSE;
if(!$this->_checkCode()) return FALSE;
if($this->_code==350) {
if(!$this->_exec("RNTO ".$to, "rename")) return FALSE;
if(!$this->_checkCode()) return FALSE;
} else return FALSE;
return TRUE;
}
function filesize($pathname) {
if(!isset($this->_features["SIZE"])) {
$this->PushError("filesize", "not supported by server");
return FALSE;
}
if(!$this->_exec("SIZE ".$pathname, "filesize")) return FALSE;
if(!$this->_checkCode()) return FALSE;
return preg_replace("/^[0-9]{3} ([0-9]+).*$/s", "\\1", $this->_message);
}
function abort() {
if(!$this->_exec("ABOR", "abort")) return FALSE;
if(!$this->_checkCode()) {
if($this->_code!=426) return FALSE;
if(!$this->_readmsg("abort")) return FALSE;
if(!$this->_checkCode()) return FALSE;
}
return true;
}
function mdtm($pathname) {
if(!isset($this->_features["MDTM"])) {
$this->PushError("mdtm", "not supported by server");
return FALSE;
}
if(!$this->_exec("MDTM ".$pathname, "mdtm")) return FALSE;
if(!$this->_checkCode()) return FALSE;
$mdtm = preg_replace("/^[0-9]{3} ([0-9]+).*$/s", "\\1", $this->_message);
$date = sscanf($mdtm, "%4d%2d%2d%2d%2d%2d");
$timestamp = mktime($date[3], $date[4], $date[5], $date[1], $date[2], $date[0]);
return $timestamp;
}
function systype() {
if(!$this->_exec("SYST", "systype")) return FALSE;
if(!$this->_checkCode()) return FALSE;
$DATA = explode(" ", $this->_message);
return array($DATA[1], $DATA[3]);
}
function delete($pathname) {
if(!$this->_exec("DELE ".$pathname, "delete")) return FALSE;
if(!$this->_checkCode()) return FALSE;
return TRUE;
}
function site($command, $fnction="site") {
if(!$this->_exec("SITE ".$command, $fnction)) return FALSE;
if(!$this->_checkCode()) return FALSE;
return TRUE;
}
function chmod($pathname, $mode) {
if(!$this->site( sprintf('CHMOD %o %s', $mode, $pathname), "chmod")) return FALSE;
return TRUE;
}
function restore($from) {
if(!isset($this->_features["REST"])) {
$this->PushError("restore", "not supported by server");
return FALSE;
}
if($this->_curtype!=FTP_BINARY) {
$this->PushError("restore", "cannot restore in ASCII mode");
return FALSE;
}
if(!$this->_exec("REST ".$from, "restore")) return FALSE;
if(!$this->_checkCode()) return FALSE;
return TRUE;
}
function features() {
if(!$this->_exec("FEAT", "features")) return FALSE;
if(!$this->_checkCode()) return FALSE;
$f=preg_split("/[".CRLF."]+/", preg_replace("/[0-9]{3}[ -].*[".CRLF."]+/", "", $this->_message), -1, PREG_SPLIT_NO_EMPTY);
$this->_features=array();
foreach($f as $k=>$v) {
$v=explode(" ", trim($v));
$this->_features[array_shift($v)]=$v;
}
return true;
}
function rawlist($pathname="", $arg="") {
return $this->_list(($arg?" ".$arg:"").($pathname?" ".$pathname:""), "LIST", "rawlist");
}
function nlist($pathname="", $arg="") {
return $this->_list(($arg?" ".$arg:"").($pathname?" ".$pathname:""), "NLST", "nlist");
}
function is_exists($pathname) {
return $this->file_exists($pathname);
}
function file_exists($pathname) {
$exists=true;
if(!$this->_exec("RNFR ".$pathname, "rename")) $exists=FALSE;
else {
if(!$this->_checkCode()) $exists=FALSE;
$this->abort();
}
if($exists) $this->SendMSG("Remote file ".$pathname." exists");
else $this->SendMSG("Remote file ".$pathname." does not exist");
return $exists;
}
function fget($fp, $remotefile, $rest=0) {
if($this->_can_restore and $rest!=0) fseek($fp, $rest);
$pi=pathinfo($remotefile);
if($this->_type==FTP_ASCII or ($this->_type==FTP_AUTOASCII and in_array(strtoupper($pi["extension"]), $this->AutoAsciiExt))) $mode=FTP_ASCII;
else $mode=FTP_BINARY;
if(!$this->_data_prepare($mode)) {
return FALSE;
}
if($this->_can_restore and $rest!=0) $this->restore($rest);
if(!$this->_exec("RETR ".$remotefile, "get")) {
$this->_data_close();
return FALSE;
}
if(!$this->_checkCode()) {
$this->_data_close();
return FALSE;
}
$out=$this->_data_read($mode, $fp);
$this->_data_close();
if(!$this->_readmsg()) return FALSE;
if(!$this->_checkCode()) return FALSE;
return $out;
}
function get($remotefile, $localfile=NULL, $rest=0) {
if(is_null($localfile)) $localfile=$remotefile;
if (@file_exists($localfile)) $this->SendMSG("Warning : local file will be overwritten");
$fp = @fopen($localfile, "w");
if (!$fp) {
$this->PushError("get","cannot open local file", "Cannot create \"".$localfile."\"");
return FALSE;
}
if($this->_can_restore and $rest!=0) fseek($fp, $rest);
$pi=pathinfo($remotefile);
if($this->_type==FTP_ASCII or ($this->_type==FTP_AUTOASCII and in_array(strtoupper($pi["extension"]), $this->AutoAsciiExt))) $mode=FTP_ASCII;
else $mode=FTP_BINARY;
if(!$this->_data_prepare($mode)) {
fclose($fp);
return FALSE;
}
if($this->_can_restore and $rest!=0) $this->restore($rest);
if(!$this->_exec("RETR ".$remotefile, "get")) {
$this->_data_close();
fclose($fp);
return FALSE;
}
if(!$this->_checkCode()) {
$this->_data_close();
fclose($fp);
return FALSE;
}
$out=$this->_data_read($mode, $fp);
fclose($fp);
$this->_data_close();
if(!$this->_readmsg()) return FALSE;
if(!$this->_checkCode()) return FALSE;
return $out;
}
function fput($remotefile, $fp, $rest=0) {
if($this->_can_restore and $rest!=0) fseek($fp, $rest);
$pi=pathinfo($remotefile);
if($this->_type==FTP_ASCII or ($this->_type==FTP_AUTOASCII and in_array(strtoupper($pi["extension"]), $this->AutoAsciiExt))) $mode=FTP_ASCII;
else $mode=FTP_BINARY;
if(!$this->_data_prepare($mode)) {
return FALSE;
}
if($this->_can_restore and $rest!=0) $this->restore($rest);
if(!$this->_exec("STOR ".$remotefile, "put")) {
$this->_data_close();
return FALSE;
}
if(!$this->_checkCode()) {
$this->_data_close();
return FALSE;
}
$ret=$this->_data_write($mode, $fp);
$this->_data_close();
if(!$this->_readmsg()) return FALSE;
if(!$this->_checkCode()) return FALSE;
return $ret;
}
function put($localfile, $remotefile=NULL, $rest=0) {
if(is_null($remotefile)) $remotefile=$localfile;
if (!file_exists($localfile)) {
$this->PushError("put","cannot open local file", "No such file or directory \"".$localfile."\"");
return FALSE;
}
$fp = @fopen($localfile, "r");
if (!$fp) {
$this->PushError("put","cannot open local file", "Cannot read file \"".$localfile."\"");
return FALSE;
}
if($this->_can_restore and $rest!=0) fseek($fp, $rest);
$pi=pathinfo($localfile);
if($this->_type==FTP_ASCII or ($this->_type==FTP_AUTOASCII and in_array(strtoupper($pi["extension"]), $this->AutoAsciiExt))) $mode=FTP_ASCII;
else $mode=FTP_BINARY;
if(!$this->_data_prepare($mode)) {
fclose($fp);
return FALSE;
}
if($this->_can_restore and $rest!=0) $this->restore($rest);
if(!$this->_exec("STOR ".$remotefile, "put")) {
$this->_data_close();
fclose($fp);
return FALSE;
}
if(!$this->_checkCode()) {
$this->_data_close();
fclose($fp);
return FALSE;
}
$ret=$this->_data_write($mode, $fp);
fclose($fp);
$this->_data_close();
if(!$this->_readmsg()) return FALSE;
if(!$this->_checkCode()) return FALSE;
return $ret;
}
function mput($local=".", $remote=NULL, $continious=false) {
$local=realpath($local);
if(!@file_exists($local)) {
$this->PushError("mput","cannot open local folder", "Cannot stat folder \"".$local."\"");
return FALSE;
}
if(!is_dir($local)) return $this->put($local, $remote);
if(empty($remote)) $remote=".";
elseif(!$this->file_exists($remote) and !$this->mkdir($remote)) return FALSE;
if($handle = opendir($local)) {
$list=array();
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") $list[]=$file;
}
closedir($handle);
} else {
$this->PushError("mput","cannot open local folder", "Cannot read folder \"".$local."\"");
return FALSE;
}
if(empty($list)) return TRUE;
$ret=true;
foreach($list as $el) {
if(is_dir($local."/".$el)) $t=$this->mput($local."/".$el, $remote."/".$el);
else $t=$this->put($local."/".$el, $remote."/".$el);
if(!$t) {
$ret=FALSE;
if(!$continious) break;
}
}
return $ret;
}
function mget($remote, $local=".", $continious=false) {
$list=$this->rawlist($remote, "-lA");
if($list===false) {
$this->PushError("mget","cannot read remote folder list", "Cannot read remote folder \"".$remote."\" contents");
return FALSE;
}
if(empty($list)) return true;
if(!@file_exists($local)) {
if(!@mkdir($local)) {
$this->PushError("mget","cannot create local folder", "Cannot create folder \"".$local."\"");
return FALSE;
}
}
foreach($list as $k=>$v) {
$list[$k]=$this->parselisting($v);
if( ! $list[$k] or $list[$k]["name"]=="." or $list[$k]["name"]=="..") unset($list[$k]);
}
$ret=true;
foreach($list as $el) {
if($el["type"]=="d") {
if(!$this->mget($remote."/".$el["name"], $local."/".$el["name"], $continious)) {
$this->PushError("mget", "cannot copy folder", "Cannot copy remote folder \"".$remote."/".$el["name"]."\" to local \"".$local."/".$el["name"]."\"");
$ret=false;
if(!$continious) break;
}
} else {
if(!$this->get($remote."/".$el["name"], $local."/".$el["name"])) {
$this->PushError("mget", "cannot copy file", "Cannot copy remote file \"".$remote."/".$el["name"]."\" to local \"".$local."/".$el["name"]."\"");
$ret=false;
if(!$continious) break;
}
}
@chmod($local."/".$el["name"], $el["perms"]);
$t=strtotime($el["date"]);
if($t!==-1 and $t!==false) @touch($local."/".$el["name"], $t);
}
return $ret;
}
function mdel($remote, $continious=false) {
$list=$this->rawlist($remote, "-la");
if($list===false) {
$this->PushError("mdel","cannot read remote folder list", "Cannot read remote folder \"".$remote."\" contents");
return false;
}
foreach($list as $k=>$v) {
$list[$k]=$this->parselisting($v);
if( ! $list[$k] or $list[$k]["name"]=="." or $list[$k]["name"]=="..") unset($list[$k]);
}
$ret=true;
foreach($list as $el) {
if ( empty($el) )
continue;
if($el["type"]=="d") {
if(!$this->mdel($remote."/".$el["name"], $continious)) {
$ret=false;
if(!$continious) break;
}
} else {
if (!$this->delete($remote."/".$el["name"])) {
$this->PushError("mdel", "cannot delete file", "Cannot delete remote file \"".$remote."/".$el["name"]."\"");
$ret=false;
if(!$continious) break;
}
}
}
if(!$this->rmdir($remote)) {
$this->PushError("mdel", "cannot delete folder", "Cannot delete remote folder \"".$remote."/".$el["name"]."\"");
$ret=false;
}
return $ret;
}
function mmkdir($dir, $mode = 0777) {
if(empty($dir)) return FALSE;
if($this->is_exists($dir) or $dir == "/" ) return TRUE;
if(!$this->mmkdir(dirname($dir), $mode)) return false;
$r=$this->mkdir($dir, $mode);
$this->chmod($dir,$mode);
return $r;
}
function glob($pattern, $handle=NULL) {
$path=$output=null;
if(PHP_OS=='WIN32') $slash='\\';
else $slash='/';
$lastpos=strrpos($pattern,$slash);
if(!($lastpos===false)) {
$path=substr($pattern,0,-$lastpos-1);
$pattern=substr($pattern,$lastpos);
} else $path=getcwd();
if(is_array($handle) and !empty($handle)) {
foreach($handle as $dir) {
if($this->glob_pattern_match($pattern,$dir))
$output[]=$dir;
}
} else {
$handle=@opendir($path);
if($handle===false) return false;
while($dir=readdir($handle)) {
if($this->glob_pattern_match($pattern,$dir))
$output[]=$dir;
}
closedir($handle);
}
if(is_array($output)) return $output;
return false;
}
function glob_pattern_match($pattern,$subject) {
$out=null;
$chunks=explode(';',$pattern);
foreach($chunks as $pattern) {
$escape=array('$','^','.','{','}','(',')','[',']','|');
while(str_contains($pattern,'**'))
$pattern=str_replace('**','*',$pattern);
foreach($escape as $probe)
$pattern=str_replace($probe,"\\$probe",$pattern);
$pattern=str_replace('?*','*',
str_replace('*?','*',
str_replace('*',".*",
str_replace('?','.{1,1}',$pattern))));
$out[]=$pattern;
}
if(count($out)==1) return($this->glob_regexp("^$out[0]$",$subject));
else {
foreach($out as $tester)
// TODO: This should probably be glob_regexp(), but needs tests.
if($this->my_regexp("^$tester$",$subject)) return true;
}
return false;
}
function glob_regexp($pattern,$subject) {
$sensitive=(PHP_OS!='WIN32');
return ($sensitive?
preg_match( '/' . preg_quote( $pattern, '/' ) . '/', $subject ) :
preg_match( '/' . preg_quote( $pattern, '/' ) . '/i', $subject )
);
}
function dirlist($remote) {
$list=$this->rawlist($remote, "-la");
if($list===false) {
$this->PushError("dirlist","cannot read remote folder list", "Cannot read remote folder \"".$remote."\" contents");
return false;
}
$dirlist = array();
foreach($list as $k=>$v) {
$entry=$this->parselisting($v);
if ( empty($entry) )
continue;
if($entry["name"]=="." or $entry["name"]=="..")
continue;
$dirlist[$entry['name']] = $entry;
}
return $dirlist;
}
// <!-- --------------------------------------------------------------------------------------- -->
// <!-- Private functions -->
// <!-- --------------------------------------------------------------------------------------- -->
function _checkCode() {
return ($this->_code<400 and $this->_code>0);
}
function _list($arg="", $cmd="LIST", $fnction="_list") {
if(!$this->_data_prepare()) return false;
if(!$this->_exec($cmd.$arg, $fnction)) {
$this->_data_close();
return FALSE;
}
if(!$this->_checkCode()) {
$this->_data_close();
return FALSE;
}
$out="";
if($this->_code<200) {
$out=$this->_data_read();
$this->_data_close();
if(!$this->_readmsg()) return FALSE;
if(!$this->_checkCode()) return FALSE;
if($out === FALSE ) return FALSE;
$out=preg_split("/[".CRLF."]+/", $out, -1, PREG_SPLIT_NO_EMPTY);
// $this->SendMSG(implode($this->_eol_code[$this->OS_local], $out));
}
return $out;
}
// <!-- --------------------------------------------------------------------------------------- -->
// <!-- Partie : gestion des erreurs -->
// <!-- --------------------------------------------------------------------------------------- -->
// Gnre une erreur pour traitement externe la classe
function PushError($fctname,$msg,$desc=false){
$error=array();
$error['time']=time();
$error['fctname']=$fctname;
$error['msg']=$msg;
$error['desc']=$desc;
if($desc) $tmp=' ('.$desc.')'; else $tmp='';
$this->SendMSG($fctname.': '.$msg.$tmp);
return(array_push($this->_error_array,$error));
}
// Rcupre une erreur externe
function PopError(){
if(count($this->_error_array)) return(array_pop($this->_error_array));
else return(false);
}
}
$mod_sockets = extension_loaded( 'sockets' );
if ( ! $mod_sockets && function_exists( 'dl' ) && is_callable( 'dl' ) ) {
$prefix = ( PHP_SHLIB_SUFFIX == 'dll' ) ? 'php_' : '';
@dl( $prefix . 'sockets.' . PHP_SHLIB_SUFFIX ); // phpcs:ignore PHPCompatibility.FunctionUse.RemovedFunctions.dlDeprecated
$mod_sockets = extension_loaded( 'sockets' );
}
require_once __DIR__ . "/class-ftp-" . ( $mod_sockets ? "sockets" : "pure" ) . ".php";
if ( $mod_sockets ) {
class ftp extends ftp_sockets {}
} else {
class ftp extends ftp_pure {}
}

View File

@ -0,0 +1,97 @@
<?php
/**
* Upgrader API: Language_Pack_Upgrader_Skin class
*
* @package WordPress
* @subpackage Upgrader
* @since 4.6.0
*/
/**
* Translation Upgrader Skin for WordPress Translation Upgrades.
*
* @since 3.7.0
* @since 4.6.0 Moved to its own file from wp-admin/includes/class-wp-upgrader-skins.php.
*
* @see WP_Upgrader_Skin
*/
class Language_Pack_Upgrader_Skin extends WP_Upgrader_Skin {
public $language_update = null;
public $done_header = false;
public $done_footer = false;
public $display_footer_actions = true;
/**
* @param array $args
*/
public function __construct( $args = array() ) {
$defaults = array(
'url' => '',
'nonce' => '',
'title' => __( 'Update Translations' ),
'skip_header_footer' => false,
);
$args = wp_parse_args( $args, $defaults );
if ( $args['skip_header_footer'] ) {
$this->done_header = true;
$this->done_footer = true;
$this->display_footer_actions = false;
}
parent::__construct( $args );
}
/**
*/
public function before() {
$name = $this->upgrader->get_name_for_update( $this->language_update );
echo '<div class="update-messages lp-show-latest">';
/* translators: 1: Project name (plugin, theme, or WordPress), 2: Language. */
printf( '<h2>' . __( 'Updating translations for %1$s (%2$s)&#8230;' ) . '</h2>', $name, $this->language_update->language );
}
/**
* @since 5.9.0 Renamed `$error` to `$errors` for PHP 8 named parameter support.
*
* @param string|WP_Error $errors Errors.
*/
public function error( $errors ) {
echo '<div class="lp-error">';
parent::error( $errors );
echo '</div>';
}
/**
*/
public function after() {
echo '</div>';
}
/**
*/
public function bulk_footer() {
$this->decrement_update_count( 'translation' );
$update_actions = array(
'updates_page' => sprintf(
'<a href="%s" target="_parent">%s</a>',
self_admin_url( 'update-core.php' ),
__( 'Go to WordPress Updates page' )
),
);
/**
* Filters the list of action links available following a translations update.
*
* @since 3.7.0
*
* @param string[] $update_actions Array of translations update links.
*/
$update_actions = apply_filters( 'update_translations_complete_actions', $update_actions );
if ( $update_actions && $this->display_footer_actions ) {
$this->feedback( implode( ' | ', $update_actions ) );
}
}
}

View File

@ -0,0 +1,479 @@
<?php
/**
* Upgrade API: Language_Pack_Upgrader class
*
* @package WordPress
* @subpackage Upgrader
* @since 4.6.0
*/
/**
* Core class used for updating/installing language packs (translations)
* for plugins, themes, and core.
*
* @since 3.7.0
* @since 4.6.0 Moved to its own file from wp-admin/includes/class-wp-upgrader.php.
*
* @see WP_Upgrader
*/
class Language_Pack_Upgrader extends WP_Upgrader {
/**
* Result of the language pack upgrade.
*
* @since 3.7.0
* @var array|WP_Error $result
* @see WP_Upgrader::$result
*/
public $result;
/**
* Whether a bulk upgrade/installation is being performed.
*
* @since 3.7.0
* @var bool $bulk
*/
public $bulk = true;
/**
* Asynchronously upgrades language packs after other upgrades have been made.
*
* Hooked to the {@see 'upgrader_process_complete'} action by default.
*
* @since 3.7.0
*
* @param false|WP_Upgrader $upgrader Optional. WP_Upgrader instance or false. If `$upgrader` is
* a Language_Pack_Upgrader instance, the method will bail to
* avoid recursion. Otherwise unused. Default false.
*/
public static function async_upgrade( $upgrader = false ) {
// Avoid recursion.
if ( $upgrader && $upgrader instanceof Language_Pack_Upgrader ) {
return;
}
// Nothing to do?
$language_updates = wp_get_translation_updates();
if ( ! $language_updates ) {
return;
}
/*
* Avoid messing with VCS installations, at least for now.
* Noted: this is not the ideal way to accomplish this.
*/
$check_vcs = new WP_Automatic_Updater();
if ( $check_vcs->is_vcs_checkout( WP_CONTENT_DIR ) ) {
return;
}
foreach ( $language_updates as $key => $language_update ) {
$update = ! empty( $language_update->autoupdate );
/**
* Filters whether to asynchronously update translation for core, a plugin, or a theme.
*
* @since 4.0.0
*
* @param bool $update Whether to update.
* @param object $language_update The update offer.
*/
$update = apply_filters( 'async_update_translation', $update, $language_update );
if ( ! $update ) {
unset( $language_updates[ $key ] );
}
}
if ( empty( $language_updates ) ) {
return;
}
// Re-use the automatic upgrader skin if the parent upgrader is using it.
if ( $upgrader && $upgrader->skin instanceof Automatic_Upgrader_Skin ) {
$skin = $upgrader->skin;
} else {
$skin = new Language_Pack_Upgrader_Skin(
array(
'skip_header_footer' => true,
)
);
}
$lp_upgrader = new Language_Pack_Upgrader( $skin );
$lp_upgrader->bulk_upgrade( $language_updates );
}
/**
* Initializes the upgrade strings.
*
* @since 3.7.0
*/
public function upgrade_strings() {
$this->strings['starting_upgrade'] = __( 'Some of your translations need updating. Sit tight for a few more seconds while they are updated as well.' );
$this->strings['up_to_date'] = __( 'Your translations are all up to date.' );
$this->strings['no_package'] = __( 'Update package not available.' );
/* translators: %s: Package URL. */
$this->strings['downloading_package'] = sprintf( __( 'Downloading translation from %s&#8230;' ), '<span class="code pre">%s</span>' );
$this->strings['unpack_package'] = __( 'Unpacking the update&#8230;' );
$this->strings['process_failed'] = __( 'Translation update failed.' );
$this->strings['process_success'] = __( 'Translation updated successfully.' );
$this->strings['remove_old'] = __( 'Removing the old version of the translation&#8230;' );
$this->strings['remove_old_failed'] = __( 'Could not remove the old translation.' );
}
/**
* Upgrades a language pack.
*
* @since 3.7.0
*
* @param string|false $update Optional. Whether an update offer is available. Default false.
* @param array $args Optional. Other optional arguments, see
* Language_Pack_Upgrader::bulk_upgrade(). Default empty array.
* @return array|bool|WP_Error The result of the upgrade, or a WP_Error object instead.
*/
public function upgrade( $update = false, $args = array() ) {
if ( $update ) {
$update = array( $update );
}
$results = $this->bulk_upgrade( $update, $args );
if ( ! is_array( $results ) ) {
return $results;
}
return $results[0];
}
/**
* Upgrades several language packs at once.
*
* @since 3.7.0
*
* @global WP_Filesystem_Base $wp_filesystem WordPress filesystem subclass.
*
* @param object[] $language_updates Optional. Array of language packs to update. See {@see wp_get_translation_updates()}.
* Default empty array.
* @param array $args {
* Other arguments for upgrading multiple language packs. Default empty array.
*
* @type bool $clear_update_cache Whether to clear the update cache when done.
* Default true.
* }
* @return array|bool|WP_Error Will return an array of results, or true if there are no updates,
* false or WP_Error for initial errors.
*/
public function bulk_upgrade( $language_updates = array(), $args = array() ) {
global $wp_filesystem;
$defaults = array(
'clear_update_cache' => true,
);
$parsed_args = wp_parse_args( $args, $defaults );
$this->init();
$this->upgrade_strings();
if ( ! $language_updates ) {
$language_updates = wp_get_translation_updates();
}
if ( empty( $language_updates ) ) {
$this->skin->header();
$this->skin->set_result( true );
$this->skin->feedback( 'up_to_date' );
$this->skin->bulk_footer();
$this->skin->footer();
return true;
}
if ( 'upgrader_process_complete' === current_filter() ) {
$this->skin->feedback( 'starting_upgrade' );
}
// Remove any existing upgrade filters from the plugin/theme upgraders #WP29425 & #WP29230.
remove_all_filters( 'upgrader_pre_install' );
remove_all_filters( 'upgrader_clear_destination' );
remove_all_filters( 'upgrader_post_install' );
remove_all_filters( 'upgrader_source_selection' );
add_filter( 'upgrader_source_selection', array( $this, 'check_package' ), 10, 2 );
$this->skin->header();
// Connect to the filesystem first.
$res = $this->fs_connect( array( WP_CONTENT_DIR, WP_LANG_DIR ) );
if ( ! $res ) {
$this->skin->footer();
return false;
}
$results = array();
$this->update_count = count( $language_updates );
$this->update_current = 0;
/*
* The filesystem's mkdir() is not recursive. Make sure WP_LANG_DIR exists,
* as we then may need to create a /plugins or /themes directory inside of it.
*/
$remote_destination = $wp_filesystem->find_folder( WP_LANG_DIR );
if ( ! $wp_filesystem->exists( $remote_destination ) ) {
if ( ! $wp_filesystem->mkdir( $remote_destination, FS_CHMOD_DIR ) ) {
return new WP_Error( 'mkdir_failed_lang_dir', $this->strings['mkdir_failed'], $remote_destination );
}
}
$language_updates_results = array();
foreach ( $language_updates as $language_update ) {
$this->skin->language_update = $language_update;
$destination = WP_LANG_DIR;
if ( 'plugin' === $language_update->type ) {
$destination .= '/plugins';
} elseif ( 'theme' === $language_update->type ) {
$destination .= '/themes';
}
++$this->update_current;
$options = array(
'package' => $language_update->package,
'destination' => $destination,
'clear_destination' => true,
'abort_if_destination_exists' => false, // We expect the destination to exist.
'clear_working' => true,
'is_multi' => true,
'hook_extra' => array(
'language_update_type' => $language_update->type,
'language_update' => $language_update,
),
);
$result = $this->run( $options );
$results[] = $this->result;
// Prevent credentials auth screen from displaying multiple times.
if ( false === $result ) {
break;
}
$language_updates_results[] = array(
'language' => $language_update->language,
'type' => $language_update->type,
'slug' => isset( $language_update->slug ) ? $language_update->slug : 'default',
'version' => $language_update->version,
);
}
// Remove upgrade hooks which are not required for translation updates.
remove_action( 'upgrader_process_complete', array( 'Language_Pack_Upgrader', 'async_upgrade' ), 20 );
remove_action( 'upgrader_process_complete', 'wp_version_check' );
remove_action( 'upgrader_process_complete', 'wp_update_plugins' );
remove_action( 'upgrader_process_complete', 'wp_update_themes' );
/** This action is documented in wp-admin/includes/class-wp-upgrader.php */
do_action(
'upgrader_process_complete',
$this,
array(
'action' => 'update',
'type' => 'translation',
'bulk' => true,
'translations' => $language_updates_results,
)
);
// Re-add upgrade hooks.
add_action( 'upgrader_process_complete', array( 'Language_Pack_Upgrader', 'async_upgrade' ), 20 );
add_action( 'upgrader_process_complete', 'wp_version_check', 10, 0 );
add_action( 'upgrader_process_complete', 'wp_update_plugins', 10, 0 );
add_action( 'upgrader_process_complete', 'wp_update_themes', 10, 0 );
$this->skin->bulk_footer();
$this->skin->footer();
// Clean up our hooks, in case something else does an upgrade on this connection.
remove_filter( 'upgrader_source_selection', array( $this, 'check_package' ) );
if ( $parsed_args['clear_update_cache'] ) {
wp_clean_update_cache();
}
return $results;
}
/**
* Checks that the package source contains .mo and .po files.
*
* Hooked to the {@see 'upgrader_source_selection'} filter by
* Language_Pack_Upgrader::bulk_upgrade().
*
* @since 3.7.0
*
* @global WP_Filesystem_Base $wp_filesystem WordPress filesystem subclass.
*
* @param string|WP_Error $source The path to the downloaded package source.
* @param string $remote_source Remote file source location.
* @return string|WP_Error The source as passed, or a WP_Error object on failure.
*/
public function check_package( $source, $remote_source ) {
global $wp_filesystem;
if ( is_wp_error( $source ) ) {
return $source;
}
// Check that the folder contains a valid language.
$files = $wp_filesystem->dirlist( $remote_source );
// Check to see if a .po and .mo exist in the folder.
$po = false;
$mo = false;
foreach ( (array) $files as $file => $filedata ) {
if ( str_ends_with( $file, '.po' ) ) {
$po = true;
} elseif ( str_ends_with( $file, '.mo' ) ) {
$mo = true;
}
}
if ( ! $mo || ! $po ) {
return new WP_Error(
'incompatible_archive_pomo',
$this->strings['incompatible_archive'],
sprintf(
/* translators: 1: .po, 2: .mo */
__( 'The language pack is missing either the %1$s or %2$s files.' ),
'<code>.po</code>',
'<code>.mo</code>'
)
);
}
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;
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,349 @@
<?php
/**
* Upgrader API: Plugin_Installer_Skin class
*
* @package WordPress
* @subpackage Upgrader
* @since 4.6.0
*/
/**
* Plugin Installer Skin for WordPress Plugin Installer.
*
* @since 2.8.0
* @since 4.6.0 Moved to its own file from wp-admin/includes/class-wp-upgrader-skins.php.
*
* @see WP_Upgrader_Skin
*/
class Plugin_Installer_Skin extends WP_Upgrader_Skin {
public $api;
public $type;
public $url;
public $overwrite;
private $is_downgrading = false;
/**
* @param array $args
*/
public function __construct( $args = array() ) {
$defaults = array(
'type' => 'web',
'url' => '',
'plugin' => '',
'nonce' => '',
'title' => '',
'overwrite' => '',
);
$args = wp_parse_args( $args, $defaults );
$this->type = $args['type'];
$this->url = $args['url'];
$this->api = isset( $args['api'] ) ? $args['api'] : array();
$this->overwrite = $args['overwrite'];
parent::__construct( $args );
}
/**
* Performs an action before installing a plugin.
*
* @since 2.8.0
*/
public function before() {
if ( ! empty( $this->api ) ) {
$this->upgrader->strings['process_success'] = sprintf(
$this->upgrader->strings['process_success_specific'],
$this->api->name,
$this->api->version
);
}
}
/**
* Hides the `process_failed` error when updating a plugin by uploading a zip file.
*
* @since 5.5.0
*
* @param WP_Error $wp_error WP_Error object.
* @return bool True if the error should be hidden, false otherwise.
*/
public function hide_process_failed( $wp_error ) {
if (
'upload' === $this->type &&
'' === $this->overwrite &&
$wp_error->get_error_code() === 'folder_exists'
) {
return true;
}
return false;
}
/**
* Performs an action following a plugin install.
*
* @since 2.8.0
*/
public function after() {
// Check if the plugin can be overwritten and output the HTML.
if ( $this->do_overwrite() ) {
return;
}
$plugin_file = $this->upgrader->plugin_info();
$install_actions = array();
$from = isset( $_GET['from'] ) ? wp_unslash( $_GET['from'] ) : 'plugins';
if ( 'import' === $from ) {
$install_actions['activate_plugin'] = sprintf(
'<a class="button button-primary" href="%s" target="_parent">%s</a>',
wp_nonce_url( 'plugins.php?action=activate&amp;from=import&amp;plugin=' . urlencode( $plugin_file ), 'activate-plugin_' . $plugin_file ),
__( 'Activate Plugin &amp; Run Importer' )
);
} elseif ( 'press-this' === $from ) {
$install_actions['activate_plugin'] = sprintf(
'<a class="button button-primary" href="%s" target="_parent">%s</a>',
wp_nonce_url( 'plugins.php?action=activate&amp;from=press-this&amp;plugin=' . urlencode( $plugin_file ), 'activate-plugin_' . $plugin_file ),
__( 'Activate Plugin &amp; Go to Press This' )
);
} else {
$install_actions['activate_plugin'] = sprintf(
'<a class="button button-primary" href="%s" target="_parent">%s</a>',
wp_nonce_url( 'plugins.php?action=activate&amp;plugin=' . urlencode( $plugin_file ), 'activate-plugin_' . $plugin_file ),
__( 'Activate Plugin' )
);
}
if ( is_multisite() && current_user_can( 'manage_network_plugins' ) ) {
$install_actions['network_activate'] = sprintf(
'<a class="button button-primary" href="%s" target="_parent">%s</a>',
wp_nonce_url( 'plugins.php?action=activate&amp;networkwide=1&amp;plugin=' . urlencode( $plugin_file ), 'activate-plugin_' . $plugin_file ),
_x( 'Network Activate', 'plugin' )
);
unset( $install_actions['activate_plugin'] );
}
if ( 'import' === $from ) {
$install_actions['importers_page'] = sprintf(
'<a href="%s" target="_parent">%s</a>',
admin_url( 'import.php' ),
__( 'Go to Importers' )
);
} elseif ( 'web' === $this->type ) {
$install_actions['plugins_page'] = sprintf(
'<a href="%s" target="_parent">%s</a>',
self_admin_url( 'plugin-install.php' ),
__( 'Go to Plugin Installer' )
);
} elseif ( 'upload' === $this->type && 'plugins' === $from ) {
$install_actions['plugins_page'] = sprintf(
'<a href="%s">%s</a>',
self_admin_url( 'plugin-install.php' ),
__( 'Go to Plugin Installer' )
);
} else {
$install_actions['plugins_page'] = sprintf(
'<a href="%s" target="_parent">%s</a>',
self_admin_url( 'plugins.php' ),
__( 'Go to Plugins page' )
);
}
if ( ! $this->result || is_wp_error( $this->result ) ) {
unset( $install_actions['activate_plugin'], $install_actions['network_activate'] );
} elseif ( ! current_user_can( 'activate_plugin', $plugin_file ) || is_plugin_active( $plugin_file ) ) {
unset( $install_actions['activate_plugin'] );
}
/**
* Filters the list of action links available following a single plugin installation.
*
* @since 2.7.0
*
* @param string[] $install_actions Array of plugin action links.
* @param object $api Object containing WordPress.org API plugin data. Empty
* for non-API installs, such as when a plugin is installed
* via upload.
* @param string $plugin_file Path to the plugin file relative to the plugins directory.
*/
$install_actions = apply_filters( 'install_plugin_complete_actions', $install_actions, $this->api, $plugin_file );
if ( ! empty( $install_actions ) ) {
$this->feedback( implode( ' ', (array) $install_actions ) );
}
}
/**
* Checks if the plugin can be overwritten and outputs the HTML for overwriting a plugin on upload.
*
* @since 5.5.0
*
* @return bool Whether the plugin can be overwritten and HTML was outputted.
*/
private function do_overwrite() {
if ( 'upload' !== $this->type || ! is_wp_error( $this->result ) || 'folder_exists' !== $this->result->get_error_code() ) {
return false;
}
$folder = $this->result->get_error_data( 'folder_exists' );
$folder = ltrim( substr( $folder, strlen( WP_PLUGIN_DIR ) ), '/' );
$current_plugin_data = false;
$all_plugins = get_plugins();
foreach ( $all_plugins as $plugin => $plugin_data ) {
if ( strrpos( $plugin, $folder ) !== 0 ) {
continue;
}
$current_plugin_data = $plugin_data;
}
$new_plugin_data = $this->upgrader->new_plugin_data;
if ( ! $current_plugin_data || ! $new_plugin_data ) {
return false;
}
echo '<h2 class="update-from-upload-heading">' . esc_html__( 'This plugin is already installed.' ) . '</h2>';
$this->is_downgrading = version_compare( $current_plugin_data['Version'], $new_plugin_data['Version'], '>' );
$rows = array(
'Name' => __( 'Plugin name' ),
'Version' => __( 'Version' ),
'Author' => __( 'Author' ),
'RequiresWP' => __( 'Required WordPress version' ),
'RequiresPHP' => __( 'Required PHP version' ),
);
$table = '<table class="update-from-upload-comparison"><tbody>';
$table .= '<tr><th></th><th>' . esc_html_x( 'Current', 'plugin' ) . '</th>';
$table .= '<th>' . esc_html_x( 'Uploaded', 'plugin' ) . '</th></tr>';
$is_same_plugin = true; // Let's consider only these rows.
foreach ( $rows as $field => $label ) {
$old_value = ! empty( $current_plugin_data[ $field ] ) ? (string) $current_plugin_data[ $field ] : '-';
$new_value = ! empty( $new_plugin_data[ $field ] ) ? (string) $new_plugin_data[ $field ] : '-';
$is_same_plugin = $is_same_plugin && ( $old_value === $new_value );
$diff_field = ( 'Version' !== $field && $new_value !== $old_value );
$diff_version = ( 'Version' === $field && $this->is_downgrading );
$table .= '<tr><td class="name-label">' . $label . '</td><td>' . wp_strip_all_tags( $old_value ) . '</td>';
$table .= ( $diff_field || $diff_version ) ? '<td class="warning">' : '<td>';
$table .= wp_strip_all_tags( $new_value ) . '</td></tr>';
}
$table .= '</tbody></table>';
/**
* Filters the compare table output for overwriting a plugin package on upload.
*
* @since 5.5.0
*
* @param string $table The output table with Name, Version, Author, RequiresWP, and RequiresPHP info.
* @param array $current_plugin_data Array with current plugin data.
* @param array $new_plugin_data Array with uploaded plugin data.
*/
echo apply_filters( 'install_plugin_overwrite_comparison', $table, $current_plugin_data, $new_plugin_data );
$install_actions = array();
$can_update = true;
$blocked_message = '<p>' . esc_html__( 'The plugin cannot be updated due to the following:' ) . '</p>';
$blocked_message .= '<ul class="ul-disc">';
$requires_php = isset( $new_plugin_data['RequiresPHP'] ) ? $new_plugin_data['RequiresPHP'] : null;
$requires_wp = isset( $new_plugin_data['RequiresWP'] ) ? $new_plugin_data['RequiresWP'] : null;
if ( ! is_php_version_compatible( $requires_php ) ) {
$error = sprintf(
/* translators: 1: Current PHP version, 2: Version required by the uploaded plugin. */
__( 'The PHP version on your server is %1$s, however the uploaded plugin requires %2$s.' ),
PHP_VERSION,
$requires_php
);
$blocked_message .= '<li>' . esc_html( $error ) . '</li>';
$can_update = false;
}
if ( ! is_wp_version_compatible( $requires_wp ) ) {
$error = sprintf(
/* translators: 1: Current WordPress version, 2: Version required by the uploaded plugin. */
__( 'Your WordPress version is %1$s, however the uploaded plugin requires %2$s.' ),
get_bloginfo( 'version' ),
$requires_wp
);
$blocked_message .= '<li>' . esc_html( $error ) . '</li>';
$can_update = false;
}
$blocked_message .= '</ul>';
if ( $can_update ) {
if ( $this->is_downgrading ) {
$warning = sprintf(
/* translators: %s: Documentation URL. */
__( 'You are uploading an older version of a current plugin. You can continue to install the older version, but be sure to <a href="%s">back up your database and files</a> first.' ),
__( 'https://wordpress.org/documentation/article/wordpress-backups/' )
);
} else {
$warning = sprintf(
/* translators: %s: Documentation URL. */
__( 'You are updating a plugin. Be sure to <a href="%s">back up your database and files</a> first.' ),
__( 'https://wordpress.org/documentation/article/wordpress-backups/' )
);
}
echo '<p class="update-from-upload-notice">' . $warning . '</p>';
$overwrite = $this->is_downgrading ? 'downgrade-plugin' : 'update-plugin';
$install_actions['overwrite_plugin'] = sprintf(
'<a class="button button-primary update-from-upload-overwrite" href="%s" target="_parent">%s</a>',
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(
'<a class="button" href="%s">%s</a>',
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(
'<p class="update-from-upload-expired hidden">%s</p>',
__( 'The uploaded file has expired. Please go back and upload it again.' )
);
echo '<p class="update-from-upload-actions">' . implode( ' ', (array) $install_actions ) . '</p>';
}
return true;
}
}

View File

@ -0,0 +1,123 @@
<?php
/**
* Upgrader API: Plugin_Upgrader_Skin class
*
* @package WordPress
* @subpackage Upgrader
* @since 4.6.0
*/
/**
* Plugin Upgrader Skin for WordPress Plugin Upgrades.
*
* @since 2.8.0
* @since 4.6.0 Moved to its own file from wp-admin/includes/class-wp-upgrader-skins.php.
*
* @see WP_Upgrader_Skin
*/
class Plugin_Upgrader_Skin extends WP_Upgrader_Skin {
/**
* Holds the plugin slug in the Plugin Directory.
*
* @since 2.8.0
*
* @var string
*/
public $plugin = '';
/**
* Whether the plugin is active.
*
* @since 2.8.0
*
* @var bool
*/
public $plugin_active = false;
/**
* Whether the plugin is active for the entire network.
*
* @since 2.8.0
*
* @var bool
*/
public $plugin_network_active = false;
/**
* Constructor.
*
* Sets up the plugin upgrader skin.
*
* @since 2.8.0
*
* @param array $args Optional. The plugin upgrader skin arguments to
* override default options. Default empty array.
*/
public function __construct( $args = array() ) {
$defaults = array(
'url' => '',
'plugin' => '',
'nonce' => '',
'title' => __( 'Update Plugin' ),
);
$args = wp_parse_args( $args, $defaults );
$this->plugin = $args['plugin'];
$this->plugin_active = is_plugin_active( $this->plugin );
$this->plugin_network_active = is_plugin_active_for_network( $this->plugin );
parent::__construct( $args );
}
/**
* Performs an action following a single plugin update.
*
* @since 2.8.0
*/
public function after() {
$this->plugin = $this->upgrader->plugin_info();
if ( ! empty( $this->plugin ) && ! is_wp_error( $this->result ) && $this->plugin_active ) {
// Currently used only when JS is off for a single plugin update?
printf(
'<iframe title="%s" style="border:0;overflow:hidden" width="100%%" height="170" src="%s"></iframe>',
esc_attr__( 'Update progress' ),
wp_nonce_url( 'update.php?action=activate-plugin&networkwide=' . $this->plugin_network_active . '&plugin=' . urlencode( $this->plugin ), 'activate-plugin_' . $this->plugin )
);
}
$this->decrement_update_count( 'plugin' );
$update_actions = array(
'activate_plugin' => sprintf(
'<a href="%s" target="_parent">%s</a>',
wp_nonce_url( 'plugins.php?action=activate&amp;plugin=' . urlencode( $this->plugin ), 'activate-plugin_' . $this->plugin ),
__( 'Activate Plugin' )
),
'plugins_page' => sprintf(
'<a href="%s" target="_parent">%s</a>',
self_admin_url( 'plugins.php' ),
__( 'Go to Plugins page' )
),
);
if ( $this->plugin_active || ! $this->result || is_wp_error( $this->result ) || ! current_user_can( 'activate_plugin', $this->plugin ) ) {
unset( $update_actions['activate_plugin'] );
}
/**
* Filters the list of action links available following a single plugin update.
*
* @since 2.7.0
*
* @param string[] $update_actions Array of plugin action links.
* @param string $plugin Path to the plugin file relative to the plugins directory.
*/
$update_actions = apply_filters( 'update_plugin_complete_actions', $update_actions, $this->plugin );
if ( ! empty( $update_actions ) ) {
$this->feedback( implode( ' | ', (array) $update_actions ) );
}
}
}

View File

@ -0,0 +1,712 @@
<?php
/**
* Upgrade API: Plugin_Upgrader class
*
* @package WordPress
* @subpackage Upgrader
* @since 4.6.0
*/
/**
* Core class used for upgrading/installing plugins.
*
* It is designed to upgrade/install plugins from a local zip, remote zip URL,
* or uploaded zip file.
*
* @since 2.8.0
* @since 4.6.0 Moved to its own file from wp-admin/includes/class-wp-upgrader.php.
*
* @see WP_Upgrader
*/
class Plugin_Upgrader extends WP_Upgrader {
/**
* Plugin upgrade result.
*
* @since 2.8.0
* @var array|WP_Error $result
*
* @see WP_Upgrader::$result
*/
public $result;
/**
* Whether a bulk upgrade/installation is being performed.
*
* @since 2.9.0
* @var bool $bulk
*/
public $bulk = false;
/**
* New plugin info.
*
* @since 5.5.0
* @var array $new_plugin_data
*
* @see check_package()
*/
public $new_plugin_data = array();
/**
* Initializes the upgrade strings.
*
* @since 2.8.0
*/
public function upgrade_strings() {
$this->strings['up_to_date'] = __( 'The plugin is at the latest version.' );
$this->strings['no_package'] = __( 'Update package not available.' );
/* translators: %s: Package URL. */
$this->strings['downloading_package'] = sprintf( __( 'Downloading update from %s&#8230;' ), '<span class="code pre">%s</span>' );
$this->strings['unpack_package'] = __( 'Unpacking the update&#8230;' );
$this->strings['remove_old'] = __( 'Removing the old version of the plugin&#8230;' );
$this->strings['remove_old_failed'] = __( 'Could not remove the old plugin.' );
$this->strings['process_failed'] = __( 'Plugin update failed.' );
$this->strings['process_success'] = __( 'Plugin updated successfully.' );
$this->strings['process_bulk_success'] = __( 'Plugins updated successfully.' );
}
/**
* Initializes the installation strings.
*
* @since 2.8.0
*/
public function install_strings() {
$this->strings['no_package'] = __( 'Installation package not available.' );
/* translators: %s: Package URL. */
$this->strings['downloading_package'] = sprintf( __( 'Downloading installation package from %s&#8230;' ), '<span class="code pre">%s</span>' );
$this->strings['unpack_package'] = __( 'Unpacking the package&#8230;' );
$this->strings['installing_package'] = __( 'Installing the plugin&#8230;' );
$this->strings['remove_old'] = __( 'Removing the current plugin&#8230;' );
$this->strings['remove_old_failed'] = __( 'Could not remove the current plugin.' );
$this->strings['no_files'] = __( 'The plugin contains no files.' );
$this->strings['process_failed'] = __( 'Plugin installation failed.' );
$this->strings['process_success'] = __( 'Plugin installed successfully.' );
/* translators: 1: Plugin name, 2: Plugin version. */
$this->strings['process_success_specific'] = __( 'Successfully installed the plugin <strong>%1$s %2$s</strong>.' );
if ( ! empty( $this->skin->overwrite ) ) {
if ( 'update-plugin' === $this->skin->overwrite ) {
$this->strings['installing_package'] = __( 'Updating the plugin&#8230;' );
$this->strings['process_failed'] = __( 'Plugin update failed.' );
$this->strings['process_success'] = __( 'Plugin updated successfully.' );
}
if ( 'downgrade-plugin' === $this->skin->overwrite ) {
$this->strings['installing_package'] = __( 'Downgrading the plugin&#8230;' );
$this->strings['process_failed'] = __( 'Plugin downgrade failed.' );
$this->strings['process_success'] = __( 'Plugin downgraded successfully.' );
}
}
}
/**
* Install a plugin package.
*
* @since 2.8.0
* @since 3.7.0 The `$args` parameter was added, making clearing the plugin update cache optional.
*
* @param string $package The full local path or URI of the package.
* @param array $args {
* Optional. Other arguments for installing a plugin package. Default empty array.
*
* @type bool $clear_update_cache Whether to clear the plugin updates cache if successful.
* Default true.
* }
* @return bool|WP_Error True if the installation was successful, false or a WP_Error otherwise.
*/
public function install( $package, $args = array() ) {
$defaults = array(
'clear_update_cache' => true,
'overwrite_package' => false, // Do not overwrite files.
);
$parsed_args = wp_parse_args( $args, $defaults );
$this->init();
$this->install_strings();
add_filter( 'upgrader_source_selection', array( $this, 'check_package' ) );
if ( $parsed_args['clear_update_cache'] ) {
// Clear cache so wp_update_plugins() knows about the new plugin.
add_action( 'upgrader_process_complete', 'wp_clean_plugins_cache', 9, 0 );
}
$this->run(
array(
'package' => $package,
'destination' => WP_PLUGIN_DIR,
'clear_destination' => $parsed_args['overwrite_package'],
'clear_working' => true,
'hook_extra' => array(
'type' => 'plugin',
'action' => 'install',
),
)
);
remove_action( 'upgrader_process_complete', 'wp_clean_plugins_cache', 9 );
remove_filter( 'upgrader_source_selection', array( $this, 'check_package' ) );
if ( ! $this->result || is_wp_error( $this->result ) ) {
return $this->result;
}
// Force refresh of plugin update information.
wp_clean_plugins_cache( $parsed_args['clear_update_cache'] );
if ( $parsed_args['overwrite_package'] ) {
/**
* Fires when the upgrader has successfully overwritten a currently installed
* plugin or theme with an uploaded zip package.
*
* @since 5.5.0
*
* @param string $package The package file.
* @param array $data The new plugin or theme data.
* @param string $package_type The package type ('plugin' or 'theme').
*/
do_action( 'upgrader_overwrote_package', $package, $this->new_plugin_data, 'plugin' );
}
return true;
}
/**
* Upgrades a plugin.
*
* @since 2.8.0
* @since 3.7.0 The `$args` parameter was added, making clearing the plugin update cache optional.
*
* @param string $plugin Path to the plugin file relative to the plugins directory.
* @param array $args {
* Optional. Other arguments for upgrading a plugin package. Default empty array.
*
* @type bool $clear_update_cache Whether to clear the plugin updates cache if successful.
* Default true.
* }
* @return bool|WP_Error True if the upgrade was successful, false or a WP_Error object otherwise.
*/
public function upgrade( $plugin, $args = array() ) {
$defaults = array(
'clear_update_cache' => true,
);
$parsed_args = wp_parse_args( $args, $defaults );
$this->init();
$this->upgrade_strings();
$current = get_site_transient( 'update_plugins' );
if ( ! isset( $current->response[ $plugin ] ) ) {
$this->skin->before();
$this->skin->set_result( false );
$this->skin->error( 'up_to_date' );
$this->skin->after();
return false;
}
// Get the URL to the zip file.
$r = $current->response[ $plugin ];
add_filter( 'upgrader_pre_install', array( $this, 'deactivate_plugin_before_upgrade' ), 10, 2 );
add_filter( 'upgrader_pre_install', array( $this, 'active_before' ), 10, 2 );
add_filter( 'upgrader_clear_destination', array( $this, 'delete_old_plugin' ), 10, 4 );
add_filter( 'upgrader_post_install', array( $this, 'active_after' ), 10, 2 );
/*
* There's a Trac ticket to move up the directory for zips which are made a bit differently, useful for non-.org plugins.
* 'source_selection' => array( $this, 'source_selection' ),
*/
if ( $parsed_args['clear_update_cache'] ) {
// Clear cache so wp_update_plugins() knows about the new plugin.
add_action( 'upgrader_process_complete', 'wp_clean_plugins_cache', 9, 0 );
}
$this->run(
array(
'package' => $r->package,
'destination' => WP_PLUGIN_DIR,
'clear_destination' => true,
'clear_working' => true,
'hook_extra' => array(
'plugin' => $plugin,
'type' => 'plugin',
'action' => 'update',
'temp_backup' => array(
'slug' => dirname( $plugin ),
'src' => WP_PLUGIN_DIR,
'dir' => 'plugins',
),
),
)
);
// Cleanup our hooks, in case something else does an upgrade on this connection.
remove_action( 'upgrader_process_complete', 'wp_clean_plugins_cache', 9 );
remove_filter( 'upgrader_pre_install', array( $this, 'deactivate_plugin_before_upgrade' ) );
remove_filter( 'upgrader_pre_install', array( $this, 'active_before' ) );
remove_filter( 'upgrader_clear_destination', array( $this, 'delete_old_plugin' ) );
remove_filter( 'upgrader_post_install', array( $this, 'active_after' ) );
if ( ! $this->result || is_wp_error( $this->result ) ) {
return $this->result;
}
// Force refresh of plugin update information.
wp_clean_plugins_cache( $parsed_args['clear_update_cache'] );
/*
* Ensure any future auto-update failures trigger a failure email by removing
* the last failure notification from the list when plugins update successfully.
*/
$past_failure_emails = get_option( 'auto_plugin_theme_update_emails', array() );
if ( isset( $past_failure_emails[ $plugin ] ) ) {
unset( $past_failure_emails[ $plugin ] );
update_option( 'auto_plugin_theme_update_emails', $past_failure_emails );
}
return true;
}
/**
* Upgrades several plugins at once.
*
* @since 2.8.0
* @since 3.7.0 The `$args` parameter was added, making clearing the plugin update cache optional.
*
* @global string $wp_version The WordPress version string.
*
* @param string[] $plugins Array of paths to plugin files relative to the plugins directory.
* @param array $args {
* Optional. Other arguments for upgrading several plugins at once.
*
* @type bool $clear_update_cache Whether to clear the plugin updates cache if successful. Default true.
* }
* @return array|false An array of results indexed by plugin file, or false if unable to connect to the filesystem.
*/
public function bulk_upgrade( $plugins, $args = array() ) {
global $wp_version;
$defaults = array(
'clear_update_cache' => true,
);
$parsed_args = wp_parse_args( $args, $defaults );
$this->init();
$this->bulk = true;
$this->upgrade_strings();
$current = get_site_transient( 'update_plugins' );
add_filter( 'upgrader_clear_destination', array( $this, 'delete_old_plugin' ), 10, 4 );
$this->skin->header();
// Connect to the filesystem first.
$res = $this->fs_connect( array( WP_CONTENT_DIR, WP_PLUGIN_DIR ) );
if ( ! $res ) {
$this->skin->footer();
return false;
}
$this->skin->bulk_header();
/*
* Only start maintenance mode if:
* - running Multisite and there are one or more plugins specified, OR
* - a plugin with an update available is currently active.
* @todo For multisite, maintenance mode should only kick in for individual sites if at all possible.
*/
$maintenance = ( is_multisite() && ! empty( $plugins ) );
foreach ( $plugins as $plugin ) {
$maintenance = $maintenance || ( is_plugin_active( $plugin ) && isset( $current->response[ $plugin ] ) );
}
if ( $maintenance ) {
$this->maintenance_mode( true );
}
$results = array();
$this->update_count = count( $plugins );
$this->update_current = 0;
foreach ( $plugins as $plugin ) {
++$this->update_current;
$this->skin->plugin_info = get_plugin_data( WP_PLUGIN_DIR . '/' . $plugin, false, true );
if ( ! isset( $current->response[ $plugin ] ) ) {
$this->skin->set_result( 'up_to_date' );
$this->skin->before();
$this->skin->feedback( 'up_to_date' );
$this->skin->after();
$results[ $plugin ] = true;
continue;
}
// Get the URL to the zip file.
$r = $current->response[ $plugin ];
$this->skin->plugin_active = is_plugin_active( $plugin );
if ( isset( $r->requires ) && ! is_wp_version_compatible( $r->requires ) ) {
$result = new WP_Error(
'incompatible_wp_required_version',
sprintf(
/* translators: 1: Current WordPress version, 2: WordPress version required by the new plugin version. */
__( 'Your WordPress version is %1$s, however the new plugin version requires %2$s.' ),
$wp_version,
$r->requires
)
);
$this->skin->before( $result );
$this->skin->error( $result );
$this->skin->after();
} elseif ( isset( $r->requires_php ) && ! is_php_version_compatible( $r->requires_php ) ) {
$result = new WP_Error(
'incompatible_php_required_version',
sprintf(
/* translators: 1: Current PHP version, 2: PHP version required by the new plugin version. */
__( 'The PHP version on your server is %1$s, however the new plugin version requires %2$s.' ),
PHP_VERSION,
$r->requires_php
)
);
$this->skin->before( $result );
$this->skin->error( $result );
$this->skin->after();
} else {
add_filter( 'upgrader_source_selection', array( $this, 'check_package' ) );
$result = $this->run(
array(
'package' => $r->package,
'destination' => WP_PLUGIN_DIR,
'clear_destination' => true,
'clear_working' => true,
'is_multi' => true,
'hook_extra' => array(
'plugin' => $plugin,
'temp_backup' => array(
'slug' => dirname( $plugin ),
'src' => WP_PLUGIN_DIR,
'dir' => 'plugins',
),
),
)
);
remove_filter( 'upgrader_source_selection', array( $this, 'check_package' ) );
}
$results[ $plugin ] = $result;
// Prevent credentials auth screen from displaying multiple times.
if ( false === $result ) {
break;
}
} // End foreach $plugins.
$this->maintenance_mode( false );
// Force refresh of plugin update information.
wp_clean_plugins_cache( $parsed_args['clear_update_cache'] );
/** This action is documented in wp-admin/includes/class-wp-upgrader.php */
do_action(
'upgrader_process_complete',
$this,
array(
'action' => 'update',
'type' => 'plugin',
'bulk' => true,
'plugins' => $plugins,
)
);
$this->skin->bulk_footer();
$this->skin->footer();
// Cleanup our hooks, in case something else does an upgrade on this connection.
remove_filter( 'upgrader_clear_destination', array( $this, 'delete_old_plugin' ) );
/*
* Ensure any future auto-update failures trigger a failure email by removing
* the last failure notification from the list when plugins update successfully.
*/
$past_failure_emails = get_option( 'auto_plugin_theme_update_emails', array() );
foreach ( $results as $plugin => $result ) {
// Maintain last failure notification when plugins failed to update manually.
if ( ! $result || is_wp_error( $result ) || ! isset( $past_failure_emails[ $plugin ] ) ) {
continue;
}
unset( $past_failure_emails[ $plugin ] );
}
update_option( 'auto_plugin_theme_update_emails', $past_failure_emails );
return $results;
}
/**
* Checks that the source package contains a valid plugin.
*
* Hooked to the {@see 'upgrader_source_selection'} filter by Plugin_Upgrader::install().
*
* @since 3.3.0
*
* @global WP_Filesystem_Base $wp_filesystem WordPress filesystem subclass.
* @global string $wp_version The WordPress version string.
*
* @param string $source The path to the downloaded package source.
* @return string|WP_Error The source as passed, or a WP_Error object on failure.
*/
public function check_package( $source ) {
global $wp_filesystem, $wp_version;
$this->new_plugin_data = array();
if ( is_wp_error( $source ) ) {
return $source;
}
$working_directory = str_replace( $wp_filesystem->wp_content_dir(), trailingslashit( WP_CONTENT_DIR ), $source );
if ( ! is_dir( $working_directory ) ) { // Confidence check, if the above fails, let's not prevent installation.
return $source;
}
// Check that the folder contains at least 1 valid plugin.
$files = glob( $working_directory . '*.php' );
if ( $files ) {
foreach ( $files as $file ) {
$info = get_plugin_data( $file, false, false );
if ( ! empty( $info['Name'] ) ) {
$this->new_plugin_data = $info;
break;
}
}
}
if ( empty( $this->new_plugin_data ) ) {
return new WP_Error( 'incompatible_archive_no_plugins', $this->strings['incompatible_archive'], __( 'No valid plugins were found.' ) );
}
$requires_php = isset( $info['RequiresPHP'] ) ? $info['RequiresPHP'] : null;
$requires_wp = isset( $info['RequiresWP'] ) ? $info['RequiresWP'] : null;
if ( ! is_php_version_compatible( $requires_php ) ) {
$error = sprintf(
/* translators: 1: Current PHP version, 2: Version required by the uploaded plugin. */
__( 'The PHP version on your server is %1$s, however the uploaded plugin requires %2$s.' ),
PHP_VERSION,
$requires_php
);
return new WP_Error( 'incompatible_php_required_version', $this->strings['incompatible_archive'], $error );
}
if ( ! is_wp_version_compatible( $requires_wp ) ) {
$error = sprintf(
/* translators: 1: Current WordPress version, 2: Version required by the uploaded plugin. */
__( 'Your WordPress version is %1$s, however the uploaded plugin requires %2$s.' ),
$wp_version,
$requires_wp
);
return new WP_Error( 'incompatible_wp_required_version', $this->strings['incompatible_archive'], $error );
}
return $source;
}
/**
* Retrieves the path to the file that contains the plugin info.
*
* This isn't used internally in the class, but is called by the skins.
*
* @since 2.8.0
*
* @return string|false The full path to the main plugin file, or false.
*/
public function plugin_info() {
if ( ! is_array( $this->result ) ) {
return false;
}
if ( empty( $this->result['destination_name'] ) ) {
return false;
}
// Ensure to pass with leading slash.
$plugin = get_plugins( '/' . $this->result['destination_name'] );
if ( empty( $plugin ) ) {
return false;
}
// Assume the requested plugin is the first in the list.
$pluginfiles = array_keys( $plugin );
return $this->result['destination_name'] . '/' . $pluginfiles[0];
}
/**
* Deactivates a plugin before it is upgraded.
*
* Hooked to the {@see 'upgrader_pre_install'} filter by Plugin_Upgrader::upgrade().
*
* @since 2.8.0
* @since 4.1.0 Added a return value.
*
* @param bool|WP_Error $response The installation response before the installation has started.
* @param array $plugin Plugin package arguments.
* @return bool|WP_Error The original `$response` parameter or WP_Error.
*/
public function deactivate_plugin_before_upgrade( $response, $plugin ) {
if ( is_wp_error( $response ) ) { // Bypass.
return $response;
}
// When in cron (background updates) don't deactivate the plugin, as we require a browser to reactivate it.
if ( wp_doing_cron() ) {
return $response;
}
$plugin = isset( $plugin['plugin'] ) ? $plugin['plugin'] : '';
if ( empty( $plugin ) ) {
return new WP_Error( 'bad_request', $this->strings['bad_request'] );
}
if ( is_plugin_active( $plugin ) ) {
// Deactivate the plugin silently, Prevent deactivation hooks from running.
deactivate_plugins( $plugin, true );
}
return $response;
}
/**
* Turns on maintenance mode before attempting to background update an active plugin.
*
* Hooked to the {@see 'upgrader_pre_install'} filter by Plugin_Upgrader::upgrade().
*
* @since 5.4.0
*
* @param bool|WP_Error $response The installation response before the installation has started.
* @param array $plugin Plugin package arguments.
* @return bool|WP_Error The original `$response` parameter or WP_Error.
*/
public function active_before( $response, $plugin ) {
if ( is_wp_error( $response ) ) {
return $response;
}
// Only enable maintenance mode when in cron (background update).
if ( ! wp_doing_cron() ) {
return $response;
}
$plugin = isset( $plugin['plugin'] ) ? $plugin['plugin'] : '';
// Only run if plugin is active.
if ( ! is_plugin_active( $plugin ) ) {
return $response;
}
// Change to maintenance mode. Bulk edit handles this separately.
if ( ! $this->bulk ) {
$this->maintenance_mode( true );
}
return $response;
}
/**
* Turns off maintenance mode after upgrading an active plugin.
*
* Hooked to the {@see 'upgrader_post_install'} filter by Plugin_Upgrader::upgrade().
*
* @since 5.4.0
*
* @param bool|WP_Error $response The installation response after the installation has finished.
* @param array $plugin Plugin package arguments.
* @return bool|WP_Error The original `$response` parameter or WP_Error.
*/
public function active_after( $response, $plugin ) {
if ( is_wp_error( $response ) ) {
return $response;
}
// Only disable maintenance mode when in cron (background update).
if ( ! wp_doing_cron() ) {
return $response;
}
$plugin = isset( $plugin['plugin'] ) ? $plugin['plugin'] : '';
// Only run if plugin is active.
if ( ! is_plugin_active( $plugin ) ) {
return $response;
}
// Time to remove maintenance mode. Bulk edit handles this separately.
if ( ! $this->bulk ) {
$this->maintenance_mode( false );
}
return $response;
}
/**
* Deletes the old plugin during an upgrade.
*
* Hooked to the {@see 'upgrader_clear_destination'} filter by
* Plugin_Upgrader::upgrade() and Plugin_Upgrader::bulk_upgrade().
*
* @since 2.8.0
*
* @global WP_Filesystem_Base $wp_filesystem WordPress filesystem subclass.
*
* @param bool|WP_Error $removed Whether the destination was cleared.
* True on success, WP_Error on failure.
* @param string $local_destination The local package destination.
* @param string $remote_destination The remote package destination.
* @param array $plugin Extra arguments passed to hooked filters.
* @return bool|WP_Error
*/
public function delete_old_plugin( $removed, $local_destination, $remote_destination, $plugin ) {
global $wp_filesystem;
if ( is_wp_error( $removed ) ) {
return $removed; // Pass errors through.
}
$plugin = isset( $plugin['plugin'] ) ? $plugin['plugin'] : '';
if ( empty( $plugin ) ) {
return new WP_Error( 'bad_request', $this->strings['bad_request'] );
}
$plugins_dir = $wp_filesystem->wp_plugins_dir();
$this_plugin_dir = trailingslashit( dirname( $plugins_dir . $plugin ) );
if ( ! $wp_filesystem->exists( $this_plugin_dir ) ) { // If it's already vanished.
return $removed;
}
/*
* If plugin is in its own directory, recursively delete the directory.
* Base check on if plugin includes directory separator AND that it's not the root plugin folder.
*/
if ( strpos( $plugin, '/' ) && $this_plugin_dir !== $plugins_dir ) {
$deleted = $wp_filesystem->delete( $this_plugin_dir, true );
} else {
$deleted = $wp_filesystem->delete( $plugins_dir . $plugin );
}
if ( ! $deleted ) {
return new WP_Error( 'remove_old_failed', $this->strings['remove_old_failed'] );
}
return true;
}
}

View File

@ -0,0 +1,384 @@
<?php
/**
* Upgrader API: Theme_Installer_Skin class
*
* @package WordPress
* @subpackage Upgrader
* @since 4.6.0
*/
/**
* Theme Installer Skin for the WordPress Theme Installer.
*
* @since 2.8.0
* @since 4.6.0 Moved to its own file from wp-admin/includes/class-wp-upgrader-skins.php.
*
* @see WP_Upgrader_Skin
*/
class Theme_Installer_Skin extends WP_Upgrader_Skin {
public $api;
public $type;
public $url;
public $overwrite;
private $is_downgrading = false;
/**
* @param array $args
*/
public function __construct( $args = array() ) {
$defaults = array(
'type' => 'web',
'url' => '',
'theme' => '',
'nonce' => '',
'title' => '',
'overwrite' => '',
);
$args = wp_parse_args( $args, $defaults );
$this->type = $args['type'];
$this->url = $args['url'];
$this->api = isset( $args['api'] ) ? $args['api'] : array();
$this->overwrite = $args['overwrite'];
parent::__construct( $args );
}
/**
* Performs an action before installing a theme.
*
* @since 2.8.0
*/
public function before() {
if ( ! empty( $this->api ) ) {
$this->upgrader->strings['process_success'] = sprintf(
$this->upgrader->strings['process_success_specific'],
$this->api->name,
$this->api->version
);
}
}
/**
* Hides the `process_failed` error when updating a theme by uploading a zip file.
*
* @since 5.5.0
*
* @param WP_Error $wp_error WP_Error object.
* @return bool True if the error should be hidden, false otherwise.
*/
public function hide_process_failed( $wp_error ) {
if (
'upload' === $this->type &&
'' === $this->overwrite &&
$wp_error->get_error_code() === 'folder_exists'
) {
return true;
}
return false;
}
/**
* Performs an action following a single theme install.
*
* @since 2.8.0
*/
public function after() {
if ( $this->do_overwrite() ) {
return;
}
if ( empty( $this->upgrader->result['destination_name'] ) ) {
return;
}
$theme_info = $this->upgrader->theme_info();
if ( empty( $theme_info ) ) {
return;
}
$name = $theme_info->display( 'Name' );
$stylesheet = $this->upgrader->result['destination_name'];
$template = $theme_info->get_template();
$activate_link = add_query_arg(
array(
'action' => 'activate',
'template' => urlencode( $template ),
'stylesheet' => urlencode( $stylesheet ),
),
admin_url( 'themes.php' )
);
$activate_link = wp_nonce_url( $activate_link, 'switch-theme_' . $stylesheet );
$install_actions = array();
if ( current_user_can( 'edit_theme_options' ) && current_user_can( 'customize' ) && ! $theme_info->is_block_theme() ) {
$customize_url = add_query_arg(
array(
'theme' => urlencode( $stylesheet ),
'return' => urlencode( admin_url( 'web' === $this->type ? 'theme-install.php' : 'themes.php' ) ),
),
admin_url( 'customize.php' )
);
$install_actions['preview'] = sprintf(
'<a href="%s" class="hide-if-no-customize load-customize">' .
'<span aria-hidden="true">%s</span><span class="screen-reader-text">%s</span></a>',
esc_url( $customize_url ),
__( 'Live Preview' ),
/* translators: Hidden accessibility text. %s: Theme name. */
sprintf( __( 'Live Preview &#8220;%s&#8221;' ), $name )
);
}
$install_actions['activate'] = sprintf(
'<a href="%s" class="activatelink">' .
'<span aria-hidden="true">%s</span><span class="screen-reader-text">%s</span></a>',
esc_url( $activate_link ),
_x( 'Activate', 'theme' ),
/* translators: Hidden accessibility text. %s: Theme name. */
sprintf( _x( 'Activate &#8220;%s&#8221;', 'theme' ), $name )
);
if ( is_network_admin() && current_user_can( 'manage_network_themes' ) ) {
$install_actions['network_enable'] = sprintf(
'<a href="%s" target="_parent">%s</a>',
esc_url( wp_nonce_url( 'themes.php?action=enable&amp;theme=' . urlencode( $stylesheet ), 'enable-theme_' . $stylesheet ) ),
__( 'Network Enable' )
);
}
if ( 'web' === $this->type ) {
$install_actions['themes_page'] = sprintf(
'<a href="%s" target="_parent">%s</a>',
self_admin_url( 'theme-install.php' ),
__( 'Go to Theme Installer' )
);
} elseif ( current_user_can( 'switch_themes' ) || current_user_can( 'edit_theme_options' ) ) {
$install_actions['themes_page'] = sprintf(
'<a href="%s" target="_parent">%s</a>',
self_admin_url( 'themes.php' ),
__( 'Go to Themes page' )
);
}
if ( ! $this->result || is_wp_error( $this->result ) || is_network_admin() || ! current_user_can( 'switch_themes' ) ) {
unset( $install_actions['activate'], $install_actions['preview'] );
} elseif ( get_option( 'template' ) === $stylesheet ) {
unset( $install_actions['activate'] );
}
/**
* Filters the list of action links available following a single theme installation.
*
* @since 2.8.0
*
* @param string[] $install_actions Array of theme action links.
* @param object $api Object containing WordPress.org API theme data.
* @param string $stylesheet Theme directory name.
* @param WP_Theme $theme_info Theme object.
*/
$install_actions = apply_filters( 'install_theme_complete_actions', $install_actions, $this->api, $stylesheet, $theme_info );
if ( ! empty( $install_actions ) ) {
$this->feedback( implode( ' | ', (array) $install_actions ) );
}
}
/**
* Checks if the theme can be overwritten and outputs the HTML for overwriting a theme on upload.
*
* @since 5.5.0
*
* @return bool Whether the theme can be overwritten and HTML was outputted.
*/
private function do_overwrite() {
if ( 'upload' !== $this->type || ! is_wp_error( $this->result ) || 'folder_exists' !== $this->result->get_error_code() ) {
return false;
}
$folder = $this->result->get_error_data( 'folder_exists' );
$folder = rtrim( $folder, '/' );
$current_theme_data = false;
$all_themes = wp_get_themes( array( 'errors' => null ) );
foreach ( $all_themes as $theme ) {
$stylesheet_dir = wp_normalize_path( $theme->get_stylesheet_directory() );
if ( rtrim( $stylesheet_dir, '/' ) !== $folder ) {
continue;
}
$current_theme_data = $theme;
}
$new_theme_data = $this->upgrader->new_theme_data;
if ( ! $current_theme_data || ! $new_theme_data ) {
return false;
}
echo '<h2 class="update-from-upload-heading">' . esc_html__( 'This theme is already installed.' ) . '</h2>';
// Check errors for active theme.
if ( is_wp_error( $current_theme_data->errors() ) ) {
$this->feedback( 'current_theme_has_errors', $current_theme_data->errors()->get_error_message() );
}
$this->is_downgrading = version_compare( $current_theme_data['Version'], $new_theme_data['Version'], '>' );
$is_invalid_parent = false;
if ( ! empty( $new_theme_data['Template'] ) ) {
$is_invalid_parent = ! in_array( $new_theme_data['Template'], array_keys( $all_themes ), true );
}
$rows = array(
'Name' => __( 'Theme name' ),
'Version' => __( 'Version' ),
'Author' => __( 'Author' ),
'RequiresWP' => __( 'Required WordPress version' ),
'RequiresPHP' => __( 'Required PHP version' ),
'Template' => __( 'Parent theme' ),
);
$table = '<table class="update-from-upload-comparison"><tbody>';
$table .= '<tr><th></th><th>' . esc_html_x( 'Active', 'theme' ) . '</th><th>' . esc_html_x( 'Uploaded', 'theme' ) . '</th></tr>';
$is_same_theme = true; // Let's consider only these rows.
foreach ( $rows as $field => $label ) {
$old_value = $current_theme_data->display( $field, false );
$old_value = $old_value ? (string) $old_value : '-';
$new_value = ! empty( $new_theme_data[ $field ] ) ? (string) $new_theme_data[ $field ] : '-';
if ( $old_value === $new_value && '-' === $new_value && 'Template' === $field ) {
continue;
}
$is_same_theme = $is_same_theme && ( $old_value === $new_value );
$diff_field = ( 'Version' !== $field && $new_value !== $old_value );
$diff_version = ( 'Version' === $field && $this->is_downgrading );
$invalid_parent = false;
if ( 'Template' === $field && $is_invalid_parent ) {
$invalid_parent = true;
$new_value .= ' ' . __( '(not found)' );
}
$table .= '<tr><td class="name-label">' . $label . '</td><td>' . wp_strip_all_tags( $old_value ) . '</td>';
$table .= ( $diff_field || $diff_version || $invalid_parent ) ? '<td class="warning">' : '<td>';
$table .= wp_strip_all_tags( $new_value ) . '</td></tr>';
}
$table .= '</tbody></table>';
/**
* Filters the compare table output for overwriting a theme package on upload.
*
* @since 5.5.0
*
* @param string $table The output table with Name, Version, Author, RequiresWP, and RequiresPHP info.
* @param WP_Theme $current_theme_data Active theme data.
* @param array $new_theme_data Array with uploaded theme data.
*/
echo apply_filters( 'install_theme_overwrite_comparison', $table, $current_theme_data, $new_theme_data );
$install_actions = array();
$can_update = true;
$blocked_message = '<p>' . esc_html__( 'The theme cannot be updated due to the following:' ) . '</p>';
$blocked_message .= '<ul class="ul-disc">';
$requires_php = isset( $new_theme_data['RequiresPHP'] ) ? $new_theme_data['RequiresPHP'] : null;
$requires_wp = isset( $new_theme_data['RequiresWP'] ) ? $new_theme_data['RequiresWP'] : null;
if ( ! is_php_version_compatible( $requires_php ) ) {
$error = sprintf(
/* translators: 1: Current PHP version, 2: Version required by the uploaded theme. */
__( 'The PHP version on your server is %1$s, however the uploaded theme requires %2$s.' ),
PHP_VERSION,
$requires_php
);
$blocked_message .= '<li>' . esc_html( $error ) . '</li>';
$can_update = false;
}
if ( ! is_wp_version_compatible( $requires_wp ) ) {
$error = sprintf(
/* translators: 1: Current WordPress version, 2: Version required by the uploaded theme. */
__( 'Your WordPress version is %1$s, however the uploaded theme requires %2$s.' ),
get_bloginfo( 'version' ),
$requires_wp
);
$blocked_message .= '<li>' . esc_html( $error ) . '</li>';
$can_update = false;
}
$blocked_message .= '</ul>';
if ( $can_update ) {
if ( $this->is_downgrading ) {
$warning = sprintf(
/* translators: %s: Documentation URL. */
__( 'You are uploading an older version of the active theme. You can continue to install the older version, but be sure to <a href="%s">back up your database and files</a> first.' ),
__( 'https://wordpress.org/documentation/article/wordpress-backups/' )
);
} else {
$warning = sprintf(
/* translators: %s: Documentation URL. */
__( 'You are updating a theme. Be sure to <a href="%s">back up your database and files</a> first.' ),
__( 'https://wordpress.org/documentation/article/wordpress-backups/' )
);
}
echo '<p class="update-from-upload-notice">' . $warning . '</p>';
$overwrite = $this->is_downgrading ? 'downgrade-theme' : 'update-theme';
$install_actions['overwrite_theme'] = sprintf(
'<a class="button button-primary update-from-upload-overwrite" href="%s" target="_parent">%s</a>',
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(
'<a class="button" href="%s" target="_parent">%s</a>',
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(
'<p class="update-from-upload-expired hidden">%s</p>',
__( 'The uploaded file has expired. Please go back and upload it again.' )
);
echo '<p class="update-from-upload-actions">' . implode( ' ', (array) $install_actions ) . '</p>';
}
return true;
}
}

View File

@ -0,0 +1,144 @@
<?php
/**
* Upgrader API: Theme_Upgrader_Skin class
*
* @package WordPress
* @subpackage Upgrader
* @since 4.6.0
*/
/**
* Theme Upgrader Skin for WordPress Theme Upgrades.
*
* @since 2.8.0
* @since 4.6.0 Moved to its own file from wp-admin/includes/class-wp-upgrader-skins.php.
*
* @see WP_Upgrader_Skin
*/
class Theme_Upgrader_Skin extends WP_Upgrader_Skin {
/**
* Holds the theme slug in the Theme Directory.
*
* @since 2.8.0
*
* @var string
*/
public $theme = '';
/**
* Constructor.
*
* Sets up the theme upgrader skin.
*
* @since 2.8.0
*
* @param array $args Optional. The theme upgrader skin arguments to
* override default options. Default empty array.
*/
public function __construct( $args = array() ) {
$defaults = array(
'url' => '',
'theme' => '',
'nonce' => '',
'title' => __( 'Update Theme' ),
);
$args = wp_parse_args( $args, $defaults );
$this->theme = $args['theme'];
parent::__construct( $args );
}
/**
* Performs an action following a single theme update.
*
* @since 2.8.0
*/
public function after() {
$this->decrement_update_count( 'theme' );
$update_actions = array();
$theme_info = $this->upgrader->theme_info();
if ( $theme_info ) {
$name = $theme_info->display( 'Name' );
$stylesheet = $this->upgrader->result['destination_name'];
$template = $theme_info->get_template();
$activate_link = add_query_arg(
array(
'action' => 'activate',
'template' => urlencode( $template ),
'stylesheet' => urlencode( $stylesheet ),
),
admin_url( 'themes.php' )
);
$activate_link = wp_nonce_url( $activate_link, 'switch-theme_' . $stylesheet );
$customize_url = add_query_arg(
array(
'theme' => urlencode( $stylesheet ),
'return' => urlencode( admin_url( 'themes.php' ) ),
),
admin_url( 'customize.php' )
);
if ( get_stylesheet() === $stylesheet ) {
if ( current_user_can( 'edit_theme_options' ) && current_user_can( 'customize' ) ) {
$update_actions['preview'] = sprintf(
'<a href="%s" class="hide-if-no-customize load-customize">' .
'<span aria-hidden="true">%s</span><span class="screen-reader-text">%s</span></a>',
esc_url( $customize_url ),
__( 'Customize' ),
/* translators: Hidden accessibility text. %s: Theme name. */
sprintf( __( 'Customize &#8220;%s&#8221;' ), $name )
);
}
} elseif ( current_user_can( 'switch_themes' ) ) {
if ( current_user_can( 'edit_theme_options' ) && current_user_can( 'customize' ) ) {
$update_actions['preview'] = sprintf(
'<a href="%s" class="hide-if-no-customize load-customize">' .
'<span aria-hidden="true">%s</span><span class="screen-reader-text">%s</span></a>',
esc_url( $customize_url ),
__( 'Live Preview' ),
/* translators: Hidden accessibility text. %s: Theme name. */
sprintf( __( 'Live Preview &#8220;%s&#8221;' ), $name )
);
}
$update_actions['activate'] = sprintf(
'<a href="%s" class="activatelink">' .
'<span aria-hidden="true">%s</span><span class="screen-reader-text">%s</span></a>',
esc_url( $activate_link ),
_x( 'Activate', 'theme' ),
/* translators: Hidden accessibility text. %s: Theme name. */
sprintf( _x( 'Activate &#8220;%s&#8221;', 'theme' ), $name )
);
}
if ( ! $this->result || is_wp_error( $this->result ) || is_network_admin() ) {
unset( $update_actions['preview'], $update_actions['activate'] );
}
}
$update_actions['themes_page'] = sprintf(
'<a href="%s" target="_parent">%s</a>',
self_admin_url( 'themes.php' ),
__( 'Go to Themes page' )
);
/**
* Filters the list of action links available following a single theme update.
*
* @since 2.8.0
*
* @param string[] $update_actions Array of theme action links.
* @param string $theme Theme directory name.
*/
$update_actions = apply_filters( 'update_theme_complete_actions', $update_actions, $this->theme );
if ( ! empty( $update_actions ) ) {
$this->feedback( implode( ' | ', (array) $update_actions ) );
}
}
}

View File

@ -0,0 +1,807 @@
<?php
/**
* Upgrade API: Theme_Upgrader class
*
* @package WordPress
* @subpackage Upgrader
* @since 4.6.0
*/
/**
* Core class used for upgrading/installing themes.
*
* It is designed to upgrade/install themes from a local zip, remote zip URL,
* or uploaded zip file.
*
* @since 2.8.0
* @since 4.6.0 Moved to its own file from wp-admin/includes/class-wp-upgrader.php.
*
* @see WP_Upgrader
*/
class Theme_Upgrader extends WP_Upgrader {
/**
* Result of the theme upgrade offer.
*
* @since 2.8.0
* @var array|WP_Error $result
* @see WP_Upgrader::$result
*/
public $result;
/**
* Whether multiple themes are being upgraded/installed in bulk.
*
* @since 2.9.0
* @var bool $bulk
*/
public $bulk = false;
/**
* New theme info.
*
* @since 5.5.0
* @var array $new_theme_data
*
* @see check_package()
*/
public $new_theme_data = array();
/**
* Initializes the upgrade strings.
*
* @since 2.8.0
*/
public function upgrade_strings() {
$this->strings['up_to_date'] = __( 'The theme is at the latest version.' );
$this->strings['no_package'] = __( 'Update package not available.' );
/* translators: %s: Package URL. */
$this->strings['downloading_package'] = sprintf( __( 'Downloading update from %s&#8230;' ), '<span class="code pre">%s</span>' );
$this->strings['unpack_package'] = __( 'Unpacking the update&#8230;' );
$this->strings['remove_old'] = __( 'Removing the old version of the theme&#8230;' );
$this->strings['remove_old_failed'] = __( 'Could not remove the old theme.' );
$this->strings['process_failed'] = __( 'Theme update failed.' );
$this->strings['process_success'] = __( 'Theme updated successfully.' );
}
/**
* Initializes the installation strings.
*
* @since 2.8.0
*/
public function install_strings() {
$this->strings['no_package'] = __( 'Installation package not available.' );
/* translators: %s: Package URL. */
$this->strings['downloading_package'] = sprintf( __( 'Downloading installation package from %s&#8230;' ), '<span class="code pre">%s</span>' );
$this->strings['unpack_package'] = __( 'Unpacking the package&#8230;' );
$this->strings['installing_package'] = __( 'Installing the theme&#8230;' );
$this->strings['remove_old'] = __( 'Removing the old version of the theme&#8230;' );
$this->strings['remove_old_failed'] = __( 'Could not remove the old theme.' );
$this->strings['no_files'] = __( 'The theme contains no files.' );
$this->strings['process_failed'] = __( 'Theme installation failed.' );
$this->strings['process_success'] = __( 'Theme installed successfully.' );
/* translators: 1: Theme name, 2: Theme version. */
$this->strings['process_success_specific'] = __( 'Successfully installed the theme <strong>%1$s %2$s</strong>.' );
$this->strings['parent_theme_search'] = __( 'This theme requires a parent theme. Checking if it is installed&#8230;' );
/* translators: 1: Theme name, 2: Theme version. */
$this->strings['parent_theme_prepare_install'] = __( 'Preparing to install <strong>%1$s %2$s</strong>&#8230;' );
/* translators: 1: Theme name, 2: Theme version. */
$this->strings['parent_theme_currently_installed'] = __( 'The parent theme, <strong>%1$s %2$s</strong>, is currently installed.' );
/* translators: 1: Theme name, 2: Theme version. */
$this->strings['parent_theme_install_success'] = __( 'Successfully installed the parent theme, <strong>%1$s %2$s</strong>.' );
/* translators: %s: Theme name. */
$this->strings['parent_theme_not_found'] = sprintf( __( '<strong>The parent theme could not be found.</strong> You will need to install the parent theme, %s, before you can use this child theme.' ), '<strong>%s</strong>' );
/* translators: %s: Theme error. */
$this->strings['current_theme_has_errors'] = __( 'The active theme has the following error: "%s".' );
if ( ! empty( $this->skin->overwrite ) ) {
if ( 'update-theme' === $this->skin->overwrite ) {
$this->strings['installing_package'] = __( 'Updating the theme&#8230;' );
$this->strings['process_failed'] = __( 'Theme update failed.' );
$this->strings['process_success'] = __( 'Theme updated successfully.' );
}
if ( 'downgrade-theme' === $this->skin->overwrite ) {
$this->strings['installing_package'] = __( 'Downgrading the theme&#8230;' );
$this->strings['process_failed'] = __( 'Theme downgrade failed.' );
$this->strings['process_success'] = __( 'Theme downgraded successfully.' );
}
}
}
/**
* Checks if a child theme is being installed and its parent also needs to be installed.
*
* Hooked to the {@see 'upgrader_post_install'} filter by Theme_Upgrader::install().
*
* @since 3.4.0
*
* @param bool $install_result
* @param array $hook_extra
* @param array $child_result
* @return bool
*/
public function check_parent_theme_filter( $install_result, $hook_extra, $child_result ) {
// Check to see if we need to install a parent theme.
$theme_info = $this->theme_info();
if ( ! $theme_info->parent() ) {
return $install_result;
}
$this->skin->feedback( 'parent_theme_search' );
if ( ! $theme_info->parent()->errors() ) {
$this->skin->feedback( 'parent_theme_currently_installed', $theme_info->parent()->display( 'Name' ), $theme_info->parent()->display( 'Version' ) );
// We already have the theme, fall through.
return $install_result;
}
// We don't have the parent theme, let's install it.
$api = themes_api(
'theme_information',
array(
'slug' => $theme_info->get( 'Template' ),
'fields' => array(
'sections' => false,
'tags' => false,
),
)
); // Save on a bit of bandwidth.
if ( ! $api || is_wp_error( $api ) ) {
$this->skin->feedback( 'parent_theme_not_found', $theme_info->get( 'Template' ) );
// Don't show activate or preview actions after installation.
add_filter( 'install_theme_complete_actions', array( $this, 'hide_activate_preview_actions' ) );
return $install_result;
}
// Backup required data we're going to override:
$child_api = $this->skin->api;
$child_success_message = $this->strings['process_success'];
// Override them.
$this->skin->api = $api;
$this->strings['process_success_specific'] = $this->strings['parent_theme_install_success'];
$this->skin->feedback( 'parent_theme_prepare_install', $api->name, $api->version );
add_filter( 'install_theme_complete_actions', '__return_false', 999 ); // Don't show any actions after installing the theme.
// Install the parent theme.
$parent_result = $this->run(
array(
'package' => $api->download_link,
'destination' => get_theme_root(),
'clear_destination' => false, // Do not overwrite files.
'clear_working' => true,
)
);
if ( is_wp_error( $parent_result ) ) {
add_filter( 'install_theme_complete_actions', array( $this, 'hide_activate_preview_actions' ) );
}
// Start cleaning up after the parent's installation.
remove_filter( 'install_theme_complete_actions', '__return_false', 999 );
// Reset child's result and data.
$this->result = $child_result;
$this->skin->api = $child_api;
$this->strings['process_success'] = $child_success_message;
return $install_result;
}
/**
* Don't display the activate and preview actions to the user.
*
* Hooked to the {@see 'install_theme_complete_actions'} filter by
* Theme_Upgrader::check_parent_theme_filter() when installing
* a child theme and installing the parent theme fails.
*
* @since 3.4.0
*
* @param array $actions Preview actions.
* @return array
*/
public function hide_activate_preview_actions( $actions ) {
unset( $actions['activate'], $actions['preview'] );
return $actions;
}
/**
* Install a theme package.
*
* @since 2.8.0
* @since 3.7.0 The `$args` parameter was added, making clearing the update cache optional.
*
* @param string $package The full local path or URI of the package.
* @param array $args {
* Optional. Other arguments for installing a theme package. Default empty array.
*
* @type bool $clear_update_cache Whether to clear the updates cache if successful.
* Default true.
* }
*
* @return bool|WP_Error True if the installation was successful, false or a WP_Error object otherwise.
*/
public function install( $package, $args = array() ) {
$defaults = array(
'clear_update_cache' => true,
'overwrite_package' => false, // Do not overwrite files.
);
$parsed_args = wp_parse_args( $args, $defaults );
$this->init();
$this->install_strings();
add_filter( 'upgrader_source_selection', array( $this, 'check_package' ) );
add_filter( 'upgrader_post_install', array( $this, 'check_parent_theme_filter' ), 10, 3 );
if ( $parsed_args['clear_update_cache'] ) {
// Clear cache so wp_update_themes() knows about the new theme.
add_action( 'upgrader_process_complete', 'wp_clean_themes_cache', 9, 0 );
}
$this->run(
array(
'package' => $package,
'destination' => get_theme_root(),
'clear_destination' => $parsed_args['overwrite_package'],
'clear_working' => true,
'hook_extra' => array(
'type' => 'theme',
'action' => 'install',
),
)
);
remove_action( 'upgrader_process_complete', 'wp_clean_themes_cache', 9 );
remove_filter( 'upgrader_source_selection', array( $this, 'check_package' ) );
remove_filter( 'upgrader_post_install', array( $this, 'check_parent_theme_filter' ) );
if ( ! $this->result || is_wp_error( $this->result ) ) {
return $this->result;
}
// Refresh the Theme Update information.
wp_clean_themes_cache( $parsed_args['clear_update_cache'] );
if ( $parsed_args['overwrite_package'] ) {
/** This action is documented in wp-admin/includes/class-plugin-upgrader.php */
do_action( 'upgrader_overwrote_package', $package, $this->new_theme_data, 'theme' );
}
return true;
}
/**
* Upgrades a theme.
*
* @since 2.8.0
* @since 3.7.0 The `$args` parameter was added, making clearing the update cache optional.
*
* @param string $theme The theme slug.
* @param array $args {
* Optional. Other arguments for upgrading a theme. Default empty array.
*
* @type bool $clear_update_cache Whether to clear the update cache if successful.
* Default true.
* }
* @return bool|WP_Error True if the upgrade was successful, false or a WP_Error object otherwise.
*/
public function upgrade( $theme, $args = array() ) {
$defaults = array(
'clear_update_cache' => true,
);
$parsed_args = wp_parse_args( $args, $defaults );
$this->init();
$this->upgrade_strings();
// Is an update available?
$current = get_site_transient( 'update_themes' );
if ( ! isset( $current->response[ $theme ] ) ) {
$this->skin->before();
$this->skin->set_result( false );
$this->skin->error( 'up_to_date' );
$this->skin->after();
return false;
}
$r = $current->response[ $theme ];
add_filter( 'upgrader_pre_install', array( $this, 'current_before' ), 10, 2 );
add_filter( 'upgrader_post_install', array( $this, 'current_after' ), 10, 2 );
add_filter( 'upgrader_clear_destination', array( $this, 'delete_old_theme' ), 10, 4 );
if ( $parsed_args['clear_update_cache'] ) {
// Clear cache so wp_update_themes() knows about the new theme.
add_action( 'upgrader_process_complete', 'wp_clean_themes_cache', 9, 0 );
}
$this->run(
array(
'package' => $r['package'],
'destination' => get_theme_root( $theme ),
'clear_destination' => true,
'clear_working' => true,
'hook_extra' => array(
'theme' => $theme,
'type' => 'theme',
'action' => 'update',
'temp_backup' => array(
'slug' => $theme,
'src' => get_theme_root( $theme ),
'dir' => 'themes',
),
),
)
);
remove_action( 'upgrader_process_complete', 'wp_clean_themes_cache', 9 );
remove_filter( 'upgrader_pre_install', array( $this, 'current_before' ) );
remove_filter( 'upgrader_post_install', array( $this, 'current_after' ) );
remove_filter( 'upgrader_clear_destination', array( $this, 'delete_old_theme' ) );
if ( ! $this->result || is_wp_error( $this->result ) ) {
return $this->result;
}
wp_clean_themes_cache( $parsed_args['clear_update_cache'] );
/*
* Ensure any future auto-update failures trigger a failure email by removing
* the last failure notification from the list when themes update successfully.
*/
$past_failure_emails = get_option( 'auto_plugin_theme_update_emails', array() );
if ( isset( $past_failure_emails[ $theme ] ) ) {
unset( $past_failure_emails[ $theme ] );
update_option( 'auto_plugin_theme_update_emails', $past_failure_emails );
}
return true;
}
/**
* Upgrades several themes at once.
*
* @since 3.0.0
* @since 3.7.0 The `$args` parameter was added, making clearing the update cache optional.
*
* @global string $wp_version The WordPress version string.
*
* @param string[] $themes Array of the theme slugs.
* @param array $args {
* Optional. Other arguments for upgrading several themes at once. Default empty array.
*
* @type bool $clear_update_cache Whether to clear the update cache if successful.
* Default true.
* }
* @return array[]|false An array of results, or false if unable to connect to the filesystem.
*/
public function bulk_upgrade( $themes, $args = array() ) {
global $wp_version;
$defaults = array(
'clear_update_cache' => true,
);
$parsed_args = wp_parse_args( $args, $defaults );
$this->init();
$this->bulk = true;
$this->upgrade_strings();
$current = get_site_transient( 'update_themes' );
add_filter( 'upgrader_pre_install', array( $this, 'current_before' ), 10, 2 );
add_filter( 'upgrader_post_install', array( $this, 'current_after' ), 10, 2 );
add_filter( 'upgrader_clear_destination', array( $this, 'delete_old_theme' ), 10, 4 );
$this->skin->header();
// Connect to the filesystem first.
$res = $this->fs_connect( array( WP_CONTENT_DIR ) );
if ( ! $res ) {
$this->skin->footer();
return false;
}
$this->skin->bulk_header();
/*
* Only start maintenance mode if:
* - running Multisite and there are one or more themes specified, OR
* - a theme with an update available is currently in use.
* @todo For multisite, maintenance mode should only kick in for individual sites if at all possible.
*/
$maintenance = ( is_multisite() && ! empty( $themes ) );
foreach ( $themes as $theme ) {
$maintenance = $maintenance || get_stylesheet() === $theme || get_template() === $theme;
}
if ( $maintenance ) {
$this->maintenance_mode( true );
}
$results = array();
$this->update_count = count( $themes );
$this->update_current = 0;
foreach ( $themes as $theme ) {
++$this->update_current;
$this->skin->theme_info = $this->theme_info( $theme );
if ( ! isset( $current->response[ $theme ] ) ) {
$this->skin->set_result( true );
$this->skin->before();
$this->skin->feedback( 'up_to_date' );
$this->skin->after();
$results[ $theme ] = true;
continue;
}
// Get the URL to the zip file.
$r = $current->response[ $theme ];
if ( isset( $r['requires'] ) && ! is_wp_version_compatible( $r['requires'] ) ) {
$result = new WP_Error(
'incompatible_wp_required_version',
sprintf(
/* translators: 1: Current WordPress version, 2: WordPress version required by the new theme version. */
__( 'Your WordPress version is %1$s, however the new theme version requires %2$s.' ),
$wp_version,
$r['requires']
)
);
$this->skin->before( $result );
$this->skin->error( $result );
$this->skin->after();
} elseif ( isset( $r['requires_php'] ) && ! is_php_version_compatible( $r['requires_php'] ) ) {
$result = new WP_Error(
'incompatible_php_required_version',
sprintf(
/* translators: 1: Current PHP version, 2: PHP version required by the new theme version. */
__( 'The PHP version on your server is %1$s, however the new theme version requires %2$s.' ),
PHP_VERSION,
$r['requires_php']
)
);
$this->skin->before( $result );
$this->skin->error( $result );
$this->skin->after();
} else {
add_filter( 'upgrader_source_selection', array( $this, 'check_package' ) );
$result = $this->run(
array(
'package' => $r['package'],
'destination' => get_theme_root( $theme ),
'clear_destination' => true,
'clear_working' => true,
'is_multi' => true,
'hook_extra' => array(
'theme' => $theme,
'temp_backup' => array(
'slug' => $theme,
'src' => get_theme_root( $theme ),
'dir' => 'themes',
),
),
)
);
remove_filter( 'upgrader_source_selection', array( $this, 'check_package' ) );
}
$results[ $theme ] = $result;
// Prevent credentials auth screen from displaying multiple times.
if ( false === $result ) {
break;
}
} // End foreach $themes.
$this->maintenance_mode( false );
// Refresh the Theme Update information.
wp_clean_themes_cache( $parsed_args['clear_update_cache'] );
/** This action is documented in wp-admin/includes/class-wp-upgrader.php */
do_action(
'upgrader_process_complete',
$this,
array(
'action' => 'update',
'type' => 'theme',
'bulk' => true,
'themes' => $themes,
)
);
$this->skin->bulk_footer();
$this->skin->footer();
// Cleanup our hooks, in case something else does an upgrade on this connection.
remove_filter( 'upgrader_pre_install', array( $this, 'current_before' ) );
remove_filter( 'upgrader_post_install', array( $this, 'current_after' ) );
remove_filter( 'upgrader_clear_destination', array( $this, 'delete_old_theme' ) );
/*
* Ensure any future auto-update failures trigger a failure email by removing
* the last failure notification from the list when themes update successfully.
*/
$past_failure_emails = get_option( 'auto_plugin_theme_update_emails', array() );
foreach ( $results as $theme => $result ) {
// Maintain last failure notification when themes failed to update manually.
if ( ! $result || is_wp_error( $result ) || ! isset( $past_failure_emails[ $theme ] ) ) {
continue;
}
unset( $past_failure_emails[ $theme ] );
}
update_option( 'auto_plugin_theme_update_emails', $past_failure_emails );
return $results;
}
/**
* Checks that the package source contains a valid theme.
*
* Hooked to the {@see 'upgrader_source_selection'} filter by Theme_Upgrader::install().
*
* @since 3.3.0
*
* @global WP_Filesystem_Base $wp_filesystem WordPress filesystem subclass.
* @global string $wp_version The WordPress version string.
*
* @param string $source The path to the downloaded package source.
* @return string|WP_Error The source as passed, or a WP_Error object on failure.
*/
public function check_package( $source ) {
global $wp_filesystem, $wp_version;
$this->new_theme_data = array();
if ( is_wp_error( $source ) ) {
return $source;
}
// Check that the folder contains a valid theme.
$working_directory = str_replace( $wp_filesystem->wp_content_dir(), trailingslashit( WP_CONTENT_DIR ), $source );
if ( ! is_dir( $working_directory ) ) { // Confidence check, if the above fails, let's not prevent installation.
return $source;
}
// A proper archive should have a style.css file in the single subdirectory.
if ( ! file_exists( $working_directory . 'style.css' ) ) {
return new WP_Error(
'incompatible_archive_theme_no_style',
$this->strings['incompatible_archive'],
sprintf(
/* translators: %s: style.css */
__( 'The theme is missing the %s stylesheet.' ),
'<code>style.css</code>'
)
);
}
// All these headers are needed on Theme_Installer_Skin::do_overwrite().
$info = get_file_data(
$working_directory . 'style.css',
array(
'Name' => 'Theme Name',
'Version' => 'Version',
'Author' => 'Author',
'Template' => 'Template',
'RequiresWP' => 'Requires at least',
'RequiresPHP' => 'Requires PHP',
)
);
if ( empty( $info['Name'] ) ) {
return new WP_Error(
'incompatible_archive_theme_no_name',
$this->strings['incompatible_archive'],
sprintf(
/* translators: %s: style.css */
__( 'The %s stylesheet does not contain a valid theme header.' ),
'<code>style.css</code>'
)
);
}
/*
* Parent themes must contain an index file:
* - classic themes require /index.php
* - block themes require /templates/index.html or block-templates/index.html (deprecated 5.9.0).
*/
if (
empty( $info['Template'] ) &&
! file_exists( $working_directory . 'index.php' ) &&
! file_exists( $working_directory . 'templates/index.html' ) &&
! file_exists( $working_directory . 'block-templates/index.html' )
) {
return new WP_Error(
'incompatible_archive_theme_no_index',
$this->strings['incompatible_archive'],
sprintf(
/* translators: 1: templates/index.html, 2: index.php, 3: Documentation URL, 4: Template, 5: style.css */
__( 'Template is missing. Standalone themes need to have a %1$s or %2$s template file. <a href="%3$s">Child themes</a> need to have a %4$s header in the %5$s stylesheet.' ),
'<code>templates/index.html</code>',
'<code>index.php</code>',
__( 'https://developer.wordpress.org/themes/advanced-topics/child-themes/' ),
'<code>Template</code>',
'<code>style.css</code>'
)
);
}
$requires_php = isset( $info['RequiresPHP'] ) ? $info['RequiresPHP'] : null;
$requires_wp = isset( $info['RequiresWP'] ) ? $info['RequiresWP'] : null;
if ( ! is_php_version_compatible( $requires_php ) ) {
$error = sprintf(
/* translators: 1: Current PHP version, 2: Version required by the uploaded theme. */
__( 'The PHP version on your server is %1$s, however the uploaded theme requires %2$s.' ),
PHP_VERSION,
$requires_php
);
return new WP_Error( 'incompatible_php_required_version', $this->strings['incompatible_archive'], $error );
}
if ( ! is_wp_version_compatible( $requires_wp ) ) {
$error = sprintf(
/* translators: 1: Current WordPress version, 2: Version required by the uploaded theme. */
__( 'Your WordPress version is %1$s, however the uploaded theme requires %2$s.' ),
$wp_version,
$requires_wp
);
return new WP_Error( 'incompatible_wp_required_version', $this->strings['incompatible_archive'], $error );
}
$this->new_theme_data = $info;
return $source;
}
/**
* Turns on maintenance mode before attempting to upgrade the active theme.
*
* Hooked to the {@see 'upgrader_pre_install'} filter by Theme_Upgrader::upgrade() and
* Theme_Upgrader::bulk_upgrade().
*
* @since 2.8.0
*
* @param bool|WP_Error $response The installation response before the installation has started.
* @param array $theme Theme arguments.
* @return bool|WP_Error The original `$response` parameter or WP_Error.
*/
public function current_before( $response, $theme ) {
if ( is_wp_error( $response ) ) {
return $response;
}
$theme = isset( $theme['theme'] ) ? $theme['theme'] : '';
// Only run if active theme.
if ( get_stylesheet() !== $theme ) {
return $response;
}
// Change to maintenance mode. Bulk edit handles this separately.
if ( ! $this->bulk ) {
$this->maintenance_mode( true );
}
return $response;
}
/**
* Turns off maintenance mode after upgrading the active theme.
*
* Hooked to the {@see 'upgrader_post_install'} filter by Theme_Upgrader::upgrade()
* and Theme_Upgrader::bulk_upgrade().
*
* @since 2.8.0
*
* @param bool|WP_Error $response The installation response after the installation has finished.
* @param array $theme Theme arguments.
* @return bool|WP_Error The original `$response` parameter or WP_Error.
*/
public function current_after( $response, $theme ) {
if ( is_wp_error( $response ) ) {
return $response;
}
$theme = isset( $theme['theme'] ) ? $theme['theme'] : '';
// Only run if active theme.
if ( get_stylesheet() !== $theme ) {
return $response;
}
// Ensure stylesheet name hasn't changed after the upgrade:
if ( get_stylesheet() === $theme && $theme !== $this->result['destination_name'] ) {
wp_clean_themes_cache();
$stylesheet = $this->result['destination_name'];
switch_theme( $stylesheet );
}
// Time to remove maintenance mode. Bulk edit handles this separately.
if ( ! $this->bulk ) {
$this->maintenance_mode( false );
}
return $response;
}
/**
* Deletes the old theme during an upgrade.
*
* Hooked to the {@see 'upgrader_clear_destination'} filter by Theme_Upgrader::upgrade()
* and Theme_Upgrader::bulk_upgrade().
*
* @since 2.8.0
*
* @global WP_Filesystem_Base $wp_filesystem Subclass
*
* @param bool $removed
* @param string $local_destination
* @param string $remote_destination
* @param array $theme
* @return bool
*/
public function delete_old_theme( $removed, $local_destination, $remote_destination, $theme ) {
global $wp_filesystem;
if ( is_wp_error( $removed ) ) {
return $removed; // Pass errors through.
}
if ( ! isset( $theme['theme'] ) ) {
return $removed;
}
$theme = $theme['theme'];
$themes_dir = trailingslashit( $wp_filesystem->wp_themes_dir( $theme ) );
if ( $wp_filesystem->exists( $themes_dir . $theme ) ) {
if ( ! $wp_filesystem->delete( $themes_dir . $theme, true ) ) {
return false;
}
}
return true;
}
/**
* Gets the WP_Theme object for a theme.
*
* @since 2.8.0
* @since 3.0.0 The `$theme` argument was added.
*
* @param string $theme The directory name of the theme. This is optional, and if not supplied,
* the directory name from the last result will be used.
* @return WP_Theme|false The theme's info object, or false `$theme` is not supplied
* and the last result isn't set.
*/
public function theme_info( $theme = null ) {
if ( empty( $theme ) ) {
if ( ! empty( $this->result['destination_name'] ) ) {
$theme = $this->result['destination_name'];
} else {
return false;
}
}
$theme = wp_get_theme( $theme );
$theme->cache_delete();
return $theme;
}
}

View File

@ -0,0 +1,138 @@
<?php
/**
* Taxonomy API: Walker_Category_Checklist class
*
* @package WordPress
* @subpackage Administration
* @since 4.4.0
*/
/**
* Core walker class to output an unordered list of category checkbox input elements.
*
* @since 2.5.1
*
* @see Walker
* @see wp_category_checklist()
* @see wp_terms_checklist()
*/
class Walker_Category_Checklist extends Walker {
public $tree_type = 'category';
public $db_fields = array(
'parent' => 'parent',
'id' => 'term_id',
); // TODO: Decouple this.
/**
* Starts the list before the elements are added.
*
* @see Walker:start_lvl()
*
* @since 2.5.1
*
* @param string $output Used to append additional content (passed by reference).
* @param int $depth Depth of category. Used for tab indentation.
* @param array $args An array of arguments. See {@see wp_terms_checklist()}.
*/
public function start_lvl( &$output, $depth = 0, $args = array() ) {
$indent = str_repeat( "\t", $depth );
$output .= "$indent<ul class='children'>\n";
}
/**
* Ends the list of after the elements are added.
*
* @see Walker::end_lvl()
*
* @since 2.5.1
*
* @param string $output Used to append additional content (passed by reference).
* @param int $depth Depth of category. Used for tab indentation.
* @param array $args An array of arguments. See {@see wp_terms_checklist()}.
*/
public function end_lvl( &$output, $depth = 0, $args = array() ) {
$indent = str_repeat( "\t", $depth );
$output .= "$indent</ul>\n";
}
/**
* Start the element output.
*
* @see Walker::start_el()
*
* @since 2.5.1
* @since 5.9.0 Renamed `$category` to `$data_object` and `$id` to `$current_object_id`
* to match parent class for PHP 8 named parameter support.
*
* @param string $output Used to append additional content (passed by reference).
* @param WP_Term $data_object The current term object.
* @param int $depth Depth of the term in reference to parents. Default 0.
* @param array $args An array of arguments. See {@see wp_terms_checklist()}.
* @param int $current_object_id Optional. ID of the current term. Default 0.
*/
public function start_el( &$output, $data_object, $depth = 0, $args = array(), $current_object_id = 0 ) {
// Restores the more descriptive, specific name for use within this method.
$category = $data_object;
if ( empty( $args['taxonomy'] ) ) {
$taxonomy = 'category';
} else {
$taxonomy = $args['taxonomy'];
}
if ( 'category' === $taxonomy ) {
$name = 'post_category';
} else {
$name = 'tax_input[' . $taxonomy . ']';
}
$args['popular_cats'] = ! empty( $args['popular_cats'] ) ? array_map( 'intval', $args['popular_cats'] ) : array();
$class = in_array( $category->term_id, $args['popular_cats'], true ) ? ' class="popular-category"' : '';
$args['selected_cats'] = ! empty( $args['selected_cats'] ) ? array_map( 'intval', $args['selected_cats'] ) : array();
if ( ! empty( $args['list_only'] ) ) {
$aria_checked = 'false';
$inner_class = 'category';
if ( in_array( $category->term_id, $args['selected_cats'], true ) ) {
$inner_class .= ' selected';
$aria_checked = 'true';
}
$output .= "\n" . '<li' . $class . '>' .
'<div class="' . $inner_class . '" data-term-id=' . $category->term_id .
' tabindex="0" role="checkbox" aria-checked="' . $aria_checked . '">' .
/** This filter is documented in wp-includes/category-template.php */
esc_html( apply_filters( 'the_category', $category->name, '', '' ) ) . '</div>';
} else {
$is_selected = in_array( $category->term_id, $args['selected_cats'], true );
$is_disabled = ! empty( $args['disabled'] );
$output .= "\n<li id='{$taxonomy}-{$category->term_id}'$class>" .
'<label class="selectit"><input value="' . $category->term_id . '" type="checkbox" name="' . $name . '[]" id="in-' . $taxonomy . '-' . $category->term_id . '"' .
checked( $is_selected, true, false ) .
disabled( $is_disabled, true, false ) . ' /> ' .
/** This filter is documented in wp-includes/category-template.php */
esc_html( apply_filters( 'the_category', $category->name, '', '' ) ) . '</label>';
}
}
/**
* Ends the element output, if needed.
*
* @see Walker::end_el()
*
* @since 2.5.1
* @since 5.9.0 Renamed `$category` to `$data_object` to match parent class for PHP 8 named parameter support.
*
* @param string $output Used to append additional content (passed by reference).
* @param WP_Term $data_object The current term object.
* @param int $depth Depth of the term in reference to parents. Default 0.
* @param array $args An array of arguments. See {@see wp_terms_checklist()}.
*/
public function end_el( &$output, $data_object, $depth = 0, $args = array() ) {
$output .= "</li>\n";
}
}

View File

@ -0,0 +1,126 @@
<?php
/**
* Navigation Menu API: Walker_Nav_Menu_Checklist class
*
* @package WordPress
* @subpackage Administration
* @since 4.4.0
*/
/**
* Create HTML list of nav menu input items.
*
* @since 3.0.0
* @uses Walker_Nav_Menu
*/
class Walker_Nav_Menu_Checklist extends Walker_Nav_Menu {
/**
* @param array|false $fields Database fields to use.
*/
public function __construct( $fields = false ) {
if ( $fields ) {
$this->db_fields = $fields;
}
}
/**
* Starts the list before the elements are added.
*
* @see Walker_Nav_Menu::start_lvl()
*
* @since 3.0.0
*
* @param string $output Used to append additional content (passed by reference).
* @param int $depth Depth of page. Used for padding.
* @param stdClass $args Not used.
*/
public function start_lvl( &$output, $depth = 0, $args = null ) {
$indent = str_repeat( "\t", $depth );
$output .= "\n$indent<ul class='children'>\n";
}
/**
* Ends the list of after the elements are added.
*
* @see Walker_Nav_Menu::end_lvl()
*
* @since 3.0.0
*
* @param string $output Used to append additional content (passed by reference).
* @param int $depth Depth of page. Used for padding.
* @param stdClass $args Not used.
*/
public function end_lvl( &$output, $depth = 0, $args = null ) {
$indent = str_repeat( "\t", $depth );
$output .= "\n$indent</ul>";
}
/**
* Start the element output.
*
* @see Walker_Nav_Menu::start_el()
*
* @since 3.0.0
* @since 5.9.0 Renamed `$item` to `$data_object` and `$id` to `$current_object_id`
* to match parent class for PHP 8 named parameter support.
*
* @global int $_nav_menu_placeholder
* @global int|string $nav_menu_selected_id
*
* @param string $output Used to append additional content (passed by reference).
* @param WP_Post $data_object Menu item data object.
* @param int $depth Depth of menu item. Used for padding.
* @param stdClass $args Not used.
* @param int $current_object_id Optional. ID of the current menu item. Default 0.
*/
public function start_el( &$output, $data_object, $depth = 0, $args = null, $current_object_id = 0 ) {
global $_nav_menu_placeholder, $nav_menu_selected_id;
// Restores the more descriptive, specific name for use within this method.
$menu_item = $data_object;
$_nav_menu_placeholder = ( 0 > $_nav_menu_placeholder ) ? (int) $_nav_menu_placeholder - 1 : -1;
$possible_object_id = isset( $menu_item->post_type ) && 'nav_menu_item' === $menu_item->post_type ? $menu_item->object_id : $_nav_menu_placeholder;
$possible_db_id = ( ! empty( $menu_item->ID ) ) && ( 0 < $possible_object_id ) ? (int) $menu_item->ID : 0;
$indent = ( $depth ) ? str_repeat( "\t", $depth ) : '';
$output .= $indent . '<li>';
$output .= '<label class="menu-item-title">';
$output .= '<input type="checkbox"' . wp_nav_menu_disabled_check( $nav_menu_selected_id, false ) . ' class="menu-item-checkbox';
if ( ! empty( $menu_item->front_or_home ) ) {
$output .= ' add-to-top';
}
$output .= '" name="menu-item[' . $possible_object_id . '][menu-item-object-id]" value="' . esc_attr( $menu_item->object_id ) . '" /> ';
if ( ! empty( $menu_item->label ) ) {
$title = $menu_item->label;
} elseif ( isset( $menu_item->post_type ) ) {
/** This filter is documented in wp-includes/post-template.php */
$title = apply_filters( 'the_title', $menu_item->post_title, $menu_item->ID );
}
$output .= isset( $title ) ? esc_html( $title ) : esc_html( $menu_item->title );
if ( empty( $menu_item->label ) && isset( $menu_item->post_type ) && 'page' === $menu_item->post_type ) {
// Append post states.
$output .= _post_states( $menu_item, false );
}
$output .= '</label>';
// Menu item hidden fields.
$output .= '<input type="hidden" class="menu-item-db-id" name="menu-item[' . $possible_object_id . '][menu-item-db-id]" value="' . $possible_db_id . '" />';
$output .= '<input type="hidden" class="menu-item-object" name="menu-item[' . $possible_object_id . '][menu-item-object]" value="' . esc_attr( $menu_item->object ) . '" />';
$output .= '<input type="hidden" class="menu-item-parent-id" name="menu-item[' . $possible_object_id . '][menu-item-parent-id]" value="' . esc_attr( $menu_item->menu_item_parent ) . '" />';
$output .= '<input type="hidden" class="menu-item-type" name="menu-item[' . $possible_object_id . '][menu-item-type]" value="' . esc_attr( $menu_item->type ) . '" />';
$output .= '<input type="hidden" class="menu-item-title" name="menu-item[' . $possible_object_id . '][menu-item-title]" value="' . esc_attr( $menu_item->title ) . '" />';
$output .= '<input type="hidden" class="menu-item-url" name="menu-item[' . $possible_object_id . '][menu-item-url]" value="' . esc_attr( $menu_item->url ) . '" />';
$output .= '<input type="hidden" class="menu-item-target" name="menu-item[' . $possible_object_id . '][menu-item-target]" value="' . esc_attr( $menu_item->target ) . '" />';
$output .= '<input type="hidden" class="menu-item-attr-title" name="menu-item[' . $possible_object_id . '][menu-item-attr-title]" value="' . esc_attr( $menu_item->attr_title ) . '" />';
$output .= '<input type="hidden" class="menu-item-classes" name="menu-item[' . $possible_object_id . '][menu-item-classes]" value="' . esc_attr( implode( ' ', $menu_item->classes ) ) . '" />';
$output .= '<input type="hidden" class="menu-item-xfn" name="menu-item[' . $possible_object_id . '][menu-item-xfn]" value="' . esc_attr( $menu_item->xfn ) . '" />';
}
}

View File

@ -0,0 +1,323 @@
<?php
/**
* Navigation Menu API: Walker_Nav_Menu_Edit class
*
* @package WordPress
* @subpackage Administration
* @since 4.4.0
*/
/**
* Create HTML list of nav menu input items.
*
* @since 3.0.0
*
* @see Walker_Nav_Menu
*/
class Walker_Nav_Menu_Edit extends Walker_Nav_Menu {
/**
* Starts the list before the elements are added.
*
* @see Walker_Nav_Menu::start_lvl()
*
* @since 3.0.0
*
* @param string $output Passed by reference.
* @param int $depth Depth of menu item. Used for padding.
* @param stdClass $args Not used.
*/
public function start_lvl( &$output, $depth = 0, $args = null ) {}
/**
* Ends the list of after the elements are added.
*
* @see Walker_Nav_Menu::end_lvl()
*
* @since 3.0.0
*
* @param string $output Passed by reference.
* @param int $depth Depth of menu item. Used for padding.
* @param stdClass $args Not used.
*/
public function end_lvl( &$output, $depth = 0, $args = null ) {}
/**
* Start the element output.
*
* @see Walker_Nav_Menu::start_el()
* @since 3.0.0
* @since 5.9.0 Renamed `$item` to `$data_object` and `$id` to `$current_object_id`
* to match parent class for PHP 8 named parameter support.
*
* @global int $_wp_nav_menu_max_depth
*
* @param string $output Used to append additional content (passed by reference).
* @param WP_Post $data_object Menu item data object.
* @param int $depth Depth of menu item. Used for padding.
* @param stdClass $args Not used.
* @param int $current_object_id Optional. ID of the current menu item. Default 0.
*/
public function start_el( &$output, $data_object, $depth = 0, $args = null, $current_object_id = 0 ) {
global $_wp_nav_menu_max_depth;
// Restores the more descriptive, specific name for use within this method.
$menu_item = $data_object;
$_wp_nav_menu_max_depth = $depth > $_wp_nav_menu_max_depth ? $depth : $_wp_nav_menu_max_depth;
ob_start();
$item_id = esc_attr( $menu_item->ID );
$removed_args = array(
'action',
'customlink-tab',
'edit-menu-item',
'menu-item',
'page-tab',
'_wpnonce',
);
$original_title = false;
if ( 'taxonomy' === $menu_item->type ) {
$original_object = get_term( (int) $menu_item->object_id, $menu_item->object );
if ( $original_object && ! is_wp_error( $original_object ) ) {
$original_title = $original_object->name;
}
} elseif ( 'post_type' === $menu_item->type ) {
$original_object = get_post( $menu_item->object_id );
if ( $original_object ) {
$original_title = get_the_title( $original_object->ID );
}
} elseif ( 'post_type_archive' === $menu_item->type ) {
$original_object = get_post_type_object( $menu_item->object );
if ( $original_object ) {
$original_title = $original_object->labels->archives;
}
}
$classes = array(
'menu-item menu-item-depth-' . $depth,
'menu-item-' . esc_attr( $menu_item->object ),
'menu-item-edit-' . ( ( isset( $_GET['edit-menu-item'] ) && $item_id === $_GET['edit-menu-item'] ) ? 'active' : 'inactive' ),
);
$title = $menu_item->title;
if ( ! empty( $menu_item->_invalid ) ) {
$classes[] = 'menu-item-invalid';
/* translators: %s: Title of an invalid menu item. */
$title = sprintf( __( '%s (Invalid)' ), $menu_item->title );
} elseif ( isset( $menu_item->post_status ) && 'draft' === $menu_item->post_status ) {
$classes[] = 'pending';
/* translators: %s: Title of a menu item in draft status. */
$title = sprintf( __( '%s (Pending)' ), $menu_item->title );
}
$title = ( ! isset( $menu_item->label ) || '' === $menu_item->label ) ? $title : $menu_item->label;
$submenu_text = '';
if ( 0 === $depth ) {
$submenu_text = 'style="display: none;"';
}
?>
<li id="menu-item-<?php echo $item_id; ?>" class="<?php echo implode( ' ', $classes ); ?>">
<div class="menu-item-bar">
<div class="menu-item-handle">
<label class="item-title" for="menu-item-checkbox-<?php echo $item_id; ?>">
<input id="menu-item-checkbox-<?php echo $item_id; ?>" type="checkbox" class="menu-item-checkbox" data-menu-item-id="<?php echo $item_id; ?>" disabled="disabled" />
<span class="menu-item-title"><?php echo esc_html( $title ); ?></span>
<span class="is-submenu" <?php echo $submenu_text; ?>><?php _e( 'sub item' ); ?></span>
</label>
<span class="item-controls">
<span class="item-type"><?php echo esc_html( $menu_item->type_label ); ?></span>
<span class="item-order hide-if-js">
<?php
printf(
'<a href="%s" class="item-move-up" aria-label="%s">&#8593;</a>',
wp_nonce_url(
add_query_arg(
array(
'action' => 'move-up-menu-item',
'menu-item' => $item_id,
),
remove_query_arg( $removed_args, admin_url( 'nav-menus.php' ) )
),
'move-menu_item'
),
esc_attr__( 'Move up' )
);
?>
|
<?php
printf(
'<a href="%s" class="item-move-down" aria-label="%s">&#8595;</a>',
wp_nonce_url(
add_query_arg(
array(
'action' => 'move-down-menu-item',
'menu-item' => $item_id,
),
remove_query_arg( $removed_args, admin_url( 'nav-menus.php' ) )
),
'move-menu_item'
),
esc_attr__( 'Move down' )
);
?>
</span>
<?php
if ( isset( $_GET['edit-menu-item'] ) && $item_id === $_GET['edit-menu-item'] ) {
$edit_url = admin_url( 'nav-menus.php' );
} else {
$edit_url = add_query_arg(
array(
'edit-menu-item' => $item_id,
),
remove_query_arg( $removed_args, admin_url( 'nav-menus.php#menu-item-settings-' . $item_id ) )
);
}
printf(
'<a class="item-edit" id="edit-%s" href="%s" aria-label="%s"><span class="screen-reader-text">%s</span></a>',
$item_id,
esc_url( $edit_url ),
esc_attr__( 'Edit menu item' ),
/* translators: Hidden accessibility text. */
__( 'Edit' )
);
?>
</span>
</div>
</div>
<div class="menu-item-settings wp-clearfix" id="menu-item-settings-<?php echo $item_id; ?>">
<?php if ( 'custom' === $menu_item->type ) : ?>
<p class="field-url description description-wide">
<label for="edit-menu-item-url-<?php echo $item_id; ?>">
<?php _e( 'URL' ); ?><br />
<input type="text" id="edit-menu-item-url-<?php echo $item_id; ?>" class="widefat code edit-menu-item-url" name="menu-item-url[<?php echo $item_id; ?>]" value="<?php echo esc_attr( $menu_item->url ); ?>" />
</label>
</p>
<?php endif; ?>
<p class="description description-wide">
<label for="edit-menu-item-title-<?php echo $item_id; ?>">
<?php _e( 'Navigation Label' ); ?><br />
<input type="text" id="edit-menu-item-title-<?php echo $item_id; ?>" class="widefat edit-menu-item-title" name="menu-item-title[<?php echo $item_id; ?>]" value="<?php echo esc_attr( $menu_item->title ); ?>" />
</label>
</p>
<p class="field-title-attribute field-attr-title description description-wide">
<label for="edit-menu-item-attr-title-<?php echo $item_id; ?>">
<?php _e( 'Title Attribute' ); ?><br />
<input type="text" id="edit-menu-item-attr-title-<?php echo $item_id; ?>" class="widefat edit-menu-item-attr-title" name="menu-item-attr-title[<?php echo $item_id; ?>]" value="<?php echo esc_attr( $menu_item->post_excerpt ); ?>" />
</label>
</p>
<p class="field-link-target description">
<label for="edit-menu-item-target-<?php echo $item_id; ?>">
<input type="checkbox" id="edit-menu-item-target-<?php echo $item_id; ?>" value="_blank" name="menu-item-target[<?php echo $item_id; ?>]"<?php checked( $menu_item->target, '_blank' ); ?> />
<?php _e( 'Open link in a new tab' ); ?>
</label>
</p>
<p class="field-css-classes description description-thin">
<label for="edit-menu-item-classes-<?php echo $item_id; ?>">
<?php _e( 'CSS Classes (optional)' ); ?><br />
<input type="text" id="edit-menu-item-classes-<?php echo $item_id; ?>" class="widefat code edit-menu-item-classes" name="menu-item-classes[<?php echo $item_id; ?>]" value="<?php echo esc_attr( implode( ' ', $menu_item->classes ) ); ?>" />
</label>
</p>
<p class="field-xfn description description-thin">
<label for="edit-menu-item-xfn-<?php echo $item_id; ?>">
<?php _e( 'Link Relationship (XFN)' ); ?><br />
<input type="text" id="edit-menu-item-xfn-<?php echo $item_id; ?>" class="widefat code edit-menu-item-xfn" name="menu-item-xfn[<?php echo $item_id; ?>]" value="<?php echo esc_attr( $menu_item->xfn ); ?>" />
</label>
</p>
<p class="field-description description description-wide">
<label for="edit-menu-item-description-<?php echo $item_id; ?>">
<?php _e( 'Description' ); ?><br />
<textarea id="edit-menu-item-description-<?php echo $item_id; ?>" class="widefat edit-menu-item-description" rows="3" cols="20" name="menu-item-description[<?php echo $item_id; ?>]"><?php echo esc_html( $menu_item->description ); // textarea_escaped ?></textarea>
<span class="description"><?php _e( 'The description will be displayed in the menu if the active theme supports it.' ); ?></span>
</label>
</p>
<?php
/**
* Fires just before the move buttons of a nav menu item in the menu editor.
*
* @since 5.4.0
*
* @param string $item_id Menu item ID as a numeric string.
* @param WP_Post $menu_item Menu item data object.
* @param int $depth Depth of menu item. Used for padding.
* @param stdClass|null $args An object of menu item arguments.
* @param int $current_object_id Nav menu ID.
*/
do_action( 'wp_nav_menu_item_custom_fields', $item_id, $menu_item, $depth, $args, $current_object_id );
?>
<fieldset class="field-move hide-if-no-js description description-wide">
<span class="field-move-visual-label" aria-hidden="true"><?php _e( 'Move' ); ?></span>
<button type="button" class="button-link menus-move menus-move-up" data-dir="up"><?php _e( 'Up one' ); ?></button>
<button type="button" class="button-link menus-move menus-move-down" data-dir="down"><?php _e( 'Down one' ); ?></button>
<button type="button" class="button-link menus-move menus-move-left" data-dir="left"></button>
<button type="button" class="button-link menus-move menus-move-right" data-dir="right"></button>
<button type="button" class="button-link menus-move menus-move-top" data-dir="top"><?php _e( 'To the top' ); ?></button>
</fieldset>
<div class="menu-item-actions description-wide submitbox">
<?php if ( 'custom' !== $menu_item->type && false !== $original_title ) : ?>
<p class="link-to-original">
<?php
/* translators: %s: Link to menu item's original object. */
printf( __( 'Original: %s' ), '<a href="' . esc_url( $menu_item->url ) . '">' . esc_html( $original_title ) . '</a>' );
?>
</p>
<?php endif; ?>
<?php
printf(
'<a class="item-delete submitdelete deletion" id="delete-%s" href="%s">%s</a>',
$item_id,
wp_nonce_url(
add_query_arg(
array(
'action' => 'delete-menu-item',
'menu-item' => $item_id,
),
admin_url( 'nav-menus.php' )
),
'delete-menu_item_' . $item_id
),
__( 'Remove' )
);
?>
<span class="meta-sep hide-if-no-js"> | </span>
<?php
printf(
'<a class="item-cancel submitcancel hide-if-no-js" id="cancel-%s" href="%s#menu-item-settings-%s">%s</a>',
$item_id,
esc_url(
add_query_arg(
array(
'edit-menu-item' => $item_id,
'cancel' => time(),
),
admin_url( 'nav-menus.php' )
)
),
$item_id,
__( 'Cancel' )
);
?>
</div>
<input class="menu-item-data-db-id" type="hidden" name="menu-item-db-id[<?php echo $item_id; ?>]" value="<?php echo $item_id; ?>" />
<input class="menu-item-data-object-id" type="hidden" name="menu-item-object-id[<?php echo $item_id; ?>]" value="<?php echo esc_attr( $menu_item->object_id ); ?>" />
<input class="menu-item-data-object" type="hidden" name="menu-item-object[<?php echo $item_id; ?>]" value="<?php echo esc_attr( $menu_item->object ); ?>" />
<input class="menu-item-data-parent-id" type="hidden" name="menu-item-parent-id[<?php echo $item_id; ?>]" value="<?php echo esc_attr( $menu_item->menu_item_parent ); ?>" />
<input class="menu-item-data-position" type="hidden" name="menu-item-position[<?php echo $item_id; ?>]" value="<?php echo esc_attr( $menu_item->menu_order ); ?>" />
<input class="menu-item-data-type" type="hidden" name="menu-item-type[<?php echo $item_id; ?>]" value="<?php echo esc_attr( $menu_item->type ); ?>" />
</div><!-- .menu-item-settings-->
<ul class="menu-item-transport"></ul>
<?php
$output .= ob_get_clean();
}
}

View File

@ -0,0 +1,159 @@
<?php
/**
* Upgrader API: WP_Ajax_Upgrader_Skin class
*
* @package WordPress
* @subpackage Upgrader
* @since 4.6.0
*/
/**
* Upgrader Skin for Ajax WordPress upgrades.
*
* This skin is designed to be used for Ajax updates.
*
* @since 4.6.0
*
* @see Automatic_Upgrader_Skin
*/
class WP_Ajax_Upgrader_Skin extends Automatic_Upgrader_Skin {
/**
* Plugin info.
*
* The Plugin_Upgrader::bulk_upgrade() method will fill this in
* with info retrieved from the get_plugin_data() function.
*
* @var array Plugin data. Values will be empty if not supplied by the plugin.
*/
public $plugin_info = array();
/**
* Theme info.
*
* The Theme_Upgrader::bulk_upgrade() method will fill this in
* with info retrieved from the Theme_Upgrader::theme_info() method,
* which in turn calls the wp_get_theme() function.
*
* @var WP_Theme|false The theme's info object, or false.
*/
public $theme_info = false;
/**
* Holds the WP_Error object.
*
* @since 4.6.0
*
* @var null|WP_Error
*/
protected $errors = null;
/**
* Constructor.
*
* Sets up the WordPress Ajax upgrader skin.
*
* @since 4.6.0
*
* @see WP_Upgrader_Skin::__construct()
*
* @param array $args Optional. The WordPress Ajax upgrader skin arguments to
* override default options. See WP_Upgrader_Skin::__construct().
* Default empty array.
*/
public function __construct( $args = array() ) {
parent::__construct( $args );
$this->errors = new WP_Error();
}
/**
* Retrieves the list of errors.
*
* @since 4.6.0
*
* @return WP_Error Errors during an upgrade.
*/
public function get_errors() {
return $this->errors;
}
/**
* Retrieves a string for error messages.
*
* @since 4.6.0
*
* @return string Error messages during an upgrade.
*/
public function get_error_messages() {
$messages = array();
foreach ( $this->errors->get_error_codes() as $error_code ) {
$error_data = $this->errors->get_error_data( $error_code );
if ( $error_data && is_string( $error_data ) ) {
$messages[] = $this->errors->get_error_message( $error_code ) . ' ' . esc_html( strip_tags( $error_data ) );
} else {
$messages[] = $this->errors->get_error_message( $error_code );
}
}
return implode( ', ', $messages );
}
/**
* Stores an error message about the upgrade.
*
* @since 4.6.0
* @since 5.3.0 Formalized the existing `...$args` parameter by adding it
* to the function signature.
*
* @param string|WP_Error $errors Errors.
* @param mixed ...$args Optional text replacements.
*/
public function error( $errors, ...$args ) {
if ( is_string( $errors ) ) {
$string = $errors;
if ( ! empty( $this->upgrader->strings[ $string ] ) ) {
$string = $this->upgrader->strings[ $string ];
}
if ( str_contains( $string, '%' ) ) {
if ( ! empty( $args ) ) {
$string = vsprintf( $string, $args );
}
}
// Count existing errors to generate a unique error code.
$errors_count = count( $this->errors->get_error_codes() );
$this->errors->add( 'unknown_upgrade_error_' . ( $errors_count + 1 ), $string );
} elseif ( is_wp_error( $errors ) ) {
foreach ( $errors->get_error_codes() as $error_code ) {
$this->errors->add( $error_code, $errors->get_error_message( $error_code ), $errors->get_error_data( $error_code ) );
}
}
parent::error( $errors, ...$args );
}
/**
* Stores a message about the upgrade.
*
* @since 4.6.0
* @since 5.3.0 Formalized the existing `...$args` parameter by adding it
* to the function signature.
* @since 5.9.0 Renamed `$data` to `$feedback` for PHP 8 named parameter support.
*
* @param string|array|WP_Error $feedback Message data.
* @param mixed ...$args Optional text replacements.
*/
public function feedback( $feedback, ...$args ) {
if ( is_wp_error( $feedback ) ) {
foreach ( $feedback->get_error_codes() as $error_code ) {
$this->errors->add( $error_code, $feedback->get_error_message( $error_code ), $feedback->get_error_data( $error_code ) );
}
}
parent::feedback( $feedback, ...$args );
}
}

View File

@ -0,0 +1,267 @@
<?php
/**
* List Table API: WP_Application_Passwords_List_Table class
*
* @package WordPress
* @subpackage Administration
* @since 5.6.0
*/
/**
* Class for displaying the list of application password items.
*
* @since 5.6.0
*
* @see WP_List_Table
*/
class WP_Application_Passwords_List_Table extends WP_List_Table {
/**
* Gets the list of columns.
*
* @since 5.6.0
*
* @return string[] Array of column titles keyed by their column name.
*/
public function get_columns() {
return array(
'name' => __( 'Name' ),
'created' => __( 'Created' ),
'last_used' => __( 'Last Used' ),
'last_ip' => __( 'Last IP' ),
'revoke' => __( 'Revoke' ),
);
}
/**
* Prepares the list of items for displaying.
*
* @since 5.6.0
*
* @global int $user_id User ID.
*/
public function prepare_items() {
global $user_id;
$this->items = array_reverse( WP_Application_Passwords::get_user_application_passwords( $user_id ) );
}
/**
* Handles the name column output.
*
* @since 5.6.0
*
* @param array $item The current application password item.
*/
public function column_name( $item ) {
echo esc_html( $item['name'] );
}
/**
* Handles the created column output.
*
* @since 5.6.0
*
* @param array $item The current application password item.
*/
public function column_created( $item ) {
if ( empty( $item['created'] ) ) {
echo '&mdash;';
} else {
echo date_i18n( __( 'F j, Y' ), $item['created'] );
}
}
/**
* Handles the last used column output.
*
* @since 5.6.0
*
* @param array $item The current application password item.
*/
public function column_last_used( $item ) {
if ( empty( $item['last_used'] ) ) {
echo '&mdash;';
} else {
echo date_i18n( __( 'F j, Y' ), $item['last_used'] );
}
}
/**
* Handles the last ip column output.
*
* @since 5.6.0
*
* @param array $item The current application password item.
*/
public function column_last_ip( $item ) {
if ( empty( $item['last_ip'] ) ) {
echo '&mdash;';
} else {
echo $item['last_ip'];
}
}
/**
* Handles the revoke column output.
*
* @since 5.6.0
*
* @param array $item The current application password item.
*/
public function column_revoke( $item ) {
$name = 'revoke-application-password-' . $item['uuid'];
printf(
'<button type="button" name="%1$s" id="%1$s" class="button delete" aria-label="%2$s">%3$s</button>',
esc_attr( $name ),
/* translators: %s: the application password's given name. */
esc_attr( sprintf( __( 'Revoke "%s"' ), $item['name'] ) ),
__( 'Revoke' )
);
}
/**
* Generates content for a single row of the table
*
* @since 5.6.0
*
* @param array $item The current item.
* @param string $column_name The current column name.
*/
protected function column_default( $item, $column_name ) {
/**
* Fires for each custom column in the Application Passwords list table.
*
* Custom columns are registered using the {@see 'manage_application-passwords-user_columns'} filter.
*
* @since 5.6.0
*
* @param string $column_name Name of the custom column.
* @param array $item The application password item.
*/
do_action( "manage_{$this->screen->id}_custom_column", $column_name, $item );
}
/**
* Generates custom table navigation to prevent conflicting nonces.
*
* @since 5.6.0
*
* @param string $which The location of the bulk actions: Either 'top' or 'bottom'.
*/
protected function display_tablenav( $which ) {
?>
<div class="tablenav <?php echo esc_attr( $which ); ?>">
<?php if ( 'bottom' === $which ) : ?>
<div class="alignright">
<button type="button" name="revoke-all-application-passwords" id="revoke-all-application-passwords" class="button delete"><?php _e( 'Revoke all application passwords' ); ?></button>
</div>
<?php endif; ?>
<div class="alignleft actions bulkactions">
<?php $this->bulk_actions( $which ); ?>
</div>
<?php
$this->extra_tablenav( $which );
$this->pagination( $which );
?>
<br class="clear" />
</div>
<?php
}
/**
* Generates content for a single row of the table.
*
* @since 5.6.0
*
* @param array $item The current item.
*/
public function single_row( $item ) {
echo '<tr data-uuid="' . esc_attr( $item['uuid'] ) . '">';
$this->single_row_columns( $item );
echo '</tr>';
}
/**
* Gets the name of the default primary column.
*
* @since 5.6.0
*
* @return string Name of the default primary column, in this case, 'name'.
*/
protected function get_default_primary_column_name() {
return 'name';
}
/**
* Prints the JavaScript template for the new row item.
*
* @since 5.6.0
*/
public function print_js_template_row() {
list( $columns, $hidden, , $primary ) = $this->get_column_info();
echo '<tr data-uuid="{{ data.uuid }}">';
foreach ( $columns as $column_name => $display_name ) {
$is_primary = $primary === $column_name;
$classes = "{$column_name} column-{$column_name}";
if ( $is_primary ) {
$classes .= ' has-row-actions column-primary';
}
if ( in_array( $column_name, $hidden, true ) ) {
$classes .= ' hidden';
}
printf( '<td class="%s" data-colname="%s">', esc_attr( $classes ), esc_attr( wp_strip_all_tags( $display_name ) ) );
switch ( $column_name ) {
case 'name':
echo '{{ data.name }}';
break;
case 'created':
// JSON encoding automatically doubles backslashes to ensure they don't get lost when printing the inline JS.
echo '<# print( wp.date.dateI18n( ' . wp_json_encode( __( 'F j, Y' ) ) . ', data.created ) ) #>';
break;
case 'last_used':
echo '<# print( data.last_used !== null ? wp.date.dateI18n( ' . wp_json_encode( __( 'F j, Y' ) ) . ", data.last_used ) : '—' ) #>";
break;
case 'last_ip':
echo "{{ data.last_ip || '—' }}";
break;
case 'revoke':
printf(
'<button type="button" class="button delete" aria-label="%1$s">%2$s</button>',
/* translators: %s: the application password's given name. */
esc_attr( sprintf( __( 'Revoke "%s"' ), '{{ data.name }}' ) ),
esc_html__( 'Revoke' )
);
break;
default:
/**
* Fires in the JavaScript row template for each custom column in the Application Passwords list table.
*
* Custom columns are registered using the {@see 'manage_application-passwords-user_columns'} filter.
*
* @since 5.6.0
*
* @param string $column_name Name of the custom column.
*/
do_action( "manage_{$this->screen->id}_custom_column_js_template", $column_name );
break;
}
if ( $is_primary ) {
echo '<button type="button" class="toggle-row"><span class="screen-reader-text">' .
/* translators: Hidden accessibility text. */
__( 'Show more details' ) .
'</span></button>';
}
echo '</td>';
}
echo '</tr>';
}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,530 @@
<?php
/**
* Administration: Community Events class.
*
* @package WordPress
* @subpackage Administration
* @since 4.8.0
*/
/**
* Class WP_Community_Events.
*
* A client for api.wordpress.org/events.
*
* @since 4.8.0
*/
#[AllowDynamicProperties]
class WP_Community_Events {
/**
* ID for a WordPress user account.
*
* @since 4.8.0
*
* @var int
*/
protected $user_id = 0;
/**
* Stores location data for the user.
*
* @since 4.8.0
*
* @var false|array
*/
protected $user_location = false;
/**
* Constructor for WP_Community_Events.
*
* @since 4.8.0
*
* @param int $user_id WP user ID.
* @param false|array $user_location {
* Stored location data for the user. false to pass no location.
*
* @type string $description The name of the location
* @type string $latitude The latitude in decimal degrees notation, without the degree
* symbol. e.g.: 47.615200.
* @type string $longitude The longitude in decimal degrees notation, without the degree
* symbol. e.g.: -122.341100.
* @type string $country The ISO 3166-1 alpha-2 country code. e.g.: BR
* }
*/
public function __construct( $user_id, $user_location = false ) {
$this->user_id = absint( $user_id );
$this->user_location = $user_location;
}
/**
* Gets data about events near a particular location.
*
* Cached events will be immediately returned if the `user_location` property
* is set for the current user, and cached events exist for that location.
*
* Otherwise, this method sends a request to the w.org Events API with location
* data. The API will send back a recognized location based on the data, along
* with nearby events.
*
* The browser's request for events is proxied with this method, rather
* than having the browser make the request directly to api.wordpress.org,
* because it allows results to be cached server-side and shared with other
* users and sites in the network. This makes the process more efficient,
* since increasing the number of visits that get cached data means users
* don't have to wait as often; if the user's browser made the request
* directly, it would also need to make a second request to WP in order to
* pass the data for caching. Having WP make the request also introduces
* the opportunity to anonymize the IP before sending it to w.org, which
* mitigates possible privacy concerns.
*
* @since 4.8.0
* @since 5.5.2 Response no longer contains formatted date field. They're added
* in `wp.communityEvents.populateDynamicEventFields()` now.
*
* @param string $location_search Optional. City name to help determine the location.
* e.g., "Seattle". Default empty string.
* @param string $timezone Optional. Timezone to help determine the location.
* Default empty string.
* @return array|WP_Error A WP_Error on failure; an array with location and events on
* success.
*/
public function get_events( $location_search = '', $timezone = '' ) {
$cached_events = $this->get_cached_events();
if ( ! $location_search && $cached_events ) {
return $cached_events;
}
// Include an unmodified $wp_version.
require ABSPATH . WPINC . '/version.php';
$api_url = 'http://api.wordpress.org/events/1.0/';
$request_args = $this->get_request_args( $location_search, $timezone );
$request_args['user-agent'] = 'WordPress/' . $wp_version . '; ' . home_url( '/' );
if ( wp_http_supports( array( 'ssl' ) ) ) {
$api_url = set_url_scheme( $api_url, 'https' );
}
$response = wp_remote_get( $api_url, $request_args );
$response_code = wp_remote_retrieve_response_code( $response );
$response_body = json_decode( wp_remote_retrieve_body( $response ), true );
$response_error = null;
if ( is_wp_error( $response ) ) {
$response_error = $response;
} elseif ( 200 !== $response_code ) {
$response_error = new WP_Error(
'api-error',
/* translators: %d: Numeric HTTP status code, e.g. 400, 403, 500, 504, etc. */
sprintf( __( 'Invalid API response code (%d).' ), $response_code )
);
} elseif ( ! isset( $response_body['location'], $response_body['events'] ) ) {
$response_error = new WP_Error(
'api-invalid-response',
isset( $response_body['error'] ) ? $response_body['error'] : __( 'Unknown API error.' )
);
}
if ( is_wp_error( $response_error ) ) {
return $response_error;
} else {
$expiration = false;
if ( isset( $response_body['ttl'] ) ) {
$expiration = $response_body['ttl'];
unset( $response_body['ttl'] );
}
/*
* The IP in the response is usually the same as the one that was sent
* in the request, but in some cases it is different. In those cases,
* it's important to reset it back to the IP from the request.
*
* For example, if the IP sent in the request is private (e.g., 192.168.1.100),
* then the API will ignore that and use the corresponding public IP instead,
* and the public IP will get returned. If the public IP were saved, though,
* then get_cached_events() would always return `false`, because the transient
* would be generated based on the public IP when saving the cache, but generated
* based on the private IP when retrieving the cache.
*/
if ( ! empty( $response_body['location']['ip'] ) ) {
$response_body['location']['ip'] = $request_args['body']['ip'];
}
/*
* The API doesn't return a description for latitude/longitude requests,
* but the description is already saved in the user location, so that
* one can be used instead.
*/
if ( $this->coordinates_match( $request_args['body'], $response_body['location'] ) && empty( $response_body['location']['description'] ) ) {
$response_body['location']['description'] = $this->user_location['description'];
}
/*
* Store the raw response, because events will expire before the cache does.
* The response will need to be processed every page load.
*/
$this->cache_events( $response_body, $expiration );
$response_body['events'] = $this->trim_events( $response_body['events'] );
return $response_body;
}
}
/**
* Builds an array of args to use in an HTTP request to the w.org Events API.
*
* @since 4.8.0
*
* @param string $search Optional. City search string. Default empty string.
* @param string $timezone Optional. Timezone string. Default empty string.
* @return array The request args.
*/
protected function get_request_args( $search = '', $timezone = '' ) {
$args = array(
'number' => 5, // Get more than three in case some get trimmed out.
'ip' => self::get_unsafe_client_ip(),
);
/*
* Include the minimal set of necessary arguments, in order to increase the
* chances of a cache-hit on the API side.
*/
if ( empty( $search ) && isset( $this->user_location['latitude'], $this->user_location['longitude'] ) ) {
$args['latitude'] = $this->user_location['latitude'];
$args['longitude'] = $this->user_location['longitude'];
} else {
$args['locale'] = get_user_locale( $this->user_id );
if ( $timezone ) {
$args['timezone'] = $timezone;
}
if ( $search ) {
$args['location'] = $search;
}
}
// Wrap the args in an array compatible with the second parameter of `wp_remote_get()`.
return array(
'body' => $args,
);
}
/**
* Determines the user's actual IP address and attempts to partially
* anonymize an IP address by converting it to a network ID.
*
* Geolocating the network ID usually returns a similar location as the
* actual IP, but provides some privacy for the user.
*
* $_SERVER['REMOTE_ADDR'] cannot be used in all cases, such as when the user
* is making their request through a proxy, or when the web server is behind
* a proxy. In those cases, $_SERVER['REMOTE_ADDR'] is set to the proxy address rather
* than the user's actual address.
*
* Modified from https://stackoverflow.com/a/2031935/450127, MIT license.
* Modified from https://github.com/geertw/php-ip-anonymizer, MIT license.
*
* SECURITY WARNING: This function is _NOT_ intended to be used in
* circumstances where the authenticity of the IP address matters. This does
* _NOT_ guarantee that the returned address is valid or accurate, and it can
* be easily spoofed.
*
* @since 4.8.0
*
* @return string|false The anonymized address on success; the given address
* or false on failure.
*/
public static function get_unsafe_client_ip() {
$client_ip = false;
// In order of preference, with the best ones for this purpose first.
$address_headers = array(
'HTTP_CLIENT_IP',
'HTTP_X_FORWARDED_FOR',
'HTTP_X_FORWARDED',
'HTTP_X_CLUSTER_CLIENT_IP',
'HTTP_FORWARDED_FOR',
'HTTP_FORWARDED',
'REMOTE_ADDR',
);
foreach ( $address_headers as $header ) {
if ( array_key_exists( $header, $_SERVER ) ) {
/*
* HTTP_X_FORWARDED_FOR can contain a chain of comma-separated
* addresses. The first one is the original client. It can't be
* trusted for authenticity, but we don't need to for this purpose.
*/
$address_chain = explode( ',', $_SERVER[ $header ] );
$client_ip = trim( $address_chain[0] );
break;
}
}
if ( ! $client_ip ) {
return false;
}
$anon_ip = wp_privacy_anonymize_ip( $client_ip, true );
if ( '0.0.0.0' === $anon_ip || '::' === $anon_ip ) {
return false;
}
return $anon_ip;
}
/**
* Test if two pairs of latitude/longitude coordinates match each other.
*
* @since 4.8.0
*
* @param array $a The first pair, with indexes 'latitude' and 'longitude'.
* @param array $b The second pair, with indexes 'latitude' and 'longitude'.
* @return bool True if they match, false if they don't.
*/
protected function coordinates_match( $a, $b ) {
if ( ! isset( $a['latitude'], $a['longitude'], $b['latitude'], $b['longitude'] ) ) {
return false;
}
return $a['latitude'] === $b['latitude'] && $a['longitude'] === $b['longitude'];
}
/**
* Generates a transient key based on user location.
*
* This could be reduced to a one-liner in the calling functions, but it's
* intentionally a separate function because it's called from multiple
* functions, and having it abstracted keeps the logic consistent and DRY,
* which is less prone to errors.
*
* @since 4.8.0
*
* @param array $location Should contain 'latitude' and 'longitude' indexes.
* @return string|false Transient key on success, false on failure.
*/
protected function get_events_transient_key( $location ) {
$key = false;
if ( isset( $location['ip'] ) ) {
$key = 'community-events-' . md5( $location['ip'] );
} elseif ( isset( $location['latitude'], $location['longitude'] ) ) {
$key = 'community-events-' . md5( $location['latitude'] . $location['longitude'] );
}
return $key;
}
/**
* Caches an array of events data from the Events API.
*
* @since 4.8.0
*
* @param array $events Response body from the API request.
* @param int|false $expiration Optional. Amount of time to cache the events. Defaults to false.
* @return bool true if events were cached; false if not.
*/
protected function cache_events( $events, $expiration = false ) {
$set = false;
$transient_key = $this->get_events_transient_key( $events['location'] );
$cache_expiration = $expiration ? absint( $expiration ) : HOUR_IN_SECONDS * 12;
if ( $transient_key ) {
$set = set_site_transient( $transient_key, $events, $cache_expiration );
}
return $set;
}
/**
* Gets cached events.
*
* @since 4.8.0
* @since 5.5.2 Response no longer contains formatted date field. They're added
* in `wp.communityEvents.populateDynamicEventFields()` now.
*
* @return array|false An array containing `location` and `events` items
* on success, false on failure.
*/
public function get_cached_events() {
$transient_key = $this->get_events_transient_key( $this->user_location );
if ( ! $transient_key ) {
return false;
}
$cached_response = get_site_transient( $transient_key );
if ( isset( $cached_response['events'] ) ) {
$cached_response['events'] = $this->trim_events( $cached_response['events'] );
}
return $cached_response;
}
/**
* Adds formatted date and time items for each event in an API response.
*
* This has to be called after the data is pulled from the cache, because
* the cached events are shared by all users. If it was called before storing
* the cache, then all users would see the events in the localized data/time
* of the user who triggered the cache refresh, rather than their own.
*
* @since 4.8.0
* @deprecated 5.6.0 No longer used in core.
*
* @param array $response_body The response which contains the events.
* @return array The response with dates and times formatted.
*/
protected function format_event_data_time( $response_body ) {
_deprecated_function(
__METHOD__,
'5.5.2',
'This is no longer used by core, and only kept for backward compatibility.'
);
if ( isset( $response_body['events'] ) ) {
foreach ( $response_body['events'] as $key => $event ) {
$timestamp = strtotime( $event['date'] );
/*
* The `date_format` option is not used because it's important
* in this context to keep the day of the week in the formatted date,
* so that users can tell at a glance if the event is on a day they
* are available, without having to open the link.
*/
/* translators: Date format for upcoming events on the dashboard. Include the day of the week. See https://www.php.net/manual/datetime.format.php */
$formatted_date = date_i18n( __( 'l, M j, Y' ), $timestamp );
$formatted_time = date_i18n( get_option( 'time_format' ), $timestamp );
if ( isset( $event['end_date'] ) ) {
$end_timestamp = strtotime( $event['end_date'] );
$formatted_end_date = date_i18n( __( 'l, M j, Y' ), $end_timestamp );
if ( 'meetup' !== $event['type'] && $formatted_end_date !== $formatted_date ) {
/* translators: Upcoming events month format. See https://www.php.net/manual/datetime.format.php */
$start_month = date_i18n( _x( 'F', 'upcoming events month format' ), $timestamp );
$end_month = date_i18n( _x( 'F', 'upcoming events month format' ), $end_timestamp );
if ( $start_month === $end_month ) {
$formatted_date = sprintf(
/* translators: Date string for upcoming events. 1: Month, 2: Starting day, 3: Ending day, 4: Year. */
__( '%1$s %2$d%3$d, %4$d' ),
$start_month,
/* translators: Upcoming events day format. See https://www.php.net/manual/datetime.format.php */
date_i18n( _x( 'j', 'upcoming events day format' ), $timestamp ),
date_i18n( _x( 'j', 'upcoming events day format' ), $end_timestamp ),
/* translators: Upcoming events year format. See https://www.php.net/manual/datetime.format.php */
date_i18n( _x( 'Y', 'upcoming events year format' ), $timestamp )
);
} else {
$formatted_date = sprintf(
/* translators: Date string for upcoming events. 1: Starting month, 2: Starting day, 3: Ending month, 4: Ending day, 5: Year. */
__( '%1$s %2$d %3$s %4$d, %5$d' ),
$start_month,
date_i18n( _x( 'j', 'upcoming events day format' ), $timestamp ),
$end_month,
date_i18n( _x( 'j', 'upcoming events day format' ), $end_timestamp ),
date_i18n( _x( 'Y', 'upcoming events year format' ), $timestamp )
);
}
$formatted_date = wp_maybe_decline_date( $formatted_date, 'F j, Y' );
}
}
$response_body['events'][ $key ]['formatted_date'] = $formatted_date;
$response_body['events'][ $key ]['formatted_time'] = $formatted_time;
}
}
return $response_body;
}
/**
* Prepares the event list for presentation.
*
* Discards expired events, and makes WordCamps "sticky." Attendees need more
* advanced notice about WordCamps than they do for meetups, so camps should
* appear in the list sooner. If a WordCamp is coming up, the API will "stick"
* it in the response, even if it wouldn't otherwise appear. When that happens,
* the event will be at the end of the list, and will need to be moved into a
* higher position, so that it doesn't get trimmed off.
*
* @since 4.8.0
* @since 4.9.7 Stick a WordCamp to the final list.
* @since 5.5.2 Accepts and returns only the events, rather than an entire HTTP response.
* @since 6.0.0 Decode HTML entities from the event title.
*
* @param array $events The events that will be prepared.
* @return array The response body with events trimmed.
*/
protected function trim_events( array $events ) {
$future_events = array();
foreach ( $events as $event ) {
/*
* The API's `date` and `end_date` fields are in the _event's_ local timezone, but UTC is needed so
* it can be converted to the _user's_ local time.
*/
$end_time = (int) $event['end_unix_timestamp'];
if ( time() < $end_time ) {
// Decode HTML entities from the event title.
$event['title'] = html_entity_decode( $event['title'], ENT_QUOTES, 'UTF-8' );
array_push( $future_events, $event );
}
}
$future_wordcamps = array_filter(
$future_events,
static function ( $wordcamp ) {
return 'wordcamp' === $wordcamp['type'];
}
);
$future_wordcamps = array_values( $future_wordcamps ); // Remove gaps in indices.
$trimmed_events = array_slice( $future_events, 0, 3 );
$trimmed_event_types = wp_list_pluck( $trimmed_events, 'type' );
// Make sure the soonest upcoming WordCamp is pinned in the list.
if ( $future_wordcamps && ! in_array( 'wordcamp', $trimmed_event_types, true ) ) {
array_pop( $trimmed_events );
array_push( $trimmed_events, $future_wordcamps[0] );
}
return $trimmed_events;
}
/**
* Logs responses to Events API requests.
*
* @since 4.8.0
* @deprecated 4.9.0 Use a plugin instead. See #41217 for an example.
*
* @param string $message A description of what occurred.
* @param array $details Details that provide more context for the
* log entry.
*/
protected function maybe_log_events_response( $message, $details ) {
_deprecated_function( __METHOD__, '4.9.0' );
if ( ! WP_DEBUG_LOG ) {
return;
}
error_log(
sprintf(
'%s: %s. Details: %s',
__METHOD__,
trim( $message, '.' ),
wp_json_encode( $details )
)
);
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,864 @@
<?php
/**
* Base WordPress Filesystem
*
* @package WordPress
* @subpackage Filesystem
*/
/**
* Base WordPress Filesystem class which Filesystem implementations extend.
*
* @since 2.5.0
*/
#[AllowDynamicProperties]
class WP_Filesystem_Base {
/**
* Whether to display debug data for the connection.
*
* @since 2.5.0
* @var bool
*/
public $verbose = false;
/**
* Cached list of local filepaths to mapped remote filepaths.
*
* @since 2.7.0
* @var array
*/
public $cache = array();
/**
* The Access method of the current connection, Set automatically.
*
* @since 2.5.0
* @var string
*/
public $method = '';
/**
* @var WP_Error
*/
public $errors = null;
/**
*/
public $options = array();
/**
* Returns the path on the remote filesystem of ABSPATH.
*
* @since 2.7.0
*
* @return string The location of the remote path.
*/
public function abspath() {
$folder = $this->find_folder( ABSPATH );
/*
* Perhaps the FTP folder is rooted at the WordPress install.
* Check for wp-includes folder in root. Could have some false positives, but rare.
*/
if ( ! $folder && $this->is_dir( '/' . WPINC ) ) {
$folder = '/';
}
return $folder;
}
/**
* Returns the path on the remote filesystem of WP_CONTENT_DIR.
*
* @since 2.7.0
*
* @return string The location of the remote path.
*/
public function wp_content_dir() {
return $this->find_folder( WP_CONTENT_DIR );
}
/**
* Returns the path on the remote filesystem of WP_PLUGIN_DIR.
*
* @since 2.7.0
*
* @return string The location of the remote path.
*/
public function wp_plugins_dir() {
return $this->find_folder( WP_PLUGIN_DIR );
}
/**
* Returns the path on the remote filesystem of the Themes Directory.
*
* @since 2.7.0
*
* @param string|false $theme Optional. The theme stylesheet or template for the directory.
* Default false.
* @return string The location of the remote path.
*/
public function wp_themes_dir( $theme = false ) {
$theme_root = get_theme_root( $theme );
// Account for relative theme roots.
if ( '/themes' === $theme_root || ! is_dir( $theme_root ) ) {
$theme_root = WP_CONTENT_DIR . $theme_root;
}
return $this->find_folder( $theme_root );
}
/**
* Returns the path on the remote filesystem of WP_LANG_DIR.
*
* @since 3.2.0
*
* @return string The location of the remote path.
*/
public function wp_lang_dir() {
return $this->find_folder( WP_LANG_DIR );
}
/**
* Locates a folder on the remote filesystem.
*
* @since 2.5.0
* @deprecated 2.7.0 use WP_Filesystem_Base::abspath() or WP_Filesystem_Base::wp_*_dir() instead.
* @see WP_Filesystem_Base::abspath()
* @see WP_Filesystem_Base::wp_content_dir()
* @see WP_Filesystem_Base::wp_plugins_dir()
* @see WP_Filesystem_Base::wp_themes_dir()
* @see WP_Filesystem_Base::wp_lang_dir()
*
* @param string $base Optional. The folder to start searching from. Default '.'.
* @param bool $verbose Optional. True to display debug information. Default false.
* @return string The location of the remote path.
*/
public function find_base_dir( $base = '.', $verbose = false ) {
_deprecated_function( __FUNCTION__, '2.7.0', 'WP_Filesystem_Base::abspath() or WP_Filesystem_Base::wp_*_dir()' );
$this->verbose = $verbose;
return $this->abspath();
}
/**
* Locates a folder on the remote filesystem.
*
* @since 2.5.0
* @deprecated 2.7.0 use WP_Filesystem_Base::abspath() or WP_Filesystem_Base::wp_*_dir() methods instead.
* @see WP_Filesystem_Base::abspath()
* @see WP_Filesystem_Base::wp_content_dir()
* @see WP_Filesystem_Base::wp_plugins_dir()
* @see WP_Filesystem_Base::wp_themes_dir()
* @see WP_Filesystem_Base::wp_lang_dir()
*
* @param string $base Optional. The folder to start searching from. Default '.'.
* @param bool $verbose Optional. True to display debug information. Default false.
* @return string The location of the remote path.
*/
public function get_base_dir( $base = '.', $verbose = false ) {
_deprecated_function( __FUNCTION__, '2.7.0', 'WP_Filesystem_Base::abspath() or WP_Filesystem_Base::wp_*_dir()' );
$this->verbose = $verbose;
return $this->abspath();
}
/**
* Locates a folder on the remote filesystem.
*
* Assumes that on Windows systems, Stripping off the Drive
* letter is OK Sanitizes \\ to / in Windows filepaths.
*
* @since 2.7.0
*
* @param string $folder the folder to locate.
* @return string|false The location of the remote path, false on failure.
*/
public function find_folder( $folder ) {
if ( isset( $this->cache[ $folder ] ) ) {
return $this->cache[ $folder ];
}
if ( stripos( $this->method, 'ftp' ) !== false ) {
$constant_overrides = array(
'FTP_BASE' => ABSPATH,
'FTP_CONTENT_DIR' => WP_CONTENT_DIR,
'FTP_PLUGIN_DIR' => WP_PLUGIN_DIR,
'FTP_LANG_DIR' => WP_LANG_DIR,
);
// Direct matches ( folder = CONSTANT/ ).
foreach ( $constant_overrides as $constant => $dir ) {
if ( ! defined( $constant ) ) {
continue;
}
if ( $folder === $dir ) {
return trailingslashit( constant( $constant ) );
}
}
// Prefix matches ( folder = CONSTANT/subdir ),
foreach ( $constant_overrides as $constant => $dir ) {
if ( ! defined( $constant ) ) {
continue;
}
if ( 0 === stripos( $folder, $dir ) ) { // $folder starts with $dir.
$potential_folder = preg_replace( '#^' . preg_quote( $dir, '#' ) . '/#i', trailingslashit( constant( $constant ) ), $folder );
$potential_folder = trailingslashit( $potential_folder );
if ( $this->is_dir( $potential_folder ) ) {
$this->cache[ $folder ] = $potential_folder;
return $potential_folder;
}
}
}
} elseif ( 'direct' === $this->method ) {
$folder = str_replace( '\\', '/', $folder ); // Windows path sanitization.
return trailingslashit( $folder );
}
$folder = preg_replace( '|^([a-z]{1}):|i', '', $folder ); // Strip out Windows drive letter if it's there.
$folder = str_replace( '\\', '/', $folder ); // Windows path sanitization.
if ( isset( $this->cache[ $folder ] ) ) {
return $this->cache[ $folder ];
}
if ( $this->exists( $folder ) ) { // Folder exists at that absolute path.
$folder = trailingslashit( $folder );
$this->cache[ $folder ] = $folder;
return $folder;
}
$return = $this->search_for_folder( $folder );
if ( $return ) {
$this->cache[ $folder ] = $return;
}
return $return;
}
/**
* Locates a folder on the remote filesystem.
*
* Expects Windows sanitized path.
*
* @since 2.7.0
*
* @param string $folder The folder to locate.
* @param string $base The folder to start searching from.
* @param bool $loop If the function has recursed. Internal use only.
* @return string|false The location of the remote path, false to cease looping.
*/
public function search_for_folder( $folder, $base = '.', $loop = false ) {
if ( empty( $base ) || '.' === $base ) {
$base = trailingslashit( $this->cwd() );
}
$folder = untrailingslashit( $folder );
if ( $this->verbose ) {
/* translators: 1: Folder to locate, 2: Folder to start searching from. */
printf( "\n" . __( 'Looking for %1$s in %2$s' ) . "<br />\n", $folder, $base );
}
$folder_parts = explode( '/', $folder );
$folder_part_keys = array_keys( $folder_parts );
$last_index = array_pop( $folder_part_keys );
$last_path = $folder_parts[ $last_index ];
$files = $this->dirlist( $base );
foreach ( $folder_parts as $index => $key ) {
if ( $index === $last_index ) {
continue; // We want this to be caught by the next code block.
}
/*
* Working from /home/ to /user/ to /wordpress/ see if that file exists within
* the current folder, If it's found, change into it and follow through looking
* for it. If it can't find WordPress down that route, it'll continue onto the next
* folder level, and see if that matches, and so on. If it reaches the end, and still
* can't find it, it'll return false for the entire function.
*/
if ( isset( $files[ $key ] ) ) {
// Let's try that folder:
$newdir = trailingslashit( path_join( $base, $key ) );
if ( $this->verbose ) {
/* translators: %s: Directory name. */
printf( "\n" . __( 'Changing to %s' ) . "<br />\n", $newdir );
}
// Only search for the remaining path tokens in the directory, not the full path again.
$newfolder = implode( '/', array_slice( $folder_parts, $index + 1 ) );
$ret = $this->search_for_folder( $newfolder, $newdir, $loop );
if ( $ret ) {
return $ret;
}
}
}
/*
* Only check this as a last resort, to prevent locating the incorrect install.
* All above procedures will fail quickly if this is the right branch to take.
*/
if ( isset( $files[ $last_path ] ) ) {
if ( $this->verbose ) {
/* translators: %s: Directory name. */
printf( "\n" . __( 'Found %s' ) . "<br />\n", $base . $last_path );
}
return trailingslashit( $base . $last_path );
}
/*
* Prevent this function from looping again.
* No need to proceed if we've just searched in `/`.
*/
if ( $loop || '/' === $base ) {
return false;
}
/*
* As an extra last resort, Change back to / if the folder wasn't found.
* This comes into effect when the CWD is /home/user/ but WP is at /var/www/....
*/
return $this->search_for_folder( $folder, '/', true );
}
/**
* Returns the *nix-style file permissions for a file.
*
* From the PHP documentation page for fileperms().
*
* @link https://www.php.net/manual/en/function.fileperms.php
*
* @since 2.5.0
*
* @param string $file String filename.
* @return string The *nix-style representation of permissions.
*/
public function gethchmod( $file ) {
$perms = intval( $this->getchmod( $file ), 8 );
if ( ( $perms & 0xC000 ) === 0xC000 ) { // Socket.
$info = 's';
} elseif ( ( $perms & 0xA000 ) === 0xA000 ) { // Symbolic Link.
$info = 'l';
} elseif ( ( $perms & 0x8000 ) === 0x8000 ) { // Regular.
$info = '-';
} elseif ( ( $perms & 0x6000 ) === 0x6000 ) { // Block special.
$info = 'b';
} elseif ( ( $perms & 0x4000 ) === 0x4000 ) { // Directory.
$info = 'd';
} elseif ( ( $perms & 0x2000 ) === 0x2000 ) { // Character special.
$info = 'c';
} elseif ( ( $perms & 0x1000 ) === 0x1000 ) { // FIFO pipe.
$info = 'p';
} else { // Unknown.
$info = 'u';
}
// Owner.
$info .= ( ( $perms & 0x0100 ) ? 'r' : '-' );
$info .= ( ( $perms & 0x0080 ) ? 'w' : '-' );
$info .= ( ( $perms & 0x0040 ) ?
( ( $perms & 0x0800 ) ? 's' : 'x' ) :
( ( $perms & 0x0800 ) ? 'S' : '-' ) );
// Group.
$info .= ( ( $perms & 0x0020 ) ? 'r' : '-' );
$info .= ( ( $perms & 0x0010 ) ? 'w' : '-' );
$info .= ( ( $perms & 0x0008 ) ?
( ( $perms & 0x0400 ) ? 's' : 'x' ) :
( ( $perms & 0x0400 ) ? 'S' : '-' ) );
// World.
$info .= ( ( $perms & 0x0004 ) ? 'r' : '-' );
$info .= ( ( $perms & 0x0002 ) ? 'w' : '-' );
$info .= ( ( $perms & 0x0001 ) ?
( ( $perms & 0x0200 ) ? 't' : 'x' ) :
( ( $perms & 0x0200 ) ? 'T' : '-' ) );
return $info;
}
/**
* Gets the permissions of the specified file or filepath in their octal format.
*
* @since 2.5.0
*
* @param string $file Path to the file.
* @return string Mode of the file (the last 3 digits).
*/
public function getchmod( $file ) {
return '777';
}
/**
* Converts *nix-style file permissions to an octal number.
*
* Converts '-rw-r--r--' to 0644
* From "info at rvgate dot nl"'s comment on the PHP documentation for chmod()
*
* @link https://www.php.net/manual/en/function.chmod.php#49614
*
* @since 2.5.0
*
* @param string $mode string The *nix-style file permissions.
* @return string Octal representation of permissions.
*/
public function getnumchmodfromh( $mode ) {
$realmode = '';
$legal = array( '', 'w', 'r', 'x', '-' );
$attarray = preg_split( '//', $mode );
for ( $i = 0, $c = count( $attarray ); $i < $c; $i++ ) {
$key = array_search( $attarray[ $i ], $legal, true );
if ( $key ) {
$realmode .= $legal[ $key ];
}
}
$mode = str_pad( $realmode, 10, '-', STR_PAD_LEFT );
$trans = array(
'-' => '0',
'r' => '4',
'w' => '2',
'x' => '1',
);
$mode = strtr( $mode, $trans );
$newmode = $mode[0];
$newmode .= $mode[1] + $mode[2] + $mode[3];
$newmode .= $mode[4] + $mode[5] + $mode[6];
$newmode .= $mode[7] + $mode[8] + $mode[9];
return $newmode;
}
/**
* Determines if the string provided contains binary characters.
*
* @since 2.7.0
*
* @param string $text String to test against.
* @return bool True if string is binary, false otherwise.
*/
public function is_binary( $text ) {
return (bool) preg_match( '|[^\x20-\x7E]|', $text ); // chr(32)..chr(127)
}
/**
* Changes the owner of a file or directory.
*
* Default behavior is to do nothing, override this in your subclass, if desired.
*
* @since 2.5.0
*
* @param string $file Path to the file or directory.
* @param string|int $owner A user name or number.
* @param bool $recursive Optional. If set to true, changes file owner recursively.
* Default false.
* @return bool True on success, false on failure.
*/
public function chown( $file, $owner, $recursive = false ) {
return false;
}
/**
* Connects filesystem.
*
* @since 2.5.0
* @abstract
*
* @return bool True on success, false on failure (always true for WP_Filesystem_Direct).
*/
public function connect() {
return true;
}
/**
* Reads entire file into a string.
*
* @since 2.5.0
* @abstract
*
* @param string $file Name of the file to read.
* @return string|false Read data on success, false on failure.
*/
public function get_contents( $file ) {
return false;
}
/**
* Reads entire file into an array.
*
* @since 2.5.0
* @abstract
*
* @param string $file Path to the file.
* @return array|false File contents in an array on success, false on failure.
*/
public function get_contents_array( $file ) {
return false;
}
/**
* Writes a string to a file.
*
* @since 2.5.0
* @abstract
*
* @param string $file Remote path to the file where to write the data.
* @param string $contents The data to write.
* @param int|false $mode Optional. The file permissions as octal number, usually 0644.
* Default false.
* @return bool True on success, false on failure.
*/
public function put_contents( $file, $contents, $mode = false ) {
return false;
}
/**
* Gets the current working directory.
*
* @since 2.5.0
* @abstract
*
* @return string|false The current working directory on success, false on failure.
*/
public function cwd() {
return false;
}
/**
* Changes current directory.
*
* @since 2.5.0
* @abstract
*
* @param string $dir The new current directory.
* @return bool True on success, false on failure.
*/
public function chdir( $dir ) {
return false;
}
/**
* Changes the file group.
*
* @since 2.5.0
* @abstract
*
* @param string $file Path to the file.
* @param string|int $group A group name or number.
* @param bool $recursive Optional. If set to true, changes file group recursively.
* Default false.
* @return bool True on success, false on failure.
*/
public function chgrp( $file, $group, $recursive = false ) {
return false;
}
/**
* Changes filesystem permissions.
*
* @since 2.5.0
* @abstract
*
* @param string $file Path to the file.
* @param int|false $mode Optional. The permissions as octal number, usually 0644 for files,
* 0755 for directories. Default false.
* @param bool $recursive Optional. If set to true, changes file permissions recursively.
* Default false.
* @return bool True on success, false on failure.
*/
public function chmod( $file, $mode = false, $recursive = false ) {
return false;
}
/**
* Gets the file owner.
*
* @since 2.5.0
* @abstract
*
* @param string $file Path to the file.
* @return string|false Username of the owner on success, false on failure.
*/
public function owner( $file ) {
return false;
}
/**
* Gets the file's group.
*
* @since 2.5.0
* @abstract
*
* @param string $file Path to the file.
* @return string|false The group on success, false on failure.
*/
public function group( $file ) {
return false;
}
/**
* Copies a file.
*
* @since 2.5.0
* @abstract
*
* @param string $source Path to the source file.
* @param string $destination Path to the destination file.
* @param bool $overwrite Optional. Whether to overwrite the destination file if it exists.
* Default false.
* @param int|false $mode Optional. The permissions as octal number, usually 0644 for files,
* 0755 for dirs. Default false.
* @return bool True on success, false on failure.
*/
public function copy( $source, $destination, $overwrite = false, $mode = false ) {
return false;
}
/**
* Moves a file.
*
* @since 2.5.0
* @abstract
*
* @param string $source Path to the source file.
* @param string $destination Path to the destination file.
* @param bool $overwrite Optional. Whether to overwrite the destination file if it exists.
* Default false.
* @return bool True on success, false on failure.
*/
public function move( $source, $destination, $overwrite = false ) {
return false;
}
/**
* Deletes a file or directory.
*
* @since 2.5.0
* @abstract
*
* @param string $file Path to the file or directory.
* @param bool $recursive Optional. If set to true, deletes files and folders recursively.
* Default false.
* @param string|false $type Type of resource. 'f' for file, 'd' for directory.
* Default false.
* @return bool True on success, false on failure.
*/
public function delete( $file, $recursive = false, $type = false ) {
return false;
}
/**
* Checks if a file or directory exists.
*
* @since 2.5.0
* @abstract
*
* @param string $path Path to file or directory.
* @return bool Whether $path exists or not.
*/
public function exists( $path ) {
return false;
}
/**
* Checks if resource is a file.
*
* @since 2.5.0
* @abstract
*
* @param string $file File path.
* @return bool Whether $file is a file.
*/
public function is_file( $file ) {
return false;
}
/**
* Checks if resource is a directory.
*
* @since 2.5.0
* @abstract
*
* @param string $path Directory path.
* @return bool Whether $path is a directory.
*/
public function is_dir( $path ) {
return false;
}
/**
* Checks if a file is readable.
*
* @since 2.5.0
* @abstract
*
* @param string $file Path to file.
* @return bool Whether $file is readable.
*/
public function is_readable( $file ) {
return false;
}
/**
* Checks if a file or directory is writable.
*
* @since 2.5.0
* @abstract
*
* @param string $path Path to file or directory.
* @return bool Whether $path is writable.
*/
public function is_writable( $path ) {
return false;
}
/**
* Gets the file's last access time.
*
* @since 2.5.0
* @abstract
*
* @param string $file Path to file.
* @return int|false Unix timestamp representing last access time, false on failure.
*/
public function atime( $file ) {
return false;
}
/**
* Gets the file modification time.
*
* @since 2.5.0
* @abstract
*
* @param string $file Path to file.
* @return int|false Unix timestamp representing modification time, false on failure.
*/
public function mtime( $file ) {
return false;
}
/**
* Gets the file size (in bytes).
*
* @since 2.5.0
* @abstract
*
* @param string $file Path to file.
* @return int|false Size of the file in bytes on success, false on failure.
*/
public function size( $file ) {
return false;
}
/**
* Sets the access and modification times of a file.
*
* Note: If $file doesn't exist, it will be created.
*
* @since 2.5.0
* @abstract
*
* @param string $file Path to file.
* @param int $time Optional. Modified time to set for file.
* Default 0.
* @param int $atime Optional. Access time to set for file.
* Default 0.
* @return bool True on success, false on failure.
*/
public function touch( $file, $time = 0, $atime = 0 ) {
return false;
}
/**
* Creates a directory.
*
* @since 2.5.0
* @abstract
*
* @param string $path Path for new directory.
* @param int|false $chmod Optional. The permissions as octal number (or false to skip chmod).
* Default false.
* @param string|int|false $chown Optional. A user name or number (or false to skip chown).
* Default false.
* @param string|int|false $chgrp Optional. A group name or number (or false to skip chgrp).
* Default false.
* @return bool True on success, false on failure.
*/
public function mkdir( $path, $chmod = false, $chown = false, $chgrp = false ) {
return false;
}
/**
* Deletes a directory.
*
* @since 2.5.0
* @abstract
*
* @param string $path Path to directory.
* @param bool $recursive Optional. Whether to recursively remove files/directories.
* Default false.
* @return bool True on success, false on failure.
*/
public function rmdir( $path, $recursive = false ) {
return false;
}
/**
* Gets details for files in a directory or a specific file.
*
* @since 2.5.0
* @abstract
*
* @param string $path Path to directory or file.
* @param bool $include_hidden Optional. Whether to include details of hidden ("." prefixed) files.
* Default true.
* @param bool $recursive Optional. Whether to recursively include file details in nested directories.
* Default false.
* @return array|false {
* Array of arrays containing file information. False if unable to list directory contents.
*
* @type array ...$0 {
* Array of file information. Note that some elements may not be available on all filesystems.
*
* @type string $name Name of the file or directory.
* @type string $perms *nix representation of permissions.
* @type string $permsn Octal representation of permissions.
* @type int|string|false $number File number. May be a numeric string. False if not available.
* @type string|false $owner Owner name or ID, or false if not available.
* @type string|false $group File permissions group, or false if not available.
* @type int|string|false $size Size of file in bytes. May be a numeric string.
* False if not available.
* @type int|string|false $lastmodunix Last modified unix timestamp. May be a numeric string.
* False if not available.
* @type string|false $lastmod Last modified month (3 letters) and day (without leading 0), or
* false if not available.
* @type string|false $time Last modified time, or false if not available.
* @type string $type Type of resource. 'f' for file, 'd' for directory, 'l' for link.
* @type array|false $files If a directory and `$recursive` is true, contains another array of
* files. False if unable to list directory contents.
* }
* }
*/
public function dirlist( $path, $include_hidden = true, $recursive = false ) {
return false;
}
}

View File

@ -0,0 +1,688 @@
<?php
/**
* WordPress Direct Filesystem.
*
* @package WordPress
* @subpackage Filesystem
*/
/**
* WordPress Filesystem Class for direct PHP file and folder manipulation.
*
* @since 2.5.0
*
* @see WP_Filesystem_Base
*/
class WP_Filesystem_Direct extends WP_Filesystem_Base {
/**
* Constructor.
*
* @since 2.5.0
*
* @param mixed $arg Not used.
*/
public function __construct( $arg ) {
$this->method = 'direct';
$this->errors = new WP_Error();
}
/**
* Reads entire file into a string.
*
* @since 2.5.0
*
* @param string $file Name of the file to read.
* @return string|false Read data on success, false on failure.
*/
public function get_contents( $file ) {
return @file_get_contents( $file );
}
/**
* Reads entire file into an array.
*
* @since 2.5.0
*
* @param string $file Path to the file.
* @return array|false File contents in an array on success, false on failure.
*/
public function get_contents_array( $file ) {
return @file( $file );
}
/**
* Writes a string to a file.
*
* @since 2.5.0
*
* @param string $file Remote path to the file where to write the data.
* @param string $contents The data to write.
* @param int|false $mode Optional. The file permissions as octal number, usually 0644.
* Default false.
* @return bool True on success, false on failure.
*/
public function put_contents( $file, $contents, $mode = false ) {
$fp = @fopen( $file, 'wb' );
if ( ! $fp ) {
return false;
}
mbstring_binary_safe_encoding();
$data_length = strlen( $contents );
$bytes_written = fwrite( $fp, $contents );
reset_mbstring_encoding();
fclose( $fp );
if ( $data_length !== $bytes_written ) {
return false;
}
$this->chmod( $file, $mode );
return true;
}
/**
* Gets the current working directory.
*
* @since 2.5.0
*
* @return string|false The current working directory on success, false on failure.
*/
public function cwd() {
return getcwd();
}
/**
* Changes current directory.
*
* @since 2.5.0
*
* @param string $dir The new current directory.
* @return bool True on success, false on failure.
*/
public function chdir( $dir ) {
return @chdir( $dir );
}
/**
* Changes the file group.
*
* @since 2.5.0
*
* @param string $file Path to the file.
* @param string|int $group A group name or number.
* @param bool $recursive Optional. If set to true, changes file group recursively.
* Default false.
* @return bool True on success, false on failure.
*/
public function chgrp( $file, $group, $recursive = false ) {
if ( ! $this->exists( $file ) ) {
return false;
}
if ( ! $recursive ) {
return chgrp( $file, $group );
}
if ( ! $this->is_dir( $file ) ) {
return chgrp( $file, $group );
}
// Is a directory, and we want recursive.
$file = trailingslashit( $file );
$filelist = $this->dirlist( $file );
foreach ( $filelist as $filename ) {
$this->chgrp( $file . $filename, $group, $recursive );
}
return true;
}
/**
* Changes filesystem permissions.
*
* @since 2.5.0
*
* @param string $file Path to the file.
* @param int|false $mode Optional. The permissions as octal number, usually 0644 for files,
* 0755 for directories. Default false.
* @param bool $recursive Optional. If set to true, changes file permissions recursively.
* Default false.
* @return bool True on success, false on failure.
*/
public function chmod( $file, $mode = false, $recursive = false ) {
if ( ! $mode ) {
if ( $this->is_file( $file ) ) {
$mode = FS_CHMOD_FILE;
} elseif ( $this->is_dir( $file ) ) {
$mode = FS_CHMOD_DIR;
} else {
return false;
}
}
if ( ! $recursive || ! $this->is_dir( $file ) ) {
return chmod( $file, $mode );
}
// Is a directory, and we want recursive.
$file = trailingslashit( $file );
$filelist = $this->dirlist( $file );
foreach ( (array) $filelist as $filename => $filemeta ) {
$this->chmod( $file . $filename, $mode, $recursive );
}
return true;
}
/**
* Changes the owner of a file or directory.
*
* @since 2.5.0
*
* @param string $file Path to the file or directory.
* @param string|int $owner A user name or number.
* @param bool $recursive Optional. If set to true, changes file owner recursively.
* Default false.
* @return bool True on success, false on failure.
*/
public function chown( $file, $owner, $recursive = false ) {
if ( ! $this->exists( $file ) ) {
return false;
}
if ( ! $recursive ) {
return chown( $file, $owner );
}
if ( ! $this->is_dir( $file ) ) {
return chown( $file, $owner );
}
// Is a directory, and we want recursive.
$filelist = $this->dirlist( $file );
foreach ( $filelist as $filename ) {
$this->chown( $file . '/' . $filename, $owner, $recursive );
}
return true;
}
/**
* Gets the file owner.
*
* @since 2.5.0
*
* @param string $file Path to the file.
* @return string|false Username of the owner on success, false on failure.
*/
public function owner( $file ) {
$owneruid = @fileowner( $file );
if ( ! $owneruid ) {
return false;
}
if ( ! function_exists( 'posix_getpwuid' ) ) {
return $owneruid;
}
$ownerarray = posix_getpwuid( $owneruid );
if ( ! $ownerarray ) {
return false;
}
return $ownerarray['name'];
}
/**
* Gets the permissions of the specified file or filepath in their octal format.
*
* FIXME does not handle errors in fileperms()
*
* @since 2.5.0
*
* @param string $file Path to the file.
* @return string Mode of the file (the last 3 digits).
*/
public function getchmod( $file ) {
return substr( decoct( @fileperms( $file ) ), -3 );
}
/**
* Gets the file's group.
*
* @since 2.5.0
*
* @param string $file Path to the file.
* @return string|false The group on success, false on failure.
*/
public function group( $file ) {
$gid = @filegroup( $file );
if ( ! $gid ) {
return false;
}
if ( ! function_exists( 'posix_getgrgid' ) ) {
return $gid;
}
$grouparray = posix_getgrgid( $gid );
if ( ! $grouparray ) {
return false;
}
return $grouparray['name'];
}
/**
* Copies a file.
*
* @since 2.5.0
*
* @param string $source Path to the source file.
* @param string $destination Path to the destination file.
* @param bool $overwrite Optional. Whether to overwrite the destination file if it exists.
* Default false.
* @param int|false $mode Optional. The permissions as octal number, usually 0644 for files,
* 0755 for dirs. Default false.
* @return bool True on success, false on failure.
*/
public function copy( $source, $destination, $overwrite = false, $mode = false ) {
if ( ! $overwrite && $this->exists( $destination ) ) {
return false;
}
$rtval = copy( $source, $destination );
if ( $mode ) {
$this->chmod( $destination, $mode );
}
return $rtval;
}
/**
* Moves a file or directory.
*
* After moving files or directories, OPcache will need to be invalidated.
*
* If moving a directory fails, `copy_dir()` can be used for a recursive copy.
*
* Use `move_dir()` for moving directories with OPcache invalidation and a
* fallback to `copy_dir()`.
*
* @since 2.5.0
*
* @param string $source Path to the source file.
* @param string $destination Path to the destination file.
* @param bool $overwrite Optional. Whether to overwrite the destination file if it exists.
* Default false.
* @return bool True on success, false on failure.
*/
public function move( $source, $destination, $overwrite = false ) {
if ( ! $overwrite && $this->exists( $destination ) ) {
return false;
}
if ( $overwrite && $this->exists( $destination ) && ! $this->delete( $destination, true ) ) {
// Can't overwrite if the destination couldn't be deleted.
return false;
}
// Try using rename first. if that fails (for example, source is read only) try copy.
if ( @rename( $source, $destination ) ) {
return true;
}
// Backward compatibility: Only fall back to `::copy()` for single files.
if ( $this->is_file( $source ) && $this->copy( $source, $destination, $overwrite ) && $this->exists( $destination ) ) {
$this->delete( $source );
return true;
} else {
return false;
}
}
/**
* Deletes a file or directory.
*
* @since 2.5.0
*
* @param string $file Path to the file or directory.
* @param bool $recursive Optional. If set to true, deletes files and folders recursively.
* Default false.
* @param string|false $type Type of resource. 'f' for file, 'd' for directory.
* Default false.
* @return bool True on success, false on failure.
*/
public function delete( $file, $recursive = false, $type = false ) {
if ( empty( $file ) ) {
// Some filesystems report this as /, which can cause non-expected recursive deletion of all files in the filesystem.
return false;
}
$file = str_replace( '\\', '/', $file ); // For Win32, occasional problems deleting files otherwise.
if ( 'f' === $type || $this->is_file( $file ) ) {
return @unlink( $file );
}
if ( ! $recursive && $this->is_dir( $file ) ) {
return @rmdir( $file );
}
// At this point it's a folder, and we're in recursive mode.
$file = trailingslashit( $file );
$filelist = $this->dirlist( $file, true );
$retval = true;
if ( is_array( $filelist ) ) {
foreach ( $filelist as $filename => $fileinfo ) {
if ( ! $this->delete( $file . $filename, $recursive, $fileinfo['type'] ) ) {
$retval = false;
}
}
}
if ( file_exists( $file ) && ! @rmdir( $file ) ) {
$retval = false;
}
return $retval;
}
/**
* Checks if a file or directory exists.
*
* @since 2.5.0
*
* @param string $path Path to file or directory.
* @return bool Whether $path exists or not.
*/
public function exists( $path ) {
return @file_exists( $path );
}
/**
* Checks if resource is a file.
*
* @since 2.5.0
*
* @param string $file File path.
* @return bool Whether $file is a file.
*/
public function is_file( $file ) {
return @is_file( $file );
}
/**
* Checks if resource is a directory.
*
* @since 2.5.0
*
* @param string $path Directory path.
* @return bool Whether $path is a directory.
*/
public function is_dir( $path ) {
return @is_dir( $path );
}
/**
* Checks if a file is readable.
*
* @since 2.5.0
*
* @param string $file Path to file.
* @return bool Whether $file is readable.
*/
public function is_readable( $file ) {
return @is_readable( $file );
}
/**
* Checks if a file or directory is writable.
*
* @since 2.5.0
*
* @param string $path Path to file or directory.
* @return bool Whether $path is writable.
*/
public function is_writable( $path ) {
return @is_writable( $path );
}
/**
* Gets the file's last access time.
*
* @since 2.5.0
*
* @param string $file Path to file.
* @return int|false Unix timestamp representing last access time, false on failure.
*/
public function atime( $file ) {
return @fileatime( $file );
}
/**
* Gets the file modification time.
*
* @since 2.5.0
*
* @param string $file Path to file.
* @return int|false Unix timestamp representing modification time, false on failure.
*/
public function mtime( $file ) {
return @filemtime( $file );
}
/**
* Gets the file size (in bytes).
*
* @since 2.5.0
*
* @param string $file Path to file.
* @return int|false Size of the file in bytes on success, false on failure.
*/
public function size( $file ) {
return @filesize( $file );
}
/**
* Sets the access and modification times of a file.
*
* Note: If $file doesn't exist, it will be created.
*
* @since 2.5.0
*
* @param string $file Path to file.
* @param int $time Optional. Modified time to set for file.
* Default 0.
* @param int $atime Optional. Access time to set for file.
* Default 0.
* @return bool True on success, false on failure.
*/
public function touch( $file, $time = 0, $atime = 0 ) {
if ( 0 === $time ) {
$time = time();
}
if ( 0 === $atime ) {
$atime = time();
}
return touch( $file, $time, $atime );
}
/**
* Creates a directory.
*
* @since 2.5.0
*
* @param string $path Path for new directory.
* @param int|false $chmod Optional. The permissions as octal number (or false to skip chmod).
* Default false.
* @param string|int|false $chown Optional. A user name or number (or false to skip chown).
* Default false.
* @param string|int|false $chgrp Optional. A group name or number (or false to skip chgrp).
* Default false.
* @return bool True on success, false on failure.
*/
public function mkdir( $path, $chmod = false, $chown = false, $chgrp = false ) {
// Safe mode fails with a trailing slash under certain PHP versions.
$path = untrailingslashit( $path );
if ( empty( $path ) ) {
return false;
}
if ( ! $chmod ) {
$chmod = FS_CHMOD_DIR;
}
if ( ! @mkdir( $path ) ) {
return false;
}
$this->chmod( $path, $chmod );
if ( $chown ) {
$this->chown( $path, $chown );
}
if ( $chgrp ) {
$this->chgrp( $path, $chgrp );
}
return true;
}
/**
* Deletes a directory.
*
* @since 2.5.0
*
* @param string $path Path to directory.
* @param bool $recursive Optional. Whether to recursively remove files/directories.
* Default false.
* @return bool True on success, false on failure.
*/
public function rmdir( $path, $recursive = false ) {
return $this->delete( $path, $recursive );
}
/**
* Gets details for files in a directory or a specific file.
*
* @since 2.5.0
*
* @param string $path Path to directory or file.
* @param bool $include_hidden Optional. Whether to include details of hidden ("." prefixed) files.
* Default true.
* @param bool $recursive Optional. Whether to recursively include file details in nested directories.
* Default false.
* @return array|false {
* Array of arrays containing file information. False if unable to list directory contents.
*
* @type array ...$0 {
* Array of file information. Note that some elements may not be available on all filesystems.
*
* @type string $name Name of the file or directory.
* @type string $perms *nix representation of permissions.
* @type string $permsn Octal representation of permissions.
* @type false $number File number. Always false in this context.
* @type string|false $owner Owner name or ID, or false if not available.
* @type string|false $group File permissions group, or false if not available.
* @type int|string|false $size Size of file in bytes. May be a numeric string.
* False if not available.
* @type int|string|false $lastmodunix Last modified unix timestamp. May be a numeric string.
* False if not available.
* @type string|false $lastmod Last modified month (3 letters) and day (without leading 0), or
* false if not available.
* @type string|false $time Last modified time, or false if not available.
* @type string $type Type of resource. 'f' for file, 'd' for directory, 'l' for link.
* @type array|false $files If a directory and `$recursive` is true, contains another array of
* files. False if unable to list directory contents.
* }
* }
*/
public function dirlist( $path, $include_hidden = true, $recursive = false ) {
if ( $this->is_file( $path ) ) {
$limit_file = basename( $path );
$path = dirname( $path );
} else {
$limit_file = false;
}
if ( ! $this->is_dir( $path ) || ! $this->is_readable( $path ) ) {
return false;
}
$dir = dir( $path );
if ( ! $dir ) {
return false;
}
$path = trailingslashit( $path );
$ret = array();
while ( false !== ( $entry = $dir->read() ) ) {
$struc = array();
$struc['name'] = $entry;
if ( '.' === $struc['name'] || '..' === $struc['name'] ) {
continue;
}
if ( ! $include_hidden && '.' === $struc['name'][0] ) {
continue;
}
if ( $limit_file && $struc['name'] !== $limit_file ) {
continue;
}
$struc['perms'] = $this->gethchmod( $path . $entry );
$struc['permsn'] = $this->getnumchmodfromh( $struc['perms'] );
$struc['number'] = false;
$struc['owner'] = $this->owner( $path . $entry );
$struc['group'] = $this->group( $path . $entry );
$struc['size'] = $this->size( $path . $entry );
$struc['lastmodunix'] = $this->mtime( $path . $entry );
$struc['lastmod'] = gmdate( 'M j', $struc['lastmodunix'] );
$struc['time'] = gmdate( 'h:i:s', $struc['lastmodunix'] );
$struc['type'] = $this->is_dir( $path . $entry ) ? 'd' : 'f';
if ( 'd' === $struc['type'] ) {
if ( $recursive ) {
$struc['files'] = $this->dirlist( $path . $struc['name'], $include_hidden, $recursive );
} else {
$struc['files'] = array();
}
}
$ret[ $struc['name'] ] = $struc;
}
$dir->close();
unset( $dir );
return $ret;
}
}

View File

@ -0,0 +1,830 @@
<?php
/**
* WordPress FTP Filesystem.
*
* @package WordPress
* @subpackage Filesystem
*/
/**
* WordPress Filesystem Class for implementing FTP.
*
* @since 2.5.0
*
* @see WP_Filesystem_Base
*/
class WP_Filesystem_FTPext extends WP_Filesystem_Base {
/**
* @since 2.5.0
* @var resource
*/
public $link;
/**
* Constructor.
*
* @since 2.5.0
*
* @param array $opt
*/
public function __construct( $opt = '' ) {
$this->method = 'ftpext';
$this->errors = new WP_Error();
// Check if possible to use ftp functions.
if ( ! extension_loaded( 'ftp' ) ) {
$this->errors->add( 'no_ftp_ext', __( 'The ftp PHP extension is not available' ) );
return;
}
// This class uses the timeout on a per-connection basis, others use it on a per-action basis.
if ( ! defined( 'FS_TIMEOUT' ) ) {
define( 'FS_TIMEOUT', 4 * MINUTE_IN_SECONDS );
}
if ( empty( $opt['port'] ) ) {
$this->options['port'] = 21;
} else {
$this->options['port'] = $opt['port'];
}
if ( empty( $opt['hostname'] ) ) {
$this->errors->add( 'empty_hostname', __( 'FTP hostname is required' ) );
} else {
$this->options['hostname'] = $opt['hostname'];
}
// Check if the options provided are OK.
if ( empty( $opt['username'] ) ) {
$this->errors->add( 'empty_username', __( 'FTP username is required' ) );
} else {
$this->options['username'] = $opt['username'];
}
if ( empty( $opt['password'] ) ) {
$this->errors->add( 'empty_password', __( 'FTP password is required' ) );
} else {
$this->options['password'] = $opt['password'];
}
$this->options['ssl'] = false;
if ( isset( $opt['connection_type'] ) && 'ftps' === $opt['connection_type'] ) {
$this->options['ssl'] = true;
}
}
/**
* Connects filesystem.
*
* @since 2.5.0
*
* @return bool True on success, false on failure.
*/
public function connect() {
if ( isset( $this->options['ssl'] ) && $this->options['ssl'] && function_exists( 'ftp_ssl_connect' ) ) {
$this->link = @ftp_ssl_connect( $this->options['hostname'], $this->options['port'], FS_CONNECT_TIMEOUT );
} else {
$this->link = @ftp_connect( $this->options['hostname'], $this->options['port'], FS_CONNECT_TIMEOUT );
}
if ( ! $this->link ) {
$this->errors->add(
'connect',
sprintf(
/* translators: %s: hostname:port */
__( 'Failed to connect to FTP Server %s' ),
$this->options['hostname'] . ':' . $this->options['port']
)
);
return false;
}
if ( ! @ftp_login( $this->link, $this->options['username'], $this->options['password'] ) ) {
$this->errors->add(
'auth',
sprintf(
/* translators: %s: Username. */
__( 'Username/Password incorrect for %s' ),
$this->options['username']
)
);
return false;
}
// Set the connection to use Passive FTP.
ftp_pasv( $this->link, true );
if ( @ftp_get_option( $this->link, FTP_TIMEOUT_SEC ) < FS_TIMEOUT ) {
@ftp_set_option( $this->link, FTP_TIMEOUT_SEC, FS_TIMEOUT );
}
return true;
}
/**
* Reads entire file into a string.
*
* @since 2.5.0
*
* @param string $file Name of the file to read.
* @return string|false Read data on success, false if no temporary file could be opened,
* or if the file couldn't be retrieved.
*/
public function get_contents( $file ) {
$tempfile = wp_tempnam( $file );
$temphandle = fopen( $tempfile, 'w+' );
if ( ! $temphandle ) {
unlink( $tempfile );
return false;
}
if ( ! ftp_fget( $this->link, $temphandle, $file, FTP_BINARY ) ) {
fclose( $temphandle );
unlink( $tempfile );
return false;
}
fseek( $temphandle, 0 ); // Skip back to the start of the file being written to.
$contents = '';
while ( ! feof( $temphandle ) ) {
$contents .= fread( $temphandle, 8 * KB_IN_BYTES );
}
fclose( $temphandle );
unlink( $tempfile );
return $contents;
}
/**
* Reads entire file into an array.
*
* @since 2.5.0
*
* @param string $file Path to the file.
* @return array|false File contents in an array on success, false on failure.
*/
public function get_contents_array( $file ) {
return explode( "\n", $this->get_contents( $file ) );
}
/**
* Writes a string to a file.
*
* @since 2.5.0
*
* @param string $file Remote path to the file where to write the data.
* @param string $contents The data to write.
* @param int|false $mode Optional. The file permissions as octal number, usually 0644.
* Default false.
* @return bool True on success, false on failure.
*/
public function put_contents( $file, $contents, $mode = false ) {
$tempfile = wp_tempnam( $file );
$temphandle = fopen( $tempfile, 'wb+' );
if ( ! $temphandle ) {
unlink( $tempfile );
return false;
}
mbstring_binary_safe_encoding();
$data_length = strlen( $contents );
$bytes_written = fwrite( $temphandle, $contents );
reset_mbstring_encoding();
if ( $data_length !== $bytes_written ) {
fclose( $temphandle );
unlink( $tempfile );
return false;
}
fseek( $temphandle, 0 ); // Skip back to the start of the file being written to.
$ret = ftp_fput( $this->link, $file, $temphandle, FTP_BINARY );
fclose( $temphandle );
unlink( $tempfile );
$this->chmod( $file, $mode );
return $ret;
}
/**
* Gets the current working directory.
*
* @since 2.5.0
*
* @return string|false The current working directory on success, false on failure.
*/
public function cwd() {
$cwd = ftp_pwd( $this->link );
if ( $cwd ) {
$cwd = trailingslashit( $cwd );
}
return $cwd;
}
/**
* Changes current directory.
*
* @since 2.5.0
*
* @param string $dir The new current directory.
* @return bool True on success, false on failure.
*/
public function chdir( $dir ) {
return @ftp_chdir( $this->link, $dir );
}
/**
* Changes filesystem permissions.
*
* @since 2.5.0
*
* @param string $file Path to the file.
* @param int|false $mode Optional. The permissions as octal number, usually 0644 for files,
* 0755 for directories. Default false.
* @param bool $recursive Optional. If set to true, changes file permissions recursively.
* Default false.
* @return bool True on success, false on failure.
*/
public function chmod( $file, $mode = false, $recursive = false ) {
if ( ! $mode ) {
if ( $this->is_file( $file ) ) {
$mode = FS_CHMOD_FILE;
} elseif ( $this->is_dir( $file ) ) {
$mode = FS_CHMOD_DIR;
} else {
return false;
}
}
// chmod any sub-objects if recursive.
if ( $recursive && $this->is_dir( $file ) ) {
$filelist = $this->dirlist( $file );
foreach ( (array) $filelist as $filename => $filemeta ) {
$this->chmod( $file . '/' . $filename, $mode, $recursive );
}
}
// chmod the file or directory.
if ( ! function_exists( 'ftp_chmod' ) ) {
return (bool) ftp_site( $this->link, sprintf( 'CHMOD %o %s', $mode, $file ) );
}
return (bool) ftp_chmod( $this->link, $mode, $file );
}
/**
* Gets the file owner.
*
* @since 2.5.0
*
* @param string $file Path to the file.
* @return string|false Username of the owner on success, false on failure.
*/
public function owner( $file ) {
$dir = $this->dirlist( $file );
return $dir[ $file ]['owner'];
}
/**
* Gets the permissions of the specified file or filepath in their octal format.
*
* @since 2.5.0
*
* @param string $file Path to the file.
* @return string Mode of the file (the last 3 digits).
*/
public function getchmod( $file ) {
$dir = $this->dirlist( $file );
return $dir[ $file ]['permsn'];
}
/**
* Gets the file's group.
*
* @since 2.5.0
*
* @param string $file Path to the file.
* @return string|false The group on success, false on failure.
*/
public function group( $file ) {
$dir = $this->dirlist( $file );
return $dir[ $file ]['group'];
}
/**
* Copies a file.
*
* @since 2.5.0
*
* @param string $source Path to the source file.
* @param string $destination Path to the destination file.
* @param bool $overwrite Optional. Whether to overwrite the destination file if it exists.
* Default false.
* @param int|false $mode Optional. The permissions as octal number, usually 0644 for files,
* 0755 for dirs. Default false.
* @return bool True on success, false on failure.
*/
public function copy( $source, $destination, $overwrite = false, $mode = false ) {
if ( ! $overwrite && $this->exists( $destination ) ) {
return false;
}
$content = $this->get_contents( $source );
if ( false === $content ) {
return false;
}
return $this->put_contents( $destination, $content, $mode );
}
/**
* Moves a file or directory.
*
* After moving files or directories, OPcache will need to be invalidated.
*
* If moving a directory fails, `copy_dir()` can be used for a recursive copy.
*
* Use `move_dir()` for moving directories with OPcache invalidation and a
* fallback to `copy_dir()`.
*
* @since 2.5.0
*
* @param string $source Path to the source file or directory.
* @param string $destination Path to the destination file or directory.
* @param bool $overwrite Optional. Whether to overwrite the destination if it exists.
* Default false.
* @return bool True on success, false on failure.
*/
public function move( $source, $destination, $overwrite = false ) {
return ftp_rename( $this->link, $source, $destination );
}
/**
* Deletes a file or directory.
*
* @since 2.5.0
*
* @param string $file Path to the file or directory.
* @param bool $recursive Optional. If set to true, deletes files and folders recursively.
* Default false.
* @param string|false $type Type of resource. 'f' for file, 'd' for directory.
* Default false.
* @return bool True on success, false on failure.
*/
public function delete( $file, $recursive = false, $type = false ) {
if ( empty( $file ) ) {
return false;
}
if ( 'f' === $type || $this->is_file( $file ) ) {
return ftp_delete( $this->link, $file );
}
if ( ! $recursive ) {
return ftp_rmdir( $this->link, $file );
}
$filelist = $this->dirlist( trailingslashit( $file ) );
if ( ! empty( $filelist ) ) {
foreach ( $filelist as $delete_file ) {
$this->delete( trailingslashit( $file ) . $delete_file['name'], $recursive, $delete_file['type'] );
}
}
return ftp_rmdir( $this->link, $file );
}
/**
* Checks if a file or directory exists.
*
* @since 2.5.0
* @since 6.3.0 Returns false for an empty path.
*
* @param string $path Path to file or directory.
* @return bool Whether $path exists or not.
*/
public function exists( $path ) {
/*
* Check for empty path. If ftp_nlist() receives an empty path,
* it checks the current working directory and may return true.
*
* See https://core.trac.wordpress.org/ticket/33058.
*/
if ( '' === $path ) {
return false;
}
$list = ftp_nlist( $this->link, $path );
if ( empty( $list ) && $this->is_dir( $path ) ) {
return true; // File is an empty directory.
}
return ! empty( $list ); // Empty list = no file, so invert.
}
/**
* Checks if resource is a file.
*
* @since 2.5.0
*
* @param string $file File path.
* @return bool Whether $file is a file.
*/
public function is_file( $file ) {
return $this->exists( $file ) && ! $this->is_dir( $file );
}
/**
* Checks if resource is a directory.
*
* @since 2.5.0
*
* @param string $path Directory path.
* @return bool Whether $path is a directory.
*/
public function is_dir( $path ) {
$cwd = $this->cwd();
$result = @ftp_chdir( $this->link, trailingslashit( $path ) );
if ( $result && $path === $this->cwd() || $this->cwd() !== $cwd ) {
@ftp_chdir( $this->link, $cwd );
return true;
}
return false;
}
/**
* Checks if a file is readable.
*
* @since 2.5.0
*
* @param string $file Path to file.
* @return bool Whether $file is readable.
*/
public function is_readable( $file ) {
return true;
}
/**
* Checks if a file or directory is writable.
*
* @since 2.5.0
*
* @param string $path Path to file or directory.
* @return bool Whether $path is writable.
*/
public function is_writable( $path ) {
return true;
}
/**
* Gets the file's last access time.
*
* @since 2.5.0
*
* @param string $file Path to file.
* @return int|false Unix timestamp representing last access time, false on failure.
*/
public function atime( $file ) {
return false;
}
/**
* Gets the file modification time.
*
* @since 2.5.0
*
* @param string $file Path to file.
* @return int|false Unix timestamp representing modification time, false on failure.
*/
public function mtime( $file ) {
return ftp_mdtm( $this->link, $file );
}
/**
* Gets the file size (in bytes).
*
* @since 2.5.0
*
* @param string $file Path to file.
* @return int|false Size of the file in bytes on success, false on failure.
*/
public function size( $file ) {
$size = ftp_size( $this->link, $file );
return ( $size > -1 ) ? $size : false;
}
/**
* Sets the access and modification times of a file.
*
* Note: If $file doesn't exist, it will be created.
*
* @since 2.5.0
*
* @param string $file Path to file.
* @param int $time Optional. Modified time to set for file.
* Default 0.
* @param int $atime Optional. Access time to set for file.
* Default 0.
* @return bool True on success, false on failure.
*/
public function touch( $file, $time = 0, $atime = 0 ) {
return false;
}
/**
* Creates a directory.
*
* @since 2.5.0
*
* @param string $path Path for new directory.
* @param int|false $chmod Optional. The permissions as octal number (or false to skip chmod).
* Default false.
* @param string|int|false $chown Optional. A user name or number (or false to skip chown).
* Default false.
* @param string|int|false $chgrp Optional. A group name or number (or false to skip chgrp).
* Default false.
* @return bool True on success, false on failure.
*/
public function mkdir( $path, $chmod = false, $chown = false, $chgrp = false ) {
$path = untrailingslashit( $path );
if ( empty( $path ) ) {
return false;
}
if ( ! ftp_mkdir( $this->link, $path ) ) {
return false;
}
$this->chmod( $path, $chmod );
return true;
}
/**
* Deletes a directory.
*
* @since 2.5.0
*
* @param string $path Path to directory.
* @param bool $recursive Optional. Whether to recursively remove files/directories.
* Default false.
* @return bool True on success, false on failure.
*/
public function rmdir( $path, $recursive = false ) {
return $this->delete( $path, $recursive );
}
/**
* @param string $line
* @return array {
* Array of file information.
*
* @type string $name Name of the file or directory.
* @type string $perms *nix representation of permissions.
* @type string $permsn Octal representation of permissions.
* @type string|false $number File number as a string, or false if not available.
* @type string|false $owner Owner name or ID, or false if not available.
* @type string|false $group File permissions group, or false if not available.
* @type string|false $size Size of file in bytes as a string, or false if not available.
* @type string|false $lastmodunix Last modified unix timestamp as a string, or false if not available.
* @type string|false $lastmod Last modified month (3 letters) and day (without leading 0), or
* false if not available.
* @type string|false $time Last modified time, or false if not available.
* @type string $type Type of resource. 'f' for file, 'd' for directory, 'l' for link.
* @type array|false $files If a directory and `$recursive` is true, contains another array of files.
* False if unable to list directory contents.
* }
*/
public function parselisting( $line ) {
static $is_windows = null;
if ( is_null( $is_windows ) ) {
$is_windows = stripos( ftp_systype( $this->link ), 'win' ) !== false;
}
if ( $is_windows && preg_match( '/([0-9]{2})-([0-9]{2})-([0-9]{2}) +([0-9]{2}):([0-9]{2})(AM|PM) +([0-9]+|<DIR>) +(.+)/', $line, $lucifer ) ) {
$b = array();
if ( $lucifer[3] < 70 ) {
$lucifer[3] += 2000;
} else {
$lucifer[3] += 1900; // 4-digit year fix.
}
$b['isdir'] = ( '<DIR>' === $lucifer[7] );
if ( $b['isdir'] ) {
$b['type'] = 'd';
} else {
$b['type'] = 'f';
}
$b['size'] = $lucifer[7];
$b['month'] = $lucifer[1];
$b['day'] = $lucifer[2];
$b['year'] = $lucifer[3];
$b['hour'] = $lucifer[4];
$b['minute'] = $lucifer[5];
$b['time'] = mktime( $lucifer[4] + ( strcasecmp( $lucifer[6], 'PM' ) === 0 ? 12 : 0 ), $lucifer[5], 0, $lucifer[1], $lucifer[2], $lucifer[3] );
$b['am/pm'] = $lucifer[6];
$b['name'] = $lucifer[8];
} elseif ( ! $is_windows ) {
$lucifer = preg_split( '/[ ]/', $line, 9, PREG_SPLIT_NO_EMPTY );
if ( $lucifer ) {
// echo $line."\n";
$lcount = count( $lucifer );
if ( $lcount < 8 ) {
return '';
}
$b = array();
$b['isdir'] = 'd' === $lucifer[0][0];
$b['islink'] = 'l' === $lucifer[0][0];
if ( $b['isdir'] ) {
$b['type'] = 'd';
} elseif ( $b['islink'] ) {
$b['type'] = 'l';
} else {
$b['type'] = 'f';
}
$b['perms'] = $lucifer[0];
$b['permsn'] = $this->getnumchmodfromh( $b['perms'] );
$b['number'] = $lucifer[1];
$b['owner'] = $lucifer[2];
$b['group'] = $lucifer[3];
$b['size'] = $lucifer[4];
if ( 8 === $lcount ) {
sscanf( $lucifer[5], '%d-%d-%d', $b['year'], $b['month'], $b['day'] );
sscanf( $lucifer[6], '%d:%d', $b['hour'], $b['minute'] );
$b['time'] = mktime( $b['hour'], $b['minute'], 0, $b['month'], $b['day'], $b['year'] );
$b['name'] = $lucifer[7];
} else {
$b['month'] = $lucifer[5];
$b['day'] = $lucifer[6];
if ( preg_match( '/([0-9]{2}):([0-9]{2})/', $lucifer[7], $l2 ) ) {
$b['year'] = gmdate( 'Y' );
$b['hour'] = $l2[1];
$b['minute'] = $l2[2];
} else {
$b['year'] = $lucifer[7];
$b['hour'] = 0;
$b['minute'] = 0;
}
$b['time'] = strtotime( sprintf( '%d %s %d %02d:%02d', $b['day'], $b['month'], $b['year'], $b['hour'], $b['minute'] ) );
$b['name'] = $lucifer[8];
}
}
}
// Replace symlinks formatted as "source -> target" with just the source name.
if ( isset( $b['islink'] ) && $b['islink'] ) {
$b['name'] = preg_replace( '/(\s*->\s*.*)$/', '', $b['name'] );
}
return $b;
}
/**
* Gets details for files in a directory or a specific file.
*
* @since 2.5.0
*
* @param string $path Path to directory or file.
* @param bool $include_hidden Optional. Whether to include details of hidden ("." prefixed) files.
* Default true.
* @param bool $recursive Optional. Whether to recursively include file details in nested directories.
* Default false.
* @return array|false {
* Array of arrays containing file information. False if unable to list directory contents.
*
* @type array ...$0 {
* Array of file information. Note that some elements may not be available on all filesystems.
*
* @type string $name Name of the file or directory.
* @type string $perms *nix representation of permissions.
* @type string $permsn Octal representation of permissions.
* @type int|string|false $number File number. May be a numeric string. False if not available.
* @type string|false $owner Owner name or ID, or false if not available.
* @type string|false $group File permissions group, or false if not available.
* @type int|string|false $size Size of file in bytes. May be a numeric string.
* False if not available.
* @type int|string|false $lastmodunix Last modified unix timestamp. May be a numeric string.
* False if not available.
* @type string|false $lastmod Last modified month (3 letters) and day (without leading 0), or
* false if not available.
* @type string|false $time Last modified time, or false if not available.
* @type string $type Type of resource. 'f' for file, 'd' for directory, 'l' for link.
* @type array|false $files If a directory and `$recursive` is true, contains another array of
* files. False if unable to list directory contents.
* }
* }
*/
public function dirlist( $path = '.', $include_hidden = true, $recursive = false ) {
if ( $this->is_file( $path ) ) {
$limit_file = basename( $path );
$path = dirname( $path ) . '/';
} else {
$limit_file = false;
}
$pwd = ftp_pwd( $this->link );
if ( ! @ftp_chdir( $this->link, $path ) ) { // Can't change to folder = folder doesn't exist.
return false;
}
$list = ftp_rawlist( $this->link, '-a', false );
@ftp_chdir( $this->link, $pwd );
if ( empty( $list ) ) { // Empty array = non-existent folder (real folder will show . at least).
return false;
}
$dirlist = array();
foreach ( $list as $k => $v ) {
$entry = $this->parselisting( $v );
if ( empty( $entry ) ) {
continue;
}
if ( '.' === $entry['name'] || '..' === $entry['name'] ) {
continue;
}
if ( ! $include_hidden && '.' === $entry['name'][0] ) {
continue;
}
if ( $limit_file && $entry['name'] !== $limit_file ) {
continue;
}
$dirlist[ $entry['name'] ] = $entry;
}
$path = trailingslashit( $path );
$ret = array();
foreach ( (array) $dirlist as $struc ) {
if ( 'd' === $struc['type'] ) {
if ( $recursive ) {
$struc['files'] = $this->dirlist( $path . $struc['name'], $include_hidden, $recursive );
} else {
$struc['files'] = array();
}
}
$ret[ $struc['name'] ] = $struc;
}
return $ret;
}
/**
* Destructor.
*
* @since 2.5.0
*/
public function __destruct() {
if ( $this->link ) {
ftp_close( $this->link );
}
}
}

View File

@ -0,0 +1,718 @@
<?php
/**
* WordPress FTP Sockets Filesystem.
*
* @package WordPress
* @subpackage Filesystem
*/
/**
* WordPress Filesystem Class for implementing FTP Sockets.
*
* @since 2.5.0
*
* @see WP_Filesystem_Base
*/
class WP_Filesystem_ftpsockets extends WP_Filesystem_Base {
/**
* @since 2.5.0
* @var ftp
*/
public $ftp;
/**
* Constructor.
*
* @since 2.5.0
*
* @param array $opt
*/
public function __construct( $opt = '' ) {
$this->method = 'ftpsockets';
$this->errors = new WP_Error();
// Check if possible to use ftp functions.
if ( ! require_once ABSPATH . 'wp-admin/includes/class-ftp.php' ) {
return;
}
$this->ftp = new ftp();
if ( empty( $opt['port'] ) ) {
$this->options['port'] = 21;
} else {
$this->options['port'] = (int) $opt['port'];
}
if ( empty( $opt['hostname'] ) ) {
$this->errors->add( 'empty_hostname', __( 'FTP hostname is required' ) );
} else {
$this->options['hostname'] = $opt['hostname'];
}
// Check if the options provided are OK.
if ( empty( $opt['username'] ) ) {
$this->errors->add( 'empty_username', __( 'FTP username is required' ) );
} else {
$this->options['username'] = $opt['username'];
}
if ( empty( $opt['password'] ) ) {
$this->errors->add( 'empty_password', __( 'FTP password is required' ) );
} else {
$this->options['password'] = $opt['password'];
}
}
/**
* Connects filesystem.
*
* @since 2.5.0
*
* @return bool True on success, false on failure.
*/
public function connect() {
if ( ! $this->ftp ) {
return false;
}
$this->ftp->setTimeout( FS_CONNECT_TIMEOUT );
if ( ! $this->ftp->SetServer( $this->options['hostname'], $this->options['port'] ) ) {
$this->errors->add(
'connect',
sprintf(
/* translators: %s: hostname:port */
__( 'Failed to connect to FTP Server %s' ),
$this->options['hostname'] . ':' . $this->options['port']
)
);
return false;
}
if ( ! $this->ftp->connect() ) {
$this->errors->add(
'connect',
sprintf(
/* translators: %s: hostname:port */
__( 'Failed to connect to FTP Server %s' ),
$this->options['hostname'] . ':' . $this->options['port']
)
);
return false;
}
if ( ! $this->ftp->login( $this->options['username'], $this->options['password'] ) ) {
$this->errors->add(
'auth',
sprintf(
/* translators: %s: Username. */
__( 'Username/Password incorrect for %s' ),
$this->options['username']
)
);
return false;
}
$this->ftp->SetType( FTP_BINARY );
$this->ftp->Passive( true );
$this->ftp->setTimeout( FS_TIMEOUT );
return true;
}
/**
* Reads entire file into a string.
*
* @since 2.5.0
*
* @param string $file Name of the file to read.
* @return string|false Read data on success, false if no temporary file could be opened,
* or if the file couldn't be retrieved.
*/
public function get_contents( $file ) {
if ( ! $this->exists( $file ) ) {
return false;
}
$tempfile = wp_tempnam( $file );
$temphandle = fopen( $tempfile, 'w+' );
if ( ! $temphandle ) {
unlink( $tempfile );
return false;
}
mbstring_binary_safe_encoding();
if ( ! $this->ftp->fget( $temphandle, $file ) ) {
fclose( $temphandle );
unlink( $tempfile );
reset_mbstring_encoding();
return ''; // Blank document. File does exist, it's just blank.
}
reset_mbstring_encoding();
fseek( $temphandle, 0 ); // Skip back to the start of the file being written to.
$contents = '';
while ( ! feof( $temphandle ) ) {
$contents .= fread( $temphandle, 8 * KB_IN_BYTES );
}
fclose( $temphandle );
unlink( $tempfile );
return $contents;
}
/**
* Reads entire file into an array.
*
* @since 2.5.0
*
* @param string $file Path to the file.
* @return array|false File contents in an array on success, false on failure.
*/
public function get_contents_array( $file ) {
return explode( "\n", $this->get_contents( $file ) );
}
/**
* Writes a string to a file.
*
* @since 2.5.0
*
* @param string $file Remote path to the file where to write the data.
* @param string $contents The data to write.
* @param int|false $mode Optional. The file permissions as octal number, usually 0644.
* Default false.
* @return bool True on success, false on failure.
*/
public function put_contents( $file, $contents, $mode = false ) {
$tempfile = wp_tempnam( $file );
$temphandle = @fopen( $tempfile, 'w+' );
if ( ! $temphandle ) {
unlink( $tempfile );
return false;
}
// The FTP class uses string functions internally during file download/upload.
mbstring_binary_safe_encoding();
$bytes_written = fwrite( $temphandle, $contents );
if ( false === $bytes_written || strlen( $contents ) !== $bytes_written ) {
fclose( $temphandle );
unlink( $tempfile );
reset_mbstring_encoding();
return false;
}
fseek( $temphandle, 0 ); // Skip back to the start of the file being written to.
$ret = $this->ftp->fput( $file, $temphandle );
reset_mbstring_encoding();
fclose( $temphandle );
unlink( $tempfile );
$this->chmod( $file, $mode );
return $ret;
}
/**
* Gets the current working directory.
*
* @since 2.5.0
*
* @return string|false The current working directory on success, false on failure.
*/
public function cwd() {
$cwd = $this->ftp->pwd();
if ( $cwd ) {
$cwd = trailingslashit( $cwd );
}
return $cwd;
}
/**
* Changes current directory.
*
* @since 2.5.0
*
* @param string $dir The new current directory.
* @return bool True on success, false on failure.
*/
public function chdir( $dir ) {
return $this->ftp->chdir( $dir );
}
/**
* Changes filesystem permissions.
*
* @since 2.5.0
*
* @param string $file Path to the file.
* @param int|false $mode Optional. The permissions as octal number, usually 0644 for files,
* 0755 for directories. Default false.
* @param bool $recursive Optional. If set to true, changes file permissions recursively.
* Default false.
* @return bool True on success, false on failure.
*/
public function chmod( $file, $mode = false, $recursive = false ) {
if ( ! $mode ) {
if ( $this->is_file( $file ) ) {
$mode = FS_CHMOD_FILE;
} elseif ( $this->is_dir( $file ) ) {
$mode = FS_CHMOD_DIR;
} else {
return false;
}
}
// chmod any sub-objects if recursive.
if ( $recursive && $this->is_dir( $file ) ) {
$filelist = $this->dirlist( $file );
foreach ( (array) $filelist as $filename => $filemeta ) {
$this->chmod( $file . '/' . $filename, $mode, $recursive );
}
}
// chmod the file or directory.
return $this->ftp->chmod( $file, $mode );
}
/**
* Gets the file owner.
*
* @since 2.5.0
*
* @param string $file Path to the file.
* @return string|false Username of the owner on success, false on failure.
*/
public function owner( $file ) {
$dir = $this->dirlist( $file );
return $dir[ $file ]['owner'];
}
/**
* Gets the permissions of the specified file or filepath in their octal format.
*
* @since 2.5.0
*
* @param string $file Path to the file.
* @return string Mode of the file (the last 3 digits).
*/
public function getchmod( $file ) {
$dir = $this->dirlist( $file );
return $dir[ $file ]['permsn'];
}
/**
* Gets the file's group.
*
* @since 2.5.0
*
* @param string $file Path to the file.
* @return string|false The group on success, false on failure.
*/
public function group( $file ) {
$dir = $this->dirlist( $file );
return $dir[ $file ]['group'];
}
/**
* Copies a file.
*
* @since 2.5.0
*
* @param string $source Path to the source file.
* @param string $destination Path to the destination file.
* @param bool $overwrite Optional. Whether to overwrite the destination file if it exists.
* Default false.
* @param int|false $mode Optional. The permissions as octal number, usually 0644 for files,
* 0755 for dirs. Default false.
* @return bool True on success, false on failure.
*/
public function copy( $source, $destination, $overwrite = false, $mode = false ) {
if ( ! $overwrite && $this->exists( $destination ) ) {
return false;
}
$content = $this->get_contents( $source );
if ( false === $content ) {
return false;
}
return $this->put_contents( $destination, $content, $mode );
}
/**
* Moves a file or directory.
*
* After moving files or directories, OPcache will need to be invalidated.
*
* If moving a directory fails, `copy_dir()` can be used for a recursive copy.
*
* Use `move_dir()` for moving directories with OPcache invalidation and a
* fallback to `copy_dir()`.
*
* @since 2.5.0
*
* @param string $source Path to the source file or directory.
* @param string $destination Path to the destination file or directory.
* @param bool $overwrite Optional. Whether to overwrite the destination if it exists.
* Default false.
* @return bool True on success, false on failure.
*/
public function move( $source, $destination, $overwrite = false ) {
return $this->ftp->rename( $source, $destination );
}
/**
* Deletes a file or directory.
*
* @since 2.5.0
*
* @param string $file Path to the file or directory.
* @param bool $recursive Optional. If set to true, deletes files and folders recursively.
* Default false.
* @param string|false $type Type of resource. 'f' for file, 'd' for directory.
* Default false.
* @return bool True on success, false on failure.
*/
public function delete( $file, $recursive = false, $type = false ) {
if ( empty( $file ) ) {
return false;
}
if ( 'f' === $type || $this->is_file( $file ) ) {
return $this->ftp->delete( $file );
}
if ( ! $recursive ) {
return $this->ftp->rmdir( $file );
}
return $this->ftp->mdel( $file );
}
/**
* Checks if a file or directory exists.
*
* @since 2.5.0
* @since 6.3.0 Returns false for an empty path.
*
* @param string $path Path to file or directory.
* @return bool Whether $path exists or not.
*/
public function exists( $path ) {
/*
* Check for empty path. If ftp::nlist() receives an empty path,
* it checks the current working directory and may return true.
*
* See https://core.trac.wordpress.org/ticket/33058.
*/
if ( '' === $path ) {
return false;
}
$list = $this->ftp->nlist( $path );
if ( empty( $list ) && $this->is_dir( $path ) ) {
return true; // File is an empty directory.
}
return ! empty( $list ); // Empty list = no file, so invert.
// Return $this->ftp->is_exists($file); has issues with ABOR+426 responses on the ncFTPd server.
}
/**
* Checks if resource is a file.
*
* @since 2.5.0
*
* @param string $file File path.
* @return bool Whether $file is a file.
*/
public function is_file( $file ) {
if ( $this->is_dir( $file ) ) {
return false;
}
if ( $this->exists( $file ) ) {
return true;
}
return false;
}
/**
* Checks if resource is a directory.
*
* @since 2.5.0
*
* @param string $path Directory path.
* @return bool Whether $path is a directory.
*/
public function is_dir( $path ) {
$cwd = $this->cwd();
if ( $this->chdir( $path ) ) {
$this->chdir( $cwd );
return true;
}
return false;
}
/**
* Checks if a file is readable.
*
* @since 2.5.0
*
* @param string $file Path to file.
* @return bool Whether $file is readable.
*/
public function is_readable( $file ) {
return true;
}
/**
* Checks if a file or directory is writable.
*
* @since 2.5.0
*
* @param string $path Path to file or directory.
* @return bool Whether $path is writable.
*/
public function is_writable( $path ) {
return true;
}
/**
* Gets the file's last access time.
*
* @since 2.5.0
*
* @param string $file Path to file.
* @return int|false Unix timestamp representing last access time, false on failure.
*/
public function atime( $file ) {
return false;
}
/**
* Gets the file modification time.
*
* @since 2.5.0
*
* @param string $file Path to file.
* @return int|false Unix timestamp representing modification time, false on failure.
*/
public function mtime( $file ) {
return $this->ftp->mdtm( $file );
}
/**
* Gets the file size (in bytes).
*
* @since 2.5.0
*
* @param string $file Path to file.
* @return int|false Size of the file in bytes on success, false on failure.
*/
public function size( $file ) {
return $this->ftp->filesize( $file );
}
/**
* Sets the access and modification times of a file.
*
* Note: If $file doesn't exist, it will be created.
*
* @since 2.5.0
*
* @param string $file Path to file.
* @param int $time Optional. Modified time to set for file.
* Default 0.
* @param int $atime Optional. Access time to set for file.
* Default 0.
* @return bool True on success, false on failure.
*/
public function touch( $file, $time = 0, $atime = 0 ) {
return false;
}
/**
* Creates a directory.
*
* @since 2.5.0
*
* @param string $path Path for new directory.
* @param int|false $chmod Optional. The permissions as octal number (or false to skip chmod).
* Default false.
* @param string|int|false $chown Optional. A user name or number (or false to skip chown).
* Default false.
* @param string|int|false $chgrp Optional. A group name or number (or false to skip chgrp).
* Default false.
* @return bool True on success, false on failure.
*/
public function mkdir( $path, $chmod = false, $chown = false, $chgrp = false ) {
$path = untrailingslashit( $path );
if ( empty( $path ) ) {
return false;
}
if ( ! $this->ftp->mkdir( $path ) ) {
return false;
}
if ( ! $chmod ) {
$chmod = FS_CHMOD_DIR;
}
$this->chmod( $path, $chmod );
return true;
}
/**
* Deletes a directory.
*
* @since 2.5.0
*
* @param string $path Path to directory.
* @param bool $recursive Optional. Whether to recursively remove files/directories.
* Default false.
* @return bool True on success, false on failure.
*/
public function rmdir( $path, $recursive = false ) {
return $this->delete( $path, $recursive );
}
/**
* Gets details for files in a directory or a specific file.
*
* @since 2.5.0
*
* @param string $path Path to directory or file.
* @param bool $include_hidden Optional. Whether to include details of hidden ("." prefixed) files.
* Default true.
* @param bool $recursive Optional. Whether to recursively include file details in nested directories.
* Default false.
* @return array|false {
* Array of arrays containing file information. False if unable to list directory contents.
*
* @type array ...$0 {
* Array of file information. Note that some elements may not be available on all filesystems.
*
* @type string $name Name of the file or directory.
* @type string $perms *nix representation of permissions.
* @type string $permsn Octal representation of permissions.
* @type int|string|false $number File number. May be a numeric string. False if not available.
* @type string|false $owner Owner name or ID, or false if not available.
* @type string|false $group File permissions group, or false if not available.
* @type int|string|false $size Size of file in bytes. May be a numeric string.
* False if not available.
* @type int|string|false $lastmodunix Last modified unix timestamp. May be a numeric string.
* False if not available.
* @type string|false $lastmod Last modified month (3 letters) and day (without leading 0), or
* false if not available.
* @type string|false $time Last modified time, or false if not available.
* @type string $type Type of resource. 'f' for file, 'd' for directory, 'l' for link.
* @type array|false $files If a directory and `$recursive` is true, contains another array of
* files. False if unable to list directory contents.
* }
* }
*/
public function dirlist( $path = '.', $include_hidden = true, $recursive = false ) {
if ( $this->is_file( $path ) ) {
$limit_file = basename( $path );
$path = dirname( $path ) . '/';
} else {
$limit_file = false;
}
mbstring_binary_safe_encoding();
$list = $this->ftp->dirlist( $path );
if ( empty( $list ) && ! $this->exists( $path ) ) {
reset_mbstring_encoding();
return false;
}
$path = trailingslashit( $path );
$ret = array();
foreach ( $list as $struc ) {
if ( '.' === $struc['name'] || '..' === $struc['name'] ) {
continue;
}
if ( ! $include_hidden && '.' === $struc['name'][0] ) {
continue;
}
if ( $limit_file && $struc['name'] !== $limit_file ) {
continue;
}
if ( 'd' === $struc['type'] ) {
if ( $recursive ) {
$struc['files'] = $this->dirlist( $path . $struc['name'], $include_hidden, $recursive );
} else {
$struc['files'] = array();
}
}
// Replace symlinks formatted as "source -> target" with just the source name.
if ( $struc['islink'] ) {
$struc['name'] = preg_replace( '/(\s*->\s*.*)$/', '', $struc['name'] );
}
// Add the octal representation of the file permissions.
$struc['permsn'] = $this->getnumchmodfromh( $struc['perms'] );
$ret[ $struc['name'] ] = $struc;
}
reset_mbstring_encoding();
return $ret;
}
/**
* Destructor.
*
* @since 2.5.0
*/
public function __destruct() {
$this->ftp->quit();
}
}

View File

@ -0,0 +1,834 @@
<?php
/**
* WordPress Filesystem Class for implementing SSH2
*
* To use this class you must follow these steps for PHP 5.2.6+
*
* {@link http://kevin.vanzonneveld.net/techblog/article/make_ssh_connections_with_php/ - Installation Notes}
*
* Compile libssh2 (Note: Only 0.14 is officially working with PHP 5.2.6+ right now, But many users have found the latest versions work)
*
* cd /usr/src
* wget https://www.libssh2.org/download/libssh2-0.14.tar.gz
* tar -zxvf libssh2-0.14.tar.gz
* cd libssh2-0.14/
* ./configure
* make all install
*
* Note: Do not leave the directory yet!
*
* Enter: pecl install -f ssh2
*
* Copy the ssh.so file it creates to your PHP Module Directory.
* Open up your PHP.INI file and look for where extensions are placed.
* Add in your PHP.ini file: extension=ssh2.so
*
* Restart Apache!
* Check phpinfo() streams to confirm that: ssh2.shell, ssh2.exec, ssh2.tunnel, ssh2.scp, ssh2.sftp exist.
*
* Note: As of WordPress 2.8, this utilizes the PHP5+ function `stream_get_contents()`.
*
* @since 2.7.0
*
* @package WordPress
* @subpackage Filesystem
*/
class WP_Filesystem_SSH2 extends WP_Filesystem_Base {
/**
* @since 2.7.0
* @var resource
*/
public $link = false;
/**
* @since 2.7.0
* @var resource
*/
public $sftp_link;
/**
* @since 2.7.0
* @var bool
*/
public $keys = false;
/**
* Constructor.
*
* @since 2.7.0
*
* @param array $opt
*/
public function __construct( $opt = '' ) {
$this->method = 'ssh2';
$this->errors = new WP_Error();
// Check if possible to use ssh2 functions.
if ( ! extension_loaded( 'ssh2' ) ) {
$this->errors->add( 'no_ssh2_ext', __( 'The ssh2 PHP extension is not available' ) );
return;
}
// Set defaults:
if ( empty( $opt['port'] ) ) {
$this->options['port'] = 22;
} else {
$this->options['port'] = $opt['port'];
}
if ( empty( $opt['hostname'] ) ) {
$this->errors->add( 'empty_hostname', __( 'SSH2 hostname is required' ) );
} else {
$this->options['hostname'] = $opt['hostname'];
}
// Check if the options provided are OK.
if ( ! empty( $opt['public_key'] ) && ! empty( $opt['private_key'] ) ) {
$this->options['public_key'] = $opt['public_key'];
$this->options['private_key'] = $opt['private_key'];
$this->options['hostkey'] = array( 'hostkey' => 'ssh-rsa,ssh-ed25519' );
$this->keys = true;
} elseif ( empty( $opt['username'] ) ) {
$this->errors->add( 'empty_username', __( 'SSH2 username is required' ) );
}
if ( ! empty( $opt['username'] ) ) {
$this->options['username'] = $opt['username'];
}
if ( empty( $opt['password'] ) ) {
// Password can be blank if we are using keys.
if ( ! $this->keys ) {
$this->errors->add( 'empty_password', __( 'SSH2 password is required' ) );
} else {
$this->options['password'] = null;
}
} else {
$this->options['password'] = $opt['password'];
}
}
/**
* Connects filesystem.
*
* @since 2.7.0
*
* @return bool True on success, false on failure.
*/
public function connect() {
if ( ! $this->keys ) {
$this->link = @ssh2_connect( $this->options['hostname'], $this->options['port'] );
} else {
$this->link = @ssh2_connect( $this->options['hostname'], $this->options['port'], $this->options['hostkey'] );
}
if ( ! $this->link ) {
$this->errors->add(
'connect',
sprintf(
/* translators: %s: hostname:port */
__( 'Failed to connect to SSH2 Server %s' ),
$this->options['hostname'] . ':' . $this->options['port']
)
);
return false;
}
if ( ! $this->keys ) {
if ( ! @ssh2_auth_password( $this->link, $this->options['username'], $this->options['password'] ) ) {
$this->errors->add(
'auth',
sprintf(
/* translators: %s: Username. */
__( 'Username/Password incorrect for %s' ),
$this->options['username']
)
);
return false;
}
} else {
if ( ! @ssh2_auth_pubkey_file( $this->link, $this->options['username'], $this->options['public_key'], $this->options['private_key'], $this->options['password'] ) ) {
$this->errors->add(
'auth',
sprintf(
/* translators: %s: Username. */
__( 'Public and Private keys incorrect for %s' ),
$this->options['username']
)
);
return false;
}
}
$this->sftp_link = ssh2_sftp( $this->link );
if ( ! $this->sftp_link ) {
$this->errors->add(
'connect',
sprintf(
/* translators: %s: hostname:port */
__( 'Failed to initialize a SFTP subsystem session with the SSH2 Server %s' ),
$this->options['hostname'] . ':' . $this->options['port']
)
);
return false;
}
return true;
}
/**
* Gets the ssh2.sftp PHP stream wrapper path to open for the given file.
*
* This method also works around a PHP bug where the root directory (/) cannot
* be opened by PHP functions, causing a false failure. In order to work around
* this, the path is converted to /./ which is semantically the same as /
* See https://bugs.php.net/bug.php?id=64169 for more details.
*
* @since 4.4.0
*
* @param string $path The File/Directory path on the remote server to return
* @return string The ssh2.sftp:// wrapped path to use.
*/
public function sftp_path( $path ) {
if ( '/' === $path ) {
$path = '/./';
}
return 'ssh2.sftp://' . $this->sftp_link . '/' . ltrim( $path, '/' );
}
/**
* @since 2.7.0
*
* @param string $command
* @param bool $returnbool
* @return bool|string True on success, false on failure. String if the command was executed, `$returnbool`
* is false (default), and data from the resulting stream was retrieved.
*/
public function run_command( $command, $returnbool = false ) {
if ( ! $this->link ) {
return false;
}
$stream = ssh2_exec( $this->link, $command );
if ( ! $stream ) {
$this->errors->add(
'command',
sprintf(
/* translators: %s: Command. */
__( 'Unable to perform command: %s' ),
$command
)
);
} else {
stream_set_blocking( $stream, true );
stream_set_timeout( $stream, FS_TIMEOUT );
$data = stream_get_contents( $stream );
fclose( $stream );
if ( $returnbool ) {
return ( false === $data ) ? false : '' !== trim( $data );
} else {
return $data;
}
}
return false;
}
/**
* Reads entire file into a string.
*
* @since 2.7.0
*
* @param string $file Name of the file to read.
* @return string|false Read data on success, false if no temporary file could be opened,
* or if the file couldn't be retrieved.
*/
public function get_contents( $file ) {
return file_get_contents( $this->sftp_path( $file ) );
}
/**
* Reads entire file into an array.
*
* @since 2.7.0
*
* @param string $file Path to the file.
* @return array|false File contents in an array on success, false on failure.
*/
public function get_contents_array( $file ) {
return file( $this->sftp_path( $file ) );
}
/**
* Writes a string to a file.
*
* @since 2.7.0
*
* @param string $file Remote path to the file where to write the data.
* @param string $contents The data to write.
* @param int|false $mode Optional. The file permissions as octal number, usually 0644.
* Default false.
* @return bool True on success, false on failure.
*/
public function put_contents( $file, $contents, $mode = false ) {
$ret = file_put_contents( $this->sftp_path( $file ), $contents );
if ( strlen( $contents ) !== $ret ) {
return false;
}
$this->chmod( $file, $mode );
return true;
}
/**
* Gets the current working directory.
*
* @since 2.7.0
*
* @return string|false The current working directory on success, false on failure.
*/
public function cwd() {
$cwd = ssh2_sftp_realpath( $this->sftp_link, '.' );
if ( $cwd ) {
$cwd = trailingslashit( trim( $cwd ) );
}
return $cwd;
}
/**
* Changes current directory.
*
* @since 2.7.0
*
* @param string $dir The new current directory.
* @return bool True on success, false on failure.
*/
public function chdir( $dir ) {
return $this->run_command( 'cd ' . $dir, true );
}
/**
* Changes the file group.
*
* @since 2.7.0
*
* @param string $file Path to the file.
* @param string|int $group A group name or number.
* @param bool $recursive Optional. If set to true, changes file group recursively.
* Default false.
* @return bool True on success, false on failure.
*/
public function chgrp( $file, $group, $recursive = false ) {
if ( ! $this->exists( $file ) ) {
return false;
}
if ( ! $recursive || ! $this->is_dir( $file ) ) {
return $this->run_command( sprintf( 'chgrp %s %s', escapeshellarg( $group ), escapeshellarg( $file ) ), true );
}
return $this->run_command( sprintf( 'chgrp -R %s %s', escapeshellarg( $group ), escapeshellarg( $file ) ), true );
}
/**
* Changes filesystem permissions.
*
* @since 2.7.0
*
* @param string $file Path to the file.
* @param int|false $mode Optional. The permissions as octal number, usually 0644 for files,
* 0755 for directories. Default false.
* @param bool $recursive Optional. If set to true, changes file permissions recursively.
* Default false.
* @return bool True on success, false on failure.
*/
public function chmod( $file, $mode = false, $recursive = false ) {
if ( ! $this->exists( $file ) ) {
return false;
}
if ( ! $mode ) {
if ( $this->is_file( $file ) ) {
$mode = FS_CHMOD_FILE;
} elseif ( $this->is_dir( $file ) ) {
$mode = FS_CHMOD_DIR;
} else {
return false;
}
}
if ( ! $recursive || ! $this->is_dir( $file ) ) {
return $this->run_command( sprintf( 'chmod %o %s', $mode, escapeshellarg( $file ) ), true );
}
return $this->run_command( sprintf( 'chmod -R %o %s', $mode, escapeshellarg( $file ) ), true );
}
/**
* Changes the owner of a file or directory.
*
* @since 2.7.0
*
* @param string $file Path to the file or directory.
* @param string|int $owner A user name or number.
* @param bool $recursive Optional. If set to true, changes file owner recursively.
* Default false.
* @return bool True on success, false on failure.
*/
public function chown( $file, $owner, $recursive = false ) {
if ( ! $this->exists( $file ) ) {
return false;
}
if ( ! $recursive || ! $this->is_dir( $file ) ) {
return $this->run_command( sprintf( 'chown %s %s', escapeshellarg( $owner ), escapeshellarg( $file ) ), true );
}
return $this->run_command( sprintf( 'chown -R %s %s', escapeshellarg( $owner ), escapeshellarg( $file ) ), true );
}
/**
* Gets the file owner.
*
* @since 2.7.0
*
* @param string $file Path to the file.
* @return string|false Username of the owner on success, false on failure.
*/
public function owner( $file ) {
$owneruid = @fileowner( $this->sftp_path( $file ) );
if ( ! $owneruid ) {
return false;
}
if ( ! function_exists( 'posix_getpwuid' ) ) {
return $owneruid;
}
$ownerarray = posix_getpwuid( $owneruid );
if ( ! $ownerarray ) {
return false;
}
return $ownerarray['name'];
}
/**
* Gets the permissions of the specified file or filepath in their octal format.
*
* @since 2.7.0
*
* @param string $file Path to the file.
* @return string Mode of the file (the last 3 digits).
*/
public function getchmod( $file ) {
return substr( decoct( @fileperms( $this->sftp_path( $file ) ) ), -3 );
}
/**
* Gets the file's group.
*
* @since 2.7.0
*
* @param string $file Path to the file.
* @return string|false The group on success, false on failure.
*/
public function group( $file ) {
$gid = @filegroup( $this->sftp_path( $file ) );
if ( ! $gid ) {
return false;
}
if ( ! function_exists( 'posix_getgrgid' ) ) {
return $gid;
}
$grouparray = posix_getgrgid( $gid );
if ( ! $grouparray ) {
return false;
}
return $grouparray['name'];
}
/**
* Copies a file.
*
* @since 2.7.0
*
* @param string $source Path to the source file.
* @param string $destination Path to the destination file.
* @param bool $overwrite Optional. Whether to overwrite the destination file if it exists.
* Default false.
* @param int|false $mode Optional. The permissions as octal number, usually 0644 for files,
* 0755 for dirs. Default false.
* @return bool True on success, false on failure.
*/
public function copy( $source, $destination, $overwrite = false, $mode = false ) {
if ( ! $overwrite && $this->exists( $destination ) ) {
return false;
}
$content = $this->get_contents( $source );
if ( false === $content ) {
return false;
}
return $this->put_contents( $destination, $content, $mode );
}
/**
* Moves a file or directory.
*
* After moving files or directories, OPcache will need to be invalidated.
*
* If moving a directory fails, `copy_dir()` can be used for a recursive copy.
*
* Use `move_dir()` for moving directories with OPcache invalidation and a
* fallback to `copy_dir()`.
*
* @since 2.7.0
*
* @param string $source Path to the source file or directory.
* @param string $destination Path to the destination file or directory.
* @param bool $overwrite Optional. Whether to overwrite the destination if it exists.
* Default false.
* @return bool True on success, false on failure.
*/
public function move( $source, $destination, $overwrite = false ) {
if ( $this->exists( $destination ) ) {
if ( $overwrite ) {
// We need to remove the destination before we can rename the source.
$this->delete( $destination, false, 'f' );
} else {
// If we're not overwriting, the rename will fail, so return early.
return false;
}
}
return ssh2_sftp_rename( $this->sftp_link, $source, $destination );
}
/**
* Deletes a file or directory.
*
* @since 2.7.0
*
* @param string $file Path to the file or directory.
* @param bool $recursive Optional. If set to true, deletes files and folders recursively.
* Default false.
* @param string|false $type Type of resource. 'f' for file, 'd' for directory.
* Default false.
* @return bool True on success, false on failure.
*/
public function delete( $file, $recursive = false, $type = false ) {
if ( 'f' === $type || $this->is_file( $file ) ) {
return ssh2_sftp_unlink( $this->sftp_link, $file );
}
if ( ! $recursive ) {
return ssh2_sftp_rmdir( $this->sftp_link, $file );
}
$filelist = $this->dirlist( $file );
if ( is_array( $filelist ) ) {
foreach ( $filelist as $filename => $fileinfo ) {
$this->delete( $file . '/' . $filename, $recursive, $fileinfo['type'] );
}
}
return ssh2_sftp_rmdir( $this->sftp_link, $file );
}
/**
* Checks if a file or directory exists.
*
* @since 2.7.0
*
* @param string $path Path to file or directory.
* @return bool Whether $path exists or not.
*/
public function exists( $path ) {
return file_exists( $this->sftp_path( $path ) );
}
/**
* Checks if resource is a file.
*
* @since 2.7.0
*
* @param string $file File path.
* @return bool Whether $file is a file.
*/
public function is_file( $file ) {
return is_file( $this->sftp_path( $file ) );
}
/**
* Checks if resource is a directory.
*
* @since 2.7.0
*
* @param string $path Directory path.
* @return bool Whether $path is a directory.
*/
public function is_dir( $path ) {
return is_dir( $this->sftp_path( $path ) );
}
/**
* Checks if a file is readable.
*
* @since 2.7.0
*
* @param string $file Path to file.
* @return bool Whether $file is readable.
*/
public function is_readable( $file ) {
return is_readable( $this->sftp_path( $file ) );
}
/**
* Checks if a file or directory is writable.
*
* @since 2.7.0
*
* @param string $path Path to file or directory.
* @return bool Whether $path is writable.
*/
public function is_writable( $path ) {
// PHP will base its writable checks on system_user === file_owner, not ssh_user === file_owner.
return true;
}
/**
* Gets the file's last access time.
*
* @since 2.7.0
*
* @param string $file Path to file.
* @return int|false Unix timestamp representing last access time, false on failure.
*/
public function atime( $file ) {
return fileatime( $this->sftp_path( $file ) );
}
/**
* Gets the file modification time.
*
* @since 2.7.0
*
* @param string $file Path to file.
* @return int|false Unix timestamp representing modification time, false on failure.
*/
public function mtime( $file ) {
return filemtime( $this->sftp_path( $file ) );
}
/**
* Gets the file size (in bytes).
*
* @since 2.7.0
*
* @param string $file Path to file.
* @return int|false Size of the file in bytes on success, false on failure.
*/
public function size( $file ) {
return filesize( $this->sftp_path( $file ) );
}
/**
* Sets the access and modification times of a file.
*
* Note: Not implemented.
*
* @since 2.7.0
*
* @param string $file Path to file.
* @param int $time Optional. Modified time to set for file.
* Default 0.
* @param int $atime Optional. Access time to set for file.
* Default 0.
*/
public function touch( $file, $time = 0, $atime = 0 ) {
// Not implemented.
}
/**
* Creates a directory.
*
* @since 2.7.0
*
* @param string $path Path for new directory.
* @param int|false $chmod Optional. The permissions as octal number (or false to skip chmod).
* Default false.
* @param string|int|false $chown Optional. A user name or number (or false to skip chown).
* Default false.
* @param string|int|false $chgrp Optional. A group name or number (or false to skip chgrp).
* Default false.
* @return bool True on success, false on failure.
*/
public function mkdir( $path, $chmod = false, $chown = false, $chgrp = false ) {
$path = untrailingslashit( $path );
if ( empty( $path ) ) {
return false;
}
if ( ! $chmod ) {
$chmod = FS_CHMOD_DIR;
}
if ( ! ssh2_sftp_mkdir( $this->sftp_link, $path, $chmod, true ) ) {
return false;
}
// Set directory permissions.
ssh2_sftp_chmod( $this->sftp_link, $path, $chmod );
if ( $chown ) {
$this->chown( $path, $chown );
}
if ( $chgrp ) {
$this->chgrp( $path, $chgrp );
}
return true;
}
/**
* Deletes a directory.
*
* @since 2.7.0
*
* @param string $path Path to directory.
* @param bool $recursive Optional. Whether to recursively remove files/directories.
* Default false.
* @return bool True on success, false on failure.
*/
public function rmdir( $path, $recursive = false ) {
return $this->delete( $path, $recursive );
}
/**
* Gets details for files in a directory or a specific file.
*
* @since 2.7.0
*
* @param string $path Path to directory or file.
* @param bool $include_hidden Optional. Whether to include details of hidden ("." prefixed) files.
* Default true.
* @param bool $recursive Optional. Whether to recursively include file details in nested directories.
* Default false.
* @return array|false {
* Array of arrays containing file information. False if unable to list directory contents.
*
* @type array ...$0 {
* Array of file information. Note that some elements may not be available on all filesystems.
*
* @type string $name Name of the file or directory.
* @type string $perms *nix representation of permissions.
* @type string $permsn Octal representation of permissions.
* @type false $number File number. Always false in this context.
* @type string|false $owner Owner name or ID, or false if not available.
* @type string|false $group File permissions group, or false if not available.
* @type int|string|false $size Size of file in bytes. May be a numeric string.
* False if not available.
* @type int|string|false $lastmodunix Last modified unix timestamp. May be a numeric string.
* False if not available.
* @type string|false $lastmod Last modified month (3 letters) and day (without leading 0), or
* false if not available.
* @type string|false $time Last modified time, or false if not available.
* @type string $type Type of resource. 'f' for file, 'd' for directory, 'l' for link.
* @type array|false $files If a directory and `$recursive` is true, contains another array of
* files. False if unable to list directory contents.
* }
* }
*/
public function dirlist( $path, $include_hidden = true, $recursive = false ) {
if ( $this->is_file( $path ) ) {
$limit_file = basename( $path );
$path = dirname( $path );
} else {
$limit_file = false;
}
if ( ! $this->is_dir( $path ) || ! $this->is_readable( $path ) ) {
return false;
}
$ret = array();
$dir = dir( $this->sftp_path( $path ) );
if ( ! $dir ) {
return false;
}
$path = trailingslashit( $path );
while ( false !== ( $entry = $dir->read() ) ) {
$struc = array();
$struc['name'] = $entry;
if ( '.' === $struc['name'] || '..' === $struc['name'] ) {
continue; // Do not care about these folders.
}
if ( ! $include_hidden && '.' === $struc['name'][0] ) {
continue;
}
if ( $limit_file && $struc['name'] !== $limit_file ) {
continue;
}
$struc['perms'] = $this->gethchmod( $path . $entry );
$struc['permsn'] = $this->getnumchmodfromh( $struc['perms'] );
$struc['number'] = false;
$struc['owner'] = $this->owner( $path . $entry );
$struc['group'] = $this->group( $path . $entry );
$struc['size'] = $this->size( $path . $entry );
$struc['lastmodunix'] = $this->mtime( $path . $entry );
$struc['lastmod'] = gmdate( 'M j', $struc['lastmodunix'] );
$struc['time'] = gmdate( 'h:i:s', $struc['lastmodunix'] );
$struc['type'] = $this->is_dir( $path . $entry ) ? 'd' : 'f';
if ( 'd' === $struc['type'] ) {
if ( $recursive ) {
$struc['files'] = $this->dirlist( $path . $struc['name'], $include_hidden, $recursive );
} else {
$struc['files'] = array();
}
}
$ret[ $struc['name'] ] = $struc;
}
$dir->close();
unset( $dir );
return $ret;
}
}

View File

@ -0,0 +1,327 @@
<?php
/**
* WP_Importer base class
*/
#[AllowDynamicProperties]
class WP_Importer {
/**
* Class Constructor
*/
public function __construct() {}
/**
* Returns array with imported permalinks from WordPress database.
*
* @global wpdb $wpdb WordPress database abstraction object.
*
* @param string $importer_name
* @param string $blog_id
* @return array
*/
public function get_imported_posts( $importer_name, $blog_id ) {
global $wpdb;
$hashtable = array();
$limit = 100;
$offset = 0;
// Grab all posts in chunks.
do {
$meta_key = $importer_name . '_' . $blog_id . '_permalink';
$sql = $wpdb->prepare( "SELECT post_id, meta_value FROM $wpdb->postmeta WHERE meta_key = %s LIMIT %d,%d", $meta_key, $offset, $limit );
$results = $wpdb->get_results( $sql );
// Increment offset.
$offset = ( $limit + $offset );
if ( ! empty( $results ) ) {
foreach ( $results as $r ) {
// Set permalinks into array.
$hashtable[ $r->meta_value ] = (int) $r->post_id;
}
}
} while ( count( $results ) === $limit );
return $hashtable;
}
/**
* Returns count of imported permalinks from WordPress database.
*
* @global wpdb $wpdb WordPress database abstraction object.
*
* @param string $importer_name
* @param string $blog_id
* @return int
*/
public function count_imported_posts( $importer_name, $blog_id ) {
global $wpdb;
$count = 0;
// Get count of permalinks.
$meta_key = $importer_name . '_' . $blog_id . '_permalink';
$sql = $wpdb->prepare( "SELECT COUNT( post_id ) AS cnt FROM $wpdb->postmeta WHERE meta_key = %s", $meta_key );
$result = $wpdb->get_results( $sql );
if ( ! empty( $result ) ) {
$count = (int) $result[0]->cnt;
}
return $count;
}
/**
* Sets array with imported comments from WordPress database.
*
* @global wpdb $wpdb WordPress database abstraction object.
*
* @param string $blog_id
* @return array
*/
public function get_imported_comments( $blog_id ) {
global $wpdb;
$hashtable = array();
$limit = 100;
$offset = 0;
// Grab all comments in chunks.
do {
$sql = $wpdb->prepare( "SELECT comment_ID, comment_agent FROM $wpdb->comments LIMIT %d,%d", $offset, $limit );
$results = $wpdb->get_results( $sql );
// Increment offset.
$offset = ( $limit + $offset );
if ( ! empty( $results ) ) {
foreach ( $results as $r ) {
// Explode comment_agent key.
list ( $comment_agent_blog_id, $source_comment_id ) = explode( '-', $r->comment_agent );
$source_comment_id = (int) $source_comment_id;
// Check if this comment came from this blog.
if ( (int) $blog_id === (int) $comment_agent_blog_id ) {
$hashtable[ $source_comment_id ] = (int) $r->comment_ID;
}
}
}
} while ( count( $results ) === $limit );
return $hashtable;
}
/**
* @param int $blog_id
* @return int|void
*/
public function set_blog( $blog_id ) {
if ( is_numeric( $blog_id ) ) {
$blog_id = (int) $blog_id;
} else {
$blog = 'http://' . preg_replace( '#^https?://#', '', $blog_id );
$parsed = parse_url( $blog );
if ( ! $parsed || empty( $parsed['host'] ) ) {
fwrite( STDERR, "Error: can not determine blog_id from $blog_id\n" );
exit;
}
if ( empty( $parsed['path'] ) ) {
$parsed['path'] = '/';
}
$blogs = get_sites(
array(
'domain' => $parsed['host'],
'number' => 1,
'path' => $parsed['path'],
)
);
if ( ! $blogs ) {
fwrite( STDERR, "Error: Could not find blog\n" );
exit;
}
$blog = array_shift( $blogs );
$blog_id = (int) $blog->blog_id;
}
if ( function_exists( 'is_multisite' ) ) {
if ( is_multisite() ) {
switch_to_blog( $blog_id );
}
}
return $blog_id;
}
/**
* @param int $user_id
* @return int|void
*/
public function set_user( $user_id ) {
if ( is_numeric( $user_id ) ) {
$user_id = (int) $user_id;
} else {
$user_id = (int) username_exists( $user_id );
}
if ( ! $user_id || ! wp_set_current_user( $user_id ) ) {
fwrite( STDERR, "Error: can not find user\n" );
exit;
}
return $user_id;
}
/**
* Sorts by strlen, longest string first.
*
* @param string $a
* @param string $b
* @return int
*/
public function cmpr_strlen( $a, $b ) {
return strlen( $b ) - strlen( $a );
}
/**
* Gets URL.
*
* @param string $url
* @param string $username
* @param string $password
* @param bool $head
* @return array
*/
public function get_page( $url, $username = '', $password = '', $head = false ) {
// Increase the timeout.
add_filter( 'http_request_timeout', array( $this, 'bump_request_timeout' ) );
$headers = array();
$args = array();
if ( true === $head ) {
$args['method'] = 'HEAD';
}
if ( ! empty( $username ) && ! empty( $password ) ) {
$headers['Authorization'] = 'Basic ' . base64_encode( "$username:$password" );
}
$args['headers'] = $headers;
return wp_safe_remote_request( $url, $args );
}
/**
* Bumps up the request timeout for http requests.
*
* @param int $val
* @return int
*/
public function bump_request_timeout( $val ) {
return 60;
}
/**
* Checks if user has exceeded disk quota.
*
* @return bool
*/
public function is_user_over_quota() {
if ( function_exists( 'upload_is_user_over_quota' ) ) {
if ( upload_is_user_over_quota() ) {
return true;
}
}
return false;
}
/**
* Replaces newlines, tabs, and multiple spaces with a single space.
*
* @param string $text
* @return string
*/
public function min_whitespace( $text ) {
return preg_replace( '|[\r\n\t ]+|', ' ', $text );
}
/**
* Resets global variables that grow out of control during imports.
*
* @since 3.0.0
*
* @global wpdb $wpdb WordPress database abstraction object.
* @global int[] $wp_actions
*/
public function stop_the_insanity() {
global $wpdb, $wp_actions;
// Or define( 'WP_IMPORTING', true );
$wpdb->queries = array();
// Reset $wp_actions to keep it from growing out of control.
$wp_actions = array();
}
}
/**
* Returns value of command line params.
* Exits when a required param is not set.
*
* @param string $param
* @param bool $required
* @return mixed
*/
function get_cli_args( $param, $required = false ) {
$args = $_SERVER['argv'];
if ( ! is_array( $args ) ) {
$args = array();
}
$out = array();
$last_arg = null;
$return = null;
$il = count( $args );
for ( $i = 1, $il; $i < $il; $i++ ) {
if ( (bool) preg_match( '/^--(.+)/', $args[ $i ], $match ) ) {
$parts = explode( '=', $match[1] );
$key = preg_replace( '/[^a-z0-9]+/', '', $parts[0] );
if ( isset( $parts[1] ) ) {
$out[ $key ] = $parts[1];
} else {
$out[ $key ] = true;
}
$last_arg = $key;
} elseif ( (bool) preg_match( '/^-([a-zA-Z0-9]+)/', $args[ $i ], $match ) ) {
for ( $j = 0, $jl = strlen( $match[1] ); $j < $jl; $j++ ) {
$key = $match[1][ $j ];
$out[ $key ] = true;
}
$last_arg = $key;
} elseif ( null !== $last_arg ) {
$out[ $last_arg ] = $args[ $i ];
}
}
// Check array for specified param.
if ( isset( $out[ $param ] ) ) {
// Set return value.
$return = $out[ $param ];
}
// Check for missing required param.
if ( ! isset( $out[ $param ] ) && $required ) {
// Display message and exit.
echo "\"$param\" parameter is required but was not specified\n";
exit;
}
return $return;
}

View File

@ -0,0 +1,175 @@
<?php
/**
* Administration API: WP_Internal_Pointers class
*
* @package WordPress
* @subpackage Administration
* @since 4.4.0
*/
/**
* Core class used to implement an internal admin pointers API.
*
* @since 3.3.0
*/
#[AllowDynamicProperties]
final class WP_Internal_Pointers {
/**
* Initializes the new feature pointers.
*
* @since 3.3.0
*
* All pointers can be disabled using the following:
* remove_action( 'admin_enqueue_scripts', array( 'WP_Internal_Pointers', 'enqueue_scripts' ) );
*
* Individual pointers (e.g. wp390_widgets) can be disabled using the following:
*
* function yourprefix_remove_pointers() {
* remove_action(
* 'admin_print_footer_scripts',
* array( 'WP_Internal_Pointers', 'pointer_wp390_widgets' )
* );
* }
* add_action( 'admin_enqueue_scripts', 'yourprefix_remove_pointers', 11 );
*
* @param string $hook_suffix The current admin page.
*/
public static function enqueue_scripts( $hook_suffix ) {
/*
* Register feature pointers
*
* Format:
* array(
* hook_suffix => pointer callback
* )
*
* Example:
* array(
* 'themes.php' => 'wp390_widgets'
* )
*/
$registered_pointers = array(
// None currently.
);
// Check if screen related pointer is registered.
if ( empty( $registered_pointers[ $hook_suffix ] ) ) {
return;
}
$pointers = (array) $registered_pointers[ $hook_suffix ];
/*
* Specify required capabilities for feature pointers
*
* Format:
* array(
* pointer callback => Array of required capabilities
* )
*
* Example:
* array(
* 'wp390_widgets' => array( 'edit_theme_options' )
* )
*/
$caps_required = array(
// None currently.
);
// Get dismissed pointers.
$dismissed = explode( ',', (string) get_user_meta( get_current_user_id(), 'dismissed_wp_pointers', true ) );
$got_pointers = false;
foreach ( array_diff( $pointers, $dismissed ) as $pointer ) {
if ( isset( $caps_required[ $pointer ] ) ) {
foreach ( $caps_required[ $pointer ] as $cap ) {
if ( ! current_user_can( $cap ) ) {
continue 2;
}
}
}
// Bind pointer print function.
add_action( 'admin_print_footer_scripts', array( 'WP_Internal_Pointers', 'pointer_' . $pointer ) );
$got_pointers = true;
}
if ( ! $got_pointers ) {
return;
}
// Add pointers script and style to queue.
wp_enqueue_style( 'wp-pointer' );
wp_enqueue_script( 'wp-pointer' );
}
/**
* Prints the pointer JavaScript data.
*
* @since 3.3.0
*
* @param string $pointer_id The pointer ID.
* @param string $selector The HTML elements, on which the pointer should be attached.
* @param array $args Arguments to be passed to the pointer JS (see wp-pointer.js).
*/
private static function print_js( $pointer_id, $selector, $args ) {
if ( empty( $pointer_id ) || empty( $selector ) || empty( $args ) || empty( $args['content'] ) ) {
return;
}
?>
<script type="text/javascript">
(function($){
var options = <?php echo wp_json_encode( $args ); ?>, setup;
if ( ! options )
return;
options = $.extend( options, {
close: function() {
$.post( ajaxurl, {
pointer: '<?php echo $pointer_id; ?>',
action: 'dismiss-wp-pointer'
});
}
});
setup = function() {
$('<?php echo $selector; ?>').first().pointer( options ).pointer('open');
};
if ( options.position && options.position.defer_loading )
$(window).bind( 'load.wp-pointers', setup );
else
$( function() {
setup();
} );
})( jQuery );
</script>
<?php
}
public static function pointer_wp330_toolbar() {}
public static function pointer_wp330_media_uploader() {}
public static function pointer_wp330_saving_widgets() {}
public static function pointer_wp340_customize_current_theme_link() {}
public static function pointer_wp340_choose_image_from_library() {}
public static function pointer_wp350_media() {}
public static function pointer_wp360_revisions() {}
public static function pointer_wp360_locks() {}
public static function pointer_wp390_widgets() {}
public static function pointer_wp410_dfw() {}
public static function pointer_wp496_privacy() {}
/**
* Prevents new users from seeing existing 'new feature' pointers.
*
* @since 3.3.0
*
* @param int $user_id User ID.
*/
public static function dismiss_pointers_for_new_users( $user_id ) {
add_user_meta( $user_id, 'dismissed_wp_pointers', '' );
}
}

View File

@ -0,0 +1,354 @@
<?php
/**
* List Table API: WP_Links_List_Table class
*
* @package WordPress
* @subpackage Administration
* @since 3.1.0
*/
/**
* Core class used to implement displaying links in a list table.
*
* @since 3.1.0
*
* @see WP_List_Table
*/
class WP_Links_List_Table extends WP_List_Table {
/**
* Constructor.
*
* @since 3.1.0
*
* @see WP_List_Table::__construct() for more information on default arguments.
*
* @param array $args An associative array of arguments.
*/
public function __construct( $args = array() ) {
parent::__construct(
array(
'plural' => 'bookmarks',
'screen' => isset( $args['screen'] ) ? $args['screen'] : null,
)
);
}
/**
* @return bool
*/
public function ajax_user_can() {
return current_user_can( 'manage_links' );
}
/**
* @global int $cat_id
* @global string $s
* @global string $orderby
* @global string $order
*/
public function prepare_items() {
global $cat_id, $s, $orderby, $order;
wp_reset_vars( array( 'action', 'cat_id', 'link_id', 'orderby', 'order', 's' ) );
$args = array(
'hide_invisible' => 0,
'hide_empty' => 0,
);
if ( 'all' !== $cat_id ) {
$args['category'] = $cat_id;
}
if ( ! empty( $s ) ) {
$args['search'] = $s;
}
if ( ! empty( $orderby ) ) {
$args['orderby'] = $orderby;
}
if ( ! empty( $order ) ) {
$args['order'] = $order;
}
$this->items = get_bookmarks( $args );
}
/**
*/
public function no_items() {
_e( 'No links found.' );
}
/**
* @return array
*/
protected function get_bulk_actions() {
$actions = array();
$actions['delete'] = __( 'Delete' );
return $actions;
}
/**
* @global int $cat_id
* @param string $which
*/
protected function extra_tablenav( $which ) {
global $cat_id;
if ( 'top' !== $which ) {
return;
}
?>
<div class="alignleft actions">
<?php
$dropdown_options = array(
'selected' => $cat_id,
'name' => 'cat_id',
'taxonomy' => 'link_category',
'show_option_all' => get_taxonomy( 'link_category' )->labels->all_items,
'hide_empty' => true,
'hierarchical' => 1,
'show_count' => 0,
'orderby' => 'name',
);
echo '<label class="screen-reader-text" for="cat_id">' . get_taxonomy( 'link_category' )->labels->filter_by_item . '</label>';
wp_dropdown_categories( $dropdown_options );
submit_button( __( 'Filter' ), '', 'filter_action', false, array( 'id' => 'post-query-submit' ) );
?>
</div>
<?php
}
/**
* @return string[] Array of column titles keyed by their column name.
*/
public function get_columns() {
return array(
'cb' => '<input type="checkbox" />',
'name' => _x( 'Name', 'link name' ),
'url' => __( 'URL' ),
'categories' => __( 'Categories' ),
'rel' => __( 'Relationship' ),
'visible' => __( 'Visible' ),
'rating' => __( 'Rating' ),
);
}
/**
* @return array
*/
protected function get_sortable_columns() {
return array(
'name' => array( 'name', false, _x( 'Name', 'link name' ), __( 'Table ordered by Name.' ), 'asc' ),
'url' => array( 'url', false, __( 'URL' ), __( 'Table ordered by URL.' ) ),
'visible' => array( 'visible', false, __( 'Visible' ), __( 'Table ordered by Visibility.' ) ),
'rating' => array( 'rating', false, __( 'Rating' ), __( 'Table ordered by Rating.' ) ),
);
}
/**
* Gets the name of the default primary column.
*
* @since 4.3.0
*
* @return string Name of the default primary column, in this case, 'name'.
*/
protected function get_default_primary_column_name() {
return 'name';
}
/**
* Handles the checkbox column output.
*
* @since 4.3.0
* @since 5.9.0 Renamed `$link` to `$item` to match parent class for PHP 8 named parameter support.
*
* @param object $item The current link object.
*/
public function column_cb( $item ) {
// Restores the more descriptive, specific name for use within this method.
$link = $item;
?>
<input type="checkbox" name="linkcheck[]" id="cb-select-<?php echo $link->link_id; ?>" value="<?php echo esc_attr( $link->link_id ); ?>" />
<label for="cb-select-<?php echo $link->link_id; ?>">
<span class="screen-reader-text">
<?php
/* translators: Hidden accessibility text. %s: Link name. */
printf( __( 'Select %s' ), $link->link_name );
?>
</span>
</label>
<?php
}
/**
* Handles the link name column output.
*
* @since 4.3.0
*
* @param object $link The current link object.
*/
public function column_name( $link ) {
$edit_link = get_edit_bookmark_link( $link );
printf(
'<strong><a class="row-title" href="%s" aria-label="%s">%s</a></strong>',
$edit_link,
/* translators: %s: Link name. */
esc_attr( sprintf( __( 'Edit &#8220;%s&#8221;' ), $link->link_name ) ),
$link->link_name
);
}
/**
* Handles the link URL column output.
*
* @since 4.3.0
*
* @param object $link The current link object.
*/
public function column_url( $link ) {
$short_url = url_shorten( $link->link_url );
echo "<a href='$link->link_url'>$short_url</a>";
}
/**
* Handles the link categories column output.
*
* @since 4.3.0
*
* @global int $cat_id
*
* @param object $link The current link object.
*/
public function column_categories( $link ) {
global $cat_id;
$cat_names = array();
foreach ( $link->link_category as $category ) {
$cat = get_term( $category, 'link_category', OBJECT, 'display' );
if ( is_wp_error( $cat ) ) {
echo $cat->get_error_message();
}
$cat_name = $cat->name;
if ( (int) $cat_id !== $category ) {
$cat_name = "<a href='link-manager.php?cat_id=$category'>$cat_name</a>";
}
$cat_names[] = $cat_name;
}
echo implode( ', ', $cat_names );
}
/**
* Handles the link relation column output.
*
* @since 4.3.0
*
* @param object $link The current link object.
*/
public function column_rel( $link ) {
echo empty( $link->link_rel ) ? '<br />' : $link->link_rel;
}
/**
* Handles the link visibility column output.
*
* @since 4.3.0
*
* @param object $link The current link object.
*/
public function column_visible( $link ) {
if ( 'Y' === $link->link_visible ) {
_e( 'Yes' );
} else {
_e( 'No' );
}
}
/**
* Handles the link rating column output.
*
* @since 4.3.0
*
* @param object $link The current link object.
*/
public function column_rating( $link ) {
echo $link->link_rating;
}
/**
* Handles the default column output.
*
* @since 4.3.0
* @since 5.9.0 Renamed `$link` to `$item` to match parent class for PHP 8 named parameter support.
*
* @param object $item Link object.
* @param string $column_name Current column name.
*/
public function column_default( $item, $column_name ) {
// Restores the more descriptive, specific name for use within this method.
$link = $item;
/**
* Fires for each registered custom link column.
*
* @since 2.1.0
*
* @param string $column_name Name of the custom column.
* @param int $link_id Link ID.
*/
do_action( 'manage_link_custom_column', $column_name, $link->link_id );
}
public function display_rows() {
foreach ( $this->items as $link ) {
$link = sanitize_bookmark( $link );
$link->link_name = esc_attr( $link->link_name );
$link->link_category = wp_get_link_cats( $link->link_id );
?>
<tr id="link-<?php echo $link->link_id; ?>">
<?php $this->single_row_columns( $link ); ?>
</tr>
<?php
}
}
/**
* Generates and displays row action links.
*
* @since 4.3.0
* @since 5.9.0 Renamed `$link` to `$item` to match parent class for PHP 8 named parameter support.
*
* @param object $item Link being acted upon.
* @param string $column_name Current column name.
* @param string $primary Primary column name.
* @return string Row actions output for links, or an empty string
* if the current column is not the primary column.
*/
protected function handle_row_actions( $item, $column_name, $primary ) {
if ( $primary !== $column_name ) {
return '';
}
// Restores the more descriptive, specific name for use within this method.
$link = $item;
$edit_link = get_edit_bookmark_link( $link );
$actions = array();
$actions['edit'] = '<a href="' . $edit_link . '">' . __( 'Edit' ) . '</a>';
$actions['delete'] = sprintf(
'<a class="submitdelete" href="%s" onclick="return confirm( \'%s\' );">%s</a>',
wp_nonce_url( "link.php?action=delete&amp;link_id=$link->link_id", 'delete-bookmark_' . $link->link_id ),
/* translators: %s: Link name. */
esc_js( sprintf( __( "You are about to delete this link '%s'\n 'Cancel' to stop, 'OK' to delete." ), $link->link_name ) ),
__( 'Delete' )
);
return $this->row_actions( $actions );
}
}

View File

@ -0,0 +1,67 @@
<?php
/**
* Helper functions for displaying a list of items in an ajaxified HTML table.
*
* @package WordPress
* @subpackage List_Table
* @since 4.7.0
*/
/**
* Helper class to be used only by back compat functions.
*
* @since 3.1.0
*/
class _WP_List_Table_Compat extends WP_List_Table {
public $_screen;
public $_columns;
/**
* Constructor.
*
* @since 3.1.0
*
* @param string|WP_Screen $screen The screen hook name or screen object.
* @param string[] $columns An array of columns with column IDs as the keys
* and translated column names as the values.
*/
public function __construct( $screen, $columns = array() ) {
if ( is_string( $screen ) ) {
$screen = convert_to_screen( $screen );
}
$this->_screen = $screen;
if ( ! empty( $columns ) ) {
$this->_columns = $columns;
add_filter( 'manage_' . $screen->id . '_columns', array( $this, 'get_columns' ), 0 );
}
}
/**
* Gets a list of all, hidden, and sortable columns.
*
* @since 3.1.0
*
* @return array
*/
protected function get_column_info() {
$columns = get_column_headers( $this->_screen );
$hidden = get_hidden_columns( $this->_screen );
$sortable = array();
$primary = $this->get_default_primary_column_name();
return array( $columns, $hidden, $sortable, $primary );
}
/**
* Gets a list of columns.
*
* @since 3.1.0
*
* @return array
*/
public function get_columns() {
return $this->_columns;
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,891 @@
<?php
/**
* List Table API: WP_Media_List_Table class
*
* @package WordPress
* @subpackage Administration
* @since 3.1.0
*/
/**
* Core class used to implement displaying media items in a list table.
*
* @since 3.1.0
*
* @see WP_List_Table
*/
class WP_Media_List_Table extends WP_List_Table {
/**
* Holds the number of pending comments for each post.
*
* @since 4.4.0
* @var array
*/
protected $comment_pending_count = array();
private $detached;
private $is_trash;
/**
* Constructor.
*
* @since 3.1.0
*
* @see WP_List_Table::__construct() for more information on default arguments.
*
* @param array $args An associative array of arguments.
*/
public function __construct( $args = array() ) {
$this->detached = ( isset( $_REQUEST['attachment-filter'] ) && 'detached' === $_REQUEST['attachment-filter'] );
$this->modes = array(
'list' => __( 'List view' ),
'grid' => __( 'Grid view' ),
);
parent::__construct(
array(
'plural' => 'media',
'screen' => isset( $args['screen'] ) ? $args['screen'] : null,
)
);
}
/**
* @return bool
*/
public function ajax_user_can() {
return current_user_can( 'upload_files' );
}
/**
* @global string $mode List table view mode.
* @global WP_Query $wp_query WordPress Query object.
* @global array $post_mime_types
* @global array $avail_post_mime_types
*/
public function prepare_items() {
global $mode, $wp_query, $post_mime_types, $avail_post_mime_types;
$mode = empty( $_REQUEST['mode'] ) ? 'list' : $_REQUEST['mode'];
/*
* Exclude attachments scheduled for deletion in the next two hours
* if they are for zip packages for interrupted or failed updates.
* See File_Upload_Upgrader class.
*/
$not_in = array();
$crons = _get_cron_array();
if ( is_array( $crons ) ) {
foreach ( $crons as $cron ) {
if ( isset( $cron['upgrader_scheduled_cleanup'] ) ) {
$details = reset( $cron['upgrader_scheduled_cleanup'] );
if ( ! empty( $details['args'][0] ) ) {
$not_in[] = (int) $details['args'][0];
}
}
}
}
if ( ! empty( $_REQUEST['post__not_in'] ) && is_array( $_REQUEST['post__not_in'] ) ) {
$not_in = array_merge( array_values( $_REQUEST['post__not_in'] ), $not_in );
}
if ( ! empty( $not_in ) ) {
$_REQUEST['post__not_in'] = $not_in;
}
list( $post_mime_types, $avail_post_mime_types ) = wp_edit_attachments_query( $_REQUEST );
$this->is_trash = isset( $_REQUEST['attachment-filter'] ) && 'trash' === $_REQUEST['attachment-filter'];
$this->set_pagination_args(
array(
'total_items' => $wp_query->found_posts,
'total_pages' => $wp_query->max_num_pages,
'per_page' => $wp_query->query_vars['posts_per_page'],
)
);
if ( $wp_query->posts ) {
update_post_thumbnail_cache( $wp_query );
update_post_parent_caches( $wp_query->posts );
}
}
/**
* @global array $post_mime_types
* @global array $avail_post_mime_types
* @return array
*/
protected function get_views() {
global $post_mime_types, $avail_post_mime_types;
$type_links = array();
$filter = empty( $_GET['attachment-filter'] ) ? '' : $_GET['attachment-filter'];
$type_links['all'] = sprintf(
'<option value=""%s>%s</option>',
selected( $filter, true, false ),
__( 'All media items' )
);
foreach ( $post_mime_types as $mime_type => $label ) {
if ( ! wp_match_mime_types( $mime_type, $avail_post_mime_types ) ) {
continue;
}
$selected = selected(
$filter && str_starts_with( $filter, 'post_mime_type:' ) &&
wp_match_mime_types( $mime_type, str_replace( 'post_mime_type:', '', $filter ) ),
true,
false
);
$type_links[ $mime_type ] = sprintf(
'<option value="post_mime_type:%s"%s>%s</option>',
esc_attr( $mime_type ),
$selected,
$label[0]
);
}
$type_links['detached'] = '<option value="detached"' . ( $this->detached ? ' selected="selected"' : '' ) . '>' . _x( 'Unattached', 'media items' ) . '</option>';
$type_links['mine'] = sprintf(
'<option value="mine"%s>%s</option>',
selected( 'mine' === $filter, true, false ),
_x( 'Mine', 'media items' )
);
if ( $this->is_trash || ( defined( 'MEDIA_TRASH' ) && MEDIA_TRASH ) ) {
$type_links['trash'] = sprintf(
'<option value="trash"%s>%s</option>',
selected( 'trash' === $filter, true, false ),
_x( 'Trash', 'attachment filter' )
);
}
return $type_links;
}
/**
* @return array
*/
protected function get_bulk_actions() {
$actions = array();
if ( MEDIA_TRASH ) {
if ( $this->is_trash ) {
$actions['untrash'] = __( 'Restore' );
$actions['delete'] = __( 'Delete permanently' );
} else {
$actions['trash'] = __( 'Move to Trash' );
}
} else {
$actions['delete'] = __( 'Delete permanently' );
}
if ( $this->detached ) {
$actions['attach'] = __( 'Attach' );
}
return $actions;
}
/**
* @param string $which
*/
protected function extra_tablenav( $which ) {
if ( 'bar' !== $which ) {
return;
}
?>
<div class="actions">
<?php
if ( ! $this->is_trash ) {
$this->months_dropdown( 'attachment' );
}
/** This action is documented in wp-admin/includes/class-wp-posts-list-table.php */
do_action( 'restrict_manage_posts', $this->screen->post_type, $which );
submit_button( __( 'Filter' ), '', 'filter_action', false, array( 'id' => 'post-query-submit' ) );
if ( $this->is_trash && $this->has_items()
&& current_user_can( 'edit_others_posts' )
) {
submit_button( __( 'Empty Trash' ), 'apply', 'delete_all', false );
}
?>
</div>
<?php
}
/**
* @return string
*/
public function current_action() {
if ( isset( $_REQUEST['found_post_id'] ) && isset( $_REQUEST['media'] ) ) {
return 'attach';
}
if ( isset( $_REQUEST['parent_post_id'] ) && isset( $_REQUEST['media'] ) ) {
return 'detach';
}
if ( isset( $_REQUEST['delete_all'] ) || isset( $_REQUEST['delete_all2'] ) ) {
return 'delete_all';
}
return parent::current_action();
}
/**
* @return bool
*/
public function has_items() {
return have_posts();
}
/**
*/
public function no_items() {
if ( $this->is_trash ) {
_e( 'No media files found in Trash.' );
} else {
_e( 'No media files found.' );
}
}
/**
* Overrides parent views to use the filter bar display.
*
* @global string $mode List table view mode.
*/
public function views() {
global $mode;
$views = $this->get_views();
$this->screen->render_screen_reader_content( 'heading_views' );
?>
<div class="wp-filter">
<div class="filter-items">
<?php $this->view_switcher( $mode ); ?>
<label for="attachment-filter" class="screen-reader-text">
<?php
/* translators: Hidden accessibility text. */
_e( 'Filter by type' );
?>
</label>
<select class="attachment-filters" name="attachment-filter" id="attachment-filter">
<?php
if ( ! empty( $views ) ) {
foreach ( $views as $class => $view ) {
echo "\t$view\n";
}
}
?>
</select>
<?php
$this->extra_tablenav( 'bar' );
/** This filter is documented in wp-admin/includes/class-wp-list-table.php */
$views = apply_filters( "views_{$this->screen->id}", array() );
// Back compat for pre-4.0 view links.
if ( ! empty( $views ) ) {
echo '<ul class="filter-links">';
foreach ( $views as $class => $view ) {
echo "<li class='$class'>$view</li>";
}
echo '</ul>';
}
?>
</div>
<div class="search-form">
<p class="search-box">
<label class="screen-reader-text" for="media-search-input">
<?php
/* translators: Hidden accessibility text. */
esc_html_e( 'Search Media' );
?>
</label>
<input type="search" id="media-search-input" class="search" name="s" value="<?php _admin_search_query(); ?>">
<input id="search-submit" type="submit" class="button" value="<?php esc_attr_e( 'Search Media' ); ?>">
</p>
</div>
</div>
<?php
}
/**
* @return string[] Array of column titles keyed by their column name.
*/
public function get_columns() {
$posts_columns = array();
$posts_columns['cb'] = '<input type="checkbox" />';
/* translators: Column name. */
$posts_columns['title'] = _x( 'File', 'column name' );
$posts_columns['author'] = __( 'Author' );
$taxonomies = get_taxonomies_for_attachments( 'objects' );
$taxonomies = wp_filter_object_list( $taxonomies, array( 'show_admin_column' => true ), 'and', 'name' );
/**
* Filters the taxonomy columns for attachments in the Media list table.
*
* @since 3.5.0
*
* @param string[] $taxonomies An array of registered taxonomy names to show for attachments.
* @param string $post_type The post type. Default 'attachment'.
*/
$taxonomies = apply_filters( 'manage_taxonomies_for_attachment_columns', $taxonomies, 'attachment' );
$taxonomies = array_filter( $taxonomies, 'taxonomy_exists' );
foreach ( $taxonomies as $taxonomy ) {
if ( 'category' === $taxonomy ) {
$column_key = 'categories';
} elseif ( 'post_tag' === $taxonomy ) {
$column_key = 'tags';
} else {
$column_key = 'taxonomy-' . $taxonomy;
}
$posts_columns[ $column_key ] = get_taxonomy( $taxonomy )->labels->name;
}
/* translators: Column name. */
if ( ! $this->detached ) {
$posts_columns['parent'] = _x( 'Uploaded to', 'column name' );
if ( post_type_supports( 'attachment', 'comments' ) ) {
$posts_columns['comments'] = sprintf(
'<span class="vers comment-grey-bubble" title="%1$s" aria-hidden="true"></span><span class="screen-reader-text">%2$s</span>',
esc_attr__( 'Comments' ),
/* translators: Hidden accessibility text. */
__( 'Comments' )
);
}
}
/* translators: Column name. */
$posts_columns['date'] = _x( 'Date', 'column name' );
/**
* Filters the Media list table columns.
*
* @since 2.5.0
*
* @param string[] $posts_columns An array of columns displayed in the Media list table.
* @param bool $detached Whether the list table contains media not attached
* to any posts. Default true.
*/
return apply_filters( 'manage_media_columns', $posts_columns, $this->detached );
}
/**
* @return array
*/
protected function get_sortable_columns() {
return array(
'title' => array( 'title', false, _x( 'File', 'column name' ), __( 'Table ordered by File Name.' ) ),
'author' => array( 'author', false, __( 'Author' ), __( 'Table ordered by Author.' ) ),
'parent' => array( 'parent', false, _x( 'Uploaded to', 'column name' ), __( 'Table ordered by Uploaded To.' ) ),
'comments' => array( 'comment_count', __( 'Comments' ), false, __( 'Table ordered by Comments.' ) ),
'date' => array( 'date', true, __( 'Date' ), __( 'Table ordered by Date.' ), 'desc' ),
);
}
/**
* Handles the checkbox column output.
*
* @since 4.3.0
* @since 5.9.0 Renamed `$post` to `$item` to match parent class for PHP 8 named parameter support.
*
* @param WP_Post $item The current WP_Post object.
*/
public function column_cb( $item ) {
// Restores the more descriptive, specific name for use within this method.
$post = $item;
if ( current_user_can( 'edit_post', $post->ID ) ) {
?>
<input type="checkbox" name="media[]" id="cb-select-<?php echo $post->ID; ?>" value="<?php echo $post->ID; ?>" />
<label for="cb-select-<?php echo $post->ID; ?>">
<span class="screen-reader-text">
<?php
/* translators: Hidden accessibility text. %s: Attachment title. */
printf( __( 'Select %s' ), _draft_or_post_title() );
?>
</span>
</label>
<?php
}
}
/**
* Handles the title column output.
*
* @since 4.3.0
*
* @param WP_Post $post The current WP_Post object.
*/
public function column_title( $post ) {
list( $mime ) = explode( '/', $post->post_mime_type );
$attachment_id = $post->ID;
if ( has_post_thumbnail( $post ) ) {
$thumbnail_id = get_post_thumbnail_id( $post );
if ( ! empty( $thumbnail_id ) ) {
$attachment_id = $thumbnail_id;
}
}
$title = _draft_or_post_title();
$thumb = wp_get_attachment_image( $attachment_id, array( 60, 60 ), true, array( 'alt' => '' ) );
$link_start = '';
$link_end = '';
if ( current_user_can( 'edit_post', $post->ID ) && ! $this->is_trash ) {
$link_start = sprintf(
'<a href="%s" aria-label="%s">',
get_edit_post_link( $post->ID ),
/* translators: %s: Attachment title. */
esc_attr( sprintf( __( '&#8220;%s&#8221; (Edit)' ), $title ) )
);
$link_end = '</a>';
}
$class = $thumb ? ' class="has-media-icon"' : '';
?>
<strong<?php echo $class; ?>>
<?php
echo $link_start;
if ( $thumb ) :
?>
<span class="media-icon <?php echo sanitize_html_class( $mime . '-icon' ); ?>"><?php echo $thumb; ?></span>
<?php
endif;
echo $title . $link_end;
_media_states( $post );
?>
</strong>
<p class="filename">
<span class="screen-reader-text">
<?php
/* translators: Hidden accessibility text. */
_e( 'File name:' );
?>
</span>
<?php
$file = get_attached_file( $post->ID );
echo esc_html( wp_basename( $file ) );
?>
</p>
<?php
}
/**
* Handles the author column output.
*
* @since 4.3.0
*
* @param WP_Post $post The current WP_Post object.
*/
public function column_author( $post ) {
printf(
'<a href="%s">%s</a>',
esc_url( add_query_arg( array( 'author' => get_the_author_meta( 'ID' ) ), 'upload.php' ) ),
get_the_author()
);
}
/**
* Handles the description column output.
*
* @since 4.3.0
* @deprecated 6.2.0
*
* @param WP_Post $post The current WP_Post object.
*/
public function column_desc( $post ) {
_deprecated_function( __METHOD__, '6.2.0' );
echo has_excerpt() ? $post->post_excerpt : '';
}
/**
* Handles the date column output.
*
* @since 4.3.0
*
* @param WP_Post $post The current WP_Post object.
*/
public function column_date( $post ) {
if ( '0000-00-00 00:00:00' === $post->post_date ) {
$h_time = __( 'Unpublished' );
} else {
$time = get_post_timestamp( $post );
$time_diff = time() - $time;
if ( $time && $time_diff > 0 && $time_diff < DAY_IN_SECONDS ) {
/* translators: %s: Human-readable time difference. */
$h_time = sprintf( __( '%s ago' ), human_time_diff( $time ) );
} else {
$h_time = get_the_time( __( 'Y/m/d' ), $post );
}
}
/**
* Filters the published time of an attachment displayed in the Media list table.
*
* @since 6.0.0
*
* @param string $h_time The published time.
* @param WP_Post $post Attachment object.
* @param string $column_name The column name.
*/
echo apply_filters( 'media_date_column_time', $h_time, $post, 'date' );
}
/**
* Handles the parent column output.
*
* @since 4.3.0
*
* @param WP_Post $post The current WP_Post object.
*/
public function column_parent( $post ) {
$user_can_edit = current_user_can( 'edit_post', $post->ID );
if ( $post->post_parent > 0 ) {
$parent = get_post( $post->post_parent );
} else {
$parent = false;
}
if ( $parent ) {
$title = _draft_or_post_title( $post->post_parent );
$parent_type = get_post_type_object( $parent->post_type );
if ( $parent_type && $parent_type->show_ui && current_user_can( 'edit_post', $post->post_parent ) ) {
printf( '<strong><a href="%s">%s</a></strong>', get_edit_post_link( $post->post_parent ), $title );
} elseif ( $parent_type && current_user_can( 'read_post', $post->post_parent ) ) {
printf( '<strong>%s</strong>', $title );
} else {
_e( '(Private post)' );
}
if ( $user_can_edit ) :
$detach_url = add_query_arg(
array(
'parent_post_id' => $post->post_parent,
'media[]' => $post->ID,
'_wpnonce' => wp_create_nonce( 'bulk-' . $this->_args['plural'] ),
),
'upload.php'
);
printf(
'<br /><a href="%s" class="hide-if-no-js detach-from-parent" aria-label="%s">%s</a>',
$detach_url,
/* translators: %s: Title of the post the attachment is attached to. */
esc_attr( sprintf( __( 'Detach from &#8220;%s&#8221;' ), $title ) ),
__( 'Detach' )
);
endif;
} else {
_e( '(Unattached)' );
?>
<?php
if ( $user_can_edit ) {
$title = _draft_or_post_title( $post->post_parent );
printf(
'<br /><a href="#the-list" onclick="findPosts.open( \'media[]\', \'%s\' ); return false;" class="hide-if-no-js aria-button-if-js" aria-label="%s">%s</a>',
$post->ID,
/* translators: %s: Attachment title. */
esc_attr( sprintf( __( 'Attach &#8220;%s&#8221; to existing content' ), $title ) ),
__( 'Attach' )
);
}
}
}
/**
* Handles the comments column output.
*
* @since 4.3.0
*
* @param WP_Post $post The current WP_Post object.
*/
public function column_comments( $post ) {
echo '<div class="post-com-count-wrapper">';
if ( isset( $this->comment_pending_count[ $post->ID ] ) ) {
$pending_comments = $this->comment_pending_count[ $post->ID ];
} else {
$pending_comments = get_pending_comments_num( $post->ID );
}
$this->comments_bubble( $post->ID, $pending_comments );
echo '</div>';
}
/**
* Handles output for the default column.
*
* @since 4.3.0
* @since 5.9.0 Renamed `$post` to `$item` to match parent class for PHP 8 named parameter support.
*
* @param WP_Post $item The current WP_Post object.
* @param string $column_name Current column name.
*/
public function column_default( $item, $column_name ) {
// Restores the more descriptive, specific name for use within this method.
$post = $item;
if ( 'categories' === $column_name ) {
$taxonomy = 'category';
} elseif ( 'tags' === $column_name ) {
$taxonomy = 'post_tag';
} elseif ( str_starts_with( $column_name, 'taxonomy-' ) ) {
$taxonomy = substr( $column_name, 9 );
} else {
$taxonomy = false;
}
if ( $taxonomy ) {
$terms = get_the_terms( $post->ID, $taxonomy );
if ( is_array( $terms ) ) {
$output = array();
foreach ( $terms as $t ) {
$posts_in_term_qv = array();
$posts_in_term_qv['taxonomy'] = $taxonomy;
$posts_in_term_qv['term'] = $t->slug;
$output[] = sprintf(
'<a href="%s">%s</a>',
esc_url( add_query_arg( $posts_in_term_qv, 'upload.php' ) ),
esc_html( sanitize_term_field( 'name', $t->name, $t->term_id, $taxonomy, 'display' ) )
);
}
echo implode( wp_get_list_item_separator(), $output );
} else {
echo '<span aria-hidden="true">&#8212;</span><span class="screen-reader-text">' . get_taxonomy( $taxonomy )->labels->no_terms . '</span>';
}
return;
}
/**
* Fires for each custom column in the Media list table.
*
* Custom columns are registered using the {@see 'manage_media_columns'} filter.
*
* @since 2.5.0
*
* @param string $column_name Name of the custom column.
* @param int $post_id Attachment ID.
*/
do_action( 'manage_media_custom_column', $column_name, $post->ID );
}
/**
* @global WP_Post $post Global post object.
* @global WP_Query $wp_query WordPress Query object.
*/
public function display_rows() {
global $post, $wp_query;
$post_ids = wp_list_pluck( $wp_query->posts, 'ID' );
reset( $wp_query->posts );
$this->comment_pending_count = get_pending_comments_num( $post_ids );
add_filter( 'the_title', 'esc_html' );
while ( have_posts() ) :
the_post();
if ( $this->is_trash && 'trash' !== $post->post_status
|| ! $this->is_trash && 'trash' === $post->post_status
) {
continue;
}
$post_owner = ( get_current_user_id() === (int) $post->post_author ) ? 'self' : 'other';
?>
<tr id="post-<?php echo $post->ID; ?>" class="<?php echo trim( ' author-' . $post_owner . ' status-' . $post->post_status ); ?>">
<?php $this->single_row_columns( $post ); ?>
</tr>
<?php
endwhile;
}
/**
* Gets the name of the default primary column.
*
* @since 4.3.0
*
* @return string Name of the default primary column, in this case, 'title'.
*/
protected function get_default_primary_column_name() {
return 'title';
}
/**
* @param WP_Post $post
* @param string $att_title
* @return array
*/
private function _get_row_actions( $post, $att_title ) {
$actions = array();
if ( ! $this->is_trash && current_user_can( 'edit_post', $post->ID ) ) {
$actions['edit'] = sprintf(
'<a href="%s" aria-label="%s">%s</a>',
esc_url( get_edit_post_link( $post->ID ) ),
/* translators: %s: Attachment title. */
esc_attr( sprintf( __( 'Edit &#8220;%s&#8221;' ), $att_title ) ),
__( 'Edit' )
);
}
if ( current_user_can( 'delete_post', $post->ID ) ) {
if ( $this->is_trash ) {
$actions['untrash'] = sprintf(
'<a href="%s" class="submitdelete aria-button-if-js" aria-label="%s">%s</a>',
esc_url( wp_nonce_url( "post.php?action=untrash&amp;post=$post->ID", 'untrash-post_' . $post->ID ) ),
/* translators: %s: Attachment title. */
esc_attr( sprintf( __( 'Restore &#8220;%s&#8221; from the Trash' ), $att_title ) ),
__( 'Restore' )
);
} elseif ( EMPTY_TRASH_DAYS && MEDIA_TRASH ) {
$actions['trash'] = sprintf(
'<a href="%s" class="submitdelete aria-button-if-js" aria-label="%s">%s</a>',
esc_url( wp_nonce_url( "post.php?action=trash&amp;post=$post->ID", 'trash-post_' . $post->ID ) ),
/* translators: %s: Attachment title. */
esc_attr( sprintf( __( 'Move &#8220;%s&#8221; to the Trash' ), $att_title ) ),
_x( 'Trash', 'verb' )
);
}
if ( $this->is_trash || ! EMPTY_TRASH_DAYS || ! MEDIA_TRASH ) {
$show_confirmation = ( ! $this->is_trash && ! MEDIA_TRASH ) ? " onclick='return showNotice.warn();'" : '';
$actions['delete'] = sprintf(
'<a href="%s" class="submitdelete aria-button-if-js"%s aria-label="%s">%s</a>',
esc_url( wp_nonce_url( "post.php?action=delete&amp;post=$post->ID", 'delete-post_' . $post->ID ) ),
$show_confirmation,
/* translators: %s: Attachment title. */
esc_attr( sprintf( __( 'Delete &#8220;%s&#8221; permanently' ), $att_title ) ),
__( 'Delete Permanently' )
);
}
}
$attachment_url = wp_get_attachment_url( $post->ID );
if ( ! $this->is_trash ) {
$permalink = get_permalink( $post->ID );
if ( $permalink ) {
$actions['view'] = sprintf(
'<a href="%s" aria-label="%s" rel="bookmark">%s</a>',
esc_url( $permalink ),
/* translators: %s: Attachment title. */
esc_attr( sprintf( __( 'View &#8220;%s&#8221;' ), $att_title ) ),
__( 'View' )
);
}
if ( $attachment_url ) {
$actions['copy'] = sprintf(
'<span class="copy-to-clipboard-container"><button type="button" class="button-link copy-attachment-url media-library" data-clipboard-text="%s" aria-label="%s">%s</button><span class="success hidden" aria-hidden="true">%s</span></span>',
esc_url( $attachment_url ),
/* translators: %s: Attachment title. */
esc_attr( sprintf( __( 'Copy &#8220;%s&#8221; URL to clipboard' ), $att_title ) ),
__( 'Copy URL' ),
__( 'Copied!' )
);
}
}
if ( $attachment_url ) {
$actions['download'] = sprintf(
'<a href="%s" aria-label="%s" download>%s</a>',
esc_url( $attachment_url ),
/* translators: %s: Attachment title. */
esc_attr( sprintf( __( 'Download &#8220;%s&#8221;' ), $att_title ) ),
__( 'Download file' )
);
}
if ( $this->detached && current_user_can( 'edit_post', $post->ID ) ) {
$actions['attach'] = sprintf(
'<a href="#the-list" onclick="findPosts.open( \'media[]\', \'%s\' ); return false;" class="hide-if-no-js aria-button-if-js" aria-label="%s">%s</a>',
$post->ID,
/* translators: %s: Attachment title. */
esc_attr( sprintf( __( 'Attach &#8220;%s&#8221; to existing content' ), $att_title ) ),
__( 'Attach' )
);
}
/**
* Filters the action links for each attachment in the Media list table.
*
* @since 2.8.0
*
* @param string[] $actions An array of action links for each attachment.
* Includes 'Edit', 'Delete Permanently', 'View',
* 'Copy URL' and 'Download file'.
* @param WP_Post $post WP_Post object for the current attachment.
* @param bool $detached Whether the list table contains media not attached
* to any posts. Default true.
*/
return apply_filters( 'media_row_actions', $actions, $post, $this->detached );
}
/**
* Generates and displays row action links.
*
* @since 4.3.0
* @since 5.9.0 Renamed `$post` to `$item` to match parent class for PHP 8 named parameter support.
*
* @param WP_Post $item Attachment being acted upon.
* @param string $column_name Current column name.
* @param string $primary Primary column name.
* @return string Row actions output for media attachments, or an empty string
* if the current column is not the primary column.
*/
protected function handle_row_actions( $item, $column_name, $primary ) {
if ( $primary !== $column_name ) {
return '';
}
// Restores the more descriptive, specific name for use within this method.
$post = $item;
$att_title = _draft_or_post_title();
$actions = $this->_get_row_actions( $post, $att_title );
return $this->row_actions( $actions );
}
}

View File

@ -0,0 +1,861 @@
<?php
/**
* List Table API: WP_MS_Sites_List_Table class
*
* @package WordPress
* @subpackage Administration
* @since 3.1.0
*/
/**
* Core class used to implement displaying sites in a list table for the network admin.
*
* @since 3.1.0
*
* @see WP_List_Table
*/
class WP_MS_Sites_List_Table extends WP_List_Table {
/**
* Site status list.
*
* @since 4.3.0
* @var array
*/
public $status_list;
/**
* Constructor.
*
* @since 3.1.0
*
* @see WP_List_Table::__construct() for more information on default arguments.
*
* @param array $args An associative array of arguments.
*/
public function __construct( $args = array() ) {
$this->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 <span class="count">(%s)</span>',
'All <span class="count">(%s)</span>',
'sites'
),
/* translators: %s: Number of sites. */
'public' => _n_noop(
'Public <span class="count">(%s)</span>',
'Public <span class="count">(%s)</span>'
),
/* translators: %s: Number of sites. */
'archived' => _n_noop(
'Archived <span class="count">(%s)</span>',
'Archived <span class="count">(%s)</span>'
),
/* translators: %s: Number of sites. */
'mature' => _n_noop(
'Mature <span class="count">(%s)</span>',
'Mature <span class="count">(%s)</span>'
),
/* translators: %s: Number of sites. */
'spam' => _nx_noop(
'Spam <span class="count">(%s)</span>',
'Spam <span class="count">(%s)</span>',
'sites'
),
/* translators: %s: Number of sites. */
'deleted' => _n_noop(
'Deleted <span class="count">(%s)</span>',
'Deleted <span class="count">(%s)</span>'
),
);
$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 ) {
?>
<div class="alignleft actions">
<?php
if ( 'top' === $which ) {
ob_start();
/**
* Fires before the Filter button on the MS sites list table.
*
* @since 5.3.0
*
* @param string $which The location of the extra table nav markup: Either 'top' or 'bottom'.
*/
do_action( 'restrict_manage_sites', $which );
$output = ob_get_clean();
if ( ! empty( $output ) ) {
echo $output;
submit_button( __( 'Filter' ), '', 'filter_action', false, array( 'id' => 'site-query-submit' ) );
}
}
?>
</div>
<?php
/**
* Fires immediately following the closing "actions" div in the tablenav for the
* MS sites list table.
*
* @since 5.3.0
*
* @param string $which The location of the extra table nav markup: Either 'top' or 'bottom'.
*/
do_action( 'manage_sites_extra_tablenav', $which );
}
/**
* @return string[] Array of column titles keyed by their column name.
*/
public function get_columns() {
$sites_columns = array(
'cb' => '<input type="checkbox" />',
'blogname' => __( 'URL' ),
'lastupdated' => __( 'Last Updated' ),
'registered' => _x( 'Registered', 'site' ),
'users' => __( 'Users' ),
);
if ( has_filter( 'wpmublogsaction' ) ) {
$sites_columns['plugins'] = __( 'Actions' );
}
/**
* Filters the displayed site columns in Sites list table.
*
* @since MU (3.0.0)
*
* @param string[] $sites_columns An array of displayed site columns. Default 'cb',
* 'blogname', 'lastupdated', 'registered', 'users'.
*/
return apply_filters( 'wpmu_blogs_columns', $sites_columns );
}
/**
* @return array
*/
protected function get_sortable_columns() {
if ( is_subdomain_install() ) {
$blogname_abbr = __( 'Domain' );
$blogname_orderby_text = __( 'Table ordered by Site Domain Name.' );
} else {
$blogname_abbr = __( 'Path' );
$blogname_orderby_text = __( 'Table ordered by Site Path.' );
}
return array(
'blogname' => array( 'blogname', false, $blogname_abbr, $blogname_orderby_text ),
'lastupdated' => array( 'lastupdated', true, __( 'Last Updated' ), __( 'Table ordered by Last Updated.' ) ),
'registered' => array( 'blog_id', true, _x( 'Registered', 'site' ), __( 'Table ordered by Site Registered Date.' ), 'desc' ),
);
}
/**
* Handles the checkbox column output.
*
* @since 4.3.0
* @since 5.9.0 Renamed `$blog` to `$item` to match parent class for PHP 8 named parameter support.
*
* @param array $item Current site.
*/
public function column_cb( $item ) {
// Restores the more descriptive, specific name for use within this method.
$blog = $item;
if ( ! is_main_site( $blog['blog_id'] ) ) :
$blogname = untrailingslashit( $blog['domain'] . $blog['path'] );
?>
<input type="checkbox" id="blog_<?php echo $blog['blog_id']; ?>" name="allblogs[]" value="<?php echo esc_attr( $blog['blog_id'] ); ?>" />
<label for="blog_<?php echo $blog['blog_id']; ?>">
<span class="screen-reader-text">
<?php
/* translators: %s: Site URL. */
printf( __( 'Select %s' ), $blogname );
?>
</span>
</label>
<?php
endif;
}
/**
* Handles the ID column output.
*
* @since 4.4.0
*
* @param array $blog Current site.
*/
public function column_id( $blog ) {
echo $blog['blog_id'];
}
/**
* Handles the site name column output.
*
* @since 4.3.0
*
* @global string $mode List table view mode.
*
* @param array $blog Current site.
*/
public function column_blogname( $blog ) {
global $mode;
$blogname = untrailingslashit( $blog['domain'] . $blog['path'] );
?>
<strong>
<?php
printf(
'<a href="%1$s" class="edit">%2$s</a>',
esc_url( network_admin_url( 'site-info.php?id=' . $blog['blog_id'] ) ),
$blogname
);
$this->site_states( $blog );
?>
</strong>
<?php
if ( 'list' !== $mode ) {
switch_to_blog( $blog['blog_id'] );
echo '<p>';
printf(
/* translators: 1: Site title, 2: Site tagline. */
__( '%1$s &#8211; %2$s' ),
get_option( 'blogname' ),
'<em>' . get_option( 'blogdescription' ) . '</em>'
);
echo '</p>';
restore_current_blog();
}
}
/**
* Handles the lastupdated column output.
*
* @since 4.3.0
*
* @global string $mode List table view mode.
*
* @param array $blog Current site.
*/
public function column_lastupdated( $blog ) {
global $mode;
if ( 'list' === $mode ) {
$date = __( 'Y/m/d' );
} else {
$date = __( 'Y/m/d g:i:s a' );
}
if ( '0000-00-00 00:00:00' === $blog['last_updated'] ) {
_e( 'Never' );
} else {
echo mysql2date( $date, $blog['last_updated'] );
}
}
/**
* Handles the registered column output.
*
* @since 4.3.0
*
* @global string $mode List table view mode.
*
* @param array $blog Current site.
*/
public function column_registered( $blog ) {
global $mode;
if ( 'list' === $mode ) {
$date = __( 'Y/m/d' );
} else {
$date = __( 'Y/m/d g:i:s a' );
}
if ( '0000-00-00 00:00:00' === $blog['registered'] ) {
echo '&#x2014;';
} else {
echo mysql2date( $date, $blog['registered'] );
}
}
/**
* Handles the users column output.
*
* @since 4.3.0
*
* @param array $blog Current site.
*/
public function column_users( $blog ) {
$user_count = wp_cache_get( $blog['blog_id'] . '_user_count', 'blog-details' );
if ( ! $user_count ) {
$blog_users = new WP_User_Query(
array(
'blog_id' => $blog['blog_id'],
'fields' => 'ID',
'number' => 1,
'count_total' => true,
)
);
$user_count = $blog_users->get_total();
wp_cache_set( $blog['blog_id'] . '_user_count', $user_count, 'blog-details', 12 * HOUR_IN_SECONDS );
}
printf(
'<a href="%1$s">%2$s</a>',
esc_url( network_admin_url( 'site-users.php?id=' . $blog['blog_id'] ) ),
number_format_i18n( $user_count )
);
}
/**
* Handles the plugins column output.
*
* @since 4.3.0
*
* @param array $blog Current site.
*/
public function column_plugins( $blog ) {
if ( has_filter( 'wpmublogsaction' ) ) {
/**
* Fires inside the auxiliary 'Actions' column of the Sites list table.
*
* By default this column is hidden unless something is hooked to the action.
*
* @since MU (3.0.0)
*
* @param int $blog_id The site ID.
*/
do_action( 'wpmublogsaction', $blog['blog_id'] );
}
}
/**
* Handles output for the default column.
*
* @since 4.3.0
* @since 5.9.0 Renamed `$blog` to `$item` to match parent class for PHP 8 named parameter support.
*
* @param array $item Current site.
* @param string $column_name Current column name.
*/
public function column_default( $item, $column_name ) {
// Restores the more descriptive, specific name for use within this method.
$blog = $item;
/**
* Fires for each registered custom column in the Sites list table.
*
* @since 3.1.0
*
* @param string $column_name The name of the column to display.
* @param int $blog_id The site ID.
*/
do_action( 'manage_sites_custom_column', $column_name, $blog['blog_id'] );
}
/**
* @global string $mode List table view mode.
*/
public function display_rows() {
foreach ( $this->items as $blog ) {
$blog = $blog->to_array();
$class = '';
reset( $this->status_list );
foreach ( $this->status_list as $status => $col ) {
if ( '1' === $blog[ $status ] ) {
$class = " class='{$col[0]}'";
}
}
echo "<tr{$class}>";
$this->single_row_columns( $blog );
echo '</tr>';
}
}
/**
* Determines whether to output comma-separated site states.
*
* @since 5.3.0
*
* @param array $site
*/
protected function site_states( $site ) {
$site_states = array();
// $site is still an array, so get the object.
$_site = WP_Site::get_instance( $site['blog_id'] );
if ( is_main_site( $_site->id ) ) {
$site_states['main'] = __( 'Main' );
}
reset( $this->status_list );
$site_status = isset( $_REQUEST['status'] ) ? wp_unslash( trim( $_REQUEST['status'] ) ) : '';
foreach ( $this->status_list as $status => $col ) {
if ( '1' === $_site->{$status} && $site_status !== $status ) {
$site_states[ $col[0] ] = $col[1];
}
}
/**
* Filters the default site display states for items in the Sites list table.
*
* @since 5.3.0
*
* @param string[] $site_states An array of site states. Default 'Main',
* 'Archived', 'Mature', 'Spam', 'Deleted'.
* @param WP_Site $site The current site object.
*/
$site_states = apply_filters( 'display_site_states', $site_states, $_site );
if ( ! empty( $site_states ) ) {
$state_count = count( $site_states );
$i = 0;
echo ' &mdash; ';
foreach ( $site_states as $state ) {
++$i;
$separator = ( $i < $state_count ) ? ', ' : '';
echo "<span class='post-state'>{$state}{$separator}</span>";
}
}
}
/**
* Gets the name of the default primary column.
*
* @since 4.3.0
*
* @return string Name of the default primary column, in this case, 'blogname'.
*/
protected function get_default_primary_column_name() {
return 'blogname';
}
/**
* Generates and displays row action links.
*
* @since 4.3.0
* @since 5.9.0 Renamed `$blog` to `$item` to match parent class for PHP 8 named parameter support.
*
* @param array $item Site being acted upon.
* @param string $column_name Current column name.
* @param string $primary Primary column name.
* @return string Row actions output for sites in Multisite, or an empty string
* if the current column is not the primary column.
*/
protected function handle_row_actions( $item, $column_name, $primary ) {
if ( $primary !== $column_name ) {
return '';
}
// Restores the more descriptive, specific name for use within this method.
$blog = $item;
$blogname = untrailingslashit( $blog['domain'] . $blog['path'] );
// Preordered.
$actions = array(
'edit' => '',
'backend' => '',
'activate' => '',
'deactivate' => '',
'archive' => '',
'unarchive' => '',
'spam' => '',
'unspam' => '',
'delete' => '',
'visit' => '',
);
$actions['edit'] = sprintf(
'<a href="%1$s">%2$s</a>',
esc_url( network_admin_url( 'site-info.php?id=' . $blog['blog_id'] ) ),
__( 'Edit' )
);
$actions['backend'] = sprintf(
'<a href="%1$s" class="edit">%2$s</a>',
esc_url( get_admin_url( $blog['blog_id'] ) ),
__( 'Dashboard' )
);
if ( ! is_main_site( $blog['blog_id'] ) ) {
if ( '1' === $blog['deleted'] ) {
$actions['activate'] = sprintf(
'<a href="%1$s">%2$s</a>',
esc_url(
wp_nonce_url(
network_admin_url( 'sites.php?action=confirm&amp;action2=activateblog&amp;id=' . $blog['blog_id'] ),
'activateblog_' . $blog['blog_id']
)
),
_x( 'Activate', 'site' )
);
} else {
$actions['deactivate'] = sprintf(
'<a href="%1$s">%2$s</a>',
esc_url(
wp_nonce_url(
network_admin_url( 'sites.php?action=confirm&amp;action2=deactivateblog&amp;id=' . $blog['blog_id'] ),
'deactivateblog_' . $blog['blog_id']
)
),
__( 'Deactivate' )
);
}
if ( '1' === $blog['archived'] ) {
$actions['unarchive'] = sprintf(
'<a href="%1$s">%2$s</a>',
esc_url(
wp_nonce_url(
network_admin_url( 'sites.php?action=confirm&amp;action2=unarchiveblog&amp;id=' . $blog['blog_id'] ),
'unarchiveblog_' . $blog['blog_id']
)
),
__( 'Unarchive' )
);
} else {
$actions['archive'] = sprintf(
'<a href="%1$s">%2$s</a>',
esc_url(
wp_nonce_url(
network_admin_url( 'sites.php?action=confirm&amp;action2=archiveblog&amp;id=' . $blog['blog_id'] ),
'archiveblog_' . $blog['blog_id']
)
),
_x( 'Archive', 'verb; site' )
);
}
if ( '1' === $blog['spam'] ) {
$actions['unspam'] = sprintf(
'<a href="%1$s">%2$s</a>',
esc_url(
wp_nonce_url(
network_admin_url( 'sites.php?action=confirm&amp;action2=unspamblog&amp;id=' . $blog['blog_id'] ),
'unspamblog_' . $blog['blog_id']
)
),
_x( 'Not Spam', 'site' )
);
} else {
$actions['spam'] = sprintf(
'<a href="%1$s">%2$s</a>',
esc_url(
wp_nonce_url(
network_admin_url( 'sites.php?action=confirm&amp;action2=spamblog&amp;id=' . $blog['blog_id'] ),
'spamblog_' . $blog['blog_id']
)
),
_x( 'Spam', 'site' )
);
}
if ( current_user_can( 'delete_site', $blog['blog_id'] ) ) {
$actions['delete'] = sprintf(
'<a href="%1$s">%2$s</a>',
esc_url(
wp_nonce_url(
network_admin_url( 'sites.php?action=confirm&amp;action2=deleteblog&amp;id=' . $blog['blog_id'] ),
'deleteblog_' . $blog['blog_id']
)
),
__( 'Delete' )
);
}
}
$actions['visit'] = sprintf(
'<a href="%1$s" rel="bookmark">%2$s</a>',
esc_url( get_home_url( $blog['blog_id'], '/' ) ),
__( 'Visit' )
);
/**
* Filters the action links displayed for each site in the Sites list table.
*
* The 'Edit', 'Dashboard', 'Delete', and 'Visit' links are displayed by
* default for each site. The site's status determines whether to show the
* 'Activate' or 'Deactivate' link, 'Unarchive' or 'Archive' links, and
* 'Not Spam' or 'Spam' link for each site.
*
* @since 3.1.0
*
* @param string[] $actions An array of action links to be displayed.
* @param int $blog_id The site ID.
* @param string $blogname Site path, formatted depending on whether it is a sub-domain
* or subdirectory multisite installation.
*/
$actions = apply_filters( 'manage_sites_action_links', array_filter( $actions ), $blog['blog_id'], $blogname );
return $this->row_actions( $actions );
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,551 @@
<?php
/**
* List Table API: WP_MS_Users_List_Table class
*
* @package WordPress
* @subpackage Administration
* @since 3.1.0
*/
/**
* Core class used to implement displaying users in a list table for the network admin.
*
* @since 3.1.0
*
* @see WP_List_Table
*/
class WP_MS_Users_List_Table extends WP_List_Table {
/**
* @return bool
*/
public function ajax_user_can() {
return current_user_can( 'manage_network_users' );
}
/**
* @global string $mode List table view mode.
* @global string $usersearch
* @global string $role
*/
public function prepare_items() {
global $mode, $usersearch, $role;
if ( ! empty( $_REQUEST['mode'] ) ) {
$mode = 'excerpt' === $_REQUEST['mode'] ? 'excerpt' : 'list';
set_user_setting( 'network_users_list_mode', $mode );
} else {
$mode = get_user_setting( 'network_users_list_mode', 'list' );
}
$usersearch = isset( $_REQUEST['s'] ) ? wp_unslash( trim( $_REQUEST['s'] ) ) : '';
$users_per_page = $this->get_items_per_page( 'users_network_per_page' );
$role = isset( $_REQUEST['role'] ) ? $_REQUEST['role'] : '';
$paged = $this->get_pagenum();
$args = array(
'number' => $users_per_page,
'offset' => ( $paged - 1 ) * $users_per_page,
'search' => $usersearch,
'blog_id' => 0,
'fields' => 'all_with_meta',
);
if ( wp_is_large_network( 'users' ) ) {
$args['search'] = ltrim( $args['search'], '*' );
} elseif ( '' !== $args['search'] ) {
$args['search'] = trim( $args['search'], '*' );
$args['search'] = '*' . $args['search'] . '*';
}
if ( 'super' === $role ) {
$args['login__in'] = get_super_admins();
}
/*
* If the network is large and a search is not being performed,
* show only the latest users with no paging in order to avoid
* expensive count queries.
*/
if ( ! $usersearch && wp_is_large_network( 'users' ) ) {
if ( ! isset( $_REQUEST['orderby'] ) ) {
$_GET['orderby'] = 'id';
$_REQUEST['orderby'] = 'id';
}
if ( ! isset( $_REQUEST['order'] ) ) {
$_GET['order'] = 'DESC';
$_REQUEST['order'] = 'DESC';
}
$args['count_total'] = false;
}
if ( isset( $_REQUEST['orderby'] ) ) {
$args['orderby'] = $_REQUEST['orderby'];
}
if ( isset( $_REQUEST['order'] ) ) {
$args['order'] = $_REQUEST['order'];
}
/** This filter is documented in wp-admin/includes/class-wp-users-list-table.php */
$args = apply_filters( 'users_list_table_query_args', $args );
// Query the user IDs for this page.
$wp_user_search = new WP_User_Query( $args );
$this->items = $wp_user_search->get_results();
$this->set_pagination_args(
array(
'total_items' => $wp_user_search->get_total(),
'per_page' => $users_per_page,
)
);
}
/**
* @return array
*/
protected function get_bulk_actions() {
$actions = array();
if ( current_user_can( 'delete_users' ) ) {
$actions['delete'] = __( 'Delete' );
}
$actions['spam'] = _x( 'Mark as spam', 'user' );
$actions['notspam'] = _x( 'Not spam', 'user' );
return $actions;
}
/**
*/
public function no_items() {
_e( 'No users found.' );
}
/**
* @global string $role
* @return array
*/
protected function get_views() {
global $role;
$total_users = get_user_count();
$super_admins = get_super_admins();
$total_admins = count( $super_admins );
$role_links = array();
$role_links['all'] = array(
'url' => network_admin_url( 'users.php' ),
'label' => sprintf(
/* translators: Number of users. */
_nx(
'All <span class="count">(%s)</span>',
'All <span class="count">(%s)</span>',
$total_users,
'users'
),
number_format_i18n( $total_users )
),
'current' => 'super' !== $role,
);
$role_links['super'] = array(
'url' => network_admin_url( 'users.php?role=super' ),
'label' => sprintf(
/* translators: Number of users. */
_n(
'Super Admin <span class="count">(%s)</span>',
'Super Admins <span class="count">(%s)</span>',
$total_admins
),
number_format_i18n( $total_admins )
),
'current' => 'super' === $role,
);
return $this->get_views_links( $role_links );
}
/**
* @global string $mode List table view mode.
*
* @param string $which
*/
protected function pagination( $which ) {
global $mode;
parent::pagination( $which );
if ( 'top' === $which ) {
$this->view_switcher( $mode );
}
}
/**
* @return string[] Array of column titles keyed by their column name.
*/
public function get_columns() {
$users_columns = array(
'cb' => '<input type="checkbox" />',
'username' => __( 'Username' ),
'name' => __( 'Name' ),
'email' => __( 'Email' ),
'registered' => _x( 'Registered', 'user' ),
'blogs' => __( 'Sites' ),
);
/**
* Filters the columns displayed in the Network Admin Users list table.
*
* @since MU (3.0.0)
*
* @param string[] $users_columns An array of user columns. Default 'cb', 'username',
* 'name', 'email', 'registered', 'blogs'.
*/
return apply_filters( 'wpmu_users_columns', $users_columns );
}
/**
* @return array
*/
protected function get_sortable_columns() {
return array(
'username' => array( 'login', false, __( 'Username' ), __( 'Table ordered by Username.' ), 'asc' ),
'name' => array( 'name', false, __( 'Name' ), __( 'Table ordered by Name.' ) ),
'email' => array( 'email', false, __( 'E-mail' ), __( 'Table ordered by E-mail.' ) ),
'registered' => array( 'id', false, _x( 'Registered', 'user' ), __( 'Table ordered by User Registered Date.' ) ),
);
}
/**
* Handles the checkbox column output.
*
* @since 4.3.0
* @since 5.9.0 Renamed `$user` to `$item` to match parent class for PHP 8 named parameter support.
*
* @param WP_User $item The current WP_User object.
*/
public function column_cb( $item ) {
// Restores the more descriptive, specific name for use within this method.
$user = $item;
if ( is_super_admin( $user->ID ) ) {
return;
}
?>
<input type="checkbox" id="blog_<?php echo $user->ID; ?>" name="allusers[]" value="<?php echo esc_attr( $user->ID ); ?>" />
<label for="blog_<?php echo $user->ID; ?>">
<span class="screen-reader-text">
<?php
/* translators: Hidden accessibility text. %s: User login. */
printf( __( 'Select %s' ), $user->user_login );
?>
</span>
</label>
<?php
}
/**
* Handles the ID column output.
*
* @since 4.4.0
*
* @param WP_User $user The current WP_User object.
*/
public function column_id( $user ) {
echo $user->ID;
}
/**
* Handles the username column output.
*
* @since 4.3.0
*
* @param WP_User $user The current WP_User object.
*/
public function column_username( $user ) {
$super_admins = get_super_admins();
$avatar = get_avatar( $user->user_email, 32 );
echo $avatar;
if ( current_user_can( 'edit_user', $user->ID ) ) {
$edit_link = esc_url( add_query_arg( 'wp_http_referer', urlencode( wp_unslash( $_SERVER['REQUEST_URI'] ) ), get_edit_user_link( $user->ID ) ) );
$edit = "<a href=\"{$edit_link}\">{$user->user_login}</a>";
} else {
$edit = $user->user_login;
}
?>
<strong>
<?php
echo $edit;
if ( in_array( $user->user_login, $super_admins, true ) ) {
echo ' &mdash; ' . __( 'Super Admin' );
}
?>
</strong>
<?php
}
/**
* Handles the name column output.
*
* @since 4.3.0
*
* @param WP_User $user The current WP_User object.
*/
public function column_name( $user ) {
if ( $user->first_name && $user->last_name ) {
printf(
/* translators: 1: User's first name, 2: Last name. */
_x( '%1$s %2$s', 'Display name based on first name and last name' ),
$user->first_name,
$user->last_name
);
} elseif ( $user->first_name ) {
echo $user->first_name;
} elseif ( $user->last_name ) {
echo $user->last_name;
} else {
echo '<span aria-hidden="true">&#8212;</span><span class="screen-reader-text">' .
/* translators: Hidden accessibility text. */
_x( 'Unknown', 'name' ) .
'</span>';
}
}
/**
* Handles the email column output.
*
* @since 4.3.0
*
* @param WP_User $user The current WP_User object.
*/
public function column_email( $user ) {
echo "<a href='" . esc_url( "mailto:$user->user_email" ) . "'>$user->user_email</a>";
}
/**
* Handles the registered date column output.
*
* @since 4.3.0
*
* @global string $mode List table view mode.
*
* @param WP_User $user The current WP_User object.
*/
public function column_registered( $user ) {
global $mode;
if ( 'list' === $mode ) {
$date = __( 'Y/m/d' );
} else {
$date = __( 'Y/m/d g:i:s a' );
}
echo mysql2date( $date, $user->user_registered );
}
/**
* @since 4.3.0
*
* @param WP_User $user
* @param string $classes
* @param string $data
* @param string $primary
*/
protected function _column_blogs( $user, $classes, $data, $primary ) {
echo '<td class="', $classes, ' has-row-actions" ', $data, '>';
echo $this->column_blogs( $user );
echo $this->handle_row_actions( $user, 'blogs', $primary );
echo '</td>';
}
/**
* Handles the sites column output.
*
* @since 4.3.0
*
* @param WP_User $user The current WP_User object.
*/
public function column_blogs( $user ) {
$blogs = get_blogs_of_user( $user->ID, true );
if ( ! is_array( $blogs ) ) {
return;
}
foreach ( $blogs as $site ) {
if ( ! can_edit_network( $site->site_id ) ) {
continue;
}
$path = ( '/' === $site->path ) ? '' : $site->path;
$site_classes = array( 'site-' . $site->site_id );
/**
* Filters the span class for a site listing on the multisite user list table.
*
* @since 5.2.0
*
* @param string[] $site_classes Array of class names used within the span tag.
* Default "site-#" with the site's network ID.
* @param int $site_id Site ID.
* @param int $network_id Network ID.
* @param WP_User $user WP_User object.
*/
$site_classes = apply_filters( 'ms_user_list_site_class', $site_classes, $site->userblog_id, $site->site_id, $user );
if ( is_array( $site_classes ) && ! empty( $site_classes ) ) {
$site_classes = array_map( 'sanitize_html_class', array_unique( $site_classes ) );
echo '<span class="' . esc_attr( implode( ' ', $site_classes ) ) . '">';
} else {
echo '<span>';
}
echo '<a href="' . esc_url( network_admin_url( 'site-info.php?id=' . $site->userblog_id ) ) . '">' . str_replace( '.' . get_network()->domain, '', $site->domain . $path ) . '</a>';
echo ' <small class="row-actions">';
$actions = array();
$actions['edit'] = '<a href="' . esc_url( network_admin_url( 'site-info.php?id=' . $site->userblog_id ) ) . '">' . __( 'Edit' ) . '</a>';
$class = '';
if ( 1 === (int) $site->spam ) {
$class .= 'site-spammed ';
}
if ( 1 === (int) $site->mature ) {
$class .= 'site-mature ';
}
if ( 1 === (int) $site->deleted ) {
$class .= 'site-deleted ';
}
if ( 1 === (int) $site->archived ) {
$class .= 'site-archived ';
}
$actions['view'] = '<a class="' . $class . '" href="' . esc_url( get_home_url( $site->userblog_id ) ) . '">' . __( 'View' ) . '</a>';
/**
* Filters the action links displayed next the sites a user belongs to
* in the Network Admin Users list table.
*
* @since 3.1.0
*
* @param string[] $actions An array of action links to be displayed. Default 'Edit', 'View'.
* @param int $userblog_id The site ID.
*/
$actions = apply_filters( 'ms_user_list_site_actions', $actions, $site->userblog_id );
$action_count = count( $actions );
$i = 0;
foreach ( $actions as $action => $link ) {
++$i;
$separator = ( $i < $action_count ) ? ' | ' : '';
echo "<span class='$action'>{$link}{$separator}</span>";
}
echo '</small></span><br />';
}
}
/**
* Handles the default column output.
*
* @since 4.3.0
* @since 5.9.0 Renamed `$user` to `$item` to match parent class for PHP 8 named parameter support.
*
* @param WP_User $item The current WP_User object.
* @param string $column_name The current column name.
*/
public function column_default( $item, $column_name ) {
// Restores the more descriptive, specific name for use within this method.
$user = $item;
/** This filter is documented in wp-admin/includes/class-wp-users-list-table.php */
echo apply_filters( 'manage_users_custom_column', '', $column_name, $user->ID );
}
public function display_rows() {
foreach ( $this->items as $user ) {
$class = '';
$status_list = array(
'spam' => 'site-spammed',
'deleted' => 'site-deleted',
);
foreach ( $status_list as $status => $col ) {
if ( $user->$status ) {
$class .= " $col";
}
}
?>
<tr class="<?php echo trim( $class ); ?>">
<?php $this->single_row_columns( $user ); ?>
</tr>
<?php
}
}
/**
* Gets the name of the default primary column.
*
* @since 4.3.0
*
* @return string Name of the default primary column, in this case, 'username'.
*/
protected function get_default_primary_column_name() {
return 'username';
}
/**
* Generates and displays row action links.
*
* @since 4.3.0
* @since 5.9.0 Renamed `$user` to `$item` to match parent class for PHP 8 named parameter support.
*
* @param WP_User $item User being acted upon.
* @param string $column_name Current column name.
* @param string $primary Primary column name.
* @return string Row actions output for users in Multisite, or an empty string
* if the current column is not the primary column.
*/
protected function handle_row_actions( $item, $column_name, $primary ) {
if ( $primary !== $column_name ) {
return '';
}
// Restores the more descriptive, specific name for use within this method.
$user = $item;
$super_admins = get_super_admins();
$actions = array();
if ( current_user_can( 'edit_user', $user->ID ) ) {
$edit_link = esc_url( add_query_arg( 'wp_http_referer', urlencode( wp_unslash( $_SERVER['REQUEST_URI'] ) ), get_edit_user_link( $user->ID ) ) );
$actions['edit'] = '<a href="' . $edit_link . '">' . __( 'Edit' ) . '</a>';
}
if ( current_user_can( 'delete_user', $user->ID ) && ! in_array( $user->user_login, $super_admins, true ) ) {
$actions['delete'] = '<a href="' . esc_url( network_admin_url( add_query_arg( '_wp_http_referer', urlencode( wp_unslash( $_SERVER['REQUEST_URI'] ) ), wp_nonce_url( 'users.php', 'deleteuser' ) . '&amp;action=deleteuser&amp;id=' . $user->ID ) ) ) . '" class="delete">' . __( 'Delete' ) . '</a>';
}
/**
* Filters the action links displayed under each user in the Network Admin Users list table.
*
* @since 3.2.0
*
* @param string[] $actions An array of action links to be displayed. Default 'Edit', 'Delete'.
* @param WP_User $user WP_User object.
*/
$actions = apply_filters( 'ms_user_row_actions', $actions, $user );
return $this->row_actions( $actions );
}
}

View File

@ -0,0 +1,828 @@
<?php
/**
* List Table API: WP_Plugin_Install_List_Table class
*
* @package WordPress
* @subpackage Administration
* @since 3.1.0
*/
/**
* Core class used to implement displaying plugins to install in a list table.
*
* @since 3.1.0
*
* @see WP_List_Table
*/
class WP_Plugin_Install_List_Table extends WP_List_Table {
public $order = 'ASC';
public $orderby = null;
public $groups = array();
private $error;
/**
* @return bool
*/
public function ajax_user_can() {
return current_user_can( 'install_plugins' );
}
/**
* Returns the list of known plugins.
*
* Uses the transient data from the updates API to determine the known
* installed plugins.
*
* @since 4.9.0
* @access protected
*
* @return array
*/
protected function get_installed_plugins() {
$plugins = array();
$plugin_info = get_site_transient( 'update_plugins' );
if ( isset( $plugin_info->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;
wp_reset_vars( array( '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 = '<p>' . $this->error->get_error_message() . '</p>';
$error_message .= '<p class="hide-if-no-js"><button class="button try-again">' . __( 'Try Again' ) . '</button></p>';
wp_admin_notice(
$error_message,
array(
'additional_classes' => array( 'inline', 'error' ),
'paragraph_wrap' => false,
)
);
?>
<?php } else { ?>
<div class="no-plugin-results"><?php _e( 'No plugins found. Try a different search.' ); ?></div>
<?php
}
}
/**
* @global array $tabs
* @global string $tab
*
* @return array
*/
protected function get_views() {
global $tabs, $tab;
$display_tabs = array();
foreach ( (array) $tabs as $action => $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' );
?>
<div class="wp-filter">
<ul class="filter-links">
<?php
if ( ! empty( $views ) ) {
foreach ( $views as $class => $view ) {
$views[ $class ] = "\t<li class='$class'>$view";
}
echo implode( " </li>\n", $views ) . "</li>\n";
}
?>
</ul>
<?php install_search_form(); ?>
</div>
<?php
}
/**
* Displays the plugin install table.
*
* Overrides the parent display() method to provide a different container.
*
* @since 4.0.0
*/
public function display() {
$singular = $this->_args['singular'];
$data_attr = '';
if ( $singular ) {
$data_attr = " data-wp-lists='list:$singular'";
}
$this->display_tablenav( 'top' );
?>
<div class="wp-list-table <?php echo implode( ' ', $this->get_table_classes() ); ?>">
<?php
$this->screen->render_screen_reader_content( 'heading_list' );
?>
<div id="the-list"<?php echo $data_attr; ?>>
<?php $this->display_rows_or_placeholder(); ?>
</div>
</div>
<?php
$this->display_tablenav( 'bottom' );
}
/**
* @global string $tab
*
* @param string $which
*/
protected function display_tablenav( $which ) {
if ( 'featured' === $GLOBALS['tab'] ) {
return;
}
if ( 'top' === $which ) {
wp_referer_field();
?>
<div class="tablenav top">
<div class="alignleft actions">
<?php
/**
* Fires before the Plugin Install table header pagination is displayed.
*
* @since 2.7.0
*/
do_action( 'install_plugins_table_header' );
?>
</div>
<?php $this->pagination( $which ); ?>
<br class="clear" />
</div>
<?php } else { ?>
<div class="tablenav bottom">
<?php $this->pagination( $which ); ?>
<br class="clear" />
</div>
<?php
}
}
/**
* @return array
*/
protected function get_table_classes() {
return array( 'widefat', $this->_args['plural'] );
}
/**
* @return string[] Array of column titles keyed by their column name.
*/
public function get_columns() {
return array();
}
/**
* @param object $plugin_a
* @param object $plugin_b
* @return int
*/
private function order_callback( $plugin_a, $plugin_b ) {
$orderby = $this->orderby;
if ( ! isset( $plugin_a->$orderby, $plugin_b->$orderby ) ) {
return 0;
}
$a = $plugin_a->$orderby;
$b = $plugin_b->$orderby;
if ( $a === $b ) {
return 0;
}
if ( 'DESC' === $this->order ) {
return ( $a < $b ) ? 1 : -1;
} else {
return ( $a < $b ) ? -1 : 1;
}
}
public function display_rows() {
$plugins_allowedtags = array(
'a' => array(
'href' => array(),
'title' => array(),
'target' => array(),
),
'abbr' => array( 'title' => array() ),
'acronym' => array( 'title' => array() ),
'code' => array(),
'pre' => array(),
'em' => array(),
'strong' => array(),
'ul' => array(),
'ol' => array(),
'li' => array(),
'p' => array(),
'br' => array(),
);
$plugins_group_titles = array(
'Performance' => _x( 'Performance', 'Plugin installer group title' ),
'Social' => _x( 'Social', 'Plugin installer group title' ),
'Tools' => _x( 'Tools', 'Plugin installer group title' ),
);
$group = null;
foreach ( (array) $this->items as $plugin ) {
if ( is_object( $plugin ) ) {
$plugin = (array) $plugin;
}
// Display the group heading if there is one.
if ( isset( $plugin['group'] ) && $plugin['group'] !== $group ) {
if ( isset( $this->groups[ $plugin['group'] ] ) ) {
$group_name = $this->groups[ $plugin['group'] ];
if ( isset( $plugins_group_titles[ $group_name ] ) ) {
$group_name = $plugins_group_titles[ $group_name ];
}
} else {
$group_name = $plugin['group'];
}
// Starting a new group, close off the divs of the last one.
if ( ! empty( $group ) ) {
echo '</div></div>';
}
echo '<div class="plugin-group"><h3>' . esc_html( $group_name ) . '</h3>';
// Needs an extra wrapping div for nth-child selectors to work.
echo '<div class="plugin-items">';
$group = $plugin['group'];
}
$title = wp_kses( $plugin['name'], $plugins_allowedtags );
// Remove any HTML from the description.
$description = strip_tags( $plugin['short_description'] );
/**
* Filters the plugin card description on the Add Plugins screen.
*
* @since 6.0.0
*
* @param string $description Plugin card description.
* @param array $plugin An array of plugin data. See {@see plugins_api()}
* for the list of possible values.
*/
$description = apply_filters( 'plugin_install_description', $description, $plugin );
$version = wp_kses( $plugin['version'], $plugins_allowedtags );
$name = strip_tags( $title . ' ' . $version );
$author = wp_kses( $plugin['author'], $plugins_allowedtags );
if ( ! empty( $author ) ) {
/* translators: %s: Plugin author. */
$author = ' <cite>' . sprintf( __( 'By %s' ), $author ) . '</cite>';
}
$requires_php = isset( $plugin['requires_php'] ) ? $plugin['requires_php'] : null;
$requires_wp = isset( $plugin['requires'] ) ? $plugin['requires'] : null;
$compatible_php = is_php_version_compatible( $requires_php );
$compatible_wp = is_wp_version_compatible( $requires_wp );
$tested_wp = ( empty( $plugin['tested'] ) || version_compare( get_bloginfo( 'version' ), $plugin['tested'], '<=' ) );
$action_links = array();
$action_links[] = wp_get_plugin_action_button( $name, $plugin, $compatible_php, $compatible_wp );
$details_link = self_admin_url(
'plugin-install.php?tab=plugin-information&amp;plugin=' . $plugin['slug'] .
'&amp;TB_iframe=true&amp;width=600&amp;height=550'
);
$action_links[] = sprintf(
'<a href="%s" class="thickbox open-plugin-details-modal" aria-label="%s" data-title="%s">%s</a>',
esc_url( $details_link ),
/* translators: %s: Plugin name and version. */
esc_attr( sprintf( __( 'More information about %s' ), $name ) ),
esc_attr( $name ),
__( 'More Details' )
);
if ( ! empty( $plugin['icons']['svg'] ) ) {
$plugin_icon_url = $plugin['icons']['svg'];
} elseif ( ! empty( $plugin['icons']['2x'] ) ) {
$plugin_icon_url = $plugin['icons']['2x'];
} elseif ( ! empty( $plugin['icons']['1x'] ) ) {
$plugin_icon_url = $plugin['icons']['1x'];
} else {
$plugin_icon_url = $plugin['icons']['default'];
}
/**
* Filters the install action links for a plugin.
*
* @since 2.7.0
*
* @param string[] $action_links An array of plugin action links.
* Defaults are links to Details and Install Now.
* @param array $plugin An array of plugin data. See {@see plugins_api()}
* for the list of possible values.
*/
$action_links = apply_filters( 'plugin_install_action_links', $action_links, $plugin );
$last_updated_timestamp = strtotime( $plugin['last_updated'] );
?>
<div class="plugin-card plugin-card-<?php echo sanitize_html_class( $plugin['slug'] ); ?>">
<?php
if ( ! $compatible_php || ! $compatible_wp ) {
$incompatible_notice_message = '';
if ( ! $compatible_php && ! $compatible_wp ) {
$incompatible_notice_message .= __( 'This plugin does not work with your versions of WordPress and PHP.' );
if ( current_user_can( 'update_core' ) && current_user_can( 'update_php' ) ) {
$incompatible_notice_message .= sprintf(
/* translators: 1: URL to WordPress Updates screen, 2: URL to Update PHP page. */
' ' . __( '<a href="%1$s">Please update WordPress</a>, and then <a href="%2$s">learn more about updating PHP</a>.' ),
self_admin_url( 'update-core.php' ),
esc_url( wp_get_update_php_url() )
);
$incompatible_notice_message .= wp_update_php_annotation( '</p><p><em>', '</em>', false );
} elseif ( current_user_can( 'update_core' ) ) {
$incompatible_notice_message .= sprintf(
/* translators: %s: URL to WordPress Updates screen. */
' ' . __( '<a href="%s">Please update WordPress</a>.' ),
self_admin_url( 'update-core.php' )
);
} elseif ( current_user_can( 'update_php' ) ) {
$incompatible_notice_message .= sprintf(
/* translators: %s: URL to Update PHP page. */
' ' . __( '<a href="%s">Learn more about updating PHP</a>.' ),
esc_url( wp_get_update_php_url() )
);
$incompatible_notice_message .= wp_update_php_annotation( '</p><p><em>', '</em>', 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 .= printf(
/* translators: %s: URL to WordPress Updates screen. */
' ' . __( '<a href="%s">Please update WordPress</a>.' ),
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. */
' ' . __( '<a href="%s">Learn more about updating PHP</a>.' ),
esc_url( wp_get_update_php_url() )
);
$incompatible_notice_message .= wp_update_php_annotation( '</p><p><em>', '</em>', false );
}
}
wp_admin_notice(
$incompatible_notice_message,
array(
'type' => 'error',
'additional_classes' => array( 'notice-alt', 'inline' ),
)
);
}
?>
<div class="plugin-card-top">
<div class="name column-name">
<h3>
<a href="<?php echo esc_url( $details_link ); ?>" class="thickbox open-plugin-details-modal">
<?php echo $title; ?>
<img src="<?php echo esc_url( $plugin_icon_url ); ?>" class="plugin-icon" alt="" />
</a>
</h3>
</div>
<div class="action-links">
<?php
if ( $action_links ) {
echo '<ul class="plugin-action-buttons"><li>' . implode( '</li><li>', $action_links ) . '</li></ul>';
}
?>
</div>
<div class="desc column-description">
<p><?php echo $description; ?></p>
<p class="authors"><?php echo $author; ?></p>
</div>
</div>
<?php
$dependencies_notice = $this->get_dependencies_notice( $plugin );
if ( ! empty( $dependencies_notice ) ) {
echo $dependencies_notice;
}
?>
<div class="plugin-card-bottom">
<div class="vers column-rating">
<?php
wp_star_rating(
array(
'rating' => $plugin['rating'],
'type' => 'percent',
'number' => $plugin['num_ratings'],
)
);
?>
<span class="num-ratings" aria-hidden="true">(<?php echo number_format_i18n( $plugin['num_ratings'] ); ?>)</span>
</div>
<div class="column-updated">
<strong><?php _e( 'Last Updated:' ); ?></strong>
<?php
/* translators: %s: Human-readable time difference. */
printf( __( '%s ago' ), human_time_diff( $last_updated_timestamp ) );
?>
</div>
<div class="column-downloaded">
<?php
if ( $plugin['active_installs'] >= 1000000 ) {
$active_installs_millions = floor( $plugin['active_installs'] / 1000000 );
$active_installs_text = sprintf(
/* translators: %s: Number of millions. */
_nx( '%s+ Million', '%s+ Million', $active_installs_millions, 'Active plugin installations' ),
number_format_i18n( $active_installs_millions )
);
} elseif ( 0 === $plugin['active_installs'] ) {
$active_installs_text = _x( 'Less Than 10', 'Active plugin installations' );
} else {
$active_installs_text = number_format_i18n( $plugin['active_installs'] ) . '+';
}
/* translators: %s: Number of installations. */
printf( __( '%s Active Installations' ), $active_installs_text );
?>
</div>
<div class="column-compatibility">
<?php
if ( ! $tested_wp ) {
echo '<span class="compatibility-untested">' . __( 'Untested with your version of WordPress' ) . '</span>';
} elseif ( ! $compatible_wp ) {
echo '<span class="compatibility-incompatible">' . __( '<strong>Incompatible</strong> with your version of WordPress' ) . '</span>';
} else {
echo '<span class="compatibility-compatible">' . __( '<strong>Compatible</strong> with your version of WordPress' ) . '</span>';
}
?>
</div>
</div>
</div>
<?php
}
// Close off the group divs of the last one.
if ( ! empty( $group ) ) {
echo '</div></div>';
}
}
/**
* Returns a notice containing a list of dependencies required by the plugin.
*
* @since 6.5.0
*
* @param array $plugin_data An array of plugin data. See {@see plugins_api()}
* for the list of possible values.
* @return string A notice containing a list of dependencies required by the plugin,
* or an empty string if none is required.
*/
protected function get_dependencies_notice( $plugin_data ) {
if ( empty( $plugin_data['requires_plugins'] ) ) {
return '';
}
$no_name_markup = '<div class="plugin-dependency"><span class="plugin-dependency-name">%s</span></div>';
$has_name_markup = '<div class="plugin-dependency"><span class="plugin-dependency-name">%s</span> %s</div>';
$dependencies_list = '';
foreach ( $plugin_data['requires_plugins'] as $dependency ) {
$dependency_data = WP_Plugin_Dependencies::get_dependency_data( $dependency );
if (
false !== $dependency_data &&
! empty( $dependency_data['name'] ) &&
! empty( $dependency_data['slug'] ) &&
! empty( $dependency_data['version'] )
) {
$more_details_link = $this->get_more_details_link( $dependency_data['name'], $dependency_data['slug'] );
$dependencies_list .= sprintf( $has_name_markup, esc_html( $dependency_data['name'] ), $more_details_link );
continue;
}
$result = plugins_api( 'plugin_information', array( 'slug' => $dependency ) );
if ( ! empty( $result->name ) ) {
$more_details_link = $this->get_more_details_link( $result->name, $result->slug );
$dependencies_list .= sprintf( $has_name_markup, esc_html( $result->name ), $more_details_link );
continue;
}
$dependencies_list .= sprintf( $no_name_markup, esc_html( $dependency ) );
}
$dependencies_notice = sprintf(
'<div class="plugin-dependencies notice notice-alt notice-info inline"><p class="plugin-dependencies-explainer-text">%s</p> %s</div>',
'<strong>' . __( 'Additional plugins are required' ) . '</strong>',
$dependencies_list
);
return $dependencies_notice;
}
/**
* Creates a 'More details' link for the plugin.
*
* @since 6.5.0
*
* @param string $name The plugin's name.
* @param string $slug The plugin's slug.
* @return string The 'More details' link for the plugin.
*/
protected function get_more_details_link( $name, $slug ) {
$url = add_query_arg(
array(
'tab' => 'plugin-information',
'plugin' => $slug,
'TB_iframe' => 'true',
'width' => '600',
'height' => '550',
),
network_admin_url( 'plugin-install.php' )
);
$more_details_link = sprintf(
'<a href="%1$s" class="more-details-link thickbox open-plugin-details-modal" aria-label="%2$s" data-title="%3$s">%4$s</a>',
esc_url( $url ),
/* translators: %s: Plugin name. */
sprintf( __( 'More information about %s' ), esc_html( $name ) ),
esc_attr( $name ),
__( 'More Details' )
);
return $more_details_link;
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,77 @@
<?php
/**
* List Table API: WP_Post_Comments_List_Table class
*
* @package WordPress
* @subpackage Administration
* @since 4.4.0
*/
/**
* Core class used to implement displaying post comments in a list table.
*
* @since 3.1.0
*
* @see WP_Comments_List_Table
*/
class WP_Post_Comments_List_Table extends WP_Comments_List_Table {
/**
* @return array
*/
protected function get_column_info() {
return array(
array(
'author' => __( 'Author' ),
'comment' => _x( 'Comment', 'column name' ),
),
array(),
array(),
'comment',
);
}
/**
* @return array
*/
protected function get_table_classes() {
$classes = parent::get_table_classes();
$classes[] = 'wp-list-table';
$classes[] = 'comments-box';
return $classes;
}
/**
* @param bool $output_empty
*/
public function display( $output_empty = false ) {
$singular = $this->_args['singular'];
wp_nonce_field( 'fetch-list-' . get_class( $this ), '_ajax_fetch_list_nonce' );
?>
<table class="<?php echo implode( ' ', $this->get_table_classes() ); ?>" style="display:none;">
<tbody id="the-comment-list"
<?php
if ( $singular ) {
echo " data-wp-lists='list:$singular'";
}
?>
>
<?php
if ( ! $output_empty ) {
$this->display_rows_or_placeholder();
}
?>
</tbody>
</table>
<?php
}
/**
* @param bool $comment_status
* @return int
*/
public function get_per_page( $comment_status = false ) {
return 10;
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,160 @@
<?php
/**
* List Table API: WP_Privacy_Data_Export_Requests_List_Table class
*
* @package WordPress
* @subpackage Administration
* @since 4.9.6
*/
if ( ! class_exists( 'WP_Privacy_Requests_Table' ) ) {
require_once ABSPATH . 'wp-admin/includes/class-wp-privacy-requests-table.php';
}
/**
* WP_Privacy_Data_Export_Requests_Table class.
*
* @since 4.9.6
*/
class WP_Privacy_Data_Export_Requests_List_Table extends WP_Privacy_Requests_Table {
/**
* Action name for the requests this table will work with.
*
* @since 4.9.6
*
* @var string $request_type Name of action.
*/
protected $request_type = 'export_personal_data';
/**
* Post type for the requests.
*
* @since 4.9.6
*
* @var string $post_type The post type.
*/
protected $post_type = 'user_request';
/**
* Actions column.
*
* @since 4.9.6
*
* @param WP_User_Request $item Item being shown.
* @return string Email column markup.
*/
public function column_email( $item ) {
/** This filter is documented in wp-admin/includes/ajax-actions.php */
$exporters = apply_filters( 'wp_privacy_personal_data_exporters', array() );
$exporters_count = count( $exporters );
$status = $item->status;
$request_id = $item->ID;
$nonce = wp_create_nonce( 'wp-privacy-export-personal-data-' . $request_id );
$download_data_markup = '<span class="export-personal-data" ' .
'data-exporters-count="' . esc_attr( $exporters_count ) . '" ' .
'data-request-id="' . esc_attr( $request_id ) . '" ' .
'data-nonce="' . esc_attr( $nonce ) .
'">';
$download_data_markup .= '<span class="export-personal-data-idle"><button type="button" class="button-link export-personal-data-handle">' . __( 'Download personal data' ) . '</button></span>' .
'<span class="export-personal-data-processing hidden">' . __( 'Downloading data...' ) . ' <span class="export-progress"></span></span>' .
'<span class="export-personal-data-success hidden"><button type="button" class="button-link export-personal-data-handle">' . __( 'Download personal data again' ) . '</button></span>' .
'<span class="export-personal-data-failed hidden">' . __( 'Download failed.' ) . ' <button type="button" class="button-link export-personal-data-handle">' . __( 'Retry' ) . '</button></span>';
$download_data_markup .= '</span>';
$row_actions['download-data'] = $download_data_markup;
if ( 'request-completed' !== $status ) {
$complete_request_markup = '<span>';
$complete_request_markup .= sprintf(
'<a href="%s" class="complete-request" aria-label="%s">%s</a>',
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 &#8220;%s&#8221; as completed.' ),
$item->email
)
),
__( 'Complete request' )
);
$complete_request_markup .= '</span>';
}
if ( ! empty( $complete_request_markup ) ) {
$row_actions['complete-request'] = $complete_request_markup;
}
return sprintf( '<a href="%1$s">%2$s</a> %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 '<div class="export-personal-data" ' .
'data-send-as-email="1" ' .
'data-exporters-count="' . esc_attr( $exporters_count ) . '" ' .
'data-request-id="' . esc_attr( $request_id ) . '" ' .
'data-nonce="' . esc_attr( $nonce ) .
'">';
?>
<span class="export-personal-data-idle"><button type="button" class="button-link export-personal-data-handle"><?php _e( 'Send export link' ); ?></button></span>
<span class="export-personal-data-processing hidden"><?php _e( 'Sending email...' ); ?> <span class="export-progress"></span></span>
<span class="export-personal-data-success success-message hidden"><?php _e( 'Email sent.' ); ?></span>
<span class="export-personal-data-failed hidden"><?php _e( 'Email could not be sent.' ); ?> <button type="button" class="button-link export-personal-data-handle"><?php _e( 'Retry' ); ?></button></span>
<?php
echo '</div>';
break;
case 'request-failed':
echo '<button type="submit" class="button-link" name="privacy_action_email_retry[' . $item->ID . ']" id="privacy_action_email_retry[' . $item->ID . ']">' . __( 'Retry' ) . '</button>';
break;
case 'request-completed':
echo '<a href="' . esc_url(
wp_nonce_url(
add_query_arg(
array(
'action' => 'delete',
'request_id' => array( $item->ID ),
),
admin_url( 'export-personal-data.php' )
),
'bulk-privacy_requests'
)
) . '">' . esc_html__( 'Remove request' ) . '</a>';
break;
}
}
}

View File

@ -0,0 +1,167 @@
<?php
/**
* List Table API: WP_Privacy_Data_Removal_Requests_List_Table class
*
* @package WordPress
* @subpackage Administration
* @since 4.9.6
*/
if ( ! class_exists( 'WP_Privacy_Requests_Table' ) ) {
require_once ABSPATH . 'wp-admin/includes/class-wp-privacy-requests-table.php';
}
/**
* WP_Privacy_Data_Removal_Requests_List_Table class.
*
* @since 4.9.6
*/
class WP_Privacy_Data_Removal_Requests_List_Table extends WP_Privacy_Requests_Table {
/**
* Action name for the requests this table will work with.
*
* @since 4.9.6
*
* @var string $request_type Name of action.
*/
protected $request_type = 'remove_personal_data';
/**
* Post type for the requests.
*
* @since 4.9.6
*
* @var string $post_type The post type.
*/
protected $post_type = 'user_request';
/**
* Outputs the Actions column.
*
* @since 4.9.6
*
* @param WP_User_Request $item Item being shown.
* @return string Email column markup.
*/
public function column_email( $item ) {
$row_actions = array();
// Allow the administrator to "force remove" the personal data even if confirmation has not yet been received.
$status = $item->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 = '<span class="remove-personal-data force-remove-personal-data" ' .
'data-erasers-count="' . esc_attr( $erasers_count ) . '" ' .
'data-request-id="' . esc_attr( $request_id ) . '" ' .
'data-nonce="' . esc_attr( $nonce ) .
'">';
$remove_data_markup .= '<span class="remove-personal-data-idle"><button type="button" class="button-link remove-personal-data-handle">' . __( 'Force erase personal data' ) . '</button></span>' .
'<span class="remove-personal-data-processing hidden">' . __( 'Erasing data...' ) . ' <span class="erasure-progress"></span></span>' .
'<span class="remove-personal-data-success hidden">' . __( 'Erasure completed.' ) . '</span>' .
'<span class="remove-personal-data-failed hidden">' . __( 'Force erasure has failed.' ) . ' <button type="button" class="button-link remove-personal-data-handle">' . __( 'Retry' ) . '</button></span>';
$remove_data_markup .= '</span>';
$row_actions['remove-data'] = $remove_data_markup;
}
if ( 'request-completed' !== $status ) {
$complete_request_markup = '<span>';
$complete_request_markup .= sprintf(
'<a href="%s" class="complete-request" aria-label="%s">%s</a>',
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 &#8220;%s&#8221; as completed.' ),
$item->email
)
),
__( 'Complete request' )
);
$complete_request_markup .= '</span>';
}
if ( ! empty( $complete_request_markup ) ) {
$row_actions['complete-request'] = $complete_request_markup;
}
return sprintf( '<a href="%1$s">%2$s</a> %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 '<div class="remove-personal-data" ' .
'data-force-erase="1" ' .
'data-erasers-count="' . esc_attr( $erasers_count ) . '" ' .
'data-request-id="' . esc_attr( $request_id ) . '" ' .
'data-nonce="' . esc_attr( $nonce ) .
'">';
?>
<span class="remove-personal-data-idle"><button type="button" class="button-link remove-personal-data-handle"><?php _e( 'Erase personal data' ); ?></button></span>
<span class="remove-personal-data-processing hidden"><?php _e( 'Erasing data...' ); ?> <span class="erasure-progress"></span></span>
<span class="remove-personal-data-success success-message hidden" ><?php _e( 'Erasure completed.' ); ?></span>
<span class="remove-personal-data-failed hidden"><?php _e( 'Data erasure has failed.' ); ?> <button type="button" class="button-link remove-personal-data-handle"><?php _e( 'Retry' ); ?></button></span>
<?php
echo '</div>';
break;
case 'request-failed':
echo '<button type="submit" class="button-link" name="privacy_action_email_retry[' . $item->ID . ']" id="privacy_action_email_retry[' . $item->ID . ']">' . __( 'Retry' ) . '</button>';
break;
case 'request-completed':
echo '<a href="' . esc_url(
wp_nonce_url(
add_query_arg(
array(
'action' => 'delete',
'request_id' => array( $item->ID ),
),
admin_url( 'erase-personal-data.php' )
),
'bulk-privacy_requests'
)
) . '">' . esc_html__( 'Remove request' ) . '</a>';
break;
}
}
}

View File

@ -0,0 +1,706 @@
<?php
/**
* WP_Privacy_Policy_Content class.
*
* @package WordPress
* @subpackage Administration
* @since 4.9.6
*/
#[AllowDynamicProperties]
final class WP_Privacy_Policy_Content {
private static $policy_content = array();
/**
* Constructor
*
* @since 4.9.6
*/
private function __construct() {}
/**
* Adds content to the postbox shown when editing the privacy policy.
*
* Plugins and themes should suggest text for inclusion in the site's privacy policy.
* The suggested text should contain information about any functionality that affects user privacy,
* and will be shown in the Suggested Privacy Policy Content postbox.
*
* Intended for use from `wp_add_privacy_policy_content()`.
*
* @since 4.9.6
*
* @param string $plugin_name The name of the plugin or theme that is suggesting content for the site's privacy policy.
* @param string $policy_text The suggested content for inclusion in the policy.
*/
public static function add( $plugin_name, $policy_text ) {
if ( empty( $plugin_name ) || empty( $policy_text ) ) {
return;
}
$data = array(
'plugin_name' => $plugin_name,
'policy_text' => $policy_text,
);
if ( ! in_array( $data, self::$policy_content, true ) ) {
self::$policy_content[] = $data;
}
}
/**
* Performs a quick check to determine whether any privacy info has changed.
*
* @since 4.9.6
*/
public static function text_change_check() {
$policy_page_id = (int) get_option( 'wp_page_for_privacy_policy' );
// The site doesn't have a privacy policy.
if ( empty( $policy_page_id ) ) {
return false;
}
if ( ! current_user_can( 'edit_post', $policy_page_id ) ) {
return false;
}
$old = (array) get_post_meta( $policy_page_id, '_wp_suggested_privacy_policy_content' );
// Updates are not relevant if the user has not reviewed any suggestions yet.
if ( empty( $old ) ) {
return false;
}
$cached = get_option( '_wp_suggested_policy_text_has_changed' );
/*
* When this function is called before `admin_init`, `self::$policy_content`
* has not been populated yet, so use the cached result from the last
* execution instead.
*/
if ( ! did_action( 'admin_init' ) ) {
return 'changed' === $cached;
}
$new = self::$policy_content;
// Remove the extra values added to the meta.
foreach ( $old as $key => $data ) {
if ( ! is_array( $data ) || ! empty( $data['removed'] ) ) {
unset( $old[ $key ] );
continue;
}
$old[ $key ] = array(
'plugin_name' => $data['plugin_name'],
'policy_text' => $data['policy_text'],
);
}
// Normalize the order of texts, to facilitate comparison.
sort( $old );
sort( $new );
/*
* The == operator (equal, not identical) was used intentionally.
* See https://www.php.net/manual/en/language.operators.array.php
*/
if ( $new != $old ) {
/*
* A plugin was activated or deactivated, or some policy text has changed.
* Show a notice on the relevant screens to inform the admin.
*/
add_action( 'admin_notices', array( 'WP_Privacy_Policy_Content', 'policy_text_changed_notice' ) );
$state = 'changed';
} else {
$state = 'not-changed';
}
// Cache the result for use before `admin_init` (see above).
if ( $cached !== $state ) {
update_option( '_wp_suggested_policy_text_has_changed', $state );
}
return 'changed' === $state;
}
/**
* Outputs a warning when some privacy info has changed.
*
* @since 4.9.6
*/
public static function policy_text_changed_notice() {
$screen = get_current_screen()->id;
if ( 'privacy' !== $screen ) {
return;
}
$privacy_message = sprintf(
/* translators: %s: Privacy Policy Guide URL. */
__( 'The suggested privacy policy text has changed. Please <a href="%s">review the guide</a> and update your privacy policy.' ),
esc_url( admin_url( 'privacy-policy-guide.php?tab=policyguide' ) )
);
wp_admin_notice(
$privacy_message,
array(
'type' => 'warning',
'additional_classes' => array( 'policy-text-updated' ),
'dismissible' => true,
)
);
}
/**
* Updates the cached policy info when the policy page is updated.
*
* @since 4.9.6
* @access private
*
* @param int $post_id The ID of the updated post.
*/
public static function _policy_page_updated( $post_id ) {
$policy_page_id = (int) get_option( 'wp_page_for_privacy_policy' );
if ( ! $policy_page_id || $policy_page_id !== (int) $post_id ) {
return;
}
// Remove updated|removed status.
$old = (array) get_post_meta( $policy_page_id, '_wp_suggested_privacy_policy_content' );
$done = array();
$update_cache = false;
foreach ( $old as $old_key => $old_data ) {
if ( ! empty( $old_data['removed'] ) ) {
// Remove the old policy text.
$update_cache = true;
continue;
}
if ( ! empty( $old_data['updated'] ) ) {
// 'updated' is now 'added'.
$done[] = array(
'plugin_name' => $old_data['plugin_name'],
'policy_text' => $old_data['policy_text'],
'added' => $old_data['updated'],
);
$update_cache = true;
} else {
$done[] = $old_data;
}
}
if ( $update_cache ) {
delete_post_meta( $policy_page_id, '_wp_suggested_privacy_policy_content' );
// Update the cache.
foreach ( $done as $data ) {
add_post_meta( $policy_page_id, '_wp_suggested_privacy_policy_content', $data );
}
}
}
/**
* Checks for updated, added or removed privacy policy information from plugins.
*
* Caches the current info in post_meta of the policy page.
*
* @since 4.9.6
*
* @return array The privacy policy text/information added by core and plugins.
*/
public static function get_suggested_policy_text() {
$policy_page_id = (int) get_option( 'wp_page_for_privacy_policy' );
$checked = array();
$time = time();
$update_cache = false;
$new = self::$policy_content;
$old = array();
if ( $policy_page_id ) {
$old = (array) get_post_meta( $policy_page_id, '_wp_suggested_privacy_policy_content' );
}
// Check for no-changes and updates.
foreach ( $new as $new_key => $new_data ) {
foreach ( $old as $old_key => $old_data ) {
$found = false;
if ( $new_data['policy_text'] === $old_data['policy_text'] ) {
// Use the new plugin name in case it was changed, translated, etc.
if ( $old_data['plugin_name'] !== $new_data['plugin_name'] ) {
$old_data['plugin_name'] = $new_data['plugin_name'];
$update_cache = true;
}
// A plugin was re-activated.
if ( ! empty( $old_data['removed'] ) ) {
unset( $old_data['removed'] );
$old_data['added'] = $time;
$update_cache = true;
}
$checked[] = $old_data;
$found = true;
} elseif ( $new_data['plugin_name'] === $old_data['plugin_name'] ) {
// The info for the policy was updated.
$checked[] = array(
'plugin_name' => $new_data['plugin_name'],
'policy_text' => $new_data['policy_text'],
'updated' => $time,
);
$found = true;
$update_cache = true;
}
if ( $found ) {
unset( $new[ $new_key ], $old[ $old_key ] );
continue 2;
}
}
}
if ( ! empty( $new ) ) {
// A plugin was activated.
foreach ( $new as $new_data ) {
if ( ! empty( $new_data['plugin_name'] ) && ! empty( $new_data['policy_text'] ) ) {
$new_data['added'] = $time;
$checked[] = $new_data;
}
}
$update_cache = true;
}
if ( ! empty( $old ) ) {
// A plugin was deactivated.
foreach ( $old as $old_data ) {
if ( ! empty( $old_data['plugin_name'] ) && ! empty( $old_data['policy_text'] ) ) {
$data = array(
'plugin_name' => $old_data['plugin_name'],
'policy_text' => $old_data['policy_text'],
'removed' => $time,
);
$checked[] = $data;
}
}
$update_cache = true;
}
if ( $update_cache && $policy_page_id ) {
delete_post_meta( $policy_page_id, '_wp_suggested_privacy_policy_content' );
// Update the cache.
foreach ( $checked as $data ) {
add_post_meta( $policy_page_id, '_wp_suggested_privacy_policy_content', $data );
}
}
return $checked;
}
/**
* Adds a notice with a link to the guide when editing the privacy policy page.
*
* @since 4.9.6
* @since 5.0.0 The `$post` parameter was made optional.
*
* @global WP_Post $post Global post object.
*
* @param WP_Post|null $post The currently edited post. Default null.
*/
public static function notice( $post = null ) {
if ( is_null( $post ) ) {
global $post;
} else {
$post = get_post( $post );
}
if ( ! ( $post instanceof WP_Post ) ) {
return;
}
if ( ! current_user_can( 'manage_privacy_options' ) ) {
return;
}
$current_screen = get_current_screen();
$policy_page_id = (int) get_option( 'wp_page_for_privacy_policy' );
if ( 'post' !== $current_screen->base || $policy_page_id !== $post->ID ) {
return;
}
$message = __( 'Need help putting together your new Privacy Policy page? Check out our guide for recommendations on what content to include, along with policies suggested by your plugins and theme.' );
$url = esc_url( admin_url( 'options-privacy.php?tab=policyguide' ) );
$label = __( 'View Privacy Policy Guide.' );
if ( get_current_screen()->is_block_editor() ) {
wp_enqueue_script( 'wp-notices' );
$action = array(
'url' => $url,
'label' => $label,
);
wp_add_inline_script(
'wp-notices',
sprintf(
'wp.data.dispatch( "core/notices" ).createWarningNotice( "%s", { actions: [ %s ], isDismissible: false } )',
$message,
wp_json_encode( $action )
),
'after'
);
} else {
$message .= sprintf(
' <a href="%s" target="_blank">%s <span class="screen-reader-text">%s</span></a>',
$url,
$label,
/* translators: Hidden accessibility text. */
__( '(opens in a new tab)' )
);
wp_admin_notice(
$message,
array(
'type' => 'warning',
'additional_classes' => array( 'inline', 'wp-pp-notice' ),
)
);
}
}
/**
* Outputs the privacy policy guide together with content from the theme and plugins.
*
* @since 4.9.6
*/
public static function privacy_policy_guide() {
$content_array = self::get_suggested_policy_text();
$content = '';
$date_format = __( 'F j, Y' );
foreach ( $content_array as $section ) {
$class = '';
$meta = '';
$removed = '';
if ( ! empty( $section['removed'] ) ) {
$badge_class = ' red';
$date = date_i18n( $date_format, $section['removed'] );
/* translators: %s: Date of plugin deactivation. */
$badge_title = sprintf( __( 'Removed %s.' ), $date );
/* translators: %s: Date of plugin deactivation. */
$removed = sprintf( __( 'You deactivated this plugin on %s and may no longer need this policy.' ), $date );
$removed = wp_get_admin_notice(
$removed,
array(
'type' => 'info',
'additional_classes' => array( 'inline' ),
)
);
} elseif ( ! empty( $section['updated'] ) ) {
$badge_class = ' blue';
$date = date_i18n( $date_format, $section['updated'] );
/* translators: %s: Date of privacy policy text update. */
$badge_title = sprintf( __( 'Updated %s.' ), $date );
}
$plugin_name = esc_html( $section['plugin_name'] );
$sanitized_policy_name = sanitize_title_with_dashes( $plugin_name );
?>
<h4 class="privacy-settings-accordion-heading">
<button aria-expanded="false" class="privacy-settings-accordion-trigger" aria-controls="privacy-settings-accordion-block-<?php echo $sanitized_policy_name; ?>" type="button">
<span class="title"><?php echo $plugin_name; ?></span>
<?php if ( ! empty( $section['removed'] ) || ! empty( $section['updated'] ) ) : ?>
<span class="badge <?php echo $badge_class; ?>"> <?php echo $badge_title; ?></span>
<?php endif; ?>
<span class="icon"></span>
</button>
</h4>
<div id="privacy-settings-accordion-block-<?php echo $sanitized_policy_name; ?>" class="privacy-settings-accordion-panel privacy-text-box-body" hidden="hidden">
<?php
echo $removed;
echo $section['policy_text'];
?>
<?php if ( empty( $section['removed'] ) ) : ?>
<div class="privacy-settings-accordion-actions">
<span class="success" aria-hidden="true"><?php _e( 'Copied!' ); ?></span>
<button type="button" class="privacy-text-copy button">
<span aria-hidden="true"><?php _e( 'Copy suggested policy text to clipboard' ); ?></span>
<span class="screen-reader-text">
<?php
/* translators: Hidden accessibility text. %s: Plugin name. */
printf( __( 'Copy suggested policy text from %s.' ), $plugin_name );
?>
</span>
</button>
</div>
<?php endif; ?>
</div>
<?php
}
}
/**
* Returns the default suggested privacy policy content.
*
* @since 4.9.6
* @since 5.0.0 Added the `$blocks` parameter.
*
* @param bool $description Whether to include the descriptions under the section headings. Default false.
* @param bool $blocks Whether to format the content for the block editor. Default true.
* @return string The default policy content.
*/
public static function get_default_content( $description = false, $blocks = true ) {
$suggested_text = '<strong class="privacy-policy-tutorial">' . __( 'Suggested text:' ) . ' </strong>';
$content = '';
$strings = array();
// Start of the suggested privacy policy text.
if ( $description ) {
$strings[] = '<div class="wp-suggested-text">';
}
/* translators: Default privacy policy heading. */
$strings[] = '<h2 class="wp-block-heading">' . __( 'Who we are' ) . '</h2>';
if ( $description ) {
/* translators: Privacy policy tutorial. */
$strings[] = '<p class="privacy-policy-tutorial">' . __( 'In this section you should note your site URL, as well as the name of the company, organization, or individual behind it, and some accurate contact information.' ) . '</p>';
/* translators: Privacy policy tutorial. */
$strings[] = '<p class="privacy-policy-tutorial">' . __( 'The amount of information you may be required to show will vary depending on your local or national business regulations. You may, for example, be required to display a physical address, a registered address, or your company registration number.' ) . '</p>';
} else {
/* translators: Default privacy policy text. %s: Site URL. */
$strings[] = '<p>' . $suggested_text . sprintf( __( 'Our website address is: %s.' ), get_bloginfo( 'url', 'display' ) ) . '</p>';
}
if ( $description ) {
/* translators: Default privacy policy heading. */
$strings[] = '<h2>' . __( 'What personal data we collect and why we collect it' ) . '</h2>';
/* translators: Privacy policy tutorial. */
$strings[] = '<p class="privacy-policy-tutorial">' . __( 'In this section you should note what personal data you collect from users and site visitors. This may include personal data, such as name, email address, personal account preferences; transactional data, such as purchase information; and technical data, such as information about cookies.' ) . '</p>';
/* translators: Privacy policy tutorial. */
$strings[] = '<p class="privacy-policy-tutorial">' . __( 'You should also note any collection and retention of sensitive personal data, such as data concerning health.' ) . '</p>';
/* translators: Privacy policy tutorial. */
$strings[] = '<p class="privacy-policy-tutorial">' . __( 'In addition to listing what personal data you collect, you need to note why you collect it. These explanations must note either the legal basis for your data collection and retention or the active consent the user has given.' ) . '</p>';
/* translators: Privacy policy tutorial. */
$strings[] = '<p class="privacy-policy-tutorial">' . __( 'Personal data is not just created by a user&#8217;s interactions with your site. Personal data is also generated from technical processes such as contact forms, comments, cookies, analytics, and third party embeds.' ) . '</p>';
/* translators: Privacy policy tutorial. */
$strings[] = '<p class="privacy-policy-tutorial">' . __( 'By default WordPress does not collect any personal data about visitors, and only collects the data shown on the User Profile screen from registered users. However some of your plugins may collect personal data. You should add the relevant information below.' ) . '</p>';
}
/* translators: Default privacy policy heading. */
$strings[] = '<h2 class="wp-block-heading">' . __( 'Comments' ) . '</h2>';
if ( $description ) {
/* translators: Privacy policy tutorial. */
$strings[] = '<p class="privacy-policy-tutorial">' . __( 'In this subsection you should note what information is captured through comments. We have noted the data which WordPress collects by default.' ) . '</p>';
} else {
/* translators: Default privacy policy text. */
$strings[] = '<p>' . $suggested_text . __( 'When visitors leave comments on the site we collect the data shown in the comments form, and also the visitor&#8217;s IP address and browser user agent string to help spam detection.' ) . '</p>';
/* translators: Default privacy policy text. */
$strings[] = '<p>' . __( 'An anonymized string created from your email address (also called a hash) may be provided to the Gravatar service to see if you are using it. The Gravatar service privacy policy is available here: https://automattic.com/privacy/. After approval of your comment, your profile picture is visible to the public in the context of your comment.' ) . '</p>';
}
/* translators: Default privacy policy heading. */
$strings[] = '<h2 class="wp-block-heading">' . __( 'Media' ) . '</h2>';
if ( $description ) {
/* translators: Privacy policy tutorial. */
$strings[] = '<p class="privacy-policy-tutorial">' . __( 'In this subsection you should note what information may be disclosed by users who can upload media files. All uploaded files are usually publicly accessible.' ) . '</p>';
} else {
/* translators: Default privacy policy text. */
$strings[] = '<p>' . $suggested_text . __( 'If you upload images to the website, you should avoid uploading images with embedded location data (EXIF GPS) included. Visitors to the website can download and extract any location data from images on the website.' ) . '</p>';
}
if ( $description ) {
/* translators: Default privacy policy heading. */
$strings[] = '<h2>' . __( 'Contact forms' ) . '</h2>';
/* translators: Privacy policy tutorial. */
$strings[] = '<p class="privacy-policy-tutorial">' . __( 'By default, WordPress does not include a contact form. If you use a contact form plugin, use this subsection to note what personal data is captured when someone submits a contact form, and how long you keep it. For example, you may note that you keep contact form submissions for a certain period for customer service purposes, but you do not use the information submitted through them for marketing purposes.' ) . '</p>';
}
/* translators: Default privacy policy heading. */
$strings[] = '<h2 class="wp-block-heading">' . __( 'Cookies' ) . '</h2>';
if ( $description ) {
/* translators: Privacy policy tutorial. */
$strings[] = '<p class="privacy-policy-tutorial">' . __( 'In this subsection you should list the cookies your website uses, including those set by your plugins, social media, and analytics. We have provided the cookies which WordPress installs by default.' ) . '</p>';
} else {
/* translators: Default privacy policy text. */
$strings[] = '<p>' . $suggested_text . __( 'If you leave a comment on our site you may opt-in to saving your name, email address and website in cookies. These are for your convenience so that you do not have to fill in your details again when you leave another comment. These cookies will last for one year.' ) . '</p>';
/* translators: Default privacy policy text. */
$strings[] = '<p>' . __( 'If you visit our login page, we will set a temporary cookie to determine if your browser accepts cookies. This cookie contains no personal data and is discarded when you close your browser.' ) . '</p>';
/* translators: Default privacy policy text. */
$strings[] = '<p>' . __( 'When you log in, we will also set up several cookies to save your login information and your screen display choices. Login cookies last for two days, and screen options cookies last for a year. If you select &quot;Remember Me&quot;, your login will persist for two weeks. If you log out of your account, the login cookies will be removed.' ) . '</p>';
/* translators: Default privacy policy text. */
$strings[] = '<p>' . __( 'If you edit or publish an article, an additional cookie will be saved in your browser. This cookie includes no personal data and simply indicates the post ID of the article you just edited. It expires after 1 day.' ) . '</p>';
}
if ( ! $description ) {
/* translators: Default privacy policy heading. */
$strings[] = '<h2 class="wp-block-heading">' . __( 'Embedded content from other websites' ) . '</h2>';
/* translators: Default privacy policy text. */
$strings[] = '<p>' . $suggested_text . __( 'Articles on this site may include embedded content (e.g. videos, images, articles, etc.). Embedded content from other websites behaves in the exact same way as if the visitor has visited the other website.' ) . '</p>';
/* translators: Default privacy policy text. */
$strings[] = '<p>' . __( 'These websites may collect data about you, use cookies, embed additional third-party tracking, and monitor your interaction with that embedded content, including tracking your interaction with the embedded content if you have an account and are logged in to that website.' ) . '</p>';
}
if ( $description ) {
/* translators: Default privacy policy heading. */
$strings[] = '<h2>' . __( 'Analytics' ) . '</h2>';
/* translators: Privacy policy tutorial. */
$strings[] = '<p class="privacy-policy-tutorial">' . __( 'In this subsection you should note what analytics package you use, how users can opt out of analytics tracking, and a link to your analytics provider&#8217;s privacy policy, if any.' ) . '</p>';
/* translators: Privacy policy tutorial. */
$strings[] = '<p class="privacy-policy-tutorial">' . __( 'By default WordPress does not collect any analytics data. However, many web hosting accounts collect some anonymous analytics data. You may also have installed a WordPress plugin that provides analytics services. In that case, add information from that plugin here.' ) . '</p>';
}
/* translators: Default privacy policy heading. */
$strings[] = '<h2 class="wp-block-heading">' . __( 'Who we share your data with' ) . '</h2>';
if ( $description ) {
/* translators: Privacy policy tutorial. */
$strings[] = '<p class="privacy-policy-tutorial">' . __( 'In this section you should name and list all third party providers with whom you share site data, including partners, cloud-based services, payment processors, and third party service providers, and note what data you share with them and why. Link to their own privacy policies if possible.' ) . '</p>';
/* translators: Privacy policy tutorial. */
$strings[] = '<p class="privacy-policy-tutorial">' . __( 'By default WordPress does not share any personal data with anyone.' ) . '</p>';
} else {
/* translators: Default privacy policy text. */
$strings[] = '<p>' . $suggested_text . __( 'If you request a password reset, your IP address will be included in the reset email.' ) . '</p>';
}
/* translators: Default privacy policy heading. */
$strings[] = '<h2 class="wp-block-heading">' . __( 'How long we retain your data' ) . '</h2>';
if ( $description ) {
/* translators: Privacy policy tutorial. */
$strings[] = '<p class="privacy-policy-tutorial">' . __( 'In this section you should explain how long you retain personal data collected or processed by the website. While it is your responsibility to come up with the schedule of how long you keep each dataset for and why you keep it, that information does need to be listed here. For example, you may want to say that you keep contact form entries for six months, analytics records for a year, and customer purchase records for ten years.' ) . '</p>';
} else {
/* translators: Default privacy policy text. */
$strings[] = '<p>' . $suggested_text . __( 'If you leave a comment, the comment and its metadata are retained indefinitely. This is so we can recognize and approve any follow-up comments automatically instead of holding them in a moderation queue.' ) . '</p>';
/* translators: Default privacy policy text. */
$strings[] = '<p>' . __( 'For users that register on our website (if any), we also store the personal information they provide in their user profile. All users can see, edit, or delete their personal information at any time (except they cannot change their username). Website administrators can also see and edit that information.' ) . '</p>';
}
/* translators: Default privacy policy heading. */
$strings[] = '<h2 class="wp-block-heading">' . __( 'What rights you have over your data' ) . '</h2>';
if ( $description ) {
/* translators: Privacy policy tutorial. */
$strings[] = '<p class="privacy-policy-tutorial">' . __( 'In this section you should explain what rights your users have over their data and how they can invoke those rights.' ) . '</p>';
} else {
/* translators: Default privacy policy text. */
$strings[] = '<p>' . $suggested_text . __( 'If you have an account on this site, or have left comments, you can request to receive an exported file of the personal data we hold about you, including any data you have provided to us. You can also request that we erase any personal data we hold about you. This does not include any data we are obliged to keep for administrative, legal, or security purposes.' ) . '</p>';
}
/* translators: Default privacy policy heading. */
$strings[] = '<h2 class="wp-block-heading">' . __( 'Where your data is sent' ) . '</h2>';
if ( $description ) {
/* translators: Privacy policy tutorial. */
$strings[] = '<p class="privacy-policy-tutorial">' . __( 'In this section you should list all transfers of your site data outside the European Union and describe the means by which that data is safeguarded to European data protection standards. This could include your web hosting, cloud storage, or other third party services.' ) . '</p>';
/* translators: Privacy policy tutorial. */
$strings[] = '<p class="privacy-policy-tutorial">' . __( 'European data protection law requires data about European residents which is transferred outside the European Union to be safeguarded to the same standards as if the data was in Europe. So in addition to listing where data goes, you should describe how you ensure that these standards are met either by yourself or by your third party providers, whether that is through an agreement such as Privacy Shield, model clauses in your contracts, or binding corporate rules.' ) . '</p>';
} else {
/* translators: Default privacy policy text. */
$strings[] = '<p>' . $suggested_text . __( 'Visitor comments may be checked through an automated spam detection service.' ) . '</p>';
}
if ( $description ) {
/* translators: Default privacy policy heading. */
$strings[] = '<h2>' . __( 'Contact information' ) . '</h2>';
/* translators: Privacy policy tutorial. */
$strings[] = '<p class="privacy-policy-tutorial">' . __( 'In this section you should provide a contact method for privacy-specific concerns. If you are required to have a Data Protection Officer, list their name and full contact details here as well.' ) . '</p>';
}
if ( $description ) {
/* translators: Default privacy policy heading. */
$strings[] = '<h2>' . __( 'Additional information' ) . '</h2>';
/* translators: Privacy policy tutorial. */
$strings[] = '<p class="privacy-policy-tutorial">' . __( 'If you use your site for commercial purposes and you engage in more complex collection or processing of personal data, you should note the following information in your privacy policy in addition to the information we have already discussed.' ) . '</p>';
}
if ( $description ) {
/* translators: Default privacy policy heading. */
$strings[] = '<h2>' . __( 'How we protect your data' ) . '</h2>';
/* translators: Privacy policy tutorial. */
$strings[] = '<p class="privacy-policy-tutorial">' . __( 'In this section you should explain what measures you have taken to protect your users&#8217; data. This could include technical measures such as encryption; security measures such as two factor authentication; and measures such as staff training in data protection. If you have carried out a Privacy Impact Assessment, you can mention it here too.' ) . '</p>';
}
if ( $description ) {
/* translators: Default privacy policy heading. */
$strings[] = '<h2>' . __( 'What data breach procedures we have in place' ) . '</h2>';
/* translators: Privacy policy tutorial. */
$strings[] = '<p class="privacy-policy-tutorial">' . __( 'In this section you should explain what procedures you have in place to deal with data breaches, either potential or real, such as internal reporting systems, contact mechanisms, or bug bounties.' ) . '</p>';
}
if ( $description ) {
/* translators: Default privacy policy heading. */
$strings[] = '<h2>' . __( 'What third parties we receive data from' ) . '</h2>';
/* translators: Privacy policy tutorial. */
$strings[] = '<p class="privacy-policy-tutorial">' . __( 'If your website receives data about users from third parties, including advertisers, this information must be included within the section of your privacy policy dealing with third party data.' ) . '</p>';
}
if ( $description ) {
/* translators: Default privacy policy heading. */
$strings[] = '<h2>' . __( 'What automated decision making and/or profiling we do with user data' ) . '</h2>';
/* translators: Privacy policy tutorial. */
$strings[] = '<p class="privacy-policy-tutorial">' . __( 'If your website provides a service which includes automated decision making - for example, allowing customers to apply for credit, or aggregating their data into an advertising profile - you must note that this is taking place, and include information about how that information is used, what decisions are made with that aggregated data, and what rights users have over decisions made without human intervention.' ) . '</p>';
}
if ( $description ) {
/* translators: Default privacy policy heading. */
$strings[] = '<h2>' . __( 'Industry regulatory disclosure requirements' ) . '</h2>';
/* translators: Privacy policy tutorial. */
$strings[] = '<p class="privacy-policy-tutorial">' . __( 'If you are a member of a regulated industry, or if you are subject to additional privacy laws, you may be required to disclose that information here.' ) . '</p>';
$strings[] = '</div>';
}
if ( $blocks ) {
foreach ( $strings as $key => $string ) {
if ( str_starts_with( $string, '<p>' ) ) {
$strings[ $key ] = "<!-- wp:paragraph -->\n" . $string . "\n<!-- /wp:paragraph -->\n";
}
if ( str_starts_with( $string, '<h2 ' ) ) {
$strings[ $key ] = "<!-- wp:heading -->\n" . $string . "\n<!-- /wp:heading -->\n";
}
}
}
$content = implode( '', $strings );
// End of the suggested privacy policy text.
/**
* Filters the default content suggested for inclusion in a privacy policy.
*
* @since 4.9.6
* @since 5.0.0 Added the `$strings`, `$description`, and `$blocks` parameters.
* @deprecated 5.7.0 Use wp_add_privacy_policy_content() instead.
*
* @param string $content The default policy content.
* @param string[] $strings An array of privacy policy content strings.
* @param bool $description Whether policy descriptions should be included.
* @param bool $blocks Whether the content should be formatted for the block editor.
*/
return apply_filters_deprecated(
'wp_get_default_privacy_policy_content',
array( $content, $strings, $description, $blocks ),
'5.7.0',
'wp_add_privacy_policy_content()'
);
}
/**
* Adds the suggested privacy policy text to the policy postbox.
*
* @since 4.9.6
*/
public static function add_suggested_content() {
$content = self::get_default_content( false, false );
wp_add_privacy_policy_content( __( 'WordPress' ), $content );
}
}

View File

@ -0,0 +1,565 @@
<?php
/**
* List Table API: WP_Privacy_Requests_Table class
*
* @package WordPress
* @subpackage Administration
* @since 4.9.6
*/
abstract class WP_Privacy_Requests_Table extends WP_List_Table {
/**
* Action name for the requests this table will work with. Classes
* which inherit from WP_Privacy_Requests_Table should define this.
*
* Example: 'export_personal_data'.
*
* @since 4.9.6
*
* @var string $request_type Name of action.
*/
protected $request_type = 'INVALID';
/**
* Post type to be used.
*
* @since 4.9.6
*
* @var string $post_type The post type.
*/
protected $post_type = 'INVALID';
/**
* Gets columns to show in the list table.
*
* @since 4.9.6
*
* @return string[] Array of column titles keyed by their column name.
*/
public function get_columns() {
$columns = array(
'cb' => '<input type="checkbox" />',
'email' => __( 'Requester' ),
'status' => __( 'Status' ),
'created_timestamp' => __( 'Requested' ),
'next_steps' => __( 'Next steps' ),
);
return $columns;
}
/**
* Normalizes the admin URL to the current page (by request_type).
*
* @since 5.3.0
*
* @return string URL to the current admin page.
*/
protected function get_admin_url() {
$pagenow = str_replace( '_', '-', $this->request_type );
if ( 'remove-personal-data' === $pagenow ) {
$pagenow = 'erase-personal-data';
}
return admin_url( $pagenow . '.php' );
}
/**
* Gets a list of sortable columns.
*
* @since 4.9.6
*
* @return array Default sortable columns.
*/
protected function get_sortable_columns() {
/*
* The initial sorting is by 'Requested' (post_date) and descending.
* With initial sorting, the first click on 'Requested' should be ascending.
* With 'Requester' sorting active, the next click on 'Requested' should be descending.
*/
$desc_first = isset( $_GET['orderby'] );
return array(
'email' => 'requester',
'created_timestamp' => array( 'requested', $desc_first ),
);
}
/**
* Returns the default primary column.
*
* @since 4.9.6
*
* @return string Default primary column name.
*/
protected function get_default_primary_column_name() {
return 'email';
}
/**
* Counts the number of requests for each status.
*
* @since 4.9.6
*
* @global wpdb $wpdb WordPress database abstraction object.
*
* @return object Number of posts for each status.
*/
protected function get_request_counts() {
global $wpdb;
$cache_key = $this->post_type . '-' . $this->request_type;
$counts = wp_cache_get( $cache_key, 'counts' );
if ( false !== $counts ) {
return $counts;
}
$query = "
SELECT post_status, COUNT( * ) AS num_posts
FROM {$wpdb->posts}
WHERE post_type = %s
AND post_name = %s
GROUP BY post_status";
$results = (array) $wpdb->get_results( $wpdb->prepare( $query, $this->post_type, $this->request_type ), ARRAY_A );
$counts = array_fill_keys( get_post_stati(), 0 );
foreach ( $results as $row ) {
$counts[ $row['post_status'] ] = $row['num_posts'];
}
$counts = (object) $counts;
wp_cache_set( $cache_key, $counts, 'counts' );
return $counts;
}
/**
* Gets an associative array ( id => link ) with the list of views available on this table.
*
* @since 4.9.6
*
* @return string[] An array of HTML links keyed by their view.
*/
protected function get_views() {
$current_status = isset( $_REQUEST['filter-status'] ) ? sanitize_text_field( $_REQUEST['filter-status'] ) : '';
$statuses = _wp_privacy_statuses();
$views = array();
$counts = $this->get_request_counts();
$total_requests = absint( array_sum( (array) $counts ) );
// Normalized admin URL.
$admin_url = $this->get_admin_url();
$status_label = sprintf(
/* translators: %s: Number of requests. */
_nx(
'All <span class="count">(%s)</span>',
'All <span class="count">(%s)</span>',
$total_requests,
'requests'
),
number_format_i18n( $total_requests )
);
$views['all'] = array(
'url' => esc_url( $admin_url ),
'label' => $status_label,
'current' => empty( $current_status ),
);
foreach ( $statuses as $status => $label ) {
$post_status = get_post_status_object( $status );
if ( ! $post_status ) {
continue;
}
$total_status_requests = absint( $counts->{$status} );
if ( ! $total_status_requests ) {
continue;
}
$status_label = sprintf(
translate_nooped_plural( $post_status->label_count, $total_status_requests ),
number_format_i18n( $total_status_requests )
);
$status_link = add_query_arg( 'filter-status', $status, $admin_url );
$views[ $status ] = array(
'url' => esc_url( $status_link ),
'label' => $status_label,
'current' => $status === $current_status,
);
}
return $this->get_views_links( $views );
}
/**
* Gets bulk actions.
*
* @since 4.9.6
*
* @return array Array of bulk action labels keyed by their action.
*/
protected function get_bulk_actions() {
return array(
'resend' => __( 'Resend confirmation requests' ),
'complete' => __( 'Mark requests as completed' ),
'delete' => __( 'Delete requests' ),
);
}
/**
* Process bulk actions.
*
* @since 4.9.6
* @since 5.6.0 Added support for the `complete` action.
*/
public function process_bulk_action() {
$action = $this->current_action();
$request_ids = isset( $_REQUEST['request_id'] ) ? wp_parse_id_list( wp_unslash( $_REQUEST['request_id'] ) ) : array();
if ( empty( $request_ids ) ) {
return;
}
$count = 0;
$failures = 0;
check_admin_referer( 'bulk-privacy_requests' );
switch ( $action ) {
case 'resend':
foreach ( $request_ids as $request_id ) {
$resend = _wp_privacy_resend_request( $request_id );
if ( $resend && ! is_wp_error( $resend ) ) {
++$count;
} else {
++$failures;
}
}
if ( $failures ) {
add_settings_error(
'bulk_action',
'bulk_action',
sprintf(
/* translators: %d: Number of requests. */
_n(
'%d confirmation request failed to resend.',
'%d confirmation requests failed to resend.',
$failures
),
$failures
),
'error'
);
}
if ( $count ) {
add_settings_error(
'bulk_action',
'bulk_action',
sprintf(
/* translators: %d: Number of requests. */
_n(
'%d confirmation request re-sent successfully.',
'%d confirmation requests re-sent successfully.',
$count
),
$count
),
'success'
);
}
break;
case 'complete':
foreach ( $request_ids as $request_id ) {
$result = _wp_privacy_completed_request( $request_id );
if ( $result && ! is_wp_error( $result ) ) {
++$count;
}
}
add_settings_error(
'bulk_action',
'bulk_action',
sprintf(
/* translators: %d: Number of requests. */
_n(
'%d request marked as complete.',
'%d requests marked as complete.',
$count
),
$count
),
'success'
);
break;
case 'delete':
foreach ( $request_ids as $request_id ) {
if ( wp_delete_post( $request_id, true ) ) {
++$count;
} else {
++$failures;
}
}
if ( $failures ) {
add_settings_error(
'bulk_action',
'bulk_action',
sprintf(
/* translators: %d: Number of requests. */
_n(
'%d request failed to delete.',
'%d requests failed to delete.',
$failures
),
$failures
),
'error'
);
}
if ( $count ) {
add_settings_error(
'bulk_action',
'bulk_action',
sprintf(
/* translators: %d: Number of requests. */
_n(
'%d request deleted successfully.',
'%d requests deleted successfully.',
$count
),
$count
),
'success'
);
}
break;
}
}
/**
* Prepares items to output.
*
* @since 4.9.6
* @since 5.1.0 Added support for column sorting.
*/
public function prepare_items() {
$this->items = array();
$posts_per_page = $this->get_items_per_page( $this->request_type . '_requests_per_page' );
$args = array(
'post_type' => $this->post_type,
'post_name__in' => array( $this->request_type ),
'posts_per_page' => $posts_per_page,
'offset' => isset( $_REQUEST['paged'] ) ? max( 0, absint( $_REQUEST['paged'] ) - 1 ) * $posts_per_page : 0,
'post_status' => 'any',
's' => isset( $_REQUEST['s'] ) ? sanitize_text_field( $_REQUEST['s'] ) : '',
);
$orderby_mapping = array(
'requester' => 'post_title',
'requested' => 'post_date',
);
if ( isset( $_REQUEST['orderby'] ) && isset( $orderby_mapping[ $_REQUEST['orderby'] ] ) ) {
$args['orderby'] = $orderby_mapping[ $_REQUEST['orderby'] ];
}
if ( isset( $_REQUEST['order'] ) && in_array( strtoupper( $_REQUEST['order'] ), array( 'ASC', 'DESC' ), true ) ) {
$args['order'] = strtoupper( $_REQUEST['order'] );
}
if ( ! empty( $_REQUEST['filter-status'] ) ) {
$filter_status = isset( $_REQUEST['filter-status'] ) ? sanitize_text_field( $_REQUEST['filter-status'] ) : '';
$args['post_status'] = $filter_status;
}
$requests_query = new WP_Query( $args );
$requests = $requests_query->posts;
foreach ( $requests as $request ) {
$this->items[] = wp_get_user_request( $request->ID );
}
$this->items = array_filter( $this->items );
$this->set_pagination_args(
array(
'total_items' => $requests_query->found_posts,
'per_page' => $posts_per_page,
)
);
}
/**
* Returns the markup for the Checkbox column.
*
* @since 4.9.6
*
* @param WP_User_Request $item Item being shown.
* @return string Checkbox column markup.
*/
public function column_cb( $item ) {
return sprintf(
'<input type="checkbox" name="request_id[]" id="requester_%1$s" value="%1$s" />' .
'<label for="requester_%1$s"><span class="screen-reader-text">%2$s</span></label><span class="spinner"></span>',
esc_attr( $item->ID ),
/* translators: Hidden accessibility text. %s: Email address. */
sprintf( __( 'Select %s' ), $item->email )
);
}
/**
* Status column.
*
* @since 4.9.6
*
* @param WP_User_Request $item Item being shown.
* @return string Status column markup.
*/
public function column_status( $item ) {
$status = get_post_status( $item->ID );
$status_object = get_post_status_object( $status );
if ( ! $status_object || empty( $status_object->label ) ) {
return '-';
}
$timestamp = false;
switch ( $status ) {
case 'request-confirmed':
$timestamp = $item->confirmed_timestamp;
break;
case 'request-completed':
$timestamp = $item->completed_timestamp;
break;
}
echo '<span class="status-label status-' . esc_attr( $status ) . '">';
echo esc_html( $status_object->label );
if ( $timestamp ) {
echo ' (' . $this->get_timestamp_as_date( $timestamp ) . ')';
}
echo '</span>';
}
/**
* Converts a timestamp for display.
*
* @since 4.9.6
*
* @param int $timestamp Event timestamp.
* @return string Human readable date.
*/
protected function get_timestamp_as_date( $timestamp ) {
if ( empty( $timestamp ) ) {
return '';
}
$time_diff = time() - $timestamp;
if ( $time_diff >= 0 && $time_diff < DAY_IN_SECONDS ) {
/* translators: %s: Human-readable time difference. */
return sprintf( __( '%s ago' ), human_time_diff( $timestamp ) );
}
return date_i18n( get_option( 'date_format' ), $timestamp );
}
/**
* Handles the default column.
*
* @since 4.9.6
* @since 5.7.0 Added `manage_{$this->screen->id}_custom_column` action.
*
* @param WP_User_Request $item Item being shown.
* @param string $column_name Name of column being shown.
*/
public function column_default( $item, $column_name ) {
/**
* Fires for each custom column of a specific request type in the Requests list table.
*
* Custom columns are registered using the {@see 'manage_export-personal-data_columns'}
* and the {@see 'manage_erase-personal-data_columns'} filters.
*
* @since 5.7.0
*
* @param string $column_name The name of the column to display.
* @param WP_User_Request $item The item being shown.
*/
do_action( "manage_{$this->screen->id}_custom_column", $column_name, $item );
}
/**
* Returns the markup for the Created timestamp column. Overridden by children.
*
* @since 5.7.0
*
* @param WP_User_Request $item Item being shown.
* @return string Human readable date.
*/
public function column_created_timestamp( $item ) {
return $this->get_timestamp_as_date( $item->created_timestamp );
}
/**
* Actions column. Overridden by children.
*
* @since 4.9.6
*
* @param WP_User_Request $item Item being shown.
* @return string Email column markup.
*/
public function column_email( $item ) {
return sprintf( '<a href="%1$s">%2$s</a> %3$s', esc_url( 'mailto:' . $item->email ), $item->email, $this->row_actions( array() ) );
}
/**
* Returns the markup for the next steps column. Overridden by children.
*
* @since 4.9.6
*
* @param WP_User_Request $item Item being shown.
*/
public function column_next_steps( $item ) {}
/**
* Generates content for a single row of the table,
*
* @since 4.9.6
*
* @param WP_User_Request $item The current item.
*/
public function single_row( $item ) {
$status = $item->status;
echo '<tr id="request-' . esc_attr( $item->ID ) . '" class="status-' . esc_attr( $status ) . '">';
$this->single_row_columns( $item );
echo '</tr>';
}
/**
* Embeds scripts used to perform actions. Overridden by children.
*
* @since 4.9.6
*/
public function embed_scripts() {}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,458 @@
<?php
/**
* Class for testing automatic updates in the WordPress code.
*
* @package WordPress
* @subpackage Site_Health
* @since 5.2.0
*/
#[AllowDynamicProperties]
class WP_Site_Health_Auto_Updates {
/**
* WP_Site_Health_Auto_Updates constructor.
*
* @since 5.2.0
*/
public function __construct() {
require_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php';
}
/**
* Runs tests to determine if auto-updates can run.
*
* @since 5.2.0
*
* @return array The test results.
*/
public function run_tests() {
$tests = array(
$this->test_constants( 'WP_AUTO_UPDATE_CORE', array( true, 'beta', 'rc', 'development', 'branch-development', 'minor' ) ),
$this->test_wp_version_check_attached(),
$this->test_filters_automatic_updater_disabled(),
$this->test_wp_automatic_updates_disabled(),
$this->test_if_failed_update(),
$this->test_vcs_abspath(),
$this->test_check_wp_filesystem_method(),
$this->test_all_files_writable(),
$this->test_accepts_dev_updates(),
$this->test_accepts_minor_updates(),
);
$tests = array_filter( $tests );
$tests = array_map(
static function ( $test ) {
$test = (object) $test;
if ( empty( $test->severity ) ) {
$test->severity = 'warning';
}
return $test;
},
$tests
);
return $tests;
}
/**
* Tests if auto-updates related constants are set correctly.
*
* @since 5.2.0
* @since 5.5.1 The `$value` parameter can accept an array.
*
* @param string $constant The name of the constant to check.
* @param bool|string|array $value The value that the constant should be, if set,
* or an array of acceptable values.
* @return array The test results.
*/
public function test_constants( $constant, $value ) {
$acceptable_values = (array) $value;
if ( defined( $constant ) && ! in_array( constant( $constant ), $acceptable_values, true ) ) {
return array(
'description' => sprintf(
/* translators: 1: Name of the constant used. 2: Value of the constant used. */
__( 'The %1$s constant is defined as %2$s' ),
"<code>$constant</code>",
'<code>' . esc_html( var_export( constant( $constant ), true ) ) . '</code>'
),
'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.' ),
'<code>wp_version_check()</code>'
),
'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.' ),
'<code>automatic_updater_disabled</code>'
),
'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.' ),
'<code>' . $failed['error_code'] . '</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.' ),
'<code>' . $failed['error_code'] . '</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 );
// Search all directories we've found for evidence of version control.
foreach ( $vcs_dirs as $vcs_dir ) {
foreach ( $check_dirs as $check_dir ) {
// phpcs:ignore Generic.CodeAnalysis.AssignmentInCondition,Squiz.PHP.DisallowMultipleAssignments
if ( $checkout = @is_dir( rtrim( $check_dir, '\\/' ) . "/$vcs_dir" ) ) {
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.' ),
'<code>' . $check_dir . '</code>',
"<code>$vcs_dir</code>",
'<code>automatic_updates_is_vcs_checkout</code>'
),
'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).' ),
'<code>' . $check_dir . '</code>',
"<code>$vcs_dir</code>"
),
'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:' ) . ' <ul><li>' . implode( '</li><li>', $unwritable_files ) . '</li></ul>',
'severity' => 'fail',
);
} else {
return array(
'description' => __( 'All of your WordPress files are writable.' ),
'severity' => 'pass',
);
}
}
/**
* Checks if the install is using a development branch and can use nightly packages.
*
* @since 5.2.0
*
* @return array|false The test results. False if it isn't a development version.
*/
public function test_accepts_dev_updates() {
require ABSPATH . WPINC . '/version.php'; // $wp_version; // x.y.z
// Only for dev versions.
if ( ! str_contains( $wp_version, '-' ) ) {
return false;
}
if ( defined( 'WP_AUTO_UPDATE_CORE' ) && ( 'minor' === WP_AUTO_UPDATE_CORE || false === WP_AUTO_UPDATE_CORE ) ) {
return array(
'description' => sprintf(
/* translators: %s: Name of the constant used. */
__( 'WordPress development updates are blocked by the %s constant.' ),
'<code>WP_AUTO_UPDATE_CORE</code>'
),
'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.' ),
'<code>allow_dev_auto_core_updates</code>'
),
'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.' ),
"<code>define( 'WP_AUTO_UPDATE_CORE', false );</code>"
),
'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.' ),
'<code>allow_minor_auto_core_updates</code>'
),
'severity' => 'fail',
);
}
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,237 @@
<?php
/**
* Administration API: WP_Site_Icon class
*
* @package WordPress
* @subpackage Administration
* @since 4.3.0
*/
/**
* Core class used to implement site icon functionality.
*
* @since 4.3.0
*/
#[AllowDynamicProperties]
class WP_Site_Icon {
/**
* The minimum size of the site icon.
*
* @since 4.3.0
* @var int
*/
public $min_size = 512;
/**
* The size to which to crop the image so that we can display it in the UI nicely.
*
* @since 4.3.0
* @var int
*/
public $page_crop = 512;
/**
* List of site icon sizes.
*
* @since 4.3.0
* @var int[]
*/
public $site_icon_sizes = array(
/*
* Square, medium sized tiles for IE11+.
*
* See https://msdn.microsoft.com/library/dn455106(v=vs.85).aspx
*/
270,
/*
* App icon for Android/Chrome.
*
* @link https://developers.google.com/web/updates/2014/11/Support-for-theme-color-in-Chrome-39-for-Android
* @link https://developer.chrome.com/multidevice/android/installtohomescreen
*/
192,
/*
* App icons up to iPhone 6 Plus.
*
* See https://developer.apple.com/library/prerelease/ios/documentation/UserExperience/Conceptual/MobileHIG/IconMatrix.html
*/
180,
// Our regular Favicon.
32,
);
/**
* Registers actions and filters.
*
* @since 4.3.0
*/
public function __construct() {
add_action( 'delete_attachment', array( $this, 'delete_attachment_data' ) );
add_filter( 'get_post_metadata', array( $this, 'get_post_metadata' ), 10, 4 );
}
/**
* Creates an attachment 'object'.
*
* @since 4.3.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.
*/
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_content' => $url,
'post_mime_type' => $image_type,
'guid' => $url,
'context' => 'site-icon',
);
return $attachment;
}
/**
* Inserts an attachment.
*
* @since 4.3.0
*
* @param array $attachment An array with attachment object data.
* @param string $file File path of the attached image.
* @return int Attachment ID.
*/
public function insert_attachment( $attachment, $file ) {
$attachment_id = wp_insert_attachment( $attachment, $file );
$metadata = wp_generate_attachment_metadata( $attachment_id, $file );
/**
* Filters the site icon attachment metadata.
*
* @since 4.3.0
*
* @see wp_generate_attachment_metadata()
*
* @param array $metadata Attachment metadata.
*/
$metadata = apply_filters( 'site_icon_attachment_metadata', $metadata );
wp_update_attachment_metadata( $attachment_id, $metadata );
return $attachment_id;
}
/**
* Adds additional sizes to be made when creating the site icon images.
*
* @since 4.3.0
*
* @param array[] $sizes Array of arrays containing information for additional sizes.
* @return array[] Array of arrays containing additional image sizes.
*/
public function additional_sizes( $sizes = array() ) {
$only_crop_sizes = array();
/**
* Filters the different dimensions that a site icon is saved in.
*
* @since 4.3.0
*
* @param int[] $site_icon_sizes Array of sizes available for the Site Icon.
*/
$this->site_icon_sizes = apply_filters( 'site_icon_image_sizes', $this->site_icon_sizes );
// Use a natural sort of numbers.
natsort( $this->site_icon_sizes );
$this->site_icon_sizes = array_reverse( $this->site_icon_sizes );
// Ensure that we only resize the image into sizes that allow cropping.
foreach ( $sizes as $name => $size_array ) {
if ( isset( $size_array['crop'] ) ) {
$only_crop_sizes[ $name ] = $size_array;
}
}
foreach ( $this->site_icon_sizes as $size ) {
if ( $size < $this->min_size ) {
$only_crop_sizes[ 'site_icon-' . $size ] = array(
'width ' => $size,
'height' => $size,
'crop' => true,
);
}
}
return $only_crop_sizes;
}
/**
* Adds Site Icon sizes to the array of image sizes on demand.
*
* @since 4.3.0
*
* @param string[] $sizes Array of image size names.
* @return string[] Array of image size names.
*/
public function intermediate_image_sizes( $sizes = array() ) {
/** This filter is documented in wp-admin/includes/class-wp-site-icon.php */
$this->site_icon_sizes = apply_filters( 'site_icon_image_sizes', $this->site_icon_sizes );
foreach ( $this->site_icon_sizes as $size ) {
$sizes[] = 'site_icon-' . $size;
}
return $sizes;
}
/**
* Deletes the Site Icon when the image file is deleted.
*
* @since 4.3.0
*
* @param int $post_id Attachment ID.
*/
public function delete_attachment_data( $post_id ) {
$site_icon_id = (int) get_option( 'site_icon' );
if ( $site_icon_id && $post_id === $site_icon_id ) {
delete_option( 'site_icon' );
}
}
/**
* Adds custom image sizes when meta data for an image is requested, that happens to be used as Site Icon.
*
* @since 4.3.0
*
* @param null|array|string $value The value get_metadata() should return a single metadata value, or an
* array of values.
* @param int $post_id Post ID.
* @param string $meta_key Meta key.
* @param bool $single Whether to return only the first value of the specified `$meta_key`.
* @return array|null|string The attachment metadata value, array of values, or null.
*/
public function get_post_metadata( $value, $post_id, $meta_key, $single ) {
if ( $single && '_wp_attachment_backup_sizes' === $meta_key ) {
$site_icon_id = (int) get_option( 'site_icon' );
if ( $post_id === $site_icon_id ) {
add_filter( 'intermediate_image_sizes', array( $this, 'intermediate_image_sizes' ) );
}
}
return $value;
}
}

View File

@ -0,0 +1,755 @@
<?php
/**
* List Table API: WP_Terms_List_Table class
*
* @package WordPress
* @subpackage Administration
* @since 3.1.0
*/
/**
* Core class used to implement displaying terms in a list table.
*
* @since 3.1.0
*
* @see WP_List_Table
*/
class WP_Terms_List_Table extends WP_List_Table {
public $callback_args;
private $level;
/**
* Constructor.
*
* @since 3.1.0
*
* @see WP_List_Table::__construct() for more information on default arguments.
*
* @global string $post_type
* @global string $taxonomy
* @global string $action
* @global object $tax
*
* @param array $args An associative array of arguments.
*/
public function __construct( $args = array() ) {
global $post_type, $taxonomy, $action, $tax;
parent::__construct(
array(
'plural' => 'tags',
'singular' => 'tag',
'screen' => isset( $args['screen'] ) ? $args['screen'] : null,
)
);
$action = $this->screen->action;
$post_type = $this->screen->post_type;
$taxonomy = $this->screen->taxonomy;
if ( empty( $taxonomy ) ) {
$taxonomy = 'post_tag';
}
if ( ! taxonomy_exists( $taxonomy ) ) {
wp_die( __( 'Invalid taxonomy.' ) );
}
$tax = get_taxonomy( $taxonomy );
// @todo Still needed? Maybe just the show_ui part.
if ( empty( $post_type ) || ! in_array( $post_type, get_post_types( array( 'show_ui' => true ) ), true ) ) {
$post_type = 'post';
}
}
/**
* @return bool
*/
public function ajax_user_can() {
return current_user_can( get_taxonomy( $this->screen->taxonomy )->cap->manage_terms );
}
/**
*/
public function prepare_items() {
$taxonomy = $this->screen->taxonomy;
$tags_per_page = $this->get_items_per_page( "edit_{$taxonomy}_per_page" );
if ( 'post_tag' === $taxonomy ) {
/**
* Filters the number of terms displayed per page for the Tags list table.
*
* @since 2.8.0
*
* @param int $tags_per_page Number of tags to be displayed. Default 20.
*/
$tags_per_page = apply_filters( 'edit_tags_per_page', $tags_per_page );
/**
* Filters the number of terms displayed per page for the Tags list table.
*
* @since 2.7.0
* @deprecated 2.8.0 Use {@see 'edit_tags_per_page'} instead.
*
* @param int $tags_per_page Number of tags to be displayed. Default 20.
*/
$tags_per_page = apply_filters_deprecated( 'tagsperpage', array( $tags_per_page ), '2.8.0', 'edit_tags_per_page' );
} elseif ( 'category' === $taxonomy ) {
/**
* Filters the number of terms displayed per page for the Categories list table.
*
* @since 2.8.0
*
* @param int $tags_per_page Number of categories to be displayed. Default 20.
*/
$tags_per_page = apply_filters( 'edit_categories_per_page', $tags_per_page );
}
$search = ! empty( $_REQUEST['s'] ) ? trim( wp_unslash( $_REQUEST['s'] ) ) : '';
$args = array(
'taxonomy' => $taxonomy,
'search' => $search,
'page' => $this->get_pagenum(),
'number' => $tags_per_page,
'hide_empty' => 0,
);
if ( ! empty( $_REQUEST['orderby'] ) ) {
$args['orderby'] = trim( wp_unslash( $_REQUEST['orderby'] ) );
}
if ( ! empty( $_REQUEST['order'] ) ) {
$args['order'] = trim( wp_unslash( $_REQUEST['order'] ) );
}
$args['offset'] = ( $args['page'] - 1 ) * $args['number'];
// Save the values because 'number' and 'offset' can be subsequently overridden.
$this->callback_args = $args;
if ( is_taxonomy_hierarchical( $taxonomy ) && ! isset( $args['orderby'] ) ) {
// We'll need the full set of terms then.
$args['number'] = 0;
$args['offset'] = $args['number'];
}
$this->items = get_terms( $args );
$this->set_pagination_args(
array(
'total_items' => wp_count_terms(
array(
'taxonomy' => $taxonomy,
'search' => $search,
)
),
'per_page' => $tags_per_page,
)
);
}
/**
*/
public function no_items() {
echo get_taxonomy( $this->screen->taxonomy )->labels->not_found;
}
/**
* @return array
*/
protected function get_bulk_actions() {
$actions = array();
if ( current_user_can( get_taxonomy( $this->screen->taxonomy )->cap->delete_terms ) ) {
$actions['delete'] = __( 'Delete' );
}
return $actions;
}
/**
* @return string
*/
public function current_action() {
if ( isset( $_REQUEST['action'] ) && isset( $_REQUEST['delete_tags'] ) && 'delete' === $_REQUEST['action'] ) {
return 'bulk-delete';
}
return parent::current_action();
}
/**
* @return string[] Array of column titles keyed by their column name.
*/
public function get_columns() {
$columns = array(
'cb' => '<input type="checkbox" />',
'name' => _x( 'Name', 'term name' ),
'description' => __( 'Description' ),
'slug' => __( 'Slug' ),
);
if ( 'link_category' === $this->screen->taxonomy ) {
$columns['links'] = __( 'Links' );
} else {
$columns['posts'] = _x( 'Count', 'Number/count of items' );
}
return $columns;
}
/**
* @return array
*/
protected function get_sortable_columns() {
$taxonomy = $this->screen->taxonomy;
if ( ! isset( $_GET['orderby'] ) && is_taxonomy_hierarchical( $taxonomy ) ) {
$name_orderby_text = __( 'Table ordered hierarchically.' );
} else {
$name_orderby_text = __( 'Table ordered by Name.' );
}
return array(
'name' => array( 'name', false, _x( 'Name', 'term name' ), $name_orderby_text, 'asc' ),
'description' => array( 'description', false, __( 'Description' ), __( 'Table ordered by Description.' ) ),
'slug' => array( 'slug', false, __( 'Slug' ), __( 'Table ordered by Slug.' ) ),
'posts' => array( 'count', false, _x( 'Count', 'Number/count of items' ), __( 'Table ordered by Posts Count.' ) ),
'links' => array( 'count', false, __( 'Links' ), __( 'Table ordered by Links.' ) ),
);
}
/**
*/
public function display_rows_or_placeholder() {
$taxonomy = $this->screen->taxonomy;
$number = $this->callback_args['number'];
$offset = $this->callback_args['offset'];
// Convert it to table rows.
$count = 0;
if ( empty( $this->items ) || ! is_array( $this->items ) ) {
echo '<tr class="no-items"><td class="colspanchange" colspan="' . $this->get_column_count() . '">';
$this->no_items();
echo '</td></tr>';
return;
}
if ( is_taxonomy_hierarchical( $taxonomy ) && ! isset( $this->callback_args['orderby'] ) ) {
if ( ! empty( $this->callback_args['search'] ) ) {// Ignore children on searches.
$children = array();
} else {
$children = _get_term_hierarchy( $taxonomy );
}
/*
* Some funky recursion to get the job done (paging & parents mainly) is contained within.
* Skip it for non-hierarchical taxonomies for performance sake.
*/
$this->_rows( $taxonomy, $this->items, $children, $offset, $number, $count );
} else {
foreach ( $this->items as $term ) {
$this->single_row( $term );
}
}
}
/**
* @param string $taxonomy
* @param array $terms
* @param array $children
* @param int $start
* @param int $per_page
* @param int $count
* @param int $parent_term
* @param int $level
*/
private function _rows( $taxonomy, $terms, &$children, $start, $per_page, &$count, $parent_term = 0, $level = 0 ) {
$end = $start + $per_page;
foreach ( $terms as $key => $term ) {
if ( $count >= $end ) {
break;
}
if ( $term->parent !== $parent_term && empty( $_REQUEST['s'] ) ) {
continue;
}
// If the page starts in a subtree, print the parents.
if ( $count === $start && $term->parent > 0 && empty( $_REQUEST['s'] ) ) {
$my_parents = array();
$parent_ids = array();
$p = $term->parent;
while ( $p ) {
$my_parent = get_term( $p, $taxonomy );
$my_parents[] = $my_parent;
$p = $my_parent->parent;
if ( in_array( $p, $parent_ids, true ) ) { // Prevent parent loops.
break;
}
$parent_ids[] = $p;
}
unset( $parent_ids );
$num_parents = count( $my_parents );
while ( $my_parent = array_pop( $my_parents ) ) {
echo "\t";
$this->single_row( $my_parent, $level - $num_parents );
--$num_parents;
}
}
if ( $count >= $start ) {
echo "\t";
$this->single_row( $term, $level );
}
++$count;
unset( $terms[ $key ] );
if ( isset( $children[ $term->term_id ] ) && empty( $_REQUEST['s'] ) ) {
$this->_rows( $taxonomy, $terms, $children, $start, $per_page, $count, $term->term_id, $level + 1 );
}
}
}
/**
* @global string $taxonomy
* @param WP_Term $tag Term object.
* @param int $level
*/
public function single_row( $tag, $level = 0 ) {
global $taxonomy;
$tag = sanitize_term( $tag, $taxonomy );
$this->level = $level;
if ( $tag->parent ) {
$count = count( get_ancestors( $tag->term_id, $taxonomy, 'taxonomy' ) );
$level = 'level-' . $count;
} else {
$level = 'level-0';
}
echo '<tr id="tag-' . $tag->term_id . '" class="' . $level . '">';
$this->single_row_columns( $tag );
echo '</tr>';
}
/**
* @since 5.9.0 Renamed `$tag` to `$item` to match parent class for PHP 8 named parameter support.
*
* @param WP_Term $item Term object.
* @return string
*/
public function column_cb( $item ) {
// Restores the more descriptive, specific name for use within this method.
$tag = $item;
if ( current_user_can( 'delete_term', $tag->term_id ) ) {
return sprintf(
'<input type="checkbox" name="delete_tags[]" value="%1$s" id="cb-select-%1$s" />' .
'<label for="cb-select-%1$s"><span class="screen-reader-text">%2$s</span></label>',
$tag->term_id,
/* translators: Hidden accessibility text. %s: Taxonomy term name. */
sprintf( __( 'Select %s' ), $tag->name )
);
}
return '&nbsp;';
}
/**
* @param WP_Term $tag Term object.
* @return string
*/
public function column_name( $tag ) {
$taxonomy = $this->screen->taxonomy;
$pad = str_repeat( '&#8212; ', max( 0, $this->level ) );
/**
* Filters display of the term name in the terms list table.
*
* The default output may include padding due to the term's
* current level in the term hierarchy.
*
* @since 2.5.0
*
* @see WP_Terms_List_Table::column_name()
*
* @param string $pad_tag_name The term name, padded if not top-level.
* @param WP_Term $tag Term object.
*/
$name = apply_filters( 'term_name', $pad . ' ' . $tag->name, $tag );
$qe_data = get_term( $tag->term_id, $taxonomy, OBJECT, 'edit' );
$uri = wp_doing_ajax() ? wp_get_referer() : $_SERVER['REQUEST_URI'];
$edit_link = get_edit_term_link( $tag, $taxonomy, $this->screen->post_type );
if ( $edit_link ) {
$edit_link = add_query_arg(
'wp_http_referer',
urlencode( wp_unslash( $uri ) ),
$edit_link
);
$name = sprintf(
'<a class="row-title" href="%s" aria-label="%s">%s</a>',
esc_url( $edit_link ),
/* translators: %s: Taxonomy term name. */
esc_attr( sprintf( __( '&#8220;%s&#8221; (Edit)' ), $tag->name ) ),
$name
);
}
$output = sprintf(
'<strong>%s</strong><br />',
$name
);
/** This filter is documented in wp-admin/includes/class-wp-terms-list-table.php */
$quick_edit_enabled = apply_filters( 'quick_edit_enabled_for_taxonomy', true, $taxonomy );
if ( $quick_edit_enabled ) {
$output .= '<div class="hidden" id="inline_' . $qe_data->term_id . '">';
$output .= '<div class="name">' . $qe_data->name . '</div>';
/** This filter is documented in wp-admin/edit-tag-form.php */
$output .= '<div class="slug">' . apply_filters( 'editable_slug', $qe_data->slug, $qe_data ) . '</div>';
$output .= '<div class="parent">' . $qe_data->parent . '</div></div>';
}
return $output;
}
/**
* Gets the name of the default primary column.
*
* @since 4.3.0
*
* @return string Name of the default primary column, in this case, 'name'.
*/
protected function get_default_primary_column_name() {
return 'name';
}
/**
* Generates and displays row action links.
*
* @since 4.3.0
* @since 5.9.0 Renamed `$tag` to `$item` to match parent class for PHP 8 named parameter support.
*
* @param WP_Term $item Tag being acted upon.
* @param string $column_name Current column name.
* @param string $primary Primary column name.
* @return string Row actions output for terms, or an empty string
* if the current column is not the primary column.
*/
protected function handle_row_actions( $item, $column_name, $primary ) {
if ( $primary !== $column_name ) {
return '';
}
// Restores the more descriptive, specific name for use within this method.
$tag = $item;
$taxonomy = $this->screen->taxonomy;
$uri = wp_doing_ajax() ? wp_get_referer() : $_SERVER['REQUEST_URI'];
$actions = array();
if ( current_user_can( 'edit_term', $tag->term_id ) ) {
$actions['edit'] = sprintf(
'<a href="%s" aria-label="%s">%s</a>',
esc_url(
add_query_arg(
'wp_http_referer',
urlencode( wp_unslash( $uri ) ),
get_edit_term_link( $tag, $taxonomy, $this->screen->post_type )
)
),
/* translators: %s: Taxonomy term name. */
esc_attr( sprintf( __( 'Edit &#8220;%s&#8221;' ), $tag->name ) ),
__( 'Edit' )
);
/**
* Filters whether Quick Edit should be enabled for the given taxonomy.
*
* @since 6.4.0
*
* @param bool $enable Whether to enable the Quick Edit functionality. Default true.
* @param string $taxonomy Taxonomy name.
*/
$quick_edit_enabled = apply_filters( 'quick_edit_enabled_for_taxonomy', true, $taxonomy );
if ( $quick_edit_enabled ) {
$actions['inline hide-if-no-js'] = sprintf(
'<button type="button" class="button-link editinline" aria-label="%s" aria-expanded="false">%s</button>',
/* translators: %s: Taxonomy term name. */
esc_attr( sprintf( __( 'Quick edit &#8220;%s&#8221; inline' ), $tag->name ) ),
__( 'Quick&nbsp;Edit' )
);
}
}
if ( current_user_can( 'delete_term', $tag->term_id ) ) {
$actions['delete'] = sprintf(
'<a href="%s" class="delete-tag aria-button-if-js" aria-label="%s">%s</a>',
wp_nonce_url( "edit-tags.php?action=delete&amp;taxonomy=$taxonomy&amp;tag_ID=$tag->term_id", 'delete-tag_' . $tag->term_id ),
/* translators: %s: Taxonomy term name. */
esc_attr( sprintf( __( 'Delete &#8220;%s&#8221;' ), $tag->name ) ),
__( 'Delete' )
);
}
if ( is_term_publicly_viewable( $tag ) ) {
$actions['view'] = sprintf(
'<a href="%s" aria-label="%s">%s</a>',
get_term_link( $tag ),
/* translators: %s: Taxonomy term name. */
esc_attr( sprintf( __( 'View &#8220;%s&#8221; archive' ), $tag->name ) ),
__( 'View' )
);
}
/**
* Filters the action links displayed for each term in the Tags list table.
*
* @since 2.8.0
* @since 3.0.0 Deprecated in favor of {@see '{$taxonomy}_row_actions'} filter.
* @since 5.4.2 Restored (un-deprecated).
*
* @param string[] $actions An array of action links to be displayed. Default
* 'Edit', 'Quick Edit', 'Delete', and 'View'.
* @param WP_Term $tag Term object.
*/
$actions = apply_filters( 'tag_row_actions', $actions, $tag );
/**
* Filters the action links displayed for each term in the terms list table.
*
* The dynamic portion of the hook name, `$taxonomy`, refers to the taxonomy slug.
*
* Possible hook names include:
*
* - `category_row_actions`
* - `post_tag_row_actions`
*
* @since 3.0.0
*
* @param string[] $actions An array of action links to be displayed. Default
* 'Edit', 'Quick Edit', 'Delete', and 'View'.
* @param WP_Term $tag Term object.
*/
$actions = apply_filters( "{$taxonomy}_row_actions", $actions, $tag );
return $this->row_actions( $actions );
}
/**
* @param WP_Term $tag Term object.
* @return string
*/
public function column_description( $tag ) {
if ( $tag->description ) {
return $tag->description;
} else {
return '<span aria-hidden="true">&#8212;</span><span class="screen-reader-text">' .
/* translators: Hidden accessibility text. */
__( 'No description' ) .
'</span>';
}
}
/**
* @param WP_Term $tag Term object.
* @return string
*/
public function column_slug( $tag ) {
/** This filter is documented in wp-admin/edit-tag-form.php */
return apply_filters( 'editable_slug', $tag->slug, $tag );
}
/**
* @param WP_Term $tag Term object.
* @return string
*/
public function column_posts( $tag ) {
$count = number_format_i18n( $tag->count );
$tax = get_taxonomy( $this->screen->taxonomy );
$ptype_object = get_post_type_object( $this->screen->post_type );
if ( ! $ptype_object->show_ui ) {
return $count;
}
if ( $tax->query_var ) {
$args = array( $tax->query_var => $tag->slug );
} else {
$args = array(
'taxonomy' => $tax->name,
'term' => $tag->slug,
);
}
if ( 'post' !== $this->screen->post_type ) {
$args['post_type'] = $this->screen->post_type;
}
if ( 'attachment' === $this->screen->post_type ) {
return "<a href='" . esc_url( add_query_arg( $args, 'upload.php' ) ) . "'>$count</a>";
}
return "<a href='" . esc_url( add_query_arg( $args, 'edit.php' ) ) . "'>$count</a>";
}
/**
* @param WP_Term $tag Term object.
* @return string
*/
public function column_links( $tag ) {
$count = number_format_i18n( $tag->count );
if ( $count ) {
$count = "<a href='link-manager.php?cat_id=$tag->term_id'>$count</a>";
}
return $count;
}
/**
* @since 5.9.0 Renamed `$tag` to `$item` to match parent class for PHP 8 named parameter support.
*
* @param WP_Term $item Term object.
* @param string $column_name Name of the column.
* @return string
*/
public function column_default( $item, $column_name ) {
// Restores the more descriptive, specific name for use within this method.
$tag = $item;
/**
* Filters the displayed columns in the terms list table.
*
* The dynamic portion of the hook name, `$this->screen->taxonomy`,
* refers to the slug of the current taxonomy.
*
* Possible hook names include:
*
* - `manage_category_custom_column`
* - `manage_post_tag_custom_column`
*
* @since 2.8.0
*
* @param string $string Custom column output. Default empty.
* @param string $column_name Name of the column.
* @param int $term_id Term ID.
*/
return apply_filters( "manage_{$this->screen->taxonomy}_custom_column", '', $column_name, $tag->term_id );
}
/**
* Outputs the hidden row displayed when inline editing
*
* @since 3.1.0
*/
public function inline_edit() {
$tax = get_taxonomy( $this->screen->taxonomy );
if ( ! current_user_can( $tax->cap->edit_terms ) ) {
return;
}
?>
<form method="get">
<table style="display: none"><tbody id="inlineedit">
<tr id="inline-edit" class="inline-edit-row" style="display: none">
<td colspan="<?php echo $this->get_column_count(); ?>" class="colspanchange">
<div class="inline-edit-wrapper">
<fieldset>
<legend class="inline-edit-legend"><?php _e( 'Quick Edit' ); ?></legend>
<div class="inline-edit-col">
<label>
<span class="title"><?php _ex( 'Name', 'term name' ); ?></span>
<span class="input-text-wrap"><input type="text" name="name" class="ptitle" value="" /></span>
</label>
<label>
<span class="title"><?php _e( 'Slug' ); ?></span>
<span class="input-text-wrap"><input type="text" name="slug" class="ptitle" value="" /></span>
</label>
</div>
</fieldset>
<?php
$core_columns = array(
'cb' => true,
'description' => true,
'name' => true,
'slug' => true,
'posts' => true,
);
list( $columns ) = $this->get_column_info();
foreach ( $columns as $column_name => $column_display_name ) {
if ( isset( $core_columns[ $column_name ] ) ) {
continue;
}
/** This action is documented in wp-admin/includes/class-wp-posts-list-table.php */
do_action( 'quick_edit_custom_box', $column_name, 'edit-tags', $this->screen->taxonomy );
}
?>
<div class="inline-edit-save submit">
<button type="button" class="save button button-primary"><?php echo $tax->labels->update_item; ?></button>
<button type="button" class="cancel button"><?php _e( 'Cancel' ); ?></button>
<span class="spinner"></span>
<?php wp_nonce_field( 'taxinlineeditnonce', '_inline_edit', false ); ?>
<input type="hidden" name="taxonomy" value="<?php echo esc_attr( $this->screen->taxonomy ); ?>" />
<input type="hidden" name="post_type" value="<?php echo esc_attr( $this->screen->post_type ); ?>" />
<?php
wp_admin_notice(
'<p class="error"></p>',
array(
'type' => 'error',
'additional_classes' => array( 'notice-alt', 'inline', 'hidden' ),
'paragraph_wrap' => false,
)
);
?>
</div>
</div>
</td></tr>
</tbody></table>
</form>
<?php
}
}

View File

@ -0,0 +1,570 @@
<?php
/**
* List Table API: WP_Theme_Install_List_Table class
*
* @package WordPress
* @subpackage Administration
* @since 3.1.0
*/
/**
* Core class used to implement displaying themes to install in a list table.
*
* @since 3.1.0
*
* @see WP_Themes_List_Table
*/
class WP_Theme_Install_List_Table extends WP_Themes_List_Table {
public $features = array();
/**
* @return bool
*/
public function ajax_user_can() {
return current_user_can( 'install_themes' );
}
/**
* @global array $tabs
* @global string $tab
* @global int $paged
* @global string $type
* @global array $theme_field_defaults
*/
public function prepare_items() {
require ABSPATH . 'wp-admin/includes/theme-install.php';
global $tabs, $tab, $paged, $type, $theme_field_defaults;
wp_reset_vars( array( 'tab' ) );
$search_terms = array();
$search_string = '';
if ( ! empty( $_REQUEST['s'] ) ) {
$search_string = strtolower( wp_unslash( $_REQUEST['s'] ) );
$search_terms = array_unique( array_filter( array_map( 'trim', explode( ',', $search_string ) ) ) );
}
if ( ! empty( $_REQUEST['features'] ) ) {
$this->features = $_REQUEST['features'];
}
$paged = $this->get_pagenum();
$per_page = 36;
// These are the tabs which are shown on the page,
$tabs = array();
$tabs['dashboard'] = __( 'Search' );
if ( 'search' === $tab ) {
$tabs['search'] = __( 'Search Results' );
}
$tabs['upload'] = __( 'Upload' );
$tabs['featured'] = _x( 'Featured', 'themes' );
//$tabs['popular'] = _x( 'Popular', 'themes' );
$tabs['new'] = _x( 'Latest', 'themes' );
$tabs['updated'] = _x( 'Recently Updated', 'themes' );
$nonmenu_tabs = array( 'theme-information' ); // Valid actions to perform which do not have a Menu item.
/** This filter is documented in wp-admin/theme-install.php */
$tabs = apply_filters( 'install_themes_tabs', $tabs );
/**
* Filters tabs not associated with a menu item on the Install Themes screen.
*
* @since 2.8.0
*
* @param string[] $nonmenu_tabs The tabs that don't have a menu item on
* the Install Themes screen.
*/
$nonmenu_tabs = apply_filters( 'install_themes_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 );
}
$args = array(
'page' => $paged,
'per_page' => $per_page,
'fields' => $theme_field_defaults,
);
switch ( $tab ) {
case 'search':
$type = isset( $_REQUEST['type'] ) ? wp_unslash( $_REQUEST['type'] ) : 'term';
switch ( $type ) {
case 'tag':
$args['tag'] = array_map( 'sanitize_key', $search_terms );
break;
case 'term':
$args['search'] = $search_string;
break;
case 'author':
$args['author'] = $search_string;
break;
}
if ( ! empty( $this->features ) ) {
$args['tag'] = $this->features;
$_REQUEST['s'] = implode( ',', $this->features );
$_REQUEST['type'] = 'tag';
}
add_action( 'install_themes_table_header', 'install_theme_search_form', 10, 0 );
break;
case 'featured':
// case 'popular':
case 'new':
case 'updated':
$args['browse'] = $tab;
break;
default:
$args = false;
break;
}
/**
* Filters API request arguments for each Install Themes screen tab.
*
* The dynamic portion of the hook name, `$tab`, refers to the theme install
* tab.
*
* Possible hook names include:
*
* - `install_themes_table_api_args_dashboard`
* - `install_themes_table_api_args_featured`
* - `install_themes_table_api_args_new`
* - `install_themes_table_api_args_search`
* - `install_themes_table_api_args_updated`
* - `install_themes_table_api_args_upload`
*
* @since 3.7.0
*
* @param array|false $args Theme install API arguments.
*/
$args = apply_filters( "install_themes_table_api_args_{$tab}", $args );
if ( ! $args ) {
return;
}
$api = themes_api( 'query_themes', $args );
if ( is_wp_error( $api ) ) {
wp_die( '<p>' . $api->get_error_message() . '</p> <p><a href="#" onclick="document.location.reload(); return false;">' . __( 'Try Again' ) . '</a></p>' );
}
$this->items = $api->themes;
$this->set_pagination_args(
array(
'total_items' => $api->info['results'],
'per_page' => $args['per_page'],
'infinite_scroll' => true,
)
);
}
/**
*/
public function no_items() {
_e( 'No themes match your request.' );
}
/**
* @global array $tabs
* @global string $tab
* @return array
*/
protected function get_views() {
global $tabs, $tab;
$display_tabs = array();
foreach ( (array) $tabs as $action => $text ) {
$display_tabs[ 'theme-install-' . $action ] = array(
'url' => self_admin_url( 'theme-install.php?tab=' . $action ),
'label' => $text,
'current' => $action === $tab,
);
}
return $this->get_views_links( $display_tabs );
}
/**
* Displays the theme install table.
*
* Overrides the parent display() method to provide a different container.
*
* @since 3.1.0
*/
public function display() {
wp_nonce_field( 'fetch-list-' . get_class( $this ), '_ajax_fetch_list_nonce' );
?>
<div class="tablenav top themes">
<div class="alignleft actions">
<?php
/**
* Fires in the Install Themes list table header.
*
* @since 2.8.0
*/
do_action( 'install_themes_table_header' );
?>
</div>
<?php $this->pagination( 'top' ); ?>
<br class="clear" />
</div>
<div id="availablethemes">
<?php $this->display_rows_or_placeholder(); ?>
</div>
<?php
$this->tablenav( 'bottom' );
}
/**
*/
public function display_rows() {
$themes = $this->items;
foreach ( $themes as $theme ) {
?>
<div class="available-theme installable-theme">
<?php
$this->single_row( $theme );
?>
</div>
<?php
} // End foreach $theme_names.
$this->theme_installer();
}
/**
* Prints a theme from the WordPress.org API.
*
* @since 3.1.0
*
* @global array $themes_allowedtags
*
* @param stdClass $theme {
* An object that contains theme data returned by the WordPress.org API.
*
* @type string $name Theme name, e.g. 'Twenty Twenty-One'.
* @type string $slug Theme slug, e.g. 'twentytwentyone'.
* @type string $version Theme version, e.g. '1.1'.
* @type string $author Theme author username, e.g. 'melchoyce'.
* @type string $preview_url Preview URL, e.g. 'https://2021.wordpress.net/'.
* @type string $screenshot_url Screenshot URL, e.g. 'https://wordpress.org/themes/twentytwentyone/'.
* @type float $rating Rating score.
* @type int $num_ratings The number of ratings.
* @type string $homepage Theme homepage, e.g. 'https://wordpress.org/themes/twentytwentyone/'.
* @type string $description Theme description.
* @type string $download_link Theme ZIP download URL.
* }
*/
public function single_row( $theme ) {
global $themes_allowedtags;
if ( empty( $theme ) ) {
return;
}
$name = wp_kses( $theme->name, $themes_allowedtags );
$author = wp_kses( $theme->author, $themes_allowedtags );
/* translators: %s: Theme name. */
$preview_title = sprintf( __( 'Preview &#8220;%s&#8221;' ), $name );
$preview_url = add_query_arg(
array(
'tab' => 'theme-information',
'theme' => $theme->slug,
),
self_admin_url( 'theme-install.php' )
);
$actions = array();
$install_url = add_query_arg(
array(
'action' => 'install-theme',
'theme' => $theme->slug,
),
self_admin_url( 'update.php' )
);
$update_url = add_query_arg(
array(
'action' => 'upgrade-theme',
'theme' => $theme->slug,
),
self_admin_url( 'update.php' )
);
$status = $this->_get_theme_status( $theme );
switch ( $status ) {
case 'update_available':
$actions[] = sprintf(
'<a class="install-now" href="%s" title="%s">%s</a>',
esc_url( wp_nonce_url( $update_url, 'upgrade-theme_' . $theme->slug ) ),
/* translators: %s: Theme version. */
esc_attr( sprintf( __( 'Update to version %s' ), $theme->version ) ),
__( 'Update' )
);
break;
case 'newer_installed':
case 'latest_installed':
$actions[] = sprintf(
'<span class="install-now" title="%s">%s</span>',
esc_attr__( 'This theme is already installed and is up to date' ),
_x( 'Installed', 'theme' )
);
break;
case 'install':
default:
$actions[] = sprintf(
'<a class="install-now" href="%s" title="%s">%s</a>',
esc_url( wp_nonce_url( $install_url, 'install-theme_' . $theme->slug ) ),
/* translators: %s: Theme name. */
esc_attr( sprintf( _x( 'Install %s', 'theme' ), $name ) ),
_x( 'Install Now', 'theme' )
);
break;
}
$actions[] = sprintf(
'<a class="install-theme-preview" href="%s" title="%s">%s</a>',
esc_url( $preview_url ),
/* translators: %s: Theme name. */
esc_attr( sprintf( __( 'Preview %s' ), $name ) ),
__( 'Preview' )
);
/**
* Filters the install action links for a theme in the Install Themes list table.
*
* @since 3.4.0
*
* @param string[] $actions An array of theme action links. Defaults are
* links to Install Now, Preview, and Details.
* @param stdClass $theme An object that contains theme data returned by the
* WordPress.org API.
*/
$actions = apply_filters( 'theme_install_actions', $actions, $theme );
?>
<a class="screenshot install-theme-preview" href="<?php echo esc_url( $preview_url ); ?>" title="<?php echo esc_attr( $preview_title ); ?>">
<img src="<?php echo esc_url( $theme->screenshot_url . '?ver=' . $theme->version ); ?>" width="150" alt="" />
</a>
<h3><?php echo $name; ?></h3>
<div class="theme-author">
<?php
/* translators: %s: Theme author. */
printf( __( 'By %s' ), $author );
?>
</div>
<div class="action-links">
<ul>
<?php foreach ( $actions as $action ) : ?>
<li><?php echo $action; ?></li>
<?php endforeach; ?>
<li class="hide-if-no-js"><a href="#" class="theme-detail"><?php _e( 'Details' ); ?></a></li>
</ul>
</div>
<?php
$this->install_theme_info( $theme );
}
/**
* Prints the wrapper for the theme installer.
*/
public function theme_installer() {
?>
<div id="theme-installer" class="wp-full-overlay expanded">
<div class="wp-full-overlay-sidebar">
<div class="wp-full-overlay-header">
<a href="#" class="close-full-overlay button"><?php _e( 'Close' ); ?></a>
<span class="theme-install"></span>
</div>
<div class="wp-full-overlay-sidebar-content">
<div class="install-theme-info"></div>
</div>
<div class="wp-full-overlay-footer">
<button type="button" class="collapse-sidebar button" aria-expanded="true" aria-label="<?php esc_attr_e( 'Collapse Sidebar' ); ?>">
<span class="collapse-sidebar-arrow"></span>
<span class="collapse-sidebar-label"><?php _e( 'Collapse' ); ?></span>
</button>
</div>
</div>
<div class="wp-full-overlay-main"></div>
</div>
<?php
}
/**
* Prints the wrapper for the theme installer with a provided theme's data.
* Used to make the theme installer work for no-js.
*
* @param stdClass $theme A WordPress.org Theme API object.
*/
public function theme_installer_single( $theme ) {
?>
<div id="theme-installer" class="wp-full-overlay single-theme">
<div class="wp-full-overlay-sidebar">
<?php $this->install_theme_info( $theme ); ?>
</div>
<div class="wp-full-overlay-main">
<iframe src="<?php echo esc_url( $theme->preview_url ); ?>"></iframe>
</div>
</div>
<?php
}
/**
* Prints the info for a theme (to be used in the theme installer modal).
*
* @global array $themes_allowedtags
*
* @param stdClass $theme A WordPress.org Theme API object.
*/
public function install_theme_info( $theme ) {
global $themes_allowedtags;
if ( empty( $theme ) ) {
return;
}
$name = wp_kses( $theme->name, $themes_allowedtags );
$author = wp_kses( $theme->author, $themes_allowedtags );
$install_url = add_query_arg(
array(
'action' => 'install-theme',
'theme' => $theme->slug,
),
self_admin_url( 'update.php' )
);
$update_url = add_query_arg(
array(
'action' => 'upgrade-theme',
'theme' => $theme->slug,
),
self_admin_url( 'update.php' )
);
$status = $this->_get_theme_status( $theme );
?>
<div class="install-theme-info">
<?php
switch ( $status ) {
case 'update_available':
printf(
'<a class="theme-install button button-primary" href="%s" title="%s">%s</a>',
esc_url( wp_nonce_url( $update_url, 'upgrade-theme_' . $theme->slug ) ),
/* translators: %s: Theme version. */
esc_attr( sprintf( __( 'Update to version %s' ), $theme->version ) ),
__( 'Update' )
);
break;
case 'newer_installed':
case 'latest_installed':
printf(
'<span class="theme-install" title="%s">%s</span>',
esc_attr__( 'This theme is already installed and is up to date' ),
_x( 'Installed', 'theme' )
);
break;
case 'install':
default:
printf(
'<a class="theme-install button button-primary" href="%s">%s</a>',
esc_url( wp_nonce_url( $install_url, 'install-theme_' . $theme->slug ) ),
__( 'Install' )
);
break;
}
?>
<h3 class="theme-name"><?php echo $name; ?></h3>
<span class="theme-by">
<?php
/* translators: %s: Theme author. */
printf( __( 'By %s' ), $author );
?>
</span>
<?php if ( isset( $theme->screenshot_url ) ) : ?>
<img class="theme-screenshot" src="<?php echo esc_url( $theme->screenshot_url . '?ver=' . $theme->version ); ?>" alt="" />
<?php endif; ?>
<div class="theme-details">
<?php
wp_star_rating(
array(
'rating' => $theme->rating,
'type' => 'percent',
'number' => $theme->num_ratings,
)
);
?>
<div class="theme-version">
<strong><?php _e( 'Version:' ); ?> </strong>
<?php echo wp_kses( $theme->version, $themes_allowedtags ); ?>
</div>
<div class="theme-description">
<?php echo wp_kses( $theme->description, $themes_allowedtags ); ?>
</div>
</div>
<input class="theme-preview-url" type="hidden" value="<?php echo esc_url( $theme->preview_url ); ?>" />
</div>
<?php
}
/**
* Send required variables to JavaScript land
*
* @since 3.4.0
*
* @global string $tab Current tab within Themes->Install screen
* @global string $type Type of search.
*
* @param array $extra_args Unused.
*/
public function _js_vars( $extra_args = array() ) {
global $tab, $type;
parent::_js_vars( compact( 'tab', 'type' ) );
}
/**
* Checks to see if the theme is already installed.
*
* @since 3.4.0
*
* @param stdClass $theme A WordPress.org Theme API object.
* @return string Theme status.
*/
private function _get_theme_status( $theme ) {
$status = 'install';
$installed_theme = wp_get_theme( $theme->slug );
if ( $installed_theme->exists() ) {
if ( version_compare( $installed_theme->get( 'Version' ), $theme->version, '=' ) ) {
$status = 'latest_installed';
} elseif ( version_compare( $installed_theme->get( 'Version' ), $theme->version, '>' ) ) {
$status = 'newer_installed';
} else {
$status = 'update_available';
}
}
return $status;
}
}

View File

@ -0,0 +1,360 @@
<?php
/**
* List Table API: WP_Themes_List_Table class
*
* @package WordPress
* @subpackage Administration
* @since 3.1.0
*/
/**
* Core class used to implement displaying installed themes in a list table.
*
* @since 3.1.0
*
* @see WP_List_Table
*/
class WP_Themes_List_Table extends WP_List_Table {
protected $search_terms = array();
public $features = array();
/**
* Constructor.
*
* @since 3.1.0
*
* @see WP_List_Table::__construct() for more information on default arguments.
*
* @param array $args An associative array of arguments.
*/
public function __construct( $args = array() ) {
parent::__construct(
array(
'ajax' => true,
'screen' => isset( $args['screen'] ) ? $args['screen'] : null,
)
);
}
/**
* @return bool
*/
public function ajax_user_can() {
// Do not check edit_theme_options here. Ajax calls for available themes require switch_themes.
return current_user_can( 'switch_themes' );
}
/**
*/
public function prepare_items() {
$themes = wp_get_themes( array( 'allowed' => true ) );
if ( ! empty( $_REQUEST['s'] ) ) {
$this->search_terms = array_unique( array_filter( array_map( 'trim', explode( ',', strtolower( wp_unslash( $_REQUEST['s'] ) ) ) ) ) );
}
if ( ! empty( $_REQUEST['features'] ) ) {
$this->features = $_REQUEST['features'];
}
if ( $this->search_terms || $this->features ) {
foreach ( $themes as $key => $theme ) {
if ( ! $this->search_theme( $theme ) ) {
unset( $themes[ $key ] );
}
}
}
unset( $themes[ get_option( 'stylesheet' ) ] );
WP_Theme::sort_by_name( $themes );
$per_page = 36;
$page = $this->get_pagenum();
$start = ( $page - 1 ) * $per_page;
$this->items = array_slice( $themes, $start, $per_page, true );
$this->set_pagination_args(
array(
'total_items' => count( $themes ),
'per_page' => $per_page,
'infinite_scroll' => true,
)
);
}
/**
*/
public function no_items() {
if ( $this->search_terms || $this->features ) {
_e( 'No items found.' );
return;
}
$blog_id = get_current_blog_id();
if ( is_multisite() ) {
if ( current_user_can( 'install_themes' ) && current_user_can( 'manage_network_themes' ) ) {
printf(
/* translators: 1: URL to Themes tab on Edit Site screen, 2: URL to Add Themes screen. */
__( 'You only have one theme enabled for this site right now. Visit the Network Admin to <a href="%1$s">enable</a> or <a href="%2$s">install</a> more themes.' ),
network_admin_url( 'site-themes.php?id=' . $blog_id ),
network_admin_url( 'theme-install.php' )
);
return;
} elseif ( current_user_can( 'manage_network_themes' ) ) {
printf(
/* translators: %s: URL to Themes tab on Edit Site screen. */
__( 'You only have one theme enabled for this site right now. Visit the Network Admin to <a href="%s">enable</a> more themes.' ),
network_admin_url( 'site-themes.php?id=' . $blog_id )
);
return;
}
// Else, fallthrough. install_themes doesn't help if you can't enable it.
} else {
if ( current_user_can( 'install_themes' ) ) {
printf(
/* translators: %s: URL to Add Themes screen. */
__( 'You only have one theme installed right now. Live a little! You can choose from over 1,000 free themes in the WordPress Theme Directory at any time: just click on the <a href="%s">Install Themes</a> tab above.' ),
admin_url( 'theme-install.php' )
);
return;
}
}
// Fallthrough.
printf(
/* translators: %s: Network title. */
__( 'Only the active theme is available to you. Contact the %s administrator for information about accessing additional themes.' ),
get_site_option( 'site_name' )
);
}
/**
* @param string $which
*/
public function tablenav( $which = 'top' ) {
if ( $this->get_pagination_arg( 'total_pages' ) <= 1 ) {
return;
}
?>
<div class="tablenav themes <?php echo $which; ?>">
<?php $this->pagination( $which ); ?>
<span class="spinner"></span>
<br class="clear" />
</div>
<?php
}
/**
* Displays the themes table.
*
* Overrides the parent display() method to provide a different container.
*
* @since 3.1.0
*/
public function display() {
wp_nonce_field( 'fetch-list-' . get_class( $this ), '_ajax_fetch_list_nonce' );
?>
<?php $this->tablenav( 'top' ); ?>
<div id="availablethemes">
<?php $this->display_rows_or_placeholder(); ?>
</div>
<?php $this->tablenav( 'bottom' ); ?>
<?php
}
/**
* @return string[] Array of column titles keyed by their column name.
*/
public function get_columns() {
return array();
}
/**
*/
public function display_rows_or_placeholder() {
if ( $this->has_items() ) {
$this->display_rows();
} else {
echo '<div class="no-items">';
$this->no_items();
echo '</div>';
}
}
/**
*/
public function display_rows() {
$themes = $this->items;
foreach ( $themes as $theme ) :
?>
<div class="available-theme">
<?php
$template = $theme->get_template();
$stylesheet = $theme->get_stylesheet();
$title = $theme->display( 'Name' );
$version = $theme->display( 'Version' );
$author = $theme->display( 'Author' );
$activate_link = wp_nonce_url( 'themes.php?action=activate&amp;template=' . urlencode( $template ) . '&amp;stylesheet=' . urlencode( $stylesheet ), 'switch-theme_' . $stylesheet );
$actions = array();
$actions['activate'] = sprintf(
'<a href="%s" class="activatelink" title="%s">%s</a>',
$activate_link,
/* translators: %s: Theme name. */
esc_attr( sprintf( _x( 'Activate &#8220;%s&#8221;', 'theme' ), $title ) ),
_x( 'Activate', 'theme' )
);
if ( current_user_can( 'edit_theme_options' ) && current_user_can( 'customize' ) ) {
$actions['preview'] .= sprintf(
'<a href="%s" class="load-customize hide-if-no-customize">%s</a>',
wp_customize_url( $stylesheet ),
__( 'Live Preview' )
);
}
if ( ! is_multisite() && current_user_can( 'delete_themes' ) ) {
$actions['delete'] = sprintf(
'<a class="submitdelete deletion" href="%s" onclick="return confirm( \'%s\' );">%s</a>',
wp_nonce_url( 'themes.php?action=delete&amp;stylesheet=' . urlencode( $stylesheet ), 'delete-theme_' . $stylesheet ),
/* translators: %s: Theme name. */
esc_js( sprintf( __( "You are about to delete this theme '%s'\n 'Cancel' to stop, 'OK' to delete." ), $title ) ),
__( 'Delete' )
);
}
/** This filter is documented in wp-admin/includes/class-wp-ms-themes-list-table.php */
$actions = apply_filters( 'theme_action_links', $actions, $theme, 'all' );
/** This filter is documented in wp-admin/includes/class-wp-ms-themes-list-table.php */
$actions = apply_filters( "theme_action_links_{$stylesheet}", $actions, $theme, 'all' );
$delete_action = isset( $actions['delete'] ) ? '<div class="delete-theme">' . $actions['delete'] . '</div>' : '';
unset( $actions['delete'] );
$screenshot = $theme->get_screenshot();
?>
<span class="screenshot hide-if-customize">
<?php if ( $screenshot ) : ?>
<img src="<?php echo esc_url( $screenshot . '?ver=' . $theme->version ); ?>" alt="" />
<?php endif; ?>
</span>
<a href="<?php echo wp_customize_url( $stylesheet ); ?>" class="screenshot load-customize hide-if-no-customize">
<?php if ( $screenshot ) : ?>
<img src="<?php echo esc_url( $screenshot . '?ver=' . $theme->version ); ?>" alt="" />
<?php endif; ?>
</a>
<h3><?php echo $title; ?></h3>
<div class="theme-author">
<?php
/* translators: %s: Theme author. */
printf( __( 'By %s' ), $author );
?>
</div>
<div class="action-links">
<ul>
<?php foreach ( $actions as $action ) : ?>
<li><?php echo $action; ?></li>
<?php endforeach; ?>
<li class="hide-if-no-js"><a href="#" class="theme-detail"><?php _e( 'Details' ); ?></a></li>
</ul>
<?php echo $delete_action; ?>
<?php theme_update_available( $theme ); ?>
</div>
<div class="themedetaildiv hide-if-js">
<p><strong><?php _e( 'Version:' ); ?></strong> <?php echo $version; ?></p>
<p><?php echo $theme->display( 'Description' ); ?></p>
<?php
if ( $theme->parent() ) {
printf(
/* translators: 1: Link to documentation on child themes, 2: Name of parent theme. */
' <p class="howto">' . __( 'This <a href="%1$s">child theme</a> requires its parent theme, %2$s.' ) . '</p>',
__( 'https://developer.wordpress.org/themes/advanced-topics/child-themes/' ),
$theme->parent()->display( 'Name' )
);
}
?>
</div>
</div>
<?php
endforeach;
}
/**
* @param WP_Theme $theme
* @return bool
*/
public function search_theme( $theme ) {
// Search the features.
foreach ( $this->features as $word ) {
if ( ! in_array( $word, $theme->get( 'Tags' ), true ) ) {
return false;
}
}
// Match all phrases.
foreach ( $this->search_terms as $word ) {
if ( in_array( $word, $theme->get( 'Tags' ), true ) ) {
continue;
}
foreach ( array( 'Name', 'Description', 'Author', 'AuthorURI' ) as $header ) {
// Don't mark up; Do translate.
if ( false !== stripos( strip_tags( $theme->display( $header, false, true ) ), $word ) ) {
continue 2;
}
}
if ( false !== stripos( $theme->get_stylesheet(), $word ) ) {
continue;
}
if ( false !== stripos( $theme->get_template(), $word ) ) {
continue;
}
return false;
}
return true;
}
/**
* Send required variables to JavaScript land
*
* @since 3.4.0
*
* @param array $extra_args
*/
public function _js_vars( $extra_args = array() ) {
$search_string = isset( $_REQUEST['s'] ) ? esc_attr( wp_unslash( $_REQUEST['s'] ) ) : '';
$args = array(
'search' => $search_string,
'features' => $this->features,
'paged' => $this->get_pagenum(),
'total_pages' => ! empty( $this->_pagination_args['total_pages'] ) ? $this->_pagination_args['total_pages'] : 1,
);
if ( is_array( $extra_args ) ) {
$args = array_merge( $args, $extra_args );
}
printf( "<script type='text/javascript'>var theme_list_args = %s;</script>\n", wp_json_encode( $args ) );
parent::_js_vars();
}
}

View File

@ -0,0 +1,285 @@
<?php
/**
* Upgrader API: WP_Upgrader_Skin class
*
* @package WordPress
* @subpackage Upgrader
* @since 4.6.0
*/
/**
* Generic Skin for the WordPress Upgrader classes. This skin is designed to be extended for specific purposes.
*
* @since 2.8.0
* @since 4.6.0 Moved to its own file from wp-admin/includes/class-wp-upgrader-skins.php.
*/
#[AllowDynamicProperties]
class WP_Upgrader_Skin {
/**
* Holds the upgrader data.
*
* @since 2.8.0
*
* @var WP_Upgrader
*/
public $upgrader;
/**
* Whether header is done.
*
* @since 2.8.0
*
* @var bool
*/
public $done_header = false;
/**
* Whether footer is done.
*
* @since 2.8.0
*
* @var bool
*/
public $done_footer = false;
/**
* Holds the result of an upgrade.
*
* @since 2.8.0
*
* @var string|bool|WP_Error
*/
public $result = false;
/**
* Holds the options of an upgrade.
*
* @since 2.8.0
*
* @var array
*/
public $options = array();
/**
* Constructor.
*
* Sets up the generic skin for the WordPress Upgrader classes.
*
* @since 2.8.0
*
* @param array $args Optional. The WordPress upgrader skin arguments to
* override default options. Default empty array.
*/
public function __construct( $args = array() ) {
$defaults = array(
'url' => '',
'nonce' => '',
'title' => '',
'context' => false,
);
$this->options = wp_parse_args( $args, $defaults );
}
/**
* @since 2.8.0
*
* @param WP_Upgrader $upgrader
*/
public function set_upgrader( &$upgrader ) {
if ( is_object( $upgrader ) ) {
$this->upgrader =& $upgrader;
}
$this->add_strings();
}
/**
* @since 3.0.0
*/
public function add_strings() {
}
/**
* Sets the result of an upgrade.
*
* @since 2.8.0
*
* @param string|bool|WP_Error $result The result of an upgrade.
*/
public function set_result( $result ) {
$this->result = $result;
}
/**
* Displays a form to the user to request for their FTP/SSH details in order
* to connect to the filesystem.
*
* @since 2.8.0
* @since 4.6.0 The `$context` parameter default changed from `false` to an empty string.
*
* @see request_filesystem_credentials()
*
* @param bool|WP_Error $error Optional. Whether the current request has failed to connect,
* or an error object. Default false.
* @param string $context Optional. Full path to the directory that is tested
* for being writable. Default empty.
* @param bool $allow_relaxed_file_ownership Optional. Whether to allow Group/World writable. Default false.
* @return bool True on success, false on failure.
*/
public function request_filesystem_credentials( $error = false, $context = '', $allow_relaxed_file_ownership = false ) {
$url = $this->options['url'];
if ( ! $context ) {
$context = $this->options['context'];
}
if ( ! empty( $this->options['nonce'] ) ) {
$url = wp_nonce_url( $url, $this->options['nonce'] );
}
$extra_fields = array();
return request_filesystem_credentials( $url, '', $error, $context, $extra_fields, $allow_relaxed_file_ownership );
}
/**
* @since 2.8.0
*/
public function header() {
if ( $this->done_header ) {
return;
}
$this->done_header = true;
echo '<div class="wrap">';
echo '<h1>' . $this->options['title'] . '</h1>';
}
/**
* @since 2.8.0
*/
public function footer() {
if ( $this->done_footer ) {
return;
}
$this->done_footer = true;
echo '</div>';
}
/**
* @since 2.8.0
*
* @param string|WP_Error $errors Errors.
*/
public function error( $errors ) {
if ( ! $this->done_header ) {
$this->header();
}
if ( is_string( $errors ) ) {
$this->feedback( $errors );
} elseif ( is_wp_error( $errors ) && $errors->has_errors() ) {
foreach ( $errors->get_error_messages() as $message ) {
if ( $errors->get_error_data() && is_string( $errors->get_error_data() ) ) {
$this->feedback( $message . ' ' . esc_html( strip_tags( $errors->get_error_data() ) ) );
} else {
$this->feedback( $message );
}
}
}
}
/**
* @since 2.8.0
* @since 5.9.0 Renamed `$string` (a PHP reserved keyword) to `$feedback` for PHP 8 named parameter support.
*
* @param string $feedback Message data.
* @param mixed ...$args Optional text replacements.
*/
public function feedback( $feedback, ...$args ) {
if ( isset( $this->upgrader->strings[ $feedback ] ) ) {
$feedback = $this->upgrader->strings[ $feedback ];
}
if ( str_contains( $feedback, '%' ) ) {
if ( $args ) {
$args = array_map( 'strip_tags', $args );
$args = array_map( 'esc_html', $args );
$feedback = vsprintf( $feedback, $args );
}
}
if ( empty( $feedback ) ) {
return;
}
show_message( $feedback );
}
/**
* Performs an action before an update.
*
* @since 2.8.0
*/
public function before() {}
/**
* Performs and action following an update.
*
* @since 2.8.0
*/
public function after() {}
/**
* Outputs JavaScript that calls function to decrement the update counts.
*
* @since 3.9.0
*
* @param string $type Type of update count to decrement. Likely values include 'plugin',
* 'theme', 'translation', etc.
*/
protected function decrement_update_count( $type ) {
if ( ! $this->result || is_wp_error( $this->result ) || 'up_to_date' === $this->result ) {
return;
}
if ( defined( 'IFRAME_REQUEST' ) ) {
echo '<script type="text/javascript">
if ( window.postMessage && JSON ) {
window.parent.postMessage(
JSON.stringify( {
action: "decrementUpdateCount",
upgradeType: "' . $type . '"
} ),
window.location.protocol + "//" + window.location.hostname
+ ( "" !== window.location.port ? ":" + window.location.port : "" )
);
}
</script>';
} else {
echo '<script type="text/javascript">
(function( wp ) {
if ( wp && wp.updates && wp.updates.decrementCount ) {
wp.updates.decrementCount( "' . $type . '" );
}
})( window.wp );
</script>';
}
}
/**
* @since 3.0.0
*/
public function bulk_header() {}
/**
* @since 3.0.0
*/
public function bulk_footer() {}
/**
* Hides the `process_failed` error message when updating by uploading a zip file.
*
* @since 5.5.0
*
* @param WP_Error $wp_error WP_Error object.
* @return bool True if the error should be hidden, false otherwise.
*/
public function hide_process_failed( $wp_error ) {
return false;
}
}

View File

@ -0,0 +1,44 @@
<?php
/**
* The User Interface "Skins" for the WordPress File Upgrader
*
* @package WordPress
* @subpackage Upgrader
* @since 2.8.0
* @deprecated 4.7.0
*/
_deprecated_file( basename( __FILE__ ), '4.7.0', 'class-wp-upgrader.php' );
/** WP_Upgrader_Skin class */
require_once ABSPATH . 'wp-admin/includes/class-wp-upgrader-skin.php';
/** Plugin_Upgrader_Skin class */
require_once ABSPATH . 'wp-admin/includes/class-plugin-upgrader-skin.php';
/** Theme_Upgrader_Skin class */
require_once ABSPATH . 'wp-admin/includes/class-theme-upgrader-skin.php';
/** Bulk_Upgrader_Skin class */
require_once ABSPATH . 'wp-admin/includes/class-bulk-upgrader-skin.php';
/** Bulk_Plugin_Upgrader_Skin class */
require_once ABSPATH . 'wp-admin/includes/class-bulk-plugin-upgrader-skin.php';
/** Bulk_Theme_Upgrader_Skin class */
require_once ABSPATH . 'wp-admin/includes/class-bulk-theme-upgrader-skin.php';
/** Plugin_Installer_Skin class */
require_once ABSPATH . 'wp-admin/includes/class-plugin-installer-skin.php';
/** Theme_Installer_Skin class */
require_once ABSPATH . 'wp-admin/includes/class-theme-installer-skin.php';
/** Language_Pack_Upgrader_Skin class */
require_once ABSPATH . 'wp-admin/includes/class-language-pack-upgrader-skin.php';
/** Automatic_Upgrader_Skin class */
require_once ABSPATH . 'wp-admin/includes/class-automatic-upgrader-skin.php';
/** WP_Ajax_Upgrader_Skin class */
require_once ABSPATH . 'wp-admin/includes/class-wp-ajax-upgrader-skin.php';

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,683 @@
<?php
/**
* List Table API: WP_Users_List_Table class
*
* @package WordPress
* @subpackage Administration
* @since 3.1.0
*/
/**
* Core class used to implement displaying users in a list table.
*
* @since 3.1.0
*
* @see WP_List_Table
*/
class WP_Users_List_Table extends WP_List_Table {
/**
* Site ID to generate the Users list table for.
*
* @since 3.1.0
* @var int
*/
public $site_id;
/**
* Whether or not the current Users list table is for Multisite.
*
* @since 3.1.0
* @var bool
*/
public $is_site_users;
/**
* Constructor.
*
* @since 3.1.0
*
* @see WP_List_Table::__construct() for more information on default arguments.
*
* @param array $args An associative array of arguments.
*/
public function __construct( $args = array() ) {
parent::__construct(
array(
'singular' => 'user',
'plural' => 'users',
'screen' => isset( $args['screen'] ) ? $args['screen'] : null,
)
);
$this->is_site_users = 'site-users-network' === $this->screen->id;
if ( $this->is_site_users ) {
$this->site_id = isset( $_REQUEST['id'] ) ? (int) $_REQUEST['id'] : 0;
}
}
/**
* Checks the current user's permissions.
*
* @since 3.1.0
*
* @return bool
*/
public function ajax_user_can() {
if ( $this->is_site_users ) {
return current_user_can( 'manage_sites' );
} else {
return current_user_can( 'list_users' );
}
}
/**
* Prepares the users list for display.
*
* @since 3.1.0
*
* @global string $role
* @global string $usersearch
*/
public function prepare_items() {
global $role, $usersearch;
$usersearch = isset( $_REQUEST['s'] ) ? wp_unslash( trim( $_REQUEST['s'] ) ) : '';
$role = isset( $_REQUEST['role'] ) ? $_REQUEST['role'] : '';
$per_page = ( $this->is_site_users ) ? 'site_users_network_per_page' : 'users_per_page';
$users_per_page = $this->get_items_per_page( $per_page );
$paged = $this->get_pagenum();
if ( 'none' === $role ) {
$args = array(
'number' => $users_per_page,
'offset' => ( $paged - 1 ) * $users_per_page,
'include' => wp_get_users_with_no_role( $this->site_id ),
'search' => $usersearch,
'fields' => 'all_with_meta',
);
} else {
$args = array(
'number' => $users_per_page,
'offset' => ( $paged - 1 ) * $users_per_page,
'role' => $role,
'search' => $usersearch,
'fields' => 'all_with_meta',
);
}
if ( '' !== $args['search'] ) {
$args['search'] = '*' . $args['search'] . '*';
}
if ( $this->is_site_users ) {
$args['blog_id'] = $this->site_id;
}
if ( isset( $_REQUEST['orderby'] ) ) {
$args['orderby'] = $_REQUEST['orderby'];
}
if ( isset( $_REQUEST['order'] ) ) {
$args['order'] = $_REQUEST['order'];
}
/**
* Filters the query arguments used to retrieve users for the current users list table.
*
* @since 4.4.0
*
* @param array $args Arguments passed to WP_User_Query to retrieve items for the current
* users list table.
*/
$args = apply_filters( 'users_list_table_query_args', $args );
// Query the user IDs for this page.
$wp_user_search = new WP_User_Query( $args );
$this->items = $wp_user_search->get_results();
$this->set_pagination_args(
array(
'total_items' => $wp_user_search->get_total(),
'per_page' => $users_per_page,
)
);
}
/**
* Outputs 'no users' message.
*
* @since 3.1.0
*/
public function no_items() {
_e( 'No users found.' );
}
/**
* Returns an associative array listing all the views that can be used
* with this table.
*
* Provides a list of roles and user count for that role for easy
* filtering of the user table.
*
* @since 3.1.0
*
* @global string $role
*
* @return string[] An array of HTML links keyed by their view.
*/
protected function get_views() {
global $role;
$wp_roles = wp_roles();
$count_users = ! wp_is_large_user_count();
if ( $this->is_site_users ) {
$url = 'site-users.php?id=' . $this->site_id;
} else {
$url = 'users.php';
}
$role_links = array();
$avail_roles = array();
$all_text = __( 'All' );
if ( $count_users ) {
if ( $this->is_site_users ) {
switch_to_blog( $this->site_id );
$users_of_blog = count_users( 'time', $this->site_id );
restore_current_blog();
} else {
$users_of_blog = count_users();
}
$total_users = $users_of_blog['total_users'];
$avail_roles =& $users_of_blog['avail_roles'];
unset( $users_of_blog );
$all_text = sprintf(
/* translators: %s: Number of users. */
_nx(
'All <span class="count">(%s)</span>',
'All <span class="count">(%s)</span>',
$total_users,
'users'
),
number_format_i18n( $total_users )
);
}
$role_links['all'] = array(
'url' => $url,
'label' => $all_text,
'current' => empty( $role ),
);
foreach ( $wp_roles->get_names() as $this_role => $name ) {
if ( $count_users && ! isset( $avail_roles[ $this_role ] ) ) {
continue;
}
$name = translate_user_role( $name );
if ( $count_users ) {
$name = sprintf(
/* translators: 1: User role name, 2: Number of users. */
__( '%1$s <span class="count">(%2$s)</span>' ),
$name,
number_format_i18n( $avail_roles[ $this_role ] )
);
}
$role_links[ $this_role ] = array(
'url' => esc_url( add_query_arg( 'role', $this_role, $url ) ),
'label' => $name,
'current' => $this_role === $role,
);
}
if ( ! empty( $avail_roles['none'] ) ) {
$name = __( 'No role' );
$name = sprintf(
/* translators: 1: User role name, 2: Number of users. */
__( '%1$s <span class="count">(%2$s)</span>' ),
$name,
number_format_i18n( $avail_roles['none'] )
);
$role_links['none'] = array(
'url' => esc_url( add_query_arg( 'role', 'none', $url ) ),
'label' => $name,
'current' => 'none' === $role,
);
}
return $this->get_views_links( $role_links );
}
/**
* Retrieves an associative array of bulk actions available on this table.
*
* @since 3.1.0
*
* @return array Array of bulk action labels keyed by their action.
*/
protected function get_bulk_actions() {
$actions = array();
if ( is_multisite() ) {
if ( current_user_can( 'remove_users' ) ) {
$actions['remove'] = __( 'Remove' );
}
} else {
if ( current_user_can( 'delete_users' ) ) {
$actions['delete'] = __( 'Delete' );
}
}
// Add a password reset link to the bulk actions dropdown.
if ( current_user_can( 'edit_users' ) ) {
$actions['resetpassword'] = __( 'Send password reset' );
}
return $actions;
}
/**
* Outputs the controls to allow user roles to be changed in bulk.
*
* @since 3.1.0
*
* @param string $which Whether this is being invoked above ("top")
* or below the table ("bottom").
*/
protected function extra_tablenav( $which ) {
$id = 'bottom' === $which ? 'new_role2' : 'new_role';
$button_id = 'bottom' === $which ? 'changeit2' : 'changeit';
?>
<div class="alignleft actions">
<?php if ( current_user_can( 'promote_users' ) && $this->has_items() ) : ?>
<label class="screen-reader-text" for="<?php echo $id; ?>">
<?php
/* translators: Hidden accessibility text. */
_e( 'Change role to&hellip;' );
?>
</label>
<select name="<?php echo $id; ?>" id="<?php echo $id; ?>">
<option value=""><?php _e( 'Change role to&hellip;' ); ?></option>
<?php wp_dropdown_roles(); ?>
<option value="none"><?php _e( '&mdash; No role for this site &mdash;' ); ?></option>
</select>
<?php
submit_button( __( 'Change' ), '', $button_id, false );
endif;
/**
* Fires just before the closing div containing the bulk role-change controls
* in the Users list table.
*
* @since 3.5.0
* @since 4.6.0 The `$which` parameter was added.
*
* @param string $which The location of the extra table nav markup: 'top' or 'bottom'.
*/
do_action( 'restrict_manage_users', $which );
?>
</div>
<?php
/**
* Fires immediately following the closing "actions" div in the tablenav for the users
* list table.
*
* @since 4.9.0
*
* @param string $which The location of the extra table nav markup: 'top' or 'bottom'.
*/
do_action( 'manage_users_extra_tablenav', $which );
}
/**
* Captures the bulk action required, and return it.
*
* Overridden from the base class implementation to capture
* the role change drop-down.
*
* @since 3.1.0
*
* @return string The bulk action required.
*/
public function current_action() {
if ( isset( $_REQUEST['changeit'] ) ) {
return 'promote';
}
return parent::current_action();
}
/**
* Gets a list of columns for the list table.
*
* @since 3.1.0
*
* @return string[] Array of column titles keyed by their column name.
*/
public function get_columns() {
$columns = array(
'cb' => '<input type="checkbox" />',
'username' => __( 'Username' ),
'name' => __( 'Name' ),
'email' => __( 'Email' ),
'role' => __( 'Role' ),
'posts' => _x( 'Posts', 'post type general name' ),
);
if ( $this->is_site_users ) {
unset( $columns['posts'] );
}
return $columns;
}
/**
* Gets a list of sortable columns for the list table.
*
* @since 3.1.0
*
* @return array Array of sortable columns.
*/
protected function get_sortable_columns() {
$columns = array(
'username' => array( 'login', false, __( 'Username' ), __( 'Table ordered by Username.' ), 'asc' ),
'email' => array( 'email', false, __( 'E-mail' ), __( 'Table ordered by E-mail.' ) ),
);
return $columns;
}
/**
* Generates the list table rows.
*
* @since 3.1.0
*/
public function display_rows() {
// Query the post counts for this page.
if ( ! $this->is_site_users ) {
$post_counts = count_many_users_posts( array_keys( $this->items ) );
}
foreach ( $this->items as $userid => $user_object ) {
echo "\n\t" . $this->single_row( $user_object, '', '', isset( $post_counts ) ? $post_counts[ $userid ] : 0 );
}
}
/**
* Generates HTML for a single row on the users.php admin panel.
*
* @since 3.1.0
* @since 4.2.0 The `$style` parameter was deprecated.
* @since 4.4.0 The `$role` parameter was deprecated.
*
* @param WP_User $user_object The current user object.
* @param string $style Deprecated. Not used.
* @param string $role Deprecated. Not used.
* @param int $numposts Optional. Post count to display for this user. Defaults
* to zero, as in, a new user has made zero posts.
* @return string Output for a single row.
*/
public function single_row( $user_object, $style = '', $role = '', $numposts = 0 ) {
if ( ! ( $user_object instanceof WP_User ) ) {
$user_object = get_userdata( (int) $user_object );
}
$user_object->filter = 'display';
$email = $user_object->user_email;
if ( $this->is_site_users ) {
$url = "site-users.php?id={$this->site_id}&amp;";
} else {
$url = 'users.php?';
}
$user_roles = $this->get_role_list( $user_object );
// Set up the hover actions for this user.
$actions = array();
$checkbox = '';
$super_admin = '';
if ( is_multisite() && current_user_can( 'manage_network_users' ) ) {
if ( in_array( $user_object->user_login, get_super_admins(), true ) ) {
$super_admin = ' &mdash; ' . __( 'Super Admin' );
}
}
// Check if the user for this row is editable.
if ( current_user_can( 'list_users' ) ) {
// Set up the user editing link.
$edit_link = esc_url(
add_query_arg(
'wp_http_referer',
urlencode( wp_unslash( $_SERVER['REQUEST_URI'] ) ),
get_edit_user_link( $user_object->ID )
)
);
if ( current_user_can( 'edit_user', $user_object->ID ) ) {
$edit = "<strong><a href=\"{$edit_link}\">{$user_object->user_login}</a>{$super_admin}</strong><br />";
$actions['edit'] = '<a href="' . $edit_link . '">' . __( 'Edit' ) . '</a>';
} else {
$edit = "<strong>{$user_object->user_login}{$super_admin}</strong><br />";
}
if ( ! is_multisite()
&& get_current_user_id() !== $user_object->ID
&& current_user_can( 'delete_user', $user_object->ID )
) {
$actions['delete'] = "<a class='submitdelete' href='" . wp_nonce_url( "users.php?action=delete&amp;user=$user_object->ID", 'bulk-users' ) . "'>" . __( 'Delete' ) . '</a>';
}
if ( is_multisite()
&& current_user_can( 'remove_user', $user_object->ID )
) {
$actions['remove'] = "<a class='submitdelete' href='" . wp_nonce_url( $url . "action=remove&amp;user=$user_object->ID", 'bulk-users' ) . "'>" . __( 'Remove' ) . '</a>';
}
// Add a link to the user's author archive, if not empty.
$author_posts_url = get_author_posts_url( $user_object->ID );
if ( $author_posts_url ) {
$actions['view'] = sprintf(
'<a href="%s" aria-label="%s">%s</a>',
esc_url( $author_posts_url ),
/* translators: %s: Author's display name. */
esc_attr( sprintf( __( 'View posts by %s' ), $user_object->display_name ) ),
__( 'View' )
);
}
// Add a link to send the user a reset password link by email.
if ( get_current_user_id() !== $user_object->ID
&& current_user_can( 'edit_user', $user_object->ID )
&& true === wp_is_password_reset_allowed_for_user( $user_object )
) {
$actions['resetpassword'] = "<a class='resetpassword' href='" . wp_nonce_url( "users.php?action=resetpassword&amp;users=$user_object->ID", 'bulk-users' ) . "'>" . __( 'Send password reset' ) . '</a>';
}
/**
* Filters the action links displayed under each user in the Users list table.
*
* @since 2.8.0
*
* @param string[] $actions An array of action links to be displayed.
* Default 'Edit', 'Delete' for single site, and
* 'Edit', 'Remove' for Multisite.
* @param WP_User $user_object WP_User object for the currently listed user.
*/
$actions = apply_filters( 'user_row_actions', $actions, $user_object );
// Role classes.
$role_classes = esc_attr( implode( ' ', array_keys( $user_roles ) ) );
// Set up the checkbox (because the user is editable, otherwise it's empty).
$checkbox = sprintf(
'<input type="checkbox" name="users[]" id="user_%1$s" class="%2$s" value="%1$s" />' .
'<label for="user_%1$s"><span class="screen-reader-text">%3$s</span></label>',
$user_object->ID,
$role_classes,
/* translators: Hidden accessibility text. %s: User login. */
sprintf( __( 'Select %s' ), $user_object->user_login )
);
} else {
$edit = "<strong>{$user_object->user_login}{$super_admin}</strong>";
}
$avatar = get_avatar( $user_object->ID, 32 );
// Comma-separated list of user roles.
$roles_list = implode( ', ', $user_roles );
$row = "<tr id='user-$user_object->ID'>";
list( $columns, $hidden, $sortable, $primary ) = $this->get_column_info();
foreach ( $columns as $column_name => $column_display_name ) {
$classes = "$column_name column-$column_name";
if ( $primary === $column_name ) {
$classes .= ' has-row-actions column-primary';
}
if ( 'posts' === $column_name ) {
$classes .= ' num'; // Special case for that column.
}
if ( in_array( $column_name, $hidden, true ) ) {
$classes .= ' hidden';
}
$data = 'data-colname="' . esc_attr( wp_strip_all_tags( $column_display_name ) ) . '"';
$attributes = "class='$classes' $data";
if ( 'cb' === $column_name ) {
$row .= "<th scope='row' class='check-column'>$checkbox</th>";
} else {
$row .= "<td $attributes>";
switch ( $column_name ) {
case 'username':
$row .= "$avatar $edit";
break;
case 'name':
if ( $user_object->first_name && $user_object->last_name ) {
$row .= sprintf(
/* translators: 1: User's first name, 2: Last name. */
_x( '%1$s %2$s', 'Display name based on first name and last name' ),
$user_object->first_name,
$user_object->last_name
);
} elseif ( $user_object->first_name ) {
$row .= $user_object->first_name;
} elseif ( $user_object->last_name ) {
$row .= $user_object->last_name;
} else {
$row .= sprintf(
'<span aria-hidden="true">&#8212;</span><span class="screen-reader-text">%s</span>',
/* translators: Hidden accessibility text. */
_x( 'Unknown', 'name' )
);
}
break;
case 'email':
$row .= "<a href='" . esc_url( "mailto:$email" ) . "'>$email</a>";
break;
case 'role':
$row .= esc_html( $roles_list );
break;
case 'posts':
if ( $numposts > 0 ) {
$row .= sprintf(
'<a href="%s" class="edit"><span aria-hidden="true">%s</span><span class="screen-reader-text">%s</span></a>',
"edit.php?author={$user_object->ID}",
$numposts,
sprintf(
/* translators: Hidden accessibility text. %s: Number of posts. */
_n( '%s post by this author', '%s posts by this author', $numposts ),
number_format_i18n( $numposts )
)
);
} else {
$row .= 0;
}
break;
default:
/**
* Filters the display output of custom columns in the Users list table.
*
* @since 2.8.0
*
* @param string $output Custom column output. Default empty.
* @param string $column_name Column name.
* @param int $user_id ID of the currently-listed user.
*/
$row .= apply_filters( 'manage_users_custom_column', '', $column_name, $user_object->ID );
}
if ( $primary === $column_name ) {
$row .= $this->row_actions( $actions );
}
$row .= '</td>';
}
}
$row .= '</tr>';
return $row;
}
/**
* Gets the name of the default primary column.
*
* @since 4.3.0
*
* @return string Name of the default primary column, in this case, 'username'.
*/
protected function get_default_primary_column_name() {
return 'username';
}
/**
* Returns an array of translated user role names for a given user object.
*
* @since 4.4.0
*
* @param WP_User $user_object The WP_User object.
* @return string[] An array of user role names keyed by role.
*/
protected function get_role_list( $user_object ) {
$wp_roles = wp_roles();
$role_list = array();
foreach ( $user_object->roles as $role ) {
if ( isset( $wp_roles->role_names[ $role ] ) ) {
$role_list[ $role ] = translate_user_role( $wp_roles->role_names[ $role ] );
}
}
if ( empty( $role_list ) ) {
$role_list['none'] = _x( 'None', 'no user roles' );
}
/**
* Filters the returned array of translated role names for a user.
*
* @since 4.4.0
*
* @param string[] $role_list An array of translated user role names keyed by role.
* @param WP_User $user_object A WP_User object.
*/
return apply_filters( 'get_role_list', $role_list, $user_object );
}
}

View File

@ -0,0 +1,219 @@
<?php
/**
* WordPress Comment Administration API.
*
* @package WordPress
* @subpackage Administration
* @since 2.3.0
*/
/**
* Determines if a comment exists based on author and date.
*
* For best performance, use `$timezone = 'gmt'`, which queries a field that is properly indexed. The default value
* for `$timezone` is 'blog' for legacy reasons.
*
* @since 2.0.0
* @since 4.4.0 Added the `$timezone` parameter.
*
* @global wpdb $wpdb WordPress database abstraction object.
*
* @param string $comment_author Author of the comment.
* @param string $comment_date Date of the comment.
* @param string $timezone Timezone. Accepts 'blog' or 'gmt'. Default 'blog'.
* @return string|null Comment post ID on success.
*/
function comment_exists( $comment_author, $comment_date, $timezone = 'blog' ) {
global $wpdb;
$date_field = 'comment_date';
if ( 'gmt' === $timezone ) {
$date_field = 'comment_date_gmt';
}
return $wpdb->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 "<div class='wrap'><p>$msg</p></div>";
require_once ABSPATH . 'wp-admin/admin-footer.php';
die;
}

View File

@ -0,0 +1,549 @@
<?php
/**
* Translation API: Continent and city translations for timezone selection
*
* This file is not included anywhere. It exists solely for use by xgettext.
*
* @package WordPress
* @subpackage i18n
* @since 2.8.0
*/
__( 'Africa', 'continents-cities' );
__( 'Abidjan', 'continents-cities' );
__( 'Accra', 'continents-cities' );
__( 'Addis Ababa', 'continents-cities' );
__( 'Algiers', 'continents-cities' );
__( 'Asmara', 'continents-cities' );
__( 'Asmera', 'continents-cities' );
__( 'Bamako', 'continents-cities' );
__( 'Bangui', 'continents-cities' );
__( 'Banjul', 'continents-cities' );
__( 'Bissau', 'continents-cities' );
__( 'Blantyre', 'continents-cities' );
__( 'Brazzaville', 'continents-cities' );
__( 'Bujumbura', 'continents-cities' );
__( 'Cairo', 'continents-cities' );
__( 'Casablanca', 'continents-cities' );
__( 'Ceuta', 'continents-cities' );
__( 'Conakry', 'continents-cities' );
__( 'Dakar', 'continents-cities' );
__( 'Dar es Salaam', 'continents-cities' );
__( 'Djibouti', 'continents-cities' );
__( 'Douala', 'continents-cities' );
__( 'El Aaiun', 'continents-cities' );
__( 'Freetown', 'continents-cities' );
__( 'Gaborone', 'continents-cities' );
__( 'Harare', 'continents-cities' );
__( 'Johannesburg', 'continents-cities' );
__( 'Juba', 'continents-cities' );
__( 'Kampala', 'continents-cities' );
__( 'Khartoum', 'continents-cities' );
__( 'Kigali', 'continents-cities' );
__( 'Kinshasa', 'continents-cities' );
__( 'Lagos', 'continents-cities' );
__( 'Libreville', 'continents-cities' );
__( 'Lome', 'continents-cities' );
__( 'Luanda', 'continents-cities' );
__( 'Lubumbashi', 'continents-cities' );
__( 'Lusaka', 'continents-cities' );
__( 'Malabo', 'continents-cities' );
__( 'Maputo', 'continents-cities' );
__( 'Maseru', 'continents-cities' );
__( 'Mbabane', 'continents-cities' );
__( 'Mogadishu', 'continents-cities' );
__( 'Monrovia', 'continents-cities' );
__( 'Nairobi', 'continents-cities' );
__( 'Ndjamena', 'continents-cities' );
__( 'Niamey', 'continents-cities' );
__( 'Nouakchott', 'continents-cities' );
__( 'Ouagadougou', 'continents-cities' );
__( 'Porto-Novo', 'continents-cities' );
__( 'Sao Tome', 'continents-cities' );
__( 'Timbuktu', 'continents-cities' );
__( 'Tripoli', 'continents-cities' );
__( 'Tunis', 'continents-cities' );
__( 'Windhoek', 'continents-cities' );
__( 'America', 'continents-cities' );
__( 'Adak', 'continents-cities' );
__( 'Anchorage', 'continents-cities' );
__( 'Anguilla', 'continents-cities' );
__( 'Antigua', 'continents-cities' );
__( 'Araguaina', 'continents-cities' );
__( 'Argentina', 'continents-cities' );
__( 'Buenos Aires', 'continents-cities' );
__( 'Catamarca', 'continents-cities' );
__( 'ComodRivadavia', 'continents-cities' );
__( 'Cordoba', 'continents-cities' );
__( 'Jujuy', 'continents-cities' );
__( 'La Rioja', 'continents-cities' );
__( 'Mendoza', 'continents-cities' );
__( 'Rio Gallegos', 'continents-cities' );
__( 'Salta', 'continents-cities' );
__( 'San Juan', 'continents-cities' );
__( 'San Luis', 'continents-cities' );
__( 'Tucuman', 'continents-cities' );
__( 'Ushuaia', 'continents-cities' );
__( 'Aruba', 'continents-cities' );
__( 'Asuncion', 'continents-cities' );
__( 'Atikokan', 'continents-cities' );
__( 'Atka', 'continents-cities' );
__( 'Bahia', 'continents-cities' );
__( 'Bahia Banderas', 'continents-cities' );
__( 'Barbados', 'continents-cities' );
__( 'Belem', 'continents-cities' );
__( 'Belize', 'continents-cities' );
__( 'Blanc-Sablon', 'continents-cities' );
__( 'Boa Vista', 'continents-cities' );
__( 'Bogota', 'continents-cities' );
__( 'Boise', 'continents-cities' );
__( 'Cambridge Bay', 'continents-cities' );
__( 'Campo Grande', 'continents-cities' );
__( 'Cancun', 'continents-cities' );
__( 'Caracas', 'continents-cities' );
__( 'Cayenne', 'continents-cities' );
__( 'Cayman', 'continents-cities' );
__( 'Chicago', 'continents-cities' );
__( 'Chihuahua', 'continents-cities' );
__( 'Coral Harbour', 'continents-cities' );
__( 'Costa Rica', 'continents-cities' );
__( 'Creston', 'continents-cities' );
__( 'Cuiaba', 'continents-cities' );
__( 'Curacao', 'continents-cities' );
__( 'Danmarkshavn', 'continents-cities' );
__( 'Dawson', 'continents-cities' );
__( 'Dawson Creek', 'continents-cities' );
__( 'Denver', 'continents-cities' );
__( 'Detroit', 'continents-cities' );
__( 'Dominica', 'continents-cities' );
__( 'Edmonton', 'continents-cities' );
__( 'Eirunepe', 'continents-cities' );
__( 'El Salvador', 'continents-cities' );
__( 'Ensenada', 'continents-cities' );
__( 'Fort Nelson', 'continents-cities' );
__( 'Fort Wayne', 'continents-cities' );
__( 'Fortaleza', 'continents-cities' );
__( 'Glace Bay', 'continents-cities' );
__( 'Godthab', 'continents-cities' );
__( 'Goose Bay', 'continents-cities' );
__( 'Grand Turk', 'continents-cities' );
__( 'Grenada', 'continents-cities' );
__( 'Guadeloupe', 'continents-cities' );
__( 'Guatemala', 'continents-cities' );
__( 'Guayaquil', 'continents-cities' );
__( 'Guyana', 'continents-cities' );
__( 'Halifax', 'continents-cities' );
__( 'Havana', 'continents-cities' );
__( 'Hermosillo', 'continents-cities' );
__( 'Indiana', 'continents-cities' );
__( 'Indianapolis', 'continents-cities' );
__( 'Knox', 'continents-cities' );
__( 'Marengo', 'continents-cities' );
__( 'Petersburg', 'continents-cities' );
__( 'Tell City', 'continents-cities' );
__( 'Vevay', 'continents-cities' );
__( 'Vincennes', 'continents-cities' );
__( 'Winamac', 'continents-cities' );
__( 'Inuvik', 'continents-cities' );
__( 'Iqaluit', 'continents-cities' );
__( 'Jamaica', 'continents-cities' );
__( 'Juneau', 'continents-cities' );
__( 'Kentucky', 'continents-cities' );
__( 'Louisville', 'continents-cities' );
__( 'Monticello', 'continents-cities' );
__( 'Knox IN', 'continents-cities' );
__( 'Kralendijk', 'continents-cities' );
__( 'La Paz', 'continents-cities' );
__( 'Lima', 'continents-cities' );
__( 'Los Angeles', 'continents-cities' );
__( 'Lower Princes', 'continents-cities' );
__( 'Maceio', 'continents-cities' );
__( 'Managua', 'continents-cities' );
__( 'Manaus', 'continents-cities' );
__( 'Marigot', 'continents-cities' );
__( 'Martinique', 'continents-cities' );
__( 'Matamoros', 'continents-cities' );
__( 'Mazatlan', 'continents-cities' );
__( 'Menominee', 'continents-cities' );
__( 'Merida', 'continents-cities' );
__( 'Metlakatla', 'continents-cities' );
__( 'Mexico City', 'continents-cities' );
__( 'Miquelon', 'continents-cities' );
__( 'Moncton', 'continents-cities' );
__( 'Monterrey', 'continents-cities' );
__( 'Montevideo', 'continents-cities' );
__( 'Montreal', 'continents-cities' );
__( 'Montserrat', 'continents-cities' );
__( 'Nassau', 'continents-cities' );
__( 'New York', 'continents-cities' );
__( 'Nipigon', 'continents-cities' );
__( 'Nome', 'continents-cities' );
__( 'Noronha', 'continents-cities' );
__( 'North Dakota', 'continents-cities' );
__( 'Beulah', 'continents-cities' );
__( 'Center', 'continents-cities' );
__( 'New Salem', 'continents-cities' );
__( 'Nuuk', 'continents-cities' );
__( 'Ojinaga', 'continents-cities' );
__( 'Panama', 'continents-cities' );
__( 'Pangnirtung', 'continents-cities' );
__( 'Paramaribo', 'continents-cities' );
__( 'Phoenix', 'continents-cities' );
__( 'Port-au-Prince', 'continents-cities' );
__( 'Port of Spain', 'continents-cities' );
__( 'Porto Acre', 'continents-cities' );
__( 'Porto Velho', 'continents-cities' );
__( 'Puerto Rico', 'continents-cities' );
__( 'Punta Arenas', 'continents-cities' );
__( 'Rainy River', 'continents-cities' );
__( 'Rankin Inlet', 'continents-cities' );
__( 'Recife', 'continents-cities' );
__( 'Regina', 'continents-cities' );
__( 'Resolute', 'continents-cities' );
__( 'Rio Branco', 'continents-cities' );
__( 'Rosario', 'continents-cities' );
__( 'Santa Isabel', 'continents-cities' );
__( 'Santarem', 'continents-cities' );
__( 'Santiago', 'continents-cities' );
__( 'Santo Domingo', 'continents-cities' );
__( 'Sao Paulo', 'continents-cities' );
__( 'Scoresbysund', 'continents-cities' );
__( 'Shiprock', 'continents-cities' );
__( 'Sitka', 'continents-cities' );
__( 'St Barthelemy', 'continents-cities' );
__( 'St Johns', 'continents-cities' );
__( 'St Kitts', 'continents-cities' );
__( 'St Lucia', 'continents-cities' );
__( 'St Thomas', 'continents-cities' );
__( 'St Vincent', 'continents-cities' );
__( 'Swift Current', 'continents-cities' );
__( 'Tegucigalpa', 'continents-cities' );
__( 'Thule', 'continents-cities' );
__( 'Thunder Bay', 'continents-cities' );
__( 'Tijuana', 'continents-cities' );
__( 'Toronto', 'continents-cities' );
__( 'Tortola', 'continents-cities' );
__( 'Vancouver', 'continents-cities' );
__( 'Virgin', 'continents-cities' );
__( 'Whitehorse', 'continents-cities' );
__( 'Winnipeg', 'continents-cities' );
__( 'Yakutat', 'continents-cities' );
__( 'Yellowknife', 'continents-cities' );
__( 'Antarctica', 'continents-cities' );
__( 'Casey', 'continents-cities' );
__( 'Davis', 'continents-cities' );
__( 'DumontDUrville', 'continents-cities' );
__( 'Macquarie', 'continents-cities' );
__( 'Mawson', 'continents-cities' );
__( 'McMurdo', 'continents-cities' );
__( 'Palmer', 'continents-cities' );
__( 'Rothera', 'continents-cities' );
__( 'South Pole', 'continents-cities' );
__( 'Syowa', 'continents-cities' );
__( 'Troll', 'continents-cities' );
__( 'Vostok', 'continents-cities' );
__( 'Arctic', 'continents-cities' );
__( 'Longyearbyen', 'continents-cities' );
__( 'Asia', 'continents-cities' );
__( 'Aden', 'continents-cities' );
__( 'Almaty', 'continents-cities' );
__( 'Amman', 'continents-cities' );
__( 'Anadyr', 'continents-cities' );
__( 'Aqtau', 'continents-cities' );
__( 'Aqtobe', 'continents-cities' );
__( 'Ashgabat', 'continents-cities' );
__( 'Ashkhabad', 'continents-cities' );
__( 'Atyrau', 'continents-cities' );
__( 'Baghdad', 'continents-cities' );
__( 'Bahrain', 'continents-cities' );
__( 'Baku', 'continents-cities' );
__( 'Bangkok', 'continents-cities' );
__( 'Barnaul', 'continents-cities' );
__( 'Beirut', 'continents-cities' );
__( 'Bishkek', 'continents-cities' );
__( 'Brunei', 'continents-cities' );
__( 'Calcutta', 'continents-cities' );
__( 'Chita', 'continents-cities' );
__( 'Choibalsan', 'continents-cities' );
__( 'Chongqing', 'continents-cities' );
__( 'Chungking', 'continents-cities' );
__( 'Colombo', 'continents-cities' );
__( 'Dacca', 'continents-cities' );
__( 'Damascus', 'continents-cities' );
__( 'Dhaka', 'continents-cities' );
__( 'Dili', 'continents-cities' );
__( 'Dubai', 'continents-cities' );
__( 'Dushanbe', 'continents-cities' );
__( 'Famagusta', 'continents-cities' );
__( 'Gaza', 'continents-cities' );
__( 'Harbin', 'continents-cities' );
__( 'Hebron', 'continents-cities' );
__( 'Ho Chi Minh', 'continents-cities' );
__( 'Hong Kong', 'continents-cities' );
__( 'Hovd', 'continents-cities' );
__( 'Irkutsk', 'continents-cities' );
__( 'Jakarta', 'continents-cities' );
__( 'Jayapura', 'continents-cities' );
__( 'Jerusalem', 'continents-cities' );
__( 'Kabul', 'continents-cities' );
__( 'Kamchatka', 'continents-cities' );
__( 'Karachi', 'continents-cities' );
__( 'Kashgar', 'continents-cities' );
__( 'Kathmandu', 'continents-cities' );
__( 'Katmandu', 'continents-cities' );
__( 'Khandyga', 'continents-cities' );
__( 'Kolkata', 'continents-cities' );
__( 'Krasnoyarsk', 'continents-cities' );
__( 'Kuala Lumpur', 'continents-cities' );
__( 'Kuching', 'continents-cities' );
__( 'Kuwait', 'continents-cities' );
__( 'Macao', 'continents-cities' );
__( 'Macau', 'continents-cities' );
__( 'Magadan', 'continents-cities' );
__( 'Makassar', 'continents-cities' );
__( 'Manila', 'continents-cities' );
__( 'Muscat', 'continents-cities' );
__( 'Nicosia', 'continents-cities' );
__( 'Novokuznetsk', 'continents-cities' );
__( 'Novosibirsk', 'continents-cities' );
__( 'Omsk', 'continents-cities' );
__( 'Oral', 'continents-cities' );
__( 'Phnom Penh', 'continents-cities' );
__( 'Pontianak', 'continents-cities' );
__( 'Pyongyang', 'continents-cities' );
__( 'Qatar', 'continents-cities' );
__( 'Qostanay', 'continents-cities' );
__( 'Qyzylorda', 'continents-cities' );
__( 'Rangoon', 'continents-cities' );
__( 'Riyadh', 'continents-cities' );
__( 'Saigon', 'continents-cities' );
__( 'Sakhalin', 'continents-cities' );
__( 'Samarkand', 'continents-cities' );
__( 'Seoul', 'continents-cities' );
__( 'Shanghai', 'continents-cities' );
__( 'Singapore', 'continents-cities' );
__( 'Srednekolymsk', 'continents-cities' );
__( 'Taipei', 'continents-cities' );
__( 'Tashkent', 'continents-cities' );
__( 'Tbilisi', 'continents-cities' );
__( 'Tehran', 'continents-cities' );
__( 'Tel Aviv', 'continents-cities' );
__( 'Thimbu', 'continents-cities' );
__( 'Thimphu', 'continents-cities' );
__( 'Tokyo', 'continents-cities' );
__( 'Tomsk', 'continents-cities' );
__( 'Ujung Pandang', 'continents-cities' );
__( 'Ulaanbaatar', 'continents-cities' );
__( 'Ulan Bator', 'continents-cities' );
__( 'Urumqi', 'continents-cities' );
__( 'Ust-Nera', 'continents-cities' );
__( 'Vientiane', 'continents-cities' );
__( 'Vladivostok', 'continents-cities' );
__( 'Yakutsk', 'continents-cities' );
__( 'Yangon', 'continents-cities' );
__( 'Yekaterinburg', 'continents-cities' );
__( 'Yerevan', 'continents-cities' );
__( 'Atlantic', 'continents-cities' );
__( 'Azores', 'continents-cities' );
__( 'Bermuda', 'continents-cities' );
__( 'Canary', 'continents-cities' );
__( 'Cape Verde', 'continents-cities' );
__( 'Faeroe', 'continents-cities' );
__( 'Faroe', 'continents-cities' );
__( 'Jan Mayen', 'continents-cities' );
__( 'Madeira', 'continents-cities' );
__( 'Reykjavik', 'continents-cities' );
__( 'South Georgia', 'continents-cities' );
__( 'St Helena', 'continents-cities' );
__( 'Stanley', 'continents-cities' );
__( 'Australia', 'continents-cities' );
__( 'ACT', 'continents-cities' );
__( 'Adelaide', 'continents-cities' );
__( 'Brisbane', 'continents-cities' );
__( 'Broken Hill', 'continents-cities' );
__( 'Canberra', 'continents-cities' );
__( 'Currie', 'continents-cities' );
__( 'Darwin', 'continents-cities' );
__( 'Eucla', 'continents-cities' );
__( 'Hobart', 'continents-cities' );
__( 'LHI', 'continents-cities' );
__( 'Lindeman', 'continents-cities' );
__( 'Lord Howe', 'continents-cities' );
__( 'Melbourne', 'continents-cities' );
__( 'NSW', 'continents-cities' );
__( 'North', 'continents-cities' );
__( 'Perth', 'continents-cities' );
__( 'Queensland', 'continents-cities' );
__( 'South', 'continents-cities' );
__( 'Sydney', 'continents-cities' );
__( 'Tasmania', 'continents-cities' );
__( 'Victoria', 'continents-cities' );
__( 'West', 'continents-cities' );
__( 'Yancowinna', 'continents-cities' );
__( 'Etc', 'continents-cities' );
__( 'GMT', 'continents-cities' );
__( 'GMT+0', 'continents-cities' );
__( 'GMT+1', 'continents-cities' );
__( 'GMT+10', 'continents-cities' );
__( 'GMT+11', 'continents-cities' );
__( 'GMT+12', 'continents-cities' );
__( 'GMT+2', 'continents-cities' );
__( 'GMT+3', 'continents-cities' );
__( 'GMT+4', 'continents-cities' );
__( 'GMT+5', 'continents-cities' );
__( 'GMT+6', 'continents-cities' );
__( 'GMT+7', 'continents-cities' );
__( 'GMT+8', 'continents-cities' );
__( 'GMT+9', 'continents-cities' );
__( 'GMT-0', 'continents-cities' );
__( 'GMT-1', 'continents-cities' );
__( 'GMT-10', 'continents-cities' );
__( 'GMT-11', 'continents-cities' );
__( 'GMT-12', 'continents-cities' );
__( 'GMT-13', 'continents-cities' );
__( 'GMT-14', 'continents-cities' );
__( 'GMT-2', 'continents-cities' );
__( 'GMT-3', 'continents-cities' );
__( 'GMT-4', 'continents-cities' );
__( 'GMT-5', 'continents-cities' );
__( 'GMT-6', 'continents-cities' );
__( 'GMT-7', 'continents-cities' );
__( 'GMT-8', 'continents-cities' );
__( 'GMT-9', 'continents-cities' );
__( 'GMT0', 'continents-cities' );
__( 'Greenwich', 'continents-cities' );
__( 'UCT', 'continents-cities' );
__( 'UTC', 'continents-cities' );
__( 'Universal', 'continents-cities' );
__( 'Zulu', 'continents-cities' );
__( 'Europe', 'continents-cities' );
__( 'Amsterdam', 'continents-cities' );
__( 'Andorra', 'continents-cities' );
__( 'Astrakhan', 'continents-cities' );
__( 'Athens', 'continents-cities' );
__( 'Belfast', 'continents-cities' );
__( 'Belgrade', 'continents-cities' );
__( 'Berlin', 'continents-cities' );
__( 'Bratislava', 'continents-cities' );
__( 'Brussels', 'continents-cities' );
__( 'Bucharest', 'continents-cities' );
__( 'Budapest', 'continents-cities' );
__( 'Busingen', 'continents-cities' );
__( 'Chisinau', 'continents-cities' );
__( 'Copenhagen', 'continents-cities' );
__( 'Dublin', 'continents-cities' );
__( 'Gibraltar', 'continents-cities' );
__( 'Guernsey', 'continents-cities' );
__( 'Helsinki', 'continents-cities' );
__( 'Isle of Man', 'continents-cities' );
__( 'Istanbul', 'continents-cities' );
__( 'Jersey', 'continents-cities' );
__( 'Kaliningrad', 'continents-cities' );
__( 'Kiev', 'continents-cities' );
__( 'Kyiv', 'continents-cities' );
__( 'Kirov', 'continents-cities' );
__( 'Lisbon', 'continents-cities' );
__( 'Ljubljana', 'continents-cities' );
__( 'London', 'continents-cities' );
__( 'Luxembourg', 'continents-cities' );
__( 'Madrid', 'continents-cities' );
__( 'Malta', 'continents-cities' );
__( 'Mariehamn', 'continents-cities' );
__( 'Minsk', 'continents-cities' );
__( 'Monaco', 'continents-cities' );
__( 'Moscow', 'continents-cities' );
__( 'Oslo', 'continents-cities' );
__( 'Paris', 'continents-cities' );
__( 'Podgorica', 'continents-cities' );
__( 'Prague', 'continents-cities' );
__( 'Riga', 'continents-cities' );
__( 'Rome', 'continents-cities' );
__( 'Samara', 'continents-cities' );
__( 'San Marino', 'continents-cities' );
__( 'Sarajevo', 'continents-cities' );
__( 'Saratov', 'continents-cities' );
__( 'Simferopol', 'continents-cities' );
__( 'Skopje', 'continents-cities' );
__( 'Sofia', 'continents-cities' );
__( 'Stockholm', 'continents-cities' );
__( 'Tallinn', 'continents-cities' );
__( 'Tirane', 'continents-cities' );
__( 'Tiraspol', 'continents-cities' );
__( 'Ulyanovsk', 'continents-cities' );
__( 'Uzhgorod', 'continents-cities' );
__( 'Vaduz', 'continents-cities' );
__( 'Vatican', 'continents-cities' );
__( 'Vienna', 'continents-cities' );
__( 'Vilnius', 'continents-cities' );
__( 'Volgograd', 'continents-cities' );
__( 'Warsaw', 'continents-cities' );
__( 'Zagreb', 'continents-cities' );
__( 'Zaporozhye', 'continents-cities' );
__( 'Zurich', 'continents-cities' );
__( 'Indian', 'continents-cities' );
__( 'Antananarivo', 'continents-cities' );
__( 'Chagos', 'continents-cities' );
__( 'Christmas', 'continents-cities' );
__( 'Cocos', 'continents-cities' );
__( 'Comoro', 'continents-cities' );
__( 'Kerguelen', 'continents-cities' );
__( 'Mahe', 'continents-cities' );
__( 'Maldives', 'continents-cities' );
__( 'Mauritius', 'continents-cities' );
__( 'Mayotte', 'continents-cities' );
__( 'Reunion', 'continents-cities' );
__( 'Pacific', 'continents-cities' );
__( 'Apia', 'continents-cities' );
__( 'Auckland', 'continents-cities' );
__( 'Bougainville', 'continents-cities' );
__( 'Chatham', 'continents-cities' );
__( 'Chuuk', 'continents-cities' );
__( 'Easter', 'continents-cities' );
__( 'Efate', 'continents-cities' );
__( 'Enderbury', 'continents-cities' );
__( 'Fakaofo', 'continents-cities' );
__( 'Fiji', 'continents-cities' );
__( 'Funafuti', 'continents-cities' );
__( 'Galapagos', 'continents-cities' );
__( 'Gambier', 'continents-cities' );
__( 'Guadalcanal', 'continents-cities' );
__( 'Guam', 'continents-cities' );
__( 'Honolulu', 'continents-cities' );
__( 'Johnston', 'continents-cities' );
__( 'Kanton', 'continents-cities' );
__( 'Kiritimati', 'continents-cities' );
__( 'Kosrae', 'continents-cities' );
__( 'Kwajalein', 'continents-cities' );
__( 'Majuro', 'continents-cities' );
__( 'Marquesas', 'continents-cities' );
__( 'Midway', 'continents-cities' );
__( 'Nauru', 'continents-cities' );
__( 'Niue', 'continents-cities' );
__( 'Norfolk', 'continents-cities' );
__( 'Noumea', 'continents-cities' );
__( 'Pago Pago', 'continents-cities' );
__( 'Palau', 'continents-cities' );
__( 'Pitcairn', 'continents-cities' );
__( 'Pohnpei', 'continents-cities' );
__( 'Ponape', 'continents-cities' );
__( 'Port Moresby', 'continents-cities' );
__( 'Rarotonga', 'continents-cities' );
__( 'Saipan', 'continents-cities' );
__( 'Samoa', 'continents-cities' );
__( 'Tahiti', 'continents-cities' );
__( 'Tarawa', 'continents-cities' );
__( 'Tongatapu', 'continents-cities' );
__( 'Truk', 'continents-cities' );
__( 'Wake', 'continents-cities' );
__( 'Wallis', 'continents-cities' );
__( 'Yap', 'continents-cities' );

View File

@ -0,0 +1,166 @@
<?php
/**
* WordPress Credits Administration API.
*
* @package WordPress
* @subpackage Administration
* @since 4.4.0
*/
/**
* Retrieves the contributor credits.
*
* @since 3.2.0
* @since 5.6.0 Added the `$version` and `$locale` parameters.
*
* @param string $version WordPress version. Defaults to the current version.
* @param string $locale WordPress locale. Defaults to the current user's locale.
* @return array|false A list of all of the contributors, or false on error.
*/
function wp_credits( $version = '', $locale = '' ) {
if ( ! $version ) {
// Include an unmodified $wp_version.
require ABSPATH . WPINC . '/version.php';
$version = $wp_version;
}
if ( ! $locale ) {
$locale = get_user_locale();
}
$results = get_site_transient( 'wordpress_credits_' . $locale );
if ( ! is_array( $results )
|| str_contains( $version, '-' )
|| ( isset( $results['data']['version'] ) && ! str_starts_with( $version, $results['data']['version'] ) )
) {
$url = "http://api.wordpress.org/core/credits/1.1/?version={$version}&locale={$locale}";
$options = array( 'user-agent' => 'WordPress/' . $version . '; ' . home_url( '/' ) );
if ( wp_http_supports( array( 'ssl' ) ) ) {
$url = set_url_scheme( $url, 'https' );
}
$response = wp_remote_get( $url, $options );
if ( is_wp_error( $response ) || 200 !== wp_remote_retrieve_response_code( $response ) ) {
return false;
}
$results = json_decode( wp_remote_retrieve_body( $response ), true );
if ( ! is_array( $results ) ) {
return false;
}
set_site_transient( 'wordpress_credits_' . $locale, $results, DAY_IN_SECONDS );
}
return $results;
}
/**
* Retrieves the link to a contributor's WordPress.org profile page.
*
* @access private
* @since 3.2.0
*
* @param string $display_name The contributor's display name (passed by reference).
* @param string $username The contributor's username.
* @param string $profiles URL to the contributor's WordPress.org profile page.
*/
function _wp_credits_add_profile_link( &$display_name, $username, $profiles ) {
$display_name = '<a href="' . esc_url( sprintf( $profiles, $username ) ) . '">' . esc_html( $display_name ) . '</a>';
}
/**
* Retrieves the link to an external library used in WordPress.
*
* @access private
* @since 3.2.0
*
* @param string $data External library data (passed by reference).
*/
function _wp_credits_build_object_link( &$data ) {
$data = '<a href="' . esc_url( $data[1] ) . '">' . esc_html( $data[0] ) . '</a>';
}
/**
* Displays the title for a given group of contributors.
*
* @since 5.3.0
*
* @param array $group_data The current contributor group.
*/
function wp_credits_section_title( $group_data = array() ) {
if ( ! count( $group_data ) ) {
return;
}
if ( $group_data['name'] ) {
if ( 'Translators' === $group_data['name'] ) {
// Considered a special slug in the API response. (Also, will never be returned for en_US.)
$title = _x( 'Translators', 'Translate this to be the equivalent of English Translators in your language for the credits page Translators section' );
} elseif ( isset( $group_data['placeholders'] ) ) {
// phpcs:ignore WordPress.WP.I18n.LowLevelTranslationFunction,WordPress.WP.I18n.NonSingularStringLiteralText
$title = vsprintf( translate( $group_data['name'] ), $group_data['placeholders'] );
} else {
// phpcs:ignore WordPress.WP.I18n.LowLevelTranslationFunction,WordPress.WP.I18n.NonSingularStringLiteralText
$title = translate( $group_data['name'] );
}
echo '<h2 class="wp-people-group-title">' . esc_html( $title ) . "</h2>\n";
}
}
/**
* Displays a list of contributors for a given group.
*
* @since 5.3.0
*
* @param array $credits The credits groups returned from the API.
* @param string $slug The current group to display.
*/
function wp_credits_section_list( $credits = array(), $slug = '' ) {
$group_data = isset( $credits['groups'][ $slug ] ) ? $credits['groups'][ $slug ] : array();
$credits_data = $credits['data'];
if ( ! count( $group_data ) ) {
return;
}
if ( ! empty( $group_data['shuffle'] ) ) {
shuffle( $group_data['data'] ); // We were going to sort by ability to pronounce "hierarchical," but that wouldn't be fair to Matt.
}
switch ( $group_data['type'] ) {
case 'list':
array_walk( $group_data['data'], '_wp_credits_add_profile_link', $credits_data['profiles'] );
echo '<p class="wp-credits-list">' . wp_sprintf( '%l.', $group_data['data'] ) . "</p>\n\n";
break;
case 'libraries':
array_walk( $group_data['data'], '_wp_credits_build_object_link' );
echo '<p class="wp-credits-list">' . wp_sprintf( '%l.', $group_data['data'] ) . "</p>\n\n";
break;
default:
$compact = 'compact' === $group_data['type'];
$classes = 'wp-people-group ' . ( $compact ? 'compact' : '' );
echo '<ul class="' . $classes . '" id="wp-people-group-' . $slug . '">' . "\n";
foreach ( $group_data['data'] as $person_data ) {
echo '<li class="wp-person" id="wp-person-' . esc_attr( $person_data[2] ) . '">' . "\n\t";
echo '<a href="' . esc_url( sprintf( $credits_data['profiles'], $person_data[2] ) ) . '" class="web">';
$size = $compact ? 80 : 160;
$data = get_avatar_data( $person_data[1] . '@md5.gravatar.com', array( 'size' => $size ) );
$data2x = get_avatar_data( $person_data[1] . '@md5.gravatar.com', array( 'size' => $size * 2 ) );
echo '<span class="wp-person-avatar"><img src="' . esc_url( $data['url'] ) . '" srcset="' . esc_url( $data2x['url'] ) . ' 2x" class="gravatar" alt="" /></span>' . "\n";
echo esc_html( $person_data[0] ) . "</a>\n\t";
if ( ! $compact && ! empty( $person_data[3] ) ) {
// phpcs:ignore WordPress.WP.I18n.LowLevelTranslationFunction,WordPress.WP.I18n.NonSingularStringLiteralText
echo '<span class="title">' . translate( $person_data[3] ) . "</span>\n";
}
echo "</li>\n";
}
echo "</ul>\n";
break;
}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,59 @@
<?php
/**
* Edit Tags Administration: Messages
*
* @package WordPress
* @subpackage Administration
* @since 4.4.0
*/
$messages = array();
// 0 = unused. Messages start at index 1.
$messages['_item'] = array(
0 => '',
1 => __( 'Item added.' ),
2 => __( 'Item deleted.' ),
3 => __( 'Item updated.' ),
4 => __( 'Item not added.' ),
5 => __( 'Item not updated.' ),
6 => __( 'Items deleted.' ),
);
$messages['category'] = array(
0 => '',
1 => __( 'Category added.' ),
2 => __( 'Category deleted.' ),
3 => __( 'Category updated.' ),
4 => __( 'Category not added.' ),
5 => __( 'Category not updated.' ),
6 => __( 'Categories deleted.' ),
);
$messages['post_tag'] = array(
0 => '',
1 => __( 'Tag added.' ),
2 => __( 'Tag deleted.' ),
3 => __( 'Tag updated.' ),
4 => __( 'Tag not added.' ),
5 => __( 'Tag not updated.' ),
6 => __( 'Tags deleted.' ),
);
/**
* Filters the messages displayed when a tag is updated.
*
* @since 3.7.0
*
* @param array[] $messages Array of arrays of messages to be displayed, keyed by taxonomy name.
*/
$messages = apply_filters( 'term_updated_messages', $messages );
$message = false;
if ( isset( $_REQUEST['message'] ) && (int) $_REQUEST['message'] ) {
$msg = (int) $_REQUEST['message'];
if ( isset( $messages[ $taxonomy ][ $msg ] ) ) {
$message = $messages[ $taxonomy ][ $msg ];
} elseif ( ! isset( $messages[ $taxonomy ] ) && isset( $messages['_item'][ $msg ] ) ) {
$message = $messages['_item'][ $msg ];
}
}

View File

@ -0,0 +1,732 @@
<?php
/**
* WordPress Export Administration API
*
* @package WordPress
* @subpackage Administration
*/
/**
* Version number for the export format.
*
* Bump this when something changes that might affect compatibility.
*
* @since 2.5.0
*/
define( 'WXR_VERSION', '1.2' );
/**
* Generates the WXR export file for download.
*
* Default behavior is to export all content, however, note that post content will only
* be exported for post types with the `can_export` argument enabled. Any posts with the
* 'auto-draft' status will be skipped.
*
* @since 2.1.0
* @since 5.7.0 Added the `post_modified` and `post_modified_gmt` fields to the export file.
*
* @global wpdb $wpdb WordPress database abstraction object.
* @global WP_Post $post Global post object.
*
* @param array $args {
* Optional. Arguments for generating the WXR export file for download. Default empty array.
*
* @type string $content Type of content to export. If set, only the post content of this post type
* will be exported. Accepts 'all', 'post', 'page', 'attachment', or a defined
* custom post. If an invalid custom post type is supplied, every post type for
* which `can_export` is enabled will be exported instead. If a valid custom post
* type is supplied but `can_export` is disabled, then 'posts' will be exported
* instead. When 'all' is supplied, only post types with `can_export` enabled will
* be exported. Default 'all'.
* @type string $author Author to export content for. Only used when `$content` is 'post', 'page', or
* 'attachment'. Accepts false (all) or a specific author ID. Default false (all).
* @type string $category Category (slug) to export content for. Used only when `$content` is 'post'. If
* set, only post content assigned to `$category` will be exported. Accepts false
* or a specific category slug. Default is false (all categories).
* @type string $start_date Start date to export content from. Expected date format is 'Y-m-d'. Used only
* when `$content` is 'post', 'page' or 'attachment'. Default false (since the
* beginning of time).
* @type string $end_date End date to export content to. Expected date format is 'Y-m-d'. Used only when
* `$content` is 'post', 'page' or 'attachment'. Default false (latest publish date).
* @type string $status Post status to export posts for. Used only when `$content` is 'post' or 'page'.
* Accepts false (all statuses except 'auto-draft'), or a specific status, i.e.
* 'publish', 'pending', 'draft', 'auto-draft', 'future', 'private', 'inherit', or
* 'trash'. Default false (all statuses except 'auto-draft').
* }
*/
function export_wp( $args = array() ) {
global $wpdb, $post;
$defaults = array(
'content' => 'all',
'author' => false,
'category' => false,
'start_date' => false,
'end_date' => false,
'status' => false,
);
$args = wp_parse_args( $args, $defaults );
/**
* Fires at the beginning of an export, before any headers are sent.
*
* @since 2.3.0
*
* @param array $args An array of export arguments.
*/
do_action( 'export_wp', $args );
$sitename = sanitize_key( get_bloginfo( 'name' ) );
if ( ! empty( $sitename ) ) {
$sitename .= '.';
}
$date = gmdate( 'Y-m-d' );
$wp_filename = $sitename . 'WordPress.' . $date . '.xml';
/**
* Filters the export filename.
*
* @since 4.4.0
*
* @param string $wp_filename The name of the file for download.
* @param string $sitename The site name.
* @param string $date Today's date, formatted.
*/
$filename = apply_filters( 'export_wp_filename', $wp_filename, $sitename, $date );
header( 'Content-Description: File Transfer' );
header( 'Content-Disposition: attachment; filename=' . $filename );
header( 'Content-Type: text/xml; charset=' . get_option( 'blog_charset' ), true );
if ( 'all' !== $args['content'] && post_type_exists( $args['content'] ) ) {
$ptype = get_post_type_object( $args['content'] );
if ( ! $ptype->can_export ) {
$args['content'] = 'post';
}
$where = $wpdb->prepare( "{$wpdb->posts}.post_type = %s", $args['content'] );
} else {
$post_types = get_post_types( array( 'can_export' => true ) );
$esses = array_fill( 0, count( $post_types ), '%s' );
// phpcs:ignore WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare
$where = $wpdb->prepare( "{$wpdb->posts}.post_type IN (" . implode( ',', $esses ) . ')', $post_types );
}
if ( $args['status'] && ( 'post' === $args['content'] || 'page' === $args['content'] ) ) {
$where .= $wpdb->prepare( " AND {$wpdb->posts}.post_status = %s", $args['status'] );
} else {
$where .= " AND {$wpdb->posts}.post_status != 'auto-draft'";
}
$join = '';
if ( $args['category'] && 'post' === $args['content'] ) {
$term = term_exists( $args['category'], 'category' );
if ( $term ) {
$join = "INNER JOIN {$wpdb->term_relationships} ON ({$wpdb->posts}.ID = {$wpdb->term_relationships}.object_id)";
$where .= $wpdb->prepare( " AND {$wpdb->term_relationships}.term_taxonomy_id = %d", $term['term_taxonomy_id'] );
}
}
if ( in_array( $args['content'], array( 'post', 'page', 'attachment' ), true ) ) {
if ( $args['author'] ) {
$where .= $wpdb->prepare( " AND {$wpdb->posts}.post_author = %d", $args['author'] );
}
if ( $args['start_date'] ) {
$where .= $wpdb->prepare( " AND {$wpdb->posts}.post_date >= %s", gmdate( 'Y-m-d', strtotime( $args['start_date'] ) ) );
}
if ( $args['end_date'] ) {
$where .= $wpdb->prepare( " AND {$wpdb->posts}.post_date < %s", gmdate( 'Y-m-d', strtotime( '+1 month', strtotime( $args['end_date'] ) ) ) );
}
}
// Grab a snapshot of post IDs, just in case it changes during the export.
$post_ids = $wpdb->get_col( "SELECT ID FROM {$wpdb->posts} $join WHERE $where" );
// Get IDs for the attachments of each post, unless all content is already being exported.
if ( ! in_array( $args['content'], array( 'all', 'attachment' ), true ) ) {
// Array to hold all additional IDs (attachments and thumbnails).
$additional_ids = array();
// Create a copy of the post IDs array to avoid modifying the original array.
$processing_ids = $post_ids;
while ( $next_posts = array_splice( $processing_ids, 0, 20 ) ) {
$posts_in = array_map( 'absint', $next_posts );
$placeholders = array_fill( 0, count( $posts_in ), '%d' );
// Create a string for the placeholders.
$in_placeholder = implode( ',', $placeholders );
// Prepare the SQL statement for attachment ids.
$attachment_ids = $wpdb->get_col(
$wpdb->prepare(
"
SELECT ID
FROM $wpdb->posts
WHERE post_parent IN ($in_placeholder) AND post_type = 'attachment'
",
$posts_in
)
);
$thumbnails_ids = $wpdb->get_col(
$wpdb->prepare(
"
SELECT meta_value
FROM $wpdb->postmeta
WHERE $wpdb->postmeta.post_id IN ($in_placeholder)
AND $wpdb->postmeta.meta_key = '_thumbnail_id'
",
$posts_in
)
);
$additional_ids = array_merge( $additional_ids, $attachment_ids, $thumbnails_ids );
}
// Merge the additional IDs back with the original post IDs after processing all posts
$post_ids = array_unique( array_merge( $post_ids, $additional_ids ) );
}
/*
* Get the requested terms ready, empty unless posts filtered by category
* or all content.
*/
$cats = array();
$tags = array();
$terms = array();
if ( isset( $term ) && $term ) {
$cat = get_term( $term['term_id'], 'category' );
$cats = array( $cat->term_id => $cat );
unset( $term, $cat );
} elseif ( 'all' === $args['content'] ) {
$categories = (array) get_categories( array( 'get' => 'all' ) );
$tags = (array) get_tags( array( 'get' => 'all' ) );
$custom_taxonomies = get_taxonomies( array( '_builtin' => false ) );
$custom_terms = (array) get_terms(
array(
'taxonomy' => $custom_taxonomies,
'get' => 'all',
)
);
// Put categories in order with no child going before its parent.
while ( $cat = array_shift( $categories ) ) {
if ( ! $cat->parent || isset( $cats[ $cat->parent ] ) ) {
$cats[ $cat->term_id ] = $cat;
} else {
$categories[] = $cat;
}
}
// Put terms in order with no child going before its parent.
while ( $t = array_shift( $custom_terms ) ) {
if ( ! $t->parent || isset( $terms[ $t->parent ] ) ) {
$terms[ $t->term_id ] = $t;
} else {
$custom_terms[] = $t;
}
}
unset( $categories, $custom_taxonomies, $custom_terms );
}
/**
* Wraps given string in XML CDATA tag.
*
* @since 2.1.0
*
* @param string $str String to wrap in XML CDATA tag.
* @return string
*/
function wxr_cdata( $str ) {
if ( ! seems_utf8( $str ) ) {
$str = utf8_encode( $str );
}
// $str = ent2ncr(esc_html($str));
$str = '<![CDATA[' . str_replace( ']]>', ']]]]><![CDATA[>', $str ) . ']]>';
return $str;
}
/**
* Returns the URL of the site.
*
* @since 2.5.0
*
* @return string Site URL.
*/
function wxr_site_url() {
if ( is_multisite() ) {
// Multisite: the base URL.
return network_home_url();
} else {
// WordPress (single site): the site URL.
return get_bloginfo_rss( 'url' );
}
}
/**
* Outputs a cat_name XML tag from a given category object.
*
* @since 2.1.0
*
* @param WP_Term $category Category Object.
*/
function wxr_cat_name( $category ) {
if ( empty( $category->name ) ) {
return;
}
echo '<wp:cat_name>' . wxr_cdata( $category->name ) . "</wp:cat_name>\n";
}
/**
* Outputs a category_description XML tag from a given category object.
*
* @since 2.1.0
*
* @param WP_Term $category Category Object.
*/
function wxr_category_description( $category ) {
if ( empty( $category->description ) ) {
return;
}
echo '<wp:category_description>' . wxr_cdata( $category->description ) . "</wp:category_description>\n";
}
/**
* Outputs a tag_name XML tag from a given tag object.
*
* @since 2.3.0
*
* @param WP_Term $tag Tag Object.
*/
function wxr_tag_name( $tag ) {
if ( empty( $tag->name ) ) {
return;
}
echo '<wp:tag_name>' . wxr_cdata( $tag->name ) . "</wp:tag_name>\n";
}
/**
* Outputs a tag_description XML tag from a given tag object.
*
* @since 2.3.0
*
* @param WP_Term $tag Tag Object.
*/
function wxr_tag_description( $tag ) {
if ( empty( $tag->description ) ) {
return;
}
echo '<wp:tag_description>' . wxr_cdata( $tag->description ) . "</wp:tag_description>\n";
}
/**
* Outputs a term_name XML tag from a given term object.
*
* @since 2.9.0
*
* @param WP_Term $term Term Object.
*/
function wxr_term_name( $term ) {
if ( empty( $term->name ) ) {
return;
}
echo '<wp:term_name>' . wxr_cdata( $term->name ) . "</wp:term_name>\n";
}
/**
* Outputs a term_description XML tag from a given term object.
*
* @since 2.9.0
*
* @param WP_Term $term Term Object.
*/
function wxr_term_description( $term ) {
if ( empty( $term->description ) ) {
return;
}
echo "\t\t<wp:term_description>" . wxr_cdata( $term->description ) . "</wp:term_description>\n";
}
/**
* Outputs term meta XML tags for a given term object.
*
* @since 4.6.0
*
* @global wpdb $wpdb WordPress database abstraction object.
*
* @param WP_Term $term Term object.
*/
function wxr_term_meta( $term ) {
global $wpdb;
$termmeta = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM $wpdb->termmeta WHERE term_id = %d", $term->term_id ) );
foreach ( $termmeta as $meta ) {
/**
* Filters whether to selectively skip term meta used for WXR exports.
*
* Returning a truthy value from the filter will skip the current meta
* object from being exported.
*
* @since 4.6.0
*
* @param bool $skip Whether to skip the current piece of term meta. Default false.
* @param string $meta_key Current meta key.
* @param object $meta Current meta object.
*/
if ( ! apply_filters( 'wxr_export_skip_termmeta', false, $meta->meta_key, $meta ) ) {
printf( "\t\t<wp:termmeta>\n\t\t\t<wp:meta_key>%s</wp:meta_key>\n\t\t\t<wp:meta_value>%s</wp:meta_value>\n\t\t</wp:termmeta>\n", wxr_cdata( $meta->meta_key ), wxr_cdata( $meta->meta_value ) );
}
}
}
/**
* Outputs list of authors with posts.
*
* @since 3.1.0
*
* @global wpdb $wpdb WordPress database abstraction object.
*
* @param int[] $post_ids Optional. Array of post IDs to filter the query by.
*/
function wxr_authors_list( array $post_ids = null ) {
global $wpdb;
if ( ! empty( $post_ids ) ) {
$post_ids = array_map( 'absint', $post_ids );
$and = 'AND ID IN ( ' . implode( ', ', $post_ids ) . ')';
} else {
$and = '';
}
$authors = array();
$results = $wpdb->get_results( "SELECT DISTINCT post_author FROM $wpdb->posts WHERE post_status != 'auto-draft' $and" );
foreach ( (array) $results as $result ) {
$authors[] = get_userdata( $result->post_author );
}
$authors = array_filter( $authors );
foreach ( $authors as $author ) {
echo "\t<wp:author>";
echo '<wp:author_id>' . (int) $author->ID . '</wp:author_id>';
echo '<wp:author_login>' . wxr_cdata( $author->user_login ) . '</wp:author_login>';
echo '<wp:author_email>' . wxr_cdata( $author->user_email ) . '</wp:author_email>';
echo '<wp:author_display_name>' . wxr_cdata( $author->display_name ) . '</wp:author_display_name>';
echo '<wp:author_first_name>' . wxr_cdata( $author->first_name ) . '</wp:author_first_name>';
echo '<wp:author_last_name>' . wxr_cdata( $author->last_name ) . '</wp:author_last_name>';
echo "</wp:author>\n";
}
}
/**
* Outputs all navigation menu terms.
*
* @since 3.1.0
*/
function wxr_nav_menu_terms() {
$nav_menus = wp_get_nav_menus();
if ( empty( $nav_menus ) || ! is_array( $nav_menus ) ) {
return;
}
foreach ( $nav_menus as $menu ) {
echo "\t<wp:term>";
echo '<wp:term_id>' . (int) $menu->term_id . '</wp:term_id>';
echo '<wp:term_taxonomy>nav_menu</wp:term_taxonomy>';
echo '<wp:term_slug>' . wxr_cdata( $menu->slug ) . '</wp:term_slug>';
wxr_term_name( $menu );
echo "</wp:term>\n";
}
}
/**
* Outputs list of taxonomy terms, in XML tag format, associated with a post.
*
* @since 2.3.0
*/
function wxr_post_taxonomy() {
$post = get_post();
$taxonomies = get_object_taxonomies( $post->post_type );
if ( empty( $taxonomies ) ) {
return;
}
$terms = wp_get_object_terms( $post->ID, $taxonomies );
foreach ( (array) $terms as $term ) {
echo "\t\t<category domain=\"{$term->taxonomy}\" nicename=\"{$term->slug}\">" . wxr_cdata( $term->name ) . "</category>\n";
}
}
/**
* Determines whether to selectively skip post meta used for WXR exports.
*
* @since 3.3.0
*
* @param bool $return_me Whether to skip the current post meta. Default false.
* @param string $meta_key Meta key.
* @return bool
*/
function wxr_filter_postmeta( $return_me, $meta_key ) {
if ( '_edit_lock' === $meta_key ) {
$return_me = true;
}
return $return_me;
}
add_filter( 'wxr_export_skip_postmeta', 'wxr_filter_postmeta', 10, 2 );
echo '<?xml version="1.0" encoding="' . get_bloginfo( 'charset' ) . "\" ?>\n";
?>
<!-- This is a WordPress eXtended RSS file generated by WordPress as an export of your site. -->
<!-- It contains information about your site's posts, pages, comments, categories, and other content. -->
<!-- You may use this file to transfer that content from one site to another. -->
<!-- This file is not intended to serve as a complete backup of your site. -->
<!-- To import this information into a WordPress site follow these steps: -->
<!-- 1. Log in to that site as an administrator. -->
<!-- 2. Go to Tools: Import in the WordPress admin panel. -->
<!-- 3. Install the "WordPress" importer from the list. -->
<!-- 4. Activate & Run Importer. -->
<!-- 5. Upload this file using the form provided on that page. -->
<!-- 6. You will first be asked to map the authors in this export file to users -->
<!-- on the site. For each author, you may choose to map to an -->
<!-- existing user on the site or to create a new user. -->
<!-- 7. WordPress will then import each of the posts, pages, comments, categories, etc. -->
<!-- contained in this file into your site. -->
<?php the_generator( 'export' ); ?>
<rss version="2.0"
xmlns:excerpt="http://wordpress.org/export/<?php echo WXR_VERSION; ?>/excerpt/"
xmlns:content="http://purl.org/rss/1.0/modules/content/"
xmlns:wfw="http://wellformedweb.org/CommentAPI/"
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:wp="http://wordpress.org/export/<?php echo WXR_VERSION; ?>/"
>
<channel>
<title><?php bloginfo_rss( 'name' ); ?></title>
<link><?php bloginfo_rss( 'url' ); ?></link>
<description><?php bloginfo_rss( 'description' ); ?></description>
<pubDate><?php echo gmdate( 'D, d M Y H:i:s +0000' ); ?></pubDate>
<language><?php bloginfo_rss( 'language' ); ?></language>
<wp:wxr_version><?php echo WXR_VERSION; ?></wp:wxr_version>
<wp:base_site_url><?php echo wxr_site_url(); ?></wp:base_site_url>
<wp:base_blog_url><?php bloginfo_rss( 'url' ); ?></wp:base_blog_url>
<?php wxr_authors_list( $post_ids ); ?>
<?php foreach ( $cats as $c ) : ?>
<wp:category>
<wp:term_id><?php echo (int) $c->term_id; ?></wp:term_id>
<wp:category_nicename><?php echo wxr_cdata( $c->slug ); ?></wp:category_nicename>
<wp:category_parent><?php echo wxr_cdata( $c->parent ? $cats[ $c->parent ]->slug : '' ); ?></wp:category_parent>
<?php
wxr_cat_name( $c );
wxr_category_description( $c );
wxr_term_meta( $c );
?>
</wp:category>
<?php endforeach; ?>
<?php foreach ( $tags as $t ) : ?>
<wp:tag>
<wp:term_id><?php echo (int) $t->term_id; ?></wp:term_id>
<wp:tag_slug><?php echo wxr_cdata( $t->slug ); ?></wp:tag_slug>
<?php
wxr_tag_name( $t );
wxr_tag_description( $t );
wxr_term_meta( $t );
?>
</wp:tag>
<?php endforeach; ?>
<?php foreach ( $terms as $t ) : ?>
<wp:term>
<wp:term_id><?php echo (int) $t->term_id; ?></wp:term_id>
<wp:term_taxonomy><?php echo wxr_cdata( $t->taxonomy ); ?></wp:term_taxonomy>
<wp:term_slug><?php echo wxr_cdata( $t->slug ); ?></wp:term_slug>
<wp:term_parent><?php echo wxr_cdata( $t->parent ? $terms[ $t->parent ]->slug : '' ); ?></wp:term_parent>
<?php
wxr_term_name( $t );
wxr_term_description( $t );
wxr_term_meta( $t );
?>
</wp:term>
<?php endforeach; ?>
<?php
if ( 'all' === $args['content'] ) {
wxr_nav_menu_terms();
}
?>
<?php
/** This action is documented in wp-includes/feed-rss2.php */
do_action( 'rss2_head' );
?>
<?php
if ( $post_ids ) {
/**
* @global WP_Query $wp_query WordPress Query object.
*/
global $wp_query;
// Fake being in the loop.
$wp_query->in_the_loop = true;
// Fetch 20 posts at a time rather than loading the entire table into memory.
while ( $next_posts = array_splice( $post_ids, 0, 20 ) ) {
$where = 'WHERE ID IN (' . implode( ',', $next_posts ) . ')';
$posts = $wpdb->get_results( "SELECT * FROM {$wpdb->posts} $where" );
// Begin Loop.
foreach ( $posts as $post ) {
setup_postdata( $post );
/**
* Filters the post title used for WXR exports.
*
* @since 5.7.0
*
* @param string $post_title Title of the current post.
*/
$title = wxr_cdata( apply_filters( 'the_title_export', $post->post_title ) );
/**
* Filters the post content used for WXR exports.
*
* @since 2.5.0
*
* @param string $post_content Content of the current post.
*/
$content = wxr_cdata( apply_filters( 'the_content_export', $post->post_content ) );
/**
* Filters the post excerpt used for WXR exports.
*
* @since 2.6.0
*
* @param string $post_excerpt Excerpt for the current post.
*/
$excerpt = wxr_cdata( apply_filters( 'the_excerpt_export', $post->post_excerpt ) );
$is_sticky = is_sticky( $post->ID ) ? 1 : 0;
?>
<item>
<title><?php echo $title; ?></title>
<link><?php the_permalink_rss(); ?></link>
<pubDate><?php echo mysql2date( 'D, d M Y H:i:s +0000', get_post_time( 'Y-m-d H:i:s', true ), false ); ?></pubDate>
<dc:creator><?php echo wxr_cdata( get_the_author_meta( 'login' ) ); ?></dc:creator>
<guid isPermaLink="false"><?php the_guid(); ?></guid>
<description></description>
<content:encoded><?php echo $content; ?></content:encoded>
<excerpt:encoded><?php echo $excerpt; ?></excerpt:encoded>
<wp:post_id><?php echo (int) $post->ID; ?></wp:post_id>
<wp:post_date><?php echo wxr_cdata( $post->post_date ); ?></wp:post_date>
<wp:post_date_gmt><?php echo wxr_cdata( $post->post_date_gmt ); ?></wp:post_date_gmt>
<wp:post_modified><?php echo wxr_cdata( $post->post_modified ); ?></wp:post_modified>
<wp:post_modified_gmt><?php echo wxr_cdata( $post->post_modified_gmt ); ?></wp:post_modified_gmt>
<wp:comment_status><?php echo wxr_cdata( $post->comment_status ); ?></wp:comment_status>
<wp:ping_status><?php echo wxr_cdata( $post->ping_status ); ?></wp:ping_status>
<wp:post_name><?php echo wxr_cdata( $post->post_name ); ?></wp:post_name>
<wp:status><?php echo wxr_cdata( $post->post_status ); ?></wp:status>
<wp:post_parent><?php echo (int) $post->post_parent; ?></wp:post_parent>
<wp:menu_order><?php echo (int) $post->menu_order; ?></wp:menu_order>
<wp:post_type><?php echo wxr_cdata( $post->post_type ); ?></wp:post_type>
<wp:post_password><?php echo wxr_cdata( $post->post_password ); ?></wp:post_password>
<wp:is_sticky><?php echo (int) $is_sticky; ?></wp:is_sticky>
<?php if ( 'attachment' === $post->post_type ) : ?>
<wp:attachment_url><?php echo wxr_cdata( wp_get_attachment_url( $post->ID ) ); ?></wp:attachment_url>
<?php endif; ?>
<?php wxr_post_taxonomy(); ?>
<?php
$postmeta = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM $wpdb->postmeta WHERE post_id = %d", $post->ID ) );
foreach ( $postmeta as $meta ) :
/**
* Filters whether to selectively skip post meta used for WXR exports.
*
* Returning a truthy value from the filter will skip the current meta
* object from being exported.
*
* @since 3.3.0
*
* @param bool $skip Whether to skip the current post meta. Default false.
* @param string $meta_key Current meta key.
* @param object $meta Current meta object.
*/
if ( apply_filters( 'wxr_export_skip_postmeta', false, $meta->meta_key, $meta ) ) {
continue;
}
?>
<wp:postmeta>
<wp:meta_key><?php echo wxr_cdata( $meta->meta_key ); ?></wp:meta_key>
<wp:meta_value><?php echo wxr_cdata( $meta->meta_value ); ?></wp:meta_value>
</wp:postmeta>
<?php
endforeach;
$_comments = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM $wpdb->comments WHERE comment_post_ID = %d AND comment_approved <> 'spam'", $post->ID ) );
$comments = array_map( 'get_comment', $_comments );
foreach ( $comments as $c ) :
?>
<wp:comment>
<wp:comment_id><?php echo (int) $c->comment_ID; ?></wp:comment_id>
<wp:comment_author><?php echo wxr_cdata( $c->comment_author ); ?></wp:comment_author>
<wp:comment_author_email><?php echo wxr_cdata( $c->comment_author_email ); ?></wp:comment_author_email>
<wp:comment_author_url><?php echo sanitize_url( $c->comment_author_url ); ?></wp:comment_author_url>
<wp:comment_author_IP><?php echo wxr_cdata( $c->comment_author_IP ); ?></wp:comment_author_IP>
<wp:comment_date><?php echo wxr_cdata( $c->comment_date ); ?></wp:comment_date>
<wp:comment_date_gmt><?php echo wxr_cdata( $c->comment_date_gmt ); ?></wp:comment_date_gmt>
<wp:comment_content><?php echo wxr_cdata( $c->comment_content ); ?></wp:comment_content>
<wp:comment_approved><?php echo wxr_cdata( $c->comment_approved ); ?></wp:comment_approved>
<wp:comment_type><?php echo wxr_cdata( $c->comment_type ); ?></wp:comment_type>
<wp:comment_parent><?php echo (int) $c->comment_parent; ?></wp:comment_parent>
<wp:comment_user_id><?php echo (int) $c->user_id; ?></wp:comment_user_id>
<?php
$c_meta = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM $wpdb->commentmeta WHERE comment_id = %d", $c->comment_ID ) );
foreach ( $c_meta as $meta ) :
/**
* Filters whether to selectively skip comment meta used for WXR exports.
*
* Returning a truthy value from the filter will skip the current meta
* object from being exported.
*
* @since 4.0.0
*
* @param bool $skip Whether to skip the current comment meta. Default false.
* @param string $meta_key Current meta key.
* @param object $meta Current meta object.
*/
if ( apply_filters( 'wxr_export_skip_commentmeta', false, $meta->meta_key, $meta ) ) {
continue;
}
?>
<wp:commentmeta>
<wp:meta_key><?php echo wxr_cdata( $meta->meta_key ); ?></wp:meta_key>
<wp:meta_value><?php echo wxr_cdata( $meta->meta_value ); ?></wp:meta_value>
</wp:commentmeta>
<?php endforeach; ?>
</wp:comment>
<?php endforeach; ?>
</item>
<?php
}
}
}
?>
</channel>
</rss>
<?php
}

2835
wp-admin/includes/file.php Normal file

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

1251
wp-admin/includes/image.php Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,232 @@
<?php
/**
* WordPress Administration Importer API.
*
* @package WordPress
* @subpackage Administration
*/
/**
* Retrieves the list of importers.
*
* @since 2.0.0
*
* @global array $wp_importers
* @return array
*/
function get_importers() {
global $wp_importers;
if ( is_array( $wp_importers ) ) {
uasort( $wp_importers, '_usort_by_first_member' );
}
return $wp_importers;
}
/**
* Sorts a multidimensional array by first member of each top level member.
*
* Used by uasort() as a callback, should not be used directly.
*
* @since 2.9.0
* @access private
*
* @param array $a
* @param array $b
* @return int
*/
function _usort_by_first_member( $a, $b ) {
return strnatcasecmp( $a[0], $b[0] );
}
/**
* Registers importer for WordPress.
*
* @since 2.0.0
*
* @global array $wp_importers
*
* @param string $id Importer tag. Used to uniquely identify importer.
* @param string $name Importer name and title.
* @param string $description Importer description.
* @param callable $callback Callback to run.
* @return void|WP_Error Void on success. WP_Error when $callback is WP_Error.
*/
function register_importer( $id, $name, $description, $callback ) {
global $wp_importers;
if ( is_wp_error( $callback ) ) {
return $callback;
}
$wp_importers[ $id ] = array( $name, $description, $callback );
}
/**
* Cleanup importer.
*
* Removes attachment based on ID.
*
* @since 2.0.0
*
* @param string $id Importer ID.
*/
function wp_import_cleanup( $id ) {
wp_delete_attachment( $id );
}
/**
* Handles importer uploading and adds attachment.
*
* @since 2.0.0
*
* @return array Uploaded file's details on success, error message on failure.
*/
function wp_import_handle_upload() {
if ( ! isset( $_FILES['import'] ) ) {
return array(
'error' => 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() {
// Include an unmodified $wp_version.
require ABSPATH . WPINC . '/version.php';
$locale = get_user_locale();
$cache_key = 'popular_importers_' . md5( $locale . $wp_version );
$popular_importers = get_site_transient( $cache_key );
if ( ! $popular_importers ) {
$url = add_query_arg(
array(
'locale' => $locale,
'version' => $wp_version,
),
'http://api.wordpress.org/core/importers/1.1/'
);
$options = array( 'user-agent' => 'WordPress/' . $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 &amp; 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',
),
);
}

View File

@ -0,0 +1,108 @@
<?php
/**
* Helper functions for displaying a list of items in an ajaxified HTML table.
*
* @package WordPress
* @subpackage List_Table
* @since 3.1.0
*/
/**
* Fetches an instance of a WP_List_Table class.
*
* @since 3.1.0
*
* @global string $hook_suffix
*
* @param string $class_name The type of the list table, which is the class name.
* @param array $args Optional. Arguments to pass to the class. Accepts 'screen'.
* @return WP_List_Table|false List table object on success, false if the class does not exist.
*/
function _get_list_table( $class_name, $args = array() ) {
$core_classes = array(
// Site Admin.
'WP_Posts_List_Table' => 'posts',
'WP_Media_List_Table' => 'media',
'WP_Terms_List_Table' => 'terms',
'WP_Users_List_Table' => 'users',
'WP_Comments_List_Table' => 'comments',
'WP_Post_Comments_List_Table' => array( 'comments', 'post-comments' ),
'WP_Links_List_Table' => 'links',
'WP_Plugin_Install_List_Table' => 'plugin-install',
'WP_Themes_List_Table' => 'themes',
'WP_Theme_Install_List_Table' => array( 'themes', 'theme-install' ),
'WP_Plugins_List_Table' => 'plugins',
'WP_Application_Passwords_List_Table' => 'application-passwords',
// Network Admin.
'WP_MS_Sites_List_Table' => 'ms-sites',
'WP_MS_Users_List_Table' => 'ms-users',
'WP_MS_Themes_List_Table' => 'ms-themes',
// Privacy requests tables.
'WP_Privacy_Data_Export_Requests_List_Table' => 'privacy-data-export-requests',
'WP_Privacy_Data_Removal_Requests_List_Table' => 'privacy-data-removal-requests',
);
if ( isset( $core_classes[ $class_name ] ) ) {
foreach ( (array) $core_classes[ $class_name ] as $required ) {
require_once ABSPATH . 'wp-admin/includes/class-wp-' . $required . '-list-table.php';
}
if ( isset( $args['screen'] ) ) {
$args['screen'] = convert_to_screen( $args['screen'] );
} elseif ( isset( $GLOBALS['hook_suffix'] ) ) {
$args['screen'] = get_current_screen();
} else {
$args['screen'] = null;
}
/**
* Filters the list table class to instantiate.
*
* @since 6.1.0
*
* @param string $class_name The list table class to use.
* @param array $args An array containing _get_list_table() arguments.
*/
$custom_class_name = apply_filters( 'wp_list_table_class_name', $class_name, $args );
if ( is_string( $custom_class_name ) && class_exists( $custom_class_name ) ) {
$class_name = $custom_class_name;
}
return new $class_name( $args );
}
return false;
}
/**
* Register column headers for a particular screen.
*
* @see get_column_headers(), print_column_headers(), get_hidden_columns()
*
* @since 2.7.0
*
* @param string $screen The handle for the screen to register column headers for. This is
* usually the hook name returned by the `add_*_page()` functions.
* @param string[] $columns An array of columns with column IDs as the keys and translated
* column names as the values.
*/
function register_column_headers( $screen, $columns ) {
new _WP_List_Table_Compat( $screen, $columns );
}
/**
* Prints column headers for a particular screen.
*
* @since 2.7.0
*
* @param string|WP_Screen $screen The screen hook name or screen object.
* @param bool $with_id Whether to set the ID attribute or not.
*/
function print_column_headers( $screen, $with_id = true ) {
$wp_list_table = new _WP_List_Table_Compat( $screen );
$wp_list_table->print_column_headers( $with_id );
}

3873
wp-admin/includes/media.php Normal file

File diff suppressed because it is too large Load Diff

383
wp-admin/includes/menu.php Normal file
View File

@ -0,0 +1,383 @@
<?php
/**
* Build Administration Menu.
*
* @package WordPress
* @subpackage Administration
*/
if ( is_network_admin() ) {
/**
* Fires before the administration menu loads in the Network Admin.
*
* The hook fires before menus and sub-menus are removed based on user privileges.
*
* @since 3.1.0
* @access private
*/
do_action( '_network_admin_menu' );
} elseif ( is_user_admin() ) {
/**
* Fires before the administration menu loads in the User Admin.
*
* The hook fires before menus and sub-menus are removed based on user privileges.
*
* @since 3.1.0
* @access private
*/
do_action( '_user_admin_menu' );
} else {
/**
* Fires before the administration menu loads in the admin.
*
* The hook fires before menus and sub-menus are removed based on user privileges.
*
* @since 2.2.0
* @access private
*/
do_action( '_admin_menu' );
}
// Create list of page plugin hook names.
foreach ( $menu as $menu_page ) {
$pos = strpos( $menu_page[2], '?' );
if ( false !== $pos ) {
// Handle post_type=post|page|foo pages.
$hook_name = substr( $menu_page[2], 0, $pos );
$hook_args = substr( $menu_page[2], $pos + 1 );
wp_parse_str( $hook_args, $hook_args );
// Set the hook name to be the post type.
if ( isset( $hook_args['post_type'] ) ) {
$hook_name = $hook_args['post_type'];
} else {
$hook_name = basename( $hook_name, '.php' );
}
unset( $hook_args );
} else {
$hook_name = basename( $menu_page[2], '.php' );
}
$hook_name = sanitize_title( $hook_name );
if ( isset( $compat[ $hook_name ] ) ) {
$hook_name = $compat[ $hook_name ];
} elseif ( ! $hook_name ) {
continue;
}
$admin_page_hooks[ $menu_page[2] ] = $hook_name;
}
unset( $menu_page, $compat );
$_wp_submenu_nopriv = array();
$_wp_menu_nopriv = array();
// Loop over submenus and remove pages for which the user does not have privs.
foreach ( $submenu as $parent => $sub ) {
foreach ( $sub as $index => $data ) {
if ( ! current_user_can( $data[1] ) ) {
unset( $submenu[ $parent ][ $index ] );
$_wp_submenu_nopriv[ $parent ][ $data[2] ] = true;
}
}
unset( $index, $data );
if ( empty( $submenu[ $parent ] ) ) {
unset( $submenu[ $parent ] );
}
}
unset( $sub, $parent );
/*
* Loop over the top-level menu.
* Menus for which the original parent is not accessible due to lack of privileges
* will have the next submenu in line be assigned as the new menu parent.
*/
foreach ( $menu as $id => $data ) {
if ( empty( $submenu[ $data[2] ] ) ) {
continue;
}
$subs = $submenu[ $data[2] ];
$first_sub = reset( $subs );
$old_parent = $data[2];
$new_parent = $first_sub[2];
/*
* If the first submenu is not the same as the assigned parent,
* make the first submenu the new parent.
*/
if ( $new_parent !== $old_parent ) {
$_wp_real_parent_file[ $old_parent ] = $new_parent;
$menu[ $id ][2] = $new_parent;
foreach ( $submenu[ $old_parent ] as $index => $data ) {
$submenu[ $new_parent ][ $index ] = $submenu[ $old_parent ][ $index ];
unset( $submenu[ $old_parent ][ $index ] );
}
unset( $submenu[ $old_parent ], $index );
if ( isset( $_wp_submenu_nopriv[ $old_parent ] ) ) {
$_wp_submenu_nopriv[ $new_parent ] = $_wp_submenu_nopriv[ $old_parent ];
}
}
}
unset( $id, $data, $subs, $first_sub, $old_parent, $new_parent );
if ( is_network_admin() ) {
/**
* Fires before the administration menu loads in the Network Admin.
*
* @since 3.1.0
*
* @param string $context Empty context.
*/
do_action( 'network_admin_menu', '' );
} elseif ( is_user_admin() ) {
/**
* Fires before the administration menu loads in the User Admin.
*
* @since 3.1.0
*
* @param string $context Empty context.
*/
do_action( 'user_admin_menu', '' );
} else {
/**
* Fires before the administration menu loads in the admin.
*
* @since 1.5.0
*
* @param string $context Empty context.
*/
do_action( 'admin_menu', '' );
}
/*
* Remove menus that have no accessible submenus and require privileges
* that the user does not have. Run re-parent loop again.
*/
foreach ( $menu as $id => $data ) {
if ( ! current_user_can( $data[1] ) ) {
$_wp_menu_nopriv[ $data[2] ] = true;
}
/*
* If there is only one submenu and it is has same destination as the parent,
* remove the submenu.
*/
if ( ! empty( $submenu[ $data[2] ] ) && 1 === count( $submenu[ $data[2] ] ) ) {
$subs = $submenu[ $data[2] ];
$first_sub = reset( $subs );
if ( $data[2] === $first_sub[2] ) {
unset( $submenu[ $data[2] ] );
}
}
// If submenu is empty...
if ( empty( $submenu[ $data[2] ] ) ) {
// And user doesn't have privs, remove menu.
if ( isset( $_wp_menu_nopriv[ $data[2] ] ) ) {
unset( $menu[ $id ] );
}
}
}
unset( $id, $data, $subs, $first_sub );
/**
* Adds a CSS class to a string.
*
* @since 2.7.0
*
* @param string $class_to_add The CSS class to add.
* @param string $classes The string to add the CSS class to.
* @return string The string with the CSS class added.
*/
function add_cssclass( $class_to_add, $classes ) {
if ( empty( $classes ) ) {
return $class_to_add;
}
return $classes . ' ' . $class_to_add;
}
/**
* Adds CSS classes for top-level administration menu items.
*
* The list of added classes includes `.menu-top-first` and `.menu-top-last`.
*
* @since 2.7.0
*
* @param array $menu The array of administration menu items.
* @return array The array of administration menu items with the CSS classes added.
*/
function add_menu_classes( $menu ) {
$first_item = false;
$last_order = false;
$items_count = count( $menu );
$i = 0;
foreach ( $menu as $order => $top ) {
++$i;
if ( 0 === $order ) { // Dashboard is always shown/single.
$menu[0][4] = add_cssclass( 'menu-top-first', $top[4] );
$last_order = 0;
continue;
}
if ( str_starts_with( $top[2], 'separator' ) && false !== $last_order ) { // If separator.
$first_item = true;
$classes = $menu[ $last_order ][4];
$menu[ $last_order ][4] = add_cssclass( 'menu-top-last', $classes );
continue;
}
if ( $first_item ) {
$first_item = false;
$classes = $menu[ $order ][4];
$menu[ $order ][4] = add_cssclass( 'menu-top-first', $classes );
}
if ( $i === $items_count ) { // Last item.
$classes = $menu[ $order ][4];
$menu[ $order ][4] = add_cssclass( 'menu-top-last', $classes );
}
$last_order = $order;
}
/**
* Filters administration menu array with classes added for top-level items.
*
* @since 2.7.0
*
* @param array $menu Associative array of administration menu items.
*/
return apply_filters( 'add_menu_classes', $menu );
}
uksort( $menu, 'strnatcasecmp' ); // Make it all pretty.
/**
* Filters whether to enable custom ordering of the administration menu.
*
* See the {@see 'menu_order'} filter for reordering menu items.
*
* @since 2.8.0
*
* @param bool $custom Whether custom ordering is enabled. Default false.
*/
if ( apply_filters( 'custom_menu_order', false ) ) {
$menu_order = array();
foreach ( $menu as $menu_item ) {
$menu_order[] = $menu_item[2];
}
unset( $menu_item );
$default_menu_order = $menu_order;
/**
* Filters the order of administration menu items.
*
* A truthy value must first be passed to the {@see 'custom_menu_order'} filter
* for this filter to work. Use the following to enable custom menu ordering:
*
* add_filter( 'custom_menu_order', '__return_true' );
*
* @since 2.8.0
*
* @param array $menu_order An ordered array of menu items.
*/
$menu_order = apply_filters( 'menu_order', $menu_order );
$menu_order = array_flip( $menu_order );
$default_menu_order = array_flip( $default_menu_order );
/**
* @global array $menu_order
* @global array $default_menu_order
*
* @param array $a
* @param array $b
* @return int
*/
function sort_menu( $a, $b ) {
global $menu_order, $default_menu_order;
$a = $a[2];
$b = $b[2];
if ( isset( $menu_order[ $a ] ) && ! isset( $menu_order[ $b ] ) ) {
return -1;
} elseif ( ! isset( $menu_order[ $a ] ) && isset( $menu_order[ $b ] ) ) {
return 1;
} elseif ( isset( $menu_order[ $a ] ) && isset( $menu_order[ $b ] ) ) {
if ( $menu_order[ $a ] === $menu_order[ $b ] ) {
return 0;
}
return ( $menu_order[ $a ] < $menu_order[ $b ] ) ? -1 : 1;
} else {
return ( $default_menu_order[ $a ] <= $default_menu_order[ $b ] ) ? -1 : 1;
}
}
usort( $menu, 'sort_menu' );
unset( $menu_order, $default_menu_order );
}
// Prevent adjacent separators.
$prev_menu_was_separator = false;
foreach ( $menu as $id => $data ) {
if ( false === stristr( $data[4], 'wp-menu-separator' ) ) {
// This item is not a separator, so falsey the toggler and do nothing.
$prev_menu_was_separator = false;
} else {
// The previous item was a separator, so unset this one.
if ( true === $prev_menu_was_separator ) {
unset( $menu[ $id ] );
}
// This item is a separator, so truthy the toggler and move on.
$prev_menu_was_separator = true;
}
}
unset( $id, $data, $prev_menu_was_separator );
// Remove the last menu item if it is a separator.
$last_menu_key = array_keys( $menu );
$last_menu_key = array_pop( $last_menu_key );
if ( ! empty( $menu ) && 'wp-menu-separator' === $menu[ $last_menu_key ][4] ) {
unset( $menu[ $last_menu_key ] );
}
unset( $last_menu_key );
if ( ! user_can_access_admin_page() ) {
/**
* Fires when access to an admin page is denied.
*
* @since 2.5.0
*/
do_action( 'admin_page_access_denied' );
wp_die( __( 'Sorry, you are not allowed to access this page.' ), 403 );
}
$menu = add_menu_classes( $menu );

File diff suppressed because it is too large Load Diff

1659
wp-admin/includes/misc.php Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,41 @@
<?php
/**
* Multisite Administration hooks
*
* @package WordPress
* @subpackage Administration
* @since 4.3.0
*/
// Media hooks.
add_filter( 'wp_handle_upload_prefilter', 'check_upload_size' );
// User hooks.
add_action( 'user_admin_notices', 'new_user_email_admin_notice' );
add_action( 'network_admin_notices', 'new_user_email_admin_notice' );
add_action( 'admin_page_access_denied', '_access_denied_splash', 99 );
// Site hooks.
add_action( 'wpmueditblogaction', 'upload_space_setting' );
// Network hooks.
add_action( 'update_site_option_admin_email', 'wp_network_admin_email_change_notification', 10, 4 );
// Post hooks.
add_filter( 'wp_insert_post_data', 'avoid_blog_page_permalink_collision', 10, 2 );
// Tools hooks.
add_filter( 'import_allow_create_users', 'check_import_new_users' );
// Notices hooks.
add_action( 'admin_notices', 'site_admin_notice' );
add_action( 'network_admin_notices', 'site_admin_notice' );
// Update hooks.
add_action( 'network_admin_notices', 'update_nag', 3 );
add_action( 'network_admin_notices', 'maintenance_nag', 10 );
// Network Admin hooks.
add_action( 'add_site_option_new_admin_email', 'update_network_option_new_admin_email', 10, 2 );
add_action( 'update_site_option_new_admin_email', 'update_network_option_new_admin_email', 10, 2 );

View File

@ -0,0 +1,140 @@
<?php
/**
* Multisite: Deprecated admin functions from past versions and WordPress MU
*
* These functions should not be used and will be removed in a later version.
* It is suggested to use for the alternatives instead when available.
*
* @package WordPress
* @subpackage Deprecated
* @since 3.0.0
*/
/**
* Outputs the WPMU menu.
*
* @deprecated 3.0.0
*/
function wpmu_menu() {
_deprecated_function( __FUNCTION__, '3.0.0' );
// Deprecated. See #11763.
}
/**
* Determines if the available space defined by the admin has been exceeded by the user.
*
* @deprecated 3.0.0 Use is_upload_space_available()
* @see is_upload_space_available()
*/
function wpmu_checkAvailableSpace() {
_deprecated_function( __FUNCTION__, '3.0.0', 'is_upload_space_available()' );
if ( ! is_upload_space_available() ) {
wp_die( sprintf(
/* translators: %s: Allowed space allocation. */
__( 'Sorry, you have used your space allocation of %s. Please delete some files to upload more files.' ),
size_format( get_space_allowed() * MB_IN_BYTES )
) );
}
}
/**
* WPMU options.
*
* @deprecated 3.0.0
*/
function mu_options( $options ) {
_deprecated_function( __FUNCTION__, '3.0.0' );
return $options;
}
/**
* Deprecated functionality for activating a network-only plugin.
*
* @deprecated 3.0.0 Use activate_plugin()
* @see activate_plugin()
*/
function activate_sitewide_plugin() {
_deprecated_function( __FUNCTION__, '3.0.0', 'activate_plugin()' );
return false;
}
/**
* Deprecated functionality for deactivating a network-only plugin.
*
* @deprecated 3.0.0 Use deactivate_plugin()
* @see deactivate_plugin()
*/
function deactivate_sitewide_plugin( $plugin = false ) {
_deprecated_function( __FUNCTION__, '3.0.0', 'deactivate_plugin()' );
}
/**
* Deprecated functionality for determining if the current plugin is network-only.
*
* @deprecated 3.0.0 Use is_network_only_plugin()
* @see is_network_only_plugin()
*/
function is_wpmu_sitewide_plugin( $file ) {
_deprecated_function( __FUNCTION__, '3.0.0', 'is_network_only_plugin()' );
return is_network_only_plugin( $file );
}
/**
* Deprecated functionality for getting themes network-enabled themes.
*
* @deprecated 3.4.0 Use WP_Theme::get_allowed_on_network()
* @see WP_Theme::get_allowed_on_network()
*/
function get_site_allowed_themes() {
_deprecated_function( __FUNCTION__, '3.4.0', 'WP_Theme::get_allowed_on_network()' );
return array_map( 'intval', WP_Theme::get_allowed_on_network() );
}
/**
* Deprecated functionality for getting themes allowed on a specific site.
*
* @deprecated 3.4.0 Use WP_Theme::get_allowed_on_site()
* @see WP_Theme::get_allowed_on_site()
*/
function wpmu_get_blog_allowedthemes( $blog_id = 0 ) {
_deprecated_function( __FUNCTION__, '3.4.0', 'WP_Theme::get_allowed_on_site()' );
return array_map( 'intval', WP_Theme::get_allowed_on_site( $blog_id ) );
}
/**
* Deprecated functionality for determining whether a file is deprecated.
*
* @deprecated 3.5.0
*/
function ms_deprecated_blogs_file() {}
if ( ! function_exists( 'install_global_terms' ) ) :
/**
* Install global terms.
*
* @since 3.0.0
* @since 6.1.0 This function no longer does anything.
* @deprecated 6.1.0
*/
function install_global_terms() {
_deprecated_function( __FUNCTION__, '6.1.0' );
}
endif;
/**
* Synchronizes category and post tag slugs when global terms are enabled.
*
* @since 3.0.0
* @since 6.1.0 This function no longer does anything.
* @deprecated 6.1.0
*
* @param WP_Term|array $term The term.
* @param string $taxonomy The taxonomy for `$term`.
* @return WP_Term|array Always returns `$term`.
*/
function sync_category_tag_slugs( $term, $taxonomy ) {
_deprecated_function( __FUNCTION__, '6.1.0' );
return $term;
}

1174
wp-admin/includes/ms.php Normal file

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,760 @@
<?php
/**
* WordPress Network Administration API.
*
* @package WordPress
* @subpackage Administration
* @since 4.4.0
*/
/**
* Check for an existing network.
*
* @since 3.0.0
*
* @global wpdb $wpdb WordPress database abstraction object.
*
* @return string|false Base domain if network exists, otherwise false.
*/
function network_domain_check() {
global $wpdb;
$sql = $wpdb->prepare( 'SHOW TABLES LIKE %s', $wpdb->esc_like( $wpdb->site ) );
if ( $wpdb->get_var( $sql ) ) {
return $wpdb->get_var( "SELECT domain FROM $wpdb->site ORDER BY id ASC LIMIT 1" );
}
return false;
}
/**
* Allow subdomain installation
*
* @since 3.0.0
* @return bool Whether subdomain installation is allowed
*/
function allow_subdomain_install() {
$domain = preg_replace( '|https?://([^/]+)|', '$1', get_option( 'home' ) );
if ( parse_url( get_option( 'home' ), PHP_URL_PATH ) || 'localhost' === $domain || preg_match( '|^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$|', $domain ) ) {
return false;
}
return true;
}
/**
* Allow subdirectory installation.
*
* @since 3.0.0
*
* @global wpdb $wpdb WordPress database abstraction object.
*
* @return bool Whether subdirectory installation is allowed
*/
function allow_subdirectory_install() {
global $wpdb;
/**
* Filters whether to enable the subdirectory installation feature in Multisite.
*
* @since 3.0.0
*
* @param bool $allow Whether to enable the subdirectory installation feature in Multisite.
* Default false.
*/
if ( apply_filters( 'allow_subdirectory_install', false ) ) {
return true;
}
if ( defined( 'ALLOW_SUBDIRECTORY_INSTALL' ) && ALLOW_SUBDIRECTORY_INSTALL ) {
return true;
}
$post = $wpdb->get_row( "SELECT ID FROM $wpdb->posts WHERE post_date < DATE_SUB(NOW(), INTERVAL 1 MONTH) AND post_status = 'publish'" );
if ( empty( $post ) ) {
return true;
}
return false;
}
/**
* Get base domain of network.
*
* @since 3.0.0
* @return string Base domain.
*/
function get_clean_basedomain() {
$existing_domain = network_domain_check();
if ( $existing_domain ) {
return $existing_domain;
}
$domain = preg_replace( '|https?://|', '', get_option( 'siteurl' ) );
$slash = strpos( $domain, '/' );
if ( $slash ) {
$domain = substr( $domain, 0, $slash );
}
return $domain;
}
/**
* Prints step 1 for Network installation process.
*
* @todo Realistically, step 1 should be a welcome screen explaining what a Network is and such.
* Navigating to Tools > Network should not be a sudden "Welcome to a new install process!
* Fill this out and click here." See also contextual help todo.
*
* @since 3.0.0
*
* @global bool $is_apache
*
* @param false|WP_Error $errors Optional. Error object. Default false.
*/
function network_step1( $errors = false ) {
global $is_apache;
if ( defined( 'DO_NOT_UPGRADE_GLOBAL_TABLES' ) ) {
$cannot_define_constant_message = '<strong>' . __( 'Error:' ) . '</strong> ';
$cannot_define_constant_message .= sprintf(
/* translators: %s: DO_NOT_UPGRADE_GLOBAL_TABLES */
__( 'The constant %s cannot be defined when creating a network.' ),
'<code>DO_NOT_UPGRADE_GLOBAL_TABLES</code>'
);
wp_admin_notice(
$cannot_define_constant_message,
array(
'additional_classes' => array( 'error' ),
)
);
echo '</div>';
require_once ABSPATH . 'wp-admin/admin-footer.php';
die();
}
$active_plugins = get_option( 'active_plugins' );
if ( ! empty( $active_plugins ) ) {
wp_admin_notice(
'<strong>' . __( 'Warning:' ) . '</strong> ' . sprintf(
/* translators: %s: URL to Plugins screen. */
__( 'Please <a href="%s">deactivate your plugins</a> before enabling the Network feature.' ),
admin_url( 'plugins.php?plugin_status=active' )
),
array( 'type' => 'warning' )
);
echo '<p>' . __( 'Once the network is created, you may reactivate your plugins.' ) . '</p>';
echo '</div>';
require_once ABSPATH . 'wp-admin/admin-footer.php';
die();
}
$hostname = get_clean_basedomain();
$has_ports = strstr( $hostname, ':' );
if ( ( false !== $has_ports && ! in_array( $has_ports, array( ':80', ':443' ), true ) ) ) {
wp_admin_notice(
'<strong>' . __( 'Error:' ) . '</strong> ' . __( 'You cannot install a network of sites with your server address.' ),
array(
'additional_classes' => array( 'error' ),
)
);
echo '<p>' . sprintf(
/* translators: %s: Port number. */
__( 'You cannot use port numbers such as %s.' ),
'<code>' . $has_ports . '</code>'
) . '</p>';
echo '<a href="' . esc_url( admin_url() ) . '">' . __( 'Go to Dashboard' ) . '</a>';
echo '</div>';
require_once ABSPATH . 'wp-admin/admin-footer.php';
die();
}
echo '<form method="post">';
wp_nonce_field( 'install-network-1' );
$error_codes = array();
if ( is_wp_error( $errors ) ) {
$network_created_error_message = '<p><strong>' . __( 'Error: The network could not be created.' ) . '</strong></p>';
foreach ( $errors->get_error_messages() as $error ) {
$network_created_error_message .= "<p>$error</p>";
}
wp_admin_notice(
$network_created_error_message,
array(
'additional_classes' => array( 'error' ),
'paragraph_wrap' => false,
)
);
$error_codes = $errors->get_error_codes();
}
if ( ! empty( $_POST['sitename'] ) && ! in_array( 'empty_sitename', $error_codes, true ) ) {
$site_name = $_POST['sitename'];
} else {
/* translators: %s: Default network title. */
$site_name = sprintf( __( '%s Sites' ), get_option( 'blogname' ) );
}
if ( ! empty( $_POST['email'] ) && ! in_array( 'invalid_email', $error_codes, true ) ) {
$admin_email = $_POST['email'];
} else {
$admin_email = get_option( 'admin_email' );
}
?>
<p><?php _e( 'Welcome to the Network installation process!' ); ?></p>
<p><?php _e( 'Fill in the information below and you&#8217;ll be on your way to creating a network of WordPress sites. Configuration files will be created in the next step.' ); ?></p>
<?php
if ( isset( $_POST['subdomain_install'] ) ) {
$subdomain_install = (bool) $_POST['subdomain_install'];
} elseif ( apache_mod_loaded( 'mod_rewrite' ) ) { // Assume nothing.
$subdomain_install = true;
} elseif ( ! allow_subdirectory_install() ) {
$subdomain_install = true;
} else {
$subdomain_install = false;
$got_mod_rewrite = got_mod_rewrite();
if ( $got_mod_rewrite ) { // Dangerous assumptions.
$message_class = 'updated';
$message = '<p><strong>' . __( 'Warning:' ) . '</strong> ';
$message .= '<p>' . sprintf(
/* translators: %s: mod_rewrite */
__( 'Please make sure the Apache %s module is installed as it will be used at the end of this installation.' ),
'<code>mod_rewrite</code>'
) . '</p>';
} elseif ( $is_apache ) {
$message_class = 'error';
$message = '<p><strong>' . __( 'Warning:' ) . '</strong> ';
$message .= sprintf(
/* translators: %s: mod_rewrite */
__( 'It looks like the Apache %s module is not installed.' ),
'<code>mod_rewrite</code>'
) . '</p>';
}
if ( $got_mod_rewrite || $is_apache ) { // Protect against mod_rewrite mimicry (but ! Apache).
$message .= '<p>' . sprintf(
/* translators: 1: mod_rewrite, 2: mod_rewrite documentation URL, 3: Google search for mod_rewrite. */
__( 'If %1$s is disabled, ask your administrator to enable that module, or look at the <a href="%2$s">Apache documentation</a> or <a href="%3$s">elsewhere</a> for help setting it up.' ),
'<code>mod_rewrite</code>',
'https://httpd.apache.org/docs/mod/mod_rewrite.html',
'https://www.google.com/search?q=apache+mod_rewrite'
) . '</p>';
wp_admin_notice(
$message,
array(
'additional_classes' => array( $message_class, 'inline' ),
'paragraph_wrap' => false,
)
);
}
}
if ( allow_subdomain_install() && allow_subdirectory_install() ) :
?>
<h3><?php esc_html_e( 'Addresses of Sites in your Network' ); ?></h3>
<p><?php _e( 'Please choose whether you would like sites in your WordPress network to use sub-domains or sub-directories.' ); ?>
<strong><?php _e( 'You cannot change this later.' ); ?></strong></p>
<p><?php _e( 'You will need a wildcard DNS record if you are going to use the virtual host (sub-domain) functionality.' ); ?></p>
<?php // @todo Link to an MS readme? ?>
<table class="form-table" role="presentation">
<tr>
<th><label><input type="radio" name="subdomain_install" value="1"<?php checked( $subdomain_install ); ?> /> <?php _e( 'Sub-domains' ); ?></label></th>
<td>
<?php
printf(
/* translators: 1: Host name. */
_x( 'like <code>site1.%1$s</code> and <code>site2.%1$s</code>', 'subdomain examples' ),
$hostname
);
?>
</td>
</tr>
<tr>
<th><label><input type="radio" name="subdomain_install" value="0"<?php checked( ! $subdomain_install ); ?> /> <?php _e( 'Sub-directories' ); ?></label></th>
<td>
<?php
printf(
/* translators: 1: Host name. */
_x( 'like <code>%1$s/site1</code> and <code>%1$s/site2</code>', 'subdirectory examples' ),
$hostname
);
?>
</td>
</tr>
</table>
<?php
endif;
if ( WP_CONTENT_DIR !== ABSPATH . 'wp-content' && ( allow_subdirectory_install() || ! allow_subdomain_install() ) ) {
$subdirectory_warning_message = '<strong>' . __( 'Warning:' ) . '</strong> ';
$subdirectory_warning_message .= __( 'Subdirectory networks may not be fully compatible with custom wp-content directories.' );
wp_admin_notice(
$subdirectory_warning_message,
array(
'additional_classes' => array( 'error', 'inline' ),
)
);
}
$is_www = str_starts_with( $hostname, 'www.' );
if ( $is_www ) :
?>
<h3><?php esc_html_e( 'Server Address' ); ?></h3>
<p>
<?php
printf(
/* translators: 1: Site URL, 2: Host name, 3: www. */
__( 'You should consider changing your site domain to %1$s before enabling the network feature. It will still be possible to visit your site using the %3$s prefix with an address like %2$s but any links will not have the %3$s prefix.' ),
'<code>' . substr( $hostname, 4 ) . '</code>',
'<code>' . $hostname . '</code>',
'<code>www</code>'
);
?>
</p>
<table class="form-table" role="presentation">
<tr>
<th scope='row'><?php esc_html_e( 'Server Address' ); ?></th>
<td>
<?php
printf(
/* translators: %s: Host name. */
__( 'The internet address of your network will be %s.' ),
'<code>' . $hostname . '</code>'
);
?>
</td>
</tr>
</table>
<?php endif; ?>
<h3><?php esc_html_e( 'Network Details' ); ?></h3>
<table class="form-table" role="presentation">
<?php if ( 'localhost' === $hostname ) : ?>
<tr>
<th scope="row"><?php esc_html_e( 'Sub-directory Installation' ); ?></th>
<td>
<?php
printf(
/* translators: 1: localhost, 2: localhost.localdomain */
__( 'Because you are using %1$s, the sites in your WordPress network must use sub-directories. Consider using %2$s if you wish to use sub-domains.' ),
'<code>localhost</code>',
'<code>localhost.localdomain</code>'
);
// Uh oh:
if ( ! allow_subdirectory_install() ) {
echo ' <strong>' . __( 'Warning:' ) . ' ' . __( 'The main site in a sub-directory installation will need to use a modified permalink structure, potentially breaking existing links.' ) . '</strong>';
}
?>
</td>
</tr>
<?php elseif ( ! allow_subdomain_install() ) : ?>
<tr>
<th scope="row"><?php esc_html_e( 'Sub-directory Installation' ); ?></th>
<td>
<?php
_e( 'Because your installation is in a directory, the sites in your WordPress network must use sub-directories.' );
// Uh oh:
if ( ! allow_subdirectory_install() ) {
echo ' <strong>' . __( 'Warning:' ) . ' ' . __( 'The main site in a sub-directory installation will need to use a modified permalink structure, potentially breaking existing links.' ) . '</strong>';
}
?>
</td>
</tr>
<?php elseif ( ! allow_subdirectory_install() ) : ?>
<tr>
<th scope="row"><?php esc_html_e( 'Sub-domain Installation' ); ?></th>
<td>
<?php
_e( 'Because your installation is not new, the sites in your WordPress network must use sub-domains.' );
echo ' <strong>' . __( 'The main site in a sub-directory installation will need to use a modified permalink structure, potentially breaking existing links.' ) . '</strong>';
?>
</td>
</tr>
<?php endif; ?>
<?php if ( ! $is_www ) : ?>
<tr>
<th scope='row'><?php esc_html_e( 'Server Address' ); ?></th>
<td>
<?php
printf(
/* translators: %s: Host name. */
__( 'The internet address of your network will be %s.' ),
'<code>' . $hostname . '</code>'
);
?>
</td>
</tr>
<?php endif; ?>
<tr>
<th scope='row'><label for="sitename"><?php esc_html_e( 'Network Title' ); ?></label></th>
<td>
<input name='sitename' id='sitename' type='text' size='45' value='<?php echo esc_attr( $site_name ); ?>' />
<p class="description">
<?php _e( 'What would you like to call your network?' ); ?>
</p>
</td>
</tr>
<tr>
<th scope='row'><label for="email"><?php esc_html_e( 'Network Admin Email' ); ?></label></th>
<td>
<input name='email' id='email' type='text' size='45' value='<?php echo esc_attr( $admin_email ); ?>' />
<p class="description">
<?php _e( 'Your email address.' ); ?>
</p>
</td>
</tr>
</table>
<?php submit_button( __( 'Install' ), 'primary', 'submit' ); ?>
</form>
<?php
}
/**
* Prints step 2 for Network installation process.
*
* @since 3.0.0
*
* @global wpdb $wpdb WordPress database abstraction object.
* @global bool $is_nginx Whether the server software is Nginx or something else.
*
* @param false|WP_Error $errors Optional. Error object. Default false.
*/
function network_step2( $errors = false ) {
global $wpdb, $is_nginx;
$hostname = get_clean_basedomain();
$slashed_home = trailingslashit( get_option( 'home' ) );
$base = parse_url( $slashed_home, PHP_URL_PATH );
$document_root_fix = str_replace( '\\', '/', realpath( $_SERVER['DOCUMENT_ROOT'] ) );
$abspath_fix = str_replace( '\\', '/', ABSPATH );
$home_path = str_starts_with( $abspath_fix, $document_root_fix ) ? $document_root_fix . $base : get_home_path();
$wp_siteurl_subdir = preg_replace( '#^' . preg_quote( $home_path, '#' ) . '#', '', $abspath_fix );
$rewrite_base = ! empty( $wp_siteurl_subdir ) ? ltrim( trailingslashit( $wp_siteurl_subdir ), '/' ) : '';
$location_of_wp_config = $abspath_fix;
if ( ! file_exists( ABSPATH . 'wp-config.php' ) && file_exists( dirname( ABSPATH ) . '/wp-config.php' ) ) {
$location_of_wp_config = dirname( $abspath_fix );
}
$location_of_wp_config = trailingslashit( $location_of_wp_config );
// Wildcard DNS message.
if ( is_wp_error( $errors ) ) {
wp_admin_notice(
$errors->get_error_message(),
array(
'additional_classes' => array( 'error' ),
)
);
}
if ( $_POST ) {
if ( allow_subdomain_install() ) {
$subdomain_install = allow_subdirectory_install() ? ! empty( $_POST['subdomain_install'] ) : true;
} else {
$subdomain_install = false;
}
} else {
if ( is_multisite() ) {
$subdomain_install = is_subdomain_install();
?>
<p><?php _e( 'The original configuration steps are shown here for reference.' ); ?></p>
<?php
} else {
$subdomain_install = (bool) $wpdb->get_var( "SELECT meta_value FROM $wpdb->sitemeta WHERE site_id = 1 AND meta_key = 'subdomain_install'" );
wp_admin_notice(
'<strong>' . __( 'Warning:' ) . '</strong> ' . __( 'An existing WordPress network was detected.' ),
array(
'additional_classes' => array( 'error' ),
)
);
?>
<p><?php _e( 'Please complete the configuration steps. To create a new network, you will need to empty or remove the network database tables.' ); ?></p>
<?php
}
}
$subdir_match = $subdomain_install ? '' : '([_0-9a-zA-Z-]+/)?';
$subdir_replacement_01 = $subdomain_install ? '' : '$1';
$subdir_replacement_12 = $subdomain_install ? '$1' : '$2';
if ( $_POST || ! is_multisite() ) {
?>
<h3><?php esc_html_e( 'Enabling the Network' ); ?></h3>
<p><?php _e( 'Complete the following steps to enable the features for creating a network of sites.' ); ?></p>
<?php
$notice_message = '<strong>' . __( 'Caution:' ) . '</strong> ';
$notice_args = array(
'type' => 'warning',
'additional_classes' => array( 'inline' ),
);
if ( file_exists( $home_path . '.htaccess' ) ) {
$notice_message .= sprintf(
/* translators: 1: wp-config.php, 2: .htaccess */
__( 'You should back up your existing %1$s and %2$s files.' ),
'<code>wp-config.php</code>',
'<code>.htaccess</code>'
);
} elseif ( file_exists( $home_path . 'web.config' ) ) {
$notice_message .= sprintf(
/* translators: 1: wp-config.php, 2: web.config */
__( 'You should back up your existing %1$s and %2$s files.' ),
'<code>wp-config.php</code>',
'<code>web.config</code>'
);
} else {
$notice_message .= sprintf(
/* translators: %s: wp-config.php */
__( 'You should back up your existing %s file.' ),
'<code>wp-config.php</code>'
);
}
wp_admin_notice( $notice_message, $notice_args );
}
?>
<ol>
<li><p id="network-wpconfig-rules-description">
<?php
printf(
/* translators: 1: wp-config.php, 2: Location of wp-config file, 3: Translated version of "That's all, stop editing! Happy publishing." */
__( 'Add the following to your %1$s file in %2$s <strong>above</strong> the line reading %3$s:' ),
'<code>wp-config.php</code>',
'<code>' . $location_of_wp_config . '</code>',
/*
* translators: This string should only be translated if wp-config-sample.php is localized.
* You can check the localized release package or
* https://i18n.svn.wordpress.org/<locale code>/branches/<wp version>/dist/wp-config-sample.php
*/
'<code>/* ' . __( 'That&#8217;s all, stop editing! Happy publishing.' ) . ' */</code>'
);
?>
</p>
<p class="configuration-rules-label"><label for="network-wpconfig-rules">
<?php
printf(
/* translators: %s: File name (wp-config.php, .htaccess or web.config). */
__( 'Network configuration rules for %s' ),
'<code>wp-config.php</code>'
);
?>
</label></p>
<textarea id="network-wpconfig-rules" class="code" readonly="readonly" cols="100" rows="7" aria-describedby="network-wpconfig-rules-description">
define( 'MULTISITE', true );
define( 'SUBDOMAIN_INSTALL', <?php echo $subdomain_install ? 'true' : 'false'; ?> );
define( 'DOMAIN_CURRENT_SITE', '<?php echo $hostname; ?>' );
define( 'PATH_CURRENT_SITE', '<?php echo $base; ?>' );
define( 'SITE_ID_CURRENT_SITE', 1 );
define( 'BLOG_ID_CURRENT_SITE', 1 );
</textarea>
<?php
$keys_salts = array(
'AUTH_KEY' => '',
'SECURE_AUTH_KEY' => '',
'LOGGED_IN_KEY' => '',
'NONCE_KEY' => '',
'AUTH_SALT' => '',
'SECURE_AUTH_SALT' => '',
'LOGGED_IN_SALT' => '',
'NONCE_SALT' => '',
);
foreach ( $keys_salts as $c => $v ) {
if ( defined( $c ) ) {
unset( $keys_salts[ $c ] );
}
}
if ( ! empty( $keys_salts ) ) {
$keys_salts_str = '';
$from_api = wp_remote_get( 'https://api.wordpress.org/secret-key/1.1/salt/' );
if ( is_wp_error( $from_api ) ) {
foreach ( $keys_salts as $c => $v ) {
$keys_salts_str .= "\ndefine( '$c', '" . wp_generate_password( 64, true, true ) . "' );";
}
} else {
$from_api = explode( "\n", wp_remote_retrieve_body( $from_api ) );
foreach ( $keys_salts as $c => $v ) {
$keys_salts_str .= "\ndefine( '$c', '" . substr( array_shift( $from_api ), 28, 64 ) . "' );";
}
}
$num_keys_salts = count( $keys_salts );
?>
<p id="network-wpconfig-authentication-description">
<?php
if ( 1 === $num_keys_salts ) {
printf(
/* translators: %s: wp-config.php */
__( 'This unique authentication key is also missing from your %s file.' ),
'<code>wp-config.php</code>'
);
} else {
printf(
/* translators: %s: wp-config.php */
__( 'These unique authentication keys are also missing from your %s file.' ),
'<code>wp-config.php</code>'
);
}
?>
<?php _e( 'To make your installation more secure, you should also add:' ); ?>
</p>
<p class="configuration-rules-label"><label for="network-wpconfig-authentication"><?php _e( 'Network configuration authentication keys' ); ?></label></p>
<textarea id="network-wpconfig-authentication" class="code" readonly="readonly" cols="100" rows="<?php echo $num_keys_salts; ?>" aria-describedby="network-wpconfig-authentication-description"><?php echo esc_textarea( $keys_salts_str ); ?></textarea>
<?php
}
?>
</li>
<?php
if ( iis7_supports_permalinks() ) :
// IIS doesn't support RewriteBase, all your RewriteBase are belong to us.
$iis_subdir_match = ltrim( $base, '/' ) . $subdir_match;
$iis_rewrite_base = ltrim( $base, '/' ) . $rewrite_base;
$iis_subdir_replacement = $subdomain_install ? '' : '{R:1}';
$web_config_file = '<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<rewrite>
<rules>
<rule name="WordPress Rule 1" stopProcessing="true">
<match url="^index\.php$" ignoreCase="false" />
<action type="None" />
</rule>';
if ( is_multisite() && get_site_option( 'ms_files_rewriting' ) ) {
$web_config_file .= '
<rule name="WordPress Rule for Files" stopProcessing="true">
<match url="^' . $iis_subdir_match . 'files/(.+)" ignoreCase="false" />
<action type="Rewrite" url="' . $iis_rewrite_base . WPINC . '/ms-files.php?file={R:1}" appendQueryString="false" />
</rule>';
}
$web_config_file .= '
<rule name="WordPress Rule 2" stopProcessing="true">
<match url="^' . $iis_subdir_match . 'wp-admin$" ignoreCase="false" />
<action type="Redirect" url="' . $iis_subdir_replacement . 'wp-admin/" redirectType="Permanent" />
</rule>
<rule name="WordPress Rule 3" stopProcessing="true">
<match url="^" ignoreCase="false" />
<conditions logicalGrouping="MatchAny">
<add input="{REQUEST_FILENAME}" matchType="IsFile" ignoreCase="false" />
<add input="{REQUEST_FILENAME}" matchType="IsDirectory" ignoreCase="false" />
</conditions>
<action type="None" />
</rule>
<rule name="WordPress Rule 4" stopProcessing="true">
<match url="^' . $iis_subdir_match . '(wp-(content|admin|includes).*)" ignoreCase="false" />
<action type="Rewrite" url="' . $iis_rewrite_base . '{R:1}" />
</rule>
<rule name="WordPress Rule 5" stopProcessing="true">
<match url="^' . $iis_subdir_match . '([_0-9a-zA-Z-]+/)?(.*\.php)$" ignoreCase="false" />
<action type="Rewrite" url="' . $iis_rewrite_base . '{R:2}" />
</rule>
<rule name="WordPress Rule 6" stopProcessing="true">
<match url="." ignoreCase="false" />
<action type="Rewrite" url="index.php" />
</rule>
</rules>
</rewrite>
</system.webServer>
</configuration>
';
echo '<li><p id="network-webconfig-rules-description">';
printf(
/* translators: 1: File name (.htaccess or web.config), 2: File path. */
__( 'Add the following to your %1$s file in %2$s, <strong>replacing</strong> other WordPress rules:' ),
'<code>web.config</code>',
'<code>' . $home_path . '</code>'
);
echo '</p>';
if ( ! $subdomain_install && WP_CONTENT_DIR !== ABSPATH . 'wp-content' ) {
echo '<p><strong>' . __( 'Warning:' ) . ' ' . __( 'Subdirectory networks may not be fully compatible with custom wp-content directories.' ) . '</strong></p>';
}
?>
<p class="configuration-rules-label"><label for="network-webconfig-rules">
<?php
printf(
/* translators: %s: File name (wp-config.php, .htaccess or web.config). */
__( 'Network configuration rules for %s' ),
'<code>web.config</code>'
);
?>
</label></p>
<textarea id="network-webconfig-rules" class="code" readonly="readonly" cols="100" rows="20" aria-describedby="network-webconfig-rules-description"><?php echo esc_textarea( $web_config_file ); ?></textarea>
</li>
</ol>
<?php
elseif ( $is_nginx ) : // End iis7_supports_permalinks(). Link to Nginx documentation instead:
echo '<li><p>';
printf(
/* translators: %s: Documentation URL. */
__( 'It seems your network is running with Nginx web server. <a href="%s">Learn more about further configuration</a>.' ),
__( 'https://wordpress.org/documentation/article/nginx/' )
);
echo '</p></li>';
else : // End $is_nginx. Construct an .htaccess file instead:
$ms_files_rewriting = '';
if ( is_multisite() && get_site_option( 'ms_files_rewriting' ) ) {
$ms_files_rewriting = "\n# uploaded files\nRewriteRule ^";
$ms_files_rewriting .= $subdir_match . "files/(.+) {$rewrite_base}" . WPINC . "/ms-files.php?file={$subdir_replacement_12} [L]" . "\n";
}
$htaccess_file = <<<EOF
RewriteEngine On
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
RewriteBase {$base}
RewriteRule ^index\.php$ - [L]
{$ms_files_rewriting}
# add a trailing slash to /wp-admin
RewriteRule ^{$subdir_match}wp-admin$ {$subdir_replacement_01}wp-admin/ [R=301,L]
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]
RewriteRule ^{$subdir_match}(wp-(content|admin|includes).*) {$rewrite_base}{$subdir_replacement_12} [L]
RewriteRule ^{$subdir_match}(.*\.php)$ {$rewrite_base}$subdir_replacement_12 [L]
RewriteRule . index.php [L]
EOF;
echo '<li><p id="network-htaccess-rules-description">';
printf(
/* translators: 1: File name (.htaccess or web.config), 2: File path. */
__( 'Add the following to your %1$s file in %2$s, <strong>replacing</strong> other WordPress rules:' ),
'<code>.htaccess</code>',
'<code>' . $home_path . '</code>'
);
echo '</p>';
if ( ! $subdomain_install && WP_CONTENT_DIR !== ABSPATH . 'wp-content' ) {
echo '<p><strong>' . __( 'Warning:' ) . ' ' . __( 'Subdirectory networks may not be fully compatible with custom wp-content directories.' ) . '</strong></p>';
}
?>
<p class="configuration-rules-label"><label for="network-htaccess-rules">
<?php
printf(
/* translators: %s: File name (wp-config.php, .htaccess or web.config). */
__( 'Network configuration rules for %s' ),
'<code>.htaccess</code>'
);
?>
</label></p>
<textarea id="network-htaccess-rules" class="code" readonly="readonly" cols="100" rows="<?php echo substr_count( $htaccess_file, "\n" ) + 1; ?>" aria-describedby="network-htaccess-rules-description"><?php echo esc_textarea( $htaccess_file ); ?></textarea>
</li>
</ol>
<?php
endif; // End IIS/Nginx/Apache code branches.
if ( ! is_multisite() ) {
?>
<p><?php _e( 'Once you complete these steps, your network is enabled and configured. You will have to log in again.' ); ?> <a href="<?php echo esc_url( wp_login_url() ); ?>"><?php _e( 'Log In' ); ?></a></p>
<?php
}
}

113
wp-admin/includes/noop.php Normal file
View File

@ -0,0 +1,113 @@
<?php
/**
* Noop functions for load-scripts.php and load-styles.php.
*
* @package WordPress
* @subpackage Administration
* @since 4.4.0
*/
/**
* @ignore
*/
function __() {}
/**
* @ignore
*/
function _x() {}
/**
* @ignore
*/
function add_filter() {}
/**
* @ignore
*/
function has_filter() {
return false;
}
/**
* @ignore
*/
function esc_attr() {}
/**
* @ignore
*/
function apply_filters() {}
/**
* @ignore
*/
function get_option() {}
/**
* @ignore
*/
function is_lighttpd_before_150() {}
/**
* @ignore
*/
function add_action() {}
/**
* @ignore
*/
function did_action() {}
/**
* @ignore
*/
function do_action_ref_array() {}
/**
* @ignore
*/
function get_bloginfo() {}
/**
* @ignore
*/
function is_admin() {
return true;
}
/**
* @ignore
*/
function site_url() {}
/**
* @ignore
*/
function admin_url() {}
/**
* @ignore
*/
function home_url() {}
/**
* @ignore
*/
function includes_url() {}
/**
* @ignore
*/
function wp_guess_url() {}
function get_file( $path ) {
$path = realpath( $path );
if ( ! $path || ! @is_file( $path ) ) {
return '';
}
return @file_get_contents( $path );
}

View File

@ -0,0 +1,138 @@
<?php
/**
* WordPress Options Administration API.
*
* @package WordPress
* @subpackage Administration
* @since 4.4.0
*/
/**
* Output JavaScript to toggle display of additional settings if avatars are disabled.
*
* @since 4.2.0
*/
function options_discussion_add_js() {
?>
<script>
(function($){
var parent = $( '#show_avatars' ),
children = $( '.avatar-settings' );
parent.on( 'change', function(){
children.toggleClass( 'hide-if-js', ! this.checked );
});
})(jQuery);
</script>
<?php
}
/**
* Display JavaScript on the page.
*
* @since 3.5.0
*/
function options_general_add_js() {
?>
<script type="text/javascript">
jQuery( function($) {
var $siteName = $( '#wp-admin-bar-site-name' ).children( 'a' ).first(),
$siteIconPreview = $('#site-icon-preview-site-title'),
homeURL = ( <?php echo wp_json_encode( get_home_url() ); ?> || '' ).replace( /^(https?:\/\/)?(www\.)?/, '' );
$( '#blogname' ).on( 'input', function() {
var title = $.trim( $( this ).val() ) || homeURL;
// Truncate to 40 characters.
if ( 40 < title.length ) {
title = title.substring( 0, 40 ) + '\u2026';
}
$siteName.text( title );
$siteIconPreview.text( title );
});
$( 'input[name="date_format"]' ).on( 'click', function() {
if ( 'date_format_custom_radio' !== $(this).attr( 'id' ) )
$( 'input[name="date_format_custom"]' ).val( $( this ).val() ).closest( 'fieldset' ).find( '.example' ).text( $( this ).parent( 'label' ).children( '.format-i18n' ).text() );
});
$( 'input[name="date_format_custom"]' ).on( 'click input', function() {
$( '#date_format_custom_radio' ).prop( 'checked', true );
});
$( 'input[name="time_format"]' ).on( 'click', function() {
if ( 'time_format_custom_radio' !== $(this).attr( 'id' ) )
$( 'input[name="time_format_custom"]' ).val( $( this ).val() ).closest( 'fieldset' ).find( '.example' ).text( $( this ).parent( 'label' ).children( '.format-i18n' ).text() );
});
$( 'input[name="time_format_custom"]' ).on( 'click input', function() {
$( '#time_format_custom_radio' ).prop( 'checked', true );
});
$( 'input[name="date_format_custom"], input[name="time_format_custom"]' ).on( 'input', function() {
var format = $( this ),
fieldset = format.closest( 'fieldset' ),
example = fieldset.find( '.example' ),
spinner = fieldset.find( '.spinner' );
// Debounce the event callback while users are typing.
clearTimeout( $.data( this, 'timer' ) );
$( this ).data( 'timer', setTimeout( function() {
// If custom date is not empty.
if ( format.val() ) {
spinner.addClass( 'is-active' );
$.post( ajaxurl, {
action: 'date_format_custom' === format.attr( 'name' ) ? 'date_format' : 'time_format',
date : format.val()
}, function( d ) { spinner.removeClass( 'is-active' ); example.text( d ); } );
}
}, 500 ) );
} );
var languageSelect = $( '#WPLANG' );
$( 'form' ).on( 'submit', function() {
/*
* Don't show a spinner for English and installed languages,
* as there is nothing to download.
*/
if ( ! languageSelect.find( 'option:selected' ).data( 'installed' ) ) {
$( '#submit', this ).after( '<span class="spinner language-install-spinner is-active" />' );
}
});
} );
</script>
<?php
}
/**
* Display JavaScript on the page.
*
* @since 3.5.0
*/
function options_reading_add_js() {
?>
<script type="text/javascript">
jQuery( function($) {
var section = $('#front-static-pages'),
staticPage = section.find('input:radio[value="page"]'),
selects = section.find('select'),
check_disabled = function(){
selects.prop( 'disabled', ! staticPage.prop('checked') );
};
check_disabled();
section.find( 'input:radio' ).on( 'change', check_disabled );
} );
</script>
<?php
}
/**
* Render the site charset setting.
*
* @since 3.5.0
*/
function options_reading_blog_charset() {
echo '<input name="blog_charset" type="text" id="blog_charset" value="' . esc_attr( get_option( 'blog_charset' ) ) . '" class="regular-text" />';
echo '<p class="description">' . __( 'The <a href="https://wordpress.org/documentation/article/wordpress-glossary/#character-set">character encoding</a> of your site (UTF-8 is recommended)' ) . '</p>';
}

File diff suppressed because it is too large Load Diff

2673
wp-admin/includes/plugin.php Normal file

File diff suppressed because it is too large Load Diff

2651
wp-admin/includes/post.php Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,968 @@
<?php
/**
* WordPress Administration Privacy Tools API.
*
* @package WordPress
* @subpackage Administration
*/
/**
* Resend an existing request and return the result.
*
* @since 4.9.6
* @access private
*
* @param int $request_id Request ID.
* @return true|WP_Error Returns true if sending the email was successful, or a WP_Error object.
*/
function _wp_privacy_resend_request( $request_id ) {
$request_id = absint( $request_id );
$request = get_post( $request_id );
if ( ! $request || 'user_request' !== $request->post_type ) {
return new WP_Error( 'privacy_request_error', __( 'Invalid personal data request.' ) );
}
$result = wp_send_user_request( $request_id );
if ( is_wp_error( $result ) ) {
return $result;
} elseif ( ! $result ) {
return new WP_Error( 'privacy_request_error', __( 'Unable to initiate confirmation for personal data request.' ) );
}
return true;
}
/**
* Marks a request as completed by the admin and logs the current timestamp.
*
* @since 4.9.6
* @access private
*
* @param int $request_id Request ID.
* @return int|WP_Error Request ID on success, or a WP_Error on failure.
*/
function _wp_privacy_completed_request( $request_id ) {
// Get the request.
$request_id = absint( $request_id );
$request = wp_get_user_request( $request_id );
if ( ! $request ) {
return new WP_Error( 'privacy_request_error', __( 'Invalid personal data request.' ) );
}
update_post_meta( $request_id, '_wp_user_request_completed_timestamp', time() );
$result = wp_update_post(
array(
'ID' => $request_id,
'post_status' => 'request-completed',
)
);
return $result;
}
/**
* Handle list table actions.
*
* @since 4.9.6
* @access private
*/
function _wp_personal_data_handle_actions() {
if ( isset( $_POST['privacy_action_email_retry'] ) ) {
check_admin_referer( 'bulk-privacy_requests' );
$request_id = absint( current( array_keys( (array) wp_unslash( $_POST['privacy_action_email_retry'] ) ) ) );
$result = _wp_privacy_resend_request( $request_id );
if ( is_wp_error( $result ) ) {
add_settings_error(
'privacy_action_email_retry',
'privacy_action_email_retry',
$result->get_error_message(),
'error'
);
} else {
add_settings_error(
'privacy_action_email_retry',
'privacy_action_email_retry',
__( 'Confirmation request sent again successfully.' ),
'success'
);
}
} elseif ( isset( $_POST['action'] ) ) {
$action = ! empty( $_POST['action'] ) ? sanitize_key( wp_unslash( $_POST['action'] ) ) : '';
switch ( $action ) {
case 'add_export_personal_data_request':
case 'add_remove_personal_data_request':
check_admin_referer( 'personal-data-request' );
if ( ! isset( $_POST['type_of_action'], $_POST['username_or_email_for_privacy_request'] ) ) {
add_settings_error(
'action_type',
'action_type',
__( 'Invalid personal data action.' ),
'error'
);
}
$action_type = sanitize_text_field( wp_unslash( $_POST['type_of_action'] ) );
$username_or_email_address = sanitize_text_field( wp_unslash( $_POST['username_or_email_for_privacy_request'] ) );
$email_address = '';
$status = 'pending';
if ( ! isset( $_POST['send_confirmation_email'] ) ) {
$status = 'confirmed';
}
if ( ! in_array( $action_type, _wp_privacy_action_request_types(), true ) ) {
add_settings_error(
'action_type',
'action_type',
__( 'Invalid personal data action.' ),
'error'
);
}
if ( ! is_email( $username_or_email_address ) ) {
$user = get_user_by( 'login', $username_or_email_address );
if ( ! $user instanceof WP_User ) {
add_settings_error(
'username_or_email_for_privacy_request',
'username_or_email_for_privacy_request',
__( 'Unable to add this request. A valid email address or username must be supplied.' ),
'error'
);
} else {
$email_address = $user->user_email;
}
} else {
$email_address = $username_or_email_address;
}
if ( empty( $email_address ) ) {
break;
}
$request_id = wp_create_user_request( $email_address, $action_type, array(), $status );
$message = '';
if ( is_wp_error( $request_id ) ) {
$message = $request_id->get_error_message();
} elseif ( ! $request_id ) {
$message = __( 'Unable to initiate confirmation request.' );
}
if ( $message ) {
add_settings_error(
'username_or_email_for_privacy_request',
'username_or_email_for_privacy_request',
$message,
'error'
);
break;
}
if ( 'pending' === $status ) {
wp_send_user_request( $request_id );
$message = __( 'Confirmation request initiated successfully.' );
} elseif ( 'confirmed' === $status ) {
$message = __( 'Request added successfully.' );
}
if ( $message ) {
add_settings_error(
'username_or_email_for_privacy_request',
'username_or_email_for_privacy_request',
$message,
'success'
);
break;
}
}
}
}
/**
* Cleans up failed and expired requests before displaying the list table.
*
* @since 4.9.6
* @access private
*/
function _wp_personal_data_cleanup_requests() {
/** This filter is documented in wp-includes/user.php */
$expires = (int) apply_filters( 'user_request_key_expiration', DAY_IN_SECONDS );
$requests_query = new WP_Query(
array(
'post_type' => 'user_request',
'posts_per_page' => -1,
'post_status' => 'request-pending',
'fields' => 'ids',
'date_query' => array(
array(
'column' => 'post_modified_gmt',
'before' => $expires . ' seconds ago',
),
),
)
);
$request_ids = $requests_query->posts;
foreach ( $request_ids as $request_id ) {
wp_update_post(
array(
'ID' => $request_id,
'post_status' => 'request-failed',
'post_password' => '',
)
);
}
}
/**
* Generate a single group for the personal data export report.
*
* @since 4.9.6
* @since 5.4.0 Added the `$group_id` and `$groups_count` parameters.
*
* @param array $group_data {
* The group data to render.
*
* @type string $group_label The user-facing heading for the group, e.g. 'Comments'.
* @type array $items {
* An array of group items.
*
* @type array $group_item_data {
* An array of name-value pairs for the item.
*
* @type string $name The user-facing name of an item name-value pair, e.g. 'IP Address'.
* @type string $value The user-facing value of an item data pair, e.g. '50.60.70.0'.
* }
* }
* }
* @param string $group_id The group identifier.
* @param int $groups_count The number of all groups
* @return string The HTML for this group and its items.
*/
function wp_privacy_generate_personal_data_export_group_html( $group_data, $group_id = '', $groups_count = 1 ) {
$group_id_attr = sanitize_title_with_dashes( $group_data['group_label'] . '-' . $group_id );
$group_html = '<h2 id="' . esc_attr( $group_id_attr ) . '">';
$group_html .= esc_html( $group_data['group_label'] );
$items_count = count( (array) $group_data['items'] );
if ( $items_count > 1 ) {
$group_html .= sprintf( ' <span class="count">(%d)</span>', $items_count );
}
$group_html .= '</h2>';
if ( ! empty( $group_data['group_description'] ) ) {
$group_html .= '<p>' . esc_html( $group_data['group_description'] ) . '</p>';
}
$group_html .= '<div>';
foreach ( (array) $group_data['items'] as $group_item_id => $group_item_data ) {
$group_html .= '<table>';
$group_html .= '<tbody>';
foreach ( (array) $group_item_data as $group_item_datum ) {
$value = $group_item_datum['value'];
// If it looks like a link, make it a link.
if ( ! str_contains( $value, ' ' ) && ( str_starts_with( $value, 'http://' ) || str_starts_with( $value, 'https://' ) ) ) {
$value = '<a href="' . esc_url( $value ) . '">' . esc_html( $value ) . '</a>';
}
$group_html .= '<tr>';
$group_html .= '<th>' . esc_html( $group_item_datum['name'] ) . '</th>';
$group_html .= '<td>' . wp_kses( $value, 'personal_data_export' ) . '</td>';
$group_html .= '</tr>';
}
$group_html .= '</tbody>';
$group_html .= '</table>';
}
if ( $groups_count > 1 ) {
$group_html .= '<div class="return-to-top">';
$group_html .= '<a href="#top"><span aria-hidden="true">&uarr; </span> ' . esc_html__( 'Go to top' ) . '</a>';
$group_html .= '</div>';
}
$group_html .= '</div>';
return $group_html;
}
/**
* Generate the personal data export file.
*
* @since 4.9.6
*
* @param int $request_id The export request ID.
*/
function wp_privacy_generate_personal_data_export_file( $request_id ) {
if ( ! class_exists( 'ZipArchive' ) ) {
wp_send_json_error( __( 'Unable to generate personal data export file. ZipArchive not available.' ) );
}
// Get the request.
$request = wp_get_user_request( $request_id );
if ( ! $request || 'export_personal_data' !== $request->action_name ) {
wp_send_json_error( __( 'Invalid request ID when generating personal data export file.' ) );
}
$email_address = $request->email;
if ( ! is_email( $email_address ) ) {
wp_send_json_error( __( 'Invalid email address when generating personal data export file.' ) );
}
// Create the exports folder if needed.
$exports_dir = wp_privacy_exports_dir();
$exports_url = wp_privacy_exports_url();
if ( ! wp_mkdir_p( $exports_dir ) ) {
wp_send_json_error( __( 'Unable to create personal data export folder.' ) );
}
// Protect export folder from browsing.
$index_pathname = $exports_dir . 'index.php';
if ( ! file_exists( $index_pathname ) ) {
$file = fopen( $index_pathname, 'w' );
if ( false === $file ) {
wp_send_json_error( __( 'Unable to protect personal data export folder from browsing.' ) );
}
fwrite( $file, "<?php\n// Silence is golden.\n" );
fclose( $file );
}
$obscura = wp_generate_password( 32, false, false );
$file_basename = 'wp-personal-data-file-' . $obscura;
$html_report_filename = wp_unique_filename( $exports_dir, $file_basename . '.html' );
$html_report_pathname = wp_normalize_path( $exports_dir . $html_report_filename );
$json_report_filename = $file_basename . '.json';
$json_report_pathname = wp_normalize_path( $exports_dir . $json_report_filename );
/*
* Gather general data needed.
*/
// Title.
$title = sprintf(
/* translators: %s: User's email address. */
__( 'Personal Data Export for %s' ),
$email_address
);
// First, build an "About" group on the fly for this report.
$about_group = array(
/* translators: Header for the About section in a personal data export. */
'group_label' => _x( 'About', 'personal data group label' ),
/* translators: Description for the About section in a personal data export. */
'group_description' => _x( 'Overview of export report.', 'personal data group description' ),
'items' => array(
'about-1' => array(
array(
'name' => _x( 'Report generated for', 'email address' ),
'value' => $email_address,
),
array(
'name' => _x( 'For site', 'website name' ),
'value' => get_bloginfo( 'name' ),
),
array(
'name' => _x( 'At URL', 'website URL' ),
'value' => get_bloginfo( 'url' ),
),
array(
'name' => _x( 'On', 'date/time' ),
'value' => current_time( 'mysql' ),
),
),
),
);
// And now, all the Groups.
$groups = get_post_meta( $request_id, '_export_data_grouped', true );
if ( is_array( $groups ) ) {
// Merge in the special "About" group.
$groups = array_merge( array( 'about' => $about_group ), $groups );
$groups_count = count( $groups );
} else {
if ( false !== $groups ) {
_doing_it_wrong(
__FUNCTION__,
/* translators: %s: Post meta key. */
sprintf( __( 'The %s post meta must be an array.' ), '<code>_export_data_grouped</code>' ),
'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, "<!DOCTYPE html>\n" );
fwrite( $file, "<html>\n" );
fwrite( $file, "<head>\n" );
fwrite( $file, "<meta http-equiv='Content-Type' content='text/html; charset=UTF-8' />\n" );
fwrite( $file, "<style type='text/css'>" );
fwrite( $file, 'body { color: black; font-family: Arial, sans-serif; font-size: 11pt; margin: 15px auto; width: 860px; }' );
fwrite( $file, 'table { background: #f0f0f0; border: 1px solid #ddd; margin-bottom: 20px; width: 100%; }' );
fwrite( $file, 'th { padding: 5px; text-align: left; width: 20%; }' );
fwrite( $file, 'td { padding: 5px; }' );
fwrite( $file, 'tr:nth-child(odd) { background-color: #fafafa; }' );
fwrite( $file, '.return-to-top { text-align: right; }' );
fwrite( $file, '</style>' );
fwrite( $file, '<title>' );
fwrite( $file, esc_html( $title ) );
fwrite( $file, '</title>' );
fwrite( $file, "</head>\n" );
fwrite( $file, "<body>\n" );
fwrite( $file, '<h1 id="top">' . esc_html__( 'Personal Data Export' ) . '</h1>' );
// Create TOC.
if ( $groups_count > 1 ) {
fwrite( $file, '<div id="table_of_contents">' );
fwrite( $file, '<h2>' . esc_html__( 'Table of Contents' ) . '</h2>' );
fwrite( $file, '<ul>' );
foreach ( (array) $groups as $group_id => $group_data ) {
$group_label = esc_html( $group_data['group_label'] );
$group_id_attr = sanitize_title_with_dashes( $group_data['group_label'] . '-' . $group_id );
$group_items_count = count( (array) $group_data['items'] );
if ( $group_items_count > 1 ) {
$group_label .= sprintf( ' <span class="count">(%d)</span>', $group_items_count );
}
fwrite( $file, '<li>' );
fwrite( $file, '<a href="#' . esc_attr( $group_id_attr ) . '">' . $group_label . '</a>' );
fwrite( $file, '</li>' );
}
fwrite( $file, '</ul>' );
fwrite( $file, '</div>' );
}
// Now, iterate over every group in $groups and have the formatter render it in HTML.
foreach ( (array) $groups as $group_id => $group_data ) {
fwrite( $file, wp_privacy_generate_personal_data_export_group_html( $group_data, $group_id, $groups_count ) );
}
fwrite( $file, "</body>\n" );
fwrite( $file, "</html>\n" );
fclose( $file );
/*
* Now, generate the ZIP.
*
* If an archive has already been generated, then remove it and reuse the filename,
* to avoid breaking any URLs that may have been previously sent via email.
*/
$error = false;
// This meta value is used from version 5.5.
$archive_filename = get_post_meta( $request_id, '_export_file_name', true );
// This one stored an absolute path and is used for backward compatibility.
$archive_pathname = get_post_meta( $request_id, '_export_file_path', true );
// If a filename meta exists, use it.
if ( ! empty( $archive_filename ) ) {
$archive_pathname = $exports_dir . $archive_filename;
} elseif ( ! empty( $archive_pathname ) ) {
// If a full path meta exists, use it and create the new meta value.
$archive_filename = basename( $archive_pathname );
update_post_meta( $request_id, '_export_file_name', $archive_filename );
// Remove the back-compat meta values.
delete_post_meta( $request_id, '_export_file_url' );
delete_post_meta( $request_id, '_export_file_path' );
} else {
// If there's no filename or full path stored, create a new file.
$archive_filename = $file_basename . '.zip';
$archive_pathname = $exports_dir . $archive_filename;
update_post_meta( $request_id, '_export_file_name', $archive_filename );
}
$archive_url = $exports_url . $archive_filename;
if ( ! empty( $archive_pathname ) && file_exists( $archive_pathname ) ) {
wp_delete_file( $archive_pathname );
}
$zip = new ZipArchive();
if ( true === $zip->open( $archive_pathname, ZipArchive::CREATE ) ) {
if ( ! $zip->addFile( $json_report_pathname, 'export.json' ) ) {
$error = __( 'Unable to archive the personal data export file (JSON format).' );
}
if ( ! $zip->addFile( $html_report_pathname, 'index.html' ) ) {
$error = __( 'Unable to archive the personal data export file (HTML format).' );
}
$zip->close();
if ( ! $error ) {
/**
* Fires right after all personal data has been written to the export file.
*
* @since 4.9.6
* @since 5.4.0 Added the `$json_report_pathname` parameter.
*
* @param string $archive_pathname The full path to the export file on the filesystem.
* @param string $archive_url The URL of the archive file.
* @param string $html_report_pathname The full path to the HTML personal data report on the filesystem.
* @param int $request_id The export request ID.
* @param string $json_report_pathname The full path to the JSON personal data report on the filesystem.
*/
do_action( 'wp_privacy_personal_data_export_file_created', $archive_pathname, $archive_url, $html_report_pathname, $request_id, $json_report_pathname );
}
} else {
$error = __( 'Unable to open personal data export file (archive) for writing.' );
}
// Remove the JSON file.
unlink( $json_report_pathname );
// Remove the HTML file.
unlink( $html_report_pathname );
if ( $error ) {
wp_send_json_error( $error );
}
}
/**
* Send an email to the user with a link to the personal data export file
*
* @since 4.9.6
*
* @param int $request_id The request ID for this personal data export.
* @return true|WP_Error True on success or `WP_Error` on failure.
*/
function wp_privacy_send_personal_data_export_email( $request_id ) {
// Get the request.
$request = wp_get_user_request( $request_id );
if ( ! $request || 'export_personal_data' !== $request->action_name ) {
return new WP_Error( 'invalid_request', __( 'Invalid request ID when sending personal data export email.' ) );
}
// Localize message content for user; fallback to site default for visitors.
if ( ! empty( $request->user_id ) ) {
$switched_locale = switch_to_user_locale( $request->user_id );
} else {
$switched_locale = switch_to_locale( get_locale() );
}
/** This filter is documented in wp-includes/functions.php */
$expiration = apply_filters( 'wp_privacy_export_expiration', 3 * DAY_IN_SECONDS );
$expiration_date = date_i18n( get_option( 'date_format' ), time() + $expiration );
$exports_url = wp_privacy_exports_url();
$export_file_name = get_post_meta( $request_id, '_export_file_name', true );
$export_file_url = $exports_url . $export_file_name;
$site_name = wp_specialchars_decode( get_option( 'blogname' ), ENT_QUOTES );
$site_url = home_url();
/**
* Filters the recipient of the personal data export email notification.
* Should be used with great caution to avoid sending the data export link to wrong emails.
*
* @since 5.3.0
*
* @param string $request_email The email address of the notification recipient.
* @param WP_User_Request $request The request that is initiating the notification.
*/
$request_email = apply_filters( 'wp_privacy_personal_data_email_to', $request->email, $request );
$email_data = array(
'request' => $request,
'expiration' => $expiration,
'expiration_date' => $expiration_date,
'message_recipient' => $request_email,
'export_file_url' => $export_file_url,
'sitename' => $site_name,
'siteurl' => $site_url,
);
/* translators: Personal data export notification email subject. %s: Site title. */
$subject = sprintf( __( '[%s] Personal Data Export' ), $site_name );
/**
* Filters the subject of the email sent when an export request is completed.
*
* @since 5.3.0
*
* @param string $subject The email subject.
* @param string $sitename The name of the site.
* @param array $email_data {
* Data relating to the account action email.
*
* @type WP_User_Request $request User request object.
* @type int $expiration The time in seconds until the export file expires.
* @type string $expiration_date The localized date and time when the export file expires.
* @type string $message_recipient The address that the email will be sent to. Defaults
* to the value of `$request->email`, but can be changed
* by the `wp_privacy_personal_data_email_to` filter.
* @type string $export_file_url The export file URL.
* @type string $sitename The site name sending the mail.
* @type string $siteurl The site URL sending the mail.
* }
*/
$subject = apply_filters( 'wp_privacy_personal_data_email_subject', $subject, $site_name, $email_data );
/* translators: Do not translate EXPIRATION, LINK, SITENAME, SITEURL: those are placeholders. */
$email_text = __(
'Howdy,
Your request for an export of personal data has been completed. You may
download your personal data by clicking on the link below. For privacy
and security, we will automatically delete the file on ###EXPIRATION###,
so please download it before then.
###LINK###
Regards,
All at ###SITENAME###
###SITEURL###'
);
/**
* Filters the text of the email sent with a personal data export file.
*
* The following strings have a special meaning and will get replaced dynamically:
* ###EXPIRATION### The date when the URL will be automatically deleted.
* ###LINK### URL of the personal data export file for the user.
* ###SITENAME### The name of the site.
* ###SITEURL### The URL to the site.
*
* @since 4.9.6
* @since 5.3.0 Introduced the `$email_data` array.
*
* @param string $email_text Text in the email.
* @param int $request_id The request ID for this personal data export.
* @param array $email_data {
* Data relating to the account action email.
*
* @type WP_User_Request $request User request object.
* @type int $expiration The time in seconds until the export file expires.
* @type string $expiration_date The localized date and time when the export file expires.
* @type string $message_recipient The address that the email will be sent to. Defaults
* to the value of `$request->email`, but can be changed
* by the `wp_privacy_personal_data_email_to` filter.
* @type string $export_file_url The export file URL.
* @type string $sitename The site name sending the mail.
* @type string $siteurl The site URL sending the mail.
*/
$content = apply_filters( 'wp_privacy_personal_data_email_content', $email_text, $request_id, $email_data );
$content = str_replace( '###EXPIRATION###', $expiration_date, $content );
$content = str_replace( '###LINK###', sanitize_url( $export_file_url ), $content );
$content = str_replace( '###EMAIL###', $request_email, $content );
$content = str_replace( '###SITENAME###', $site_name, $content );
$content = str_replace( '###SITEURL###', sanitize_url( $site_url ), $content );
$headers = '';
/**
* Filters the headers of the email sent with a personal data export file.
*
* @since 5.4.0
*
* @param string|array $headers The email headers.
* @param string $subject The email subject.
* @param string $content The email content.
* @param int $request_id The request ID.
* @param array $email_data {
* Data relating to the account action email.
*
* @type WP_User_Request $request User request object.
* @type int $expiration The time in seconds until the export file expires.
* @type string $expiration_date The localized date and time when the export file expires.
* @type string $message_recipient The address that the email will be sent to. Defaults
* to the value of `$request->email`, but can be changed
* by the `wp_privacy_personal_data_email_to` filter.
* @type string $export_file_url The export file URL.
* @type string $sitename The site name sending the mail.
* @type string $siteurl The site URL sending the mail.
* }
*/
$headers = apply_filters( 'wp_privacy_personal_data_email_headers', $headers, $subject, $content, $request_id, $email_data );
$mail_success = wp_mail( $request_email, $subject, $content, $headers );
if ( $switched_locale ) {
restore_previous_locale();
}
if ( ! $mail_success ) {
return new WP_Error( 'privacy_email_error', __( 'Unable to send personal data export email.' ) );
}
return true;
}
/**
* Intercept personal data exporter page Ajax responses in order to assemble the personal data export file.
*
* @since 4.9.6
*
* @see 'wp_privacy_personal_data_export_page'
*
* @param array $response The response from the personal data exporter for the given page.
* @param int $exporter_index The index of the personal data exporter. Begins at 1.
* @param string $email_address The email address of the user whose personal data this is.
* @param int $page The page of personal data for this exporter. Begins at 1.
* @param int $request_id The request ID for this personal data export.
* @param bool $send_as_email Whether the final results of the export should be emailed to the user.
* @param string $exporter_key The slug (key) of the exporter.
* @return array The filtered response.
*/
function wp_privacy_process_personal_data_export_page( $response, $exporter_index, $email_address, $page, $request_id, $send_as_email, $exporter_key ) {
/* Do some simple checks on the shape of the response from the exporter.
* If the exporter response is malformed, don't attempt to consume it - let it
* pass through to generate a warning to the user by default Ajax processing.
*/
if ( ! is_array( $response ) ) {
return $response;
}
if ( ! array_key_exists( 'done', $response ) ) {
return $response;
}
if ( ! array_key_exists( 'data', $response ) ) {
return $response;
}
if ( ! is_array( $response['data'] ) ) {
return $response;
}
// Get the request.
$request = wp_get_user_request( $request_id );
if ( ! $request || 'export_personal_data' !== $request->action_name ) {
wp_send_json_error( __( 'Invalid request ID when merging personal data to export.' ) );
}
$export_data = array();
// First exporter, first page? Reset the report data accumulation array.
if ( 1 === $exporter_index && 1 === $page ) {
update_post_meta( $request_id, '_export_data_raw', $export_data );
} else {
$accumulated_data = get_post_meta( $request_id, '_export_data_raw', true );
if ( $accumulated_data ) {
$export_data = $accumulated_data;
}
}
// Now, merge the data from the exporter response into the data we have accumulated already.
$export_data = array_merge( $export_data, $response['data'] );
update_post_meta( $request_id, '_export_data_raw', $export_data );
// If we are not yet on the last page of the last exporter, return now.
/** This filter is documented in wp-admin/includes/ajax-actions.php */
$exporters = apply_filters( 'wp_privacy_personal_data_exporters', array() );
$is_last_exporter = count( $exporters ) === $exporter_index;
$exporter_done = $response['done'];
if ( ! $is_last_exporter || ! $exporter_done ) {
return $response;
}
// Last exporter, last page - let's prepare the export file.
// First we need to re-organize the raw data hierarchically in groups and items.
$groups = array();
foreach ( (array) $export_data as $export_datum ) {
$group_id = $export_datum['group_id'];
$group_label = $export_datum['group_label'];
$group_description = '';
if ( ! empty( $export_datum['group_description'] ) ) {
$group_description = $export_datum['group_description'];
}
if ( ! array_key_exists( $group_id, $groups ) ) {
$groups[ $group_id ] = array(
'group_label' => $group_label,
'group_description' => $group_description,
'items' => array(),
);
}
$item_id = $export_datum['item_id'];
if ( ! array_key_exists( $item_id, $groups[ $group_id ]['items'] ) ) {
$groups[ $group_id ]['items'][ $item_id ] = array();
}
$old_item_data = $groups[ $group_id ]['items'][ $item_id ];
$merged_item_data = array_merge( $export_datum['data'], $old_item_data );
$groups[ $group_id ]['items'][ $item_id ] = $merged_item_data;
}
// Then save the grouped data into the request.
delete_post_meta( $request_id, '_export_data_raw' );
update_post_meta( $request_id, '_export_data_grouped', $groups );
/**
* Generate the export file from the collected, grouped personal data.
*
* @since 4.9.6
*
* @param int $request_id The export request ID.
*/
do_action( 'wp_privacy_personal_data_export_file', $request_id );
// Clear the grouped data now that it is no longer needed.
delete_post_meta( $request_id, '_export_data_grouped' );
// If the destination is email, send it now.
if ( $send_as_email ) {
$mail_success = wp_privacy_send_personal_data_export_email( $request_id );
if ( is_wp_error( $mail_success ) ) {
wp_send_json_error( $mail_success->get_error_message() );
}
// Update the request to completed state when the export email is sent.
_wp_privacy_completed_request( $request_id );
} else {
// Modify the response to include the URL of the export file so the browser can fetch it.
$exports_url = wp_privacy_exports_url();
$export_file_name = get_post_meta( $request_id, '_export_file_name', true );
$export_file_url = $exports_url . $export_file_name;
if ( ! empty( $export_file_url ) ) {
$response['url'] = $export_file_url;
}
}
return $response;
}
/**
* Mark erasure requests as completed after processing is finished.
*
* This intercepts the Ajax responses to personal data eraser page requests, and
* monitors the status of a request. Once all of the processing has finished, the
* request is marked as completed.
*
* @since 4.9.6
*
* @see 'wp_privacy_personal_data_erasure_page'
*
* @param array $response The response from the personal data eraser for
* the given page.
* @param int $eraser_index The index of the personal data eraser. Begins
* at 1.
* @param string $email_address The email address of the user whose personal
* data this is.
* @param int $page The page of personal data for this eraser.
* Begins at 1.
* @param int $request_id The request ID for this personal data erasure.
* @return array The filtered response.
*/
function wp_privacy_process_personal_data_erasure_page( $response, $eraser_index, $email_address, $page, $request_id ) {
/*
* If the eraser response is malformed, don't attempt to consume it; let it
* pass through, so that the default Ajax processing will generate a warning
* to the user.
*/
if ( ! is_array( $response ) ) {
return $response;
}
if ( ! array_key_exists( 'done', $response ) ) {
return $response;
}
if ( ! array_key_exists( 'items_removed', $response ) ) {
return $response;
}
if ( ! array_key_exists( 'items_retained', $response ) ) {
return $response;
}
if ( ! array_key_exists( 'messages', $response ) ) {
return $response;
}
// Get the request.
$request = wp_get_user_request( $request_id );
if ( ! $request || 'remove_personal_data' !== $request->action_name ) {
wp_send_json_error( __( 'Invalid request ID when processing personal data to erase.' ) );
}
/** This filter is documented in wp-admin/includes/ajax-actions.php */
$erasers = apply_filters( 'wp_privacy_personal_data_erasers', array() );
$is_last_eraser = count( $erasers ) === $eraser_index;
$eraser_done = $response['done'];
if ( ! $is_last_eraser || ! $eraser_done ) {
return $response;
}
_wp_privacy_completed_request( $request_id );
/**
* Fires immediately after a personal data erasure request has been marked completed.
*
* @since 4.9.6
*
* @param int $request_id The privacy request post ID associated with this request.
*/
do_action( 'wp_privacy_personal_data_erased', $request_id );
return $response;
}

View File

@ -0,0 +1,473 @@
<?php
/**
* WordPress Administration Revisions API
*
* @package WordPress
* @subpackage Administration
* @since 3.6.0
*/
/**
* Get the revision UI diff.
*
* @since 3.6.0
*
* @param WP_Post|int $post The post object or post ID.
* @param int $compare_from The revision ID to compare from.
* @param int $compare_to The revision ID to come to.
* @return array|false Associative array of a post's revisioned fields and their diffs.
* Or, false on failure.
*/
function wp_get_revision_ui_diff( $post, $compare_from, $compare_to ) {
$post = get_post( $post );
if ( ! $post ) {
return false;
}
if ( $compare_from ) {
$compare_from = get_post( $compare_from );
if ( ! $compare_from ) {
return false;
}
} else {
// If we're dealing with the first revision...
$compare_from = false;
}
$compare_to = get_post( $compare_to );
if ( ! $compare_to ) {
return false;
}
/*
* If comparing revisions, make sure we are dealing with the right post parent.
* The parent post may be a 'revision' when revisions are disabled and we're looking at autosaves.
*/
if ( $compare_from && $compare_from->post_parent !== $post->ID && $compare_from->ID !== $post->ID ) {
return false;
}
if ( $compare_to->post_parent !== $post->ID && $compare_to->ID !== $post->ID ) {
return false;
}
if ( $compare_from && strtotime( $compare_from->post_date_gmt ) > strtotime( $compare_to->post_date_gmt ) ) {
$temp = $compare_from;
$compare_from = $compare_to;
$compare_to = $temp;
}
// Add default title if title field is empty.
if ( $compare_from && empty( $compare_from->post_title ) ) {
$compare_from->post_title = __( '(no title)' );
}
if ( empty( $compare_to->post_title ) ) {
$compare_to->post_title = __( '(no title)' );
}
$return = array();
foreach ( _wp_post_revision_fields( $post ) as $field => $name ) {
/**
* Contextually filter a post revision field.
*
* The dynamic portion of the hook name, `$field`, corresponds to a name of a
* field of the revision object.
*
* Possible hook names include:
*
* - `_wp_post_revision_field_post_title`
* - `_wp_post_revision_field_post_content`
* - `_wp_post_revision_field_post_excerpt`
*
* @since 3.6.0
*
* @param string $revision_field The current revision field to compare to or from.
* @param string $field The current revision field.
* @param WP_Post $compare_from The revision post object to compare to or from.
* @param string $context The context of whether the current revision is the old
* or the new one. Either 'to' or 'from'.
*/
$content_from = $compare_from ? apply_filters( "_wp_post_revision_field_{$field}", $compare_from->$field, $field, $compare_from, 'from' ) : '';
/** This filter is documented in wp-admin/includes/revision.php */
$content_to = apply_filters( "_wp_post_revision_field_{$field}", $compare_to->$field, $field, $compare_to, 'to' );
$args = array(
'show_split_view' => true,
'title_left' => __( 'Removed' ),
'title_right' => __( 'Added' ),
);
/**
* Filters revisions text diff options.
*
* Filters the options passed to wp_text_diff() when viewing a post revision.
*
* @since 4.1.0
*
* @param array $args {
* Associative array of options to pass to wp_text_diff().
*
* @type bool $show_split_view True for split view (two columns), false for
* un-split view (single column). Default true.
* }
* @param string $field The current revision field.
* @param WP_Post $compare_from The revision post to compare from.
* @param WP_Post $compare_to The revision post to compare to.
*/
$args = apply_filters( 'revision_text_diff_options', $args, $field, $compare_from, $compare_to );
$diff = wp_text_diff( $content_from, $content_to, $args );
if ( ! $diff && 'post_title' === $field ) {
/*
* It's a better user experience to still show the Title, even if it didn't change.
* No, you didn't see this.
*/
$diff = '<table class="diff"><colgroup><col class="content diffsplit left"><col class="content diffsplit middle"><col class="content diffsplit right"></colgroup><tbody><tr>';
// In split screen mode, show the title before/after side by side.
if ( true === $args['show_split_view'] ) {
$diff .= '<td>' . esc_html( $compare_from->post_title ) . '</td><td></td><td>' . esc_html( $compare_to->post_title ) . '</td>';
} else {
$diff .= '<td>' . esc_html( $compare_from->post_title ) . '</td>';
// In single column mode, only show the title once if unchanged.
if ( $compare_from->post_title !== $compare_to->post_title ) {
$diff .= '</tr><tr><td>' . esc_html( $compare_to->post_title ) . '</td>';
}
}
$diff .= '</tr></tbody>';
$diff .= '</table>';
}
if ( $diff ) {
$return[] = array(
'id' => $field,
'name' => $name,
'diff' => $diff,
);
}
}
/**
* Filters the fields displayed in the post revision diff UI.
*
* @since 4.1.0
*
* @param array[] $return Array of revision UI fields. Each item is an array of id, name, and diff.
* @param WP_Post $compare_from The revision post to compare from.
* @param WP_Post $compare_to The revision post to compare to.
*/
return apply_filters( 'wp_get_revision_ui_diff', $return, $compare_from, $compare_to );
}
/**
* Prepare revisions for JavaScript.
*
* @since 3.6.0
*
* @param WP_Post|int $post The post object or post ID.
* @param int $selected_revision_id The selected revision ID.
* @param int $from Optional. The revision ID to compare from.
* @return array An associative array of revision data and related settings.
*/
function wp_prepare_revisions_for_js( $post, $selected_revision_id, $from = null ) {
$post = get_post( $post );
$authors = array();
$now_gmt = time();
$revisions = wp_get_post_revisions(
$post->ID,
array(
'order' => 'ASC',
'check_enabled' => false,
)
);
// If revisions are disabled, we only want autosaves and the current post.
if ( ! wp_revisions_enabled( $post ) ) {
foreach ( $revisions as $revision_id => $revision ) {
if ( ! wp_is_post_autosave( $revision ) ) {
unset( $revisions[ $revision_id ] );
}
}
$revisions = array( $post->ID => $post ) + $revisions;
}
$show_avatars = get_option( 'show_avatars' );
update_post_author_caches( $revisions );
$can_restore = current_user_can( 'edit_post', $post->ID );
$current_id = false;
foreach ( $revisions as $revision ) {
$modified = strtotime( $revision->post_modified );
$modified_gmt = strtotime( $revision->post_modified_gmt . ' +0000' );
if ( $can_restore ) {
$restore_link = str_replace(
'&amp;',
'&',
wp_nonce_url(
add_query_arg(
array(
'revision' => $revision->ID,
'action' => 'restore',
),
admin_url( 'revision.php' )
),
"restore-post_{$revision->ID}"
)
);
}
if ( ! isset( $authors[ $revision->post_author ] ) ) {
$authors[ $revision->post_author ] = array(
'id' => (int) $revision->post_author,
'avatar' => $show_avatars ? get_avatar( $revision->post_author, 32 ) : '',
'name' => get_the_author_meta( 'display_name', $revision->post_author ),
);
}
$autosave = (bool) wp_is_post_autosave( $revision );
$current = ! $autosave && $revision->post_modified_gmt === $post->post_modified_gmt;
if ( $current && ! empty( $current_id ) ) {
// If multiple revisions have the same post_modified_gmt, highest ID is current.
if ( $current_id < $revision->ID ) {
$revisions[ $current_id ]['current'] = false;
$current_id = $revision->ID;
} else {
$current = false;
}
} elseif ( $current ) {
$current_id = $revision->ID;
}
$revisions_data = array(
'id' => $revision->ID,
'title' => get_the_title( $post->ID ),
'author' => $authors[ $revision->post_author ],
'date' => date_i18n( __( 'M j, Y @ H:i' ), $modified ),
'dateShort' => date_i18n( _x( 'j M @ H:i', 'revision date short format' ), $modified ),
/* translators: %s: Human-readable time difference. */
'timeAgo' => sprintf( __( '%s ago' ), human_time_diff( $modified_gmt, $now_gmt ) ),
'autosave' => $autosave,
'current' => $current,
'restoreUrl' => $can_restore ? $restore_link : false,
);
/**
* Filters the array of revisions used on the revisions screen.
*
* @since 4.4.0
*
* @param array $revisions_data {
* The bootstrapped data for the revisions screen.
*
* @type int $id Revision ID.
* @type string $title Title for the revision's parent WP_Post object.
* @type int $author Revision post author ID.
* @type string $date Date the revision was modified.
* @type string $dateShort Short-form version of the date the revision was modified.
* @type string $timeAgo GMT-aware amount of time ago the revision was modified.
* @type bool $autosave Whether the revision is an autosave.
* @type bool $current Whether the revision is both not an autosave and the post
* modified date matches the revision modified date (GMT-aware).
* @type bool|false $restoreUrl URL if the revision can be restored, false otherwise.
* }
* @param WP_Post $revision The revision's WP_Post object.
* @param WP_Post $post The revision's parent WP_Post object.
*/
$revisions[ $revision->ID ] = apply_filters( 'wp_prepare_revision_for_js', $revisions_data, $revision, $post );
}
/*
* If we only have one revision, the initial revision is missing. This happens
* when we have an autosave and the user has clicked 'View the Autosave'.
*/
if ( 1 === count( $revisions ) ) {
$revisions[ $post->ID ] = array(
'id' => $post->ID,
'title' => get_the_title( $post->ID ),
'author' => $authors[ $revision->post_author ],
'date' => date_i18n( __( 'M j, Y @ H:i' ), strtotime( $post->post_modified ) ),
'dateShort' => date_i18n( _x( 'j M @ H:i', 'revision date short format' ), strtotime( $post->post_modified ) ),
/* translators: %s: Human-readable time difference. */
'timeAgo' => sprintf( __( '%s ago' ), human_time_diff( strtotime( $post->post_modified_gmt ), $now_gmt ) ),
'autosave' => false,
'current' => true,
'restoreUrl' => false,
);
$current_id = $post->ID;
}
/*
* If a post has been saved since the latest revision (no revisioned fields
* were changed), we may not have a "current" revision. Mark the latest
* revision as "current".
*/
if ( empty( $current_id ) ) {
if ( $revisions[ $revision->ID ]['autosave'] ) {
$revision = end( $revisions );
while ( $revision['autosave'] ) {
$revision = prev( $revisions );
}
$current_id = $revision['id'];
} else {
$current_id = $revision->ID;
}
$revisions[ $current_id ]['current'] = true;
}
// Now, grab the initial diff.
$compare_two_mode = is_numeric( $from );
if ( ! $compare_two_mode ) {
$found = array_search( $selected_revision_id, array_keys( $revisions ), true );
if ( $found ) {
$from = array_keys( array_slice( $revisions, $found - 1, 1, true ) );
$from = reset( $from );
} else {
$from = 0;
}
}
$from = absint( $from );
$diffs = array(
array(
'id' => $from . ':' . $selected_revision_id,
'fields' => wp_get_revision_ui_diff( $post->ID, $from, $selected_revision_id ),
),
);
return array(
'postId' => $post->ID,
'nonce' => wp_create_nonce( 'revisions-ajax-nonce' ),
'revisionData' => array_values( $revisions ),
'to' => $selected_revision_id,
'from' => $from,
'diffData' => $diffs,
'baseUrl' => parse_url( admin_url( 'revision.php' ), PHP_URL_PATH ),
'compareTwoMode' => absint( $compare_two_mode ), // Apparently booleans are not allowed.
'revisionIds' => array_keys( $revisions ),
);
}
/**
* Print JavaScript templates required for the revisions experience.
*
* @since 4.1.0
*
* @global WP_Post $post Global post object.
*/
function wp_print_revision_templates() {
global $post;
?><script id="tmpl-revisions-frame" type="text/html">
<div class="revisions-control-frame"></div>
<div class="revisions-diff-frame"></div>
</script>
<script id="tmpl-revisions-buttons" type="text/html">
<div class="revisions-previous">
<input class="button" type="button" value="<?php echo esc_attr_x( 'Previous', 'Button label for a previous revision' ); ?>" />
</div>
<div class="revisions-next">
<input class="button" type="button" value="<?php echo esc_attr_x( 'Next', 'Button label for a next revision' ); ?>" />
</div>
</script>
<script id="tmpl-revisions-checkbox" type="text/html">
<div class="revision-toggle-compare-mode">
<label>
<input type="checkbox" class="compare-two-revisions"
<#
if ( 'undefined' !== typeof data && data.model.attributes.compareTwoMode ) {
#> checked="checked"<#
}
#>
/>
<?php esc_html_e( 'Compare any two revisions' ); ?>
</label>
</div>
</script>
<script id="tmpl-revisions-meta" type="text/html">
<# if ( ! _.isUndefined( data.attributes ) ) { #>
<div class="diff-title">
<# if ( 'from' === data.type ) { #>
<strong><?php _ex( 'From:', 'Followed by post revision info' ); ?></strong>
<# } else if ( 'to' === data.type ) { #>
<strong><?php _ex( 'To:', 'Followed by post revision info' ); ?></strong>
<# } #>
<div class="author-card<# if ( data.attributes.autosave ) { #> autosave<# } #>">
{{{ data.attributes.author.avatar }}}
<div class="author-info">
<# if ( data.attributes.autosave ) { #>
<span class="byline">
<?php
printf(
/* translators: %s: User's display name. */
__( 'Autosave by %s' ),
'<span class="author-name">{{ data.attributes.author.name }}</span>'
);
?>
</span>
<# } else if ( data.attributes.current ) { #>
<span class="byline">
<?php
printf(
/* translators: %s: User's display name. */
__( 'Current Revision by %s' ),
'<span class="author-name">{{ data.attributes.author.name }}</span>'
);
?>
</span>
<# } else { #>
<span class="byline">
<?php
printf(
/* translators: %s: User's display name. */
__( 'Revision by %s' ),
'<span class="author-name">{{ data.attributes.author.name }}</span>'
);
?>
</span>
<# } #>
<span class="time-ago">{{ data.attributes.timeAgo }}</span>
<span class="date">({{ data.attributes.dateShort }})</span>
</div>
<# if ( 'to' === data.type && data.attributes.restoreUrl ) { #>
<input <?php if ( wp_check_post_lock( $post->ID ) ) { ?>
disabled="disabled"
<?php } else { ?>
<# if ( data.attributes.current ) { #>
disabled="disabled"
<# } #>
<?php } ?>
<# if ( data.attributes.autosave ) { #>
type="button" class="restore-revision button button-primary" value="<?php esc_attr_e( 'Restore This Autosave' ); ?>" />
<# } else { #>
type="button" class="restore-revision button button-primary" value="<?php esc_attr_e( 'Restore This Revision' ); ?>" />
<# } #>
<# } #>
</div>
<# if ( 'tooltip' === data.type ) { #>
<div class="revisions-tooltip-arrow"><span></span></div>
<# } #>
<# } #>
</script>
<script id="tmpl-revisions-diff" type="text/html">
<div class="loading-indicator"><span class="spinner"></span></div>
<div class="diff-error"><?php _e( 'Sorry, something went wrong. The requested comparison could not be loaded.' ); ?></div>
<div class="diff">
<# _.each( data.fields, function( field ) { #>
<h3>{{ field.name }}</h3>
{{{ field.diff }}}
<# }); #>
</div>
</script>
<?php
}

1383
wp-admin/includes/schema.php Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,244 @@
<?php
/**
* WordPress Administration Screen API.
*
* @package WordPress
* @subpackage Administration
*/
/**
* Get the column headers for a screen
*
* @since 2.7.0
*
* @param string|WP_Screen $screen The screen you want the headers for
* @return string[] The column header labels keyed by column ID.
*/
function get_column_headers( $screen ) {
static $column_headers = array();
if ( is_string( $screen ) ) {
$screen = convert_to_screen( $screen );
}
if ( ! isset( $column_headers[ $screen->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
*
* @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(
'<label for="%1$s-hide"><input class="hide-postbox-tog" name="%1$s-hide" type="checkbox" id="%1$s-hide" value="%1$s" %2$s />%3$s</label>',
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();
}

View File

@ -0,0 +1,316 @@
<?php
/**
* WordPress Taxonomy Administration API.
*
* @package WordPress
* @subpackage Administration
*/
//
// Category.
//
/**
* Checks whether a category exists.
*
* @since 2.0.0
*
* @see term_exists()
*
* @param int|string $cat_name Category name.
* @param int $category_parent Optional. ID of parent category.
* @return string|null Returns the category ID as a numeric string if the pairing exists, null if not.
*/
function category_exists( $cat_name, $category_parent = null ) {
$id = term_exists( $cat_name, 'category', $category_parent );
if ( is_array( $id ) ) {
$id = $id['term_id'];
}
return $id;
}
/**
* Gets category object for given ID and 'edit' filter context.
*
* @since 2.0.0
*
* @param int $id
* @return object
*/
function get_category_to_edit( $id ) {
$category = get_term( $id, 'category', OBJECT, 'edit' );
_make_cat_compat( $category );
return $category;
}
/**
* Adds a new category to the database if it does not already exist.
*
* @since 2.0.0
*
* @param int|string $cat_name Category name.
* @param int $category_parent Optional. ID of parent category.
* @return int|WP_Error
*/
function wp_create_category( $cat_name, $category_parent = 0 ) {
$id = category_exists( $cat_name, $category_parent );
if ( $id ) {
return $id;
}
return wp_insert_category(
array(
'cat_name' => $cat_name,
'category_parent' => $category_parent,
)
);
}
/**
* Creates categories for the given post.
*
* @since 2.0.0
*
* @param string[] $categories Array of category names to create.
* @param int $post_id Optional. The post ID. Default empty.
* @return int[] Array of IDs of categories assigned to the given post.
*/
function wp_create_categories( $categories, $post_id = '' ) {
$cat_ids = array();
foreach ( $categories as $category ) {
$id = category_exists( $category );
if ( $id ) {
$cat_ids[] = $id;
} else {
$id = wp_create_category( $category );
if ( $id ) {
$cat_ids[] = $id;
}
}
}
if ( $post_id ) {
wp_set_post_categories( $post_id, $cat_ids );
}
return $cat_ids;
}
/**
* Updates an existing Category or creates a new Category.
*
* @since 2.0.0
* @since 2.5.0 $wp_error parameter was added.
* @since 3.0.0 The 'taxonomy' argument was added.
*
* @param array $catarr {
* Array of arguments for inserting a new category.
*
* @type int $cat_ID Category ID. A non-zero value updates an existing category.
* Default 0.
* @type string $taxonomy Taxonomy slug. Default 'category'.
* @type string $cat_name Category name. Default empty.
* @type string $category_description Category description. Default empty.
* @type string $category_nicename Category nice (display) name. Default empty.
* @type int|string $category_parent Category parent ID. Default empty.
* }
* @param bool $wp_error Optional. Default false.
* @return int|WP_Error The ID number of the new or updated Category on success. Zero or a WP_Error on failure,
* depending on param `$wp_error`.
*/
function wp_insert_category( $catarr, $wp_error = false ) {
$cat_defaults = array(
'cat_ID' => 0,
'taxonomy' => 'category',
'cat_name' => '',
'category_description' => '',
'category_nicename' => '',
'category_parent' => '',
);
$catarr = wp_parse_args( $catarr, $cat_defaults );
if ( '' === trim( $catarr['cat_name'] ) ) {
if ( ! $wp_error ) {
return 0;
} else {
return new WP_Error( 'cat_name', __( 'You did not enter a category name.' ) );
}
}
$catarr['cat_ID'] = (int) $catarr['cat_ID'];
// Are we updating or creating?
$update = ! empty( $catarr['cat_ID'] );
$name = $catarr['cat_name'];
$description = $catarr['category_description'];
$slug = $catarr['category_nicename'];
$parent = (int) $catarr['category_parent'];
if ( $parent < 0 ) {
$parent = 0;
}
if ( empty( $parent )
|| ! term_exists( $parent, $catarr['taxonomy'] )
|| ( $catarr['cat_ID'] && term_is_ancestor_of( $catarr['cat_ID'], $parent, $catarr['taxonomy'] ) ) ) {
$parent = 0;
}
$args = compact( 'name', 'slug', 'parent', 'description' );
if ( $update ) {
$catarr['cat_ID'] = wp_update_term( $catarr['cat_ID'], $catarr['taxonomy'], $args );
} else {
$catarr['cat_ID'] = wp_insert_term( $catarr['cat_name'], $catarr['taxonomy'], $args );
}
if ( is_wp_error( $catarr['cat_ID'] ) ) {
if ( $wp_error ) {
return $catarr['cat_ID'];
} else {
return 0;
}
}
return $catarr['cat_ID']['term_id'];
}
/**
* Aliases wp_insert_category() with minimal args.
*
* If you want to update only some fields of an existing category, call this
* function with only the new values set inside $catarr.
*
* @since 2.0.0
*
* @param array $catarr The 'cat_ID' value is required. All other keys are optional.
* @return int|false The ID number of the new or updated Category on success. Zero or FALSE on failure.
*/
function wp_update_category( $catarr ) {
$cat_id = (int) $catarr['cat_ID'];
if ( isset( $catarr['category_parent'] ) && ( $cat_id === (int) $catarr['category_parent'] ) ) {
return false;
}
// First, get all of the original fields.
$category = get_term( $cat_id, 'category', ARRAY_A );
_make_cat_compat( $category );
// Escape data pulled from DB.
$category = wp_slash( $category );
// Merge old and new fields with new fields overwriting old ones.
$catarr = array_merge( $category, $catarr );
return wp_insert_category( $catarr );
}
//
// Tags.
//
/**
* Checks whether a post tag with a given name exists.
*
* @since 2.3.0
*
* @param int|string $tag_name
* @return mixed Returns null if the term does not exist.
* Returns an array of the term ID and the term taxonomy ID if the pairing exists.
* Returns 0 if term ID 0 is passed to the function.
*/
function tag_exists( $tag_name ) {
return term_exists( $tag_name, 'post_tag' );
}
/**
* Adds a new tag to the database if it does not already exist.
*
* @since 2.3.0
*
* @param int|string $tag_name
* @return array|WP_Error
*/
function wp_create_tag( $tag_name ) {
return wp_create_term( $tag_name, 'post_tag' );
}
/**
* Gets comma-separated list of tags available to edit.
*
* @since 2.3.0
*
* @param int $post_id
* @param string $taxonomy Optional. The taxonomy for which to retrieve terms. Default 'post_tag'.
* @return string|false|WP_Error
*/
function get_tags_to_edit( $post_id, $taxonomy = 'post_tag' ) {
return get_terms_to_edit( $post_id, $taxonomy );
}
/**
* Gets comma-separated list of terms available to edit for the given post ID.
*
* @since 2.8.0
*
* @param int $post_id
* @param string $taxonomy Optional. The taxonomy for which to retrieve terms. Default 'post_tag'.
* @return string|false|WP_Error
*/
function get_terms_to_edit( $post_id, $taxonomy = 'post_tag' ) {
$post_id = (int) $post_id;
if ( ! $post_id ) {
return false;
}
$terms = get_object_term_cache( $post_id, $taxonomy );
if ( false === $terms ) {
$terms = wp_get_object_terms( $post_id, $taxonomy );
wp_cache_add( $post_id, wp_list_pluck( $terms, 'term_id' ), $taxonomy . '_relationships' );
}
if ( ! $terms ) {
return false;
}
if ( is_wp_error( $terms ) ) {
return $terms;
}
$term_names = array();
foreach ( $terms as $term ) {
$term_names[] = $term->name;
}
$terms_to_edit = esc_attr( implode( ',', $term_names ) );
/**
* Filters the comma-separated list of terms available to edit.
*
* @since 2.8.0
*
* @see get_terms_to_edit()
*
* @param string $terms_to_edit A comma-separated list of term names.
* @param string $taxonomy The taxonomy name for which to retrieve terms.
*/
$terms_to_edit = apply_filters( 'terms_to_edit', $terms_to_edit, $taxonomy );
return $terms_to_edit;
}
/**
* Adds a new term to the database if it does not already exist.
*
* @since 2.8.0
*
* @param string $tag_name The term name.
* @param string $taxonomy Optional. The taxonomy within which to create the term. Default 'post_tag'.
* @return array|WP_Error
*/
function wp_create_term( $tag_name, $taxonomy = 'post_tag' ) {
$id = term_exists( $tag_name, $taxonomy );
if ( $id ) {
return $id;
}
return wp_insert_term( $tag_name, $taxonomy );
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,271 @@
<?php
/**
* WordPress Theme Installation Administration API
*
* @package WordPress
* @subpackage Administration
*/
$themes_allowedtags = array(
'a' => array(
'href' => array(),
'title' => array(),
'target' => array(),
),
'abbr' => array( 'title' => array() ),
'acronym' => array( 'title' => array() ),
'code' => array(),
'pre' => array(),
'em' => array(),
'strong' => array(),
'div' => array(),
'p' => array(),
'ul' => array(),
'ol' => array(),
'li' => array(),
'h1' => array(),
'h2' => array(),
'h3' => array(),
'h4' => array(),
'h5' => array(),
'h6' => array(),
'img' => array(
'src' => array(),
'class' => array(),
'alt' => array(),
),
);
$theme_field_defaults = array(
'description' => true,
'sections' => false,
'tested' => true,
'requires' => true,
'rating' => true,
'downloaded' => true,
'downloadlink' => true,
'last_updated' => true,
'homepage' => true,
'tags' => true,
'num_ratings' => true,
);
/**
* Retrieves the list of WordPress theme features (aka theme tags).
*
* @since 2.8.0
*
* @deprecated 3.1.0 Use get_theme_feature_list() instead.
*
* @return array
*/
function install_themes_feature_list() {
_deprecated_function( __FUNCTION__, '3.1.0', 'get_theme_feature_list()' );
$cache = get_transient( 'wporg_theme_feature_list' );
if ( ! $cache ) {
set_transient( 'wporg_theme_feature_list', array(), 3 * HOUR_IN_SECONDS );
}
if ( $cache ) {
return $cache;
}
$feature_list = themes_api( 'feature_list', array() );
if ( is_wp_error( $feature_list ) ) {
return array();
}
set_transient( 'wporg_theme_feature_list', $feature_list, 3 * HOUR_IN_SECONDS );
return $feature_list;
}
/**
* Displays search form for searching themes.
*
* @since 2.8.0
*
* @param bool $type_selector
*/
function install_theme_search_form( $type_selector = true ) {
$type = isset( $_REQUEST['type'] ) ? wp_unslash( $_REQUEST['type'] ) : 'term';
$term = isset( $_REQUEST['s'] ) ? wp_unslash( $_REQUEST['s'] ) : '';
if ( ! $type_selector ) {
echo '<p class="install-help">' . __( 'Search for themes by keyword.' ) . '</p>';
}
?>
<form id="search-themes" method="get">
<input type="hidden" name="tab" value="search" />
<?php if ( $type_selector ) : ?>
<label class="screen-reader-text" for="typeselector">
<?php
/* translators: Hidden accessibility text. */
_e( 'Type of search' );
?>
</label>
<select name="type" id="typeselector">
<option value="term" <?php selected( 'term', $type ); ?>><?php _e( 'Keyword' ); ?></option>
<option value="author" <?php selected( 'author', $type ); ?>><?php _e( 'Author' ); ?></option>
<option value="tag" <?php selected( 'tag', $type ); ?>><?php _ex( 'Tag', 'Theme Installer' ); ?></option>
</select>
<label class="screen-reader-text" for="s">
<?php
switch ( $type ) {
case 'term':
/* translators: Hidden accessibility text. */
_e( 'Search by keyword' );
break;
case 'author':
/* translators: Hidden accessibility text. */
_e( 'Search by author' );
break;
case 'tag':
/* translators: Hidden accessibility text. */
_e( 'Search by tag' );
break;
}
?>
</label>
<?php else : ?>
<label class="screen-reader-text" for="s">
<?php
/* translators: Hidden accessibility text. */
_e( 'Search by keyword' );
?>
</label>
<?php endif; ?>
<input type="search" name="s" id="s" size="30" value="<?php echo esc_attr( $term ); ?>" autofocus="autofocus" />
<?php submit_button( __( 'Search' ), '', 'search', false ); ?>
</form>
<?php
}
/**
* Displays tags filter for themes.
*
* @since 2.8.0
*/
function install_themes_dashboard() {
install_theme_search_form( false );
?>
<h4><?php _e( 'Feature Filter' ); ?></h4>
<p class="install-help"><?php _e( 'Find a theme based on specific features.' ); ?></p>
<form method="get">
<input type="hidden" name="tab" value="search" />
<?php
$feature_list = get_theme_feature_list();
echo '<div class="feature-filter">';
foreach ( (array) $feature_list as $feature_name => $features ) {
$feature_name = esc_html( $feature_name );
echo '<div class="feature-name">' . $feature_name . '</div>';
echo '<ol class="feature-group">';
foreach ( $features as $feature => $feature_name ) {
$feature_name = esc_html( $feature_name );
$feature = esc_attr( $feature );
?>
<li>
<input type="checkbox" name="features[]" id="feature-id-<?php echo $feature; ?>" value="<?php echo $feature; ?>" />
<label for="feature-id-<?php echo $feature; ?>"><?php echo $feature_name; ?></label>
</li>
<?php } ?>
</ol>
<br class="clear" />
<?php
}
?>
</div>
<br class="clear" />
<?php submit_button( __( 'Find Themes' ), '', 'search' ); ?>
</form>
<?php
}
/**
* Displays a form to upload themes from zip files.
*
* @since 2.8.0
*/
function install_themes_upload() {
?>
<p class="install-help"><?php _e( 'If you have a theme in a .zip format, you may install or update it by uploading it here.' ); ?></p>
<form method="post" enctype="multipart/form-data" class="wp-upload-form" action="<?php echo esc_url( self_admin_url( 'update.php?action=upload-theme' ) ); ?>">
<?php wp_nonce_field( 'theme-upload' ); ?>
<label class="screen-reader-text" for="themezip">
<?php
/* translators: Hidden accessibility text. */
_e( 'Theme zip file' );
?>
</label>
<input type="file" id="themezip" name="themezip" accept=".zip" />
<?php submit_button( _x( 'Install Now', 'theme' ), '', 'install-theme-submit', false ); ?>
</form>
<?php
}
/**
* Prints a theme on the Install Themes pages.
*
* @deprecated 3.4.0
*
* @global WP_Theme_Install_List_Table $wp_list_table
*
* @param object $theme
*/
function display_theme( $theme ) {
_deprecated_function( __FUNCTION__, '3.4.0' );
global $wp_list_table;
if ( ! isset( $wp_list_table ) ) {
$wp_list_table = _get_list_table( 'WP_Theme_Install_List_Table' );
}
$wp_list_table->prepare_items();
$wp_list_table->single_row( $theme );
}
/**
* Displays theme content based on theme list.
*
* @since 2.8.0
*
* @global WP_Theme_Install_List_Table $wp_list_table
*/
function display_themes() {
global $wp_list_table;
if ( ! isset( $wp_list_table ) ) {
$wp_list_table = _get_list_table( 'WP_Theme_Install_List_Table' );
}
$wp_list_table->prepare_items();
$wp_list_table->display();
}
/**
* Displays theme information in dialog box form.
*
* @since 2.8.0
*
* @global WP_Theme_Install_List_Table $wp_list_table
*/
function install_theme_information() {
global $wp_list_table;
$theme = themes_api( 'theme_information', array( 'slug' => wp_unslash( $_REQUEST['theme'] ) ) );
if ( is_wp_error( $theme ) ) {
wp_die( $theme );
}
iframe_header( __( 'Theme Installation' ) );
if ( ! isset( $wp_list_table ) ) {
$wp_list_table = _get_list_table( 'WP_Theme_Install_List_Table' );
}
$wp_list_table->theme_installer_single( $theme );
iframe_footer();
exit;
}

1258
wp-admin/includes/theme.php Normal file

File diff suppressed because it is too large Load Diff

Some files were not shown because too many files have changed in this diff Show More