[ Index ]

PHP Cross Reference of WordPress

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


Generated: Sun May 31 01:00:03 2020 Cross-referenced by PHPXref 0.7.1