[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

Search

title

Body

[close]

/wp-admin/includes/ -> post.php (source)

   1  <?php
   2  /**
   3   * WordPress Post Administration API.
   4   *
   5   * @package WordPress
   6   * @subpackage Administration
   7   */
   8  
   9  /**
  10   * Rename $_POST data from form names to DB post columns.
  11   *
  12   * Manipulates $_POST directly.
  13   *
  14   * @since 2.6.0
  15   *
  16   * @param bool  $update    Are we updating a pre-existing post?
  17   * @param array $post_data Array of post data. Defaults to the contents of $_POST.
  18   * @return array|WP_Error Array of post data on success, WP_Error on failure.
  19   */
  20  function _wp_translate_postdata( $update = false, $post_data = null ) {
  21  
  22      if ( empty( $post_data ) ) {
  23          $post_data = &$_POST;
  24      }
  25  
  26      if ( $update ) {
  27          $post_data['ID'] = (int) $post_data['post_ID'];
  28      }
  29  
  30      $ptype = get_post_type_object( $post_data['post_type'] );
  31  
  32      if ( $update && ! current_user_can( 'edit_post', $post_data['ID'] ) ) {
  33          if ( 'page' === $post_data['post_type'] ) {
  34              return new WP_Error( 'edit_others_pages', __( 'Sorry, you are not allowed to edit pages as this user.' ) );
  35          } else {
  36              return new WP_Error( 'edit_others_posts', __( 'Sorry, you are not allowed to edit posts as this user.' ) );
  37          }
  38      } elseif ( ! $update && ! current_user_can( $ptype->cap->create_posts ) ) {
  39          if ( 'page' === $post_data['post_type'] ) {
  40              return new WP_Error( 'edit_others_pages', __( 'Sorry, you are not allowed to create pages as this user.' ) );
  41          } else {
  42              return new WP_Error( 'edit_others_posts', __( 'Sorry, you are not allowed to create posts as this user.' ) );
  43          }
  44      }
  45  
  46      if ( isset( $post_data['content'] ) ) {
  47          $post_data['post_content'] = $post_data['content'];
  48      }
  49  
  50      if ( isset( $post_data['excerpt'] ) ) {
  51          $post_data['post_excerpt'] = $post_data['excerpt'];
  52      }
  53  
  54      if ( isset( $post_data['parent_id'] ) ) {
  55          $post_data['post_parent'] = (int) $post_data['parent_id'];
  56      }
  57  
  58      if ( isset( $post_data['trackback_url'] ) ) {
  59          $post_data['to_ping'] = $post_data['trackback_url'];
  60      }
  61  
  62      $post_data['user_ID'] = get_current_user_id();
  63  
  64      if ( ! empty( $post_data['post_author_override'] ) ) {
  65          $post_data['post_author'] = (int) $post_data['post_author_override'];
  66      } else {
  67          if ( ! empty( $post_data['post_author'] ) ) {
  68              $post_data['post_author'] = (int) $post_data['post_author'];
  69          } else {
  70              $post_data['post_author'] = (int) $post_data['user_ID'];
  71          }
  72      }
  73  
  74      if ( isset( $post_data['user_ID'] ) && ( $post_data['post_author'] != $post_data['user_ID'] )
  75          && ! current_user_can( $ptype->cap->edit_others_posts ) ) {
  76  
  77          if ( $update ) {
  78              if ( 'page' === $post_data['post_type'] ) {
  79                  return new WP_Error( 'edit_others_pages', __( 'Sorry, you are not allowed to edit pages as this user.' ) );
  80              } else {
  81                  return new WP_Error( 'edit_others_posts', __( 'Sorry, you are not allowed to edit posts as this user.' ) );
  82              }
  83          } else {
  84              if ( 'page' === $post_data['post_type'] ) {
  85                  return new WP_Error( 'edit_others_pages', __( 'Sorry, you are not allowed to create pages as this user.' ) );
  86              } else {
  87                  return new WP_Error( 'edit_others_posts', __( 'Sorry, you are not allowed to create posts as this user.' ) );
  88              }
  89          }
  90      }
  91  
  92      if ( ! empty( $post_data['post_status'] ) ) {
  93          $post_data['post_status'] = sanitize_key( $post_data['post_status'] );
  94  
  95          // No longer an auto-draft.
  96          if ( 'auto-draft' === $post_data['post_status'] ) {
  97              $post_data['post_status'] = 'draft';
  98          }
  99  
 100          if ( ! get_post_status_object( $post_data['post_status'] ) ) {
 101              unset( $post_data['post_status'] );
 102          }
 103      }
 104  
 105      // What to do based on which button they pressed.
 106      if ( isset( $post_data['saveasdraft'] ) && '' !== $post_data['saveasdraft'] ) {
 107          $post_data['post_status'] = 'draft';
 108      }
 109      if ( isset( $post_data['saveasprivate'] ) && '' !== $post_data['saveasprivate'] ) {
 110          $post_data['post_status'] = 'private';
 111      }
 112      if ( isset( $post_data['publish'] ) && ( '' !== $post_data['publish'] )
 113          && ( ! isset( $post_data['post_status'] ) || 'private' !== $post_data['post_status'] )
 114      ) {
 115          $post_data['post_status'] = 'publish';
 116      }
 117      if ( isset( $post_data['advanced'] ) && '' !== $post_data['advanced'] ) {
 118          $post_data['post_status'] = 'draft';
 119      }
 120      if ( isset( $post_data['pending'] ) && '' !== $post_data['pending'] ) {
 121          $post_data['post_status'] = 'pending';
 122      }
 123  
 124      if ( isset( $post_data['ID'] ) ) {
 125          $post_id = $post_data['ID'];
 126      } else {
 127          $post_id = false;
 128      }
 129      $previous_status = $post_id ? get_post_field( 'post_status', $post_id ) : false;
 130  
 131      if ( isset( $post_data['post_status'] ) && 'private' === $post_data['post_status'] && ! current_user_can( $ptype->cap->publish_posts ) ) {
 132          $post_data['post_status'] = $previous_status ? $previous_status : 'pending';
 133      }
 134  
 135      $published_statuses = array( 'publish', 'future' );
 136  
 137      // Posts 'submitted for approval' are submitted to $_POST the same as if they were being published.
 138      // Change status from 'publish' to 'pending' if user lacks permissions to publish or to resave published posts.
 139      if ( isset( $post_data['post_status'] )
 140          && ( in_array( $post_data['post_status'], $published_statuses, true )
 141          && ! current_user_can( $ptype->cap->publish_posts ) )
 142      ) {
 143          if ( ! in_array( $previous_status, $published_statuses, true ) || ! current_user_can( 'edit_post', $post_id ) ) {
 144              $post_data['post_status'] = 'pending';
 145          }
 146      }
 147  
 148      if ( ! isset( $post_data['post_status'] ) ) {
 149          $post_data['post_status'] = 'auto-draft' === $previous_status ? 'draft' : $previous_status;
 150      }
 151  
 152      if ( isset( $post_data['post_password'] ) && ! current_user_can( $ptype->cap->publish_posts ) ) {
 153          unset( $post_data['post_password'] );
 154      }
 155  
 156      if ( ! isset( $post_data['comment_status'] ) ) {
 157          $post_data['comment_status'] = 'closed';
 158      }
 159  
 160      if ( ! isset( $post_data['ping_status'] ) ) {
 161          $post_data['ping_status'] = 'closed';
 162      }
 163  
 164      foreach ( array( 'aa', 'mm', 'jj', 'hh', 'mn' ) as $timeunit ) {
 165          if ( ! empty( $post_data[ 'hidden_' . $timeunit ] ) && $post_data[ 'hidden_' . $timeunit ] != $post_data[ $timeunit ] ) {
 166              $post_data['edit_date'] = '1';
 167              break;
 168          }
 169      }
 170  
 171      if ( ! empty( $post_data['edit_date'] ) ) {
 172          $aa = $post_data['aa'];
 173          $mm = $post_data['mm'];
 174          $jj = $post_data['jj'];
 175          $hh = $post_data['hh'];
 176          $mn = $post_data['mn'];
 177          $ss = $post_data['ss'];
 178          $aa = ( $aa <= 0 ) ? gmdate( 'Y' ) : $aa;
 179          $mm = ( $mm <= 0 ) ? gmdate( 'n' ) : $mm;
 180          $jj = ( $jj > 31 ) ? 31 : $jj;
 181          $jj = ( $jj <= 0 ) ? gmdate( 'j' ) : $jj;
 182          $hh = ( $hh > 23 ) ? $hh - 24 : $hh;
 183          $mn = ( $mn > 59 ) ? $mn - 60 : $mn;
 184          $ss = ( $ss > 59 ) ? $ss - 60 : $ss;
 185  
 186          $post_data['post_date'] = sprintf( '%04d-%02d-%02d %02d:%02d:%02d', $aa, $mm, $jj, $hh, $mn, $ss );
 187  
 188          $valid_date = wp_checkdate( $mm, $jj, $aa, $post_data['post_date'] );
 189          if ( ! $valid_date ) {
 190              return new WP_Error( 'invalid_date', __( 'Invalid date.' ) );
 191          }
 192  
 193          $post_data['post_date_gmt'] = get_gmt_from_date( $post_data['post_date'] );
 194      }
 195  
 196      if ( isset( $post_data['post_category'] ) ) {
 197          $category_object = get_taxonomy( 'category' );
 198          if ( ! current_user_can( $category_object->cap->assign_terms ) ) {
 199              unset( $post_data['post_category'] );
 200          }
 201      }
 202  
 203      return $post_data;
 204  }
 205  
 206  /**
 207   * Returns only allowed post data fields
 208   *
 209   * @since 5.0.1
 210   *
 211   * @param array $post_data Array of post data. Defaults to the contents of $_POST.
 212   * @return array|WP_Error Array of post data on success, WP_Error on failure.
 213   */
 214  function _wp_get_allowed_postdata( $post_data = null ) {
 215      if ( empty( $post_data ) ) {
 216          $post_data = $_POST;
 217      }
 218  
 219      // Pass through errors.
 220      if ( is_wp_error( $post_data ) ) {
 221          return $post_data;
 222      }
 223  
 224      return array_diff_key( $post_data, array_flip( array( 'meta_input', 'file', 'guid' ) ) );
 225  }
 226  
 227  /**
 228   * Update an existing post with values provided in $_POST.
 229   *
 230   * If post data is passed as an argument, it is treated as an array of data
 231   * keyed appropriately for turning into a post object.
 232   *
 233   * If post data is not passed, the $_POST global variable is used instead.
 234   *
 235   * @since 1.5.0
 236   *
 237   * @global wpdb $wpdb WordPress database abstraction object.
 238   *
 239   * @param array $post_data Optional. Defaults to the $_POST global.
 240   * @return int Post ID.
 241   */
 242  function edit_post( $post_data = null ) {
 243      global $wpdb;
 244  
 245      if ( empty( $post_data ) ) {
 246          $post_data = &$_POST;
 247      }
 248  
 249      // Clear out any data in internal vars.
 250      unset( $post_data['filter'] );
 251  
 252      $post_ID = (int) $post_data['post_ID'];
 253      $post    = get_post( $post_ID );
 254  
 255      $post_data['post_type']      = $post->post_type;
 256      $post_data['post_mime_type'] = $post->post_mime_type;
 257  
 258      if ( ! empty( $post_data['post_status'] ) ) {
 259          $post_data['post_status'] = sanitize_key( $post_data['post_status'] );
 260  
 261          if ( 'inherit' === $post_data['post_status'] ) {
 262              unset( $post_data['post_status'] );
 263          }
 264      }
 265  
 266      $ptype = get_post_type_object( $post_data['post_type'] );
 267      if ( ! current_user_can( 'edit_post', $post_ID ) ) {
 268          if ( 'page' === $post_data['post_type'] ) {
 269              wp_die( __( 'Sorry, you are not allowed to edit this page.' ) );
 270          } else {
 271              wp_die( __( 'Sorry, you are not allowed to edit this post.' ) );
 272          }
 273      }
 274  
 275      if ( post_type_supports( $ptype->name, 'revisions' ) ) {
 276          $revisions = wp_get_post_revisions(
 277              $post_ID,
 278              array(
 279                  'order'          => 'ASC',
 280                  'posts_per_page' => 1,
 281              )
 282          );
 283          $revision  = current( $revisions );
 284  
 285          // Check if the revisions have been upgraded.
 286          if ( $revisions && _wp_get_post_revision_version( $revision ) < 1 ) {
 287              _wp_upgrade_revisions_of_post( $post, wp_get_post_revisions( $post_ID ) );
 288          }
 289      }
 290  
 291      if ( isset( $post_data['visibility'] ) ) {
 292          switch ( $post_data['visibility'] ) {
 293              case 'public':
 294                  $post_data['post_password'] = '';
 295                  break;
 296              case 'password':
 297                  unset( $post_data['sticky'] );
 298                  break;
 299              case 'private':
 300                  $post_data['post_status']   = 'private';
 301                  $post_data['post_password'] = '';
 302                  unset( $post_data['sticky'] );
 303                  break;
 304          }
 305      }
 306  
 307      $post_data = _wp_translate_postdata( true, $post_data );
 308      if ( is_wp_error( $post_data ) ) {
 309          wp_die( $post_data->get_error_message() );
 310      }
 311      $translated = _wp_get_allowed_postdata( $post_data );
 312  
 313      // Post formats.
 314      if ( isset( $post_data['post_format'] ) ) {
 315          set_post_format( $post_ID, $post_data['post_format'] );
 316      }
 317  
 318      $format_meta_urls = array( 'url', 'link_url', 'quote_source_url' );
 319      foreach ( $format_meta_urls as $format_meta_url ) {
 320          $keyed = '_format_' . $format_meta_url;
 321          if ( isset( $post_data[ $keyed ] ) ) {
 322              update_post_meta( $post_ID, $keyed, wp_slash( esc_url_raw( wp_unslash( $post_data[ $keyed ] ) ) ) );
 323          }
 324      }
 325  
 326      $format_keys = array( 'quote', 'quote_source_name', 'image', 'gallery', 'audio_embed', 'video_embed' );
 327  
 328      foreach ( $format_keys as $key ) {
 329          $keyed = '_format_' . $key;
 330          if ( isset( $post_data[ $keyed ] ) ) {
 331              if ( current_user_can( 'unfiltered_html' ) ) {
 332                  update_post_meta( $post_ID, $keyed, $post_data[ $keyed ] );
 333              } else {
 334                  update_post_meta( $post_ID, $keyed, wp_filter_post_kses( $post_data[ $keyed ] ) );
 335              }
 336          }
 337      }
 338  
 339      if ( 'attachment' === $post_data['post_type'] && preg_match( '#^(audio|video)/#', $post_data['post_mime_type'] ) ) {
 340          $id3data = wp_get_attachment_metadata( $post_ID );
 341          if ( ! is_array( $id3data ) ) {
 342              $id3data = array();
 343          }
 344  
 345          foreach ( wp_get_attachment_id3_keys( $post, 'edit' ) as $key => $label ) {
 346              if ( isset( $post_data[ 'id3_' . $key ] ) ) {
 347                  $id3data[ $key ] = sanitize_text_field( wp_unslash( $post_data[ 'id3_' . $key ] ) );
 348              }
 349          }
 350          wp_update_attachment_metadata( $post_ID, $id3data );
 351      }
 352  
 353      // Meta stuff.
 354      if ( isset( $post_data['meta'] ) && $post_data['meta'] ) {
 355          foreach ( $post_data['meta'] as $key => $value ) {
 356              $meta = get_post_meta_by_id( $key );
 357              if ( ! $meta ) {
 358                  continue;
 359              }
 360              if ( $meta->post_id != $post_ID ) {
 361                  continue;
 362              }
 363              if ( is_protected_meta( $meta->meta_key, 'post' ) || ! current_user_can( 'edit_post_meta', $post_ID, $meta->meta_key ) ) {
 364                  continue;
 365              }
 366              if ( is_protected_meta( $value['key'], 'post' ) || ! current_user_can( 'edit_post_meta', $post_ID, $value['key'] ) ) {
 367                  continue;
 368              }
 369              update_meta( $key, $value['key'], $value['value'] );
 370          }
 371      }
 372  
 373      if ( isset( $post_data['deletemeta'] ) && $post_data['deletemeta'] ) {
 374          foreach ( $post_data['deletemeta'] as $key => $value ) {
 375              $meta = get_post_meta_by_id( $key );
 376              if ( ! $meta ) {
 377                  continue;
 378              }
 379              if ( $meta->post_id != $post_ID ) {
 380                  continue;
 381              }
 382              if ( is_protected_meta( $meta->meta_key, 'post' ) || ! current_user_can( 'delete_post_meta', $post_ID, $meta->meta_key ) ) {
 383                  continue;
 384              }
 385              delete_meta( $key );
 386          }
 387      }
 388  
 389      // Attachment stuff.
 390      if ( 'attachment' === $post_data['post_type'] ) {
 391          if ( isset( $post_data['_wp_attachment_image_alt'] ) ) {
 392              $image_alt = wp_unslash( $post_data['_wp_attachment_image_alt'] );
 393  
 394              if ( get_post_meta( $post_ID, '_wp_attachment_image_alt', true ) !== $image_alt ) {
 395                  $image_alt = wp_strip_all_tags( $image_alt, true );
 396  
 397                  // update_post_meta() expects slashed.
 398                  update_post_meta( $post_ID, '_wp_attachment_image_alt', wp_slash( $image_alt ) );
 399              }
 400          }
 401  
 402          $attachment_data = isset( $post_data['attachments'][ $post_ID ] ) ? $post_data['attachments'][ $post_ID ] : array();
 403  
 404          /** This filter is documented in wp-admin/includes/media.php */
 405          $translated = apply_filters( 'attachment_fields_to_save', $translated, $attachment_data );
 406      }
 407  
 408      // Convert taxonomy input to term IDs, to avoid ambiguity.
 409      if ( isset( $post_data['tax_input'] ) ) {
 410          foreach ( (array) $post_data['tax_input'] as $taxonomy => $terms ) {
 411              $tax_object = get_taxonomy( $taxonomy );
 412  
 413              if ( $tax_object && isset( $tax_object->meta_box_sanitize_cb ) ) {
 414                  $translated['tax_input'][ $taxonomy ] = call_user_func_array( $tax_object->meta_box_sanitize_cb, array( $taxonomy, $terms ) );
 415              }
 416          }
 417      }
 418  
 419      add_meta( $post_ID );
 420  
 421      update_post_meta( $post_ID, '_edit_last', get_current_user_id() );
 422  
 423      $success = wp_update_post( $translated );
 424  
 425      // If the save failed, see if we can sanity check the main fields and try again.
 426      if ( ! $success && is_callable( array( $wpdb, 'strip_invalid_text_for_column' ) ) ) {
 427          $fields = array( 'post_title', 'post_content', 'post_excerpt' );
 428  
 429          foreach ( $fields as $field ) {
 430              if ( isset( $translated[ $field ] ) ) {
 431                  $translated[ $field ] = $wpdb->strip_invalid_text_for_column( $wpdb->posts, $field, $translated[ $field ] );
 432              }
 433          }
 434  
 435          wp_update_post( $translated );
 436      }
 437  
 438      // Now that we have an ID we can fix any attachment anchor hrefs.
 439      _fix_attachment_links( $post_ID );
 440  
 441      wp_set_post_lock( $post_ID );
 442  
 443      if ( current_user_can( $ptype->cap->edit_others_posts ) && current_user_can( $ptype->cap->publish_posts ) ) {
 444          if ( ! empty( $post_data['sticky'] ) ) {
 445              stick_post( $post_ID );
 446          } else {
 447              unstick_post( $post_ID );
 448          }
 449      }
 450  
 451      return $post_ID;
 452  }
 453  
 454  /**
 455   * Process the post data for the bulk editing of posts.
 456   *
 457   * Updates all bulk edited posts/pages, adding (but not removing) tags and
 458   * categories. Skips pages when they would be their own parent or child.
 459   *
 460   * @since 2.7.0
 461   *
 462   * @global wpdb $wpdb WordPress database abstraction object.
 463   *
 464   * @param array $post_data Optional, the array of post data to process if not provided will use $_POST superglobal.
 465   * @return array
 466   */
 467  function bulk_edit_posts( $post_data = null ) {
 468      global $wpdb;
 469  
 470      if ( empty( $post_data ) ) {
 471          $post_data = &$_POST;
 472      }
 473  
 474      if ( isset( $post_data['post_type'] ) ) {
 475          $ptype = get_post_type_object( $post_data['post_type'] );
 476      } else {
 477          $ptype = get_post_type_object( 'post' );
 478      }
 479  
 480      if ( ! current_user_can( $ptype->cap->edit_posts ) ) {
 481          if ( 'page' === $ptype->name ) {
 482              wp_die( __( 'Sorry, you are not allowed to edit pages.' ) );
 483          } else {
 484              wp_die( __( 'Sorry, you are not allowed to edit posts.' ) );
 485          }
 486      }
 487  
 488      if ( -1 == $post_data['_status'] ) {
 489          $post_data['post_status'] = null;
 490          unset( $post_data['post_status'] );
 491      } else {
 492          $post_data['post_status'] = $post_data['_status'];
 493      }
 494      unset( $post_data['_status'] );
 495  
 496      if ( ! empty( $post_data['post_status'] ) ) {
 497          $post_data['post_status'] = sanitize_key( $post_data['post_status'] );
 498  
 499          if ( 'inherit' === $post_data['post_status'] ) {
 500              unset( $post_data['post_status'] );
 501          }
 502      }
 503  
 504      $post_IDs = array_map( 'intval', (array) $post_data['post'] );
 505  
 506      $reset = array(
 507          'post_author',
 508          'post_status',
 509          'post_password',
 510          'post_parent',
 511          'page_template',
 512          'comment_status',
 513          'ping_status',
 514          'keep_private',
 515          'tax_input',
 516          'post_category',
 517          'sticky',
 518          'post_format',
 519      );
 520  
 521      foreach ( $reset as $field ) {
 522          if ( isset( $post_data[ $field ] ) && ( '' === $post_data[ $field ] || -1 == $post_data[ $field ] ) ) {
 523              unset( $post_data[ $field ] );
 524          }
 525      }
 526  
 527      if ( isset( $post_data['post_category'] ) ) {
 528          if ( is_array( $post_data['post_category'] ) && ! empty( $post_data['post_category'] ) ) {
 529              $new_cats = array_map( 'absint', $post_data['post_category'] );
 530          } else {
 531              unset( $post_data['post_category'] );
 532          }
 533      }
 534  
 535      $tax_input = array();
 536      if ( isset( $post_data['tax_input'] ) ) {
 537          foreach ( $post_data['tax_input'] as $tax_name => $terms ) {
 538              if ( empty( $terms ) ) {
 539                  continue;
 540              }
 541              if ( is_taxonomy_hierarchical( $tax_name ) ) {
 542                  $tax_input[ $tax_name ] = array_map( 'absint', $terms );
 543              } else {
 544                  $comma = _x( ',', 'tag delimiter' );
 545                  if ( ',' !== $comma ) {
 546                      $terms = str_replace( $comma, ',', $terms );
 547                  }
 548                  $tax_input[ $tax_name ] = explode( ',', trim( $terms, " \n\t\r\0\x0B," ) );
 549              }
 550          }
 551      }
 552  
 553      if ( isset( $post_data['post_parent'] ) && (int) $post_data['post_parent'] ) {
 554          $parent   = (int) $post_data['post_parent'];
 555          $pages    = $wpdb->get_results( "SELECT ID, post_parent FROM $wpdb->posts WHERE post_type = 'page'" );
 556          $children = array();
 557  
 558          for ( $i = 0; $i < 50 && $parent > 0; $i++ ) {
 559              $children[] = $parent;
 560  
 561              foreach ( $pages as $page ) {
 562                  if ( (int) $page->ID === $parent ) {
 563                      $parent = (int) $page->post_parent;
 564                      break;
 565                  }
 566              }
 567          }
 568      }
 569  
 570      $updated          = array();
 571      $skipped          = array();
 572      $locked           = array();
 573      $shared_post_data = $post_data;
 574  
 575      foreach ( $post_IDs as $post_ID ) {
 576          // Start with fresh post data with each iteration.
 577          $post_data = $shared_post_data;
 578  
 579          $post_type_object = get_post_type_object( get_post_type( $post_ID ) );
 580  
 581          if ( ! isset( $post_type_object )
 582              || ( isset( $children ) && in_array( $post_ID, $children, true ) )
 583              || ! current_user_can( 'edit_post', $post_ID )
 584          ) {
 585              $skipped[] = $post_ID;
 586              continue;
 587          }
 588  
 589          if ( wp_check_post_lock( $post_ID ) ) {
 590              $locked[] = $post_ID;
 591              continue;
 592          }
 593  
 594          $post      = get_post( $post_ID );
 595          $tax_names = get_object_taxonomies( $post );
 596          foreach ( $tax_names as $tax_name ) {
 597              $taxonomy_obj = get_taxonomy( $tax_name );
 598              if ( isset( $tax_input[ $tax_name ] ) && current_user_can( $taxonomy_obj->cap->assign_terms ) ) {
 599                  $new_terms = $tax_input[ $tax_name ];
 600              } else {
 601                  $new_terms = array();
 602              }
 603  
 604              if ( $taxonomy_obj->hierarchical ) {
 605                  $current_terms = (array) wp_get_object_terms( $post_ID, $tax_name, array( 'fields' => 'ids' ) );
 606              } else {
 607                  $current_terms = (array) wp_get_object_terms( $post_ID, $tax_name, array( 'fields' => 'names' ) );
 608              }
 609  
 610              $post_data['tax_input'][ $tax_name ] = array_merge( $current_terms, $new_terms );
 611          }
 612  
 613          if ( isset( $new_cats ) && in_array( 'category', $tax_names, true ) ) {
 614              $cats                       = (array) wp_get_post_categories( $post_ID );
 615              $post_data['post_category'] = array_unique( array_merge( $cats, $new_cats ) );
 616              unset( $post_data['tax_input']['category'] );
 617          }
 618  
 619          $post_data['post_ID']        = $post_ID;
 620          $post_data['post_type']      = $post->post_type;
 621          $post_data['post_mime_type'] = $post->post_mime_type;
 622  
 623          foreach ( array( 'comment_status', 'ping_status', 'post_author' ) as $field ) {
 624              if ( ! isset( $post_data[ $field ] ) ) {
 625                  $post_data[ $field ] = $post->$field;
 626              }
 627          }
 628  
 629          $post_data = _wp_translate_postdata( true, $post_data );
 630          if ( is_wp_error( $post_data ) ) {
 631              $skipped[] = $post_ID;
 632              continue;
 633          }
 634          $post_data = _wp_get_allowed_postdata( $post_data );
 635  
 636          if ( isset( $shared_post_data['post_format'] ) ) {
 637              set_post_format( $post_ID, $shared_post_data['post_format'] );
 638          }
 639  
 640          // Prevent wp_insert_post() from overwriting post format with the old data.
 641          unset( $post_data['tax_input']['post_format'] );
 642  
 643          $updated[] = wp_update_post( $post_data );
 644  
 645          if ( isset( $post_data['sticky'] ) && current_user_can( $ptype->cap->edit_others_posts ) ) {
 646              if ( 'sticky' === $post_data['sticky'] ) {
 647                  stick_post( $post_ID );
 648              } else {
 649                  unstick_post( $post_ID );
 650              }
 651          }
 652      }
 653  
 654      return array(
 655          'updated' => $updated,
 656          'skipped' => $skipped,
 657          'locked'  => $locked,
 658      );
 659  }
 660  
 661  /**
 662   * Default post information to use when populating the "Write Post" form.
 663   *
 664   * @since 2.0.0
 665   *
 666   * @param string $post_type    Optional. A post type string. Default 'post'.
 667   * @param bool   $create_in_db Optional. Whether to insert the post into database. Default false.
 668   * @return WP_Post Post object containing all the default post data as attributes
 669   */
 670  function get_default_post_to_edit( $post_type = 'post', $create_in_db = false ) {
 671      $post_title = '';
 672      if ( ! empty( $_REQUEST['post_title'] ) ) {
 673          $post_title = esc_html( wp_unslash( $_REQUEST['post_title'] ) );
 674      }
 675  
 676      $post_content = '';
 677      if ( ! empty( $_REQUEST['content'] ) ) {
 678          $post_content = esc_html( wp_unslash( $_REQUEST['content'] ) );
 679      }
 680  
 681      $post_excerpt = '';
 682      if ( ! empty( $_REQUEST['excerpt'] ) ) {
 683          $post_excerpt = esc_html( wp_unslash( $_REQUEST['excerpt'] ) );
 684      }
 685  
 686      if ( $create_in_db ) {
 687          $post_id = wp_insert_post(
 688              array(
 689                  'post_title'  => __( 'Auto Draft' ),
 690                  'post_type'   => $post_type,
 691                  'post_status' => 'auto-draft',
 692              ),
 693              false,
 694              false
 695          );
 696          $post    = get_post( $post_id );
 697          if ( current_theme_supports( 'post-formats' ) && post_type_supports( $post->post_type, 'post-formats' ) && get_option( 'default_post_format' ) ) {
 698              set_post_format( $post, get_option( 'default_post_format' ) );
 699          }
 700          wp_after_insert_post( $post, false, null );
 701  
 702          // Schedule auto-draft cleanup.
 703          if ( ! wp_next_scheduled( 'wp_scheduled_auto_draft_delete' ) ) {
 704              wp_schedule_event( time(), 'daily', 'wp_scheduled_auto_draft_delete' );
 705          }
 706      } else {
 707          $post                 = new stdClass;
 708          $post->ID             = 0;
 709          $post->post_author    = '';
 710          $post->post_date      = '';
 711          $post->post_date_gmt  = '';
 712          $post->post_password  = '';
 713          $post->post_name      = '';
 714          $post->post_type      = $post_type;
 715          $post->post_status    = 'draft';
 716          $post->to_ping        = '';
 717          $post->pinged         = '';
 718          $post->comment_status = get_default_comment_status( $post_type );
 719          $post->ping_status    = get_default_comment_status( $post_type, 'pingback' );
 720          $post->post_pingback  = get_option( 'default_pingback_flag' );
 721          $post->post_category  = get_option( 'default_category' );
 722          $post->page_template  = 'default';
 723          $post->post_parent    = 0;
 724          $post->menu_order     = 0;
 725          $post                 = new WP_Post( $post );
 726      }
 727  
 728      /**
 729       * Filters the default post content initially used in the "Write Post" form.
 730       *
 731       * @since 1.5.0
 732       *
 733       * @param string  $post_content Default post content.
 734       * @param WP_Post $post         Post object.
 735       */
 736      $post->post_content = (string) apply_filters( 'default_content', $post_content, $post );
 737  
 738      /**
 739       * Filters the default post title initially used in the "Write Post" form.
 740       *
 741       * @since 1.5.0
 742       *
 743       * @param string  $post_title Default post title.
 744       * @param WP_Post $post       Post object.
 745       */
 746      $post->post_title = (string) apply_filters( 'default_title', $post_title, $post );
 747  
 748      /**
 749       * Filters the default post excerpt initially used in the "Write Post" form.
 750       *
 751       * @since 1.5.0
 752       *
 753       * @param string  $post_excerpt Default post excerpt.
 754       * @param WP_Post $post         Post object.
 755       */
 756      $post->post_excerpt = (string) apply_filters( 'default_excerpt', $post_excerpt, $post );
 757  
 758      return $post;
 759  }
 760  
 761  /**
 762   * Determines if a post exists based on title, content, date and type.
 763   *
 764   * @since 2.0.0
 765   * @since 5.2.0 Added the `$type` parameter.
 766   *
 767   * @global wpdb $wpdb WordPress database abstraction object.
 768   *
 769   * @param string $title   Post title.
 770   * @param string $content Optional post content.
 771   * @param string $date    Optional post date.
 772   * @param string $type    Optional post type.
 773   * @return int Post ID if post exists, 0 otherwise.
 774   */
 775  function post_exists( $title, $content = '', $date = '', $type = '' ) {
 776      global $wpdb;
 777  
 778      $post_title   = wp_unslash( sanitize_post_field( 'post_title', $title, 0, 'db' ) );
 779      $post_content = wp_unslash( sanitize_post_field( 'post_content', $content, 0, 'db' ) );
 780      $post_date    = wp_unslash( sanitize_post_field( 'post_date', $date, 0, 'db' ) );
 781      $post_type    = wp_unslash( sanitize_post_field( 'post_type', $type, 0, 'db' ) );
 782  
 783      $query = "SELECT ID FROM $wpdb->posts WHERE 1=1";
 784      $args  = array();
 785  
 786      if ( ! empty( $date ) ) {
 787          $query .= ' AND post_date = %s';
 788          $args[] = $post_date;
 789      }
 790  
 791      if ( ! empty( $title ) ) {
 792          $query .= ' AND post_title = %s';
 793          $args[] = $post_title;
 794      }
 795  
 796      if ( ! empty( $content ) ) {
 797          $query .= ' AND post_content = %s';
 798          $args[] = $post_content;
 799      }
 800  
 801      if ( ! empty( $type ) ) {
 802          $query .= ' AND post_type = %s';
 803          $args[] = $post_type;
 804      }
 805  
 806      if ( ! empty( $args ) ) {
 807          return (int) $wpdb->get_var( $wpdb->prepare( $query, $args ) );
 808      }
 809  
 810      return 0;
 811  }
 812  
 813  /**
 814   * Creates a new post from the "Write Post" form using $_POST information.
 815   *
 816   * @since 2.1.0
 817   *
 818   * @global WP_User $current_user
 819   *
 820   * @return int|WP_Error Post ID on success, WP_Error on failure.
 821   */
 822  function wp_write_post() {
 823      if ( isset( $_POST['post_type'] ) ) {
 824          $ptype = get_post_type_object( $_POST['post_type'] );
 825      } else {
 826          $ptype = get_post_type_object( 'post' );
 827      }
 828  
 829      if ( ! current_user_can( $ptype->cap->edit_posts ) ) {
 830          if ( 'page' === $ptype->name ) {
 831              return new WP_Error( 'edit_pages', __( 'Sorry, you are not allowed to create pages on this site.' ) );
 832          } else {
 833              return new WP_Error( 'edit_posts', __( 'Sorry, you are not allowed to create posts or drafts on this site.' ) );
 834          }
 835      }
 836  
 837      $_POST['post_mime_type'] = '';
 838  
 839      // Clear out any data in internal vars.
 840      unset( $_POST['filter'] );
 841  
 842      // Edit, don't write, if we have a post ID.
 843      if ( isset( $_POST['post_ID'] ) ) {
 844          return edit_post();
 845      }
 846  
 847      if ( isset( $_POST['visibility'] ) ) {
 848          switch ( $_POST['visibility'] ) {
 849              case 'public':
 850                  $_POST['post_password'] = '';
 851                  break;
 852              case 'password':
 853                  unset( $_POST['sticky'] );
 854                  break;
 855              case 'private':
 856                  $_POST['post_status']   = 'private';
 857                  $_POST['post_password'] = '';
 858                  unset( $_POST['sticky'] );
 859                  break;
 860          }
 861      }
 862  
 863      $translated = _wp_translate_postdata( false );
 864      if ( is_wp_error( $translated ) ) {
 865          return $translated;
 866      }
 867      $translated = _wp_get_allowed_postdata( $translated );
 868  
 869      // Create the post.
 870      $post_ID = wp_insert_post( $translated );
 871      if ( is_wp_error( $post_ID ) ) {
 872          return $post_ID;
 873      }
 874  
 875      if ( empty( $post_ID ) ) {
 876          return 0;
 877      }
 878  
 879      add_meta( $post_ID );
 880  
 881      add_post_meta( $post_ID, '_edit_last', $GLOBALS['current_user']->ID );
 882  
 883      // Now that we have an ID we can fix any attachment anchor hrefs.
 884      _fix_attachment_links( $post_ID );
 885  
 886      wp_set_post_lock( $post_ID );
 887  
 888      return $post_ID;
 889  }
 890  
 891  /**
 892   * Calls wp_write_post() and handles the errors.
 893   *
 894   * @since 2.0.0
 895   *
 896   * @return int|void Post ID on success, void on failure.
 897   */
 898  function write_post() {
 899      $result = wp_write_post();
 900      if ( is_wp_error( $result ) ) {
 901          wp_die( $result->get_error_message() );
 902      } else {
 903          return $result;
 904      }
 905  }
 906  
 907  //
 908  // Post Meta.
 909  //
 910  
 911  /**
 912   * Add post meta data defined in $_POST superglobal for post with given ID.
 913   *
 914   * @since 1.2.0
 915   *
 916   * @param int $post_ID
 917   * @return int|bool
 918   */
 919  function add_meta( $post_ID ) {
 920      $post_ID = (int) $post_ID;
 921  
 922      $metakeyselect = isset( $_POST['metakeyselect'] ) ? wp_unslash( trim( $_POST['metakeyselect'] ) ) : '';
 923      $metakeyinput  = isset( $_POST['metakeyinput'] ) ? wp_unslash( trim( $_POST['metakeyinput'] ) ) : '';
 924      $metavalue     = isset( $_POST['metavalue'] ) ? $_POST['metavalue'] : '';
 925      if ( is_string( $metavalue ) ) {
 926          $metavalue = trim( $metavalue );
 927      }
 928  
 929      if ( ( ( '#NONE#' !== $metakeyselect ) && ! empty( $metakeyselect ) ) || ! empty( $metakeyinput ) ) {
 930          /*
 931           * We have a key/value pair. If both the select and the input
 932           * for the key have data, the input takes precedence.
 933           */
 934          if ( '#NONE#' !== $metakeyselect ) {
 935              $metakey = $metakeyselect;
 936          }
 937  
 938          if ( $metakeyinput ) {
 939              $metakey = $metakeyinput; // Default.
 940          }
 941  
 942          if ( is_protected_meta( $metakey, 'post' ) || ! current_user_can( 'add_post_meta', $post_ID, $metakey ) ) {
 943              return false;
 944          }
 945  
 946          $metakey = wp_slash( $metakey );
 947  
 948          return add_post_meta( $post_ID, $metakey, $metavalue );
 949      }
 950  
 951      return false;
 952  }
 953  
 954  /**
 955   * Delete post meta data by meta ID.
 956   *
 957   * @since 1.2.0
 958   *
 959   * @param int $mid
 960   * @return bool
 961   */
 962  function delete_meta( $mid ) {
 963      return delete_metadata_by_mid( 'post', $mid );
 964  }
 965  
 966  /**
 967   * Get a list of previously defined keys.
 968   *
 969   * @since 1.2.0
 970   *
 971   * @global wpdb $wpdb WordPress database abstraction object.
 972   *
 973   * @return mixed
 974   */
 975  function get_meta_keys() {
 976      global $wpdb;
 977  
 978      $keys = $wpdb->get_col(
 979          "
 980              SELECT meta_key
 981              FROM $wpdb->postmeta
 982              GROUP BY meta_key
 983              ORDER BY meta_key"
 984      );
 985  
 986      return $keys;
 987  }
 988  
 989  /**
 990   * Get post meta data by meta ID.
 991   *
 992   * @since 2.1.0
 993   *
 994   * @param int $mid
 995   * @return object|bool
 996   */
 997  function get_post_meta_by_id( $mid ) {
 998      return get_metadata_by_mid( 'post', $mid );
 999  }
1000  
1001  /**
1002   * Get meta data for the given post ID.
1003   *
1004   * @since 1.2.0
1005   *
1006   * @global wpdb $wpdb WordPress database abstraction object.
1007   *
1008   * @param int $postid
1009   * @return mixed
1010   */
1011  function has_meta( $postid ) {
1012      global $wpdb;
1013  
1014      return $wpdb->get_results(
1015          $wpdb->prepare(
1016              "SELECT meta_key, meta_value, meta_id, post_id
1017              FROM $wpdb->postmeta WHERE post_id = %d
1018              ORDER BY meta_key,meta_id",
1019              $postid
1020          ),
1021          ARRAY_A
1022      );
1023  }
1024  
1025  /**
1026   * Update post meta data by meta ID.
1027   *
1028   * @since 1.2.0
1029   *
1030   * @param int    $meta_id
1031   * @param string $meta_key Expect Slashed
1032   * @param string $meta_value Expect Slashed
1033   * @return bool
1034   */
1035  function update_meta( $meta_id, $meta_key, $meta_value ) {
1036      $meta_key   = wp_unslash( $meta_key );
1037      $meta_value = wp_unslash( $meta_value );
1038  
1039      return update_metadata_by_mid( 'post', $meta_id, $meta_value, $meta_key );
1040  }
1041  
1042  //
1043  // Private.
1044  //
1045  
1046  /**
1047   * Replace hrefs of attachment anchors with up-to-date permalinks.
1048   *
1049   * @since 2.3.0
1050   * @access private
1051   *
1052   * @param int|object $post Post ID or post object.
1053   * @return void|int|WP_Error Void if nothing fixed. 0 or WP_Error on update failure. The post ID on update success.
1054   */
1055  function _fix_attachment_links( $post ) {
1056      $post    = get_post( $post, ARRAY_A );
1057      $content = $post['post_content'];
1058  
1059      // Don't run if no pretty permalinks or post is not published, scheduled, or privately published.
1060      if ( ! get_option( 'permalink_structure' ) || ! in_array( $post['post_status'], array( 'publish', 'future', 'private' ), true ) ) {
1061          return;
1062      }
1063  
1064      // Short if there aren't any links or no '?attachment_id=' strings (strpos cannot be zero).
1065      if ( ! strpos( $content, '?attachment_id=' ) || ! preg_match_all( '/<a ([^>]+)>[\s\S]+?<\/a>/', $content, $link_matches ) ) {
1066          return;
1067      }
1068  
1069      $site_url = get_bloginfo( 'url' );
1070      $site_url = substr( $site_url, (int) strpos( $site_url, '://' ) ); // Remove the http(s).
1071      $replace  = '';
1072  
1073      foreach ( $link_matches[1] as $key => $value ) {
1074          if ( ! strpos( $value, '?attachment_id=' ) || ! strpos( $value, 'wp-att-' )
1075              || ! preg_match( '/href=(["\'])[^"\']*\?attachment_id=(\d+)[^"\']*\\1/', $value, $url_match )
1076              || ! preg_match( '/rel=["\'][^"\']*wp-att-(\d+)/', $value, $rel_match ) ) {
1077                  continue;
1078          }
1079  
1080          $quote  = $url_match[1]; // The quote (single or double).
1081          $url_id = (int) $url_match[2];
1082          $rel_id = (int) $rel_match[1];
1083  
1084          if ( ! $url_id || ! $rel_id || $url_id != $rel_id || strpos( $url_match[0], $site_url ) === false ) {
1085              continue;
1086          }
1087  
1088          $link    = $link_matches[0][ $key ];
1089          $replace = str_replace( $url_match[0], 'href=' . $quote . get_attachment_link( $url_id ) . $quote, $link );
1090  
1091          $content = str_replace( $link, $replace, $content );
1092      }
1093  
1094      if ( $replace ) {
1095          $post['post_content'] = $content;
1096          // Escape data pulled from DB.
1097          $post = add_magic_quotes( $post );
1098  
1099          return wp_update_post( $post );
1100      }
1101  }
1102  
1103  /**
1104   * Get all the possible statuses for a post_type
1105   *
1106   * @since 2.5.0
1107   *
1108   * @param string $type The post_type you want the statuses for. Default 'post'.
1109   * @return string[] An array of all the statuses for the supplied post type.
1110   */
1111  function get_available_post_statuses( $type = 'post' ) {
1112      $stati = wp_count_posts( $type );
1113  
1114      return array_keys( get_object_vars( $stati ) );
1115  }
1116  
1117  /**
1118   * Run the wp query to fetch the posts for listing on the edit posts page
1119   *
1120   * @since 2.5.0
1121   *
1122   * @param array|false $q Array of query variables to use to build the query or false to use $_GET superglobal.
1123   * @return array
1124   */
1125  function wp_edit_posts_query( $q = false ) {
1126      if ( false === $q ) {
1127          $q = $_GET;
1128      }
1129      $q['m']     = isset( $q['m'] ) ? (int) $q['m'] : 0;
1130      $q['cat']   = isset( $q['cat'] ) ? (int) $q['cat'] : 0;
1131      $post_stati = get_post_stati();
1132  
1133      if ( isset( $q['post_type'] ) && in_array( $q['post_type'], get_post_types(), true ) ) {
1134          $post_type = $q['post_type'];
1135      } else {
1136          $post_type = 'post';
1137      }
1138  
1139      $avail_post_stati = get_available_post_statuses( $post_type );
1140      $post_status      = '';
1141      $perm             = '';
1142  
1143      if ( isset( $q['post_status'] ) && in_array( $q['post_status'], $post_stati, true ) ) {
1144          $post_status = $q['post_status'];
1145          $perm        = 'readable';
1146      }
1147  
1148      $orderby = '';
1149  
1150      if ( isset( $q['orderby'] ) ) {
1151          $orderby = $q['orderby'];
1152      } elseif ( isset( $q['post_status'] ) && in_array( $q['post_status'], array( 'pending', 'draft' ), true ) ) {
1153          $orderby = 'modified';
1154      }
1155  
1156      $order = '';
1157  
1158      if ( isset( $q['order'] ) ) {
1159          $order = $q['order'];
1160      } elseif ( isset( $q['post_status'] ) && 'pending' === $q['post_status'] ) {
1161          $order = 'ASC';
1162      }
1163  
1164      $per_page       = "edit_{$post_type}_per_page";
1165      $posts_per_page = (int) get_user_option( $per_page );
1166      if ( empty( $posts_per_page ) || $posts_per_page < 1 ) {
1167          $posts_per_page = 20;
1168      }
1169  
1170      /**
1171       * Filters the number of items per page to show for a specific 'per_page' type.
1172       *
1173       * The dynamic portion of the hook name, `$post_type`, refers to the post type.
1174       *
1175       * Possible hook names include:
1176       *
1177       *  - `edit_post_per_page`
1178       *  - `edit_page_per_page`
1179       *  - `edit_attachment_per_page`
1180       *
1181       * @since 3.0.0
1182       *
1183       * @param int $posts_per_page Number of posts to display per page for the given post
1184       *                            type. Default 20.
1185       */
1186      $posts_per_page = apply_filters( "edit_{$post_type}_per_page", $posts_per_page );
1187  
1188      /**
1189       * Filters the number of posts displayed per page when specifically listing "posts".
1190       *
1191       * @since 2.8.0
1192       *
1193       * @param int    $posts_per_page Number of posts to be displayed. Default 20.
1194       * @param string $post_type      The post type.
1195       */
1196      $posts_per_page = apply_filters( 'edit_posts_per_page', $posts_per_page, $post_type );
1197  
1198      $query = compact( 'post_type', 'post_status', 'perm', 'order', 'orderby', 'posts_per_page' );
1199  
1200      // Hierarchical types require special args.
1201      if ( is_post_type_hierarchical( $post_type ) && empty( $orderby ) ) {
1202          $query['orderby']                = 'menu_order title';
1203          $query['order']                  = 'asc';
1204          $query['posts_per_page']         = -1;
1205          $query['posts_per_archive_page'] = -1;
1206          $query['fields']                 = 'id=>parent';
1207      }
1208  
1209      if ( ! empty( $q['show_sticky'] ) ) {
1210          $query['post__in'] = (array) get_option( 'sticky_posts' );
1211      }
1212  
1213      wp( $query );
1214  
1215      return $avail_post_stati;
1216  }
1217  
1218  /**
1219   * Get the query variables for the current attachments request.
1220   *
1221   * @since 4.2.0
1222   *
1223   * @param array|false $q Optional. Array of query variables to use to build the query or false
1224   *                       to use $_GET superglobal. Default false.
1225   * @return array The parsed query vars.
1226   */
1227  function wp_edit_attachments_query_vars( $q = false ) {
1228      if ( false === $q ) {
1229          $q = $_GET;
1230      }
1231      $q['m']         = isset( $q['m'] ) ? (int) $q['m'] : 0;
1232      $q['cat']       = isset( $q['cat'] ) ? (int) $q['cat'] : 0;
1233      $q['post_type'] = 'attachment';
1234      $post_type      = get_post_type_object( 'attachment' );
1235      $states         = 'inherit';
1236      if ( current_user_can( $post_type->cap->read_private_posts ) ) {
1237          $states .= ',private';
1238      }
1239  
1240      $q['post_status'] = isset( $q['status'] ) && 'trash' === $q['status'] ? 'trash' : $states;
1241      $q['post_status'] = isset( $q['attachment-filter'] ) && 'trash' === $q['attachment-filter'] ? 'trash' : $states;
1242  
1243      $media_per_page = (int) get_user_option( 'upload_per_page' );
1244      if ( empty( $media_per_page ) || $media_per_page < 1 ) {
1245          $media_per_page = 20;
1246      }
1247  
1248      /**
1249       * Filters the number of items to list per page when listing media items.
1250       *
1251       * @since 2.9.0
1252       *
1253       * @param int $media_per_page Number of media to list. Default 20.
1254       */
1255      $q['posts_per_page'] = apply_filters( 'upload_per_page', $media_per_page );
1256  
1257      $post_mime_types = get_post_mime_types();
1258      if ( isset( $q['post_mime_type'] ) && ! array_intersect( (array) $q['post_mime_type'], array_keys( $post_mime_types ) ) ) {
1259          unset( $q['post_mime_type'] );
1260      }
1261  
1262      foreach ( array_keys( $post_mime_types ) as $type ) {
1263          if ( isset( $q['attachment-filter'] ) && "post_mime_type:$type" === $q['attachment-filter'] ) {
1264              $q['post_mime_type'] = $type;
1265              break;
1266          }
1267      }
1268  
1269      if ( isset( $q['detached'] ) || ( isset( $q['attachment-filter'] ) && 'detached' === $q['attachment-filter'] ) ) {
1270          $q['post_parent'] = 0;
1271      }
1272  
1273      if ( isset( $q['mine'] ) || ( isset( $q['attachment-filter'] ) && 'mine' === $q['attachment-filter'] ) ) {
1274          $q['author'] = get_current_user_id();
1275      }
1276  
1277      // Filter query clauses to include filenames.
1278      if ( isset( $q['s'] ) ) {
1279          add_filter( 'posts_clauses', '_filter_query_attachment_filenames' );
1280      }
1281  
1282      return $q;
1283  }
1284  
1285  /**
1286   * Executes a query for attachments. An array of WP_Query arguments
1287   * can be passed in, which will override the arguments set by this function.
1288   *
1289   * @since 2.5.0
1290   *
1291   * @param array|false $q Array of query variables to use to build the query or false to use $_GET superglobal.
1292   * @return array
1293   */
1294  function wp_edit_attachments_query( $q = false ) {
1295      wp( wp_edit_attachments_query_vars( $q ) );
1296  
1297      $post_mime_types       = get_post_mime_types();
1298      $avail_post_mime_types = get_available_post_mime_types( 'attachment' );
1299  
1300      return array( $post_mime_types, $avail_post_mime_types );
1301  }
1302  
1303  /**
1304   * Returns the list of classes to be used by a meta box.
1305   *
1306   * @since 2.5.0
1307   *
1308   * @param string $box_id    Meta box ID (used in the 'id' attribute for the meta box).
1309   * @param string $screen_id The screen on which the meta box is shown.
1310   * @return string Space-separated string of class names.
1311   */
1312  function postbox_classes( $box_id, $screen_id ) {
1313      if ( isset( $_GET['edit'] ) && $_GET['edit'] == $box_id ) {
1314          $classes = array( '' );
1315      } elseif ( get_user_option( 'closedpostboxes_' . $screen_id ) ) {
1316          $closed = get_user_option( 'closedpostboxes_' . $screen_id );
1317          if ( ! is_array( $closed ) ) {
1318              $classes = array( '' );
1319          } else {
1320              $classes = in_array( $box_id, $closed, true ) ? array( 'closed' ) : array( '' );
1321          }
1322      } else {
1323          $classes = array( '' );
1324      }
1325  
1326      /**
1327       * Filters the postbox classes for a specific screen and box ID combo.
1328       *
1329       * The dynamic portions of the hook name, `$screen_id` and `$box_id`, refer to
1330       * the screen ID and meta box ID, respectively.
1331       *
1332       * @since 3.2.0
1333       *
1334       * @param string[] $classes An array of postbox classes.
1335       */
1336      $classes = apply_filters( "postbox_classes_{$screen_id}_{$box_id}", $classes );
1337      return implode( ' ', $classes );
1338  }
1339  
1340  /**
1341   * Get a sample permalink based off of the post name.
1342   *
1343   * @since 2.5.0
1344   *
1345   * @param int|WP_Post $id    Post ID or post object.
1346   * @param string      $title Optional. Title to override the post's current title when generating the post name. Default null.
1347   * @param string      $name  Optional. Name to override the post name. Default null.
1348   * @return array {
1349   *     Array containing the sample permalink with placeholder for the post name, and the post name.
1350   *
1351   *     @type string $0 The permalink with placeholder for the post name.
1352   *     @type string $1 The post name.
1353   * }
1354   */
1355  function get_sample_permalink( $id, $title = null, $name = null ) {
1356      $post = get_post( $id );
1357      if ( ! $post ) {
1358          return array( '', '' );
1359      }
1360  
1361      $ptype = get_post_type_object( $post->post_type );
1362  
1363      $original_status = $post->post_status;
1364      $original_date   = $post->post_date;
1365      $original_name   = $post->post_name;
1366  
1367      // Hack: get_permalink() would return plain permalink for drafts, so we will fake that our post is published.
1368      if ( in_array( $post->post_status, array( 'draft', 'pending', 'future' ), true ) ) {
1369          $post->post_status = 'publish';
1370          $post->post_name   = sanitize_title( $post->post_name ? $post->post_name : $post->post_title, $post->ID );
1371      }
1372  
1373      // If the user wants to set a new name -- override the current one.
1374      // Note: if empty name is supplied -- use the title instead, see #6072.
1375      if ( ! is_null( $name ) ) {
1376          $post->post_name = sanitize_title( $name ? $name : $title, $post->ID );
1377      }
1378  
1379      $post->post_name = wp_unique_post_slug( $post->post_name, $post->ID, $post->post_status, $post->post_type, $post->post_parent );
1380  
1381      $post->filter = 'sample';
1382  
1383      $permalink = get_permalink( $post, true );
1384  
1385      // Replace custom post_type token with generic pagename token for ease of use.
1386      $permalink = str_replace( "%$post->post_type%", '%pagename%', $permalink );
1387  
1388      // Handle page hierarchy.
1389      if ( $ptype->hierarchical ) {
1390          $uri = get_page_uri( $post );
1391          if ( $uri ) {
1392              $uri = untrailingslashit( $uri );
1393              $uri = strrev( stristr( strrev( $uri ), '/' ) );
1394              $uri = untrailingslashit( $uri );
1395          }
1396  
1397          /** This filter is documented in wp-admin/edit-tag-form.php */
1398          $uri = apply_filters( 'editable_slug', $uri, $post );
1399          if ( ! empty( $uri ) ) {
1400              $uri .= '/';
1401          }
1402          $permalink = str_replace( '%pagename%', "{$uri}%pagename%", $permalink );
1403      }
1404  
1405      /** This filter is documented in wp-admin/edit-tag-form.php */
1406      $permalink         = array( $permalink, apply_filters( 'editable_slug', $post->post_name, $post ) );
1407      $post->post_status = $original_status;
1408      $post->post_date   = $original_date;
1409      $post->post_name   = $original_name;
1410      unset( $post->filter );
1411  
1412      /**
1413       * Filters the sample permalink.
1414       *
1415       * @since 4.4.0
1416       *
1417       * @param array   $permalink {
1418       *     Array containing the sample permalink with placeholder for the post name, and the post name.
1419       *
1420       *     @type string $0 The permalink with placeholder for the post name.
1421       *     @type string $1 The post name.
1422       * }
1423       * @param int     $post_id   Post ID.
1424       * @param string  $title     Post title.
1425       * @param string  $name      Post name (slug).
1426       * @param WP_Post $post      Post object.
1427       */
1428      return apply_filters( 'get_sample_permalink', $permalink, $post->ID, $title, $name, $post );
1429  }
1430  
1431  /**
1432   * Returns the HTML of the sample permalink slug editor.
1433   *
1434   * @since 2.5.0
1435   *
1436   * @param int    $id        Post ID or post object.
1437   * @param string $new_title Optional. New title. Default null.
1438   * @param string $new_slug  Optional. New slug. Default null.
1439   * @return string The HTML of the sample permalink slug editor.
1440   */
1441  function get_sample_permalink_html( $id, $new_title = null, $new_slug = null ) {
1442      $post = get_post( $id );
1443      if ( ! $post ) {
1444          return '';
1445      }
1446  
1447      list($permalink, $post_name) = get_sample_permalink( $post->ID, $new_title, $new_slug );
1448  
1449      $view_link      = false;
1450      $preview_target = '';
1451  
1452      if ( current_user_can( 'read_post', $post->ID ) ) {
1453          if ( 'draft' === $post->post_status || empty( $post->post_name ) ) {
1454              $view_link      = get_preview_post_link( $post );
1455              $preview_target = " target='wp-preview-{$post->ID}'";
1456          } else {
1457              if ( 'publish' === $post->post_status || 'attachment' === $post->post_type ) {
1458                  $view_link = get_permalink( $post );
1459              } else {
1460                  // Allow non-published (private, future) to be viewed at a pretty permalink, in case $post->post_name is set.
1461                  $view_link = str_replace( array( '%pagename%', '%postname%' ), $post->post_name, $permalink );
1462              }
1463          }
1464      }
1465  
1466      // Permalinks without a post/page name placeholder don't have anything to edit.
1467      if ( false === strpos( $permalink, '%postname%' ) && false === strpos( $permalink, '%pagename%' ) ) {
1468          $return = '<strong>' . __( 'Permalink:' ) . "</strong>\n";
1469  
1470          if ( false !== $view_link ) {
1471              $display_link = urldecode( $view_link );
1472              $return      .= '<a id="sample-permalink" href="' . esc_url( $view_link ) . '"' . $preview_target . '>' . esc_html( $display_link ) . "</a>\n";
1473          } else {
1474              $return .= '<span id="sample-permalink">' . $permalink . "</span>\n";
1475          }
1476  
1477          // Encourage a pretty permalink setting.
1478          if ( ! get_option( 'permalink_structure' ) && current_user_can( 'manage_options' )
1479              && ! ( 'page' === get_option( 'show_on_front' ) && get_option( 'page_on_front' ) == $id )
1480          ) {
1481              $return .= '<span id="change-permalinks"><a href="options-permalink.php" class="button button-small" target="_blank">' . __( 'Change Permalinks' ) . "</a></span>\n";
1482          }
1483      } else {
1484          if ( mb_strlen( $post_name ) > 34 ) {
1485              $post_name_abridged = mb_substr( $post_name, 0, 16 ) . '&hellip;' . mb_substr( $post_name, -16 );
1486          } else {
1487              $post_name_abridged = $post_name;
1488          }
1489  
1490          $post_name_html = '<span id="editable-post-name">' . esc_html( $post_name_abridged ) . '</span>';
1491          $display_link   = str_replace( array( '%pagename%', '%postname%' ), $post_name_html, esc_html( urldecode( $permalink ) ) );
1492  
1493          $return  = '<strong>' . __( 'Permalink:' ) . "</strong>\n";
1494          $return .= '<span id="sample-permalink"><a href="' . esc_url( $view_link ) . '"' . $preview_target . '>' . $display_link . "</a></span>\n";
1495          $return .= '&lrm;'; // Fix bi-directional text display defect in RTL languages.
1496          $return .= '<span id="edit-slug-buttons"><button type="button" class="edit-slug button button-small hide-if-no-js" aria-label="' . __( 'Edit permalink' ) . '">' . __( 'Edit' ) . "</button></span>\n";
1497          $return .= '<span id="editable-post-name-full">' . esc_html( $post_name ) . "</span>\n";
1498      }
1499  
1500      /**
1501       * Filters the sample permalink HTML markup.
1502       *
1503       * @since 2.9.0
1504       * @since 4.4.0 Added `$post` parameter.
1505       *
1506       * @param string  $return    Sample permalink HTML markup.
1507       * @param int     $post_id   Post ID.
1508       * @param string  $new_title New sample permalink title.
1509       * @param string  $new_slug  New sample permalink slug.
1510       * @param WP_Post $post      Post object.
1511       */
1512      $return = apply_filters( 'get_sample_permalink_html', $return, $post->ID, $new_title, $new_slug, $post );
1513  
1514      return $return;
1515  }
1516  
1517  /**
1518   * Returns HTML for the post thumbnail meta box.
1519   *
1520   * @since 2.9.0
1521   *
1522   * @param int         $thumbnail_id ID of the attachment used for thumbnail
1523   * @param int|WP_Post $post         Optional. The post ID or object associated with the thumbnail, defaults to global $post.
1524   * @return string The post thumbnail HTML.
1525   */
1526  function _wp_post_thumbnail_html( $thumbnail_id = null, $post = null ) {
1527      $_wp_additional_image_sizes = wp_get_additional_image_sizes();
1528  
1529      $post               = get_post( $post );
1530      $post_type_object   = get_post_type_object( $post->post_type );
1531      $set_thumbnail_link = '<p class="hide-if-no-js"><a href="%s" id="set-post-thumbnail"%s class="thickbox">%s</a></p>';
1532      $upload_iframe_src  = get_upload_iframe_src( 'image', $post->ID );
1533  
1534      $content = sprintf(
1535          $set_thumbnail_link,
1536          esc_url( $upload_iframe_src ),
1537          '', // Empty when there's no featured image set, `aria-describedby` attribute otherwise.
1538          esc_html( $post_type_object->labels->set_featured_image )
1539      );
1540  
1541      if ( $thumbnail_id && get_post( $thumbnail_id ) ) {
1542          $size = isset( $_wp_additional_image_sizes['post-thumbnail'] ) ? 'post-thumbnail' : array( 266, 266 );
1543  
1544          /**
1545           * Filters the size used to display the post thumbnail image in the 'Featured image' meta box.
1546           *
1547           * Note: When a theme adds 'post-thumbnail' support, a special 'post-thumbnail'
1548           * image size is registered, which differs from the 'thumbnail' image size
1549           * managed via the Settings > Media screen.
1550           *
1551           * @since 4.4.0
1552           *
1553           * @param string|int[] $size         Requested image size. Can be any registered image size name, or
1554           *                                   an array of width and height values in pixels (in that order).
1555           * @param int          $thumbnail_id Post thumbnail attachment ID.
1556           * @param WP_Post      $post         The post object associated with the thumbnail.
1557           */
1558          $size = apply_filters( 'admin_post_thumbnail_size', $size, $thumbnail_id, $post );
1559  
1560          $thumbnail_html = wp_get_attachment_image( $thumbnail_id, $size );
1561  
1562          if ( ! empty( $thumbnail_html ) ) {
1563              $content  = sprintf(
1564                  $set_thumbnail_link,
1565                  esc_url( $upload_iframe_src ),
1566                  ' aria-describedby="set-post-thumbnail-desc"',
1567                  $thumbnail_html
1568              );
1569              $content .= '<p class="hide-if-no-js howto" id="set-post-thumbnail-desc">' . __( 'Click the image to edit or update' ) . '</p>';
1570              $content .= '<p class="hide-if-no-js"><a href="#" id="remove-post-thumbnail">' . esc_html( $post_type_object->labels->remove_featured_image ) . '</a></p>';
1571          }
1572      }
1573  
1574      $content .= '<input type="hidden" id="_thumbnail_id" name="_thumbnail_id" value="' . esc_attr( $thumbnail_id ? $thumbnail_id : '-1' ) . '" />';
1575  
1576      /**
1577       * Filters the admin post thumbnail HTML markup to return.
1578       *
1579       * @since 2.9.0
1580       * @since 3.5.0 Added the `$post_id` parameter.
1581       * @since 4.6.0 Added the `$thumbnail_id` parameter.
1582       *
1583       * @param string   $content      Admin post thumbnail HTML markup.
1584       * @param int      $post_id      Post ID.
1585       * @param int|null $thumbnail_id Thumbnail attachment ID, or null if there isn't one.
1586       */
1587      return apply_filters( 'admin_post_thumbnail_html', $content, $post->ID, $thumbnail_id );
1588  }
1589  
1590  /**
1591   * Check to see if the post is currently being edited by another user.
1592   *
1593   * @since 2.5.0
1594   *
1595   * @param int|WP_Post $post_id ID or object of the post to check for editing.
1596   * @return int|false ID of the user with lock. False if the post does not exist, post is not locked,
1597   *                   the user with lock does not exist, or the post is locked by current user.
1598   */
1599  function wp_check_post_lock( $post_id ) {
1600      $post = get_post( $post_id );
1601      if ( ! $post ) {
1602          return false;
1603      }
1604  
1605      $lock = get_post_meta( $post->ID, '_edit_lock', true );
1606      if ( ! $lock ) {
1607          return false;
1608      }
1609  
1610      $lock = explode( ':', $lock );
1611      $time = $lock[0];
1612      $user = isset( $lock[1] ) ? $lock[1] : get_post_meta( $post->ID, '_edit_last', true );
1613  
1614      if ( ! get_userdata( $user ) ) {
1615          return false;
1616      }
1617  
1618      /** This filter is documented in wp-admin/includes/ajax-actions.php */
1619      $time_window = apply_filters( 'wp_check_post_lock_window', 150 );
1620  
1621      if ( $time && $time > time() - $time_window && get_current_user_id() != $user ) {
1622          return $user;
1623      }
1624  
1625      return false;
1626  }
1627  
1628  /**
1629   * Mark the post as currently being edited by the current user
1630   *
1631   * @since 2.5.0
1632   *
1633   * @param int|WP_Post $post_id ID or object of the post being edited.
1634   * @return array|false Array of the lock time and user ID. False if the post does not exist, or
1635   *                     there is no current user.
1636   */
1637  function wp_set_post_lock( $post_id ) {
1638      $post = get_post( $post_id );
1639      if ( ! $post ) {
1640          return false;
1641      }
1642  
1643      $user_id = get_current_user_id();
1644      if ( 0 == $user_id ) {
1645          return false;
1646      }
1647  
1648      $now  = time();
1649      $lock = "$now:$user_id";
1650  
1651      update_post_meta( $post->ID, '_edit_lock', $lock );
1652  
1653      return array( $now, $user_id );
1654  }
1655  
1656  /**
1657   * Outputs the HTML for the notice to say that someone else is editing or has taken over editing of this post.
1658   *
1659   * @since 2.8.5
1660   */
1661  function _admin_notice_post_locked() {
1662      $post = get_post();
1663      if ( ! $post ) {
1664          return;
1665      }
1666  
1667      $user    = null;
1668      $user_id = wp_check_post_lock( $post->ID );
1669      if ( $user_id ) {
1670          $user = get_userdata( $user_id );
1671      }
1672  
1673      if ( $user ) {
1674          /**
1675           * Filters whether to show the post locked dialog.
1676           *
1677           * Returning false from the filter will prevent the dialog from being displayed.
1678           *
1679           * @since 3.6.0
1680           *
1681           * @param bool    $display Whether to display the dialog. Default true.
1682           * @param WP_Post $post    Post object.
1683           * @param WP_User $user    The user with the lock for the post.
1684           */
1685          if ( ! apply_filters( 'show_post_locked_dialog', true, $post, $user ) ) {
1686              return;
1687          }
1688  
1689          $locked = true;
1690      } else {
1691          $locked = false;
1692      }
1693  
1694      $sendback = wp_get_referer();
1695      if ( $locked && $sendback && false === strpos( $sendback, 'post.php' ) && false === strpos( $sendback, 'post-new.php' ) ) {
1696  
1697          $sendback_text = __( 'Go back' );
1698      } else {
1699          $sendback = admin_url( 'edit.php' );
1700  
1701          if ( 'post' !== $post->post_type ) {
1702              $sendback = add_query_arg( 'post_type', $post->post_type, $sendback );
1703          }
1704  
1705          $sendback_text = get_post_type_object( $post->post_type )->labels->all_items;
1706      }
1707  
1708      $hidden = $locked ? '' : ' hidden';
1709  
1710      ?>
1711      <div id="post-lock-dialog" class="notification-dialog-wrap<?php echo $hidden; ?>">
1712      <div class="notification-dialog-background"></div>
1713      <div class="notification-dialog">
1714      <?php
1715  
1716      if ( $locked ) {
1717          $query_args = array();
1718          if ( get_post_type_object( $post->post_type )->public ) {
1719              if ( 'publish' === $post->post_status || $user->ID != $post->post_author ) {
1720                  // Latest content is in autosave.
1721                  $nonce                       = wp_create_nonce( 'post_preview_' . $post->ID );
1722                  $query_args['preview_id']    = $post->ID;
1723                  $query_args['preview_nonce'] = $nonce;
1724              }
1725          }
1726  
1727          $preview_link = get_preview_post_link( $post->ID, $query_args );
1728  
1729          /**
1730           * Filters whether to allow the post lock to be overridden.
1731           *
1732           * Returning false from the filter will disable the ability
1733           * to override the post lock.
1734           *
1735           * @since 3.6.0
1736           *
1737           * @param bool    $override Whether to allow the post lock to be overridden. Default true.
1738           * @param WP_Post $post     Post object.
1739           * @param WP_User $user     The user with the lock for the post.
1740           */
1741          $override = apply_filters( 'override_post_lock', true, $post, $user );
1742          $tab_last = $override ? '' : ' wp-tab-last';
1743  
1744          ?>
1745          <div class="post-locked-message">
1746          <div class="post-locked-avatar"><?php echo get_avatar( $user->ID, 64 ); ?></div>
1747          <p class="currently-editing wp-tab-first" tabindex="0">
1748          <?php
1749          if ( $override ) {
1750              /* translators: %s: User's display name. */
1751              printf( __( '%s is currently editing this post. Do you want to take over?' ), esc_html( $user->display_name ) );
1752          } else {
1753              /* translators: %s: User's display name. */
1754              printf( __( '%s is currently editing this post.' ), esc_html( $user->display_name ) );
1755          }
1756          ?>
1757          </p>
1758          <?php
1759          /**
1760           * Fires inside the post locked dialog before the buttons are displayed.
1761           *
1762           * @since 3.6.0
1763           * @since 5.4.0 The $user parameter was added.
1764           *
1765           * @param WP_Post $post Post object.
1766           * @param WP_User $user The user with the lock for the post.
1767           */
1768          do_action( 'post_locked_dialog', $post, $user );
1769          ?>
1770          <p>
1771          <a class="button" href="<?php echo esc_url( $sendback ); ?>"><?php echo $sendback_text; ?></a>
1772          <?php if ( $preview_link ) { ?>
1773          <a class="button<?php echo $tab_last; ?>" href="<?php echo esc_url( $preview_link ); ?>"><?php _e( 'Preview' ); ?></a>
1774              <?php
1775          }
1776  
1777          // Allow plugins to prevent some users overriding the post lock.
1778          if ( $override ) {
1779              ?>
1780      <a class="button button-primary wp-tab-last" href="<?php echo esc_url( add_query_arg( 'get-post-lock', '1', wp_nonce_url( get_edit_post_link( $post->ID, 'url' ), 'lock-post_' . $post->ID ) ) ); ?>"><?php _e( 'Take over' ); ?></a>
1781              <?php
1782          }
1783  
1784          ?>
1785          </p>
1786          </div>
1787          <?php
1788      } else {
1789          ?>
1790          <div class="post-taken-over">
1791              <div class="post-locked-avatar"></div>
1792              <p class="wp-tab-first" tabindex="0">
1793              <span class="currently-editing"></span><br />
1794              <span class="locked-saving hidden"><img src="<?php echo esc_url( admin_url( 'images/spinner-2x.gif' ) ); ?>" width="16" height="16" alt="" /> <?php _e( 'Saving revision&hellip;' ); ?></span>
1795              <span class="locked-saved hidden"><?php _e( 'Your latest changes were saved as a revision.' ); ?></span>
1796              </p>
1797              <?php
1798              /**
1799               * Fires inside the dialog displayed when a user has lost the post lock.
1800               *
1801               * @since 3.6.0
1802               *
1803               * @param WP_Post $post Post object.
1804               */
1805              do_action( 'post_lock_lost_dialog', $post );
1806              ?>
1807              <p><a class="button button-primary wp-tab-last" href="<?php echo esc_url( $sendback ); ?>"><?php echo $sendback_text; ?></a></p>
1808          </div>
1809          <?php
1810      }
1811  
1812      ?>
1813      </div>
1814      </div>
1815      <?php
1816  }
1817  
1818  /**
1819   * Creates autosave data for the specified post from $_POST data.
1820   *
1821   * @since 2.6.0
1822   *
1823   * @param array|int $post_data Associative array containing the post data or int post ID.
1824   * @return int|WP_Error The autosave revision ID. WP_Error or 0 on error.
1825   */
1826  function wp_create_post_autosave( $post_data ) {
1827      if ( is_numeric( $post_data ) ) {
1828          $post_id   = $post_data;
1829          $post_data = $_POST;
1830      } else {
1831          $post_id = (int) $post_data['post_ID'];
1832      }
1833  
1834      $post_data = _wp_translate_postdata( true, $post_data );
1835      if ( is_wp_error( $post_data ) ) {
1836          return $post_data;
1837      }
1838      $post_data = _wp_get_allowed_postdata( $post_data );
1839  
1840      $post_author = get_current_user_id();
1841  
1842      // Store one autosave per author. If there is already an autosave, overwrite it.
1843      $old_autosave = wp_get_post_autosave( $post_id, $post_author );
1844      if ( $old_autosave ) {
1845          $new_autosave                = _wp_post_revision_data( $post_data, true );
1846          $new_autosave['ID']          = $old_autosave->ID;
1847          $new_autosave['post_author'] = $post_author;
1848  
1849          $post = get_post( $post_id );
1850  
1851          // If the new autosave has the same content as the post, delete the autosave.
1852          $autosave_is_different = false;
1853          foreach ( array_intersect( array_keys( $new_autosave ), array_keys( _wp_post_revision_fields( $post ) ) ) as $field ) {
1854              if ( normalize_whitespace( $new_autosave[ $field ] ) !== normalize_whitespace( $post->$field ) ) {
1855                  $autosave_is_different = true;
1856                  break;
1857              }
1858          }
1859  
1860          if ( ! $autosave_is_different ) {
1861              wp_delete_post_revision( $old_autosave->ID );
1862              return 0;
1863          }
1864  
1865          /**
1866           * Fires before an autosave is stored.
1867           *
1868           * @since 4.1.0
1869           *
1870           * @param array $new_autosave Post array - the autosave that is about to be saved.
1871           */
1872          do_action( 'wp_creating_autosave', $new_autosave );
1873  
1874          return wp_update_post( $new_autosave );
1875      }
1876  
1877      // _wp_put_post_revision() expects unescaped.
1878      $post_data = wp_unslash( $post_data );
1879  
1880      // Otherwise create the new autosave as a special post revision.
1881      return _wp_put_post_revision( $post_data, true );
1882  }
1883  
1884  /**
1885   * Saves a draft or manually autosaves for the purpose of showing a post preview.
1886   *
1887   * @since 2.7.0
1888   *
1889   * @return string URL to redirect to show the preview.
1890   */
1891  function post_preview() {
1892  
1893      $post_ID     = (int) $_POST['post_ID'];
1894      $_POST['ID'] = $post_ID;
1895  
1896      $post = get_post( $post_ID );
1897      if ( ! $post ) {
1898          wp_die( __( 'Sorry, you are not allowed to edit this post.' ) );
1899      }
1900  
1901      if ( ! current_user_can( 'edit_post', $post->ID ) ) {
1902          wp_die( __( 'Sorry, you are not allowed to edit this post.' ) );
1903      }
1904  
1905      $is_autosave = false;
1906  
1907      if ( ! wp_check_post_lock( $post->ID ) && get_current_user_id() == $post->post_author
1908          && ( 'draft' === $post->post_status || 'auto-draft' === $post->post_status )
1909      ) {
1910          $saved_post_id = edit_post();
1911      } else {
1912          $is_autosave = true;
1913  
1914          if ( isset( $_POST['post_status'] ) && 'auto-draft' === $_POST['post_status'] ) {
1915              $_POST['post_status'] = 'draft';
1916          }
1917  
1918          $saved_post_id = wp_create_post_autosave( $post->ID );
1919      }
1920  
1921      if ( is_wp_error( $saved_post_id ) ) {
1922          wp_die( $saved_post_id->get_error_message() );
1923      }
1924  
1925      $query_args = array();
1926  
1927      if ( $is_autosave && $saved_post_id ) {
1928          $query_args['preview_id']    = $post->ID;
1929          $query_args['preview_nonce'] = wp_create_nonce( 'post_preview_' . $post->ID );
1930  
1931          if ( isset( $_POST['post_format'] ) ) {
1932              $query_args['post_format'] = empty( $_POST['post_format'] ) ? 'standard' : sanitize_key( $_POST['post_format'] );
1933          }
1934  
1935          if ( isset( $_POST['_thumbnail_id'] ) ) {
1936              $query_args['_thumbnail_id'] = ( (int) $_POST['_thumbnail_id'] <= 0 ) ? '-1' : (int) $_POST['_thumbnail_id'];
1937          }
1938      }
1939  
1940      return get_preview_post_link( $post, $query_args );
1941  }
1942  
1943  /**
1944   * Save a post submitted with XHR
1945   *
1946   * Intended for use with heartbeat and autosave.js
1947   *
1948   * @since 3.9.0
1949   *
1950   * @param array $post_data Associative array of the submitted post data.
1951   * @return mixed The value 0 or WP_Error on failure. The saved post ID on success.
1952   *               The ID can be the draft post_id or the autosave revision post_id.
1953   */
1954  function wp_autosave( $post_data ) {
1955      // Back-compat.
1956      if ( ! defined( 'DOING_AUTOSAVE' ) ) {
1957          define( 'DOING_AUTOSAVE', true );
1958      }
1959  
1960      $post_id              = (int) $post_data['post_id'];
1961      $post_data['ID']      = $post_id;
1962      $post_data['post_ID'] = $post_id;
1963  
1964      if ( false === wp_verify_nonce( $post_data['_wpnonce'], 'update-post_' . $post_id ) ) {
1965          return new WP_Error( 'invalid_nonce', __( 'Error while saving.' ) );
1966      }
1967  
1968      $post = get_post( $post_id );
1969  
1970      if ( ! current_user_can( 'edit_post', $post->ID ) ) {
1971          return new WP_Error( 'edit_posts', __( 'Sorry, you are not allowed to edit this item.' ) );
1972      }
1973  
1974      if ( 'auto-draft' === $post->post_status ) {
1975          $post_data['post_status'] = 'draft';
1976      }
1977  
1978      if ( 'page' !== $post_data['post_type'] && ! empty( $post_data['catslist'] ) ) {
1979          $post_data['post_category'] = explode( ',', $post_data['catslist'] );
1980      }
1981  
1982      if ( ! wp_check_post_lock( $post->ID ) && get_current_user_id() == $post->post_author
1983          && ( 'auto-draft' === $post->post_status || 'draft' === $post->post_status )
1984      ) {
1985          // Drafts and auto-drafts are just overwritten by autosave for the same user if the post is not locked.
1986          return edit_post( wp_slash( $post_data ) );
1987      } else {
1988          // Non-drafts or other users' drafts are not overwritten.
1989          // The autosave is stored in a special post revision for each user.
1990          return wp_create_post_autosave( wp_slash( $post_data ) );
1991      }
1992  }
1993  
1994  /**
1995   * Redirect to previous page.
1996   *
1997   * @since 2.7.0
1998   *
1999   * @param int $post_id Optional. Post ID.
2000   */
2001  function redirect_post( $post_id = '' ) {
2002      if ( isset( $_POST['save'] ) || isset( $_POST['publish'] ) ) {
2003          $status = get_post_status( $post_id );
2004  
2005          if ( isset( $_POST['publish'] ) ) {
2006              switch ( $status ) {
2007                  case 'pending':
2008                      $message = 8;
2009                      break;
2010                  case 'future':
2011                      $message = 9;
2012                      break;
2013                  default:
2014                      $message = 6;
2015              }
2016          } else {
2017              $message = 'draft' === $status ? 10 : 1;
2018          }
2019  
2020          $location = add_query_arg( 'message', $message, get_edit_post_link( $post_id, 'url' ) );
2021      } elseif ( isset( $_POST['addmeta'] ) && $_POST['addmeta'] ) {
2022          $location = add_query_arg( 'message', 2, wp_get_referer() );
2023          $location = explode( '#', $location );
2024          $location = $location[0] . '#postcustom';
2025      } elseif ( isset( $_POST['deletemeta'] ) && $_POST['deletemeta'] ) {
2026          $location = add_query_arg( 'message', 3, wp_get_referer() );
2027          $location = explode( '#', $location );
2028          $location = $location[0] . '#postcustom';
2029      } else {
2030          $location = add_query_arg( 'message', 4, get_edit_post_link( $post_id, 'url' ) );
2031      }
2032  
2033      /**
2034       * Filters the post redirect destination URL.
2035       *
2036       * @since 2.9.0
2037       *
2038       * @param string $location The destination URL.
2039       * @param int    $post_id  The post ID.
2040       */
2041      wp_redirect( apply_filters( 'redirect_post_location', $location, $post_id ) );
2042      exit;
2043  }
2044  
2045  /**
2046   * Sanitizes POST values from a checkbox taxonomy metabox.
2047   *
2048   * @since 5.1.0
2049   *
2050   * @param string $taxonomy The taxonomy name.
2051   * @param array  $terms    Raw term data from the 'tax_input' field.
2052   * @return int[] Array of sanitized term IDs.
2053   */
2054  function taxonomy_meta_box_sanitize_cb_checkboxes( $taxonomy, $terms ) {
2055      return array_map( 'intval', $terms );
2056  }
2057  
2058  /**
2059   * Sanitizes POST values from an input taxonomy metabox.
2060   *
2061   * @since 5.1.0
2062   *
2063   * @param string       $taxonomy The taxonomy name.
2064   * @param array|string $terms    Raw term data from the 'tax_input' field.
2065   * @return array
2066   */
2067  function taxonomy_meta_box_sanitize_cb_input( $taxonomy, $terms ) {
2068      /*
2069       * Assume that a 'tax_input' string is a comma-separated list of term names.
2070       * Some languages may use a character other than a comma as a delimiter, so we standardize on
2071       * commas before parsing the list.
2072       */
2073      if ( ! is_array( $terms ) ) {
2074          $comma = _x( ',', 'tag delimiter' );
2075          if ( ',' !== $comma ) {
2076              $terms = str_replace( $comma, ',', $terms );
2077          }
2078          $terms = explode( ',', trim( $terms, " \n\t\r\0\x0B," ) );
2079      }
2080  
2081      $clean_terms = array();
2082      foreach ( $terms as $term ) {
2083          // Empty terms are invalid input.
2084          if ( empty( $term ) ) {
2085              continue;
2086          }
2087  
2088          $_term = get_terms(
2089              array(
2090                  'taxonomy'   => $taxonomy,
2091                  'name'       => $term,
2092                  'fields'     => 'ids',
2093                  'hide_empty' => false,
2094              )
2095          );
2096  
2097          if ( ! empty( $_term ) ) {
2098              $clean_terms[] = (int) $_term[0];
2099          } else {
2100              // No existing term was found, so pass the string. A new term will be created.
2101              $clean_terms[] = $term;
2102          }
2103      }
2104  
2105      return $clean_terms;
2106  }
2107  
2108  /**
2109   * Return whether the post can be edited in the block editor.
2110   *
2111   * @since 5.0.0
2112   *
2113   * @param int|WP_Post $post Post ID or WP_Post object.
2114   * @return bool Whether the post can be edited in the block editor.
2115   */
2116  function use_block_editor_for_post( $post ) {
2117      $post = get_post( $post );
2118  
2119      if ( ! $post ) {
2120          return false;
2121      }
2122  
2123      // We're in the meta box loader, so don't use the block editor.
2124      if ( isset( $_GET['meta-box-loader'] ) ) {
2125          check_admin_referer( 'meta-box-loader', 'meta-box-loader-nonce' );
2126          return false;
2127      }
2128  
2129      // The posts page can't be edited in the block editor.
2130      if ( absint( get_option( 'page_for_posts' ) ) === $post->ID && empty( $post->post_content ) ) {
2131          return false;
2132      }
2133  
2134      $use_block_editor = use_block_editor_for_post_type( $post->post_type );
2135  
2136      /**
2137       * Filters whether a post is able to be edited in the block editor.
2138       *
2139       * @since 5.0.0
2140       *
2141       * @param bool    $use_block_editor Whether the post can be edited or not.
2142       * @param WP_Post $post             The post being checked.
2143       */
2144      return apply_filters( 'use_block_editor_for_post', $use_block_editor, $post );
2145  }
2146  
2147  /**
2148   * Return whether a post type is compatible with the block editor.
2149   *
2150   * The block editor depends on the REST API, and if the post type is not shown in the
2151   * REST API, then it won't work with the block editor.
2152   *
2153   * @since 5.0.0
2154   *
2155   * @param string $post_type The post type.
2156   * @return bool Whether the post type can be edited with the block editor.
2157   */
2158  function use_block_editor_for_post_type( $post_type ) {
2159      if ( ! post_type_exists( $post_type ) ) {
2160          return false;
2161      }
2162  
2163      if ( ! post_type_supports( $post_type, 'editor' ) ) {
2164          return false;
2165      }
2166  
2167      $post_type_object = get_post_type_object( $post_type );
2168      if ( $post_type_object && ! $post_type_object->show_in_rest ) {
2169          return false;
2170      }
2171  
2172      /**
2173       * Filters whether a post is able to be edited in the block editor.
2174       *
2175       * @since 5.0.0
2176       *
2177       * @param bool   $use_block_editor  Whether the post type can be edited or not. Default true.
2178       * @param string $post_type         The post type being checked.
2179       */
2180      return apply_filters( 'use_block_editor_for_post_type', true, $post_type );
2181  }
2182  
2183  /**
2184   * Prepares server-registered blocks for the block editor.
2185   *
2186   * Returns an associative array of registered block data keyed by block name. Data includes properties
2187   * of a block relevant for client registration.
2188   *
2189   * @since 5.0.0
2190   *
2191   * @return array An associative array of registered block data.
2192   */
2193  function get_block_editor_server_block_settings() {
2194      $block_registry = WP_Block_Type_Registry::get_instance();
2195      $blocks         = array();
2196      $fields_to_pick = array(
2197          'api_version'      => 'apiVersion',
2198          'title'            => 'title',
2199          'description'      => 'description',
2200          'icon'             => 'icon',
2201          'attributes'       => 'attributes',
2202          'provides_context' => 'providesContext',
2203          'uses_context'     => 'usesContext',
2204          'supports'         => 'supports',
2205          'category'         => 'category',
2206          'styles'           => 'styles',
2207          'textdomain'       => 'textdomain',
2208          'parent'           => 'parent',
2209          'keywords'         => 'keywords',
2210          'example'          => 'example',
2211          'variations'       => 'variations',
2212      );
2213  
2214      foreach ( $block_registry->get_all_registered() as $block_name => $block_type ) {
2215          foreach ( $fields_to_pick as $field => $key ) {
2216              if ( ! isset( $block_type->{ $field } ) ) {
2217                  continue;
2218              }
2219  
2220              if ( ! isset( $blocks[ $block_name ] ) ) {
2221                  $blocks[ $block_name ] = array();
2222              }
2223  
2224              $blocks[ $block_name ][ $key ] = $block_type->{ $field };
2225          }
2226      }
2227  
2228      return $blocks;
2229  }
2230  
2231  /**
2232   * Renders the meta boxes forms.
2233   *
2234   * @since 5.0.0
2235   */
2236  function the_block_editor_meta_boxes() {
2237      global $post, $current_screen, $wp_meta_boxes;
2238  
2239      // Handle meta box state.
2240      $_original_meta_boxes = $wp_meta_boxes;
2241  
2242      /**
2243       * Fires right before the meta boxes are rendered.
2244       *
2245       * This allows for the filtering of meta box data, that should already be
2246       * present by this point. Do not use as a means of adding meta box data.
2247       *
2248       * @since 5.0.0
2249       *
2250       * @param array $wp_meta_boxes Global meta box state.
2251       */
2252      $wp_meta_boxes = apply_filters( 'filter_block_editor_meta_boxes', $wp_meta_boxes );
2253      $locations     = array( 'side', 'normal', 'advanced' );
2254      $priorities    = array( 'high', 'sorted', 'core', 'default', 'low' );
2255  
2256      // Render meta boxes.
2257      ?>
2258      <form class="metabox-base-form">
2259      <?php the_block_editor_meta_box_post_form_hidden_fields( $post ); ?>
2260      </form>
2261      <form id="toggle-custom-fields-form" method="post" action="<?php echo esc_url( admin_url( 'post.php' ) ); ?>">
2262          <?php wp_nonce_field( 'toggle-custom-fields', 'toggle-custom-fields-nonce' ); ?>
2263          <input type="hidden" name="action" value="toggle-custom-fields" />
2264      </form>
2265      <?php foreach ( $locations as $location ) : ?>
2266          <form class="metabox-location-<?php echo esc_attr( $location ); ?>" onsubmit="return false;">
2267              <div id="poststuff" class="sidebar-open">
2268                  <div id="postbox-container-2" class="postbox-container">
2269                      <?php
2270                      do_meta_boxes(
2271                          $current_screen,
2272                          $location,
2273                          $post
2274                      );
2275                      ?>
2276                  </div>
2277              </div>
2278          </form>
2279      <?php endforeach; ?>
2280      <?php
2281  
2282      $meta_boxes_per_location = array();
2283      foreach ( $locations as $location ) {
2284          $meta_boxes_per_location[ $location ] = array();
2285  
2286          if ( ! isset( $wp_meta_boxes[ $current_screen->id ][ $location ] ) ) {
2287              continue;
2288          }
2289  
2290          foreach ( $priorities as $priority ) {
2291              if ( ! isset( $wp_meta_boxes[ $current_screen->id ][ $location ][ $priority ] ) ) {
2292                  continue;
2293              }
2294  
2295              $meta_boxes = (array) $wp_meta_boxes[ $current_screen->id ][ $location ][ $priority ];
2296              foreach ( $meta_boxes as $meta_box ) {
2297                  if ( false == $meta_box || ! $meta_box['title'] ) {
2298                      continue;
2299                  }
2300  
2301                  // If a meta box is just here for back compat, don't show it in the block editor.
2302                  if ( isset( $meta_box['args']['__back_compat_meta_box'] ) && $meta_box['args']['__back_compat_meta_box'] ) {
2303                      continue;
2304                  }
2305  
2306                  $meta_boxes_per_location[ $location ][] = array(
2307                      'id'    => $meta_box['id'],
2308                      'title' => $meta_box['title'],
2309                  );
2310              }
2311          }
2312      }
2313  
2314      /**
2315       * Sadly we probably can not add this data directly into editor settings.
2316       *
2317       * Some meta boxes need admin_head to fire for meta box registry.
2318       * admin_head fires after admin_enqueue_scripts, which is where we create our
2319       * editor instance.
2320       */
2321      $script = 'window._wpLoadBlockEditor.then( function() {
2322          wp.data.dispatch( \'core/edit-post\' ).setAvailableMetaBoxesPerLocation( ' . wp_json_encode( $meta_boxes_per_location ) . ' );
2323      } );';
2324  
2325      wp_add_inline_script( 'wp-edit-post', $script );
2326  
2327      /**
2328       * When `wp-edit-post` is output in the `<head>`, the inline script needs to be manually printed. Otherwise,
2329       * meta boxes will not display because inline scripts for `wp-edit-post` will not be printed again after this point.
2330       */
2331      if ( wp_script_is( 'wp-edit-post', 'done' ) ) {
2332          printf( "<script type='text/javascript'>\n%s\n</script>\n", trim( $script ) );
2333      }
2334  
2335      /**
2336       * If the 'postcustom' meta box is enabled, then we need to perform some
2337       * extra initialization on it.
2338       */
2339      $enable_custom_fields = (bool) get_user_meta( get_current_user_id(), 'enable_custom_fields', true );
2340      if ( $enable_custom_fields ) {
2341          $script = "( function( $ ) {
2342              if ( $('#postcustom').length ) {
2343                  $( '#the-list' ).wpList( {
2344                      addBefore: function( s ) {
2345                          s.data += '&post_id=$post->ID';
2346                          return s;
2347                      },
2348                      addAfter: function() {
2349                          $('table#list-table').show();
2350                      }
2351                  });
2352              }
2353          } )( jQuery );";
2354          wp_enqueue_script( 'wp-lists' );
2355          wp_add_inline_script( 'wp-lists', $script );
2356      }
2357  
2358      // Reset meta box data.
2359      $wp_meta_boxes = $_original_meta_boxes;
2360  }
2361  
2362  /**
2363   * Renders the hidden form required for the meta boxes form.
2364   *
2365   * @since 5.0.0
2366   *
2367   * @param WP_Post $post Current post object.
2368   */
2369  function the_block_editor_meta_box_post_form_hidden_fields( $post ) {
2370      $form_extra = '';
2371      if ( 'auto-draft' === $post->post_status ) {
2372          $form_extra .= "<input type='hidden' id='auto_draft' name='auto_draft' value='1' />";
2373      }
2374      $form_action  = 'editpost';
2375      $nonce_action = 'update-post_' . $post->ID;
2376      $form_extra  .= "<input type='hidden' id='post_ID' name='post_ID' value='" . esc_attr( $post->ID ) . "' />";
2377      $referer      = wp_get_referer();
2378      $current_user = wp_get_current_user();
2379      $user_id      = $current_user->ID;
2380      wp_nonce_field( $nonce_action );
2381  
2382      /*
2383       * Some meta boxes hook into these actions to add hidden input fields in the classic post form. For backwards
2384       * compatibility, we can capture the output from these actions, and extract the hidden input fields.
2385       */
2386      ob_start();
2387      /** This filter is documented in wp-admin/edit-form-advanced.php */
2388      do_action( 'edit_form_after_title', $post );
2389      /** This filter is documented in wp-admin/edit-form-advanced.php */
2390      do_action( 'edit_form_advanced', $post );
2391      $classic_output = ob_get_clean();
2392  
2393      $classic_elements = wp_html_split( $classic_output );
2394      $hidden_inputs    = '';
2395      foreach ( $classic_elements as $element ) {
2396          if ( 0 !== strpos( $element, '<input ' ) ) {
2397              continue;
2398          }
2399  
2400          if ( preg_match( '/\stype=[\'"]hidden[\'"]\s/', $element ) ) {
2401              echo $element;
2402          }
2403      }
2404      ?>
2405      <input type="hidden" id="user-id" name="user_ID" value="<?php echo (int) $user_id; ?>" />
2406      <input type="hidden" id="hiddenaction" name="action" value="<?php echo esc_attr( $form_action ); ?>" />
2407      <input type="hidden" id="originalaction" name="originalaction" value="<?php echo esc_attr( $form_action ); ?>" />
2408      <input type="hidden" id="post_type" name="post_type" value="<?php echo esc_attr( $post->post_type ); ?>" />
2409      <input type="hidden" id="original_post_status" name="original_post_status" value="<?php echo esc_attr( $post->post_status ); ?>" />
2410      <input type="hidden" id="referredby" name="referredby" value="<?php echo $referer ? esc_url( $referer ) : ''; ?>" />
2411  
2412      <?php
2413      if ( 'draft' !== get_post_status( $post ) ) {
2414          wp_original_referer_field( true, 'previous' );
2415      }
2416      echo $form_extra;
2417      wp_nonce_field( 'meta-box-order', 'meta-box-order-nonce', false );
2418      wp_nonce_field( 'closedpostboxes', 'closedpostboxesnonce', false );
2419      // Permalink title nonce.
2420      wp_nonce_field( 'samplepermalink', 'samplepermalinknonce', false );
2421  
2422      /**
2423       * Add hidden input fields to the meta box save form.
2424       *
2425       * Hook into this action to print `<input type="hidden" ... />` fields, which will be POSTed back to
2426       * the server when meta boxes are saved.
2427       *
2428       * @since 5.0.0
2429       *
2430       * @param WP_Post $post The post that is being edited.
2431       */
2432      do_action( 'block_editor_meta_box_hidden_fields', $post );
2433  }


Generated : Mon May 17 08:20:01 2021 Cross-referenced by PHPXref