Customize: Extend changesets to support autosave revisions with restoration notifications, and introduce a new default linear history mode for saved changesets (with a filter for opt-in to changeset branching).

* Autosaved changes made on top of `auto-draft` changesets get written on top of the `auto-draft` itself, similar to how autosaves for posts will overwrite post drafts.
* Autosaved changes made to saved changesets (e.g. `draft`, `future`) will be placed into an autosave revision for that changeset and that user.
* Opening the Customizer will now prompt the user to restore their most recent auto-draft changeset; if notification is dismissed or ignored then the auto-draft will be marked as dismissed and will not be prompted to user in a notification again.
* Customizer will no longer automatically supply the `changeset_uuid` param in the `customize.php` URL when branching changesets are not active.
* If user closes Customizer explicitly via clicking on X link, then autosave auto-draft/autosave will be dismissed so as to not be prompted again.
* If there is a changeset already saved as a `draft` or `future` (UI is forthcoming) then this changeset will now be autoloaded for the user to keep making additional changes. This is the linear model for changesets.
* To restore the previous behavior of the Customizer where each session started a new changeset, regardless of whether or not there was an existing changeset saved, there is now a `customize_changeset_branching` hook which can be filtered to return `true`.
* `wp.customize.requestChangesetUpdate()` now supports a second with options including `autosave`, `title`, and `date`.
* The window `blur` event for `customize.php` has been replaced with a `visibilitychange` event to reduce autosave requests when clicking into preview window.
* Adds `autosaved` and `branching` args to `WP_Customize_Manager`.
* The `changeset_uuid` param for `WP_Customize_Manager` is extended to recognize a `false` value which causes the Customizer to defer identifying the UUID until `after_setup_theme` in the new `WP_Customize_Manager::establish_loaded_changeset()` method.
* A new `customize_autosaved` query parameter can now be supplied which is passed into the `autosaved` arg in `WP_Customize_Manager`; this option is an opt-in to source data from the autosave revision, allowing a user to restore autosaved changes.

Props westonruter, dlh, sayedwp, JoshuaWold, melchoyce.
See #39896.

Built from https://develop.svn.wordpress.org/trunk@41597


git-svn-id: http://core.svn.wordpress.org/trunk@41430 1a063a9b-81f0-0310-95a4-ce76da25c4cd
This commit is contained in:
Weston Ruter 2017-09-26 07:38:45 +00:00
parent 85712eb281
commit 1a7616ad54
8 changed files with 657 additions and 69 deletions

View File

@ -1,4 +1,4 @@
/* global _wpCustomizeHeader, _wpCustomizeBackground, _wpMediaViewsL10n, MediaElementPlayer, console */
/* global _wpCustomizeHeader, _wpCustomizeBackground, _wpMediaViewsL10n, MediaElementPlayer, console, confirm */
(function( exports, $ ){
var Container, focus, normalizedTransitionendEventName, api = wp.customize;
@ -355,14 +355,24 @@
* @since 4.7.0
* @access public
*
* @param {object} [changes] Mapping of setting IDs to setting params each normally including a value property, or mapping to null.
* If not provided, then the changes will still be obtained from unsaved dirty settings.
* @param {object} [changes] - Mapping of setting IDs to setting params each normally including a value property, or mapping to null.
* If not provided, then the changes will still be obtained from unsaved dirty settings.
* @param {object} [args] - Additional options for the save request.
* @param {boolean} [args.autosave=false] - Whether changes will be stored in autosave revision if the changeset has been promoted from an auto-draft.
* @param {string} [args.title] - Title to update in the changeset. Optional.
* @param {string} [args.date] - Date to update in the changeset. Optional.
* @returns {jQuery.Promise} Promise resolving with the response data.
*/
api.requestChangesetUpdate = function requestChangesetUpdate( changes ) {
var deferred, request, submittedChanges = {}, data;
api.requestChangesetUpdate = function requestChangesetUpdate( changes, args ) {
var deferred, request, submittedChanges = {}, data, submittedArgs;
deferred = new $.Deferred();
submittedArgs = _.extend( {
title: null,
date: null,
autosave: false
}, args );
if ( changes ) {
_.extend( submittedChanges, changes );
}
@ -379,20 +389,30 @@
} );
// Short-circuit when there are no pending changes.
if ( _.isEmpty( submittedChanges ) ) {
if ( _.isEmpty( submittedChanges ) && null === submittedArgs.title && null === submittedArgs.date ) {
deferred.resolve( {} );
return deferred.promise();
}
// Allow plugins to attach additional params to the settings.
api.trigger( 'changeset-save', submittedChanges, submittedArgs );
// A status would cause a revision to be made, and for this wp.customize.previewer.save() should be used. Status is also disallowed for revisions regardless.
if ( submittedArgs.status ) {
return deferred.reject( { code: 'illegal_status_in_changeset_update' } ).promise();
}
// Dates not beung allowed for revisions are is a technical limitation of post revisions.
if ( submittedArgs.date && submittedArgs.autosave ) {
return deferred.reject( { code: 'illegal_autosave_with_date_gmt' } ).promise();
}
// Make sure that publishing a changeset waits for all changeset update requests to complete.
api.state( 'processing' ).set( api.state( 'processing' ).get() + 1 );
deferred.always( function() {
api.state( 'processing' ).set( api.state( 'processing' ).get() - 1 );
} );
// Allow plugins to attach additional params to the settings.
api.trigger( 'changeset-save', submittedChanges );
// Ensure that if any plugins add data to save requests by extending query() that they get included here.
data = api.previewer.query( { excludeCustomizedSaved: true } );
delete data.customized; // Being sent in customize_changeset_data instead.
@ -401,6 +421,15 @@
customize_theme: api.settings.theme.stylesheet,
customize_changeset_data: JSON.stringify( submittedChanges )
} );
if ( null !== submittedArgs.title ) {
data.customize_changeset_title = submittedArgs.title;
}
if ( null !== submittedArgs.date ) {
data.customize_changeset_date = submittedArgs.date;
}
if ( false !== submittedArgs.autosave ) {
data.customize_changeset_autosave = 'true';
}
request = wp.ajax.post( 'customize_save', data );
@ -1705,9 +1734,15 @@
api.state( 'processing' ).unbind( onceProcessingComplete );
request = api.requestChangesetUpdate();
request = api.requestChangesetUpdate( {}, { autosave: true } );
request.done( function() {
$( window ).off( 'beforeunload.customize-confirm' );
// Include autosaved param to load autosave revision without prompting user to restore it.
if ( ! api.state( 'saved' ).get() ) {
urlParser.search += '&customize_autosaved=on';
}
top.location.href = urlParser.href;
deferred.resolve();
} );
@ -4024,6 +4059,9 @@
customize_messenger_channel: previewFrame.query.customize_messenger_channel
}
);
if ( ! api.state( 'saved' ).get() ) {
params.customize_autosaved = 'on';
}
urlParser.search = $.param( params );
previewFrame.iframe = $( '<iframe />', {
@ -4260,6 +4298,7 @@
delete queryParams.customize_changeset_uuid;
delete queryParams.customize_theme;
delete queryParams.customize_messenger_channel;
delete queryParams.customize_autosaved;
if ( _.isEmpty( queryParams ) ) {
urlParser.search = '';
} else {
@ -4884,6 +4923,9 @@
nonce: this.nonce.preview,
customize_changeset_uuid: api.settings.changeset.uuid
};
if ( ! api.state( 'saved' ).get() ) {
queryVars.customize_autosaved = 'on';
}
/*
* Exclude customized data if requested especially for calls to requestChangesetUpdate.
@ -5098,6 +5140,9 @@
parent.send( 'changeset-uuid', api.settings.changeset.uuid );
}
// Prevent subsequent requestChangesetUpdate() calls from including the settings that have been saved.
api._lastSavedRevision = Math.max( latestRevision, api._lastSavedRevision );
if ( response.setting_validities ) {
api._handleSettingValidities( {
settingValidities: response.setting_validities,
@ -5315,10 +5360,18 @@
api.bind( 'change', function() {
if ( state( 'saved' ).get() ) {
state( 'saved' ).set( false );
populateChangesetUuidParam( true );
}
});
// Populate changeset UUID param when state becomes dirty.
if ( api.settings.changeset.branching ) {
saved.bind( function( isSaved ) {
if ( ! isSaved ) {
populateChangesetUuidParam( true );
}
});
}
saving.bind( function( isSaving ) {
body.toggleClass( 'saving', isSaving );
} );
@ -5371,14 +5424,123 @@
history.replaceState( {}, document.title, urlParser.href );
};
changesetStatus.bind( function( newStatus ) {
populateChangesetUuidParam( '' !== newStatus && 'publish' !== newStatus );
} );
// Show changeset UUID in URL when in branching mode and there is a saved changeset.
if ( api.settings.changeset.branching ) {
changesetStatus.bind( function( newStatus ) {
populateChangesetUuidParam( '' !== newStatus && 'publish' !== newStatus );
} );
}
// Expose states to the API.
api.state = state;
}());
// Set up autosave prompt.
(function() {
/**
* Obtain the URL to restore the autosave.
*
* @returns {string} Customizer URL.
*/
function getAutosaveRestorationUrl() {
var urlParser, queryParams;
urlParser = document.createElement( 'a' );
urlParser.href = location.href;
queryParams = api.utils.parseQueryString( urlParser.search.substr( 1 ) );
if ( api.settings.changeset.latestAutoDraftUuid ) {
queryParams.changeset_uuid = api.settings.changeset.latestAutoDraftUuid;
} else {
queryParams.customize_autosaved = 'on';
}
urlParser.search = $.param( queryParams );
return urlParser.href;
}
/**
* Remove parameter from the URL.
*
* @param {Array} params - Parameter names to remove.
* @returns {void}
*/
function stripParamsFromLocation( params ) {
var urlParser = document.createElement( 'a' ), queryParams, strippedParams = 0;
urlParser.href = location.href;
queryParams = api.utils.parseQueryString( urlParser.search.substr( 1 ) );
_.each( params, function( param ) {
if ( 'undefined' !== typeof queryParams[ param ] ) {
strippedParams += 1;
delete queryParams[ param ];
}
} );
if ( 0 === strippedParams ) {
return;
}
urlParser.search = $.param( queryParams );
history.replaceState( {}, document.title, urlParser.href );
}
/**
* Add notification regarding the availability of an autosave to restore.
*
* @returns {void}
*/
function addAutosaveRestoreNotification() {
var code = 'autosave_available', onStateChange;
// Since there is an autosave revision and the user hasn't loaded with autosaved, add notification to prompt to load autosaved version.
api.notifications.add( code, new api.Notification( code, {
message: api.l10n.autosaveNotice,
type: 'warning',
dismissible: true,
render: function() {
var li = api.Notification.prototype.render.call( this ), link;
// Handle clicking on restoration link.
link = li.find( 'a' );
link.prop( 'href', getAutosaveRestorationUrl() );
link.on( 'click', function( event ) {
event.preventDefault();
location.replace( getAutosaveRestorationUrl() );
} );
// Handle dismissal of notice.
li.find( '.notice-dismiss' ).on( 'click', function() {
wp.ajax.post( 'dismiss_customize_changeset_autosave', {
wp_customize: 'on',
customize_theme: api.settings.theme.stylesheet,
customize_changeset_uuid: api.settings.changeset.latestAutoDraftUuid || api.settings.changeset.uuid,
nonce: api.settings.nonce.dismiss_autosave
} );
} );
return li;
}
} ) );
// Remove the notification once the user starts making changes.
onStateChange = function() {
api.notifications.remove( code );
api.state( 'saved' ).unbind( onStateChange );
api.state( 'saving' ).unbind( onStateChange );
api.state( 'changesetStatus' ).unbind( onStateChange );
};
api.state( 'saved' ).bind( onStateChange );
api.state( 'saving' ).bind( onStateChange );
api.state( 'changesetStatus' ).bind( onStateChange );
}
if ( api.settings.changeset.autosaved ) {
stripParamsFromLocation( [ 'customize_autosaved' ] ); // Remove param when restoring autosave revision.
} else if ( ! api.settings.changeset.branching && 'auto-draft' === api.settings.changeset.status ) {
stripParamsFromLocation( [ 'changeset_uuid' ] ); // Remove UUID when restoring autosave auto-draft.
}
if ( api.settings.changeset.latestAutoDraftUuid || api.settings.changeset.hasAutosaveRevision ) {
addAutosaveRestoreNotification();
}
})();
// Check if preview url is valid and load the preview frame.
if ( api.previewer.previewUrl() ) {
api.previewer.refresh();
@ -5742,26 +5904,82 @@
channel: 'loader'
});
/*
* If we receive a 'back' event, we're inside an iframe.
* Send any clicks to the 'Return' link to the parent page.
*/
parent.bind( 'back', function() {
closeBtn.on( 'click.customize-controls-close', function( event ) {
event.preventDefault();
parent.send( 'close' );
});
});
// Handle exiting of Customizer.
(function() {
var isInsideIframe = false;
// Prompt user with AYS dialog if leaving the Customizer with unsaved changes
$( window ).on( 'beforeunload.customize-confirm', function () {
if ( ! api.state( 'saved' )() ) {
setTimeout( function() {
overlay.removeClass( 'customize-loading' );
}, 1 );
return api.l10n.saveAlert;
function isCleanState() {
return api.state( 'saved' ).get() && 'auto-draft' !== api.state( 'changesetStatus' ).get();
}
} );
/*
* If we receive a 'back' event, we're inside an iframe.
* Send any clicks to the 'Return' link to the parent page.
*/
parent.bind( 'back', function() {
isInsideIframe = true;
});
// Prompt user with AYS dialog if leaving the Customizer with unsaved changes
$( window ).on( 'beforeunload.customize-confirm', function() {
if ( ! isCleanState() ) {
setTimeout( function() {
overlay.removeClass( 'customize-loading' );
}, 1 );
return api.l10n.saveAlert;
}
});
closeBtn.on( 'click.customize-controls-close', function( event ) {
var clearedToClose = $.Deferred();
event.preventDefault();
/*
* The isInsideIframe condition is because Customizer is not able to use a confirm()
* since customize-loader.js will also use one. So autosave restorations are disabled
* when customize-loader.js is used.
*/
if ( isInsideIframe && isCleanState() ) {
clearedToClose.resolve();
} else if ( confirm( api.l10n.saveAlert ) ) {
// Mark all settings as clean to prevent another call to requestChangesetUpdate.
api.each( function( setting ) {
setting._dirty = false;
});
$( document ).off( 'visibilitychange.wp-customize-changeset-update' );
$( window ).off( 'beforeunload.wp-customize-changeset-update' );
closeBtn.css( 'cursor', 'progress' );
if ( '' === api.state( 'changesetStatus' ).get() ) {
clearedToClose.resolve();
} else {
wp.ajax.send( 'dismiss_customize_changeset_autosave', {
timeout: 500, // Don't wait too long.
data: {
wp_customize: 'on',
customize_theme: api.settings.theme.stylesheet,
customize_changeset_uuid: api.settings.changeset.uuid,
nonce: api.settings.nonce.dismiss_autosave
}
} ).always( function() {
clearedToClose.resolve();
} );
}
} else {
clearedToClose.reject();
}
clearedToClose.done( function() {
$( window ).off( 'beforeunload.customize-confirm' );
if ( isInsideIframe ) {
parent.send( 'close' );
} else {
window.location.href = closeBtn.prop( 'href' );
}
} );
});
})();
// Pass events through to the parent.
$.each( [ 'saved', 'change' ], function ( i, event ) {
@ -6084,6 +6302,13 @@
( function() {
var timeoutId, updateChangesetWithReschedule, scheduleChangesetUpdate, updatePending = false;
api.state( 'saved' ).bind( function( isSaved ) {
if ( ! isSaved && ! api.settings.changeset.autosaved ) {
api.settings.changeset.autosaved = true; // Once a change is made then autosaving kicks in.
api.previewer.send( 'autosaving' );
}
} );
/**
* Request changeset update and then re-schedule the next changeset update time.
*
@ -6093,7 +6318,7 @@
updateChangesetWithReschedule = function() {
if ( ! updatePending ) {
updatePending = true;
api.requestChangesetUpdate().always( function() {
api.requestChangesetUpdate( {}, { autosave: true } ).always( function() {
updatePending = false;
} );
}
@ -6117,8 +6342,10 @@
scheduleChangesetUpdate();
// Save changeset when focus removed from window.
$( window ).on( 'blur.wp-customize-changeset-update', function() {
updateChangesetWithReschedule();
$( document ).on( 'visibilitychange.wp-customize-changeset-update', function() {
if ( document.hidden ) {
updateChangesetWithReschedule();
}
} );
// Save changeset before unloading window.

File diff suppressed because one or more lines are too long

View File

@ -173,13 +173,37 @@ final class WP_Customize_Manager {
*/
protected $messenger_channel;
/**
* Whether the autosave revision of the changeset should should be loaded.
*
* @since 4.9.0
* @var bool
*/
protected $autosaved = false;
/**
* Whether the changeset branching is allowed.
*
* @since 4.9.0
* @var bool
*/
protected $branching = true;
/**
* Whether settings should be previewed.
*
* @since 4.9.0
* @var bool
*/
protected $settings_previewed;
protected $settings_previewed = true;
/**
* Whether a starter content changeset was saved.
*
* @since 4.9.0
* @var bool
*/
protected $saved_starter_content_changeset = false;
/**
* Unsanitized values for Customize Settings parsed from $_POST['customized'].
@ -221,16 +245,23 @@ final class WP_Customize_Manager {
* @param array $args {
* Args.
*
* @type string $changeset_uuid Changeset UUID, the post_name for the customize_changeset post containing the customized state. Defaults to new UUID.
* @type string $theme Theme to be previewed (for theme switch). Defaults to customize_theme or theme query params.
* @type string $messenger_channel Messenger channel. Defaults to customize_messenger_channel query param.
* @type bool $settings_previewed If settings should be previewed. Defaults to true.
* @type null|string|false $changeset_uuid Changeset UUID, the `post_name` for the customize_changeset post containing the customized state.
* Defaults to `null` resulting in a UUID to be immediately generated. If `false` is provided, then
* then the changeset UUID will be determined during `after_setup_theme`: when the
* `customize_changeset_branching` filter returns false, then the default UUID will be that
* of the most recent `customize_changeset` post that has a status other than 'auto-draft',
* 'publish', or 'trash'. Otherwise, if changeset branching is enabled, then a random UUID will be used.
* @type string $theme Theme to be previewed (for theme switch). Defaults to customize_theme or theme query params.
* @type string $messenger_channel Messenger channel. Defaults to customize_messenger_channel query param.
* @type bool $settings_previewed If settings should be previewed. Defaults to true.
* @type bool $branching If changeset branching is allowed; otherwise, changesets are linear. Defaults to true.
* @type bool $autosaved If data from a changeset's autosaved revision should be loaded if it exists. Defaults to false.
* }
*/
public function __construct( $args = array() ) {
$args = array_merge(
array_fill_keys( array( 'changeset_uuid', 'theme', 'messenger_channel', 'settings_previewed' ), null ),
array_fill_keys( array( 'changeset_uuid', 'theme', 'messenger_channel', 'settings_previewed', 'autosaved', 'branching' ), null ),
$args
);
@ -251,16 +282,17 @@ final class WP_Customize_Manager {
$args['messenger_channel'] = sanitize_key( wp_unslash( $_REQUEST['customize_messenger_channel'] ) );
}
if ( ! isset( $args['settings_previewed'] ) ) {
$args['settings_previewed'] = true;
}
$this->original_stylesheet = get_stylesheet();
$this->theme = wp_get_theme( 0 === validate_file( $args['theme'] ) ? $args['theme'] : null );
$this->messenger_channel = $args['messenger_channel'];
$this->settings_previewed = ! empty( $args['settings_previewed'] );
$this->_changeset_uuid = $args['changeset_uuid'];
foreach ( array( 'settings_previewed', 'autosaved', 'branching' ) as $key ) {
if ( isset( $args[ $key ] ) ) {
$this->$key = (bool) $args[ $key ];
}
}
require_once( ABSPATH . WPINC . '/class-wp-customize-setting.php' );
require_once( ABSPATH . WPINC . '/class-wp-customize-panel.php' );
require_once( ABSPATH . WPINC . '/class-wp-customize-section.php' );
@ -343,6 +375,7 @@ final class WP_Customize_Manager {
add_action( 'wp_ajax_customize_save', array( $this, 'save' ) );
add_action( 'wp_ajax_customize_refresh_nonces', array( $this, 'refresh_nonces' ) );
add_action( 'wp_ajax_dismiss_customize_changeset_autosave', array( $this, 'handle_dismiss_changeset_autosave_request' ) );
add_action( 'customize_register', array( $this, 'register_controls' ) );
add_action( 'customize_register', array( $this, 'register_dynamic_settings' ), 11 ); // allow code to create settings first
@ -474,7 +507,8 @@ final class WP_Customize_Manager {
return;
}
if ( ! wp_is_uuid( $this->_changeset_uuid ) ) {
// If a changeset was provided is invalid.
if ( isset( $this->_changeset_uuid ) && false !== $this->_changeset_uuid && ! wp_is_uuid( $this->_changeset_uuid ) ) {
$this->wp_die( -1, __( 'Invalid changeset UUID' ) );
}
@ -535,6 +569,9 @@ final class WP_Customize_Manager {
}
}
// Make sure changeset UUID is established immediately after the theme is loaded.
add_action( 'after_setup_theme', array( $this, 'establish_loaded_changeset' ), 5 );
/*
* Import theme starter content for fresh installations when landing in the customizer.
* Import starter content at after_setup_theme:100 so that any
@ -547,6 +584,72 @@ final class WP_Customize_Manager {
$this->start_previewing_theme();
}
/**
* Establish the loaded changeset.
*
* This method runs right at after_setup_theme and applies the 'customize_changeset_branching' filter to determine
* whether concurrent changesets are allowed. Then if the Customizer is not initialized with a `changeset_uuid` param,
* this method will determine which UUID should be used. If changeset branching is disabled, then the most saved
* changeset will be loaded by default. Otherwise, if there are no existing saved changesets or if changeset branching is
* enabled, then a new UUID will be generated.
*
* @since 4.9.0
*/
public function establish_loaded_changeset() {
/**
* Filters whether or not changeset branching is allowed.
*
* By default in core, when changeset branching is not allowed, changesets will operate
* linearly in that only one saved changeset will exist at a time (with a 'draft' or
* 'future' status). This makes the Customizer operate in a way that is similar to going to
* "edit" to one existing post: all users will be making changes to the same post, and autosave
* revisions will be made for that post.
*
* By contrast, when changeset branching is allowed, then the model is like users going
* to "add new" for a page and each user makes changes independently of each other since
* they are all operating on their own separate pages, each getting their own separate
* initial auto-drafts and then once initially saved, autosave revisions on top of that
* user's specific post.
*
* Since linear changesets are deemed to be more suitable for the majority of WordPress users,
* they are the default. For WordPress sites that have heavy site management in the Customizer
* by multiple users then branching changesets should be enabled by means of this filter.
*
* @since 4.9.0
*
* @param bool $allow_branching Whether branching is allowed. If `false`, the default,
* then only one saved changeset exists at a time.
* @param WP_Customize_Manager $wp_customize Manager instance.
*/
$this->branching = apply_filters( 'customize_changeset_branching', $this->branching, $this );
if ( empty( $this->_changeset_uuid ) ) {
$changeset_uuid = null;
if ( ! $this->branching ) {
$unpublished_changeset_posts = $this->get_changeset_posts( array(
'post_status' => array_diff( get_post_stati(), array( 'auto-draft', 'publish', 'trash', 'inherit', 'private' ) ),
'exclude_restore_dismissed' => false,
'posts_per_page' => 1,
'order' => 'DESC',
'orderby' => 'date',
) );
$unpublished_changeset_post = array_shift( $unpublished_changeset_posts );
if ( ! empty( $unpublished_changeset_post ) && wp_is_uuid( $unpublished_changeset_post->post_name ) ) {
$changeset_uuid = $unpublished_changeset_post->post_name;
}
}
// If no changeset UUID has been set yet, then generate a new one.
if ( empty( $changeset_uuid ) ) {
$changeset_uuid = wp_generate_uuid4();
}
$this->_changeset_uuid = $changeset_uuid;
}
}
/**
* Callback to validate a theme once it is loaded
*
@ -652,10 +755,16 @@ final class WP_Customize_Manager {
* Get the changeset UUID.
*
* @since 4.7.0
* @since 4.9.0 An exception is thrown if the changeset UUID has not been established yet.
* @see WP_Customize_Manager::establish_loaded_changeset()
*
* @throws Exception When the UUID has not been set yet.
* @return string UUID.
*/
public function changeset_uuid() {
if ( empty( $this->_changeset_uuid ) ) {
throw new Exception( 'Changeset UUID has not been set.' ); // @todo Replace this with a call to `WP_Customize_Manager::establish_loaded_changeset()` during 4.9-beta2.
}
return $this->_changeset_uuid;
}
@ -824,6 +933,53 @@ final class WP_Customize_Manager {
return null;
}
/**
* Get changeset posts.
*
* @since 4.9.0
*
* @param array $args {
* Args to pass into `get_posts()` to query changesets.
*
* @type int $posts_per_page Number of posts to return. Defaults to -1 (all posts).
* @type int $author Post author. Defaults to current user.
* @type string $post_status Status of changeset. Defaults to 'auto-draft'.
* @type bool $exclude_restore_dismissed Whether to exclude changeset auto-drafts that have been dismissed. Defaults to true.
* }
* @return WP_Post[] Auto-draft changesets.
*/
protected function get_changeset_posts( $args = array() ) {
$default_args = array(
'exclude_restore_dismissed' => true,
'posts_per_page' => -1,
'post_type' => 'customize_changeset',
'post_status' => 'auto-draft',
'order' => 'DESC',
'orderby' => 'date',
'no_found_rows' => true,
'cache_results' => true,
'update_post_meta_cache' => false,
'update_post_term_cache' => false,
'lazy_load_term_meta' => false,
);
if ( get_current_user_id() ) {
$default_args['author'] = get_current_user_id();
}
$args = array_merge( $default_args, $args );
if ( ! empty( $args['exclude_restore_dismissed'] ) ) {
unset( $args['exclude_restore_dismissed'] );
$args['meta_query'] = array(
array(
'key' => '_customize_restore_dismissed',
'compare' => 'NOT EXISTS',
),
);
}
return get_posts( $args );
}
/**
* Get the changeset post id for the loaded changeset.
*
@ -833,7 +989,7 @@ final class WP_Customize_Manager {
*/
public function changeset_post_id() {
if ( ! isset( $this->_changeset_post_id ) ) {
$post_id = $this->find_changeset_post_id( $this->_changeset_uuid );
$post_id = $this->find_changeset_post_id( $this->changeset_uuid() );
if ( ! $post_id ) {
$post_id = false;
}
@ -861,7 +1017,11 @@ final class WP_Customize_Manager {
if ( ! $changeset_post ) {
return new WP_Error( 'missing_post' );
}
if ( 'customize_changeset' !== $changeset_post->post_type ) {
if ( 'revision' === $changeset_post->post_type ) {
if ( 'customize_changeset' !== get_post_type( $changeset_post->post_parent ) ) {
return new WP_Error( 'wrong_post_type' );
}
} elseif ( 'customize_changeset' !== $changeset_post->post_type ) {
return new WP_Error( 'wrong_post_type' );
}
$changeset_data = json_decode( $changeset_post->post_content, true );
@ -878,6 +1038,7 @@ final class WP_Customize_Manager {
* Get changeset data.
*
* @since 4.7.0
* @since 4.9.0 This will return the changeset's data with a user's autosave revision merged on top, if one exists and $autosaved is true.
*
* @return array Changeset data.
*/
@ -889,11 +1050,24 @@ final class WP_Customize_Manager {
if ( ! $changeset_post_id ) {
$this->_changeset_data = array();
} else {
$data = $this->get_changeset_post_data( $changeset_post_id );
if ( ! is_wp_error( $data ) ) {
$this->_changeset_data = $data;
} else {
$this->_changeset_data = array();
if ( $this->autosaved ) {
$autosave_post = wp_get_post_autosave( $changeset_post_id );
if ( $autosave_post ) {
$data = $this->get_changeset_post_data( $autosave_post->ID );
if ( ! is_wp_error( $data ) ) {
$this->_changeset_data = $data;
}
}
}
// Load data from the changeset if it was not loaded from an autosave.
if ( ! isset( $this->_changeset_data ) ) {
$data = $this->get_changeset_post_data( $changeset_post_id );
if ( ! is_wp_error( $data ) ) {
$this->_changeset_data = $data;
} else {
$this->_changeset_data = array();
}
}
}
return $this->_changeset_data;
@ -1374,6 +1548,7 @@ final class WP_Customize_Manager {
'data' => array_fill_keys( $this->pending_starter_content_settings_ids, array( 'starter_content' => true ) ),
'starter_content' => true,
) );
$this->saved_starter_content_changeset = true;
$this->pending_starter_content_settings_ids = array();
}
@ -1796,7 +1971,8 @@ final class WP_Customize_Manager {
$settings = array(
'changeset' => array(
'uuid' => $this->_changeset_uuid,
'uuid' => $this->changeset_uuid(),
'autosaved' => $this->autosaved,
),
'timeouts' => array(
'selectiveRefresh' => 250,
@ -2078,7 +2254,8 @@ final class WP_Customize_Manager {
}
$changeset_post_id = $this->changeset_post_id();
if ( empty( $changeset_post_id ) ) {
$is_new_changeset = empty( $changeset_post_id );
if ( $is_new_changeset ) {
if ( ! current_user_can( get_post_type_object( 'customize_changeset' )->cap->create_posts ) ) {
wp_send_json_error( 'cannot_create_changeset_post' );
}
@ -2144,11 +2321,17 @@ final class WP_Customize_Manager {
}
}
$autosave = ! empty( $_POST['customize_changeset_autosave'] );
if ( $autosave && ! defined( 'DOING_AUTOSAVE' ) ) { // Back-compat.
define( 'DOING_AUTOSAVE', true );
}
$r = $this->save_changeset_post( array(
'status' => $changeset_status,
'title' => $changeset_title,
'date_gmt' => $changeset_date_gmt,
'data' => $input_changeset_data,
'autosave' => $autosave,
) );
if ( is_wp_error( $r ) ) {
$response = array(
@ -2163,6 +2346,20 @@ final class WP_Customize_Manager {
} else {
$response = $r;
// Dismiss all other auto-draft changeset posts for this user (they serve like autosave revisions), as there should only be one.
if ( $is_new_changeset ) {
$changeset_autodraft_posts = $this->get_changeset_posts( array(
'post_status' => 'auto-draft',
'exclude_restore_dismissed' => true,
'posts_per_page' => -1,
) );
foreach ( $changeset_autodraft_posts as $autosave_autodraft_post ) {
if ( $autosave_autodraft_post->ID !== $this->changeset_post_id() ) {
update_post_meta( $autosave_autodraft_post->ID, '_customize_restore_dismissed', true );
}
}
}
// Note that if the changeset status was publish, then it will get set to trash if revisions are not supported.
$response['changeset_status'] = get_post_status( $this->changeset_post_id() );
if ( $is_publish && 'trash' === $response['changeset_status'] ) {
@ -2212,6 +2409,7 @@ final class WP_Customize_Manager {
* @type string $date_gmt Date in GMT. Optional.
* @type int $user_id ID for user who is saving the changeset. Optional, defaults to the current user ID.
* @type bool $starter_content Whether the data is starter content. If false (default), then $starter_content will be cleared for any $data being saved.
* @type bool $autosave Whether this is a request to create an autosave revision.
* }
*
* @return array|WP_Error Returns array on success and WP_Error with array data on error.
@ -2226,6 +2424,7 @@ final class WP_Customize_Manager {
'date_gmt' => null,
'user_id' => get_current_user_id(),
'starter_content' => false,
'autosave' => false,
),
$args
);
@ -2277,6 +2476,17 @@ final class WP_Customize_Manager {
$args['status'] = 'future';
}
// Validate autosave param. See _wp_post_revision_fields() for why these fields are disallowed.
if ( $args['autosave'] ) {
if ( $args['date_gmt'] ) {
return new WP_Error( 'illegal_autosave_with_date_gmt' );
} elseif ( $args['status'] ) {
return new WP_Error( 'illegal_autosave_with_status' );
} elseif ( $args['user_id'] && get_current_user_id() !== $args['user_id'] ) {
return new WP_Error( 'illegal_autosave_with_non_current_user' );
}
}
// The request was made via wp.customize.previewer.save().
$update_transactionally = (bool) $args['status'];
$allow_revision = (bool) $args['status'];
@ -2519,8 +2729,23 @@ final class WP_Customize_Manager {
// Note that updating a post with publish status will trigger WP_Customize_Manager::publish_changeset_values().
if ( $changeset_post_id ) {
$post_array['edit_date'] = true; // Prevent date clearing.
$r = wp_update_post( wp_slash( $post_array ), true );
if ( $args['autosave'] && 'auto-draft' !== get_post_status( $changeset_post_id ) ) {
// See _wp_translate_postdata() for why this is required as it will use the edit_post meta capability.
add_filter( 'map_meta_cap', array( $this, 'grant_edit_post_capability_for_changeset' ), 10, 4 );
$post_array['post_ID'] = $post_array['ID'];
$post_array['post_type'] = 'customize_changeset';
$r = wp_create_post_autosave( wp_slash( $post_array ) );
remove_filter( 'map_meta_cap', array( $this, 'grant_edit_post_capability_for_changeset' ), 10 );
} else {
$post_array['edit_date'] = true; // Prevent date clearing.
$r = wp_update_post( wp_slash( $post_array ), true );
// Delete autosave revision when the changeset is updated.
$autosave_draft = wp_get_post_autosave( $changeset_post_id );
if ( $autosave_draft ) {
wp_delete_post( $autosave_draft->ID, true );
}
}
} else {
$r = wp_insert_post( wp_slash( $post_array ), true );
if ( ! is_wp_error( $r ) ) {
@ -2546,6 +2771,35 @@ final class WP_Customize_Manager {
return $response;
}
/**
* Re-map 'edit_post' meta cap for a customize_changeset post to be the same as 'customize' maps.
*
* There is essentially a "meta meta" cap in play here, where 'edit_post' meta cap maps to
* the 'customize' meta cap which then maps to 'edit_theme_options'. This is currently
* required in core for `wp_create_post_autosave()` because it will call
* `_wp_translate_postdata()` which in turn will check if a user can 'edit_post', but the
* the caps for the customize_changeset post type are all mapping to the meta capability.
* This should be able to be removed once #40922 is addressed in core.
*
* @since 4.9.0
* @link https://core.trac.wordpress.org/ticket/40922
* @see WP_Customize_Manager::save_changeset_post()
* @see _wp_translate_postdata()
*
* @param array $caps Returns the user's actual capabilities.
* @param string $cap Capability name.
* @param int $user_id The user ID.
* @param array $args Adds the context to the cap. Typically the object ID.
* @return array Capabilities.
*/
public function grant_edit_post_capability_for_changeset( $caps, $cap, $user_id, $args ) {
if ( 'edit_post' === $cap && ! empty( $args[0] ) && 'customize_changeset' === get_post_type( $args[0] ) ) {
$post_type_obj = get_post_type_object( 'customize_changeset' );
$caps = map_meta_cap( $post_type_obj->cap->$cap, $user_id );
}
return $caps;
}
/**
* Whether a changeset revision should be made.
*
@ -2785,6 +3039,51 @@ final class WP_Customize_Manager {
wp_send_json_success( $this->get_nonces() );
}
/**
* Delete a given auto-draft changeset or the autosave revision for a given changeset.
*
* @since 4.9.0
*/
public function handle_dismiss_changeset_autosave_request() {
if ( ! $this->is_preview() ) {
wp_send_json_error( 'not_preview', 400 );
}
if ( ! check_ajax_referer( 'dismiss_customize_changeset_autosave', 'nonce', false ) ) {
wp_send_json_error( 'invalid_nonce', 403 );
}
$changeset_post_id = $this->changeset_post_id();
if ( empty( $changeset_post_id ) ) {
wp_send_json_error( 'missing_changeset', 404 );
}
if ( 'auto-draft' === get_post_status( $changeset_post_id ) ) {
if ( ! update_post_meta( $changeset_post_id, '_customize_restore_dismissed', true ) ) {
wp_send_json_error( 'auto_draft_dismissal_failure', 500 );
} else {
wp_send_json_success( 'auto_draft_dismissed' );
}
} else {
$revision = wp_get_post_autosave( $changeset_post_id );
if ( $revision ) {
if ( ! current_user_can( get_post_type_object( 'customize_changeset' )->cap->delete_post, $changeset_post_id ) ) {
wp_send_json_error( 'cannot_delete_autosave_revision', 403 );
}
if ( ! wp_delete_post( $revision->ID, true ) ) {
wp_send_json_error( 'autosave_revision_deletion_failure', 500 );
} else {
wp_send_json_success( 'autosave_revision_deleted' );
}
} else {
wp_send_json_error( 'no_autosave_to_delete', 404 );
}
}
wp_send_json_error( 'unknown_error', 500 );
}
/**
* Add a customize setting.
*
@ -3527,6 +3826,7 @@ final class WP_Customize_Manager {
$nonces = array(
'save' => wp_create_nonce( 'save-customize_' . $this->get_stylesheet() ),
'preview' => wp_create_nonce( 'preview-customize_' . $this->get_stylesheet() ),
'dismiss_autosave' => wp_create_nonce( 'dismiss_customize_changeset_autosave' ),
);
/**
@ -3563,11 +3863,33 @@ final class WP_Customize_Manager {
}
}
$autosave_revision_post = null;
$autosave_autodraft_post = null;
$changeset_post_id = $this->changeset_post_id();
if ( ! $this->saved_starter_content_changeset && ! $this->autosaved ) {
if ( $changeset_post_id ) {
$autosave_revision_post = wp_get_post_autosave( $changeset_post_id );
} else {
$autosave_autodraft_posts = $this->get_changeset_posts( array(
'posts_per_page' => 1,
'post_status' => 'auto-draft',
'exclude_restore_dismissed' => true,
) );
if ( ! empty( $autosave_autodraft_posts ) ) {
$autosave_autodraft_post = array_shift( $autosave_autodraft_posts );
}
}
}
// Prepare Customizer settings to pass to JavaScript.
$settings = array(
'changeset' => array(
'uuid' => $this->changeset_uuid(),
'status' => $this->changeset_post_id() ? get_post_status( $this->changeset_post_id() ) : '',
'branching' => $this->branching,
'autosaved' => $this->autosaved,
'hasAutosaveRevision' => ! empty( $autosave_revision_post ),
'latestAutoDraftUuid' => $autosave_autodraft_post ? $autosave_autodraft_post->post_name : null,
'status' => $changeset_post_id ? get_post_status( $changeset_post_id ) : '',
),
'timeouts' => array(
'windowRefresh' => 250,

View File

@ -36,6 +36,9 @@
newQueryParams = api.utils.parseQueryString( urlParser.search.substr( 1 ) );
newQueryParams.customize_changeset_uuid = oldQueryParams.customize_changeset_uuid;
if ( api.settings.changeset.autosaved ) {
newQueryParams.customize_autosaved = 'on';
}
if ( oldQueryParams.customize_theme ) {
newQueryParams.customize_theme = oldQueryParams.customize_theme;
}
@ -364,6 +367,9 @@
queryParams = api.utils.parseQueryString( element.search.substring( 1 ) );
queryParams.customize_changeset_uuid = api.settings.changeset.uuid;
if ( api.settings.changeset.autosaved ) {
queryParams.customize_autosaved = 'on';
}
if ( ! api.settings.theme.active ) {
queryParams.customize_theme = api.settings.theme.stylesheet;
}
@ -439,6 +445,9 @@
// Include customized state query params in URL.
queryParams.customize_changeset_uuid = api.settings.changeset.uuid;
if ( api.settings.changeset.autosaved ) {
queryParams.customize_autosaved = 'on';
}
if ( ! api.settings.theme.active ) {
queryParams.customize_theme = api.settings.theme.stylesheet;
}
@ -516,6 +525,9 @@
$( form ).removeClass( 'customize-unpreviewable' );
stateParams.customize_changeset_uuid = api.settings.changeset.uuid;
if ( api.settings.changeset.autosaved ) {
stateParams.customize_autosaved = 'on';
}
if ( ! api.settings.theme.active ) {
stateParams.customize_theme = api.settings.theme.stylesheet;
}
@ -555,7 +567,7 @@
var previousPathName = location.pathname,
previousQueryString = location.search.substr( 1 ),
previousQueryParams = null,
stateQueryParams = [ 'customize_theme', 'customize_changeset_uuid', 'customize_messenger_channel' ];
stateQueryParams = [ 'customize_theme', 'customize_changeset_uuid', 'customize_messenger_channel', 'customize_autosaved' ];
return function keepAliveCurrentUrl() {
var urlParser, currentQueryParams;
@ -754,7 +766,6 @@
});
api.preview.bind( 'saved', function( response ) {
if ( response.next_changeset_uuid ) {
api.settings.changeset.uuid = response.next_changeset_uuid;
@ -779,6 +790,25 @@
api.trigger( 'saved', response );
} );
// Update the URLs to reflect the fact we've started autosaving.
api.preview.bind( 'autosaving', function() {
if ( api.settings.changeset.autosaved ) {
return;
}
api.settings.changeset.autosaved = true; // Start deferring to any autosave once changeset is updated.
$( document.body ).find( 'a[href], area' ).each( function() {
api.prepareLinkPreview( this );
} );
$( document.body ).find( 'form' ).each( function() {
api.prepareFormPreview( this );
} );
if ( history.replaceState ) {
history.replaceState( currentHistoryState, '', location.href );
}
} );
/*
* Clear dirty flag for settings when saved to changeset so that they
* won't be needlessly included in selective refresh or ajax requests.

File diff suppressed because one or more lines are too long

View File

@ -561,6 +561,8 @@ function wp_default_scripts( &$scripts ) {
'expandSidebar' => _x( 'Show Controls', 'label for hide controls button without length constraints' ),
'untitledBlogName' => __( '(Untitled)' ),
'serverSaveError' => __( 'Failed connecting to the server. Please try saving again.' ),
/* translators: placeholder is URL to the Customizer to load the autosaved version */
'autosaveNotice' => __( 'There is a more recent autosave of your changes than the one you are previewing. <a href="%s">Restore the autosave</a>' ),
'videoHeaderNotice' => __( 'This theme doesn\'t support video headers on this page. Navigate to the front page or another page that supports video headers.' ),
// Used for overriding the file types allowed in plupload.
'allowedFiles' => __( 'Allowed Files' ),

View File

@ -2787,15 +2787,17 @@ function _wp_customize_include() {
* 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' );
$keys = array( 'changeset_uuid', 'customize_changeset_uuid', 'customize_theme', 'theme', 'customize_messenger_channel', 'customize_autosaved' );
$input_vars = array_merge(
wp_array_slice_assoc( $_GET, $keys ),
wp_array_slice_assoc( $_POST, $keys )
);
$theme = null;
$changeset_uuid = null;
$changeset_uuid = false; // Value false indicates UUID should be determined after_setup_theme to either re-use existing saved changeset or else generate a new UUID if none exists.
$messenger_channel = null;
$autosaved = null;
$branching = false; // Set initially fo false since defaults to true for back-compat; can be overridden via the customize_changeset_branching filter.
if ( $is_customize_admin_page && isset( $input_vars['changeset_uuid'] ) ) {
$changeset_uuid = sanitize_key( $input_vars['changeset_uuid'] );
@ -2809,6 +2811,11 @@ function _wp_customize_include() {
} elseif ( isset( $input_vars['customize_theme'] ) ) {
$theme = $input_vars['customize_theme'];
}
if ( ! empty( $input_vars['customize_autosaved'] ) ) {
$autosaved = true;
}
if ( isset( $input_vars['customize_messenger_channel'] ) ) {
$messenger_channel = sanitize_key( $input_vars['customize_messenger_channel'] );
}
@ -2830,7 +2837,7 @@ function _wp_customize_include() {
$settings_previewed = ! $is_customize_save_action;
require_once ABSPATH . WPINC . '/class-wp-customize-manager.php';
$GLOBALS['wp_customize'] = new WP_Customize_Manager( compact( 'changeset_uuid', 'theme', 'messenger_channel', 'settings_previewed' ) );
$GLOBALS['wp_customize'] = new WP_Customize_Manager( compact( 'changeset_uuid', 'theme', 'messenger_channel', 'settings_previewed', 'autosaved', 'branching' ) );
}
/**

View File

@ -4,7 +4,7 @@
*
* @global string $wp_version
*/
$wp_version = '4.9-alpha-41596';
$wp_version = '4.9-alpha-41597';
/**
* Holds the WordPress DB revision, increments when changes are made to the WordPress DB schema.