[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

Search

title

Body

[close]

/wp-includes/ -> revision.php (source)

   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   * @since 2.6.0
  13   * @since 4.5.0 A `WP_Post` object can now be passed to the `$post` parameter.
  14   * @since 4.5.0 The optional `$autosave` parameter was deprecated and renamed to `$deprecated`.
  15   * @access private
  16   *
  17   * @param array|WP_Post $post       Optional. A post array or a WP_Post object being processed
  18   *                                  for insertion as a post revision. Default empty array.
  19   * @param bool          $deprecated Not used.
  20   * @return string[] Array of fields that can be versioned.
  21   */
  22  function _wp_post_revision_fields( $post = array(), $deprecated = false ) {
  23      static $fields = null;
  24  
  25      if ( ! is_array( $post ) ) {
  26          $post = get_post( $post, ARRAY_A );
  27      }
  28  
  29      if ( is_null( $fields ) ) {
  30          // Allow these to be versioned.
  31          $fields = array(
  32              'post_title'   => __( 'Title' ),
  33              'post_content' => __( 'Content' ),
  34              'post_excerpt' => __( 'Excerpt' ),
  35          );
  36      }
  37  
  38      /**
  39       * Filters the list of fields saved in post revisions.
  40       *
  41       * Included by default: 'post_title', 'post_content' and 'post_excerpt'.
  42       *
  43       * Disallowed fields: 'ID', 'post_name', 'post_parent', 'post_date',
  44       * 'post_date_gmt', 'post_status', 'post_type', 'comment_count',
  45       * and 'post_author'.
  46       *
  47       * @since 2.6.0
  48       * @since 4.5.0 The `$post` parameter was added.
  49       *
  50       * @param string[] $fields List of fields to revision. Contains 'post_title',
  51       *                         'post_content', and 'post_excerpt' by default.
  52       * @param array    $post   A post array being processed for insertion as a post revision.
  53       */
  54      $fields = apply_filters( '_wp_post_revision_fields', $fields, $post );
  55  
  56      // WP uses these internally either in versioning or elsewhere - they cannot be versioned.
  57      foreach ( array( 'ID', 'post_name', 'post_parent', 'post_date', 'post_date_gmt', 'post_status', 'post_type', 'comment_count', 'post_author' ) as $protect ) {
  58          unset( $fields[ $protect ] );
  59      }
  60  
  61      return $fields;
  62  }
  63  
  64  /**
  65   * Returns a post array ready to be inserted into the posts table as a post revision.
  66   *
  67   * @since 4.5.0
  68   * @access private
  69   *
  70   * @param array|WP_Post $post     Optional. A post array or a WP_Post object to be processed
  71   *                                for insertion as a post revision. Default empty array.
  72   * @param bool          $autosave Optional. Is the revision an autosave? Default false.
  73   * @return array Post array ready to be inserted as a post revision.
  74   */
  75  function _wp_post_revision_data( $post = array(), $autosave = false ) {
  76      if ( ! is_array( $post ) ) {
  77          $post = get_post( $post, ARRAY_A );
  78      }
  79  
  80      $fields = _wp_post_revision_fields( $post );
  81  
  82      $revision_data = array();
  83  
  84      foreach ( array_intersect( array_keys( $post ), array_keys( $fields ) ) as $field ) {
  85          $revision_data[ $field ] = $post[ $field ];
  86      }
  87  
  88      $revision_data['post_parent']   = $post['ID'];
  89      $revision_data['post_status']   = 'inherit';
  90      $revision_data['post_type']     = 'revision';
  91      $revision_data['post_name']     = $autosave ? "$post[ID]-autosave-v1" : "$post[ID]-revision-v1"; // "1" is the revisioning system version.
  92      $revision_data['post_date']     = $post['post_modified'] ?? '';
  93      $revision_data['post_date_gmt'] = $post['post_modified_gmt'] ?? '';
  94  
  95      return $revision_data;
  96  }
  97  
  98  /**
  99   * Saves revisions for a post after all changes have been made.
 100   *
 101   * @since 6.4.0
 102   *
 103   * @param int     $post_id The post id that was inserted.
 104   * @param WP_Post $post    The post object that was inserted.
 105   * @param bool    $update  Whether this insert is updating an existing post.
 106   */
 107  function wp_save_post_revision_on_insert( $post_id, $post, $update ) {
 108      if ( ! $update ) {
 109          return;
 110      }
 111  
 112      if ( ! has_action( 'post_updated', 'wp_save_post_revision' ) ) {
 113          return;
 114      }
 115  
 116      wp_save_post_revision( $post_id );
 117  }
 118  
 119  /**
 120   * Creates a revision for the current version of a post.
 121   *
 122   * Typically used immediately after a post update, as every update is a revision,
 123   * and the most recent revision always matches the current post.
 124   *
 125   * @since 2.6.0
 126   *
 127   * @param int $post_id The ID of the post to save as a revision.
 128   * @return int|WP_Error|null Null or 0 if error, new revision ID, if success.
 129   */
 130  function wp_save_post_revision( $post_id ) {
 131      if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
 132          return null;
 133      }
 134  
 135      // Prevent saving post revisions if revisions should be saved on wp_after_insert_post.
 136      if ( doing_action( 'post_updated' ) && has_action( 'wp_after_insert_post', 'wp_save_post_revision_on_insert' ) ) {
 137          return null;
 138      }
 139  
 140      $post = get_post( $post_id );
 141  
 142      if ( ! $post ) {
 143          return null;
 144      }
 145  
 146      if ( ! post_type_supports( $post->post_type, 'revisions' ) ) {
 147          return null;
 148      }
 149  
 150      if ( 'auto-draft' === $post->post_status ) {
 151          return null;
 152      }
 153  
 154      if ( ! wp_revisions_enabled( $post ) ) {
 155          return null;
 156      }
 157  
 158      /*
 159       * Compare the proposed update with the last stored revision verifying that
 160       * they are different, unless a plugin tells us to always save regardless.
 161       * If no previous revisions, save one.
 162       */
 163      $revisions = wp_get_post_revisions( $post_id );
 164      if ( $revisions ) {
 165          // Grab the latest revision, but not an autosave.
 166          foreach ( $revisions as $revision ) {
 167              if ( str_contains( $revision->post_name, "{$revision->post_parent}-revision" ) ) {
 168                  $latest_revision = $revision;
 169                  break;
 170              }
 171          }
 172  
 173          /**
 174           * Filters whether the post has changed since the latest revision.
 175           *
 176           * By default a revision is saved only if one of the revisioned fields has changed.
 177           * This filter can override that so a revision is saved even if nothing has changed.
 178           *
 179           * @since 3.6.0
 180           *
 181           * @param bool    $check_for_changes Whether to check for changes before saving a new revision.
 182           *                                   Default true.
 183           * @param WP_Post $latest_revision   The latest revision post object.
 184           * @param WP_Post $post              The post object.
 185           */
 186          if ( isset( $latest_revision ) && apply_filters( 'wp_save_post_revision_check_for_changes', true, $latest_revision, $post ) ) {
 187              $post_has_changed = false;
 188  
 189              foreach ( array_keys( _wp_post_revision_fields( $post ) ) as $field ) {
 190                  if ( normalize_whitespace( maybe_serialize( $post->$field ) ) !== normalize_whitespace( maybe_serialize( $latest_revision->$field ) ) ) {
 191                      $post_has_changed = true;
 192                      break;
 193                  }
 194              }
 195  
 196              /**
 197               * Filters whether a post has changed.
 198               *
 199               * By default a revision is saved only if one of the revisioned fields has changed.
 200               * This filter allows for additional checks to determine if there were changes.
 201               *
 202               * @since 4.1.0
 203               *
 204               * @param bool    $post_has_changed Whether the post has changed.
 205               * @param WP_Post $latest_revision  The latest revision post object.
 206               * @param WP_Post $post             The post object.
 207               */
 208              $post_has_changed = (bool) apply_filters( 'wp_save_post_revision_post_has_changed', $post_has_changed, $latest_revision, $post );
 209  
 210              // Don't save revision if post unchanged.
 211              if ( ! $post_has_changed ) {
 212                  return null;
 213              }
 214          }
 215      }
 216  
 217      $return = _wp_put_post_revision( $post );
 218  
 219      /*
 220       * If a limit for the number of revisions to keep has been set,
 221       * delete the oldest ones.
 222       */
 223      $revisions_to_keep = wp_revisions_to_keep( $post );
 224  
 225      if ( $revisions_to_keep < 0 ) {
 226          return $return;
 227      }
 228  
 229      $revisions = wp_get_post_revisions( $post_id, array( 'order' => 'ASC' ) );
 230  
 231      /**
 232       * Filters the revisions to be considered for deletion.
 233       *
 234       * @since 6.2.0
 235       *
 236       * @param WP_Post[] $revisions Array of revisions, or an empty array if none.
 237       * @param int       $post_id   The ID of the post to save as a revision.
 238       */
 239      $revisions = apply_filters(
 240          'wp_save_post_revision_revisions_before_deletion',
 241          $revisions,
 242          $post_id
 243      );
 244  
 245      $delete = count( $revisions ) - $revisions_to_keep;
 246  
 247      if ( $delete < 1 ) {
 248          return $return;
 249      }
 250  
 251      $revisions = array_slice( $revisions, 0, $delete );
 252  
 253      for ( $i = 0; isset( $revisions[ $i ] ); $i++ ) {
 254          if ( str_contains( $revisions[ $i ]->post_name, 'autosave' ) ) {
 255              continue;
 256          }
 257  
 258          wp_delete_post_revision( $revisions[ $i ]->ID );
 259      }
 260  
 261      return $return;
 262  }
 263  
 264  /**
 265   * Retrieves the autosaved data of the specified post.
 266   *
 267   * Returns a post object with the information that was autosaved for the specified post.
 268   * If the optional $user_id is passed, returns the autosave for that user, otherwise
 269   * returns the latest autosave.
 270   *
 271   * @since 2.6.0
 272   *
 273   * @param int $post_id The post ID.
 274   * @param int $user_id Optional. The post author ID. Default 0.
 275   * @return WP_Post|false The autosaved data or false on failure or when no autosave exists.
 276   */
 277  function wp_get_post_autosave( $post_id, $user_id = 0 ) {
 278      $args = array(
 279          'post_type'      => 'revision',
 280          'post_status'    => 'inherit',
 281          'post_parent'    => $post_id,
 282          'name'           => $post_id . '-autosave-v1',
 283          'posts_per_page' => 1,
 284          'orderby'        => 'date',
 285          'order'          => 'DESC',
 286          'fields'         => 'ids',
 287          'no_found_rows'  => true,
 288      );
 289  
 290      if ( 0 !== $user_id ) {
 291          $args['author'] = $user_id;
 292      }
 293  
 294      $query = new WP_Query( $args );
 295  
 296      if ( ! $query->have_posts() ) {
 297          return false;
 298      }
 299  
 300      return get_post( $query->posts[0] );
 301  }
 302  
 303  /**
 304   * Determines if the specified post is a revision.
 305   *
 306   * @since 2.6.0
 307   *
 308   * @param int|WP_Post $post Post ID or post object.
 309   * @return int|false ID of revision's parent on success, false if not a revision.
 310   */
 311  function wp_is_post_revision( $post ) {
 312      $post = wp_get_post_revision( $post );
 313  
 314      if ( ! $post ) {
 315          return false;
 316      }
 317  
 318      return (int) $post->post_parent;
 319  }
 320  
 321  /**
 322   * Determines if the specified post is an autosave.
 323   *
 324   * @since 2.6.0
 325   *
 326   * @param int|WP_Post $post Post ID or post object.
 327   * @return int|false ID of autosave's parent on success, false if not a revision.
 328   */
 329  function wp_is_post_autosave( $post ) {
 330      $post = wp_get_post_revision( $post );
 331  
 332      if ( ! $post ) {
 333          return false;
 334      }
 335  
 336      if ( str_contains( $post->post_name, "{$post->post_parent}-autosave" ) ) {
 337          return (int) $post->post_parent;
 338      }
 339  
 340      return false;
 341  }
 342  
 343  /**
 344   * Inserts post data into the posts table as a post revision.
 345   *
 346   * @since 2.6.0
 347   * @access private
 348   *
 349   * @param int|WP_Post|array|null $post     Post ID, post object OR post array.
 350   * @param bool                   $autosave Optional. Whether the revision is an autosave or not.
 351   *                                         Default false.
 352   * @return int|WP_Error WP_Error or 0 if error, new revision ID if success.
 353   */
 354  function _wp_put_post_revision( $post = null, $autosave = false ) {
 355      if ( is_object( $post ) ) {
 356          $post = get_object_vars( $post );
 357      } elseif ( ! is_array( $post ) ) {
 358          $post = get_post( $post, ARRAY_A );
 359      }
 360  
 361      if ( ! $post || empty( $post['ID'] ) ) {
 362          return new WP_Error( 'invalid_post', __( 'Invalid post ID.' ) );
 363      }
 364  
 365      if ( isset( $post['post_type'] ) && 'revision' === $post['post_type'] ) {
 366          return new WP_Error( 'post_type', __( 'Cannot create a revision of a revision' ) );
 367      }
 368  
 369      $post = _wp_post_revision_data( $post, $autosave );
 370      $post = wp_slash( $post ); // Since data is from DB.
 371  
 372      $revision_id = wp_insert_post( $post, true );
 373      if ( is_wp_error( $revision_id ) ) {
 374          return $revision_id;
 375      }
 376  
 377      if ( $revision_id ) {
 378          /**
 379           * Fires once a revision has been saved.
 380           *
 381           * @since 2.6.0
 382           * @since 6.4.0 The `$post_id` parameter was added.
 383           *
 384           * @param int $revision_id Post revision ID.
 385           * @param int $post_id     Post ID.
 386           */
 387          do_action( '_wp_put_post_revision', $revision_id, $post['post_parent'] );
 388      }
 389  
 390      return $revision_id;
 391  }
 392  
 393  
 394  /**
 395   * Save the revisioned meta fields.
 396   *
 397   * @since 6.4.0
 398   *
 399   * @param int $revision_id The ID of the revision to save the meta to.
 400   * @param int $post_id     The ID of the post the revision is associated with.
 401   */
 402  function wp_save_revisioned_meta_fields( $revision_id, $post_id ) {
 403      $post_type = get_post_type( $post_id );
 404      if ( ! $post_type ) {
 405          return;
 406      }
 407  
 408      foreach ( wp_post_revision_meta_keys( $post_type ) as $meta_key ) {
 409          if ( metadata_exists( 'post', $post_id, $meta_key ) ) {
 410              _wp_copy_post_meta( $post_id, $revision_id, $meta_key );
 411          }
 412      }
 413  }
 414  
 415  /**
 416   * Gets a post revision.
 417   *
 418   * @since 2.6.0
 419   *
 420   * @param int|WP_Post $post   Post ID or post object.
 421   * @param string      $output Optional. The required return type. One of OBJECT, ARRAY_A, or ARRAY_N, which
 422   *                            correspond to a WP_Post object, an associative array, or a numeric array,
 423   *                            respectively. Default OBJECT.
 424   * @param string      $filter Optional sanitization filter. See sanitize_post(). Default 'raw'.
 425   * @return WP_Post|array|null WP_Post (or array) on success, or null on failure.
 426   *
 427   * @phpstan-param int|WP_Post $post
 428   * @phpstan-param 'OBJECT'|'ARRAY_A'|'ARRAY_N' $output
 429   * @phpstan-param 'raw'|'edit'|'db'|'display' $filter
 430   * @phpstan-return (
 431   *     $output is 'ARRAY_A' ? non-empty-array<string, mixed>|null : (
 432   *         $output is 'ARRAY_N' ? non-empty-array<int, mixed>|null : (
 433   *             WP_Post|null
 434   *         )
 435   *     )
 436   * )
 437   */
 438  function wp_get_post_revision( &$post, $output = OBJECT, $filter = 'raw' ) {
 439      $revision = get_post( $post, OBJECT, $filter );
 440  
 441      if ( ! $revision ) {
 442          return $revision;
 443      }
 444  
 445      if ( 'revision' !== $revision->post_type ) {
 446          return null;
 447      }
 448  
 449      if ( OBJECT === $output ) {
 450          return $revision;
 451      } elseif ( ARRAY_A === $output ) {
 452          /** @var non-empty-array<string, mixed> $_revision */
 453          $_revision = get_object_vars( $revision );
 454          return $_revision;
 455      } elseif ( ARRAY_N === $output ) {
 456          /** @var non-empty-array<string, mixed> $vars */
 457          $vars      = get_object_vars( $revision );
 458          $_revision = array_values( $vars );
 459          return $_revision;
 460      }
 461  
 462      return $revision;
 463  }
 464  
 465  /**
 466   * Restores a post to the specified revision.
 467   *
 468   * Can restore a past revision using all fields of the post revision, or only selected fields.
 469   *
 470   * @since 2.6.0
 471   *
 472   * @param int|WP_Post $revision Revision ID or revision object.
 473   * @param array       $fields   Optional. What fields to restore from. Defaults to all.
 474   * @return int|false|null Null if error, false if no fields to restore, (int) post ID if success.
 475   */
 476  function wp_restore_post_revision( $revision, $fields = null ) {
 477      $revision = wp_get_post_revision( $revision, ARRAY_A );
 478  
 479      if ( ! $revision ) {
 480          return $revision;
 481      }
 482  
 483      if ( ! is_array( $fields ) ) {
 484          $fields = array_keys( _wp_post_revision_fields( $revision ) );
 485      }
 486  
 487      $update = array();
 488      foreach ( array_intersect( array_keys( $revision ), $fields ) as $field ) {
 489          $update[ $field ] = $revision[ $field ];
 490      }
 491  
 492      if ( ! $update ) {
 493          return false;
 494      }
 495  
 496      $update['ID'] = $revision['post_parent'];
 497  
 498      $update = wp_slash( $update ); // Since data is from DB.
 499  
 500      $post_id = wp_update_post( $update );
 501  
 502      if ( ! $post_id || is_wp_error( $post_id ) ) {
 503          return $post_id;
 504      }
 505  
 506      // Update last edit user.
 507      update_post_meta( $post_id, '_edit_last', get_current_user_id() );
 508  
 509      /**
 510       * Fires after a post revision has been restored.
 511       *
 512       * @since 2.6.0
 513       *
 514       * @param int $post_id     Post ID.
 515       * @param int $revision_id Post revision ID.
 516       */
 517      do_action( 'wp_restore_post_revision', $post_id, $revision['ID'] );
 518  
 519      return $post_id;
 520  }
 521  
 522  /**
 523   * Restore the revisioned meta values for a post.
 524   *
 525   * @since 6.4.0
 526   *
 527   * @param int $post_id     The ID of the post to restore the meta to.
 528   * @param int $revision_id The ID of the revision to restore the meta from.
 529   */
 530  function wp_restore_post_revision_meta( $post_id, $revision_id ) {
 531      $post_type = get_post_type( $post_id );
 532      if ( ! $post_type ) {
 533          return;
 534      }
 535  
 536      // Restore revisioned meta fields.
 537      foreach ( wp_post_revision_meta_keys( $post_type ) as $meta_key ) {
 538  
 539          // Clear any existing meta.
 540          delete_post_meta( $post_id, $meta_key );
 541  
 542          _wp_copy_post_meta( $revision_id, $post_id, $meta_key );
 543      }
 544  }
 545  
 546  /**
 547   * Copy post meta for the given key from one post to another.
 548   *
 549   * @since 6.4.0
 550   *
 551   * @param int    $source_post_id Post ID to copy meta value(s) from.
 552   * @param int    $target_post_id Post ID to copy meta value(s) to.
 553   * @param string $meta_key       Meta key to copy.
 554   */
 555  function _wp_copy_post_meta( $source_post_id, $target_post_id, $meta_key ) {
 556  
 557      foreach ( get_post_meta( $source_post_id, $meta_key ) as $meta_value ) {
 558          /**
 559           * We use add_metadata() function vs add_post_meta() here
 560           * to allow for a revision post target OR regular post.
 561           */
 562          add_metadata( 'post', $target_post_id, $meta_key, wp_slash( $meta_value ) );
 563      }
 564  }
 565  
 566  /**
 567   * Determine which post meta fields should be revisioned.
 568   *
 569   * @since 6.4.0
 570   *
 571   * @param string $post_type The post type being revisioned.
 572   * @return array An array of meta keys to be revisioned.
 573   */
 574  function wp_post_revision_meta_keys( $post_type ) {
 575      $registered_meta = array_merge(
 576          get_registered_meta_keys( 'post' ),
 577          get_registered_meta_keys( 'post', $post_type )
 578      );
 579  
 580      $wp_revisioned_meta_keys = array();
 581  
 582      foreach ( $registered_meta as $name => $args ) {
 583          if ( $args['revisions_enabled'] ) {
 584              $wp_revisioned_meta_keys[ $name ] = true;
 585          }
 586      }
 587  
 588      $wp_revisioned_meta_keys = array_keys( $wp_revisioned_meta_keys );
 589  
 590      /**
 591       * Filter the list of post meta keys to be revisioned.
 592       *
 593       * @since 6.4.0
 594       *
 595       * @param array  $keys      An array of meta fields to be revisioned.
 596       * @param string $post_type The post type being revisioned.
 597       */
 598      return apply_filters( 'wp_post_revision_meta_keys', $wp_revisioned_meta_keys, $post_type );
 599  }
 600  
 601  /**
 602   * Check whether revisioned post meta fields have changed.
 603   *
 604   * @since 6.4.0
 605   *
 606   * @param bool    $post_has_changed Whether the post has changed.
 607   * @param WP_Post $last_revision    The last revision post object.
 608   * @param WP_Post $post             The post object.
 609   * @return bool Whether the post has changed.
 610   */
 611  function wp_check_revisioned_meta_fields_have_changed( $post_has_changed, WP_Post $last_revision, WP_Post $post ) {
 612      foreach ( wp_post_revision_meta_keys( $post->post_type ) as $meta_key ) {
 613          if ( get_post_meta( $post->ID, $meta_key ) !== get_post_meta( $last_revision->ID, $meta_key ) ) {
 614              $post_has_changed = true;
 615              break;
 616          }
 617      }
 618      return $post_has_changed;
 619  }
 620  
 621  /**
 622   * Deletes a revision.
 623   *
 624   * Deletes the row from the posts table corresponding to the specified revision.
 625   *
 626   * @since 2.6.0
 627   *
 628   * @param int|WP_Post $revision Revision ID or revision object.
 629   * @return WP_Post|false|null Null or false if error, deleted post object if success.
 630   */
 631  function wp_delete_post_revision( $revision ) {
 632      $revision = wp_get_post_revision( $revision );
 633  
 634      if ( ! $revision ) {
 635          return $revision;
 636      }
 637  
 638      $delete = wp_delete_post( $revision->ID );
 639  
 640      if ( $delete ) {
 641          /**
 642           * Fires once a post revision has been deleted.
 643           *
 644           * @since 2.6.0
 645           *
 646           * @param int     $revision_id Post revision ID.
 647           * @param WP_Post $revision    Post revision object.
 648           */
 649          do_action( 'wp_delete_post_revision', $revision->ID, $revision );
 650      }
 651  
 652      return $delete;
 653  }
 654  
 655  /**
 656   * Returns all revisions of specified post.
 657   *
 658   * @since 2.6.0
 659   *
 660   * @see get_children()
 661   *
 662   * @param int|WP_Post $post Optional. Post ID or WP_Post object. Default is global `$post`.
 663   * @param array|null  $args Optional. Arguments for retrieving post revisions. Default null.
 664   * @return WP_Post[]|int[] Array of revision objects or IDs, or an empty array if none.
 665   */
 666  function wp_get_post_revisions( $post = 0, $args = null ) {
 667      $post = get_post( $post );
 668  
 669      if ( ! $post || empty( $post->ID ) ) {
 670          return array();
 671      }
 672  
 673      $defaults = array(
 674          'order'         => 'DESC',
 675          'orderby'       => 'date ID',
 676          'check_enabled' => true,
 677      );
 678      $args     = wp_parse_args( $args, $defaults );
 679  
 680      if ( $args['check_enabled'] && ! wp_revisions_enabled( $post ) ) {
 681          return array();
 682      }
 683  
 684      $args = array_merge(
 685          $args,
 686          array(
 687              'post_parent' => $post->ID,
 688              'post_type'   => 'revision',
 689              'post_status' => 'inherit',
 690          )
 691      );
 692  
 693      $revisions = get_children( $args );
 694  
 695      if ( ! $revisions ) {
 696          return array();
 697      }
 698  
 699      return $revisions;
 700  }
 701  
 702  /**
 703   * Returns the latest revision ID and count of revisions for a post.
 704   *
 705   * @since 6.1.0
 706   *
 707   * @param int|WP_Post $post Optional. Post ID or WP_Post object. Default is global $post.
 708   * @return array|WP_Error {
 709   *     Returns associative array with latest revision ID and total count,
 710   *     or a WP_Error if the post does not exist or revisions are not enabled.
 711   *
 712   *     @type int $latest_id The latest revision post ID or 0 if no revisions exist.
 713   *     @type int $count     The total count of revisions for the given post.
 714   * }
 715   */
 716  function wp_get_latest_revision_id_and_total_count( $post = 0 ) {
 717      $post = get_post( $post );
 718  
 719      if ( ! $post ) {
 720          return new WP_Error( 'invalid_post', __( 'Invalid post.' ) );
 721      }
 722  
 723      if ( ! wp_revisions_enabled( $post ) ) {
 724          return new WP_Error( 'revisions_not_enabled', __( 'Revisions not enabled.' ) );
 725      }
 726  
 727      $args = array(
 728          'post_parent'         => $post->ID,
 729          'fields'              => 'ids',
 730          'post_type'           => 'revision',
 731          'post_status'         => 'inherit',
 732          'order'               => 'DESC',
 733          'orderby'             => 'date ID',
 734          'posts_per_page'      => 1,
 735          'ignore_sticky_posts' => true,
 736      );
 737  
 738      $revision_query = new WP_Query();
 739      $revisions      = $revision_query->query( $args );
 740  
 741      if ( ! $revisions ) {
 742          return array(
 743              'latest_id' => 0,
 744              'count'     => 0,
 745          );
 746      }
 747  
 748      return array(
 749          'latest_id' => $revisions[0],
 750          'count'     => $revision_query->found_posts,
 751      );
 752  }
 753  
 754  /**
 755   * Returns the url for viewing and potentially restoring revisions of a given post.
 756   *
 757   * @since 5.9.0
 758   *
 759   * @param int|WP_Post $post Optional. Post ID or WP_Post object. Default is global `$post`.
 760   * @return string|null The URL for editing revisions on the given post, otherwise null.
 761   */
 762  function wp_get_post_revisions_url( $post = 0 ) {
 763      $post = get_post( $post );
 764  
 765      if ( ! $post instanceof WP_Post ) {
 766          return null;
 767      }
 768  
 769      // If the post is a revision, return early.
 770      if ( 'revision' === $post->post_type ) {
 771          return get_edit_post_link( $post );
 772      }
 773  
 774      if ( ! wp_revisions_enabled( $post ) ) {
 775          return null;
 776      }
 777  
 778      $revisions = wp_get_latest_revision_id_and_total_count( $post->ID );
 779  
 780      if ( is_wp_error( $revisions ) || 0 === $revisions['count'] ) {
 781          return null;
 782      }
 783  
 784      return get_edit_post_link( $revisions['latest_id'] );
 785  }
 786  
 787  /**
 788   * Determines whether revisions are enabled for a given post.
 789   *
 790   * @since 3.6.0
 791   *
 792   * @param WP_Post $post The post object.
 793   * @return bool True if number of revisions to keep isn't zero, false otherwise.
 794   */
 795  function wp_revisions_enabled( $post ) {
 796      return wp_revisions_to_keep( $post ) !== 0;
 797  }
 798  
 799  /**
 800   * Determines how many revisions to retain for a given post.
 801   *
 802   * By default, an infinite number of revisions are kept.
 803   *
 804   * The constant WP_POST_REVISIONS can be set in wp-config to specify the limit
 805   * of revisions to keep.
 806   *
 807   * @since 3.6.0
 808   *
 809   * @param WP_Post $post The post object.
 810   * @return int The number of revisions to keep.
 811   */
 812  function wp_revisions_to_keep( $post ) {
 813      $num = WP_POST_REVISIONS;
 814  
 815      if ( true === $num ) {
 816          $num = -1;
 817      } else {
 818          $num = (int) $num;
 819      }
 820  
 821      if ( ! post_type_supports( $post->post_type, 'revisions' ) ) {
 822          $num = 0;
 823      }
 824  
 825      /**
 826       * Filters the number of revisions to save for the given post.
 827       *
 828       * Overrides the value of WP_POST_REVISIONS.
 829       *
 830       * @since 3.6.0
 831       *
 832       * @param int     $num  Number of revisions to store.
 833       * @param WP_Post $post Post object.
 834       */
 835      $num = apply_filters( 'wp_revisions_to_keep', $num, $post );
 836  
 837      /**
 838       * Filters the number of revisions to save for the given post by its post type.
 839       *
 840       * Overrides both the value of WP_POST_REVISIONS and the {@see 'wp_revisions_to_keep'} filter.
 841       *
 842       * The dynamic portion of the hook name, `$post->post_type`, refers to
 843       * the post type slug.
 844       *
 845       * Possible hook names include:
 846       *
 847       *  - `wp_post_revisions_to_keep`
 848       *  - `wp_page_revisions_to_keep`
 849       *
 850       * @since 5.8.0
 851       *
 852       * @param int     $num  Number of revisions to store.
 853       * @param WP_Post $post Post object.
 854       */
 855      $num = apply_filters( "wp_{$post->post_type}_revisions_to_keep", $num, $post );
 856  
 857      return (int) $num;
 858  }
 859  
 860  /**
 861   * Sets up the post object for preview based on the post autosave.
 862   *
 863   * @since 2.7.0
 864   * @access private
 865   *
 866   * @param WP_Post $post
 867   * @return WP_Post|false
 868   */
 869  function _set_preview( $post ) {
 870      if ( ! is_object( $post ) ) {
 871          return $post;
 872      }
 873  
 874      $preview = wp_get_post_autosave( $post->ID );
 875  
 876      if ( is_object( $preview ) ) {
 877          $preview = sanitize_post( $preview );
 878  
 879          $post->post_content = $preview->post_content;
 880          $post->post_title   = $preview->post_title;
 881          $post->post_excerpt = $preview->post_excerpt;
 882      }
 883  
 884      add_filter( 'get_the_terms', '_wp_preview_terms_filter', 10, 3 );
 885      add_filter( 'get_post_metadata', '_wp_preview_post_thumbnail_filter', 10, 3 );
 886      add_filter( 'get_post_metadata', '_wp_preview_meta_filter', 10, 4 );
 887  
 888      return $post;
 889  }
 890  
 891  /**
 892   * Filters the latest content for preview from the post autosave.
 893   *
 894   * @since 2.7.0
 895   * @access private
 896   */
 897  function _show_post_preview() {
 898      if ( isset( $_GET['preview_id'] ) && isset( $_GET['preview_nonce'] ) ) {
 899          $id = (int) $_GET['preview_id'];
 900  
 901          if ( false === wp_verify_nonce( $_GET['preview_nonce'], 'post_preview_' . $id ) ) {
 902              wp_die( __( 'Sorry, you are not allowed to preview drafts.' ), 403 );
 903          }
 904  
 905          add_filter( 'the_preview', '_set_preview' );
 906      }
 907  }
 908  
 909  /**
 910   * Filters terms lookup to set the post format.
 911   *
 912   * @since 3.6.0
 913   * @access private
 914   *
 915   * @param array  $terms
 916   * @param int    $post_id
 917   * @param string $taxonomy
 918   * @return array
 919   */
 920  function _wp_preview_terms_filter( $terms, $post_id, $taxonomy ) {
 921      $post = get_post();
 922  
 923      if ( ! $post ) {
 924          return $terms;
 925      }
 926  
 927      if ( empty( $_REQUEST['post_format'] ) || $post->ID !== $post_id
 928          || 'post_format' !== $taxonomy || 'revision' === $post->post_type
 929      ) {
 930          return $terms;
 931      }
 932  
 933      if ( 'standard' === $_REQUEST['post_format'] ) {
 934          $terms = array();
 935      } else {
 936          $term = get_term_by( 'slug', 'post-format-' . sanitize_key( $_REQUEST['post_format'] ), 'post_format' );
 937  
 938          if ( $term ) {
 939              $terms = array( $term ); // Can only have one post format.
 940          }
 941      }
 942  
 943      return $terms;
 944  }
 945  
 946  /**
 947   * Filters post thumbnail lookup to set the post thumbnail.
 948   *
 949   * @since 4.6.0
 950   * @access private
 951   *
 952   * @param null|array|string $value    The value to return - a single metadata value, or an array of values.
 953   * @param int               $post_id  Post ID.
 954   * @param string            $meta_key Meta key.
 955   * @return null|array The default return value or the post thumbnail meta array.
 956   */
 957  function _wp_preview_post_thumbnail_filter( $value, $post_id, $meta_key ) {
 958      $post = get_post();
 959  
 960      if ( ! $post ) {
 961          return $value;
 962      }
 963  
 964      if ( empty( $_REQUEST['_thumbnail_id'] ) || empty( $_REQUEST['preview_id'] )
 965          || $post->ID !== $post_id || $post_id !== (int) $_REQUEST['preview_id']
 966          || '_thumbnail_id' !== $meta_key || 'revision' === $post->post_type
 967      ) {
 968          return $value;
 969      }
 970  
 971      $thumbnail_id = (int) $_REQUEST['_thumbnail_id'];
 972  
 973      if ( $thumbnail_id <= 0 ) {
 974          return '';
 975      }
 976  
 977      return (string) $thumbnail_id;
 978  }
 979  
 980  /**
 981   * Gets the post revision version.
 982   *
 983   * @since 3.6.0
 984   * @access private
 985   *
 986   * @param WP_Post $revision
 987   * @return int|false
 988   */
 989  function _wp_get_post_revision_version( $revision ) {
 990      if ( is_object( $revision ) ) {
 991          $revision = get_object_vars( $revision );
 992      } elseif ( ! is_array( $revision ) ) {
 993          return false;
 994      }
 995  
 996      if ( preg_match( '/^\d+-(?:autosave|revision)-v(\d+)$/', $revision['post_name'], $matches ) ) {
 997          return (int) $matches[1];
 998      }
 999  
1000      return 0;
1001  }
1002  
1003  /**
1004   * Upgrades the revisions author, adds the current post as a revision and sets the revisions version to 1.
1005   *
1006   * @since 3.6.0
1007   * @access private
1008   *
1009   * @global wpdb $wpdb WordPress database abstraction object.
1010   *
1011   * @param WP_Post $post      Post object.
1012   * @param array   $revisions Current revisions of the post.
1013   * @return bool true if the revisions were upgraded, false if problems.
1014   */
1015  function _wp_upgrade_revisions_of_post( $post, $revisions ) {
1016      global $wpdb;
1017  
1018      // Add post option exclusively.
1019      $lock   = "revision-upgrade-{$post->ID}";
1020      $now    = time();
1021      $result = $wpdb->query( $wpdb->prepare( "INSERT IGNORE INTO `$wpdb->options` (`option_name`, `option_value`, `autoload`) VALUES (%s, %s, 'off') /* LOCK */", $lock, $now ) );
1022  
1023      if ( ! $result ) {
1024          // If we couldn't get a lock, see how old the previous lock is.
1025          $locked = get_option( $lock );
1026  
1027          if ( ! $locked ) {
1028              /*
1029               * Can't write to the lock, and can't read the lock.
1030               * Something broken has happened.
1031               */
1032              return false;
1033          }
1034  
1035          if ( $locked > $now - HOUR_IN_SECONDS ) {
1036              // Lock is not too old: some other process may be upgrading this post. Bail.
1037              return false;
1038          }
1039  
1040          // Lock is too old - update it (below) and continue.
1041      }
1042  
1043      // If we could get a lock, re-"add" the option to fire all the correct filters.
1044      update_option( $lock, $now );
1045  
1046      reset( $revisions );
1047      $add_last = true;
1048  
1049      do {
1050          $this_revision = current( $revisions );
1051          $prev_revision = next( $revisions );
1052  
1053          $this_revision_version = _wp_get_post_revision_version( $this_revision );
1054  
1055          // Something terrible happened.
1056          if ( false === $this_revision_version ) {
1057              continue;
1058          }
1059  
1060          /*
1061           * 1 is the latest revision version, so we're already up to date.
1062           * No need to add a copy of the post as latest revision.
1063           */
1064          if ( 0 < $this_revision_version ) {
1065              $add_last = false;
1066              continue;
1067          }
1068  
1069          // Always update the revision version.
1070          $update = array(
1071              'post_name' => preg_replace( '/^(\d+-(?:autosave|revision))[\d-]*$/', '$1-v1', $this_revision->post_name ),
1072          );
1073  
1074          /*
1075           * If this revision is the oldest revision of the post, i.e. no $prev_revision,
1076           * the correct post_author is probably $post->post_author, but that's only a good guess.
1077           * Update the revision version only and Leave the author as-is.
1078           */
1079          if ( $prev_revision ) {
1080              $prev_revision_version = _wp_get_post_revision_version( $prev_revision );
1081  
1082              // If the previous revision is already up to date, it no longer has the information we need :(
1083              if ( $prev_revision_version < 1 ) {
1084                  $update['post_author'] = $prev_revision->post_author;
1085              }
1086          }
1087  
1088          // Upgrade this revision.
1089          $result = $wpdb->update( $wpdb->posts, $update, array( 'ID' => $this_revision->ID ) );
1090  
1091          if ( $result ) {
1092              wp_cache_delete( $this_revision->ID, 'posts' );
1093          }
1094      } while ( $prev_revision );
1095  
1096      delete_option( $lock );
1097  
1098      // Add a copy of the post as latest revision.
1099      if ( $add_last ) {
1100          wp_save_post_revision( $post->ID );
1101      }
1102  
1103      return true;
1104  }
1105  
1106  /**
1107   * Filters preview post meta retrieval to get values from the autosave.
1108   *
1109   * Filters revisioned meta keys only.
1110   *
1111   * @since 6.4.0
1112   *
1113   * @param mixed  $value     Meta value to filter.
1114   * @param int    $object_id Object ID.
1115   * @param string $meta_key  Meta key to filter a value for.
1116   * @param bool   $single    Whether to return a single value.
1117   * @return mixed Original meta value if the meta key isn't revisioned, the object doesn't exist,
1118   *               the post type is a revision or the post ID doesn't match the object ID.
1119   *               Otherwise, the revisioned meta value is returned for the preview.
1120   */
1121  function _wp_preview_meta_filter( $value, $object_id, $meta_key, $single ) {
1122      $post = get_post();
1123  
1124      if ( empty( $post )
1125          || $post->ID !== $object_id
1126          || ! in_array( $meta_key, wp_post_revision_meta_keys( $post->post_type ), true )
1127          || 'revision' === $post->post_type
1128      ) {
1129          return $value;
1130      }
1131  
1132      $preview = wp_get_post_autosave( $post->ID );
1133  
1134      if ( false === $preview ) {
1135          return $value;
1136      }
1137  
1138      return get_post_meta( $preview->ID, $meta_key, $single );
1139  }


Generated : Sat Jul 25 08:20:20 2026 Cross-referenced by PHPXref