[ Index ]

PHP Cross Reference of WordPress

title

Body

[close]

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

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


Generated: Wed Aug 12 01:00:03 2020 Cross-referenced by PHPXref 0.7.1