]> scripts.mit.edu Git - autoinstalls/wordpress.git/blob - wp-includes/revision.php
WordPress 4.4
[autoinstalls/wordpress.git] / wp-includes / revision.php
1 <?php
2 /**
3  * Post revision functions.
4  *
5  * @package WordPress
6  * @subpackage Post_Revisions
7  */
8
9 /**
10  * Determines which fields of posts are to be saved in revisions.
11  *
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.
15  *
16  * @since 2.6.0
17  * @access private
18  *
19  * @staticvar array $fields
20  *
21  * @param array|null $post     Optional. A post array to be processed for insertion as a post revision. Default null.
22  * @param bool       $autosave Optional. Is the revision an autosave? Default false.
23  * @return array Post array ready to be inserted as a post revision or array of fields that can be versioned.
24  */
25 function _wp_post_revision_fields( $post = null, $autosave = false ) {
26         static $fields = null;
27
28         if ( is_null( $fields ) ) {
29                 // Allow these to be versioned
30                 $fields = array(
31                         'post_title' => __( 'Title' ),
32                         'post_content' => __( 'Content' ),
33                         'post_excerpt' => __( 'Excerpt' ),
34                 );
35
36                 /**
37                  * Filter the list of fields saved in post revisions.
38                  *
39                  * Included by default: 'post_title', 'post_content' and 'post_excerpt'.
40                  *
41                  * Disallowed fields: 'ID', 'post_name', 'post_parent', 'post_date',
42                  * 'post_date_gmt', 'post_status', 'post_type', 'comment_count',
43                  * and 'post_author'.
44                  *
45                  * @since 2.6.0
46                  *
47                  * @param array $fields List of fields to revision. Contains 'post_title',
48                  *                      'post_content', and 'post_excerpt' by default.
49                  */
50                 $fields = apply_filters( '_wp_post_revision_fields', $fields );
51
52                 // WP uses these internally either in versioning or elsewhere - they cannot be versioned
53                 foreach ( array( 'ID', 'post_name', 'post_parent', 'post_date', 'post_date_gmt', 'post_status', 'post_type', 'comment_count', 'post_author' ) as $protect )
54                         unset( $fields[$protect] );
55         }
56
57         if ( !is_array($post) )
58                 return $fields;
59
60         $return = array();
61         foreach ( array_intersect( array_keys( $post ), array_keys( $fields ) ) as $field )
62                 $return[$field] = $post[$field];
63
64         $return['post_parent']   = $post['ID'];
65         $return['post_status']   = 'inherit';
66         $return['post_type']     = 'revision';
67         $return['post_name']     = $autosave ? "$post[ID]-autosave-v1" : "$post[ID]-revision-v1"; // "1" is the revisioning system version
68         $return['post_date']     = isset($post['post_modified']) ? $post['post_modified'] : '';
69         $return['post_date_gmt'] = isset($post['post_modified_gmt']) ? $post['post_modified_gmt'] : '';
70
71         return $return;
72 }
73
74 /**
75  * Creates a revision for the current version of a post.
76  *
77  * Typically used immediately after a post update, as every update is a revision,
78  * and the most recent revision always matches the current post.
79  *
80  * @since 2.6.0
81  *
82  * @param int $post_id The ID of the post to save as a revision.
83  * @return int|WP_Error|void Void or 0 if error, new revision ID, if success.
84  */
85 function wp_save_post_revision( $post_id ) {
86         if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
87                 return;
88
89         if ( ! $post = get_post( $post_id ) )
90                 return;
91
92         if ( ! post_type_supports( $post->post_type, 'revisions' ) )
93                 return;
94
95         if ( 'auto-draft' == $post->post_status )
96                 return;
97
98         if ( ! wp_revisions_enabled( $post ) )
99                 return;
100
101         // Compare the proposed update with the last stored revision verifying that
102         // they are different, unless a plugin tells us to always save regardless.
103         // If no previous revisions, save one
104         if ( $revisions = wp_get_post_revisions( $post_id ) ) {
105                 // grab the last revision, but not an autosave
106                 foreach ( $revisions as $revision ) {
107                         if ( false !== strpos( $revision->post_name, "{$revision->post_parent}-revision" ) ) {
108                                 $last_revision = $revision;
109                                 break;
110                         }
111                 }
112
113                 /**
114                  * Filter whether the post has changed since the last revision.
115                  *
116                  * By default a revision is saved only if one of the revisioned fields has changed.
117                  * This filter can override that so a revision is saved even if nothing has changed.
118                  *
119                  * @since 3.6.0
120                  *
121                  * @param bool    $check_for_changes Whether to check for changes before saving a new revision.
122                  *                                   Default true.
123                  * @param WP_Post $last_revision     The the last revision post object.
124                  * @param WP_Post $post              The post object.
125                  *
126                  */
127                 if ( isset( $last_revision ) && apply_filters( 'wp_save_post_revision_check_for_changes', $check_for_changes = true, $last_revision, $post ) ) {
128                         $post_has_changed = false;
129
130                         foreach ( array_keys( _wp_post_revision_fields() ) as $field ) {
131                                 if ( normalize_whitespace( $post->$field ) != normalize_whitespace( $last_revision->$field ) ) {
132                                         $post_has_changed = true;
133                                         break;
134                                 }
135                         }
136
137                         /**
138                          * Filter whether a post has changed.
139                          *
140                          * By default a revision is saved only if one of the revisioned fields has changed.
141                          * This filter allows for additional checks to determine if there were changes.
142                          *
143                          * @since 4.1.0
144                          *
145                          * @param bool    $post_has_changed Whether the post has changed.
146                          * @param WP_Post $last_revision    The last revision post object.
147                          * @param WP_Post $post             The post object.
148                          *
149                          */
150                         $post_has_changed = (bool) apply_filters( 'wp_save_post_revision_post_has_changed', $post_has_changed, $last_revision, $post );
151
152                         //don't save revision if post unchanged
153                         if ( ! $post_has_changed ) {
154                                 return;
155                         }
156                 }
157         }
158
159         $return = _wp_put_post_revision( $post );
160
161         // If a limit for the number of revisions to keep has been set,
162         // delete the oldest ones.
163         $revisions_to_keep = wp_revisions_to_keep( $post );
164
165         if ( $revisions_to_keep < 0 )
166                 return $return;
167
168         $revisions = wp_get_post_revisions( $post_id, array( 'order' => 'ASC' ) );
169
170         $delete = count($revisions) - $revisions_to_keep;
171
172         if ( $delete < 1 )
173                 return $return;
174
175         $revisions = array_slice( $revisions, 0, $delete );
176
177         for ( $i = 0; isset( $revisions[$i] ); $i++ ) {
178                 if ( false !== strpos( $revisions[ $i ]->post_name, 'autosave' ) )
179                         continue;
180
181                 wp_delete_post_revision( $revisions[ $i ]->ID );
182         }
183
184         return $return;
185 }
186
187 /**
188  * Retrieve the autosaved data of the specified post.
189  *
190  * Returns a post object containing the information that was autosaved for the
191  * specified post. If the optional $user_id is passed, returns the autosave for that user
192  * otherwise returns the latest autosave.
193  *
194  * @since 2.6.0
195  *
196  * @param int $post_id The post ID.
197  * @param int $user_id Optional The post author ID.
198  * @return WP_Post|false The autosaved data or false on failure or when no autosave exists.
199  */
200 function wp_get_post_autosave( $post_id, $user_id = 0 ) {
201         $revisions = wp_get_post_revisions( $post_id, array( 'check_enabled' => false ) );
202
203         foreach ( $revisions as $revision ) {
204                 if ( false !== strpos( $revision->post_name, "{$post_id}-autosave" ) ) {
205                         if ( $user_id && $user_id != $revision->post_author )
206                                 continue;
207
208                         return $revision;
209                 }
210         }
211
212         return false;
213 }
214
215 /**
216  * Determines if the specified post is a revision.
217  *
218  * @since 2.6.0
219  *
220  * @param int|WP_Post $post Post ID or post object.
221  * @return false|int False if not a revision, ID of revision's parent otherwise.
222  */
223 function wp_is_post_revision( $post ) {
224         if ( !$post = wp_get_post_revision( $post ) )
225                 return false;
226
227         return (int) $post->post_parent;
228 }
229
230 /**
231  * Determines if the specified post is an autosave.
232  *
233  * @since 2.6.0
234  *
235  * @param int|WP_Post $post Post ID or post object.
236  * @return false|int False if not a revision, ID of autosave's parent otherwise
237  */
238 function wp_is_post_autosave( $post ) {
239         if ( !$post = wp_get_post_revision( $post ) )
240                 return false;
241
242         if ( false !== strpos( $post->post_name, "{$post->post_parent}-autosave" ) )
243                 return (int) $post->post_parent;
244
245         return false;
246 }
247
248 /**
249  * Inserts post data into the posts table as a post revision.
250  *
251  * @since 2.6.0
252  * @access private
253  *
254  * @param int|WP_Post|array|null $post     Post ID, post object OR post array.
255  * @param bool                   $autosave Optional. Is the revision an autosave?
256  * @return int|WP_Error WP_Error or 0 if error, new revision ID if success.
257  */
258 function _wp_put_post_revision( $post = null, $autosave = false ) {
259         if ( is_object($post) )
260                 $post = get_object_vars( $post );
261         elseif ( !is_array($post) )
262                 $post = get_post($post, ARRAY_A);
263
264         if ( ! $post || empty($post['ID']) )
265                 return new WP_Error( 'invalid_post', __( 'Invalid post ID.' ) );
266
267         if ( isset($post['post_type']) && 'revision' == $post['post_type'] )
268                 return new WP_Error( 'post_type', __( 'Cannot create a revision of a revision' ) );
269
270         $post = _wp_post_revision_fields( $post, $autosave );
271         $post = wp_slash($post); //since data is from db
272
273         $revision_id = wp_insert_post( $post );
274         if ( is_wp_error($revision_id) )
275                 return $revision_id;
276
277         if ( $revision_id ) {
278                 /**
279                  * Fires once a revision has been saved.
280                  *
281                  * @since 2.6.0
282                  *
283                  * @param int $revision_id Post revision ID.
284                  */
285                 do_action( '_wp_put_post_revision', $revision_id );
286         }
287
288         return $revision_id;
289 }
290
291 /**
292  * Gets a post revision.
293  *
294  * @since 2.6.0
295  *
296  * @param int|WP_Post $post   The post ID or object.
297  * @param string      $output Optional. OBJECT, ARRAY_A, or ARRAY_N.
298  * @param string      $filter Optional sanitation filter. @see sanitize_post().
299  * @return WP_Post|array|null Null if error or post object if success.
300  */
301 function wp_get_post_revision(&$post, $output = OBJECT, $filter = 'raw') {
302         if ( !$revision = get_post( $post, OBJECT, $filter ) )
303                 return $revision;
304         if ( 'revision' !== $revision->post_type )
305                 return null;
306
307         if ( $output == OBJECT ) {
308                 return $revision;
309         } elseif ( $output == ARRAY_A ) {
310                 $_revision = get_object_vars($revision);
311                 return $_revision;
312         } elseif ( $output == ARRAY_N ) {
313                 $_revision = array_values(get_object_vars($revision));
314                 return $_revision;
315         }
316
317         return $revision;
318 }
319
320 /**
321  * Restores a post to the specified revision.
322  *
323  * Can restore a past revision using all fields of the post revision, or only selected fields.
324  *
325  * @since 2.6.0
326  *
327  * @param int|WP_Post $revision_id Revision ID or revision object.
328  * @param array       $fields      Optional. What fields to restore from. Defaults to all.
329  * @return int|false|null Null if error, false if no fields to restore, (int) post ID if success.
330  */
331 function wp_restore_post_revision( $revision_id, $fields = null ) {
332         if ( !$revision = wp_get_post_revision( $revision_id, ARRAY_A ) )
333                 return $revision;
334
335         if ( !is_array( $fields ) )
336                 $fields = array_keys( _wp_post_revision_fields() );
337
338         $update = array();
339         foreach ( array_intersect( array_keys( $revision ), $fields ) as $field ) {
340                 $update[$field] = $revision[$field];
341         }
342
343         if ( !$update )
344                 return false;
345
346         $update['ID'] = $revision['post_parent'];
347
348         $update = wp_slash( $update ); //since data is from db
349
350         $post_id = wp_update_post( $update );
351         if ( ! $post_id || is_wp_error( $post_id ) )
352                 return $post_id;
353
354         // Add restore from details
355         $restore_details = array(
356                 'restored_revision_id' => $revision_id,
357                 'restored_by_user'     => get_current_user_id(),
358                 'restored_time'        => time()
359         );
360         update_post_meta( $post_id, '_post_restored_from', $restore_details );
361
362         // Update last edit user
363         update_post_meta( $post_id, '_edit_last', get_current_user_id() );
364
365         /**
366          * Fires after a post revision has been restored.
367          *
368          * @since 2.6.0
369          *
370          * @param int $post_id     Post ID.
371          * @param int $revision_id Post revision ID.
372          */
373         do_action( 'wp_restore_post_revision', $post_id, $revision['ID'] );
374
375         return $post_id;
376 }
377
378 /**
379  * Deletes a revision.
380  *
381  * Deletes the row from the posts table corresponding to the specified revision.
382  *
383  * @since 2.6.0
384  *
385  * @param int|WP_Post $revision_id Revision ID or revision object.
386  * @return array|false|WP_Post|WP_Error|null Null or WP_Error if error, deleted post if success.
387  */
388 function wp_delete_post_revision( $revision_id ) {
389         if ( ! $revision = wp_get_post_revision( $revision_id ) ) {
390                 return $revision;
391         }
392
393         $delete = wp_delete_post( $revision->ID );
394         if ( $delete ) {
395                 /**
396                  * Fires once a post revision has been deleted.
397                  *
398                  * @since 2.6.0
399                  *
400                  * @param int          $revision_id Post revision ID.
401                  * @param object|array $revision    Post revision object or array.
402                  */
403                 do_action( 'wp_delete_post_revision', $revision->ID, $revision );
404         }
405
406         return $delete;
407 }
408
409 /**
410  * Returns all revisions of specified post.
411  *
412  * @since 2.6.0
413  *
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.
416  */
417 function wp_get_post_revisions( $post_id = 0, $args = null ) {
418         $post = get_post( $post_id );
419         if ( ! $post || empty( $post->ID ) )
420                 return array();
421
422         $defaults = array( 'order' => 'DESC', 'orderby' => 'date ID', 'check_enabled' => true );
423         $args = wp_parse_args( $args, $defaults );
424
425         if ( $args['check_enabled'] && ! wp_revisions_enabled( $post ) )
426                 return array();
427
428         $args = array_merge( $args, array( 'post_parent' => $post->ID, 'post_type' => 'revision', 'post_status' => 'inherit' ) );
429
430         if ( ! $revisions = get_children( $args ) )
431                 return array();
432
433         return $revisions;
434 }
435
436 /**
437  * Determine if revisions are enabled for a given post.
438  *
439  * @since 3.6.0
440  *
441  * @param WP_Post $post The post object.
442  * @return bool True if number of revisions to keep isn't zero, false otherwise.
443  */
444 function wp_revisions_enabled( $post ) {
445         return wp_revisions_to_keep( $post ) !== 0;
446 }
447
448 /**
449  * Determine how many revisions to retain for a given post.
450  *
451  * By default, an infinite number of revisions are kept.
452  *
453  * The constant WP_POST_REVISIONS can be set in wp-config to specify the limit
454  * of revisions to keep.
455  *
456  * @since 3.6.0
457  *
458  * @param WP_Post $post The post object.
459  * @return int The number of revisions to keep.
460  */
461 function wp_revisions_to_keep( $post ) {
462         $num = WP_POST_REVISIONS;
463
464         if ( true === $num )
465                 $num = -1;
466         else
467                 $num = intval( $num );
468
469         if ( ! post_type_supports( $post->post_type, 'revisions' ) )
470                 $num = 0;
471
472         /**
473          * Filter the number of revisions to save for the given post.
474          *
475          * Overrides the value of WP_POST_REVISIONS.
476          *
477          * @since 3.6.0
478          *
479          * @param int     $num  Number of revisions to store.
480          * @param WP_Post $post Post object.
481          */
482         return (int) apply_filters( 'wp_revisions_to_keep', $num, $post );
483 }
484
485 /**
486  * Sets up the post object for preview based on the post autosave.
487  *
488  * @since 2.7.0
489  * @access private
490  *
491  * @param WP_Post $post
492  * @return WP_Post|false
493  */
494 function _set_preview( $post ) {
495         if ( ! is_object( $post ) ) {
496                 return $post;
497         }
498
499         $preview = wp_get_post_autosave( $post->ID );
500         if ( ! is_object( $preview ) ) {
501                 return $post;
502         }
503
504         $preview = sanitize_post( $preview );
505
506         $post->post_content = $preview->post_content;
507         $post->post_title = $preview->post_title;
508         $post->post_excerpt = $preview->post_excerpt;
509
510         add_filter( 'get_the_terms', '_wp_preview_terms_filter', 10, 3 );
511
512         return $post;
513 }
514
515 /**
516  * Filters the latest content for preview from the post autosave.
517  *
518  * @since 2.7.0
519  * @access private
520  */
521 function _show_post_preview() {
522         if ( isset($_GET['preview_id']) && isset($_GET['preview_nonce']) ) {
523                 $id = (int) $_GET['preview_id'];
524
525                 if ( false === wp_verify_nonce( $_GET['preview_nonce'], 'post_preview_' . $id ) )
526                         wp_die( __('You do not have permission to preview drafts.') );
527
528                 add_filter('the_preview', '_set_preview');
529         }
530 }
531
532 /**
533  * Filters terms lookup to set the post format.
534  *
535  * @since 3.6.0
536  * @access private
537  *
538  * @param array  $terms
539  * @param int    $post_id
540  * @param string $taxonomy
541  * @return array
542  */
543 function _wp_preview_terms_filter( $terms, $post_id, $taxonomy ) {
544         if ( ! $post = get_post() )
545                 return $terms;
546
547         if ( empty( $_REQUEST['post_format'] ) || $post->ID != $post_id || 'post_format' != $taxonomy || 'revision' == $post->post_type )
548                 return $terms;
549
550         if ( 'standard' == $_REQUEST['post_format'] )
551                 $terms = array();
552         elseif ( $term = get_term_by( 'slug', 'post-format-' . sanitize_key( $_REQUEST['post_format'] ), 'post_format' ) )
553                 $terms = array( $term ); // Can only have one post format
554
555         return $terms;
556 }
557
558 /**
559  * Gets the post revision version.
560  *
561  * @since 3.6.0
562  * @access private
563  *
564  * @param WP_Post $revision
565  * @return int|false
566  */
567 function _wp_get_post_revision_version( $revision ) {
568         if ( is_object( $revision ) )
569                 $revision = get_object_vars( $revision );
570         elseif ( !is_array( $revision ) )
571                 return false;
572
573         if ( preg_match( '/^\d+-(?:autosave|revision)-v(\d+)$/', $revision['post_name'], $matches ) )
574                 return (int) $matches[1];
575
576         return 0;
577 }
578
579 /**
580  * Upgrade the revisions author, add the current post as a revision and set the revisions version to 1
581  *
582  * @since 3.6.0
583  * @access private
584  *
585  * @global wpdb $wpdb WordPress database abstraction object.
586  *
587  * @param WP_Post $post      Post object
588  * @param array   $revisions Current revisions of the post
589  * @return bool true if the revisions were upgraded, false if problems
590  */
591 function _wp_upgrade_revisions_of_post( $post, $revisions ) {
592         global $wpdb;
593
594         // Add post option exclusively
595         $lock = "revision-upgrade-{$post->ID}";
596         $now = time();
597         $result = $wpdb->query( $wpdb->prepare( "INSERT IGNORE INTO `$wpdb->options` (`option_name`, `option_value`, `autoload`) VALUES (%s, %s, 'no') /* LOCK */", $lock, $now ) );
598         if ( ! $result ) {
599                 // If we couldn't get a lock, see how old the previous lock is
600                 $locked = get_option( $lock );
601                 if ( ! $locked ) {
602                         // Can't write to the lock, and can't read the lock.
603                         // Something broken has happened
604                         return false;
605                 }
606
607                 if ( $locked > $now - 3600 ) {
608                         // Lock is not too old: some other process may be upgrading this post.  Bail.
609                         return false;
610                 }
611
612                 // Lock is too old - update it (below) and continue
613         }
614
615         // If we could get a lock, re-"add" the option to fire all the correct filters.
616         update_option( $lock, $now );
617
618         reset( $revisions );
619         $add_last = true;
620
621         do {
622                 $this_revision = current( $revisions );
623                 $prev_revision = next( $revisions );
624
625                 $this_revision_version = _wp_get_post_revision_version( $this_revision );
626
627                 // Something terrible happened
628                 if ( false === $this_revision_version )
629                         continue;
630
631                 // 1 is the latest revision version, so we're already up to date.
632                 // No need to add a copy of the post as latest revision.
633                 if ( 0 < $this_revision_version ) {
634                         $add_last = false;
635                         continue;
636                 }
637
638                 // Always update the revision version
639                 $update = array(
640                         'post_name' => preg_replace( '/^(\d+-(?:autosave|revision))[\d-]*$/', '$1-v1', $this_revision->post_name ),
641                 );
642
643                 // If this revision is the oldest revision of the post, i.e. no $prev_revision,
644                 // the correct post_author is probably $post->post_author, but that's only a good guess.
645                 // Update the revision version only and Leave the author as-is.
646                 if ( $prev_revision ) {
647                         $prev_revision_version = _wp_get_post_revision_version( $prev_revision );
648
649                         // If the previous revision is already up to date, it no longer has the information we need :(
650                         if ( $prev_revision_version < 1 )
651                                 $update['post_author'] = $prev_revision->post_author;
652                 }
653
654                 // Upgrade this revision
655                 $result = $wpdb->update( $wpdb->posts, $update, array( 'ID' => $this_revision->ID ) );
656
657                 if ( $result )
658                         wp_cache_delete( $this_revision->ID, 'posts' );
659
660         } while ( $prev_revision );
661
662         delete_option( $lock );
663
664         // Add a copy of the post as latest revision.
665         if ( $add_last )
666                 wp_save_post_revision( $post->ID );
667
668         return true;
669 }