[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

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


Generated: Mon Jun 17 08:20:02 2019 Cross-referenced by PHPXref 0.7