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


Generated: Thu Sep 23 01:00:04 2021 Cross-referenced by PHPXref 0.7.1