Customize: Implement customized state persistence with changesets.

Includes infrastructure developed in the Customize Snapshots feature plugin.

See https://make.wordpress.org/core/2016/10/12/customize-changesets-technical-design-decisions/

Props westonruter, valendesigns, utkarshpatel, stubgo, lgedeon, ocean90, ryankienstra, mihai2u, dlh, aaroncampbell, jonathanbardo, jorbin.
See #28721.
See #31089.
Fixes #30937.
Fixes #31517.
Fixes #30028.
Fixes #23225.
Fixes #34142.
Fixes #36485.


git-svn-id: https://develop.svn.wordpress.org/trunk@38810 602fd350-edb4-49c9-b593-d223f7449a82
This commit is contained in:
Weston Ruter
2016-10-18 20:04:36 +00:00
parent 2ba32a2d48
commit 83b059aa19
32 changed files with 4186 additions and 539 deletions

View File

@@ -20,6 +20,31 @@ if ( ! current_user_can( 'customize' ) ) {
);
}
/**
* @global WP_Scripts $wp_scripts
* @global WP_Customize_Manager $wp_customize
*/
global $wp_scripts, $wp_customize;
if ( $wp_customize->changeset_post_id() ) {
if ( ! current_user_can( get_post_type_object( 'customize_changeset' )->cap->edit_post, $wp_customize->changeset_post_id() ) ) {
wp_die(
'<h1>' . __( 'Cheatin&#8217; uh?' ) . '</h1>' .
'<p>' . __( 'Sorry, you are not allowed to edit this changeset.' ) . '</p>',
403
);
}
if ( in_array( get_post_status( $wp_customize->changeset_post_id() ), array( 'publish', 'trash' ), true ) ) {
wp_die(
'<h1>' . __( 'Cheatin&#8217; uh?' ) . '</h1>' .
'<p>' . __( 'This changeset has already been published and cannot be further modified.' ) . '</p>' .
'<p><a href="' . esc_url( remove_query_arg( 'changeset_uuid' ) ) . '">' . __( 'Customize New Changes' ) . '</a></p>',
403
);
}
}
wp_reset_vars( array( 'url', 'return', 'autofocus' ) );
if ( ! empty( $url ) ) {
$wp_customize->set_preview_url( wp_unslash( $url ) );
@@ -31,12 +56,6 @@ if ( ! empty( $autofocus ) && is_array( $autofocus ) ) {
$wp_customize->set_autofocus( wp_unslash( $autofocus ) );
}
/**
* @global WP_Scripts $wp_scripts
* @global WP_Customize_Manager $wp_customize
*/
global $wp_scripts, $wp_customize;
$registered = $wp_scripts->registered;
$wp_scripts = new WP_Scripts;
$wp_scripts->registered = $registered;
@@ -115,7 +134,11 @@ do_action( 'customize_controls_print_scripts' );
<div id="customize-header-actions" class="wp-full-overlay-header">
<?php
$save_text = $wp_customize->is_theme_active() ? __( 'Save &amp; Publish' ) : __( 'Save &amp; Activate' );
submit_button( $save_text, 'primary save', 'save', false );
$save_attrs = array();
if ( ! current_user_can( get_post_type_object( 'customize_changeset' )->cap->publish_posts ) ) {
$save_attrs['style'] = 'display: none';
}
submit_button( $save_text, 'primary save', 'save', false, $save_attrs );
?>
<span class="spinner"></span>
<button type="button" class="customize-controls-preview-toggle">

File diff suppressed because it is too large Load Diff

View File

@@ -1154,7 +1154,7 @@
params.action = 'update-widget';
params.wp_customize = 'on';
params.nonce = api.settings.nonce['update-widget'];
params.theme = api.settings.theme.stylesheet;
params.customize_theme = api.settings.theme.stylesheet;
params.customized = wp.customize.previewer.query().customized;
data = $.param( params );

View File

@@ -366,15 +366,30 @@ function wp_admin_bar_site_menu( $wp_admin_bar ) {
* @since 4.3.0
*
* @param WP_Admin_Bar $wp_admin_bar WP_Admin_Bar instance.
* @global WP_Customize_Manager $wp_customize
*/
function wp_admin_bar_customize_menu( $wp_admin_bar ) {
global $wp_customize;
// Don't show for users who can't access the customizer or when in the admin.
if ( ! current_user_can( 'customize' ) || is_admin() ) {
return;
}
// Don't show if the user cannot edit a given customize_changeset post currently being previewed.
if ( is_customize_preview() && $wp_customize->changeset_post_id() && ! current_user_can( get_post_type_object( 'customize_changeset' )->cap->edit_post, $wp_customize->changeset_post_id() ) ) {
return;
}
$current_url = ( is_ssl() ? 'https://' : 'http://' ) . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
if ( is_customize_preview() && $wp_customize->changeset_uuid() ) {
$current_url = remove_query_arg( 'customize_changeset_uuid', $current_url );
}
$customize_url = add_query_arg( 'url', urlencode( $current_url ), wp_customize_url() );
if ( is_customize_preview() ) {
$customize_url = add_query_arg( array( 'changeset_uuid' => $wp_customize->changeset_uuid() ), $customize_url );
}
$wp_admin_bar->add_menu( array(
'id' => 'customize',

File diff suppressed because it is too large Load Diff

View File

@@ -48,7 +48,12 @@ final class WP_Customize_Nav_Menus {
$this->previewed_menus = array();
$this->manager = $manager;
// Skip useless hooks when the user can't manage nav menus anyway.
// See https://github.com/xwp/wp-customize-snapshots/blob/962586659688a5b1fd9ae93618b7ce2d4e7a421c/php/class-customize-snapshot-manager.php#L469-L499
add_action( 'customize_register', array( $this, 'customize_register' ), 11 );
add_filter( 'customize_dynamic_setting_args', array( $this, 'filter_dynamic_setting_args' ), 10, 2 );
add_filter( 'customize_dynamic_setting_class', array( $this, 'filter_dynamic_setting_class' ), 10, 3 );
// Skip remaining hooks when the user can't manage nav menus anyway.
if ( ! current_user_can( 'edit_theme_options' ) ) {
return;
}
@@ -58,9 +63,6 @@ final class WP_Customize_Nav_Menus {
add_action( 'wp_ajax_search-available-menu-items-customizer', array( $this, 'ajax_search_available_items' ) );
add_action( 'wp_ajax_customize-nav-menus-insert-auto-draft', array( $this, 'ajax_insert_auto_draft_post' ) );
add_action( 'customize_controls_enqueue_scripts', array( $this, 'enqueue_scripts' ) );
add_action( 'customize_register', array( $this, 'customize_register' ), 11 );
add_filter( 'customize_dynamic_setting_args', array( $this, 'filter_dynamic_setting_args' ), 10, 2 );
add_filter( 'customize_dynamic_setting_class', array( $this, 'filter_dynamic_setting_class' ), 10, 3 );
add_action( 'customize_controls_print_footer_scripts', array( $this, 'print_templates' ) );
add_action( 'customize_controls_print_footer_scripts', array( $this, 'available_items_template' ) );
add_action( 'customize_preview_init', array( $this, 'customize_preview_init' ) );
@@ -486,6 +488,23 @@ final class WP_Customize_Nav_Menus {
*/
public function customize_register() {
/*
* Preview settings for nav menus early so that the sections and controls will be added properly.
* See https://github.com/xwp/wp-customize-snapshots/blob/962586659688a5b1fd9ae93618b7ce2d4e7a421c/php/class-customize-snapshot-manager.php#L506-L543
*/
$nav_menus_setting_ids = array();
foreach ( array_keys( $this->manager->unsanitized_post_values() ) as $setting_id ) {
if ( preg_match( '/^(nav_menu_locations|nav_menu|nav_menu_item)\[/', $setting_id ) ) {
$nav_menus_setting_ids[] = $setting_id;
}
}
foreach ( $nav_menus_setting_ids as $setting_id ) {
$setting = $this->manager->get_setting( $setting_id );
if ( $setting ) {
$setting->preview();
}
}
// Require JS-rendered control types.
$this->manager->register_panel_type( 'WP_Customize_Nav_Menus_Panel' );
$this->manager->register_control_type( 'WP_Customize_Nav_Menu_Control' );

View File

@@ -93,16 +93,18 @@ final class WP_Customize_Widgets {
public function __construct( $manager ) {
$this->manager = $manager;
// Skip useless hooks when the user can't manage widgets anyway.
// See https://github.com/xwp/wp-customize-snapshots/blob/962586659688a5b1fd9ae93618b7ce2d4e7a421c/php/class-customize-snapshot-manager.php#L420-L449
add_filter( 'customize_dynamic_setting_args', array( $this, 'filter_customize_dynamic_setting_args' ), 10, 2 );
add_action( 'widgets_init', array( $this, 'register_settings' ), 95 );
add_action( 'customize_register', array( $this, 'schedule_customize_register' ), 1 );
// Skip remaining hooks when the user can't manage widgets anyway.
if ( ! current_user_can( 'edit_theme_options' ) ) {
return;
}
add_filter( 'customize_dynamic_setting_args', array( $this, 'filter_customize_dynamic_setting_args' ), 10, 2 );
add_action( 'widgets_init', array( $this, 'register_settings' ), 95 );
add_action( 'wp_loaded', array( $this, 'override_sidebars_widgets_for_theme_switch' ) );
add_action( 'customize_controls_init', array( $this, 'customize_controls_init' ) );
add_action( 'customize_register', array( $this, 'schedule_customize_register' ), 1 );
add_action( 'customize_controls_enqueue_scripts', array( $this, 'enqueue_scripts' ) );
add_action( 'customize_controls_print_styles', array( $this, 'print_styles' ) );
add_action( 'customize_controls_print_scripts', array( $this, 'print_scripts' ) );
@@ -276,6 +278,7 @@ final class WP_Customize_Widgets {
$this->old_sidebars_widgets = wp_get_sidebars_widgets();
add_filter( 'customize_value_old_sidebars_widgets_data', array( $this, 'filter_customize_value_old_sidebars_widgets_data' ) );
$this->manager->set_post_value( 'old_sidebars_widgets_data', $this->old_sidebars_widgets ); // Override any value cached in changeset.
// retrieve_widgets() looks at the global $sidebars_widgets
$sidebars_widgets = $this->old_sidebars_widgets;

View File

@@ -307,8 +307,6 @@ final class WP_Customize_Selective_Refresh {
return;
}
$this->manager->remove_preview_signature();
/*
* Note that is_customize_preview() returning true will entail that the
* user passed the 'customize' capability check and the nonce check, since

View File

@@ -63,8 +63,8 @@ class WP_Customize_Theme_Control extends WP_Customize_Control {
*/
public function content_template() {
$current_url = set_url_scheme( 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] );
$active_url = esc_url( remove_query_arg( 'theme', $current_url ) );
$preview_url = esc_url( add_query_arg( 'theme', '__THEME__', $current_url ) ); // Token because esc_url() strips curly braces.
$active_url = esc_url( remove_query_arg( 'customize_theme', $current_url ) );
$preview_url = esc_url( add_query_arg( 'customize_theme', '__THEME__', $current_url ) ); // Token because esc_url() strips curly braces.
$preview_url = str_replace( '__THEME__', '{{ data.theme.id }}', $preview_url );
?>
<# if ( data.theme.isActiveTheme ) { #>

View File

@@ -75,6 +75,7 @@ foreach ( array( 'user_url', 'link_url', 'link_image', 'link_rss', 'comment_url'
// Slugs
add_filter( 'pre_term_slug', 'sanitize_title' );
add_filter( 'wp_insert_post_data', '_wp_customize_changeset_filter_insert_post_data', 10, 2 );
// Keys
foreach ( array( 'pre_post_type', 'pre_post_status', 'pre_post_comment_status', 'pre_post_ping_status' ) as $filter ) {
@@ -382,6 +383,7 @@ add_action( 'parse_request', 'rest_api_loaded' );
add_action( 'wp_loaded', '_custom_header_background_just_in_time' );
add_action( 'wp_head', '_custom_logo_header_styles' );
add_action( 'plugins_loaded', '_wp_customize_include' );
add_action( 'transition_post_status', '_wp_customize_publish_changeset', 10, 3 );
add_action( 'admin_enqueue_scripts', '_wp_customize_loader_settings' );
add_action( 'delete_attachment', '_delete_attachment_theme_mod' );

View File

@@ -5523,3 +5523,20 @@ function wp_raise_memory_limit( $context = 'admin' ) {
return false;
}
/**
* Generate a random UUID (version 4).
*
* @since 4.7.0
*
* @return string UUID.
*/
function wp_generate_uuid4() {
return sprintf( '%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ),
mt_rand( 0, 0xffff ),
mt_rand( 0, 0x0fff ) | 0x4000,
mt_rand( 0, 0x3fff ) | 0x8000,
mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff )
);
}

View File

@@ -34,7 +34,7 @@ function wp_scripts() {
* @param string $function Function name.
*/
function _wp_scripts_maybe_doing_it_wrong( $function ) {
if ( did_action( 'init' ) ) {
if ( did_action( 'init' ) || did_action( 'admin_enqueue_scripts' ) || did_action( 'wp_enqueue_scripts' ) || did_action( 'login_enqueue_scripts' ) ) {
return;
}

View File

@@ -637,22 +637,24 @@ window.wp = window.wp || {};
/**
* Initialize Messenger.
*
* @param {object} params Parameters to configure the messenger.
* {string} .url The URL to communicate with.
* {window} .targetWindow The window instance to communicate with. Default window.parent.
* {string} .channel If provided, will send the channel with each message and only accept messages a matching channel.
* @param {object} options Extend any instance parameter or method with this object.
* @param {object} params - Parameters to configure the messenger.
* {string} params.url - The URL to communicate with.
* {window} params.targetWindow - The window instance to communicate with. Default window.parent.
* {string} params.channel - If provided, will send the channel with each message and only accept messages a matching channel.
* @param {object} options - Extend any instance parameter or method with this object.
*/
initialize: function( params, options ) {
// Target the parent frame by default, but only if a parent frame exists.
var defaultTarget = window.parent == window ? null : window.parent;
var defaultTarget = window.parent === window ? null : window.parent;
$.extend( this, options || {} );
this.add( 'channel', params.channel );
this.add( 'url', params.url || '' );
this.add( 'origin', this.url() ).link( this.url ).setter( function( to ) {
return to.replace( /([^:]+:\/\/[^\/]+).*/, '$1' );
var urlParser = document.createElement( 'a' );
urlParser.href = to;
return urlParser.protocol + '//' + urlParser.hostname;
});
// first add with no value
@@ -807,6 +809,40 @@ window.wp = window.wp || {};
return result;
};
/**
* Utility function namespace
*/
api.utils = {};
/**
* Parse query string.
*
* @since 4.7.0
* @access public
*
* @param {string} queryString Query string.
* @returns {object} Parsed query string.
*/
api.utils.parseQueryString = function parseQueryString( queryString ) {
var queryParams = {};
_.each( queryString.split( '&' ), function( pair ) {
var parts, key, value;
parts = pair.split( '=', 2 );
if ( ! parts[0] ) {
return;
}
key = decodeURIComponent( parts[0].replace( /\+/g, ' ' ) );
key = key.replace( / /g, '_' ); // What PHP does.
if ( _.isUndefined( parts[1] ) ) {
value = null;
} else {
value = decodeURIComponent( parts[1].replace( /\+/g, ' ' ) );
}
queryParams[ key ] = value;
} );
return queryParams;
};
// Expose the API publicly on window.wp.customize
exports.customize = api;
})( wp, jQuery );

View File

@@ -132,6 +132,19 @@ window.wp = window.wp || {};
targetWindow: this.iframe[0].contentWindow
});
// Expose the changeset UUID on the parent window's URL so that the customized state can survive a refresh.
if ( history.replaceState ) {
this.messenger.bind( 'changeset-uuid', function( changesetUuid ) {
var urlParser = document.createElement( 'a' );
urlParser.href = location.href;
urlParser.search = $.param( _.extend(
api.utils.parseQueryString( urlParser.search.substr( 1 ) ),
{ changeset_uuid: changesetUuid }
) );
history.replaceState( { customize: urlParser.href }, '', urlParser.href );
} );
}
// Wait for the connection from the iframe before sending any postMessage events.
this.messenger.bind( 'ready', function() {
Loader.messenger.send( 'back' );

View File

@@ -106,7 +106,7 @@ wp.customize.navMenusPreview = wp.customize.MenusCustomizerPreview = ( function(
* @returns {boolean}
*/
isRelatedSetting: function( setting, newValue, oldValue ) {
var partial = this, navMenuLocationSetting, navMenuId, isNavMenuItemSetting;
var partial = this, navMenuLocationSetting, navMenuId, isNavMenuItemSetting, _newValue, _oldValue, urlParser;
if ( _.isString( setting ) ) {
setting = api( setting );
}
@@ -123,9 +123,23 @@ wp.customize.navMenusPreview = wp.customize.MenusCustomizerPreview = ( function(
*/
isNavMenuItemSetting = /^nav_menu_item\[/.test( setting.id );
if ( isNavMenuItemSetting && _.isObject( newValue ) && _.isObject( oldValue ) ) {
delete newValue.type_label;
delete oldValue.type_label;
if ( _.isEqual( oldValue, newValue ) ) {
_newValue = _.clone( newValue );
_oldValue = _.clone( oldValue );
delete _newValue.type_label;
delete _oldValue.type_label;
// Normalize URL scheme when parent frame is HTTPS to prevent selective refresh upon initial page load.
if ( 'https' === api.preview.scheme.get() ) {
urlParser = document.createElement( 'a' );
urlParser.href = _newValue.url;
urlParser.protocol = 'https:';
_newValue.url = urlParser.href;
urlParser.href = _oldValue.url;
urlParser.protocol = 'https:';
_oldValue.url = urlParser.href;
}
if ( _.isEqual( _oldValue, _newValue ) ) {
return false;
}
}
@@ -365,6 +379,11 @@ wp.customize.navMenusPreview = wp.customize.MenusCustomizerPreview = ( function(
self.highlightControls = function() {
var selector = '.menu-item';
// Skip adding highlights if not in the customizer preview iframe.
if ( ! api.settings.channel ) {
return;
}
// Focus on the menu item control when shift+clicking the menu item.
$( document ).on( 'click', selector, function( e ) {
var navMenuItemParts;

View File

@@ -572,6 +572,11 @@ wp.customize.widgetsPreview = wp.customize.WidgetCustomizerPreview = (function(
var self = this,
selector = this.widgetSelectors.join( ',' );
// Skip adding highlights if not in the customizer preview iframe.
if ( ! api.settings.channel ) {
return;
}
$( selector ).attr( 'title', this.l10n.widgetTooltip );
$( document ).on( 'mouseenter', selector, function() {

View File

@@ -3,7 +3,67 @@
*/
(function( exports, $ ){
var api = wp.customize,
debounce;
debounce,
currentHistoryState = {};
/*
* Capture the state that is passed into history.replaceState() and history.pushState()
* and also which is returned in the popstate event so that when the changeset_uuid
* gets updated when transitioning to a new changeset there the current state will
* be supplied in the call to history.replaceState().
*/
( function( history ) {
var injectUrlWithState;
if ( ! history.replaceState ) {
return;
}
/**
* Amend the supplied URL with the customized state.
*
* @since 4.7.0
* @access private
*
* @param {string} url URL.
* @returns {string} URL with customized state.
*/
injectUrlWithState = function( url ) {
var urlParser, queryParams;
urlParser = document.createElement( 'a' );
urlParser.href = url;
queryParams = api.utils.parseQueryString( urlParser.search.substr( 1 ) );
queryParams.customize_changeset_uuid = api.settings.changeset.uuid;
if ( ! api.settings.theme.active ) {
queryParams.customize_theme = api.settings.theme.stylesheet;
}
if ( api.settings.theme.channel ) {
queryParams.customize_messenger_channel = api.settings.channel;
}
urlParser.search = $.param( queryParams );
return url;
};
history.replaceState = ( function( nativeReplaceState ) {
return function historyReplaceState( data, title, url ) {
currentHistoryState = data;
return nativeReplaceState.call( history, data, title, injectUrlWithState( url ) );
};
} )( history.replaceState );
history.pushState = ( function( nativePushState ) {
return function historyPushState( data, title, url ) {
currentHistoryState = data;
return nativePushState.call( history, data, title, injectUrlWithState( url ) );
};
} )( history.pushState );
window.addEventListener( 'popstate', function( event ) {
currentHistoryState = event.state;
} );
}( history ) );
/**
* Returns a debounced version of the function.
@@ -37,38 +97,73 @@
* @param {object} options - Extend any instance parameter or method with this object.
*/
initialize: function( params, options ) {
var self = this;
var preview = this, urlParser = document.createElement( 'a' );
api.Messenger.prototype.initialize.call( this, params, options );
api.Messenger.prototype.initialize.call( preview, params, options );
this.body = $( document.body );
this.body.on( 'click.preview', 'a', function( event ) {
urlParser.href = preview.origin();
preview.add( 'scheme', urlParser.protocol.replace( /:$/, '' ) );
preview.body = $( document.body );
preview.body.on( 'click.preview', 'a', function( event ) {
var link, isInternalJumpLink;
link = $( this );
isInternalJumpLink = ( '#' === link.attr( 'href' ).substr( 0, 1 ) );
event.preventDefault();
if ( isInternalJumpLink && '#' !== link.attr( 'href' ) ) {
$( link.attr( 'href' ) ).each( function() {
this.scrollIntoView();
} );
// No-op if the anchor is not a link.
if ( _.isUndefined( link.attr( 'href' ) ) ) {
return;
}
isInternalJumpLink = ( '#' === link.attr( 'href' ).substr( 0, 1 ) );
// Allow internal jump links to behave normally without preventing default.
if ( isInternalJumpLink ) {
return;
}
// If the link is not previewable, prevent the browser from navigating to it.
if ( ! api.isLinkPreviewable( link[0] ) ) {
wp.a11y.speak( api.settings.l10n.linkUnpreviewable );
event.preventDefault();
return;
}
// If not in an iframe, then allow the link click to proceed normally since the state query params are added.
if ( ! api.settings.channel ) {
return;
}
// Prevent initiating navigating from click and instead rely on sending url message to pane.
event.preventDefault();
/*
* Note the shift key is checked so shift+click on widgets or
* nav menu items can just result on focusing on the corresponding
* control instead of also navigating to the URL linked to.
*/
if ( event.shiftKey || isInternalJumpLink ) {
if ( event.shiftKey ) {
return;
}
self.send( 'scroll', 0 );
self.send( 'url', link.prop( 'href' ) );
});
// You cannot submit forms.
this.body.on( 'submit.preview', 'form', function( event ) {
var urlParser;
// Note: It's not relevant to send scroll because sending url message will have the same effect.
preview.send( 'url', link.prop( 'href' ) );
} );
preview.body.on( 'submit.preview', 'form', function( event ) {
var urlParser = document.createElement( 'a' );
urlParser.href = this.action;
// If the link is not previewable, prevent the browser from navigating to it.
if ( 'GET' !== this.method.toUpperCase() || ! api.isLinkPreviewable( urlParser ) ) {
wp.a11y.speak( api.settings.l10n.formUnpreviewable );
event.preventDefault();
return;
}
// If not in an iframe, then allow the form submission to proceed normally with the state inputs injected.
if ( ! api.settings.channel ) {
return;
}
/*
* If the default wasn't prevented already (in which case the form
@@ -81,30 +176,399 @@
* a no-op, which is the same behavior as when clicking a link to an
* external site in the preview.
*/
if ( ! event.isDefaultPrevented() && 'GET' === this.method.toUpperCase() ) {
urlParser = document.createElement( 'a' );
urlParser.href = this.action;
if ( urlParser.search.substr( 1 ).length > 1 ) {
if ( ! event.isDefaultPrevented() ) {
if ( urlParser.search.length > 1 ) {
urlParser.search += '&';
}
urlParser.search += $( this ).serialize();
api.preview.send( 'url', urlParser.href );
}
// Prevent default since navigation should be done via sending url message or via JS submit handler.
event.preventDefault();
});
this.window = $( window );
this.window.on( 'scroll.preview', debounce( function() {
self.send( 'scroll', self.window.scrollTop() );
}, 200 ));
preview.window = $( window );
this.bind( 'scroll', function( distance ) {
self.window.scrollTop( distance );
});
if ( api.settings.channel ) {
preview.window.on( 'scroll.preview', debounce( function() {
preview.send( 'scroll', preview.window.scrollTop() );
}, 200 ) );
preview.bind( 'scroll', function( distance ) {
preview.window.scrollTop( distance );
});
}
}
});
/**
* Inject the changeset UUID into links in the document.
*
* @since 4.7.0
* @access protected
*
* @access private
* @returns {void}
*/
api.addLinkPreviewing = function addLinkPreviewing() {
var linkSelectors = 'a[href], area';
// Inject links into initial document.
$( document.body ).find( linkSelectors ).each( function() {
api.prepareLinkPreview( this );
} );
// Inject links for new elements added to the page.
if ( 'undefined' !== typeof MutationObserver ) {
api.mutationObserver = new MutationObserver( function( mutations ) {
_.each( mutations, function( mutation ) {
$( mutation.target ).find( linkSelectors ).each( function() {
api.prepareLinkPreview( this );
} );
} );
} );
api.mutationObserver.observe( document.documentElement, {
childList: true,
subtree: true
} );
} else {
// If mutation observers aren't available, fallback to just-in-time injection.
$( document.documentElement ).on( 'click focus mouseover', linkSelectors, function() {
api.prepareLinkPreview( this );
} );
}
};
/**
* Should the supplied link is previewable.
*
* @since 4.7.0
* @access public
*
* @param {HTMLAnchorElement|HTMLAreaElement} element Link element.
* @param {string} element.search Query string.
* @param {string} element.pathname Path.
* @param {string} element.hostname Hostname.
* @param {object} [options]
* @param {object} [options.allowAdminAjax=false] Allow admin-ajax.php requests.
* @returns {boolean} Is appropriate for changeset link.
*/
api.isLinkPreviewable = function isLinkPreviewable( element, options ) {
var hasMatchingHost, urlParser, args;
args = _.extend( {}, { allowAdminAjax: false }, options || {} );
if ( 'javascript:' === element.protocol ) { // jshint ignore:line
return true;
}
// Only web URLs can be previewed.
if ( 'https:' !== element.protocol && 'http:' !== element.protocol ) {
return false;
}
urlParser = document.createElement( 'a' );
hasMatchingHost = ! _.isUndefined( _.find( api.settings.url.allowed, function( allowedUrl ) {
urlParser.href = allowedUrl;
if ( urlParser.hostname === element.hostname && urlParser.protocol === element.protocol ) {
return true;
}
return false;
} ) );
if ( ! hasMatchingHost ) {
return false;
}
// Skip wp login and signup pages.
if ( /\/wp-(login|signup)\.php$/.test( element.pathname ) ) {
return false;
}
// Allow links to admin ajax as faux frontend URLs.
if ( /\/wp-admin\/admin-ajax\.php$/.test( element.pathname ) ) {
return args.allowAdminAjax;
}
// Disallow links to admin, includes, and content.
if ( /\/wp-(admin|includes|content)(\/|$)/.test( element.pathname ) ) {
return false;
}
return true;
};
/**
* Inject the customize_changeset_uuid query param into links on the frontend.
*
* @since 4.7.0
* @access protected
*
* @param {HTMLAnchorElement|HTMLAreaElement} element Link element.
* @param {object} element.search Query string.
* @returns {void}
*/
api.prepareLinkPreview = function prepareLinkPreview( element ) {
var queryParams;
// Skip links in admin bar.
if ( $( element ).closest( '#wpadminbar' ).length ) {
return;
}
// Ignore links with href="#" or href="#id".
if ( '#' === $( element ).attr( 'href' ).substr( 0, 1 ) ) {
return;
}
// Make sure links in preview use HTTPS if parent frame uses HTTPS.
if ( 'https' === api.preview.scheme.get() && 'http:' === element.protocol && -1 !== api.settings.url.allowedHosts.indexOf( element.hostname ) ) {
element.protocol = 'https:';
}
if ( ! api.isLinkPreviewable( element ) ) {
$( element ).addClass( 'customize-unpreviewable' );
return;
}
$( element ).removeClass( 'customize-unpreviewable' );
queryParams = api.utils.parseQueryString( element.search.substring( 1 ) );
queryParams.customize_changeset_uuid = api.settings.changeset.uuid;
if ( ! api.settings.theme.active ) {
queryParams.customize_theme = api.settings.theme.stylesheet;
}
if ( api.settings.channel ) {
queryParams.customize_messenger_channel = api.settings.channel;
}
element.search = $.param( queryParams );
// Prevent links from breaking out of preview iframe.
if ( api.settings.channel ) {
element.target = '_self';
}
};
/**
* Inject the changeset UUID into Ajax requests.
*
* @since 4.7.0
* @access protected
*
* @return {void}
*/
api.addRequestPreviewing = function addRequestPreviewing() {
/**
* Rewrite Ajax requests to inject customizer state.
*
* @param {object} options Options.
* @param {string} options.type Type.
* @param {string} options.url URL.
* @param {object} originalOptions Original options.
* @param {XMLHttpRequest} xhr XHR.
* @returns {void}
*/
var prefilterAjax = function( options, originalOptions, xhr ) {
var urlParser, queryParams, requestMethod, dirtyValues = {};
urlParser = document.createElement( 'a' );
urlParser.href = options.url;
// Abort if the request is not for this site.
if ( ! api.isLinkPreviewable( urlParser, { allowAdminAjax: true } ) ) {
return;
}
queryParams = api.utils.parseQueryString( urlParser.search.substring( 1 ) );
// Note that _dirty flag will be cleared with changeset updates.
api.each( function( setting ) {
if ( setting._dirty ) {
dirtyValues[ setting.id ] = setting.get();
}
} );
if ( ! _.isEmpty( dirtyValues ) ) {
requestMethod = options.type.toUpperCase();
// Override underlying request method to ensure unsaved changes to changeset can be included (force Backbone.emulateHTTP).
if ( 'POST' !== requestMethod ) {
xhr.setRequestHeader( 'X-HTTP-Method-Override', requestMethod );
queryParams._method = requestMethod;
options.type = 'POST';
}
// Amend the post data with the customized values.
if ( options.data ) {
options.data += '&';
} else {
options.data = '';
}
options.data += $.param( {
customized: JSON.stringify( dirtyValues )
} );
}
// Include customized state query params in URL.
queryParams.customize_changeset_uuid = api.settings.changeset.uuid;
if ( ! api.settings.theme.active ) {
queryParams.customize_theme = api.settings.theme.stylesheet;
}
urlParser.search = $.param( queryParams );
options.url = urlParser.href;
};
$.ajaxPrefilter( prefilterAjax );
};
/**
* Inject changeset UUID into forms, allowing preview to persist through submissions.
*
* @since 4.7.0
* @access protected
*
* @returns {void}
*/
api.addFormPreviewing = function addFormPreviewing() {
// Inject inputs for forms in initial document.
$( document.body ).find( 'form' ).each( function() {
api.prepareFormPreview( this );
} );
// Inject inputs for new forms added to the page.
if ( 'undefined' !== typeof MutationObserver ) {
api.mutationObserver = new MutationObserver( function( mutations ) {
_.each( mutations, function( mutation ) {
$( mutation.target ).find( 'form' ).each( function() {
api.prepareFormPreview( this );
} );
} );
} );
api.mutationObserver.observe( document.documentElement, {
childList: true,
subtree: true
} );
}
};
/**
* Inject changeset into form inputs.
*
* @since 4.7.0
* @access protected
*
* @param {HTMLFormElement} form Form.
* @returns {void}
*/
api.prepareFormPreview = function prepareFormPreview( form ) {
var urlParser, stateParams = {};
if ( ! form.action ) {
form.action = location.href;
}
urlParser = document.createElement( 'a' );
urlParser.href = form.action;
// Make sure forms in preview use HTTPS if parent frame uses HTTPS.
if ( 'https' === api.preview.scheme.get() && 'http:' === urlParser.protocol && -1 !== api.settings.url.allowedHosts.indexOf( urlParser.hostname ) ) {
urlParser.protocol = 'https:';
form.action = urlParser.href;
}
if ( 'GET' !== form.method.toUpperCase() || ! api.isLinkPreviewable( urlParser ) ) {
$( form ).addClass( 'customize-unpreviewable' );
return;
}
$( form ).removeClass( 'customize-unpreviewable' );
stateParams.customize_changeset_uuid = api.settings.changeset.uuid;
if ( ! api.settings.theme.active ) {
stateParams.customize_theme = api.settings.theme.stylesheet;
}
if ( api.settings.channel ) {
stateParams.customize_messenger_channel = api.settings.channel;
}
_.each( stateParams, function( value, name ) {
var input = $( form ).find( 'input[name="' + name + '"]' );
if ( input.length ) {
input.val( value );
} else {
$( form ).prepend( $( '<input>', {
type: 'hidden',
name: name,
value: value
} ) );
}
} );
// Prevent links from breaking out of preview iframe.
if ( api.settings.channel ) {
form.target = '_self';
}
};
/**
* Watch current URL and send keep-alive (heartbeat) messages to the parent.
*
* Keep the customizer pane notified that the preview is still alive
* and that the user hasn't navigated to a non-customized URL.
*
* @since 4.7.0
* @access protected
*/
api.keepAliveCurrentUrl = ( function() {
var previousPathName = location.pathname,
previousQueryString = location.search.substr( 1 ),
previousQueryParams = null,
stateQueryParams = [ 'customize_theme', 'customize_changeset_uuid', 'customize_messenger_channel' ];
return function keepAliveCurrentUrl() {
var urlParser, currentQueryParams;
// Short-circuit with keep-alive if previous URL is identical (as is normal case).
if ( previousQueryString === location.search.substr( 1 ) && previousPathName === location.pathname ) {
api.preview.send( 'keep-alive' );
return;
}
urlParser = document.createElement( 'a' );
if ( null === previousQueryParams ) {
urlParser.search = previousQueryString;
previousQueryParams = api.utils.parseQueryString( previousQueryString );
_.each( stateQueryParams, function( name ) {
delete previousQueryParams[ name ];
} );
}
// Determine if current URL minus customized state params and URL hash.
urlParser.href = location.href;
currentQueryParams = api.utils.parseQueryString( urlParser.search.substr( 1 ) );
_.each( stateQueryParams, function( name ) {
delete currentQueryParams[ name ];
} );
if ( previousPathName !== location.pathname || ! _.isEqual( previousQueryParams, currentQueryParams ) ) {
urlParser.search = $.param( currentQueryParams );
urlParser.hash = '';
api.settings.url.self = urlParser.href;
api.preview.send( 'ready', {
currentUrl: api.settings.url.self,
activePanels: api.settings.activePanels,
activeSections: api.settings.activeSections,
activeControls: api.settings.activeControls,
settingValidities: api.settings.settingValidities
} );
} else {
api.preview.send( 'keep-alive' );
}
previousQueryParams = currentQueryParams;
previousQueryString = location.search.substr( 1 );
previousPathName = location.pathname;
};
} )();
$( function() {
var bg, setValue;
@@ -118,6 +582,10 @@
channel: api.settings.channel
});
api.addLinkPreviewing();
api.addRequestPreviewing();
api.addFormPreviewing();
/**
* Create/update a setting value.
*
@@ -171,15 +639,47 @@
api.preview.send( 'nonce', api.settings.nonce );
api.preview.send( 'documentTitle', document.title );
// Send scroll in case of loading via non-refresh.
api.preview.send( 'scroll', $( window ).scrollTop() );
});
api.preview.bind( 'saved', function( response ) {
if ( response.next_changeset_uuid ) {
api.settings.changeset.uuid = response.next_changeset_uuid;
// Update UUIDs in links and forms.
$( document.body ).find( 'a[href], area' ).each( function() {
api.prepareLinkPreview( this );
} );
$( document.body ).find( 'form' ).each( function() {
api.prepareFormPreview( this );
} );
/*
* Replace the UUID in the URL. Note that the wrapped history.replaceState()
* will handle injecting the current api.settings.changeset.uuid into the URL,
* so this is merely to trigger that logic.
*/
if ( history.replaceState ) {
history.replaceState( currentHistoryState, '', location.href );
}
}
api.trigger( 'saved', response );
} );
api.bind( 'saved', function() {
api.each( function( setting ) {
setting._dirty = false;
/*
* Clear dirty flag for settings when saved to changeset so that they
* won't be needlessly included in selective refresh or ajax requests.
*/
api.preview.bind( 'changeset-saved', function( data ) {
_.each( data.saved_changeset_values, function( value, settingId ) {
var setting = api( settingId );
if ( setting && _.isEqual( setting.get(), value ) ) {
setting._dirty = false;
}
} );
} );
@@ -192,12 +692,16 @@
* containers and controls are active.
*/
api.preview.send( 'ready', {
currentUrl: api.settings.url.self,
activePanels: api.settings.activePanels,
activeSections: api.settings.activeSections,
activeControls: api.settings.activeControls,
settingValidities: api.settings.settingValidities
} );
// Send ready when URL changes via JS.
setInterval( api.keepAliveCurrentUrl, api.settings.timeouts.keepAliveSend );
// Display a loading indicator when preview is reloading, and remove on failure.
api.preview.bind( 'loading-initiated', function () {
$( 'body' ).addClass( 'wp-customizer-unloading' );

View File

@@ -11,8 +11,7 @@ wp.customize.selectiveRefresh = ( function( $, api ) {
renderQueryVar: '',
l10n: {
shiftClickToEdit: ''
},
refreshBuffer: 250
}
},
currentRequest: null
};
@@ -485,8 +484,9 @@ wp.customize.selectiveRefresh = ( function( $, api ) {
return {
wp_customize: 'on',
nonce: api.settings.nonce.preview,
theme: api.settings.theme.stylesheet,
customized: JSON.stringify( dirtyCustomized )
customize_theme: api.settings.theme.stylesheet,
customized: JSON.stringify( dirtyCustomized ),
customize_changeset_uuid: api.settings.changeset.uuid
};
};
@@ -668,7 +668,7 @@ wp.customize.selectiveRefresh = ( function( $, api ) {
self._pendingPartialRequests = {};
} );
},
self.data.refreshBuffer
api.settings.timeouts.selectiveRefresh
);
return partialRequest.deferred.promise();

View File

@@ -111,6 +111,51 @@ function create_initial_post_types() {
'query_var' => false,
) );
register_post_type( 'customize_changeset', array(
'labels' => array(
'name' => _x( 'Changesets', 'post type general name' ),
'singular_name' => _x( 'Changeset', 'post type singular name' ),
'menu_name' => _x( 'Changesets', 'admin menu' ),
'name_admin_bar' => _x( 'Changeset', 'add new on admin bar' ),
'add_new' => _x( 'Add New', 'Customize Changeset' ),
'add_new_item' => __( 'Add New Changeset' ),
'new_item' => __( 'New Changeset' ),
'edit_item' => __( 'Edit Changeset' ),
'view_item' => __( 'View Changeset' ),
'all_items' => __( 'All Changesets' ),
'search_items' => __( 'Search Changesets' ),
'not_found' => __( 'No changesets found.' ),
'not_found_in_trash' => __( 'No changesets found in Trash.' ),
),
'public' => false,
'_builtin' => true, /* internal use only. don't use this when registering your own post type. */
'map_meta_cap' => true,
'hierarchical' => false,
'rewrite' => false,
'query_var' => false,
'can_export' => false,
'delete_with_user' => false,
'supports' => array( 'title', 'author' ),
'capability_type' => 'customize_changeset',
'capabilities' => array(
'create_posts' => 'customize',
'delete_others_posts' => 'customize',
'delete_post' => 'customize',
'delete_posts' => 'customize',
'delete_private_posts' => 'customize',
'delete_published_posts' => 'customize',
'edit_others_posts' => 'customize',
'edit_post' => 'customize',
'edit_posts' => 'customize',
'edit_private_posts' => 'customize',
'edit_published_posts' => 'do_not_allow',
'publish_posts' => 'customize',
'read' => 'read',
'read_post' => 'customize',
'read_private_posts' => 'customize',
),
) );
register_post_status( 'publish', array(
'label' => _x( 'Published', 'post status' ),
'public' => true,

View File

@@ -450,7 +450,7 @@ function wp_default_scripts( &$scripts ) {
$scripts->add( 'customize-base', "/wp-includes/js/customize-base$suffix.js", array( 'jquery', 'json2', 'underscore' ), false, 1 );
$scripts->add( 'customize-loader', "/wp-includes/js/customize-loader$suffix.js", array( 'customize-base' ), false, 1 );
$scripts->add( 'customize-preview', "/wp-includes/js/customize-preview$suffix.js", array( 'customize-base' ), false, 1 );
$scripts->add( 'customize-preview', "/wp-includes/js/customize-preview$suffix.js", array( 'wp-a11y', 'customize-base' ), false, 1 );
$scripts->add( 'customize-models', "/wp-includes/js/customize-models.js", array( 'underscore', 'backbone' ), false, 1 );
$scripts->add( 'customize-views', "/wp-includes/js/customize-views.js", array( 'jquery', 'underscore', 'imgareaselect', 'customize-models', 'media-editor', 'media-views' ), false, 1 );
$scripts->add( 'customize-controls', "/wp-admin/js/customize-controls$suffix.js", array( 'customize-base', 'wp-a11y', 'wp-util' ), false, 1 );

View File

@@ -2066,9 +2066,9 @@ function check_theme_switched() {
* Includes and instantiates the WP_Customize_Manager class.
*
* Loads the Customizer at plugins_loaded when accessing the customize.php admin
* page or when any request includes a wp_customize=on param, either as a GET
* query var or as POST data. This param is a signal for whether to bootstrap
* the Customizer when WordPress is loading, especially in the Customizer preview
* page or when any request includes a wp_customize=on param or a customize_changeset
* param (a UUID). This param is a signal for whether to bootstrap the Customizer when
* WordPress is loading, especially in the Customizer preview
* or when making Customizer Ajax requests for widgets or menus.
*
* @since 3.4.0
@@ -2076,14 +2076,140 @@ function check_theme_switched() {
* @global WP_Customize_Manager $wp_customize
*/
function _wp_customize_include() {
if ( ! ( ( isset( $_REQUEST['wp_customize'] ) && 'on' == $_REQUEST['wp_customize'] )
|| ( is_admin() && 'customize.php' == basename( $_SERVER['PHP_SELF'] ) )
) ) {
$is_customize_admin_page = ( is_admin() && 'customize.php' == basename( $_SERVER['PHP_SELF'] ) );
$should_include = (
$is_customize_admin_page
||
( isset( $_REQUEST['wp_customize'] ) && 'on' == $_REQUEST['wp_customize'] )
||
( ! empty( $_GET['customize_changeset_uuid'] ) || ! empty( $_POST['customize_changeset_uuid'] ) )
);
if ( ! $should_include ) {
return;
}
require_once ABSPATH . WPINC . '/class-wp-customize-manager.php';
$GLOBALS['wp_customize'] = new WP_Customize_Manager();
/*
* Note that wp_unslash() is not being used on the input vars because it is
* called before wp_magic_quotes() gets called. Besides this fact, none of
* the values should contain any characters needing slashes anyway.
*/
$keys = array( 'changeset_uuid', 'customize_changeset_uuid', 'customize_theme', 'theme', 'customize_messenger_channel' );
$input_vars = array_merge(
wp_array_slice_assoc( $_GET, $keys ),
wp_array_slice_assoc( $_POST, $keys )
);
$theme = null;
$changeset_uuid = null;
$messenger_channel = null;
if ( $is_customize_admin_page && isset( $input_vars['changeset_uuid'] ) ) {
$changeset_uuid = sanitize_key( $input_vars['changeset_uuid'] );
} elseif ( ! empty( $input_vars['customize_changeset_uuid'] ) ) {
$changeset_uuid = sanitize_key( $input_vars['customize_changeset_uuid'] );
}
// Note that theme will be sanitized via WP_Theme.
if ( $is_customize_admin_page && isset( $input_vars['theme'] ) ) {
$theme = $input_vars['theme'];
} elseif ( isset( $input_vars['customize_theme'] ) ) {
$theme = $input_vars['customize_theme'];
}
if ( isset( $input_vars['customize_messenger_channel'] ) ) {
$messenger_channel = sanitize_key( $input_vars['customize_messenger_channel'] );
}
require_once ABSPATH . WPINC . '/class-wp-customize-manager.php';
$GLOBALS['wp_customize'] = new WP_Customize_Manager( compact( 'changeset_uuid', 'theme', 'messenger_channel' ) );
}
/**
* Publish a snapshot's changes.
*
* @param string $new_status New post status.
* @param string $old_status Old post status.
* @param WP_Post $changeset_post Changeset post object.
*/
function _wp_customize_publish_changeset( $new_status, $old_status, $changeset_post ) {
global $wp_customize;
$is_publishing_changeset = (
'customize_changeset' === $changeset_post->post_type
&&
'publish' === $new_status
&&
'publish' !== $old_status
);
if ( ! $is_publishing_changeset ) {
return;
}
if ( empty( $wp_customize ) ) {
require_once ABSPATH . WPINC . '/class-wp-customize-manager.php';
$wp_customize = new WP_Customize_Manager( $changeset_post->post_name );
}
if ( ! did_action( 'customize_register' ) ) {
/*
* When running from CLI or Cron, the customize_register action will need
* to be triggered in order for core, themes, and plugins to register their
* settings. Normally core will add_action( 'customize_register' ) at
* priority 10 to register the core settings, and if any themes/plugins
* also add_action( 'customize_register' ) at the same priority, they
* will have a $wp_customize with those settings registered since they
* call add_action() afterward, normally. However, when manually doing
* the customize_register action after the setup_theme, then the order
* will be reversed for two actions added at priority 10, resulting in
* the core settings no longer being available as expected to themes/plugins.
* So the following manually calls the method that registers the core
* settings up front before doing the action.
*/
remove_action( 'customize_register', array( $wp_customize, 'register_controls' ) );
$wp_customize->register_controls();
/** This filter is documented in /wp-includes/class-wp-customize-manager.php */
do_action( 'customize_register', $wp_customize );
}
$wp_customize->_publish_changeset_values( $changeset_post->ID ) ;
/*
* Trash the changeset post if revisions are not enabled. Unpublished
* changesets by default get garbage collected due to the auto-draft status.
* When a changeset post is published, however, it would no longer get cleaned
* out. Ths is a problem when the changeset posts are never displayed anywhere,
* since they would just be endlessly piling up. So here we use the revisions
* feature to indicate whether or not a published changeset should get trashed
* and thus garbage collected.
*/
if ( ! wp_revisions_enabled( $changeset_post ) ) {
wp_trash_post( $changeset_post->ID );
}
}
/**
* Filters changeset post data upon insert to ensure post_name is intact.
*
* This is needed to prevent the post_name from being dropped when the post is
* transitioned into pending status by a contributor.
*
* @since 4.7.0
* @see wp_insert_post()
*
* @param array $post_data An array of slashed post data.
* @param array $supplied_post_data An array of sanitized, but otherwise unmodified post data.
* @returns array Filtered data.
*/
function _wp_customize_changeset_filter_insert_post_data( $post_data, $supplied_post_data ) {
if ( isset( $post_data['post_type'] ) && 'customize_changeset' === $post_data['post_type'] ) {
// Prevent post_name from being dropped, such as when contributor saves a changeset post as pending.
if ( empty( $post_data['post_name'] ) && ! empty( $supplied_post_data['post_name'] ) ) {
$post_data['post_name'] = $supplied_post_data['post_name'];
}
}
return $post_data;
}
/**

View File

@@ -550,4 +550,37 @@ class Tests_AdminBar extends WP_UnitTestCase {
$this->assertNull( $node );
}
/**
* @ticket 30937
* @covers wp_admin_bar_customize_menu()
*/
public function test_customize_link() {
global $wp_customize;
require_once ABSPATH . WPINC . '/class-wp-customize-manager.php';
$uuid = wp_generate_uuid4();
$this->go_to( home_url( "/?customize_changeset_uuid=$uuid" ) );
wp_set_current_user( self::$admin_id );
$this->factory()->post->create( array(
'post_type' => 'customize_changeset',
'post_status' => 'auto-draft',
'post_name' => $uuid,
) );
$wp_customize = new WP_Customize_Manager( array(
'changeset_uuid' => $uuid,
) );
$wp_customize->start_previewing_theme();
set_current_screen( 'front' );
$wp_admin_bar = $this->get_standard_admin_bar();
$node = $wp_admin_bar->get_node( 'customize' );
$this->assertNotEmpty( $node );
$parsed_url = wp_parse_url( $node->href );
$query_params = array();
wp_parse_str( $parsed_url['query'], $query_params );
$this->assertEquals( $uuid, $query_params['changeset_uuid'] );
$this->assertNotContains( 'changeset_uuid', $query_params['url'] );
}
}

View File

@@ -0,0 +1,310 @@
<?php
/**
* Testing ajax customize manager functionality
*
* @package WordPress
* @subpackage UnitTests
* @since 4.3.0
* @group ajax
*/
class Tests_Ajax_CustomizeManager extends WP_Ajax_UnitTestCase {
/**
* Instance of WP_Customize_Manager which is reset for each test.
*
* @var WP_Customize_Manager
*/
public $wp_customize;
/**
* Admin user ID.
*
* @var int
*/
protected static $admin_user_id;
/**
* Subscriber user ID.
*
* @var int
*/
protected static $subscriber_user_id;
/**
* Last response parsed.
*
* @var array|null
*/
protected $_last_response_parsed;
/**
* Set up before class.
*
* @param WP_UnitTest_Factory $factory Factory.
*/
public static function wpSetUpBeforeClass( $factory ) {
self::$subscriber_user_id = $factory->user->create( array( 'role' => 'subscriber' ) );
self::$admin_user_id = $factory->user->create( array( 'role' => 'administrator' ) );
}
/**
* Set up the test fixture.
*/
public function setUp() {
parent::setUp();
require_once ABSPATH . WPINC . '/class-wp-customize-manager.php';
}
/**
* Tear down.
*/
public function tearDown() {
parent::tearDown();
$_REQUEST = array();
}
/**
* Helper to keep it DRY
*
* @param string $action Action.
*/
protected function make_ajax_call( $action ) {
$this->_last_response_parsed = null;
$this->_last_response = '';
try {
$this->_handleAjax( $action );
} catch ( WPAjaxDieContinueException $e ) {
unset( $e );
}
if ( $this->_last_response ) {
$this->_last_response_parsed = json_decode( $this->_last_response, true );
}
}
/**
* Overridden caps for user_has_cap.
*
* @var array
*/
protected $overridden_caps = array();
/**
* Dynamically filter a user's capabilities.
*
* @param array $allcaps An array of all the user's capabilities.
* @return array All caps.
*/
function filter_user_has_cap( $allcaps ) {
$allcaps = array_merge( $allcaps, $this->overridden_caps );
return $allcaps;
}
/**
* Test WP_Customize_Manager::save().
*
* @ticket 30937
* @covers WP_Customize_Manager::save()
*/
function test_save_failures() {
global $wp_customize;
$wp_customize = new WP_Customize_Manager();
$wp_customize->register_controls();
add_filter( 'user_has_cap', array( $this, 'filter_user_has_cap' ) );
// Unauthenticated.
wp_set_current_user( 0 );
$this->make_ajax_call( 'customize_save' );
$this->assertFalse( $this->_last_response_parsed['success'] );
$this->assertEquals( 'unauthenticated', $this->_last_response_parsed['data'] );
// Unauthorized.
wp_set_current_user( self::$subscriber_user_id );
$nonce = wp_create_nonce( 'save-customize_' . $wp_customize->get_stylesheet() );
$_POST['nonce'] = $_GET['nonce'] = $_REQUEST['nonce'] = $nonce;
$exception = null;
try {
ob_start();
$wp_customize->setup_theme();
} catch ( WPAjaxDieContinueException $e ) {
$exception = $e;
}
$this->assertNotEmpty( $e );
$this->assertEquals( -1, $e->getMessage() );
// Not called setup_theme.
wp_set_current_user( self::$admin_user_id );
$nonce = wp_create_nonce( 'save-customize_' . $wp_customize->get_stylesheet() );
$_POST['nonce'] = $_GET['nonce'] = $_REQUEST['nonce'] = $nonce;
$this->make_ajax_call( 'customize_save' );
$this->assertFalse( $this->_last_response_parsed['success'] );
$this->assertEquals( 'not_preview', $this->_last_response_parsed['data'] );
// Bad nonce.
$_POST['nonce'] = $_GET['nonce'] = $_REQUEST['nonce'] = 'bad';
$wp_customize->setup_theme();
$this->make_ajax_call( 'customize_save' );
$this->assertFalse( $this->_last_response_parsed['success'] );
$this->assertEquals( 'invalid_nonce', $this->_last_response_parsed['data'] );
// User cannot create.
$nonce = wp_create_nonce( 'save-customize_' . $wp_customize->get_stylesheet() );
$_POST['nonce'] = $_GET['nonce'] = $_REQUEST['nonce'] = $nonce;
$post_type_obj = get_post_type_object( 'customize_changeset' );
$post_type_obj->cap->create_posts = 'create_customize_changesets';
$this->make_ajax_call( 'customize_save' );
$this->assertFalse( $this->_last_response_parsed['success'] );
$this->assertEquals( 'cannot_create_changeset_post', $this->_last_response_parsed['data'] );
$this->overridden_caps[ $post_type_obj->cap->create_posts ] = true;
$this->make_ajax_call( 'customize_save' );
$this->assertTrue( $this->_last_response_parsed['success'] );
$post_type_obj->cap->create_posts = 'customize'; // Restore.
// Changeset already published.
$wp_customize->set_post_value( 'blogname', 'Hello' );
$wp_customize->save_changeset_post( array( 'status' => 'publish' ) );
$this->make_ajax_call( 'customize_save' );
$this->assertFalse( $this->_last_response_parsed['success'] );
$this->assertEquals( 'changeset_already_published', $this->_last_response_parsed['data'] );
wp_update_post( array( 'ID' => $wp_customize->changeset_post_id(), 'post_status' => 'auto-draft' ) );
// User cannot edit.
$post_type_obj = get_post_type_object( 'customize_changeset' );
$post_type_obj->cap->edit_post = 'edit_customize_changesets';
$this->make_ajax_call( 'customize_save' );
$this->assertFalse( $this->_last_response_parsed['success'] );
$this->assertEquals( 'cannot_edit_changeset_post', $this->_last_response_parsed['data'] );
$this->overridden_caps[ $post_type_obj->cap->edit_post ] = true;
$this->make_ajax_call( 'customize_save' );
$this->assertTrue( $this->_last_response_parsed['success'] );
$post_type_obj->cap->edit_post = 'customize'; // Restore.
// Bad customize_changeset_data.
$_POST['customize_changeset_data'] = '[MALFORMED]';
$this->make_ajax_call( 'customize_save' );
$this->assertFalse( $this->_last_response_parsed['success'] );
$this->assertEquals( 'invalid_customize_changeset_data', $this->_last_response_parsed['data'] );
// Bad customize_changeset_status.
$_POST['customize_changeset_data'] = '{}';
$_POST['customize_changeset_status'] = 'unrecognized';
$this->make_ajax_call( 'customize_save' );
$this->assertFalse( $this->_last_response_parsed['success'] );
$this->assertEquals( 'bad_customize_changeset_status', $this->_last_response_parsed['data'] );
// Disallowed publish posts if not allowed.
$post_type_obj = get_post_type_object( 'customize_changeset' );
$post_type_obj->cap->publish_posts = 'publish_customize_changesets';
$_POST['customize_changeset_status'] = 'publish';
$this->make_ajax_call( 'customize_save' );
$this->assertFalse( $this->_last_response_parsed['success'] );
$this->assertEquals( 'changeset_publish_unauthorized', $this->_last_response_parsed['data'] );
$_POST['customize_changeset_status'] = 'future';
$this->make_ajax_call( 'customize_save' );
$this->assertFalse( $this->_last_response_parsed['success'] );
$this->assertEquals( 'changeset_publish_unauthorized', $this->_last_response_parsed['data'] );
$post_type_obj->cap->publish_posts = 'customize'; // Restore.
// Validate date.
$_POST['customize_changeset_status'] = 'draft';
$_POST['customize_changeset_date'] = 'BAD DATE';
$this->make_ajax_call( 'customize_save' );
$this->assertFalse( $this->_last_response_parsed['success'] );
$this->assertEquals( 'bad_customize_changeset_date', $this->_last_response_parsed['data'] );
$_POST['customize_changeset_date'] = '2010-01-01 00:00:00';
$this->make_ajax_call( 'customize_save' );
$this->assertFalse( $this->_last_response_parsed['success'] );
$this->assertEquals( 'not_future_date', $this->_last_response_parsed['data'] );
$_POST['customize_changeset_date'] = ( gmdate( 'Y' ) + 1 ) . '-01-01 00:00:00';
$this->make_ajax_call( 'customize_save' );
$this->assertTrue( $this->_last_response_parsed['success'] );
$_POST['customize_changeset_status'] = 'future';
$_POST['customize_changeset_date'] = '+10 minutes';
$this->make_ajax_call( 'customize_save' );
$this->assertTrue( $this->_last_response_parsed['success'] );
$this->assertEquals( 'future', get_post_status( $wp_customize->changeset_post_id() ) );
wp_update_post( array( 'ID' => $wp_customize->changeset_post_id(), 'post_status' => 'auto-draft' ) );
}
/**
* Set up valid user state.
*
* @param string $uuid Changeset UUID.
* @return WP_Customize_Manager
*/
protected function set_up_valid_state( $uuid = null ) {
global $wp_customize;
wp_set_current_user( self::$admin_user_id );
$wp_customize = new WP_Customize_Manager( array(
'changeset_uuid' => $uuid,
) );
$wp_customize->register_controls();
$nonce = wp_create_nonce( 'save-customize_' . $wp_customize->get_stylesheet() );
$_POST['nonce'] = $_GET['nonce'] = $_REQUEST['nonce'] = $nonce;
$wp_customize->setup_theme();
return $wp_customize;
}
/**
* Test WP_Customize_Manager::save().
*
* @ticket 30937
* @covers WP_Customize_Manager::save()
*/
function test_save_success_publish_create() {
$wp_customize = $this->set_up_valid_state();
// Successful future.
$_POST['customize_changeset_status'] = 'publish';
$_POST['customize_changeset_title'] = 'Success Changeset';
$_POST['customize_changeset_data'] = wp_json_encode( array(
'blogname' => array(
'value' => 'Successful Site Title',
),
) );
$this->make_ajax_call( 'customize_save' );
$this->assertTrue( $this->_last_response_parsed['success'] );
$this->assertInternalType( 'array', $this->_last_response_parsed['data'] );
$this->assertEquals( 'publish', $this->_last_response_parsed['data']['changeset_status'] );
$this->assertArrayHasKey( 'next_changeset_uuid', $this->_last_response_parsed['data'] );
$this->assertEquals( 'Success Changeset', get_post( $wp_customize->changeset_post_id() )->post_title );
$this->assertEquals( 'Successful Site Title', get_option( 'blogname' ) );
}
/**
* Test WP_Customize_Manager::save().
*
* @ticket 30937
* @covers WP_Customize_Manager::save()
*/
function test_save_success_publish_edit() {
$uuid = wp_generate_uuid4();
$post_id = $this->factory()->post->create( array(
'post_name' => $uuid,
'post_title' => 'Original',
'post_type' => 'customize_changeset',
'post_status' => 'auto-draft',
'post_content' => wp_json_encode( array(
'blogname' => array(
'value' => 'New Site Title',
),
) ),
) );
$wp_customize = $this->set_up_valid_state( $uuid );
// Successful future.
$_POST['customize_changeset_status'] = 'publish';
$_POST['customize_changeset_title'] = 'Published';
$this->make_ajax_call( 'customize_save' );
$this->assertTrue( $this->_last_response_parsed['success'] );
$this->assertInternalType( 'array', $this->_last_response_parsed['data'] );
$this->assertEquals( 'publish', $this->_last_response_parsed['data']['changeset_status'] );
$this->assertArrayHasKey( 'next_changeset_uuid', $this->_last_response_parsed['data'] );
$this->assertEquals( 'New Site Title', get_option( 'blogname' ) );
$this->assertEquals( 'Published', get_post( $post_id )->post_title );
}
}

View File

@@ -26,6 +26,30 @@ class Tests_WP_Customize_Manager extends WP_UnitTestCase {
*/
public $undefined;
/**
* Admin user ID.
*
* @var int
*/
protected static $admin_user_id;
/**
* Subscriber user ID.
*
* @var int
*/
protected static $subscriber_user_id;
/**
* Set up before class.
*
* @param WP_UnitTest_Factory $factory Factory.
*/
public static function wpSetUpBeforeClass( $factory ) {
self::$subscriber_user_id = $factory->user->create( array( 'role' => 'subscriber' ) );
self::$admin_user_id = $factory->user->create( array( 'role' => 'administrator' ) );
}
/**
* Set up test.
*/
@@ -42,6 +66,7 @@ class Tests_WP_Customize_Manager extends WP_UnitTestCase {
function tearDown() {
$this->manager = null;
unset( $GLOBALS['wp_customize'] );
$_REQUEST = array();
parent::tearDown();
}
@@ -55,6 +80,608 @@ class Tests_WP_Customize_Manager extends WP_UnitTestCase {
return $GLOBALS['wp_customize'];
}
/**
* Test WP_Customize_Manager::__construct().
*
* @covers WP_Customize_Manager::__construct()
*/
function test_constructor() {
$uuid = wp_generate_uuid4();
$theme = 'twentyfifteen';
$messenger_channel = 'preview-123';
$wp_customize = new WP_Customize_Manager( array(
'changeset_uuid' => $uuid,
'theme' => $theme,
'messenger_channel' => $messenger_channel,
) );
$this->assertEquals( $uuid, $wp_customize->changeset_uuid() );
$this->assertEquals( $theme, $wp_customize->get_stylesheet() );
$this->assertEquals( $messenger_channel, $wp_customize->get_messenger_channel() );
$theme = 'twentyfourteen';
$messenger_channel = 'preview-456';
$_REQUEST['theme'] = $theme;
$_REQUEST['customize_messenger_channel'] = $messenger_channel;
$wp_customize = new WP_Customize_Manager( array( 'changeset_uuid' => $uuid ) );
$this->assertEquals( $theme, $wp_customize->get_stylesheet() );
$this->assertEquals( $messenger_channel, $wp_customize->get_messenger_channel() );
$theme = 'twentyfourteen';
$_REQUEST['customize_theme'] = $theme;
$wp_customize = new WP_Customize_Manager();
$this->assertEquals( $theme, $wp_customize->get_stylesheet() );
$this->assertNotEmpty( $wp_customize->changeset_uuid() );
}
/**
* Test WP_Customize_Manager::setup_theme() for admin screen.
*
* @covers WP_Customize_Manager::setup_theme()
*/
function test_setup_theme_in_customize_admin() {
global $pagenow, $wp_customize;
$pagenow = 'customize.php';
set_current_screen( 'customize' );
// Unauthorized.
$exception = null;
$wp_customize = new WP_Customize_Manager();
wp_set_current_user( self::$subscriber_user_id );
try {
$wp_customize->setup_theme();
} catch ( Exception $e ) {
$exception = $e;
}
$this->assertInstanceOf( 'WPDieException', $exception );
$this->assertContains( 'you are not allowed to customize this site', $exception->getMessage() );
// Bad changeset.
$exception = null;
wp_set_current_user( self::$admin_user_id );
$wp_customize = new WP_Customize_Manager( array( 'changeset_uuid' => 'bad' ) );
try {
$wp_customize->setup_theme();
} catch ( Exception $e ) {
$exception = $e;
}
$this->assertInstanceOf( 'WPDieException', $exception );
$this->assertContains( 'Invalid changeset UUID', $exception->getMessage() );
$wp_customize = new WP_Customize_Manager();
$wp_customize->setup_theme();
}
/**
* Test WP_Customize_Manager::setup_theme() for frontend.
*
* @covers WP_Customize_Manager::setup_theme()
*/
function test_setup_theme_in_frontend() {
global $wp_customize, $pagenow, $show_admin_bar;
$pagenow = 'front';
set_current_screen( 'front' );
wp_set_current_user( 0 );
$exception = null;
$wp_customize = new WP_Customize_Manager();
wp_set_current_user( self::$subscriber_user_id );
try {
$wp_customize->setup_theme();
} catch ( Exception $e ) {
$exception = $e;
}
$this->assertInstanceOf( 'WPDieException', $exception );
$this->assertContains( 'Non-existent changeset UUID', $exception->getMessage() );
wp_set_current_user( self::$admin_user_id );
$wp_customize = new WP_Customize_Manager( array( 'messenger_channel' => 'preview-1' ) );
$wp_customize->setup_theme();
$this->assertFalse( $show_admin_bar );
show_admin_bar( true );
wp_set_current_user( self::$admin_user_id );
$wp_customize = new WP_Customize_Manager( array( 'messenger_channel' => null ) );
$wp_customize->setup_theme();
$this->assertTrue( $show_admin_bar );
}
/**
* Test WP_Customize_Manager::changeset_uuid().
*
* @ticket 30937
* @covers WP_Customize_Manager::changeset_uuid()
*/
function test_changeset_uuid() {
$uuid = wp_generate_uuid4();
$wp_customize = new WP_Customize_Manager( array( 'changeset_uuid' => $uuid ) );
$this->assertEquals( $uuid, $wp_customize->changeset_uuid() );
}
/**
* Test WP_Customize_Manager::wp_loaded().
*
* Ensure that post values are previewed even without being in preview.
*
* @ticket 30937
* @covers WP_Customize_Manager::wp_loaded()
*/
function test_wp_loaded() {
wp_set_current_user( self::$admin_user_id );
$wp_customize = new WP_Customize_Manager();
$title = 'Hello World';
$wp_customize->set_post_value( 'blogname', $title );
$this->assertNotEquals( $title, get_option( 'blogname' ) );
$wp_customize->wp_loaded();
$this->assertFalse( $wp_customize->is_preview() );
$this->assertEquals( $title, $wp_customize->get_setting( 'blogname' )->value() );
$this->assertEquals( $title, get_option( 'blogname' ) );
}
/**
* Test WP_Customize_Manager::find_changeset_post_id().
*
* @ticket 30937
* @covers WP_Customize_Manager::find_changeset_post_id()
*/
function test_find_changeset_post_id() {
$uuid = wp_generate_uuid4();
$post_id = $this->factory()->post->create( array(
'post_name' => $uuid,
'post_type' => 'customize_changeset',
'post_status' => 'auto-draft',
'post_content' => '{}',
) );
$wp_customize = new WP_Customize_Manager();
$this->assertNull( $wp_customize->find_changeset_post_id( wp_generate_uuid4() ) );
$this->assertEquals( $post_id, $wp_customize->find_changeset_post_id( $uuid ) );
}
/**
* Test WP_Customize_Manager::changeset_post_id().
*
* @ticket 30937
* @covers WP_Customize_Manager::changeset_post_id()
*/
function test_changeset_post_id() {
$uuid = wp_generate_uuid4();
$wp_customize = new WP_Customize_Manager( array( 'changeset_uuid' => $uuid ) );
$this->assertNull( $wp_customize->changeset_post_id() );
$uuid = wp_generate_uuid4();
$wp_customize = new WP_Customize_Manager( array( 'changeset_uuid' => $uuid ) );
$post_id = $this->factory()->post->create( array(
'post_name' => $uuid,
'post_type' => 'customize_changeset',
'post_status' => 'auto-draft',
'post_content' => '{}',
) );
$this->assertEquals( $post_id, $wp_customize->changeset_post_id() );
}
/**
* Test WP_Customize_Manager::changeset_data().
*
* @ticket 30937
* @covers WP_Customize_Manager::changeset_data()
*/
function test_changeset_data() {
$uuid = wp_generate_uuid4();
$wp_customize = new WP_Customize_Manager( array( 'changeset_uuid' => $uuid ) );
$this->assertEquals( array(), $wp_customize->changeset_data() );
$uuid = wp_generate_uuid4();
$data = array( 'blogname' => array( 'value' => 'Hello World' ) );
$this->factory()->post->create( array(
'post_name' => $uuid,
'post_type' => 'customize_changeset',
'post_status' => 'auto-draft',
'post_content' => wp_json_encode( $data ),
) );
$wp_customize = new WP_Customize_Manager( array( 'changeset_uuid' => $uuid ) );
$this->assertEquals( $data, $wp_customize->changeset_data() );
}
/**
* Test WP_Customize_Manager::customize_preview_init().
*
* @ticket 30937
* @covers WP_Customize_Manager::customize_preview_init()
*/
function test_customize_preview_init() {
// Test authorized admin user.
wp_set_current_user( self::$admin_user_id );
$did_action_customize_preview_init = did_action( 'customize_preview_init' );
$wp_customize = new WP_Customize_Manager();
$wp_customize->customize_preview_init();
$this->assertEquals( $did_action_customize_preview_init + 1, did_action( 'customize_preview_init' ) );
$this->assertEquals( 10, has_action( 'wp_head', 'wp_no_robots' ) );
$this->assertEquals( 10, has_filter( 'wp_headers', array( $wp_customize, 'filter_iframe_security_headers' ) ) );
$this->assertEquals( 10, has_filter( 'wp_redirect', array( $wp_customize, 'add_state_query_params' ) ) );
$this->assertTrue( wp_script_is( 'customize-preview', 'enqueued' ) );
$this->assertEquals( 10, has_action( 'wp_head', array( $wp_customize, 'customize_preview_loading_style' ) ) );
$this->assertEquals( 20, has_action( 'wp_footer', array( $wp_customize, 'customize_preview_settings' ) ) );
// Test unauthorized user outside preview (no messenger_channel).
wp_set_current_user( self::$subscriber_user_id );
$wp_customize = new WP_Customize_Manager();
$wp_customize->register_controls();
$this->assertNotEmpty( $wp_customize->controls() );
$wp_customize->customize_preview_init();
$this->assertEmpty( $wp_customize->controls() );
// Test unauthorized user inside preview (with messenger_channel).
wp_set_current_user( self::$subscriber_user_id );
$wp_customize = new WP_Customize_Manager( array( 'messenger_channel' => 'preview-0' ) );
$exception = null;
try {
$wp_customize->customize_preview_init();
} catch ( WPDieException $e ) {
$exception = $e;
}
$this->assertNotNull( $exception );
$this->assertContains( 'Unauthorized', $exception->getMessage() );
}
/**
* Test WP_Customize_Manager::filter_iframe_security_headers().
*
* @ticket 30937
* @covers WP_Customize_Manager::filter_iframe_security_headers()
*/
function test_filter_iframe_security_headers() {
$customize_url = admin_url( 'customize.php' );
$wp_customize = new WP_Customize_Manager();
$headers = $wp_customize->filter_iframe_security_headers( array() );
$this->assertArrayHasKey( 'X-Frame-Options', $headers );
$this->assertArrayHasKey( 'Content-Security-Policy', $headers );
$this->assertEquals( "ALLOW-FROM $customize_url", $headers['X-Frame-Options'] );
}
/**
* Test WP_Customize_Manager::add_state_query_params().
*
* @ticket 30937
* @covers WP_Customize_Manager::add_state_query_params()
*/
function test_add_state_query_params() {
$uuid = wp_generate_uuid4();
$messenger_channel = 'preview-0';
$wp_customize = new WP_Customize_Manager( array(
'changeset_uuid' => $uuid,
'messenger_channel' => $messenger_channel,
) );
$url = $wp_customize->add_state_query_params( home_url( '/' ) );
$parsed_url = wp_parse_url( $url );
parse_str( $parsed_url['query'], $query_params );
$this->assertArrayHasKey( 'customize_messenger_channel', $query_params );
$this->assertArrayHasKey( 'customize_changeset_uuid', $query_params );
$this->assertArrayNotHasKey( 'customize_theme', $query_params );
$this->assertEquals( $uuid, $query_params['customize_changeset_uuid'] );
$this->assertEquals( $messenger_channel, $query_params['customize_messenger_channel'] );
$uuid = wp_generate_uuid4();
$wp_customize = new WP_Customize_Manager( array(
'changeset_uuid' => $uuid,
'messenger_channel' => null,
'theme' => 'twentyfifteen',
) );
$url = $wp_customize->add_state_query_params( home_url( '/' ) );
$parsed_url = wp_parse_url( $url );
parse_str( $parsed_url['query'], $query_params );
$this->assertArrayNotHasKey( 'customize_messenger_channel', $query_params );
$this->assertArrayHasKey( 'customize_changeset_uuid', $query_params );
$this->assertArrayHasKey( 'customize_theme', $query_params );
$this->assertEquals( $uuid, $query_params['customize_changeset_uuid'] );
$this->assertEquals( 'twentyfifteen', $query_params['customize_theme'] );
$uuid = wp_generate_uuid4();
$wp_customize = new WP_Customize_Manager( array(
'changeset_uuid' => $uuid,
'messenger_channel' => null,
'theme' => 'twentyfifteen',
) );
$url = $wp_customize->add_state_query_params( 'http://not-allowed.example.com/?q=1' );
$parsed_url = wp_parse_url( $url );
parse_str( $parsed_url['query'], $query_params );
$this->assertArrayNotHasKey( 'customize_messenger_channel', $query_params );
$this->assertArrayNotHasKey( 'customize_changeset_uuid', $query_params );
$this->assertArrayNotHasKey( 'customize_theme', $query_params );
}
/**
* Test WP_Customize_Manager::save_changeset_post().
*
* @ticket 30937
* @covers WP_Customize_Manager::save_changeset_post()
*/
function test_save_changeset_post_without_theme_activation() {
wp_set_current_user( self::$admin_user_id );
$did_action = array(
'customize_save_validation_before' => did_action( 'customize_save_validation_before' ),
'customize_save' => did_action( 'customize_save' ),
'customize_save_after' => did_action( 'customize_save_after' ),
);
$uuid = wp_generate_uuid4();
$manager = new WP_Customize_Manager( array(
'changeset_uuid' => $uuid,
) );
$manager->register_controls();
$manager->set_post_value( 'blogname', 'Changeset Title' );
$manager->set_post_value( 'blogdescription', 'Changeset Tagline' );
$r = $manager->save_changeset_post( array(
'status' => 'auto-draft',
'title' => 'Auto Draft',
'date_gmt' => '2010-01-01 00:00:00',
'data' => array(
'blogname' => array(
'value' => 'Overridden Changeset Title',
),
'blogdescription' => array(
'custom' => 'something',
),
),
) );
$this->assertInternalType( 'array', $r );
$this->assertEquals( $did_action['customize_save_validation_before'] + 1, did_action( 'customize_save_validation_before' ) );
$post_id = $manager->find_changeset_post_id( $uuid );
$this->assertNotNull( $post_id );
$saved_data = json_decode( get_post( $post_id )->post_content, true );
$this->assertEquals( $manager->unsanitized_post_values(), wp_list_pluck( $saved_data, 'value' ) );
$this->assertEquals( 'Overridden Changeset Title', $saved_data['blogname']['value'] );
$this->assertEquals( 'something', $saved_data['blogdescription']['custom'] );
$this->assertEquals( 'Auto Draft', get_post( $post_id )->post_title );
$this->assertEquals( 'auto-draft', get_post( $post_id )->post_status );
$this->assertEquals( '2010-01-01 00:00:00', get_post( $post_id )->post_date_gmt );
$this->assertNotEquals( 'Changeset Title', get_option( 'blogname' ) );
$this->assertArrayHasKey( 'setting_validities', $r );
// Test saving with invalid settings, ensuring transaction blocked.
$previous_saved_data = $saved_data;
$manager->add_setting( 'foo_unauthorized', array(
'capability' => 'do_not_allow',
) );
$manager->add_setting( 'baz_illegal', array(
'validate_callback' => array( $this, 'return_illegal_error' ),
) );
$r = $manager->save_changeset_post( array(
'status' => 'auto-draft',
'data' => array(
'blogname' => array(
'value' => 'OK',
),
'foo_unauthorized' => array(
'value' => 'No',
),
'bar_unknown' => array(
'value' => 'No',
),
'baz_illegal' => array(
'value' => 'No',
),
),
) );
$this->assertInstanceOf( 'WP_Error', $r );
$this->assertEquals( 'transaction_fail', $r->get_error_code() );
$this->assertInternalType( 'array', $r->get_error_data() );
$this->assertArrayHasKey( 'setting_validities', $r->get_error_data() );
$error_data = $r->get_error_data();
$this->assertArrayHasKey( 'blogname', $error_data['setting_validities'] );
$this->assertTrue( $error_data['setting_validities']['blogname'] );
$this->assertArrayHasKey( 'foo_unauthorized', $error_data['setting_validities'] );
$this->assertInstanceOf( 'WP_Error', $error_data['setting_validities']['foo_unauthorized'] );
$this->assertEquals( 'unauthorized', $error_data['setting_validities']['foo_unauthorized']->get_error_code() );
$this->assertArrayHasKey( 'bar_unknown', $error_data['setting_validities'] );
$this->assertInstanceOf( 'WP_Error', $error_data['setting_validities']['bar_unknown'] );
$this->assertEquals( 'unrecognized', $error_data['setting_validities']['bar_unknown']->get_error_code() );
$this->assertArrayHasKey( 'baz_illegal', $error_data['setting_validities'] );
$this->assertInstanceOf( 'WP_Error', $error_data['setting_validities']['baz_illegal'] );
$this->assertEquals( 'illegal', $error_data['setting_validities']['baz_illegal']->get_error_code() );
// Since transactional, ensure no changes have been made.
$this->assertEquals( $previous_saved_data, json_decode( get_post( $post_id )->post_content, true ) );
// Attempt a non-transactional/incremental update.
$manager = new WP_Customize_Manager( array(
'changeset_uuid' => $uuid,
) );
$manager->register_controls(); // That is, register settings.
$r = $manager->save_changeset_post( array(
'status' => null,
'data' => array(
'blogname' => array(
'value' => 'Non-Transactional \o/ <script>unsanitized</script>',
),
'bar_unknown' => array(
'value' => 'No',
),
),
) );
$this->assertInternalType( 'array', $r );
$this->assertArrayHasKey( 'setting_validities', $r );
$this->assertTrue( $r['setting_validities']['blogname'] );
$this->assertInstanceOf( 'WP_Error', $r['setting_validities']['bar_unknown'] );
$saved_data = json_decode( get_post( $post_id )->post_content, true );
$this->assertNotEquals( $previous_saved_data, $saved_data );
$this->assertEquals( 'Non-Transactional \o/ <script>unsanitized</script>', $saved_data['blogname']['value'] );
// Ensure the filter applies.
$customize_changeset_save_data_call_count = $this->customize_changeset_save_data_call_count;
add_filter( 'customize_changeset_save_data', array( $this, 'filter_customize_changeset_save_data' ), 10, 2 );
$manager->save_changeset_post( array(
'status' => null,
'data' => array(
'blogname' => array(
'value' => 'Filtered',
),
),
) );
$this->assertEquals( $customize_changeset_save_data_call_count + 1, $this->customize_changeset_save_data_call_count );
// Publish the changeset.
$manager = new WP_Customize_Manager( array( 'changeset_uuid' => $uuid ) );
$manager->register_controls();
$GLOBALS['wp_customize'] = $manager;
$r = $manager->save_changeset_post( array(
'status' => 'publish',
'data' => array(
'blogname' => array(
'value' => 'Do it live \o/',
),
),
) );
$this->assertInternalType( 'array', $r );
$this->assertEquals( 'Do it live \o/', get_option( 'blogname' ) );
$this->assertEquals( 'trash', get_post_status( $post_id ) ); // Auto-trashed.
// Test revisions.
add_post_type_support( 'customize_changeset', 'revisions' );
$uuid = wp_generate_uuid4();
$manager = new WP_Customize_Manager( array( 'changeset_uuid' => $uuid ) );
$manager->register_controls();
$GLOBALS['wp_customize'] = $manager;
$manager->set_post_value( 'blogname', 'Hello Surface' );
$manager->save_changeset_post( array( 'status' => 'auto-draft' ) );
$manager->set_post_value( 'blogname', 'Hello World' );
$manager->save_changeset_post( array( 'status' => 'draft' ) );
$this->assertTrue( wp_revisions_enabled( get_post( $manager->changeset_post_id() ) ) );
$manager->set_post_value( 'blogname', 'Hello Solar System' );
$manager->save_changeset_post( array( 'status' => 'draft' ) );
$manager->set_post_value( 'blogname', 'Hello Galaxy' );
$manager->save_changeset_post( array( 'status' => 'draft' ) );
$this->assertCount( 3, wp_get_post_revisions( $manager->changeset_post_id() ) );
}
/**
* Call count for customize_changeset_save_data filter.
*
* @var int
*/
protected $customize_changeset_save_data_call_count = 0;
/**
* Filter customize_changeset_save_data.
*
* @param array $data Data.
* @param array $context Context.
* @returns array Data.
*/
function filter_customize_changeset_save_data( $data, $context ) {
$this->customize_changeset_save_data_call_count += 1;
$this->assertInternalType( 'array', $data );
$this->assertInternalType( 'array', $context );
$this->assertArrayHasKey( 'uuid', $context );
$this->assertArrayHasKey( 'title', $context );
$this->assertArrayHasKey( 'status', $context );
$this->assertArrayHasKey( 'date_gmt', $context );
$this->assertArrayHasKey( 'post_id', $context );
$this->assertArrayHasKey( 'previous_data', $context );
$this->assertArrayHasKey( 'manager', $context );
return $data;
}
/**
* Return illegal error.
*
* @return WP_Error Error.
*/
function return_illegal_error() {
return new WP_Error( 'illegal' );
}
/**
* Test WP_Customize_Manager::save_changeset_post().
*
* @ticket 30937
* @covers WP_Customize_Manager::save_changeset_post()
* @covers WP_Customize_Manager::update_stashed_theme_mod_settings()
*/
function test_save_changeset_post_with_theme_activation() {
wp_set_current_user( self::$admin_user_id );
$stashed_theme_mods = array(
'twentyfifteen' => array(
'background_color' => array(
'value' => '#123456',
),
),
);
update_option( 'customize_stashed_theme_mods', $stashed_theme_mods );
$uuid = wp_generate_uuid4();
$manager = new WP_Customize_Manager( array(
'changeset_uuid' => $uuid,
'theme' => 'twentyfifteen',
) );
$manager->register_controls();
$GLOBALS['wp_customize'] = $manager;
$manager->set_post_value( 'blogname', 'Hello 2015' );
$post_values = $manager->unsanitized_post_values();
$manager->save_changeset_post( array( 'status' => 'publish' ) ); // Activate.
$this->assertEquals( '#123456', $post_values['background_color'] );
$this->assertEquals( 'twentyfifteen', get_stylesheet() );
$this->assertEquals( 'Hello 2015', get_option( 'blogname' ) );
}
/**
* Test WP_Customize_Manager::is_cross_domain().
*
* @ticket 30937
* @covers WP_Customize_Manager::is_cross_domain()
*/
function test_is_cross_domain() {
$wp_customize = new WP_Customize_Manager();
update_option( 'home', 'http://example.com' );
update_option( 'siteurl', 'http://example.com' );
$this->assertFalse( $wp_customize->is_cross_domain() );
update_option( 'home', 'http://example.com' );
update_option( 'siteurl', 'https://admin.example.com' );
$this->assertTrue( $wp_customize->is_cross_domain() );
}
/**
* Test WP_Customize_Manager::get_allowed_urls().
*
* @ticket 30937
* @covers WP_Customize_Manager::get_allowed_urls()
*/
function test_get_allowed_urls() {
$wp_customize = new WP_Customize_Manager();
$this->assertFalse( is_ssl() );
$this->assertFalse( $wp_customize->is_cross_domain() );
$allowed = $wp_customize->get_allowed_urls();
$this->assertEquals( $allowed, array( home_url( '/', 'http' ) ) );
add_filter( 'customize_allowed_urls', array( $this, 'filter_customize_allowed_urls' ) );
$allowed = $wp_customize->get_allowed_urls();
$this->assertEqualSets( $allowed, array( 'http://headless.example.com/', home_url( '/', 'http' ) ) );
}
/**
* Callback for customize_allowed_urls filter.
*
* @param array $urls URLs.
* @return array URLs.
*/
function filter_customize_allowed_urls( $urls ) {
$urls[] = 'http://headless.example.com/';
return $urls;
}
/**
* Test WP_Customize_Manager::doing_ajax().
*
@@ -90,7 +717,8 @@ class Tests_WP_Customize_Manager extends WP_UnitTestCase {
*
* @ticket 30988
*/
function test_unsanitized_post_values() {
function test_unsanitized_post_values_from_input() {
wp_set_current_user( self::$admin_user_id );
$manager = $this->manager;
$customized = array(
@@ -100,6 +728,117 @@ class Tests_WP_Customize_Manager extends WP_UnitTestCase {
$_POST['customized'] = wp_slash( wp_json_encode( $customized ) );
$post_values = $manager->unsanitized_post_values();
$this->assertEquals( $customized, $post_values );
$this->assertEmpty( $manager->unsanitized_post_values( array( 'exclude_post_data' => true ) ) );
$manager->set_post_value( 'foo', 'BAR' );
$post_values = $manager->unsanitized_post_values();
$this->assertEquals( 'BAR', $post_values['foo'] );
$this->assertEmpty( $manager->unsanitized_post_values( array( 'exclude_post_data' => true ) ) );
// If user is unprivileged, the post data is ignored.
wp_set_current_user( 0 );
$this->assertEmpty( $manager->unsanitized_post_values() );
}
/**
* Test WP_Customize_Manager::unsanitized_post_values().
*
* @ticket 30937
* @covers WP_Customize_Manager::unsanitized_post_values()
*/
function test_unsanitized_post_values_with_changeset_and_stashed_theme_mods() {
wp_set_current_user( self::$admin_user_id );
$stashed_theme_mods = array(
'twentyfifteen' => array(
'background_color' => array(
'value' => '#000000',
),
),
);
$stashed_theme_mods[ get_stylesheet() ] = array(
'background_color' => array(
'value' => '#FFFFFF',
),
);
update_option( 'customize_stashed_theme_mods', $stashed_theme_mods );
$post_values = array(
'blogdescription' => 'Post Input Tagline',
);
$_POST['customized'] = wp_slash( wp_json_encode( $post_values ) );
$uuid = wp_generate_uuid4();
$changeset_data = array(
'blogname' => array(
'value' => 'Changeset Title',
),
'blogdescription' => array(
'value' => 'Changeset Tagline',
),
);
$this->factory()->post->create( array(
'post_type' => 'customize_changeset',
'post_status' => 'auto-draft',
'post_name' => $uuid,
'post_content' => wp_json_encode( $changeset_data ),
) );
$manager = new WP_Customize_Manager( array(
'changeset_uuid' => $uuid,
) );
$this->assertTrue( $manager->is_theme_active() );
$this->assertArrayNotHasKey( 'background_color', $manager->unsanitized_post_values() );
$this->assertEquals(
array(
'blogname' => 'Changeset Title',
'blogdescription' => 'Post Input Tagline',
),
$manager->unsanitized_post_values()
);
$this->assertEquals(
array(
'blogdescription' => 'Post Input Tagline',
),
$manager->unsanitized_post_values( array( 'exclude_changeset' => true ) )
);
$manager->set_post_value( 'blogdescription', 'Post Override Tagline' );
$this->assertEquals(
array(
'blogname' => 'Changeset Title',
'blogdescription' => 'Post Override Tagline',
),
$manager->unsanitized_post_values()
);
$this->assertEquals(
array(
'blogname' => 'Changeset Title',
'blogdescription' => 'Changeset Tagline',
),
$manager->unsanitized_post_values( array( 'exclude_post_data' => true ) )
);
$this->assertEmpty( $manager->unsanitized_post_values( array( 'exclude_post_data' => true, 'exclude_changeset' => true ) ) );
// Test unstashing theme mods.
$manager = new WP_Customize_Manager( array(
'changeset_uuid' => $uuid,
'theme' => 'twentyfifteen',
) );
$this->assertFalse( $manager->is_theme_active() );
$values = $manager->unsanitized_post_values( array( 'exclude_post_data' => true, 'exclude_changeset' => true ) );
$this->assertNotEmpty( $values );
$this->assertArrayHasKey( 'background_color', $values );
$this->assertEquals( '#000000', $values['background_color'] );
$values = $manager->unsanitized_post_values( array( 'exclude_post_data' => false, 'exclude_changeset' => false ) );
$this->assertArrayHasKey( 'background_color', $values );
$this->assertArrayHasKey( 'blogname', $values );
$this->assertArrayHasKey( 'blogdescription', $values );
}
/**
@@ -108,6 +847,7 @@ class Tests_WP_Customize_Manager extends WP_UnitTestCase {
* @ticket 30988
*/
function test_post_value() {
wp_set_current_user( self::$admin_user_id );
$posted_settings = array(
'foo' => 'OOF',
);
@@ -131,6 +871,7 @@ class Tests_WP_Customize_Manager extends WP_UnitTestCase {
* @ticket 34893
*/
function test_invalid_post_value() {
wp_set_current_user( self::$admin_user_id );
$default_value = 'foo_default';
$setting = $this->manager->add_setting( 'foo', array(
'validate_callback' => array( $this, 'filter_customize_validate_foo' ),
@@ -196,6 +937,7 @@ class Tests_WP_Customize_Manager extends WP_UnitTestCase {
* @ticket 37247
*/
function test_post_value_validation_sanitization_order() {
wp_set_current_user( self::$admin_user_id );
$default_value = '0';
$setting = $this->manager->add_setting( 'numeric', array(
'validate_callback' => array( $this, 'filter_customize_validate_numeric' ),
@@ -240,6 +982,7 @@ class Tests_WP_Customize_Manager extends WP_UnitTestCase {
* @see WP_Customize_Manager::validate_setting_values()
*/
function test_validate_setting_values() {
wp_set_current_user( self::$admin_user_id );
$setting = $this->manager->add_setting( 'foo', array(
'validate_callback' => array( $this, 'filter_customize_validate_foo' ),
'sanitize_callback' => array( $this, 'filter_customize_sanitize_foo' ),
@@ -304,6 +1047,40 @@ class Tests_WP_Customize_Manager extends WP_UnitTestCase {
$this->assertEquals( 'minlength', $validity->get_error_code() );
}
/**
* Test WP_Customize_Manager::validate_setting_values().
*
* @ticket 30937
* @covers WP_Customize_Manager::validate_setting_values()
*/
function test_validate_setting_values_args() {
wp_set_current_user( self::$admin_user_id );
$this->manager->register_controls();
$validities = $this->manager->validate_setting_values( array( 'unknown' => 'X' ) );
$this->assertEmpty( $validities );
$validities = $this->manager->validate_setting_values( array( 'unknown' => 'X' ), array( 'validate_existence' => false ) );
$this->assertEmpty( $validities );
$validities = $this->manager->validate_setting_values( array( 'unknown' => 'X' ), array( 'validate_existence' => true ) );
$this->assertNotEmpty( $validities );
$this->assertArrayHasKey( 'unknown', $validities );
$error = $validities['unknown'];
$this->assertInstanceOf( 'WP_Error', $error );
$this->assertEquals( 'unrecognized', $error->get_error_code() );
$this->manager->get_setting( 'blogname' )->capability = 'do_not_allow';
$validities = $this->manager->validate_setting_values( array( 'blogname' => 'X' ), array( 'validate_capability' => false ) );
$this->assertArrayHasKey( 'blogname', $validities );
$this->assertTrue( $validities['blogname'] );
$validities = $this->manager->validate_setting_values( array( 'blogname' => 'X' ), array( 'validate_capability' => true ) );
$this->assertArrayHasKey( 'blogname', $validities );
$error = $validities['blogname'];
$this->assertInstanceOf( 'WP_Error', $error );
$this->assertEquals( 'unauthorized', $error->get_error_code() );
}
/**
* Add a length constraint to a setting.
*
@@ -328,6 +1105,7 @@ class Tests_WP_Customize_Manager extends WP_UnitTestCase {
* @ticket 37247
*/
function test_validate_setting_values_validation_sanitization_order() {
wp_set_current_user( self::$admin_user_id );
$setting = $this->manager->add_setting( 'numeric', array(
'validate_callback' => array( $this, 'filter_customize_validate_numeric' ),
'sanitize_callback' => array( $this, 'filter_customize_sanitize_numeric' ),
@@ -369,6 +1147,7 @@ class Tests_WP_Customize_Manager extends WP_UnitTestCase {
* @see WP_Customize_Manager::set_post_value()
*/
function test_set_post_value() {
wp_set_current_user( self::$admin_user_id );
$this->manager->add_setting( 'foo', array(
'sanitize_callback' => array( $this, 'sanitize_foo_for_test_set_post_value' ),
) );
@@ -473,7 +1252,7 @@ class Tests_WP_Customize_Manager extends WP_UnitTestCase {
}
$this->assertFalse( $this->manager->has_published_pages() );
wp_set_current_user( $this->factory()->user->create( array( 'role' => 'editor' ) ) );
wp_set_current_user( self::$admin_user_id );
$this->manager->nav_menus->customize_register();
$setting_id = 'nav_menus_created_posts';
$setting = $this->manager->get_setting( $setting_id );
@@ -492,6 +1271,7 @@ class Tests_WP_Customize_Manager extends WP_UnitTestCase {
* @ticket 30936
*/
function test_register_dynamic_settings() {
wp_set_current_user( self::$admin_user_id );
$posted_settings = array(
'foo' => 'OOF',
'bar' => 'RAB',
@@ -591,7 +1371,7 @@ class Tests_WP_Customize_Manager extends WP_UnitTestCase {
wp_set_current_user( self::factory()->user->create( array( 'role' => 'author' ) ) );
$this->assertEquals( home_url( '/' ), $this->manager->get_return_url() );
wp_set_current_user( self::factory()->user->create( array( 'role' => 'administrator' ) ) );
wp_set_current_user( self::$admin_user_id );
$this->assertTrue( current_user_can( 'edit_theme_options' ) );
$this->assertEquals( home_url( '/' ), $this->manager->get_return_url() );
@@ -684,7 +1464,7 @@ class Tests_WP_Customize_Manager extends WP_UnitTestCase {
* @see WP_Customize_Manager::customize_pane_settings()
*/
function test_customize_pane_settings() {
wp_set_current_user( self::factory()->user->create( array( 'role' => 'administrator' ) ) );
wp_set_current_user( self::$admin_user_id );
$this->manager->register_controls();
$this->manager->prepare_controls();
$autofocus = array( 'control' => 'blogname' );
@@ -706,7 +1486,7 @@ class Tests_WP_Customize_Manager extends WP_UnitTestCase {
$data = json_decode( $json, true );
$this->assertNotEmpty( $data );
$this->assertEqualSets( array( 'theme', 'url', 'browser', 'panels', 'sections', 'nonce', 'autofocus', 'documentTitleTmpl', 'previewableDevices' ), array_keys( $data ) );
$this->assertEqualSets( array( 'theme', 'url', 'browser', 'panels', 'sections', 'nonce', 'autofocus', 'documentTitleTmpl', 'previewableDevices', 'changeset', 'timeouts' ), array_keys( $data ) );
$this->assertEquals( $autofocus, $data['autofocus'] );
$this->assertArrayHasKey( 'save', $data['nonce'] );
$this->assertArrayHasKey( 'preview', $data['nonce'] );
@@ -718,7 +1498,7 @@ class Tests_WP_Customize_Manager extends WP_UnitTestCase {
* @see WP_Customize_Manager::customize_preview_settings()
*/
function test_customize_preview_settings() {
wp_set_current_user( self::factory()->user->create( array( 'role' => 'administrator' ) ) );
wp_set_current_user( self::$admin_user_id );
$this->manager->register_controls();
$this->manager->prepare_controls();
$this->manager->set_post_value( 'foo', 'bar' );
@@ -740,9 +1520,10 @@ class Tests_WP_Customize_Manager extends WP_UnitTestCase {
$this->assertArrayHasKey( 'settingValidities', $settings );
$this->assertArrayHasKey( 'nonce', $settings );
$this->assertArrayHasKey( '_dirty', $settings );
$this->assertArrayHasKey( 'timeouts', $settings );
$this->assertArrayHasKey( 'changeset', $settings );
$this->assertArrayHasKey( 'preview', $settings['nonce'] );
$this->assertEquals( array( 'foo' ), $settings['_dirty'] );
}
/**
@@ -814,7 +1595,7 @@ class Tests_WP_Customize_Manager extends WP_UnitTestCase {
$manager = new WP_Customize_Manager();
$manager->register_controls();
$section_id = 'foo-section';
wp_set_current_user( self::factory()->user->create( array( 'role' => 'administrator' ) ) );
wp_set_current_user( self::$admin_user_id );
$manager->add_section( $section_id, array(
'title' => 'Section',
'priority' => 1,
@@ -845,7 +1626,7 @@ class Tests_WP_Customize_Manager extends WP_UnitTestCase {
*/
function test_add_section_return_instance() {
$manager = new WP_Customize_Manager();
wp_set_current_user( self::factory()->user->create( array( 'role' => 'administrator' ) ) );
wp_set_current_user( self::$admin_user_id );
$section_id = 'foo-section';
$result_section = $manager->add_section( $section_id, array(
@@ -872,7 +1653,7 @@ class Tests_WP_Customize_Manager extends WP_UnitTestCase {
*/
function test_add_setting_return_instance() {
$manager = new WP_Customize_Manager();
wp_set_current_user( self::factory()->user->create( array( 'role' => 'administrator' ) ) );
wp_set_current_user( self::$admin_user_id );
$setting_id = 'foo-setting';
$result_setting = $manager->add_setting( $setting_id );
@@ -943,7 +1724,7 @@ class Tests_WP_Customize_Manager extends WP_UnitTestCase {
*/
function test_add_panel_return_instance() {
$manager = new WP_Customize_Manager();
wp_set_current_user( self::factory()->user->create( array( 'role' => 'administrator' ) ) );
wp_set_current_user( self::$admin_user_id );
$panel_id = 'foo-panel';
$result_panel = $manager->add_panel( $panel_id, array(
@@ -970,7 +1751,7 @@ class Tests_WP_Customize_Manager extends WP_UnitTestCase {
function test_add_control_return_instance() {
$manager = new WP_Customize_Manager();
$section_id = 'foo-section';
wp_set_current_user( self::factory()->user->create( array( 'role' => 'administrator' ) ) );
wp_set_current_user( self::$admin_user_id );
$manager->add_section( $section_id, array(
'title' => 'Section',
'priority' => 1,

View File

@@ -139,25 +139,6 @@ class Test_WP_Customize_Selective_Refresh_Ajax extends WP_UnitTestCase {
$this->do_customize_boot_actions();
}
/**
* Make sure that the Customizer "signature" is not included in partial render responses.
*
* @see WP_Customize_Selective_Refresh::handle_render_partials_request()
*/
function test_handle_render_partials_request_removes_customize_signature() {
$this->setup_valid_render_partials_request_environment();
$this->assertTrue( is_customize_preview() );
$this->assertEquals( 1000, has_action( 'shutdown', array( $this->wp_customize, 'customize_preview_signature' ) ) );
ob_start();
try {
$this->selective_refresh->handle_render_partials_request();
} catch ( WPDieException $e ) {
unset( $e );
}
ob_end_clean();
$this->assertFalse( has_action( 'shutdown', array( $this->wp_customize, 'customize_preview_signature' ) ) );
}
/**
* Test WP_Customize_Selective_Refresh::handle_render_partials_request() for an unrecognized partial.
*

View File

@@ -97,6 +97,7 @@ class Tests_WP_Customize_Setting extends WP_UnitTestCase {
* @see WP_Customize_Setting::value()
*/
function test_preview_standard_types_non_multidimensional() {
wp_set_current_user( $this->factory()->user->create( array( 'role' => 'administrator' ) ) );
$_POST['customized'] = wp_slash( wp_json_encode( $this->post_data_overrides ) );
// Try non-multidimensional settings.
@@ -175,6 +176,7 @@ class Tests_WP_Customize_Setting extends WP_UnitTestCase {
* @see WP_Customize_Setting::value()
*/
function test_preview_standard_types_multidimensional() {
wp_set_current_user( $this->factory()->user->create( array( 'role' => 'administrator' ) ) );
$_POST['customized'] = wp_slash( wp_json_encode( $this->post_data_overrides ) );
foreach ( $this->standard_type_configs as $type => $type_options ) {
@@ -314,6 +316,7 @@ class Tests_WP_Customize_Setting extends WP_UnitTestCase {
* @see WP_Customize_Setting::preview()
*/
function test_preview_custom_type() {
wp_set_current_user( $this->factory()->user->create( array( 'role' => 'administrator' ) ) );
$type = 'custom_type';
$post_data_overrides = array(
"unset_{$type}_with_post_value" => "unset_{$type}_without_post_value\\o/",
@@ -478,6 +481,7 @@ class Tests_WP_Customize_Setting extends WP_UnitTestCase {
* @ticket 31428
*/
function test_is_current_blog_previewed() {
wp_set_current_user( $this->factory()->user->create( array( 'role' => 'administrator' ) ) );
$type = 'option';
$name = 'blogname';
$post_value = __FUNCTION__;
@@ -502,6 +506,7 @@ class Tests_WP_Customize_Setting extends WP_UnitTestCase {
$this->markTestSkipped( 'Cannot test WP_Customize_Setting::is_current_blog_previewed() with switch_to_blog() if not on multisite.' );
}
wp_set_current_user( self::factory()->user->create( array( 'role' => 'administrator' ) ) );
$type = 'option';
$name = 'blogdescription';
$post_value = __FUNCTION__;
@@ -647,6 +652,7 @@ class Tests_WP_Customize_Setting extends WP_UnitTestCase {
* @ticket 37294
*/
public function test_multidimensional_value_when_previewed() {
wp_set_current_user( $this->factory()->user->create( array( 'role' => 'administrator' ) ) );
WP_Customize_Setting::reset_aggregated_multidimensionals();
$initial_value = 456;

View File

@@ -880,4 +880,22 @@ class Tests_Functions extends WP_UnitTestCase {
$this->assertSame( false, $raised_limit );
$this->assertEquals( WP_MAX_MEMORY_LIMIT, $ini_limit_after );
}
/**
* Tests wp_generate_uuid4().
*
* @covers wp_generate_uuid4()
* @ticket 38164
*/
function test_wp_generate_uuid4() {
$uuids = array();
for ( $i = 0; $i < 20; $i += 1 ) {
$uuid = wp_generate_uuid4();
$this->assertRegExp( '/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/', $uuid );
$uuids[] = $uuid;
}
$unique_uuids = array_unique( $uuids );
$this->assertEquals( $uuids, $unique_uuids );
}
}

View File

@@ -1240,4 +1240,50 @@ class Tests_Post extends WP_UnitTestCase {
$this->assertEquals( 0, get_post( $page_id )->post_parent );
}
/**
* Test ensuring that the post_name (UUID) is preserved when wp_insert_post()/wp_update_post() is called.
*
* @see _wp_customize_changeset_filter_insert_post_data()
* @ticket 30937
*/
function test_wp_insert_post_for_customize_changeset_should_not_drop_post_name() {
$this->assertEquals( 10, has_filter( 'wp_insert_post_data', '_wp_customize_changeset_filter_insert_post_data' ) );
$changeset_data = array(
'blogname' => array(
'value' => 'Hello World',
),
);
wp_set_current_user( $this->factory()->user->create( array( 'role' => 'contributor' ) ) );
$uuid = wp_generate_uuid4();
$post_id = wp_insert_post( array(
'post_type' => 'customize_changeset',
'post_name' => strtoupper( $uuid ),
'post_content' => wp_json_encode( $changeset_data ),
) );
$this->assertEquals( $uuid, get_post( $post_id )->post_name, 'Expected lower-case UUID4 to be inserted.' );
$this->assertEquals( $changeset_data, json_decode( get_post( $post_id )->post_content, true ) );
$changeset_data['blogname']['value'] = 'Hola Mundo';
wp_update_post( array(
'ID' => $post_id,
'post_status' => 'draft',
'post_content' => wp_json_encode( $changeset_data ),
) );
$this->assertEquals( $uuid, get_post( $post_id )->post_name, 'Expected post_name to not have been dropped for drafts.' );
$this->assertEquals( $changeset_data, json_decode( get_post( $post_id )->post_content, true ) );
$changeset_data['blogname']['value'] = 'Hallo Welt';
wp_update_post( array(
'ID' => $post_id,
'post_status' => 'pending',
'post_content' => wp_json_encode( $changeset_data ),
) );
$this->assertEquals( $uuid, get_post( $post_id )->post_name, 'Expected post_name to not have been dropped for pending.' );
$this->assertEquals( $changeset_data, json_decode( get_post( $post_id )->post_content, true ) );
}
}

View File

@@ -147,6 +147,17 @@ window._wpCustomizeSettings = {
'mobile': {
'label': 'Enter mobile preview mode'
}
},
changeset: {
status: '',
uuid: '0c674ff4-c159-4e7a-beb4-cb830ae73979'
},
timeouts: {
windowRefresh: 250,
changesetAutoSave: 60000,
keepAliveCheck: 2500,
reflowPaneContents: 100,
previewFrameSensitivity: 2000
}
};
window._wpCustomizeControlsL10n = {};

View File

@@ -315,6 +315,10 @@
</li>
</script>
<div hidden>
<div id="customize-preview"></div>
</div>
<div hidden>
<div id="available-menu-items" class="accordion-container">
<div class="customize-section-title">

View File

@@ -184,4 +184,23 @@ jQuery( function( $ ) {
assert.equal( 'error', notification.type );
assert.equal( null, notification.data );
} );
module( 'Customize Base: utils.parseQueryString' );
test( 'wp.customize.utils.parseQueryString works', function( assert ) {
var queryParams;
queryParams = wp.customize.utils.parseQueryString( 'a=1&b=2' );
assert.ok( _.isEqual( queryParams, { a: '1', b: '2' } ) );
queryParams = wp.customize.utils.parseQueryString( 'a+b=1&b=Hello%20World' );
assert.ok( _.isEqual( queryParams, { 'a_b': '1', b: 'Hello World' } ) );
queryParams = wp.customize.utils.parseQueryString( 'a%20b=1&b=Hello+World' );
assert.ok( _.isEqual( queryParams, { 'a_b': '1', b: 'Hello World' } ) );
queryParams = wp.customize.utils.parseQueryString( 'a=1&b' );
assert.ok( _.isEqual( queryParams, { 'a': '1', b: null } ) );
queryParams = wp.customize.utils.parseQueryString( 'a=1&b=' );
assert.ok( _.isEqual( queryParams, { 'a': '1', b: '' } ) );
} );
});

View File

@@ -1,4 +1,4 @@
/* global wp, test, ok, equal, module */
/* global JSON, wp, test, ok, equal, module */
wp.customize.settingConstructor.abbreviation = wp.customize.Setting.extend({
validate: function( value ) {
@@ -558,4 +558,74 @@ jQuery( window ).load( function (){
equal( 1, controlsForSettings['fixture-setting'].length );
equal( wp.customize.control( controlId ), controlsForSettings['fixture-setting'][0] );
} );
module( 'Customize Controls wp.customize.dirtyValues' );
test( 'dirtyValues() returns expected values', function() {
wp.customize.each( function( setting ) {
setting._dirty = false;
} );
ok( _.isEmpty( wp.customize.dirtyValues() ) );
ok( _.isEmpty( wp.customize.dirtyValues( { unsaved: false } ) ) );
wp.customize( 'fixture-setting' )._dirty = true;
ok( ! _.isEmpty( wp.customize.dirtyValues() ) );
ok( _.isEmpty( wp.customize.dirtyValues( { unsaved: true } ) ) );
wp.customize( 'fixture-setting' ).set( 'Modified' );
ok( ! _.isEmpty( wp.customize.dirtyValues() ) );
ok( ! _.isEmpty( wp.customize.dirtyValues( { unsaved: true } ) ) );
equal( 'Modified', wp.customize.dirtyValues()['fixture-setting'] );
} );
module( 'Customize Controls: wp.customize.requestChangesetUpdate()' );
test( 'requestChangesetUpdate makes request and returns promise', function( assert ) {
var request, originalBeforeSetup = jQuery.ajaxSettings.beforeSend;
jQuery.ajaxSetup( {
beforeSend: function( e, data ) {
var queryParams, changesetData;
queryParams = wp.customize.utils.parseQueryString( data.data );
assert.equal( 'customize_save', queryParams.action );
assert.ok( ! _.isUndefined( queryParams.customize_changeset_data ) );
assert.ok( ! _.isUndefined( queryParams.nonce ) );
assert.ok( ! _.isUndefined( queryParams.customize_theme ) );
assert.equal( wp.customize.settings.changeset.uuid, queryParams.customize_changeset_uuid );
assert.equal( 'on', queryParams.wp_customize );
changesetData = JSON.parse( queryParams.customize_changeset_data );
assert.ok( ! _.isUndefined( changesetData.additionalSetting ) );
assert.ok( ! _.isUndefined( changesetData['fixture-setting'] ) );
assert.equal( 'additionalValue', changesetData.additionalSetting.value );
assert.equal( 'requestChangesetUpdate', changesetData['fixture-setting'].value );
// Prevent Ajax request from completing.
return false;
}
} );
wp.customize.each( function( setting ) {
setting._dirty = false;
} );
request = wp.customize.requestChangesetUpdate();
assert.equal( 'resolved', request.state());
request.done( function( data ) {
assert.ok( _.isEqual( {}, data ) );
} );
wp.customize( 'fixture-setting' ).set( 'requestChangesetUpdate' );
request = wp.customize.requestChangesetUpdate( {
additionalSetting: {
value: 'additionalValue'
}
} );
request.always( function( data ) {
assert.equal( 'canceled', data.statusText );
jQuery.ajaxSetup( { beforeSend: originalBeforeSetup } );
} );
} );
});