[ Index ]

PHP Cross Reference of WordPress

title

Body

[close]

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

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


Generated: Tue Nov 19 01:00:03 2019 Cross-referenced by PHPXref 0.7.1