[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

Search

title

Body

[close]

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

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


Generated : Wed Apr 8 08:20:02 2020 Cross-referenced by PHPXref