[ 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          if ( post_type_supports( $post_type, 'title' ) ) {
 684              $default_title = __( 'Auto Draft' );
 685          } else {
 686              $default_title = __( '(no title supported)' );
 687          }
 688  
 689          $post_id = wp_insert_post(
 690              array(
 691                  'post_title'  => $default_title,
 692                  'post_type'   => $post_type,
 693                  'post_status' => 'auto-draft',
 694              ),
 695              false,
 696              true
 697          );
 698          $post    = get_post( $post_id );
 699  
 700          if ( current_theme_supports( 'post-formats' )
 701              && post_type_supports( $post->post_type, 'post-formats' )
 702              && get_option( 'default_post_format' )
 703          ) {
 704              set_post_format( $post, get_option( 'default_post_format' ) );
 705          }
 706  
 707          wp_after_insert_post( $post, false );
 708  
 709          // Schedule auto-draft cleanup.
 710          if ( ! wp_next_scheduled( 'wp_scheduled_auto_draft_delete' ) ) {
 711              wp_schedule_event( time(), 'daily', 'wp_scheduled_auto_draft_delete' );
 712          }
 713      } else {
 714          $post                 = new stdClass;
 715          $post->ID             = 0;
 716          $post->post_author    = '';
 717          $post->post_date      = '';
 718          $post->post_date_gmt  = '';
 719          $post->post_password  = '';
 720          $post->post_name      = '';
 721          $post->post_type      = $post_type;
 722          $post->post_status    = 'draft';
 723          $post->to_ping        = '';
 724          $post->pinged         = '';
 725          $post->comment_status = get_default_comment_status( $post_type );
 726          $post->ping_status    = get_default_comment_status( $post_type, 'pingback' );
 727          $post->post_pingback  = get_option( 'default_pingback_flag' );
 728          $post->post_category  = get_option( 'default_category' );
 729          $post->page_template  = 'default';
 730          $post->post_parent    = 0;
 731          $post->menu_order     = 0;
 732          $post                 = new WP_Post( $post );
 733      }
 734  
 735      /**
 736       * Filters the default post content initially used in the "Write Post" form.
 737       *
 738       * @since 1.5.0
 739       *
 740       * @param string  $post_content Default post content.
 741       * @param WP_Post $post         Post object.
 742       */
 743      $post->post_content = (string) apply_filters( 'default_content', $post_content, $post );
 744  
 745      /**
 746       * Filters the default post title initially used in the "Write Post" form.
 747       *
 748       * @since 1.5.0
 749       *
 750       * @param string  $post_title Default post title.
 751       * @param WP_Post $post       Post object.
 752       */
 753      $post->post_title = (string) apply_filters( 'default_title', $post_title, $post );
 754  
 755      /**
 756       * Filters the default post excerpt initially used in the "Write Post" form.
 757       *
 758       * @since 1.5.0
 759       *
 760       * @param string  $post_excerpt Default post excerpt.
 761       * @param WP_Post $post         Post object.
 762       */
 763      $post->post_excerpt = (string) apply_filters( 'default_excerpt', $post_excerpt, $post );
 764  
 765      return $post;
 766  }
 767  
 768  /**
 769   * Determines if a post exists based on title, content, date and type.
 770   *
 771   * @since 2.0.0
 772   * @since 5.2.0 Added the `$type` parameter.
 773   *
 774   * @global wpdb $wpdb WordPress database abstraction object.
 775   *
 776   * @param string $title   Post title.
 777   * @param string $content Optional post content.
 778   * @param string $date    Optional post date.
 779   * @param string $type    Optional post type.
 780   * @return int Post ID if post exists, 0 otherwise.
 781   */
 782  function post_exists( $title, $content = '', $date = '', $type = '' ) {
 783      global $wpdb;
 784  
 785      $post_title   = wp_unslash( sanitize_post_field( 'post_title', $title, 0, 'db' ) );
 786      $post_content = wp_unslash( sanitize_post_field( 'post_content', $content, 0, 'db' ) );
 787      $post_date    = wp_unslash( sanitize_post_field( 'post_date', $date, 0, 'db' ) );
 788      $post_type    = wp_unslash( sanitize_post_field( 'post_type', $type, 0, 'db' ) );
 789  
 790      $query = "SELECT ID FROM $wpdb->posts WHERE 1=1";
 791      $args  = array();
 792  
 793      if ( ! empty( $date ) ) {
 794          $query .= ' AND post_date = %s';
 795          $args[] = $post_date;
 796      }
 797  
 798      if ( ! empty( $title ) ) {
 799          $query .= ' AND post_title = %s';
 800          $args[] = $post_title;
 801      }
 802  
 803      if ( ! empty( $content ) ) {
 804          $query .= ' AND post_content = %s';
 805          $args[] = $post_content;
 806      }
 807  
 808      if ( ! empty( $type ) ) {
 809          $query .= ' AND post_type = %s';
 810          $args[] = $post_type;
 811      }
 812  
 813      if ( ! empty( $args ) ) {
 814          return (int) $wpdb->get_var( $wpdb->prepare( $query, $args ) );
 815      }
 816  
 817      return 0;
 818  }
 819  
 820  /**
 821   * Creates a new post from the "Write Post" form using $_POST information.
 822   *
 823   * @since 2.1.0
 824   *
 825   * @global WP_User $current_user
 826   *
 827   * @return int|WP_Error
 828   */
 829  function wp_write_post() {
 830      if ( isset( $_POST['post_type'] ) ) {
 831          $ptype = get_post_type_object( $_POST['post_type'] );
 832      } else {
 833          $ptype = get_post_type_object( 'post' );
 834      }
 835  
 836      if ( ! current_user_can( $ptype->cap->edit_posts ) ) {
 837          if ( 'page' === $ptype->name ) {
 838              return new WP_Error( 'edit_pages', __( 'Sorry, you are not allowed to create pages on this site.' ) );
 839          } else {
 840              return new WP_Error( 'edit_posts', __( 'Sorry, you are not allowed to create posts or drafts on this site.' ) );
 841          }
 842      }
 843  
 844      $_POST['post_mime_type'] = '';
 845  
 846      // Clear out any data in internal vars.
 847      unset( $_POST['filter'] );
 848  
 849      // Edit, don't write, if we have a post ID.
 850      if ( isset( $_POST['post_ID'] ) ) {
 851          return edit_post();
 852      }
 853  
 854      if ( isset( $_POST['visibility'] ) ) {
 855          switch ( $_POST['visibility'] ) {
 856              case 'public':
 857                  $_POST['post_password'] = '';
 858                  break;
 859              case 'password':
 860                  unset( $_POST['sticky'] );
 861                  break;
 862              case 'private':
 863                  $_POST['post_status']   = 'private';
 864                  $_POST['post_password'] = '';
 865                  unset( $_POST['sticky'] );
 866                  break;
 867          }
 868      }
 869  
 870      $translated = _wp_translate_postdata( false );
 871      if ( is_wp_error( $translated ) ) {
 872          return $translated;
 873      }
 874      $translated = _wp_get_allowed_postdata( $translated );
 875  
 876      // Create the post.
 877      $post_ID = wp_insert_post( $translated );
 878      if ( is_wp_error( $post_ID ) ) {
 879          return $post_ID;
 880      }
 881  
 882      if ( empty( $post_ID ) ) {
 883          return 0;
 884      }
 885  
 886      add_meta( $post_ID );
 887  
 888      add_post_meta( $post_ID, '_edit_last', $GLOBALS['current_user']->ID );
 889  
 890      // Now that we have an ID we can fix any attachment anchor hrefs.
 891      _fix_attachment_links( $post_ID );
 892  
 893      wp_set_post_lock( $post_ID );
 894  
 895      return $post_ID;
 896  }
 897  
 898  /**
 899   * Calls wp_write_post() and handles the errors.
 900   *
 901   * @since 2.0.0
 902   *
 903   * @return int|null
 904   */
 905  function write_post() {
 906      $result = wp_write_post();
 907      if ( is_wp_error( $result ) ) {
 908          wp_die( $result->get_error_message() );
 909      } else {
 910          return $result;
 911      }
 912  }
 913  
 914  //
 915  // Post Meta.
 916  //
 917  
 918  /**
 919   * Add post meta data defined in $_POST superglobal for post with given ID.
 920   *
 921   * @since 1.2.0
 922   *
 923   * @param int $post_ID
 924   * @return int|bool
 925   */
 926  function add_meta( $post_ID ) {
 927      $post_ID = (int) $post_ID;
 928  
 929      $metakeyselect = isset( $_POST['metakeyselect'] ) ? wp_unslash( trim( $_POST['metakeyselect'] ) ) : '';
 930      $metakeyinput  = isset( $_POST['metakeyinput'] ) ? wp_unslash( trim( $_POST['metakeyinput'] ) ) : '';
 931      $metavalue     = isset( $_POST['metavalue'] ) ? $_POST['metavalue'] : '';
 932      if ( is_string( $metavalue ) ) {
 933          $metavalue = trim( $metavalue );
 934      }
 935  
 936      if ( ( ( '#NONE#' !== $metakeyselect ) && ! empty( $metakeyselect ) ) || ! empty( $metakeyinput ) ) {
 937          /*
 938           * We have a key/value pair. If both the select and the input
 939           * for the key have data, the input takes precedence.
 940           */
 941          if ( '#NONE#' !== $metakeyselect ) {
 942              $metakey = $metakeyselect;
 943          }
 944  
 945          if ( $metakeyinput ) {
 946              $metakey = $metakeyinput; // Default.
 947          }
 948  
 949          if ( is_protected_meta( $metakey, 'post' ) || ! current_user_can( 'add_post_meta', $post_ID, $metakey ) ) {
 950              return false;
 951          }
 952  
 953          $metakey = wp_slash( $metakey );
 954  
 955          return add_post_meta( $post_ID, $metakey, $metavalue );
 956      }
 957  
 958      return false;
 959  }
 960  
 961  /**
 962   * Delete post meta data by meta ID.
 963   *
 964   * @since 1.2.0
 965   *
 966   * @param int $mid
 967   * @return bool
 968   */
 969  function delete_meta( $mid ) {
 970      return delete_metadata_by_mid( 'post', $mid );
 971  }
 972  
 973  /**
 974   * Get a list of previously defined keys.
 975   *
 976   * @since 1.2.0
 977   *
 978   * @global wpdb $wpdb WordPress database abstraction object.
 979   *
 980   * @return mixed
 981   */
 982  function get_meta_keys() {
 983      global $wpdb;
 984  
 985      $keys = $wpdb->get_col(
 986          "
 987              SELECT meta_key
 988              FROM $wpdb->postmeta
 989              GROUP BY meta_key
 990              ORDER BY meta_key"
 991      );
 992  
 993      return $keys;
 994  }
 995  
 996  /**
 997   * Get post meta data by meta ID.
 998   *
 999   * @since 2.1.0
1000   *
1001   * @param int $mid
1002   * @return object|bool
1003   */
1004  function get_post_meta_by_id( $mid ) {
1005      return get_metadata_by_mid( 'post', $mid );
1006  }
1007  
1008  /**
1009   * Get meta data for the given post ID.
1010   *
1011   * @since 1.2.0
1012   *
1013   * @global wpdb $wpdb WordPress database abstraction object.
1014   *
1015   * @param int $postid
1016   * @return mixed
1017   */
1018  function has_meta( $postid ) {
1019      global $wpdb;
1020  
1021      return $wpdb->get_results(
1022          $wpdb->prepare(
1023              "SELECT meta_key, meta_value, meta_id, post_id
1024              FROM $wpdb->postmeta WHERE post_id = %d
1025              ORDER BY meta_key,meta_id",
1026              $postid
1027          ),
1028          ARRAY_A
1029      );
1030  }
1031  
1032  /**
1033   * Update post meta data by meta ID.
1034   *
1035   * @since 1.2.0
1036   *
1037   * @param int    $meta_id
1038   * @param string $meta_key Expect Slashed
1039   * @param string $meta_value Expect Slashed
1040   * @return bool
1041   */
1042  function update_meta( $meta_id, $meta_key, $meta_value ) {
1043      $meta_key   = wp_unslash( $meta_key );
1044      $meta_value = wp_unslash( $meta_value );
1045  
1046      return update_metadata_by_mid( 'post', $meta_id, $meta_value, $meta_key );
1047  }
1048  
1049  //
1050  // Private.
1051  //
1052  
1053  /**
1054   * Replace hrefs of attachment anchors with up-to-date permalinks.
1055   *
1056   * @since 2.3.0
1057   * @access private
1058   *
1059   * @param int|object $post Post ID or post object.
1060   * @return void|int|WP_Error Void if nothing fixed. 0 or WP_Error on update failure. The post ID on update success.
1061   */
1062  function _fix_attachment_links( $post ) {
1063      $post    = get_post( $post, ARRAY_A );
1064      $content = $post['post_content'];
1065  
1066      // Don't run if no pretty permalinks or post is not published, scheduled, or privately published.
1067      if ( ! get_option( 'permalink_structure' ) || ! in_array( $post['post_status'], array( 'publish', 'future', 'private' ), true ) ) {
1068          return;
1069      }
1070  
1071      // Short if there aren't any links or no '?attachment_id=' strings (strpos cannot be zero).
1072      if ( ! strpos( $content, '?attachment_id=' ) || ! preg_match_all( '/<a ([^>]+)>[\s\S]+?<\/a>/', $content, $link_matches ) ) {
1073          return;
1074      }
1075  
1076      $site_url = get_bloginfo( 'url' );
1077      $site_url = substr( $site_url, (int) strpos( $site_url, '://' ) ); // Remove the http(s).
1078      $replace  = '';
1079  
1080      foreach ( $link_matches[1] as $key => $value ) {
1081          if ( ! strpos( $value, '?attachment_id=' ) || ! strpos( $value, 'wp-att-' )
1082              || ! preg_match( '/href=(["\'])[^"\']*\?attachment_id=(\d+)[^"\']*\\1/', $value, $url_match )
1083              || ! preg_match( '/rel=["\'][^"\']*wp-att-(\d+)/', $value, $rel_match ) ) {
1084                  continue;
1085          }
1086  
1087          $quote  = $url_match[1]; // The quote (single or double).
1088          $url_id = (int) $url_match[2];
1089          $rel_id = (int) $rel_match[1];
1090  
1091          if ( ! $url_id || ! $rel_id || $url_id != $rel_id || strpos( $url_match[0], $site_url ) === false ) {
1092              continue;
1093          }
1094  
1095          $link    = $link_matches[0][ $key ];
1096          $replace = str_replace( $url_match[0], 'href=' . $quote . get_attachment_link( $url_id ) . $quote, $link );
1097  
1098          $content = str_replace( $link, $replace, $content );
1099      }
1100  
1101      if ( $replace ) {
1102          $post['post_content'] = $content;
1103          // Escape data pulled from DB.
1104          $post = add_magic_quotes( $post );
1105  
1106          return wp_update_post( $post );
1107      }
1108  }
1109  
1110  /**
1111   * Get all the possible statuses for a post_type
1112   *
1113   * @since 2.5.0
1114   *
1115   * @param string $type The post_type you want the statuses for. Default 'post'.
1116   * @return string[] An array of all the statuses for the supplied post type.
1117   */
1118  function get_available_post_statuses( $type = 'post' ) {
1119      $stati = wp_count_posts( $type );
1120  
1121      return array_keys( get_object_vars( $stati ) );
1122  }
1123  
1124  /**
1125   * Run the wp query to fetch the posts for listing on the edit posts page
1126   *
1127   * @since 2.5.0
1128   *
1129   * @param array|bool $q Array of query variables to use to build the query or false to use $_GET superglobal.
1130   * @return array
1131   */
1132  function wp_edit_posts_query( $q = false ) {
1133      if ( false === $q ) {
1134          $q = $_GET;
1135      }
1136      $q['m']     = isset( $q['m'] ) ? (int) $q['m'] : 0;
1137      $q['cat']   = isset( $q['cat'] ) ? (int) $q['cat'] : 0;
1138      $post_stati = get_post_stati();
1139  
1140      if ( isset( $q['post_type'] ) && in_array( $q['post_type'], get_post_types(), true ) ) {
1141          $post_type = $q['post_type'];
1142      } else {
1143          $post_type = 'post';
1144      }
1145  
1146      $avail_post_stati = get_available_post_statuses( $post_type );
1147      $post_status      = '';
1148      $perm             = '';
1149  
1150      if ( isset( $q['post_status'] ) && in_array( $q['post_status'], $post_stati, true ) ) {
1151          $post_status = $q['post_status'];
1152          $perm        = 'readable';
1153      }
1154  
1155      $orderby = '';
1156  
1157      if ( isset( $q['orderby'] ) ) {
1158          $orderby = $q['orderby'];
1159      } elseif ( isset( $q['post_status'] ) && in_array( $q['post_status'], array( 'pending', 'draft' ), true ) ) {
1160          $orderby = 'modified';
1161      }
1162  
1163      $order = '';
1164  
1165      if ( isset( $q['order'] ) ) {
1166          $order = $q['order'];
1167      } elseif ( isset( $q['post_status'] ) && 'pending' === $q['post_status'] ) {
1168          $order = 'ASC';
1169      }
1170  
1171      $per_page       = "edit_{$post_type}_per_page";
1172      $posts_per_page = (int) get_user_option( $per_page );
1173      if ( empty( $posts_per_page ) || $posts_per_page < 1 ) {
1174          $posts_per_page = 20;
1175      }
1176  
1177      /**
1178       * Filters the number of items per page to show for a specific 'per_page' type.
1179       *
1180       * The dynamic portion of the hook name, `$post_type`, refers to the post type.
1181       *
1182       * Some examples of filter hooks generated here include: 'edit_attachment_per_page',
1183       * 'edit_post_per_page', 'edit_page_per_page', etc.
1184       *
1185       * @since 3.0.0
1186       *
1187       * @param int $posts_per_page Number of posts to display per page for the given post
1188       *                            type. Default 20.
1189       */
1190      $posts_per_page = apply_filters( "edit_{$post_type}_per_page", $posts_per_page );
1191  
1192      /**
1193       * Filters the number of posts displayed per page when specifically listing "posts".
1194       *
1195       * @since 2.8.0
1196       *
1197       * @param int    $posts_per_page Number of posts to be displayed. Default 20.
1198       * @param string $post_type      The post type.
1199       */
1200      $posts_per_page = apply_filters( 'edit_posts_per_page', $posts_per_page, $post_type );
1201  
1202      $query = compact( 'post_type', 'post_status', 'perm', 'order', 'orderby', 'posts_per_page' );
1203  
1204      // Hierarchical types require special args.
1205      if ( is_post_type_hierarchical( $post_type ) && empty( $orderby ) ) {
1206          $query['orderby']                = 'menu_order title';
1207          $query['order']                  = 'asc';
1208          $query['posts_per_page']         = -1;
1209          $query['posts_per_archive_page'] = -1;
1210          $query['fields']                 = 'id=>parent';
1211      }
1212  
1213      if ( ! empty( $q['show_sticky'] ) ) {
1214          $query['post__in'] = (array) get_option( 'sticky_posts' );
1215      }
1216  
1217      wp( $query );
1218  
1219      return $avail_post_stati;
1220  }
1221  
1222  /**
1223   * Get the query variables for the current attachments request.
1224   *
1225   * @since 4.2.0
1226   *
1227   * @param array|false $q Optional. Array of query variables to use to build the query or false
1228   *                       to use $_GET superglobal. Default false.
1229   * @return array The parsed query vars.
1230   */
1231  function wp_edit_attachments_query_vars( $q = false ) {
1232      if ( false === $q ) {
1233          $q = $_GET;
1234      }
1235      $q['m']         = isset( $q['m'] ) ? (int) $q['m'] : 0;
1236      $q['cat']       = isset( $q['cat'] ) ? (int) $q['cat'] : 0;
1237      $q['post_type'] = 'attachment';
1238      $post_type      = get_post_type_object( 'attachment' );
1239      $states         = 'inherit';
1240      if ( current_user_can( $post_type->cap->read_private_posts ) ) {
1241          $states .= ',private';
1242      }
1243  
1244      $q['post_status'] = isset( $q['status'] ) && 'trash' === $q['status'] ? 'trash' : $states;
1245      $q['post_status'] = isset( $q['attachment-filter'] ) && 'trash' === $q['attachment-filter'] ? 'trash' : $states;
1246  
1247      $media_per_page = (int) get_user_option( 'upload_per_page' );
1248      if ( empty( $media_per_page ) || $media_per_page < 1 ) {
1249          $media_per_page = 20;
1250      }
1251  
1252      /**
1253       * Filters the number of items to list per page when listing media items.
1254       *
1255       * @since 2.9.0
1256       *
1257       * @param int $media_per_page Number of media to list. Default 20.
1258       */
1259      $q['posts_per_page'] = apply_filters( 'upload_per_page', $media_per_page );
1260  
1261      $post_mime_types = get_post_mime_types();
1262      if ( isset( $q['post_mime_type'] ) && ! array_intersect( (array) $q['post_mime_type'], array_keys( $post_mime_types ) ) ) {
1263          unset( $q['post_mime_type'] );
1264      }
1265  
1266      foreach ( array_keys( $post_mime_types ) as $type ) {
1267          if ( isset( $q['attachment-filter'] ) && "post_mime_type:$type" === $q['attachment-filter'] ) {
1268              $q['post_mime_type'] = $type;
1269              break;
1270          }
1271      }
1272  
1273      if ( isset( $q['detached'] ) || ( isset( $q['attachment-filter'] ) && 'detached' === $q['attachment-filter'] ) ) {
1274          $q['post_parent'] = 0;
1275      }
1276  
1277      if ( isset( $q['mine'] ) || ( isset( $q['attachment-filter'] ) && 'mine' === $q['attachment-filter'] ) ) {
1278          $q['author'] = get_current_user_id();
1279      }
1280  
1281      // Filter query clauses to include filenames.
1282      if ( isset( $q['s'] ) ) {
1283          add_filter( 'posts_clauses', '_filter_query_attachment_filenames' );
1284      }
1285  
1286      return $q;
1287  }
1288  
1289  /**
1290   * Executes a query for attachments. An array of WP_Query arguments
1291   * can be passed in, which will override the arguments set by this function.
1292   *
1293   * @since 2.5.0
1294   *
1295   * @param array|false $q Array of query variables to use to build the query or false to use $_GET superglobal.
1296   * @return array
1297   */
1298  function wp_edit_attachments_query( $q = false ) {
1299      wp( wp_edit_attachments_query_vars( $q ) );
1300  
1301      $post_mime_types       = get_post_mime_types();
1302      $avail_post_mime_types = get_available_post_mime_types( 'attachment' );
1303  
1304      return array( $post_mime_types, $avail_post_mime_types );
1305  }
1306  
1307  /**
1308   * Returns the list of classes to be used by a meta box.
1309   *
1310   * @since 2.5.0
1311   *
1312   * @param string $box_id    Meta box ID (used in the 'id' attribute for the meta box).
1313   * @param string $screen_id The screen on which the meta box is shown.
1314   * @return string Space-separated string of class names.
1315   */
1316  function postbox_classes( $box_id, $screen_id ) {
1317      if ( isset( $_GET['edit'] ) && $_GET['edit'] == $box_id ) {
1318          $classes = array( '' );
1319      } elseif ( get_user_option( 'closedpostboxes_' . $screen_id ) ) {
1320          $closed = get_user_option( 'closedpostboxes_' . $screen_id );
1321          if ( ! is_array( $closed ) ) {
1322              $classes = array( '' );
1323          } else {
1324              $classes = in_array( $box_id, $closed, true ) ? array( 'closed' ) : array( '' );
1325          }
1326      } else {
1327          $classes = array( '' );
1328      }
1329  
1330      /**
1331       * Filters the postbox classes for a specific screen and box ID combo.
1332       *
1333       * The dynamic portions of the hook name, `$screen_id` and `$box_id`, refer to
1334       * the screen ID and meta box ID, respectively.
1335       *
1336       * @since 3.2.0
1337       *
1338       * @param string[] $classes An array of postbox classes.
1339       */
1340      $classes = apply_filters( "postbox_classes_{$screen_id}_{$box_id}", $classes );
1341      return implode( ' ', $classes );
1342  }
1343  
1344  /**
1345   * Get a sample permalink based off of the post name.
1346   *
1347   * @since 2.5.0
1348   *
1349   * @param int    $id    Post ID or post object.
1350   * @param string $title Optional. Title to override the post's current title when generating the post name. Default null.
1351   * @param string $name  Optional. Name to override the post name. Default null.
1352   * @return array {
1353   *     Array containing the sample permalink with placeholder for the post name, and the post name.
1354   *
1355   *     @type string $0 The permalink with placeholder for the post name.
1356   *     @type string $1 The post name.
1357   * }
1358   */
1359  function get_sample_permalink( $id, $title = null, $name = null ) {
1360      $post = get_post( $id );
1361      if ( ! $post ) {
1362          return array( '', '' );
1363      }
1364  
1365      $ptype = get_post_type_object( $post->post_type );
1366  
1367      $original_status = $post->post_status;
1368      $original_date   = $post->post_date;
1369      $original_name   = $post->post_name;
1370  
1371      // Hack: get_permalink() would return ugly permalink for drafts, so we will fake that our post is published.
1372      if ( in_array( $post->post_status, array( 'draft', 'pending', 'future' ), true ) ) {
1373          $post->post_status = 'publish';
1374          $post->post_name   = sanitize_title( $post->post_name ? $post->post_name : $post->post_title, $post->ID );
1375      }
1376  
1377      // If the user wants to set a new name -- override the current one.
1378      // Note: if empty name is supplied -- use the title instead, see #6072.
1379      if ( ! is_null( $name ) ) {
1380          $post->post_name = sanitize_title( $name ? $name : $title, $post->ID );
1381      }
1382  
1383      $post->post_name = wp_unique_post_slug( $post->post_name, $post->ID, $post->post_status, $post->post_type, $post->post_parent );
1384  
1385      $post->filter = 'sample';
1386  
1387      $permalink = get_permalink( $post, true );
1388  
1389      // Replace custom post_type token with generic pagename token for ease of use.
1390      $permalink = str_replace( "%$post->post_type%", '%pagename%', $permalink );
1391  
1392      // Handle page hierarchy.
1393      if ( $ptype->hierarchical ) {
1394          $uri = get_page_uri( $post );
1395          if ( $uri ) {
1396              $uri = untrailingslashit( $uri );
1397              $uri = strrev( stristr( strrev( $uri ), '/' ) );
1398              $uri = untrailingslashit( $uri );
1399          }
1400  
1401          /** This filter is documented in wp-admin/edit-tag-form.php */
1402          $uri = apply_filters( 'editable_slug', $uri, $post );
1403          if ( ! empty( $uri ) ) {
1404              $uri .= '/';
1405          }
1406          $permalink = str_replace( '%pagename%', "{$uri}%pagename%", $permalink );
1407      }
1408  
1409      /** This filter is documented in wp-admin/edit-tag-form.php */
1410      $permalink         = array( $permalink, apply_filters( 'editable_slug', $post->post_name, $post ) );
1411      $post->post_status = $original_status;
1412      $post->post_date   = $original_date;
1413      $post->post_name   = $original_name;
1414      unset( $post->filter );
1415  
1416      /**
1417       * Filters the sample permalink.
1418       *
1419       * @since 4.4.0
1420       *
1421       * @param array   $permalink {
1422       *     Array containing the sample permalink with placeholder for the post name, and the post name.
1423       *
1424       *     @type string $0 The permalink with placeholder for the post name.
1425       *     @type string $1 The post name.
1426       * }
1427       * @param int     $post_id   Post ID.
1428       * @param string  $title     Post title.
1429       * @param string  $name      Post name (slug).
1430       * @param WP_Post $post      Post object.
1431       */
1432      return apply_filters( 'get_sample_permalink', $permalink, $post->ID, $title, $name, $post );
1433  }
1434  
1435  /**
1436   * Returns the HTML of the sample permalink slug editor.
1437   *
1438   * @since 2.5.0
1439   *
1440   * @param int    $id        Post ID or post object.
1441   * @param string $new_title Optional. New title. Default null.
1442   * @param string $new_slug  Optional. New slug. Default null.
1443   * @return string The HTML of the sample permalink slug editor.
1444   */
1445  function get_sample_permalink_html( $id, $new_title = null, $new_slug = null ) {
1446      $post = get_post( $id );
1447      if ( ! $post ) {
1448          return '';
1449      }
1450  
1451      list($permalink, $post_name) = get_sample_permalink( $post->ID, $new_title, $new_slug );
1452  
1453      $view_link      = false;
1454      $preview_target = '';
1455  
1456      if ( current_user_can( 'read_post', $post->ID ) ) {
1457          if ( 'draft' === $post->post_status || empty( $post->post_name ) ) {
1458              $view_link      = get_preview_post_link( $post );
1459              $preview_target = " target='wp-preview-{$post->ID}'";
1460          } else {
1461              if ( 'publish' === $post->post_status || 'attachment' === $post->post_type ) {
1462                  $view_link = get_permalink( $post );
1463              } else {
1464                  // Allow non-published (private, future) to be viewed at a pretty permalink, in case $post->post_name is set.
1465                  $view_link = str_replace( array( '%pagename%', '%postname%' ), $post->post_name, $permalink );
1466              }
1467          }
1468      }
1469  
1470      // Permalinks without a post/page name placeholder don't have anything to edit.
1471      if ( false === strpos( $permalink, '%postname%' ) && false === strpos( $permalink, '%pagename%' ) ) {
1472          $return = '<strong>' . __( 'Permalink:' ) . "</strong>\n";
1473  
1474          if ( false !== $view_link ) {
1475              $display_link = urldecode( $view_link );
1476              $return      .= '<a id="sample-permalink" href="' . esc_url( $view_link ) . '"' . $preview_target . '>' . esc_html( $display_link ) . "</a>\n";
1477          } else {
1478              $return .= '<span id="sample-permalink">' . $permalink . "</span>\n";
1479          }
1480  
1481          // Encourage a pretty permalink setting.
1482          if ( ! get_option( 'permalink_structure' ) && current_user_can( 'manage_options' )
1483              && ! ( 'page' === get_option( 'show_on_front' ) && get_option( 'page_on_front' ) == $id )
1484          ) {
1485              $return .= '<span id="change-permalinks"><a href="options-permalink.php" class="button button-small" target="_blank">' . __( 'Change Permalinks' ) . "</a></span>\n";
1486          }
1487      } else {
1488          if ( mb_strlen( $post_name ) > 34 ) {
1489              $post_name_abridged = mb_substr( $post_name, 0, 16 ) . '&hellip;' . mb_substr( $post_name, -16 );
1490          } else {
1491              $post_name_abridged = $post_name;
1492          }
1493  
1494          $post_name_html = '<span id="editable-post-name">' . esc_html( $post_name_abridged ) . '</span>';
1495          $display_link   = str_replace( array( '%pagename%', '%postname%' ), $post_name_html, esc_html( urldecode( $permalink ) ) );
1496  
1497          $return  = '<strong>' . __( 'Permalink:' ) . "</strong>\n";
1498          $return .= '<span id="sample-permalink"><a href="' . esc_url( $view_link ) . '"' . $preview_target . '>' . $display_link . "</a></span>\n";
1499          $return .= '&lrm;'; // Fix bi-directional text display defect in RTL languages.
1500          $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";
1501          $return .= '<span id="editable-post-name-full">' . esc_html( $post_name ) . "</span>\n";
1502      }
1503  
1504      /**
1505       * Filters the sample permalink HTML markup.
1506       *
1507       * @since 2.9.0
1508       * @since 4.4.0 Added `$post` parameter.
1509       *
1510       * @param string  $return    Sample permalink HTML markup.
1511       * @param int     $post_id   Post ID.
1512       * @param string  $new_title New sample permalink title.
1513       * @param string  $new_slug  New sample permalink slug.
1514       * @param WP_Post $post      Post object.
1515       */
1516      $return = apply_filters( 'get_sample_permalink_html', $return, $post->ID, $new_title, $new_slug, $post );
1517  
1518      return $return;
1519  }
1520  
1521  /**
1522   * Returns HTML for the post thumbnail meta box.
1523   *
1524   * @since 2.9.0
1525   *
1526   * @param int         $thumbnail_id ID of the attachment used for thumbnail
1527   * @param int|WP_Post $post         Optional. The post ID or object associated with the thumbnail, defaults to global $post.
1528   * @return string The post thumbnail HTML.
1529   */
1530  function _wp_post_thumbnail_html( $thumbnail_id = null, $post = null ) {
1531      $_wp_additional_image_sizes = wp_get_additional_image_sizes();
1532  
1533      $post               = get_post( $post );
1534      $post_type_object   = get_post_type_object( $post->post_type );
1535      $set_thumbnail_link = '<p class="hide-if-no-js"><a href="%s" id="set-post-thumbnail"%s class="thickbox">%s</a></p>';
1536      $upload_iframe_src  = get_upload_iframe_src( 'image', $post->ID );
1537  
1538      $content = sprintf(
1539          $set_thumbnail_link,
1540          esc_url( $upload_iframe_src ),
1541          '', // Empty when there's no featured image set, `aria-describedby` attribute otherwise.
1542          esc_html( $post_type_object->labels->set_featured_image )
1543      );
1544  
1545      if ( $thumbnail_id && get_post( $thumbnail_id ) ) {
1546          $size = isset( $_wp_additional_image_sizes['post-thumbnail'] ) ? 'post-thumbnail' : array( 266, 266 );
1547  
1548          /**
1549           * Filters the size used to display the post thumbnail image in the 'Featured image' meta box.
1550           *
1551           * Note: When a theme adds 'post-thumbnail' support, a special 'post-thumbnail'
1552           * image size is registered, which differs from the 'thumbnail' image size
1553           * managed via the Settings > Media screen.
1554           *
1555           * @since 4.4.0
1556           *
1557           * @param string|int[] $size         Requested image size. Can be any registered image size name, or
1558           *                                   an array of width and height values in pixels (in that order).
1559           * @param int          $thumbnail_id Post thumbnail attachment ID.
1560           * @param WP_Post      $post         The post object associated with the thumbnail.
1561           */
1562          $size = apply_filters( 'admin_post_thumbnail_size', $size, $thumbnail_id, $post );
1563  
1564          $thumbnail_html = wp_get_attachment_image( $thumbnail_id, $size );
1565  
1566          if ( ! empty( $thumbnail_html ) ) {
1567              $content  = sprintf(
1568                  $set_thumbnail_link,
1569                  esc_url( $upload_iframe_src ),
1570                  ' aria-describedby="set-post-thumbnail-desc"',
1571                  $thumbnail_html
1572              );
1573              $content .= '<p class="hide-if-no-js howto" id="set-post-thumbnail-desc">' . __( 'Click the image to edit or update' ) . '</p>';
1574              $content .= '<p class="hide-if-no-js"><a href="#" id="remove-post-thumbnail">' . esc_html( $post_type_object->labels->remove_featured_image ) . '</a></p>';
1575          }
1576      }
1577  
1578      $content .= '<input type="hidden" id="_thumbnail_id" name="_thumbnail_id" value="' . esc_attr( $thumbnail_id ? $thumbnail_id : '-1' ) . '" />';
1579  
1580      /**
1581       * Filters the admin post thumbnail HTML markup to return.
1582       *
1583       * @since 2.9.0
1584       * @since 3.5.0 Added the `$post_id` parameter.
1585       * @since 4.6.0 Added the `$thumbnail_id` parameter.
1586       *
1587       * @param string   $content      Admin post thumbnail HTML markup.
1588       * @param int      $post_id      Post ID.
1589       * @param int|null $thumbnail_id Thumbnail attachment ID, or null if there isn't one.
1590       */
1591      return apply_filters( 'admin_post_thumbnail_html', $content, $post->ID, $thumbnail_id );
1592  }
1593  
1594  /**
1595   * Check to see if the post is currently being edited by another user.
1596   *
1597   * @since 2.5.0
1598   *
1599   * @param int $post_id ID of the post to check for editing.
1600   * @return int|false ID of the user with lock. False if the post does not exist, post is not locked,
1601   *                   the user with lock does not exist, or the post is locked by current user.
1602   */
1603  function wp_check_post_lock( $post_id ) {
1604      $post = get_post( $post_id );
1605      if ( ! $post ) {
1606          return false;
1607      }
1608  
1609      $lock = get_post_meta( $post->ID, '_edit_lock', true );
1610      if ( ! $lock ) {
1611          return false;
1612      }
1613  
1614      $lock = explode( ':', $lock );
1615      $time = $lock[0];
1616      $user = isset( $lock[1] ) ? $lock[1] : get_post_meta( $post->ID, '_edit_last', true );
1617  
1618      if ( ! get_userdata( $user ) ) {
1619          return false;
1620      }
1621  
1622      /** This filter is documented in wp-admin/includes/ajax-actions.php */
1623      $time_window = apply_filters( 'wp_check_post_lock_window', 150 );
1624  
1625      if ( $time && $time > time() - $time_window && get_current_user_id() != $user ) {
1626          return $user;
1627      }
1628  
1629      return false;
1630  }
1631  
1632  /**
1633   * Mark the post as currently being edited by the current user
1634   *
1635   * @since 2.5.0
1636   *
1637   * @param int $post_id ID of the post being edited.
1638   * @return array|false Array of the lock time and user ID. False if the post does not exist, or
1639   *                     there is no current user.
1640   */
1641  function wp_set_post_lock( $post_id ) {
1642      $post = get_post( $post_id );
1643      if ( ! $post ) {
1644          return false;
1645      }
1646  
1647      $user_id = get_current_user_id();
1648      if ( 0 == $user_id ) {
1649          return false;
1650      }
1651  
1652      $now  = time();
1653      $lock = "$now:$user_id";
1654  
1655      update_post_meta( $post->ID, '_edit_lock', $lock );
1656  
1657      return array( $now, $user_id );
1658  }
1659  
1660  /**
1661   * Outputs the HTML for the notice to say that someone else is editing or has taken over editing of this post.
1662   *
1663   * @since 2.8.5
1664   */
1665  function _admin_notice_post_locked() {
1666      $post = get_post();
1667      if ( ! $post ) {
1668          return;
1669      }
1670  
1671      $user    = null;
1672      $user_id = wp_check_post_lock( $post->ID );
1673      if ( $user_id ) {
1674          $user = get_userdata( $user_id );
1675      }
1676  
1677      if ( $user ) {
1678          /**
1679           * Filters whether to show the post locked dialog.
1680           *
1681           * Returning false from the filter will prevent the dialog from being displayed.
1682           *
1683           * @since 3.6.0
1684           *
1685           * @param bool    $display Whether to display the dialog. Default true.
1686           * @param WP_Post $post    Post object.
1687           * @param WP_User $user    The user with the lock for the post.
1688           */
1689          if ( ! apply_filters( 'show_post_locked_dialog', true, $post, $user ) ) {
1690              return;
1691          }
1692  
1693          $locked = true;
1694      } else {
1695          $locked = false;
1696      }
1697  
1698      $sendback = wp_get_referer();
1699      if ( $locked && $sendback && false === strpos( $sendback, 'post.php' ) && false === strpos( $sendback, 'post-new.php' ) ) {
1700  
1701          $sendback_text = __( 'Go back' );
1702      } else {
1703          $sendback = admin_url( 'edit.php' );
1704  
1705          if ( 'post' !== $post->post_type ) {
1706              $sendback = add_query_arg( 'post_type', $post->post_type, $sendback );
1707          }
1708  
1709          $sendback_text = get_post_type_object( $post->post_type )->labels->all_items;
1710      }
1711  
1712      $hidden = $locked ? '' : ' hidden';
1713  
1714      ?>
1715      <div id="post-lock-dialog" class="notification-dialog-wrap<?php echo $hidden; ?>">
1716      <div class="notification-dialog-background"></div>
1717      <div class="notification-dialog">
1718      <?php
1719  
1720      if ( $locked ) {
1721          $query_args = array();
1722          if ( get_post_type_object( $post->post_type )->public ) {
1723              if ( 'publish' === $post->post_status || $user->ID != $post->post_author ) {
1724                  // Latest content is in autosave.
1725                  $nonce                       = wp_create_nonce( 'post_preview_' . $post->ID );
1726                  $query_args['preview_id']    = $post->ID;
1727                  $query_args['preview_nonce'] = $nonce;
1728              }
1729          }
1730  
1731          $preview_link = get_preview_post_link( $post->ID, $query_args );
1732  
1733          /**
1734           * Filters whether to allow the post lock to be overridden.
1735           *
1736           * Returning false from the filter will disable the ability
1737           * to override the post lock.
1738           *
1739           * @since 3.6.0
1740           *
1741           * @param bool    $override Whether to allow the post lock to be overridden. Default true.
1742           * @param WP_Post $post     Post object.
1743           * @param WP_User $user     The user with the lock for the post.
1744           */
1745          $override = apply_filters( 'override_post_lock', true, $post, $user );
1746          $tab_last = $override ? '' : ' wp-tab-last';
1747  
1748          ?>
1749          <div class="post-locked-message">
1750          <div class="post-locked-avatar"><?php echo get_avatar( $user->ID, 64 ); ?></div>
1751          <p class="currently-editing wp-tab-first" tabindex="0">
1752          <?php
1753          if ( $override ) {
1754              /* translators: %s: User's display name. */
1755              printf( __( '%s is currently editing this post. Do you want to take over?' ), esc_html( $user->display_name ) );
1756          } else {
1757              /* translators: %s: User's display name. */
1758              printf( __( '%s is currently editing this post.' ), esc_html( $user->display_name ) );
1759          }
1760          ?>
1761          </p>
1762          <?php
1763          /**
1764           * Fires inside the post locked dialog before the buttons are displayed.
1765           *
1766           * @since 3.6.0
1767           * @since 5.4.0 The $user parameter was added.
1768           *
1769           * @param WP_Post $post Post object.
1770           * @param WP_User $user The user with the lock for the post.
1771           */
1772          do_action( 'post_locked_dialog', $post, $user );
1773          ?>
1774          <p>
1775          <a class="button" href="<?php echo esc_url( $sendback ); ?>"><?php echo $sendback_text; ?></a>
1776          <?php if ( $preview_link ) { ?>
1777          <a class="button<?php echo $tab_last; ?>" href="<?php echo esc_url( $preview_link ); ?>"><?php _e( 'Preview' ); ?></a>
1778              <?php
1779          }
1780  
1781          // Allow plugins to prevent some users overriding the post lock.
1782          if ( $override ) {
1783              ?>
1784      <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>
1785              <?php
1786          }
1787  
1788          ?>
1789          </p>
1790          </div>
1791          <?php
1792      } else {
1793          ?>
1794          <div class="post-taken-over">
1795              <div class="post-locked-avatar"></div>
1796              <p class="wp-tab-first" tabindex="0">
1797              <span class="currently-editing"></span><br />
1798              <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>
1799              <span class="locked-saved hidden"><?php _e( 'Your latest changes were saved as a revision.' ); ?></span>
1800              </p>
1801              <?php
1802              /**
1803               * Fires inside the dialog displayed when a user has lost the post lock.
1804               *
1805               * @since 3.6.0
1806               *
1807               * @param WP_Post $post Post object.
1808               */
1809              do_action( 'post_lock_lost_dialog', $post );
1810              ?>
1811              <p><a class="button button-primary wp-tab-last" href="<?php echo esc_url( $sendback ); ?>"><?php echo $sendback_text; ?></a></p>
1812          </div>
1813          <?php
1814      }
1815  
1816      ?>
1817      </div>
1818      </div>
1819      <?php
1820  }
1821  
1822  /**
1823   * Creates autosave data for the specified post from $_POST data.
1824   *
1825   * @since 2.6.0
1826   *
1827   * @param array|int $post_data Associative array containing the post data or int post ID.
1828   * @return int|WP_Error The autosave revision ID. WP_Error or 0 on error.
1829   */
1830  function wp_create_post_autosave( $post_data ) {
1831      if ( is_numeric( $post_data ) ) {
1832          $post_id   = $post_data;
1833          $post_data = $_POST;
1834      } else {
1835          $post_id = (int) $post_data['post_ID'];
1836      }
1837  
1838      $post_data = _wp_translate_postdata( true, $post_data );
1839      if ( is_wp_error( $post_data ) ) {
1840          return $post_data;
1841      }
1842      $post_data = _wp_get_allowed_postdata( $post_data );
1843  
1844      $post_author = get_current_user_id();
1845  
1846      // Store one autosave per author. If there is already an autosave, overwrite it.
1847      $old_autosave = wp_get_post_autosave( $post_id, $post_author );
1848      if ( $old_autosave ) {
1849          $new_autosave                = _wp_post_revision_data( $post_data, true );
1850          $new_autosave['ID']          = $old_autosave->ID;
1851          $new_autosave['post_author'] = $post_author;
1852  
1853          $post = get_post( $post_id );
1854  
1855          // If the new autosave has the same content as the post, delete the autosave.
1856          $autosave_is_different = false;
1857          foreach ( array_intersect( array_keys( $new_autosave ), array_keys( _wp_post_revision_fields( $post ) ) ) as $field ) {
1858              if ( normalize_whitespace( $new_autosave[ $field ] ) !== normalize_whitespace( $post->$field ) ) {
1859                  $autosave_is_different = true;
1860                  break;
1861              }
1862          }
1863  
1864          if ( ! $autosave_is_different ) {
1865              wp_delete_post_revision( $old_autosave->ID );
1866              return 0;
1867          }
1868  
1869          /**
1870           * Fires before an autosave is stored.
1871           *
1872           * @since 4.1.0
1873           *
1874           * @param array $new_autosave Post array - the autosave that is about to be saved.
1875           */
1876          do_action( 'wp_creating_autosave', $new_autosave );
1877  
1878          return wp_update_post( $new_autosave );
1879      }
1880  
1881      // _wp_put_post_revision() expects unescaped.
1882      $post_data = wp_unslash( $post_data );
1883  
1884      // Otherwise create the new autosave as a special post revision.
1885      return _wp_put_post_revision( $post_data, true );
1886  }
1887  
1888  /**
1889   * Saves a draft or manually autosaves for the purpose of showing a post preview.
1890   *
1891   * @since 2.7.0
1892   *
1893   * @return string URL to redirect to show the preview.
1894   */
1895  function post_preview() {
1896  
1897      $post_ID     = (int) $_POST['post_ID'];
1898      $_POST['ID'] = $post_ID;
1899  
1900      $post = get_post( $post_ID );
1901      if ( ! $post ) {
1902          wp_die( __( 'Sorry, you are not allowed to edit this post.' ) );
1903      }
1904  
1905      if ( ! current_user_can( 'edit_post', $post->ID ) ) {
1906          wp_die( __( 'Sorry, you are not allowed to edit this post.' ) );
1907      }
1908  
1909      $is_autosave = false;
1910  
1911      if ( ! wp_check_post_lock( $post->ID ) && get_current_user_id() == $post->post_author
1912          && ( 'draft' === $post->post_status || 'auto-draft' === $post->post_status )
1913      ) {
1914          $saved_post_id = edit_post();
1915      } else {
1916          $is_autosave = true;
1917  
1918          if ( isset( $_POST['post_status'] ) && 'auto-draft' === $_POST['post_status'] ) {
1919              $_POST['post_status'] = 'draft';
1920          }
1921  
1922          $saved_post_id = wp_create_post_autosave( $post->ID );
1923      }
1924  
1925      if ( is_wp_error( $saved_post_id ) ) {
1926          wp_die( $saved_post_id->get_error_message() );
1927      }
1928  
1929      $query_args = array();
1930  
1931      if ( $is_autosave && $saved_post_id ) {
1932          $query_args['preview_id']    = $post->ID;
1933          $query_args['preview_nonce'] = wp_create_nonce( 'post_preview_' . $post->ID );
1934  
1935          if ( isset( $_POST['post_format'] ) ) {
1936              $query_args['post_format'] = empty( $_POST['post_format'] ) ? 'standard' : sanitize_key( $_POST['post_format'] );
1937          }
1938  
1939          if ( isset( $_POST['_thumbnail_id'] ) ) {
1940              $query_args['_thumbnail_id'] = ( (int) $_POST['_thumbnail_id'] <= 0 ) ? '-1' : (int) $_POST['_thumbnail_id'];
1941          }
1942      }
1943  
1944      return get_preview_post_link( $post, $query_args );
1945  }
1946  
1947  /**
1948   * Save a post submitted with XHR
1949   *
1950   * Intended for use with heartbeat and autosave.js
1951   *
1952   * @since 3.9.0
1953   *
1954   * @param array $post_data Associative array of the submitted post data.
1955   * @return mixed The value 0 or WP_Error on failure. The saved post ID on success.
1956   *               The ID can be the draft post_id or the autosave revision post_id.
1957   */
1958  function wp_autosave( $post_data ) {
1959      // Back-compat.
1960      if ( ! defined( 'DOING_AUTOSAVE' ) ) {
1961          define( 'DOING_AUTOSAVE', true );
1962      }
1963  
1964      $post_id              = (int) $post_data['post_id'];
1965      $post_data['ID']      = $post_id;
1966      $post_data['post_ID'] = $post_id;
1967  
1968      if ( false === wp_verify_nonce( $post_data['_wpnonce'], 'update-post_' . $post_id ) ) {
1969          return new WP_Error( 'invalid_nonce', __( 'Error while saving.' ) );
1970      }
1971  
1972      $post = get_post( $post_id );
1973  
1974      if ( ! current_user_can( 'edit_post', $post->ID ) ) {
1975          return new WP_Error( 'edit_posts', __( 'Sorry, you are not allowed to edit this item.' ) );
1976      }
1977  
1978      if ( 'auto-draft' === $post->post_status ) {
1979          $post_data['post_status'] = 'draft';
1980      }
1981  
1982      if ( 'page' !== $post_data['post_type'] && ! empty( $post_data['catslist'] ) ) {
1983          $post_data['post_category'] = explode( ',', $post_data['catslist'] );
1984      }
1985  
1986      if ( ! wp_check_post_lock( $post->ID ) && get_current_user_id() == $post->post_author
1987          && ( 'auto-draft' === $post->post_status || 'draft' === $post->post_status )
1988      ) {
1989          // Drafts and auto-drafts are just overwritten by autosave for the same user if the post is not locked.
1990          return edit_post( wp_slash( $post_data ) );
1991      } else {
1992          // Non-drafts or other users' drafts are not overwritten.
1993          // The autosave is stored in a special post revision for each user.
1994          return wp_create_post_autosave( wp_slash( $post_data ) );
1995      }
1996  }
1997  
1998  /**
1999   * Redirect to previous page.
2000   *
2001   * @since 2.7.0
2002   *
2003   * @param int $post_id Optional. Post ID.
2004   */
2005  function redirect_post( $post_id = '' ) {
2006      if ( isset( $_POST['save'] ) || isset( $_POST['publish'] ) ) {
2007          $status = get_post_status( $post_id );
2008  
2009          if ( isset( $_POST['publish'] ) ) {
2010              switch ( $status ) {
2011                  case 'pending':
2012                      $message = 8;
2013                      break;
2014                  case 'future':
2015                      $message = 9;
2016                      break;
2017                  default:
2018                      $message = 6;
2019              }
2020          } else {
2021              $message = 'draft' === $status ? 10 : 1;
2022          }
2023  
2024          $location = add_query_arg( 'message', $message, get_edit_post_link( $post_id, 'url' ) );
2025      } elseif ( isset( $_POST['addmeta'] ) && $_POST['addmeta'] ) {
2026          $location = add_query_arg( 'message', 2, wp_get_referer() );
2027          $location = explode( '#', $location );
2028          $location = $location[0] . '#postcustom';
2029      } elseif ( isset( $_POST['deletemeta'] ) && $_POST['deletemeta'] ) {
2030          $location = add_query_arg( 'message', 3, wp_get_referer() );
2031          $location = explode( '#', $location );
2032          $location = $location[0] . '#postcustom';
2033      } else {
2034          $location = add_query_arg( 'message', 4, get_edit_post_link( $post_id, 'url' ) );
2035      }
2036  
2037      /**
2038       * Filters the post redirect destination URL.
2039       *
2040       * @since 2.9.0
2041       *
2042       * @param string $location The destination URL.
2043       * @param int    $post_id  The post ID.
2044       */
2045      wp_redirect( apply_filters( 'redirect_post_location', $location, $post_id ) );
2046      exit;
2047  }
2048  
2049  /**
2050   * Sanitizes POST values from a checkbox taxonomy metabox.
2051   *
2052   * @since 5.1.0
2053   *
2054   * @param string $taxonomy The taxonomy name.
2055   * @param array  $terms    Raw term data from the 'tax_input' field.
2056   * @return int[] Array of sanitized term IDs.
2057   */
2058  function taxonomy_meta_box_sanitize_cb_checkboxes( $taxonomy, $terms ) {
2059      return array_map( 'intval', $terms );
2060  }
2061  
2062  /**
2063   * Sanitizes POST values from an input taxonomy metabox.
2064   *
2065   * @since 5.1.0
2066   *
2067   * @param string       $taxonomy The taxonomy name.
2068   * @param array|string $terms    Raw term data from the 'tax_input' field.
2069   * @return array
2070   */
2071  function taxonomy_meta_box_sanitize_cb_input( $taxonomy, $terms ) {
2072      /*
2073       * Assume that a 'tax_input' string is a comma-separated list of term names.
2074       * Some languages may use a character other than a comma as a delimiter, so we standardize on
2075       * commas before parsing the list.
2076       */
2077      if ( ! is_array( $terms ) ) {
2078          $comma = _x( ',', 'tag delimiter' );
2079          if ( ',' !== $comma ) {
2080              $terms = str_replace( $comma, ',', $terms );
2081          }
2082          $terms = explode( ',', trim( $terms, " \n\t\r\0\x0B," ) );
2083      }
2084  
2085      $clean_terms = array();
2086      foreach ( $terms as $term ) {
2087          // Empty terms are invalid input.
2088          if ( empty( $term ) ) {
2089              continue;
2090          }
2091  
2092          $_term = get_terms(
2093              array(
2094                  'taxonomy'   => $taxonomy,
2095                  'name'       => $term,
2096                  'fields'     => 'ids',
2097                  'hide_empty' => false,
2098              )
2099          );
2100  
2101          if ( ! empty( $_term ) ) {
2102              $clean_terms[] = (int) $_term[0];
2103          } else {
2104              // No existing term was found, so pass the string. A new term will be created.
2105              $clean_terms[] = $term;
2106          }
2107      }
2108  
2109      return $clean_terms;
2110  }
2111  
2112  /**
2113   * Return whether the post can be edited in the block editor.
2114   *
2115   * @since 5.0.0
2116   *
2117   * @param int|WP_Post $post Post ID or WP_Post object.
2118   * @return bool Whether the post can be edited in the block editor.
2119   */
2120  function use_block_editor_for_post( $post ) {
2121      $post = get_post( $post );
2122  
2123      if ( ! $post ) {
2124          return false;
2125      }
2126  
2127      // We're in the meta box loader, so don't use the block editor.
2128      if ( isset( $_GET['meta-box-loader'] ) ) {
2129          check_admin_referer( 'meta-box-loader', 'meta-box-loader-nonce' );
2130          return false;
2131      }
2132  
2133      // The posts page can't be edited in the block editor.
2134      if ( absint( get_option( 'page_for_posts' ) ) === $post->ID && empty( $post->post_content ) ) {
2135          return false;
2136      }
2137  
2138      $use_block_editor = use_block_editor_for_post_type( $post->post_type );
2139  
2140      /**
2141       * Filters whether a post is able to be edited in the block editor.
2142       *
2143       * @since 5.0.0
2144       *
2145       * @param bool    $use_block_editor Whether the post can be edited or not.
2146       * @param WP_Post $post             The post being checked.
2147       */
2148      return apply_filters( 'use_block_editor_for_post', $use_block_editor, $post );
2149  }
2150  
2151  /**
2152   * Return whether a post type is compatible with the block editor.
2153   *
2154   * The block editor depends on the REST API, and if the post type is not shown in the
2155   * REST API, then it won't work with the block editor.
2156   *
2157   * @since 5.0.0
2158   *
2159   * @param string $post_type The post type.
2160   * @return bool Whether the post type can be edited with the block editor.
2161   */
2162  function use_block_editor_for_post_type( $post_type ) {
2163      if ( ! post_type_exists( $post_type ) ) {
2164          return false;
2165      }
2166  
2167      if ( ! post_type_supports( $post_type, 'editor' ) ) {
2168          return false;
2169      }
2170  
2171      $post_type_object = get_post_type_object( $post_type );
2172      if ( $post_type_object && ! $post_type_object->show_in_rest ) {
2173          return false;
2174      }
2175  
2176      /**
2177       * Filters whether a post is able to be edited in the block editor.
2178       *
2179       * @since 5.0.0
2180       *
2181       * @param bool   $use_block_editor  Whether the post type can be edited or not. Default true.
2182       * @param string $post_type         The post type being checked.
2183       */
2184      return apply_filters( 'use_block_editor_for_post_type', true, $post_type );
2185  }
2186  
2187  /**
2188   * Returns all the block categories that will be shown in the block editor.
2189   *
2190   * @since 5.0.0
2191   *
2192   * @param WP_Post $post Post object.
2193   * @return array[] Array of block categories.
2194   */
2195  function get_block_categories( $post ) {
2196      $default_categories = array(
2197          array(
2198              'slug'  => 'text',
2199              'title' => _x( 'Text', 'block category' ),
2200              'icon'  => null,
2201          ),
2202          array(
2203              'slug'  => 'media',
2204              'title' => _x( 'Media', 'block category' ),
2205              'icon'  => null,
2206          ),
2207          array(
2208              'slug'  => 'design',
2209              'title' => _x( 'Design', 'block category' ),
2210              'icon'  => null,
2211          ),
2212          array(
2213              'slug'  => 'widgets',
2214              'title' => _x( 'Widgets', 'block category' ),
2215              'icon'  => null,
2216          ),
2217          array(
2218              'slug'  => 'embed',
2219              'title' => _x( 'Embeds', 'block category' ),
2220              'icon'  => null,
2221          ),
2222          array(
2223              'slug'  => 'reusable',
2224              'title' => _x( 'Reusable Blocks', 'block category' ),
2225              'icon'  => null,
2226          ),
2227      );
2228  
2229      /**
2230       * Filters the default array of block categories.
2231       *
2232       * @since 5.0.0
2233       *
2234       * @param array[] $default_categories Array of block categories.
2235       * @param WP_Post $post               Post being loaded.
2236       */
2237      return apply_filters( 'block_categories', $default_categories, $post );
2238  }
2239  
2240  /**
2241   * Prepares server-registered blocks for the block editor.
2242   *
2243   * Returns an associative array of registered block data keyed by block name. Data includes properties
2244   * of a block relevant for client registration.
2245   *
2246   * @since 5.0.0
2247   *
2248   * @return array An associative array of registered block data.
2249   */
2250  function get_block_editor_server_block_settings() {
2251      $block_registry = WP_Block_Type_Registry::get_instance();
2252      $blocks         = array();
2253      $fields_to_pick = array(
2254          'title'            => 'title',
2255          'description'      => 'description',
2256          'icon'             => 'icon',
2257          'category'         => 'category',
2258          'keywords'         => 'keywords',
2259          'parent'           => 'parent',
2260          'supports'         => 'supports',
2261          'attributes'       => 'attributes',
2262          'provides_context' => 'providesContext',
2263          'uses_context'     => 'usesContext',
2264          'styles'           => 'styles',
2265          'textdomain'       => 'textdomain',
2266          'example'          => 'example',
2267      );
2268  
2269      foreach ( $block_registry->get_all_registered() as $block_name => $block_type ) {
2270          foreach ( $fields_to_pick as $field => $key ) {
2271              if ( ! isset( $block_type->{ $field } ) ) {
2272                  continue;
2273              }
2274  
2275              if ( ! isset( $blocks[ $block_name ] ) ) {
2276                  $blocks[ $block_name ] = array();
2277              }
2278  
2279              $blocks[ $block_name ][ $key ] = $block_type->{ $field };
2280          }
2281      }
2282  
2283      return $blocks;
2284  }
2285  
2286  /**
2287   * Renders the meta boxes forms.
2288   *
2289   * @since 5.0.0
2290   */
2291  function the_block_editor_meta_boxes() {
2292      global $post, $current_screen, $wp_meta_boxes;
2293  
2294      // Handle meta box state.
2295      $_original_meta_boxes = $wp_meta_boxes;
2296  
2297      /**
2298       * Fires right before the meta boxes are rendered.
2299       *
2300       * This allows for the filtering of meta box data, that should already be
2301       * present by this point. Do not use as a means of adding meta box data.
2302       *
2303       * @since 5.0.0
2304       *
2305       * @param array $wp_meta_boxes Global meta box state.
2306       */
2307      $wp_meta_boxes = apply_filters( 'filter_block_editor_meta_boxes', $wp_meta_boxes );
2308      $locations     = array( 'side', 'normal', 'advanced' );
2309      $priorities    = array( 'high', 'sorted', 'core', 'default', 'low' );
2310  
2311      // Render meta boxes.
2312      ?>
2313      <form class="metabox-base-form">
2314      <?php the_block_editor_meta_box_post_form_hidden_fields( $post ); ?>
2315      </form>
2316      <form id="toggle-custom-fields-form" method="post" action="<?php echo esc_attr( admin_url( 'post.php' ) ); ?>">
2317          <?php wp_nonce_field( 'toggle-custom-fields' ); ?>
2318          <input type="hidden" name="action" value="toggle-custom-fields" />
2319      </form>
2320      <?php foreach ( $locations as $location ) : ?>
2321          <form class="metabox-location-<?php echo esc_attr( $location ); ?>" onsubmit="return false;">
2322              <div id="poststuff" class="sidebar-open">
2323                  <div id="postbox-container-2" class="postbox-container">
2324                      <?php
2325                      do_meta_boxes(
2326                          $current_screen,
2327                          $location,
2328                          $post
2329                      );
2330                      ?>
2331                  </div>
2332              </div>
2333          </form>
2334      <?php endforeach; ?>
2335      <?php
2336  
2337      $meta_boxes_per_location = array();
2338      foreach ( $locations as $location ) {
2339          $meta_boxes_per_location[ $location ] = array();
2340  
2341          if ( ! isset( $wp_meta_boxes[ $current_screen->id ][ $location ] ) ) {
2342              continue;
2343          }
2344  
2345          foreach ( $priorities as $priority ) {
2346              if ( ! isset( $wp_meta_boxes[ $current_screen->id ][ $location ][ $priority ] ) ) {
2347                  continue;
2348              }
2349  
2350              $meta_boxes = (array) $wp_meta_boxes[ $current_screen->id ][ $location ][ $priority ];
2351              foreach ( $meta_boxes as $meta_box ) {
2352                  if ( false == $meta_box || ! $meta_box['title'] ) {
2353                      continue;
2354                  }
2355  
2356                  // If a meta box is just here for back compat, don't show it in the block editor.
2357                  if ( isset( $meta_box['args']['__back_compat_meta_box'] ) && $meta_box['args']['__back_compat_meta_box'] ) {
2358                      continue;
2359                  }
2360  
2361                  $meta_boxes_per_location[ $location ][] = array(
2362                      'id'    => $meta_box['id'],
2363                      'title' => $meta_box['title'],
2364                  );
2365              }
2366          }
2367      }
2368  
2369      /**
2370       * Sadly we probably can not add this data directly into editor settings.
2371       *
2372       * Some meta boxes need admin_head to fire for meta box registry.
2373       * admin_head fires after admin_enqueue_scripts, which is where we create our
2374       * editor instance.
2375       */
2376      $script = 'window._wpLoadBlockEditor.then( function() {
2377          wp.data.dispatch( \'core/edit-post\' ).setAvailableMetaBoxesPerLocation( ' . wp_json_encode( $meta_boxes_per_location ) . ' );
2378      } );';
2379  
2380      wp_add_inline_script( 'wp-edit-post', $script );
2381  
2382      /**
2383       * When `wp-edit-post` is output in the `<head>`, the inline script needs to be manually printed. Otherwise,
2384       * meta boxes will not display because inline scripts for `wp-edit-post` will not be printed again after this point.
2385       */
2386      if ( wp_script_is( 'wp-edit-post', 'done' ) ) {
2387          printf( "<script type='text/javascript'>\n%s\n</script>\n", trim( $script ) );
2388      }
2389  
2390      /**
2391       * If the 'postcustom' meta box is enabled, then we need to perform some
2392       * extra initialization on it.
2393       */
2394      $enable_custom_fields = (bool) get_user_meta( get_current_user_id(), 'enable_custom_fields', true );
2395      if ( $enable_custom_fields ) {
2396          $script = "( function( $ ) {
2397              if ( $('#postcustom').length ) {
2398                  $( '#the-list' ).wpList( {
2399                      addBefore: function( s ) {
2400                          s.data += '&post_id=$post->ID';
2401                          return s;
2402                      },
2403                      addAfter: function() {
2404                          $('table#list-table').show();
2405                      }
2406                  });
2407              }
2408          } )( jQuery );";
2409          wp_enqueue_script( 'wp-lists' );
2410          wp_add_inline_script( 'wp-lists', $script );
2411      }
2412  
2413      // Reset meta box data.
2414      $wp_meta_boxes = $_original_meta_boxes;
2415  }
2416  
2417  /**
2418   * Renders the hidden form required for the meta boxes form.
2419   *
2420   * @since 5.0.0
2421   *
2422   * @param WP_Post $post Current post object.
2423   */
2424  function the_block_editor_meta_box_post_form_hidden_fields( $post ) {
2425      $form_extra = '';
2426      if ( 'auto-draft' === $post->post_status ) {
2427          $form_extra .= "<input type='hidden' id='auto_draft' name='auto_draft' value='1' />";
2428      }
2429      $form_action  = 'editpost';
2430      $nonce_action = 'update-post_' . $post->ID;
2431      $form_extra  .= "<input type='hidden' id='post_ID' name='post_ID' value='" . esc_attr( $post->ID ) . "' />";
2432      $referer      = wp_get_referer();
2433      $current_user = wp_get_current_user();
2434      $user_id      = $current_user->ID;
2435      wp_nonce_field( $nonce_action );
2436  
2437      /*
2438       * Some meta boxes hook into these actions to add hidden input fields in the classic post form. For backwards
2439       * compatibility, we can capture the output from these actions, and extract the hidden input fields.
2440       */
2441      ob_start();
2442      /** This filter is documented in wp-admin/edit-form-advanced.php */
2443      do_action( 'edit_form_after_title', $post );
2444      /** This filter is documented in wp-admin/edit-form-advanced.php */
2445      do_action( 'edit_form_advanced', $post );
2446      $classic_output = ob_get_clean();
2447  
2448      $classic_elements = wp_html_split( $classic_output );
2449      $hidden_inputs    = '';
2450      foreach ( $classic_elements as $element ) {
2451          if ( 0 !== strpos( $element, '<input ' ) ) {
2452              continue;
2453          }
2454  
2455          if ( preg_match( '/\stype=[\'"]hidden[\'"]\s/', $element ) ) {
2456              echo $element;
2457          }
2458      }
2459      ?>
2460      <input type="hidden" id="user-id" name="user_ID" value="<?php echo (int) $user_id; ?>" />
2461      <input type="hidden" id="hiddenaction" name="action" value="<?php echo esc_attr( $form_action ); ?>" />
2462      <input type="hidden" id="originalaction" name="originalaction" value="<?php echo esc_attr( $form_action ); ?>" />
2463      <input type="hidden" id="post_type" name="post_type" value="<?php echo esc_attr( $post->post_type ); ?>" />
2464      <input type="hidden" id="original_post_status" name="original_post_status" value="<?php echo esc_attr( $post->post_status ); ?>" />
2465      <input type="hidden" id="referredby" name="referredby" value="<?php echo $referer ? esc_url( $referer ) : ''; ?>" />
2466  
2467      <?php
2468      if ( 'draft' !== get_post_status( $post ) ) {
2469          wp_original_referer_field( true, 'previous' );
2470      }
2471      echo $form_extra;
2472      wp_nonce_field( 'meta-box-order', 'meta-box-order-nonce', false );
2473      wp_nonce_field( 'closedpostboxes', 'closedpostboxesnonce', false );
2474      // Permalink title nonce.
2475      wp_nonce_field( 'samplepermalink', 'samplepermalinknonce', false );
2476  
2477      /**
2478       * Add hidden input fields to the meta box save form.
2479       *
2480       * Hook into this action to print `<input type="hidden" ... />` fields, which will be POSTed back to
2481       * the server when meta boxes are saved.
2482       *
2483       * @since 5.0.0
2484       *
2485       * @param WP_Post $post The post that is being edited.
2486       */
2487      do_action( 'block_editor_meta_box_hidden_fields', $post );
2488  }


Generated: Fri Oct 30 01:00:03 2020 Cross-referenced by PHPXref 0.7.1