[ 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']     = isset( $post['post_modified'] ) ? $post['post_modified'] : '';
  93      $revision_data['post_date_gmt'] = isset( $post['post_modified_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|void Void 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;
 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;
 138      }
 139  
 140      $post = get_post( $post_id );
 141  
 142      if ( ! $post ) {
 143          return;
 144      }
 145  
 146      if ( ! post_type_supports( $post->post_type, 'revisions' ) ) {
 147          return;
 148      }
 149  
 150      if ( 'auto-draft' === $post->post_status ) {
 151          return;
 152      }
 153  
 154      if ( ! wp_revisions_enabled( $post ) ) {
 155          return;
 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( $post->$field ) !== normalize_whitespace( $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;
 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   * @global wpdb $wpdb WordPress database abstraction object.
 274   *
 275   * @param int $post_id The post ID.
 276   * @param int $user_id Optional. The post author ID. Default 0.
 277   * @return WP_Post|false The autosaved data or false on failure or when no autosave exists.
 278   */
 279  function wp_get_post_autosave( $post_id, $user_id = 0 ) {
 280      global $wpdb;
 281  
 282      $autosave_name = $post_id . '-autosave-v1';
 283      $user_id_query = ( 0 !== $user_id ) ? "AND post_author = $user_id" : null;
 284  
 285      // Construct the autosave query.
 286      $autosave_query = "
 287          SELECT *
 288          FROM $wpdb->posts
 289          WHERE post_parent = %d
 290          AND post_type = 'revision'
 291          AND post_status = 'inherit'
 292          AND post_name   = %s " . $user_id_query . '
 293          ORDER BY post_date DESC
 294          LIMIT 1';
 295  
 296      $autosave = $wpdb->get_results(
 297          $wpdb->prepare(
 298              $autosave_query,
 299              $post_id,
 300              $autosave_name
 301          )
 302      );
 303  
 304      if ( ! $autosave ) {
 305          return false;
 306      }
 307  
 308      return get_post( $autosave[0] );
 309  }
 310  
 311  /**
 312   * Determines if the specified post is a revision.
 313   *
 314   * @since 2.6.0
 315   *
 316   * @param int|WP_Post $post Post ID or post object.
 317   * @return int|false ID of revision's parent on success, false if not a revision.
 318   */
 319  function wp_is_post_revision( $post ) {
 320      $post = wp_get_post_revision( $post );
 321  
 322      if ( ! $post ) {
 323          return false;
 324      }
 325  
 326      return (int) $post->post_parent;
 327  }
 328  
 329  /**
 330   * Determines if the specified post is an autosave.
 331   *
 332   * @since 2.6.0
 333   *
 334   * @param int|WP_Post $post Post ID or post object.
 335   * @return int|false ID of autosave's parent on success, false if not a revision.
 336   */
 337  function wp_is_post_autosave( $post ) {
 338      $post = wp_get_post_revision( $post );
 339  
 340      if ( ! $post ) {
 341          return false;
 342      }
 343  
 344      if ( str_contains( $post->post_name, "{$post->post_parent}-autosave" ) ) {
 345          return (int) $post->post_parent;
 346      }
 347  
 348      return false;
 349  }
 350  
 351  /**
 352   * Inserts post data into the posts table as a post revision.
 353   *
 354   * @since 2.6.0
 355   * @access private
 356   *
 357   * @param int|WP_Post|array|null $post     Post ID, post object OR post array.
 358   * @param bool                   $autosave Optional. Whether the revision is an autosave or not.
 359   *                                         Default false.
 360   * @return int|WP_Error WP_Error or 0 if error, new revision ID if success.
 361   */
 362  function _wp_put_post_revision( $post = null, $autosave = false ) {
 363      if ( is_object( $post ) ) {
 364          $post = get_object_vars( $post );
 365      } elseif ( ! is_array( $post ) ) {
 366          $post = get_post( $post, ARRAY_A );
 367      }
 368  
 369      if ( ! $post || empty( $post['ID'] ) ) {
 370          return new WP_Error( 'invalid_post', __( 'Invalid post ID.' ) );
 371      }
 372  
 373      if ( isset( $post['post_type'] ) && 'revision' === $post['post_type'] ) {
 374          return new WP_Error( 'post_type', __( 'Cannot create a revision of a revision' ) );
 375      }
 376  
 377      $post = _wp_post_revision_data( $post, $autosave );
 378      $post = wp_slash( $post ); // Since data is from DB.
 379  
 380      $revision_id = wp_insert_post( $post, true );
 381      if ( is_wp_error( $revision_id ) ) {
 382          return $revision_id;
 383      }
 384  
 385      if ( $revision_id ) {
 386          /**
 387           * Fires once a revision has been saved.
 388           *
 389           * @since 2.6.0
 390           * @since 6.4.0 The post_id parameter was added.
 391           *
 392           * @param int $revision_id Post revision ID.
 393           * @param int $post_id     Post ID.
 394           */
 395          do_action( '_wp_put_post_revision', $revision_id, $post['post_parent'] );
 396      }
 397  
 398      return $revision_id;
 399  }
 400  
 401  
 402  /**
 403   * Save the revisioned meta fields.
 404   *
 405   * @since 6.4.0
 406   *
 407   * @param int $revision_id The ID of the revision to save the meta to.
 408   * @param int $post_id     The ID of the post the revision is associated with.
 409   */
 410  function wp_save_revisioned_meta_fields( $revision_id, $post_id ) {
 411      $post_type = get_post_type( $post_id );
 412      if ( ! $post_type ) {
 413          return;
 414      }
 415  
 416      foreach ( wp_post_revision_meta_keys( $post_type ) as $meta_key ) {
 417          if ( metadata_exists( 'post', $post_id, $meta_key ) ) {
 418              _wp_copy_post_meta( $post_id, $revision_id, $meta_key );
 419          }
 420      }
 421  }
 422  
 423  /**
 424   * Gets a post revision.
 425   *
 426   * @since 2.6.0
 427   *
 428   * @param int|WP_Post $post   Post ID or post object.
 429   * @param string      $output Optional. The required return type. One of OBJECT, ARRAY_A, or ARRAY_N, which
 430   *                            correspond to a WP_Post object, an associative array, or a numeric array,
 431   *                            respectively. Default OBJECT.
 432   * @param string      $filter Optional sanitization filter. See sanitize_post(). Default 'raw'.
 433   * @return WP_Post|array|null WP_Post (or array) on success, or null on failure.
 434   */
 435  function wp_get_post_revision( &$post, $output = OBJECT, $filter = 'raw' ) {
 436      $revision = get_post( $post, OBJECT, $filter );
 437  
 438      if ( ! $revision ) {
 439          return $revision;
 440      }
 441  
 442      if ( 'revision' !== $revision->post_type ) {
 443          return null;
 444      }
 445  
 446      if ( OBJECT === $output ) {
 447          return $revision;
 448      } elseif ( ARRAY_A === $output ) {
 449          $_revision = get_object_vars( $revision );
 450          return $_revision;
 451      } elseif ( ARRAY_N === $output ) {
 452          $_revision = array_values( get_object_vars( $revision ) );
 453          return $_revision;
 454      }
 455  
 456      return $revision;
 457  }
 458  
 459  /**
 460   * Restores a post to the specified revision.
 461   *
 462   * Can restore a past revision using all fields of the post revision, or only selected fields.
 463   *
 464   * @since 2.6.0
 465   *
 466   * @param int|WP_Post $revision Revision ID or revision object.
 467   * @param array       $fields   Optional. What fields to restore from. Defaults to all.
 468   * @return int|false|null Null if error, false if no fields to restore, (int) post ID if success.
 469   */
 470  function wp_restore_post_revision( $revision, $fields = null ) {
 471      $revision = wp_get_post_revision( $revision, ARRAY_A );
 472  
 473      if ( ! $revision ) {
 474          return $revision;
 475      }
 476  
 477      if ( ! is_array( $fields ) ) {
 478          $fields = array_keys( _wp_post_revision_fields( $revision ) );
 479      }
 480  
 481      $update = array();
 482      foreach ( array_intersect( array_keys( $revision ), $fields ) as $field ) {
 483          $update[ $field ] = $revision[ $field ];
 484      }
 485  
 486      if ( ! $update ) {
 487          return false;
 488      }
 489  
 490      $update['ID'] = $revision['post_parent'];
 491  
 492      $update = wp_slash( $update ); // Since data is from DB.
 493  
 494      $post_id = wp_update_post( $update );
 495  
 496      if ( ! $post_id || is_wp_error( $post_id ) ) {
 497          return $post_id;
 498      }
 499  
 500      // Update last edit user.
 501      update_post_meta( $post_id, '_edit_last', get_current_user_id() );
 502  
 503      /**
 504       * Fires after a post revision has been restored.
 505       *
 506       * @since 2.6.0
 507       *
 508       * @param int $post_id     Post ID.
 509       * @param int $revision_id Post revision ID.
 510       */
 511      do_action( 'wp_restore_post_revision', $post_id, $revision['ID'] );
 512  
 513      return $post_id;
 514  }
 515  
 516  /**
 517   * Restore the revisioned meta values for a post.
 518   *
 519   * @since 6.4.0
 520   *
 521   * @param int $post_id     The ID of the post to restore the meta to.
 522   * @param int $revision_id The ID of the revision to restore the meta from.
 523   */
 524  function wp_restore_post_revision_meta( $post_id, $revision_id ) {
 525      $post_type = get_post_type( $post_id );
 526      if ( ! $post_type ) {
 527          return;
 528      }
 529  
 530      // Restore revisioned meta fields.
 531      foreach ( wp_post_revision_meta_keys( $post_type ) as $meta_key ) {
 532  
 533          // Clear any existing meta.
 534          delete_post_meta( $post_id, $meta_key );
 535  
 536          _wp_copy_post_meta( $revision_id, $post_id, $meta_key );
 537      }
 538  }
 539  
 540  /**
 541   * Copy post meta for the given key from one post to another.
 542   *
 543   * @since 6.4.0
 544   *
 545   * @param int    $source_post_id Post ID to copy meta value(s) from.
 546   * @param int    $target_post_id Post ID to copy meta value(s) to.
 547   * @param string $meta_key       Meta key to copy.
 548   */
 549  function _wp_copy_post_meta( $source_post_id, $target_post_id, $meta_key ) {
 550  
 551      foreach ( get_post_meta( $source_post_id, $meta_key ) as $meta_value ) {
 552          /**
 553           * We use add_metadata() function vs add_post_meta() here
 554           * to allow for a revision post target OR regular post.
 555           */
 556          add_metadata( 'post', $target_post_id, $meta_key, wp_slash( $meta_value ) );
 557      }
 558  }
 559  
 560  /**
 561   * Determine which post meta fields should be revisioned.
 562   *
 563   * @since 6.4.0
 564   *
 565   * @param string $post_type The post type being revisioned.
 566   * @return array An array of meta keys to be revisioned.
 567   */
 568  function wp_post_revision_meta_keys( $post_type ) {
 569      $registered_meta = array_merge(
 570          get_registered_meta_keys( 'post' ),
 571          get_registered_meta_keys( 'post', $post_type )
 572      );
 573  
 574      $wp_revisioned_meta_keys = array();
 575  
 576      foreach ( $registered_meta as $name => $args ) {
 577          if ( $args['revisions_enabled'] ) {
 578              $wp_revisioned_meta_keys[ $name ] = true;
 579          }
 580      }
 581  
 582      $wp_revisioned_meta_keys = array_keys( $wp_revisioned_meta_keys );
 583  
 584      /**
 585       * Filter the list of post meta keys to be revisioned.
 586       *
 587       * @since 6.4.0
 588       *
 589       * @param array  $keys      An array of meta fields to be revisioned.
 590       * @param string $post_type The post type being revisioned.
 591       */
 592      return apply_filters( 'wp_post_revision_meta_keys', $wp_revisioned_meta_keys, $post_type );
 593  }
 594  
 595  /**
 596   * Check whether revisioned post meta fields have changed.
 597   *
 598   * @since 6.4.0
 599   *
 600   * @param bool    $post_has_changed Whether the post has changed.
 601   * @param WP_Post $last_revision    The last revision post object.
 602   * @param WP_Post $post             The post object.
 603   * @return bool Whether the post has changed.
 604   */
 605  function wp_check_revisioned_meta_fields_have_changed( $post_has_changed, WP_Post $last_revision, WP_Post $post ) {
 606      foreach ( wp_post_revision_meta_keys( $post->post_type ) as $meta_key ) {
 607          if ( get_post_meta( $post->ID, $meta_key ) !== get_post_meta( $last_revision->ID, $meta_key ) ) {
 608              $post_has_changed = true;
 609              break;
 610          }
 611      }
 612      return $post_has_changed;
 613  }
 614  
 615  /**
 616   * Deletes a revision.
 617   *
 618   * Deletes the row from the posts table corresponding to the specified revision.
 619   *
 620   * @since 2.6.0
 621   *
 622   * @param int|WP_Post $revision Revision ID or revision object.
 623   * @return WP_Post|false|null Null or false if error, deleted post object if success.
 624   */
 625  function wp_delete_post_revision( $revision ) {
 626      $revision = wp_get_post_revision( $revision );
 627  
 628      if ( ! $revision ) {
 629          return $revision;
 630      }
 631  
 632      $delete = wp_delete_post( $revision->ID );
 633  
 634      if ( $delete ) {
 635          /**
 636           * Fires once a post revision has been deleted.
 637           *
 638           * @since 2.6.0
 639           *
 640           * @param int     $revision_id Post revision ID.
 641           * @param WP_Post $revision    Post revision object.
 642           */
 643          do_action( 'wp_delete_post_revision', $revision->ID, $revision );
 644      }
 645  
 646      return $delete;
 647  }
 648  
 649  /**
 650   * Returns all revisions of specified post.
 651   *
 652   * @since 2.6.0
 653   *
 654   * @see get_children()
 655   *
 656   * @param int|WP_Post $post Optional. Post ID or WP_Post object. Default is global `$post`.
 657   * @param array|null  $args Optional. Arguments for retrieving post revisions. Default null.
 658   * @return WP_Post[]|int[] Array of revision objects or IDs, or an empty array if none.
 659   */
 660  function wp_get_post_revisions( $post = 0, $args = null ) {
 661      $post = get_post( $post );
 662  
 663      if ( ! $post || empty( $post->ID ) ) {
 664          return array();
 665      }
 666  
 667      $defaults = array(
 668          'order'         => 'DESC',
 669          'orderby'       => 'date ID',
 670          'check_enabled' => true,
 671      );
 672      $args     = wp_parse_args( $args, $defaults );
 673  
 674      if ( $args['check_enabled'] && ! wp_revisions_enabled( $post ) ) {
 675          return array();
 676      }
 677  
 678      $args = array_merge(
 679          $args,
 680          array(
 681              'post_parent' => $post->ID,
 682              'post_type'   => 'revision',
 683              'post_status' => 'inherit',
 684          )
 685      );
 686  
 687      $revisions = get_children( $args );
 688  
 689      if ( ! $revisions ) {
 690          return array();
 691      }
 692  
 693      return $revisions;
 694  }
 695  
 696  /**
 697   * Returns the latest revision ID and count of revisions for a post.
 698   *
 699   * @since 6.1.0
 700   *
 701   * @param int|WP_Post $post Optional. Post ID or WP_Post object. Default is global $post.
 702   * @return array|WP_Error {
 703   *     Returns associative array with latest revision ID and total count,
 704   *     or a WP_Error if the post does not exist or revisions are not enabled.
 705   *
 706   *     @type int $latest_id The latest revision post ID or 0 if no revisions exist.
 707   *     @type int $count     The total count of revisions for the given post.
 708   * }
 709   */
 710  function wp_get_latest_revision_id_and_total_count( $post = 0 ) {
 711      $post = get_post( $post );
 712  
 713      if ( ! $post ) {
 714          return new WP_Error( 'invalid_post', __( 'Invalid post.' ) );
 715      }
 716  
 717      if ( ! wp_revisions_enabled( $post ) ) {
 718          return new WP_Error( 'revisions_not_enabled', __( 'Revisions not enabled.' ) );
 719      }
 720  
 721      $args = array(
 722          'post_parent'         => $post->ID,
 723          'fields'              => 'ids',
 724          'post_type'           => 'revision',
 725          'post_status'         => 'inherit',
 726          'order'               => 'DESC',
 727          'orderby'             => 'date ID',
 728          'posts_per_page'      => 1,
 729          'ignore_sticky_posts' => true,
 730      );
 731  
 732      $revision_query = new WP_Query();
 733      $revisions      = $revision_query->query( $args );
 734  
 735      if ( ! $revisions ) {
 736          return array(
 737              'latest_id' => 0,
 738              'count'     => 0,
 739          );
 740      }
 741  
 742      return array(
 743          'latest_id' => $revisions[0],
 744          'count'     => $revision_query->found_posts,
 745      );
 746  }
 747  
 748  /**
 749   * Returns the url for viewing and potentially restoring revisions of a given post.
 750   *
 751   * @since 5.9.0
 752   *
 753   * @param int|WP_Post $post Optional. Post ID or WP_Post object. Default is global `$post`.
 754   * @return string|null The URL for editing revisions on the given post, otherwise null.
 755   */
 756  function wp_get_post_revisions_url( $post = 0 ) {
 757      $post = get_post( $post );
 758  
 759      if ( ! $post instanceof WP_Post ) {
 760          return null;
 761      }
 762  
 763      // If the post is a revision, return early.
 764      if ( 'revision' === $post->post_type ) {
 765          return get_edit_post_link( $post );
 766      }
 767  
 768      if ( ! wp_revisions_enabled( $post ) ) {
 769          return null;
 770      }
 771  
 772      $revisions = wp_get_latest_revision_id_and_total_count( $post->ID );
 773  
 774      if ( is_wp_error( $revisions ) || 0 === $revisions['count'] ) {
 775          return null;
 776      }
 777  
 778      return get_edit_post_link( $revisions['latest_id'] );
 779  }
 780  
 781  /**
 782   * Determines whether revisions are enabled for a given post.
 783   *
 784   * @since 3.6.0
 785   *
 786   * @param WP_Post $post The post object.
 787   * @return bool True if number of revisions to keep isn't zero, false otherwise.
 788   */
 789  function wp_revisions_enabled( $post ) {
 790      return wp_revisions_to_keep( $post ) !== 0;
 791  }
 792  
 793  /**
 794   * Determines how many revisions to retain for a given post.
 795   *
 796   * By default, an infinite number of revisions are kept.
 797   *
 798   * The constant WP_POST_REVISIONS can be set in wp-config to specify the limit
 799   * of revisions to keep.
 800   *
 801   * @since 3.6.0
 802   *
 803   * @param WP_Post $post The post object.
 804   * @return int The number of revisions to keep.
 805   */
 806  function wp_revisions_to_keep( $post ) {
 807      $num = WP_POST_REVISIONS;
 808  
 809      if ( true === $num ) {
 810          $num = -1;
 811      } else {
 812          $num = (int) $num;
 813      }
 814  
 815      if ( ! post_type_supports( $post->post_type, 'revisions' ) ) {
 816          $num = 0;
 817      }
 818  
 819      /**
 820       * Filters the number of revisions to save for the given post.
 821       *
 822       * Overrides the value of WP_POST_REVISIONS.
 823       *
 824       * @since 3.6.0
 825       *
 826       * @param int     $num  Number of revisions to store.
 827       * @param WP_Post $post Post object.
 828       */
 829      $num = apply_filters( 'wp_revisions_to_keep', $num, $post );
 830  
 831      /**
 832       * Filters the number of revisions to save for the given post by its post type.
 833       *
 834       * Overrides both the value of WP_POST_REVISIONS and the {@see 'wp_revisions_to_keep'} filter.
 835       *
 836       * The dynamic portion of the hook name, `$post->post_type`, refers to
 837       * the post type slug.
 838       *
 839       * Possible hook names include:
 840       *
 841       *  - `wp_post_revisions_to_keep`
 842       *  - `wp_page_revisions_to_keep`
 843       *
 844       * @since 5.8.0
 845       *
 846       * @param int     $num  Number of revisions to store.
 847       * @param WP_Post $post Post object.
 848       */
 849      $num = apply_filters( "wp_{$post->post_type}_revisions_to_keep", $num, $post );
 850  
 851      return (int) $num;
 852  }
 853  
 854  /**
 855   * Sets up the post object for preview based on the post autosave.
 856   *
 857   * @since 2.7.0
 858   * @access private
 859   *
 860   * @param WP_Post $post
 861   * @return WP_Post|false
 862   */
 863  function _set_preview( $post ) {
 864      if ( ! is_object( $post ) ) {
 865          return $post;
 866      }
 867  
 868      $preview = wp_get_post_autosave( $post->ID );
 869  
 870      if ( is_object( $preview ) ) {
 871          $preview = sanitize_post( $preview );
 872  
 873          $post->post_content = $preview->post_content;
 874          $post->post_title   = $preview->post_title;
 875          $post->post_excerpt = $preview->post_excerpt;
 876      }
 877  
 878      add_filter( 'get_the_terms', '_wp_preview_terms_filter', 10, 3 );
 879      add_filter( 'get_post_metadata', '_wp_preview_post_thumbnail_filter', 10, 3 );
 880      add_filter( 'get_post_metadata', '_wp_preview_meta_filter', 10, 4 );
 881  
 882      return $post;
 883  }
 884  
 885  /**
 886   * Filters the latest content for preview from the post autosave.
 887   *
 888   * @since 2.7.0
 889   * @access private
 890   */
 891  function _show_post_preview() {
 892      if ( isset( $_GET['preview_id'] ) && isset( $_GET['preview_nonce'] ) ) {
 893          $id = (int) $_GET['preview_id'];
 894  
 895          if ( false === wp_verify_nonce( $_GET['preview_nonce'], 'post_preview_' . $id ) ) {
 896              wp_die( __( 'Sorry, you are not allowed to preview drafts.' ), 403 );
 897          }
 898  
 899          add_filter( 'the_preview', '_set_preview' );
 900      }
 901  }
 902  
 903  /**
 904   * Filters terms lookup to set the post format.
 905   *
 906   * @since 3.6.0
 907   * @access private
 908   *
 909   * @param array  $terms
 910   * @param int    $post_id
 911   * @param string $taxonomy
 912   * @return array
 913   */
 914  function _wp_preview_terms_filter( $terms, $post_id, $taxonomy ) {
 915      $post = get_post();
 916  
 917      if ( ! $post ) {
 918          return $terms;
 919      }
 920  
 921      if ( empty( $_REQUEST['post_format'] ) || $post->ID !== $post_id
 922          || 'post_format' !== $taxonomy || 'revision' === $post->post_type
 923      ) {
 924          return $terms;
 925      }
 926  
 927      if ( 'standard' === $_REQUEST['post_format'] ) {
 928          $terms = array();
 929      } else {
 930          $term = get_term_by( 'slug', 'post-format-' . sanitize_key( $_REQUEST['post_format'] ), 'post_format' );
 931  
 932          if ( $term ) {
 933              $terms = array( $term ); // Can only have one post format.
 934          }
 935      }
 936  
 937      return $terms;
 938  }
 939  
 940  /**
 941   * Filters post thumbnail lookup to set the post thumbnail.
 942   *
 943   * @since 4.6.0
 944   * @access private
 945   *
 946   * @param null|array|string $value    The value to return - a single metadata value, or an array of values.
 947   * @param int               $post_id  Post ID.
 948   * @param string            $meta_key Meta key.
 949   * @return null|array The default return value or the post thumbnail meta array.
 950   */
 951  function _wp_preview_post_thumbnail_filter( $value, $post_id, $meta_key ) {
 952      $post = get_post();
 953  
 954      if ( ! $post ) {
 955          return $value;
 956      }
 957  
 958      if ( empty( $_REQUEST['_thumbnail_id'] ) || empty( $_REQUEST['preview_id'] )
 959          || $post->ID !== $post_id || $post_id !== (int) $_REQUEST['preview_id']
 960          || '_thumbnail_id' !== $meta_key || 'revision' === $post->post_type
 961      ) {
 962          return $value;
 963      }
 964  
 965      $thumbnail_id = (int) $_REQUEST['_thumbnail_id'];
 966  
 967      if ( $thumbnail_id <= 0 ) {
 968          return '';
 969      }
 970  
 971      return (string) $thumbnail_id;
 972  }
 973  
 974  /**
 975   * Gets the post revision version.
 976   *
 977   * @since 3.6.0
 978   * @access private
 979   *
 980   * @param WP_Post $revision
 981   * @return int|false
 982   */
 983  function _wp_get_post_revision_version( $revision ) {
 984      if ( is_object( $revision ) ) {
 985          $revision = get_object_vars( $revision );
 986      } elseif ( ! is_array( $revision ) ) {
 987          return false;
 988      }
 989  
 990      if ( preg_match( '/^\d+-(?:autosave|revision)-v(\d+)$/', $revision['post_name'], $matches ) ) {
 991          return (int) $matches[1];
 992      }
 993  
 994      return 0;
 995  }
 996  
 997  /**
 998   * Upgrades the revisions author, adds the current post as a revision and sets the revisions version to 1.
 999   *
1000   * @since 3.6.0
1001   * @access private
1002   *
1003   * @global wpdb $wpdb WordPress database abstraction object.
1004   *
1005   * @param WP_Post $post      Post object.
1006   * @param array   $revisions Current revisions of the post.
1007   * @return bool true if the revisions were upgraded, false if problems.
1008   */
1009  function _wp_upgrade_revisions_of_post( $post, $revisions ) {
1010      global $wpdb;
1011  
1012      // Add post option exclusively.
1013      $lock   = "revision-upgrade-{$post->ID}";
1014      $now    = time();
1015      $result = $wpdb->query( $wpdb->prepare( "INSERT IGNORE INTO `$wpdb->options` (`option_name`, `option_value`, `autoload`) VALUES (%s, %s, 'no') /* LOCK */", $lock, $now ) );
1016  
1017      if ( ! $result ) {
1018          // If we couldn't get a lock, see how old the previous lock is.
1019          $locked = get_option( $lock );
1020  
1021          if ( ! $locked ) {
1022              /*
1023               * Can't write to the lock, and can't read the lock.
1024               * Something broken has happened.
1025               */
1026              return false;
1027          }
1028  
1029          if ( $locked > $now - HOUR_IN_SECONDS ) {
1030              // Lock is not too old: some other process may be upgrading this post. Bail.
1031              return false;
1032          }
1033  
1034          // Lock is too old - update it (below) and continue.
1035      }
1036  
1037      // If we could get a lock, re-"add" the option to fire all the correct filters.
1038      update_option( $lock, $now );
1039  
1040      reset( $revisions );
1041      $add_last = true;
1042  
1043      do {
1044          $this_revision = current( $revisions );
1045          $prev_revision = next( $revisions );
1046  
1047          $this_revision_version = _wp_get_post_revision_version( $this_revision );
1048  
1049          // Something terrible happened.
1050          if ( false === $this_revision_version ) {
1051              continue;
1052          }
1053  
1054          /*
1055           * 1 is the latest revision version, so we're already up to date.
1056           * No need to add a copy of the post as latest revision.
1057           */
1058          if ( 0 < $this_revision_version ) {
1059              $add_last = false;
1060              continue;
1061          }
1062  
1063          // Always update the revision version.
1064          $update = array(
1065              'post_name' => preg_replace( '/^(\d+-(?:autosave|revision))[\d-]*$/', '$1-v1', $this_revision->post_name ),
1066          );
1067  
1068          /*
1069           * If this revision is the oldest revision of the post, i.e. no $prev_revision,
1070           * the correct post_author is probably $post->post_author, but that's only a good guess.
1071           * Update the revision version only and Leave the author as-is.
1072           */
1073          if ( $prev_revision ) {
1074              $prev_revision_version = _wp_get_post_revision_version( $prev_revision );
1075  
1076              // If the previous revision is already up to date, it no longer has the information we need :(
1077              if ( $prev_revision_version < 1 ) {
1078                  $update['post_author'] = $prev_revision->post_author;
1079              }
1080          }
1081  
1082          // Upgrade this revision.
1083          $result = $wpdb->update( $wpdb->posts, $update, array( 'ID' => $this_revision->ID ) );
1084  
1085          if ( $result ) {
1086              wp_cache_delete( $this_revision->ID, 'posts' );
1087          }
1088      } while ( $prev_revision );
1089  
1090      delete_option( $lock );
1091  
1092      // Add a copy of the post as latest revision.
1093      if ( $add_last ) {
1094          wp_save_post_revision( $post->ID );
1095      }
1096  
1097      return true;
1098  }
1099  
1100  /**
1101   * Filters preview post meta retrieval to get values from the autosave.
1102   *
1103   * Filters revisioned meta keys only.
1104   *
1105   * @since 6.4.0
1106   *
1107   * @param mixed  $value     Meta value to filter.
1108   * @param int    $object_id Object ID.
1109   * @param string $meta_key  Meta key to filter a value for.
1110   * @param bool   $single    Whether to return a single value. Default false.
1111   * @return mixed Original meta value if the meta key isn't revisioned, the object doesn't exist,
1112   *               the post type is a revision or the post ID doesn't match the object ID.
1113   *               Otherwise, the revisioned meta value is returned for the preview.
1114   */
1115  function _wp_preview_meta_filter( $value, $object_id, $meta_key, $single ) {
1116  
1117      $post = get_post();
1118      if (
1119          empty( $post ) ||
1120          $post->ID !== $object_id ||
1121          ! in_array( $meta_key, wp_post_revision_meta_keys( $post->post_type ), true ) ||
1122          'revision' === $post->post_type
1123      ) {
1124          return $value;
1125      }
1126  
1127      $preview = wp_get_post_autosave( $post->ID );
1128      if ( false === $preview ) {
1129          return $value;
1130      }
1131  
1132      return get_post_meta( $preview->ID, $meta_key, $single );
1133  }


Generated : Thu Apr 25 08:20:02 2024 Cross-referenced by PHPXref