[ Index ]

WordPress 5.4.1

[ Index ]     [ Classes ]     [ Functions ]     [ Variables ]     [ Constants ]     [ Statistics ]    

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


Generated: Tue May 19 15:51:04 2020 Cross-referenced by PHPXref 0.7.1