3 * Post revision functions.
6 * @subpackage Post_Revisions
10 * Determines which fields of posts are to be saved in revisions.
12 * Does two things. If passed a post *array*, it will return a post array ready
13 * to be inserted into the posts table as a post revision. Otherwise, returns
14 * an array whose keys are the post fields to be saved for post revisions.
19 * @param array $post Optional a post array to be processed for insertion as a post revision.
20 * @param bool $autosave optional Is the revision an autosave?
21 * @return array Post array ready to be inserted as a post revision or array of fields that can be versioned.
23 function _wp_post_revision_fields( $post = null, $autosave = false ) {
24 static $fields = false;
27 // Allow these to be versioned
29 'post_title' => __( 'Title' ),
30 'post_content' => __( 'Content' ),
31 'post_excerpt' => __( 'Excerpt' ),
35 * Filter the list of fields saved in post revisions.
37 * Included by default: 'post_title', 'post_content' and 'post_excerpt'.
39 * Disallowed fields: 'ID', 'post_name', 'post_parent', 'post_date',
40 * 'post_date_gmt', 'post_status', 'post_type', 'comment_count',
45 * @param array $fields List of fields to revision. Contains 'post_title',
46 * 'post_content', and 'post_excerpt' by default.
48 $fields = apply_filters( '_wp_post_revision_fields', $fields );
50 // WP uses these internally either in versioning or elsewhere - they cannot be versioned
51 foreach ( array( 'ID', 'post_name', 'post_parent', 'post_date', 'post_date_gmt', 'post_status', 'post_type', 'comment_count', 'post_author' ) as $protect )
52 unset( $fields[$protect] );
55 if ( !is_array($post) )
59 foreach ( array_intersect( array_keys( $post ), array_keys( $fields ) ) as $field )
60 $return[$field] = $post[$field];
62 $return['post_parent'] = $post['ID'];
63 $return['post_status'] = 'inherit';
64 $return['post_type'] = 'revision';
65 $return['post_name'] = $autosave ? "$post[ID]-autosave-v1" : "$post[ID]-revision-v1"; // "1" is the revisioning system version
66 $return['post_date'] = isset($post['post_modified']) ? $post['post_modified'] : '';
67 $return['post_date_gmt'] = isset($post['post_modified_gmt']) ? $post['post_modified_gmt'] : '';
73 * Creates a revision for the current version of a post.
75 * Typically used immediately after a post update, as every update is a revision,
76 * and the most recent revision always matches the current post.
80 * @param int $post_id The ID of the post to save as a revision.
81 * @return null|int Null or 0 if error, new revision ID, if success.
83 function wp_save_post_revision( $post_id ) {
84 if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
87 if ( ! $post = get_post( $post_id ) )
90 if ( ! post_type_supports( $post->post_type, 'revisions' ) )
93 if ( 'auto-draft' == $post->post_status )
96 if ( ! wp_revisions_enabled( $post ) )
99 // Compare the proposed update with the last stored revision verifying that
100 // they are different, unless a plugin tells us to always save regardless.
101 // If no previous revisions, save one
102 if ( $revisions = wp_get_post_revisions( $post_id ) ) {
103 // grab the last revision, but not an autosave
104 foreach ( $revisions as $revision ) {
105 if ( false !== strpos( $revision->post_name, "{$revision->post_parent}-revision" ) ) {
106 $last_revision = $revision;
112 * Filter whether the post has changed since the last revision.
114 * By default a revision is saved only if one of the revisioned fields has changed.
115 * This filter can override that so a revision is saved even if nothing has changed.
119 * @param bool $check_for_changes Whether to check for changes before saving a new revision.
121 * @param WP_Post $last_revision The the last revision post object.
122 * @param WP_Post $post The post object.
125 if ( isset( $last_revision ) && apply_filters( 'wp_save_post_revision_check_for_changes', $check_for_changes = true, $last_revision, $post ) ) {
126 $post_has_changed = false;
128 foreach ( array_keys( _wp_post_revision_fields() ) as $field ) {
129 if ( normalize_whitespace( $post->$field ) != normalize_whitespace( $last_revision->$field ) ) {
130 $post_has_changed = true;
136 * Filter whether a post has changed.
138 * By default a revision is saved only if one of the revisioned fields has changed.
139 * This filter allows for additional checks to determine if there were changes.
143 * @param bool $post_has_changed Whether the post has changed.
144 * @param WP_Post $last_revision The last revision post object.
145 * @param WP_Post $post The post object.
148 $post_has_changed = (bool) apply_filters( 'wp_save_post_revision_post_has_changed', $post_has_changed, $last_revision, $post );
150 //don't save revision if post unchanged
151 if( ! $post_has_changed ) {
157 $return = _wp_put_post_revision( $post );
159 // If a limit for the number of revisions to keep has been set,
160 // delete the oldest ones.
161 $revisions_to_keep = wp_revisions_to_keep( $post );
163 if ( $revisions_to_keep < 0 )
166 $revisions = wp_get_post_revisions( $post_id, array( 'order' => 'ASC' ) );
168 $delete = count($revisions) - $revisions_to_keep;
173 $revisions = array_slice( $revisions, 0, $delete );
175 for ( $i = 0; isset( $revisions[$i] ); $i++ ) {
176 if ( false !== strpos( $revisions[ $i ]->post_name, 'autosave' ) )
179 wp_delete_post_revision( $revisions[ $i ]->ID );
186 * Retrieve the autosaved data of the specified post.
188 * Returns a post object containing the information that was autosaved for the
189 * specified post. If the optional $user_id is passed, returns the autosave for that user
190 * otherwise returns the latest autosave.
194 * @param int $post_id The post ID.
195 * @param int $user_id optional The post author ID.
196 * @return object|bool The autosaved data or false on failure or when no autosave exists.
198 function wp_get_post_autosave( $post_id, $user_id = 0 ) {
199 $revisions = wp_get_post_revisions( $post_id, array( 'check_enabled' => false ) );
201 foreach ( $revisions as $revision ) {
202 if ( false !== strpos( $revision->post_name, "{$post_id}-autosave" ) ) {
203 if ( $user_id && $user_id != $revision->post_author )
214 * Determines if the specified post is a revision.
218 * @param int|object $post Post ID or post object.
219 * @return bool|int False if not a revision, ID of revision's parent otherwise.
221 function wp_is_post_revision( $post ) {
222 if ( !$post = wp_get_post_revision( $post ) )
225 return (int) $post->post_parent;
229 * Determines if the specified post is an autosave.
233 * @param int|object $post Post ID or post object.
234 * @return bool|int False if not a revision, ID of autosave's parent otherwise
236 function wp_is_post_autosave( $post ) {
237 if ( !$post = wp_get_post_revision( $post ) )
240 if ( false !== strpos( $post->post_name, "{$post->post_parent}-autosave" ) )
241 return (int) $post->post_parent;
247 * Inserts post data into the posts table as a post revision.
252 * @param int|object|array $post Post ID, post object OR post array.
253 * @param bool $autosave Optional. Is the revision an autosave?
254 * @return mixed WP_Error or 0 if error, new revision ID if success.
256 function _wp_put_post_revision( $post = null, $autosave = false ) {
257 if ( is_object($post) )
258 $post = get_object_vars( $post );
259 elseif ( !is_array($post) )
260 $post = get_post($post, ARRAY_A);
262 if ( ! $post || empty($post['ID']) )
263 return new WP_Error( 'invalid_post', __( 'Invalid post ID' ) );
265 if ( isset($post['post_type']) && 'revision' == $post['post_type'] )
266 return new WP_Error( 'post_type', __( 'Cannot create a revision of a revision' ) );
268 $post = _wp_post_revision_fields( $post, $autosave );
269 $post = wp_slash($post); //since data is from db
271 $revision_id = wp_insert_post( $post );
272 if ( is_wp_error($revision_id) )
275 if ( $revision_id ) {
277 * Fires once a revision has been saved.
281 * @param int $revision_id Post revision ID.
283 do_action( '_wp_put_post_revision', $revision_id );
290 * Gets a post revision.
294 * @param int|object $post The post ID or object.
295 * @param string $output Optional. OBJECT, ARRAY_A, or ARRAY_N.
296 * @param string $filter Optional sanitation filter. @see sanitize_post().
297 * @return mixed Null if error or post object if success.
299 function wp_get_post_revision(&$post, $output = OBJECT, $filter = 'raw') {
300 if ( !$revision = get_post( $post, OBJECT, $filter ) )
302 if ( 'revision' !== $revision->post_type )
305 if ( $output == OBJECT ) {
307 } elseif ( $output == ARRAY_A ) {
308 $_revision = get_object_vars($revision);
310 } elseif ( $output == ARRAY_N ) {
311 $_revision = array_values(get_object_vars($revision));
319 * Restores a post to the specified revision.
321 * Can restore a past revision using all fields of the post revision, or only selected fields.
325 * @param int|object $revision_id Revision ID or revision object.
326 * @param array $fields Optional. What fields to restore from. Defaults to all.
327 * @return mixed Null if error, false if no fields to restore, (int) post ID if success.
329 function wp_restore_post_revision( $revision_id, $fields = null ) {
330 if ( !$revision = wp_get_post_revision( $revision_id, ARRAY_A ) )
333 if ( !is_array( $fields ) )
334 $fields = array_keys( _wp_post_revision_fields() );
337 foreach( array_intersect( array_keys( $revision ), $fields ) as $field ) {
338 $update[$field] = $revision[$field];
344 $update['ID'] = $revision['post_parent'];
346 $update = wp_slash( $update ); //since data is from db
348 $post_id = wp_update_post( $update );
349 if ( ! $post_id || is_wp_error( $post_id ) )
352 // Add restore from details
353 $restore_details = array(
354 'restored_revision_id' => $revision_id,
355 'restored_by_user' => get_current_user_id(),
356 'restored_time' => time()
358 update_post_meta( $post_id, '_post_restored_from', $restore_details );
360 // Update last edit user
361 update_post_meta( $post_id, '_edit_last', get_current_user_id() );
364 * Fires after a post revision has been restored.
368 * @param int $post_id Post ID.
369 * @param int $revision_id Post revision ID.
371 do_action( 'wp_restore_post_revision', $post_id, $revision['ID'] );
377 * Deletes a revision.
379 * Deletes the row from the posts table corresponding to the specified revision.
383 * @param int|object $revision_id Revision ID or revision object.
384 * @return mixed Null or WP_Error if error, deleted post if success.
386 function wp_delete_post_revision( $revision_id ) {
387 if ( !$revision = wp_get_post_revision( $revision_id ) )
390 $delete = wp_delete_post( $revision->ID );
391 if ( is_wp_error( $delete ) )
396 * Fires once a post revision has been deleted.
400 * @param int $revision_id Post revision ID.
401 * @param object|array $revision Post revision object or array.
403 do_action( 'wp_delete_post_revision', $revision->ID, $revision );
410 * Returns all revisions of specified post.
414 * @param int|WP_Post $post_id Optional. Post ID or WP_Post object. Default is global $post.
415 * @return array An array of revisions, or an empty array if none.
417 function wp_get_post_revisions( $post_id = 0, $args = null ) {
418 $post = get_post( $post_id );
419 if ( ! $post || empty( $post->ID ) )
422 $defaults = array( 'order' => 'DESC', 'orderby' => 'date ID', 'check_enabled' => true );
423 $args = wp_parse_args( $args, $defaults );
425 if ( $args['check_enabled'] && ! wp_revisions_enabled( $post ) )
428 $args = array_merge( $args, array( 'post_parent' => $post->ID, 'post_type' => 'revision', 'post_status' => 'inherit' ) );
430 if ( ! $revisions = get_children( $args ) )
437 * Determine if revisions are enabled for a given post.
441 * @param WP_Post $post The post object.
442 * @return bool True if number of revisions to keep isn't zero, false otherwise.
444 function wp_revisions_enabled( $post ) {
445 return wp_revisions_to_keep( $post ) != 0;
449 * Determine how many revisions to retain for a given post.
451 * By default, an infinite number of revisions are kept.
453 * The constant WP_POST_REVISIONS can be set in wp-config to specify the limit
454 * of revisions to keep.
458 * @param WP_Post $post The post object.
459 * @return int The number of revisions to keep.
461 function wp_revisions_to_keep( $post ) {
462 $num = WP_POST_REVISIONS;
467 $num = intval( $num );
469 if ( ! post_type_supports( $post->post_type, 'revisions' ) )
473 * Filter the number of revisions to save for the given post.
475 * Overrides the value of WP_POST_REVISIONS.
479 * @param int $num Number of revisions to store.
480 * @param WP_Post $post Post object.
482 return (int) apply_filters( 'wp_revisions_to_keep', $num, $post );
486 * Sets up the post object for preview based on the post autosave.
491 function _set_preview($post) {
493 if ( ! is_object($post) )
496 $preview = wp_get_post_autosave($post->ID);
498 if ( ! is_object($preview) )
501 $preview = sanitize_post($preview);
503 $post->post_content = $preview->post_content;
504 $post->post_title = $preview->post_title;
505 $post->post_excerpt = $preview->post_excerpt;
507 add_filter( 'get_the_terms', '_wp_preview_terms_filter', 10, 3 );
513 * Filters the latest content for preview from the post autosave.
518 function _show_post_preview() {
520 if ( isset($_GET['preview_id']) && isset($_GET['preview_nonce']) ) {
521 $id = (int) $_GET['preview_id'];
523 if ( false == wp_verify_nonce( $_GET['preview_nonce'], 'post_preview_' . $id ) )
524 wp_die( __('You do not have permission to preview drafts.') );
526 add_filter('the_preview', '_set_preview');
531 * Filters terms lookup to set the post format.
536 function _wp_preview_terms_filter( $terms, $post_id, $taxonomy ) {
537 if ( ! $post = get_post() )
540 if ( empty( $_REQUEST['post_format'] ) || $post->ID != $post_id || 'post_format' != $taxonomy || 'revision' == $post->post_type )
543 if ( 'standard' == $_REQUEST['post_format'] )
545 elseif ( $term = get_term_by( 'slug', 'post-format-' . sanitize_key( $_REQUEST['post_format'] ), 'post_format' ) )
546 $terms = array( $term ); // Can only have one post format
552 * Gets the post revision version.
557 function _wp_get_post_revision_version( $revision ) {
558 if ( is_object( $revision ) )
559 $revision = get_object_vars( $revision );
560 elseif ( !is_array( $revision ) )
563 if ( preg_match( '/^\d+-(?:autosave|revision)-v(\d+)$/', $revision['post_name'], $matches ) )
564 return (int) $matches[1];
570 * Upgrade the revisions author, add the current post as a revision and set the revisions version to 1
575 * @param WP_Post $post Post object
576 * @param array $revisions Current revisions of the post
577 * @return bool true if the revisions were upgraded, false if problems
579 function _wp_upgrade_revisions_of_post( $post, $revisions ) {
582 // Add post option exclusively
583 $lock = "revision-upgrade-{$post->ID}";
585 $result = $wpdb->query( $wpdb->prepare( "INSERT IGNORE INTO `$wpdb->options` (`option_name`, `option_value`, `autoload`) VALUES (%s, %s, 'no') /* LOCK */", $lock, $now ) );
587 // If we couldn't get a lock, see how old the previous lock is
588 $locked = get_option( $lock );
590 // Can't write to the lock, and can't read the lock.
591 // Something broken has happened
595 if ( $locked > $now - 3600 ) {
596 // Lock is not too old: some other process may be upgrading this post. Bail.
600 // Lock is too old - update it (below) and continue
603 // If we could get a lock, re-"add" the option to fire all the correct filters.
604 update_option( $lock, $now );
610 $this_revision = current( $revisions );
611 $prev_revision = next( $revisions );
613 $this_revision_version = _wp_get_post_revision_version( $this_revision );
615 // Something terrible happened
616 if ( false === $this_revision_version )
619 // 1 is the latest revision version, so we're already up to date.
620 // No need to add a copy of the post as latest revision.
621 if ( 0 < $this_revision_version ) {
626 // Always update the revision version
628 'post_name' => preg_replace( '/^(\d+-(?:autosave|revision))[\d-]*$/', '$1-v1', $this_revision->post_name ),
631 // If this revision is the oldest revision of the post, i.e. no $prev_revision,
632 // the correct post_author is probably $post->post_author, but that's only a good guess.
633 // Update the revision version only and Leave the author as-is.
634 if ( $prev_revision ) {
635 $prev_revision_version = _wp_get_post_revision_version( $prev_revision );
637 // If the previous revision is already up to date, it no longer has the information we need :(
638 if ( $prev_revision_version < 1 )
639 $update['post_author'] = $prev_revision->post_author;
642 // Upgrade this revision
643 $result = $wpdb->update( $wpdb->posts, $update, array( 'ID' => $this_revision->ID ) );
646 wp_cache_delete( $this_revision->ID, 'posts' );
648 } while ( $prev_revision );
650 delete_option( $lock );
652 // Add a copy of the post as latest revision.
654 wp_save_post_revision( $post->ID );