home *** CD-ROM | disk | FTP | other *** search
/ HTML Examples / WP.iso / wordpress / wp-admin / includes / post.php < prev    next >
Encoding:
PHP Script  |  2017-10-03  |  58.6 KB  |  1,873 lines

  1. <?php
  2. /**
  3.  * WordPress Post Administration API.
  4.  *
  5.  * @package WordPress
  6.  * @subpackage Administration
  7.  */
  8.  
  9. /**
  10.  * Rename $_POST data from form names to DB post columns.
  11.  *
  12.  * Manipulates $_POST directly.
  13.  *
  14.  * @since 2.6.0
  15.  *
  16.  * @param bool $update Are we updating a pre-existing post?
  17.  * @param array $post_data Array of post data. Defaults to the contents of $_POST.
  18.  * @return object|bool WP_Error on failure, true on success.
  19.  */
  20. function _wp_translate_postdata( $update = false, $post_data = null ) {
  21.  
  22.     if ( empty($post_data) )
  23.         $post_data = &$_POST;
  24.  
  25.     if ( $update )
  26.         $post_data['ID'] = (int) $post_data['post_ID'];
  27.  
  28.     $ptype = get_post_type_object( $post_data['post_type'] );
  29.  
  30.     if ( $update && ! current_user_can( 'edit_post', $post_data['ID'] ) ) {
  31.         if ( 'page' == $post_data['post_type'] )
  32.             return new WP_Error( 'edit_others_pages', __( 'Sorry, you are not allowed to edit pages as this user.' ) );
  33.         else
  34.             return new WP_Error( 'edit_others_posts', __( 'Sorry, you are not allowed to edit posts as this user.' ) );
  35.     } elseif ( ! $update && ! current_user_can( $ptype->cap->create_posts ) ) {
  36.         if ( 'page' == $post_data['post_type'] )
  37.             return new WP_Error( 'edit_others_pages', __( 'Sorry, you are not allowed to create pages as this user.' ) );
  38.         else
  39.             return new WP_Error( 'edit_others_posts', __( 'Sorry, you are not allowed to create posts as this user.' ) );
  40.     }
  41.  
  42.     if ( isset( $post_data['content'] ) )
  43.         $post_data['post_content'] = $post_data['content'];
  44.  
  45.     if ( isset( $post_data['excerpt'] ) )
  46.         $post_data['post_excerpt'] = $post_data['excerpt'];
  47.  
  48.     if ( isset( $post_data['parent_id'] ) )
  49.         $post_data['post_parent'] = (int) $post_data['parent_id'];
  50.  
  51.     if ( isset($post_data['trackback_url']) )
  52.         $post_data['to_ping'] = $post_data['trackback_url'];
  53.  
  54.     $post_data['user_ID'] = get_current_user_id();
  55.  
  56.     if (!empty ( $post_data['post_author_override'] ) ) {
  57.         $post_data['post_author'] = (int) $post_data['post_author_override'];
  58.     } else {
  59.         if (!empty ( $post_data['post_author'] ) ) {
  60.             $post_data['post_author'] = (int) $post_data['post_author'];
  61.         } else {
  62.             $post_data['post_author'] = (int) $post_data['user_ID'];
  63.         }
  64.     }
  65.  
  66.     if ( isset( $post_data['user_ID'] ) && ( $post_data['post_author'] != $post_data['user_ID'] )
  67.          && ! current_user_can( $ptype->cap->edit_others_posts ) ) {
  68.         if ( $update ) {
  69.             if ( 'page' == $post_data['post_type'] )
  70.                 return new WP_Error( 'edit_others_pages', __( 'Sorry, you are not allowed to edit pages as this user.' ) );
  71.             else
  72.                 return new WP_Error( 'edit_others_posts', __( 'Sorry, you are not allowed to edit posts as this user.' ) );
  73.         } else {
  74.             if ( 'page' == $post_data['post_type'] )
  75.                 return new WP_Error( 'edit_others_pages', __( 'Sorry, you are not allowed to create pages as this user.' ) );
  76.             else
  77.                 return new WP_Error( 'edit_others_posts', __( 'Sorry, you are not allowed to create posts as this user.' ) );
  78.         }
  79.     }
  80.  
  81.     if ( ! empty( $post_data['post_status'] ) ) {
  82.         $post_data['post_status'] = sanitize_key( $post_data['post_status'] );
  83.  
  84.         // No longer an auto-draft
  85.         if ( 'auto-draft' === $post_data['post_status'] ) {
  86.             $post_data['post_status'] = 'draft';
  87.         }
  88.  
  89.         if ( ! get_post_status_object( $post_data['post_status'] ) ) {
  90.             unset( $post_data['post_status'] );
  91.         }
  92.     }
  93.  
  94.     // What to do based on which button they pressed
  95.     if ( isset($post_data['saveasdraft']) && '' != $post_data['saveasdraft'] )
  96.         $post_data['post_status'] = 'draft';
  97.     if ( isset($post_data['saveasprivate']) && '' != $post_data['saveasprivate'] )
  98.         $post_data['post_status'] = 'private';
  99.     if ( isset($post_data['publish']) && ( '' != $post_data['publish'] ) && ( !isset($post_data['post_status']) || $post_data['post_status'] != 'private' ) )
  100.         $post_data['post_status'] = 'publish';
  101.     if ( isset($post_data['advanced']) && '' != $post_data['advanced'] )
  102.         $post_data['post_status'] = 'draft';
  103.     if ( isset($post_data['pending']) && '' != $post_data['pending'] )
  104.         $post_data['post_status'] = 'pending';
  105.  
  106.     if ( isset( $post_data['ID'] ) )
  107.         $post_id = $post_data['ID'];
  108.     else
  109.         $post_id = false;
  110.     $previous_status = $post_id ? get_post_field( 'post_status', $post_id ) : false;
  111.  
  112.     if ( isset( $post_data['post_status'] ) && 'private' == $post_data['post_status'] && ! current_user_can( $ptype->cap->publish_posts ) ) {
  113.         $post_data['post_status'] = $previous_status ? $previous_status : 'pending';
  114.     }
  115.  
  116.     $published_statuses = array( 'publish', 'future' );
  117.  
  118.     // Posts 'submitted for approval' present are submitted to $_POST the same as if they were being published.
  119.     // Change status from 'publish' to 'pending' if user lacks permissions to publish or to resave published posts.
  120.     if ( isset($post_data['post_status']) && (in_array( $post_data['post_status'], $published_statuses ) && !current_user_can( $ptype->cap->publish_posts )) )
  121.         if ( ! in_array( $previous_status, $published_statuses ) || !current_user_can( 'edit_post', $post_id ) )
  122.             $post_data['post_status'] = 'pending';
  123.  
  124.     if ( ! isset( $post_data['post_status'] ) ) {
  125.         $post_data['post_status'] = 'auto-draft' === $previous_status ? 'draft' : $previous_status;
  126.     }
  127.  
  128.     if ( isset( $post_data['post_password'] ) && ! current_user_can( $ptype->cap->publish_posts ) ) {
  129.         unset( $post_data['post_password'] );
  130.     }
  131.  
  132.     if (!isset( $post_data['comment_status'] ))
  133.         $post_data['comment_status'] = 'closed';
  134.  
  135.     if (!isset( $post_data['ping_status'] ))
  136.         $post_data['ping_status'] = 'closed';
  137.  
  138.     foreach ( array('aa', 'mm', 'jj', 'hh', 'mn') as $timeunit ) {
  139.         if ( !empty( $post_data['hidden_' . $timeunit] ) && $post_data['hidden_' . $timeunit] != $post_data[$timeunit] ) {
  140.             $post_data['edit_date'] = '1';
  141.             break;
  142.         }
  143.     }
  144.  
  145.     if ( !empty( $post_data['edit_date'] ) ) {
  146.         $aa = $post_data['aa'];
  147.         $mm = $post_data['mm'];
  148.         $jj = $post_data['jj'];
  149.         $hh = $post_data['hh'];
  150.         $mn = $post_data['mn'];
  151.         $ss = $post_data['ss'];
  152.         $aa = ($aa <= 0 ) ? date('Y') : $aa;
  153.         $mm = ($mm <= 0 ) ? date('n') : $mm;
  154.         $jj = ($jj > 31 ) ? 31 : $jj;
  155.         $jj = ($jj <= 0 ) ? date('j') : $jj;
  156.         $hh = ($hh > 23 ) ? $hh -24 : $hh;
  157.         $mn = ($mn > 59 ) ? $mn -60 : $mn;
  158.         $ss = ($ss > 59 ) ? $ss -60 : $ss;
  159.         $post_data['post_date'] = sprintf( "%04d-%02d-%02d %02d:%02d:%02d", $aa, $mm, $jj, $hh, $mn, $ss );
  160.         $valid_date = wp_checkdate( $mm, $jj, $aa, $post_data['post_date'] );
  161.         if ( !$valid_date ) {
  162.             return new WP_Error( 'invalid_date', __( 'Invalid date.' ) );
  163.         }
  164.         $post_data['post_date_gmt'] = get_gmt_from_date( $post_data['post_date'] );
  165.     }
  166.  
  167.     if ( isset( $post_data['post_category'] ) ) {
  168.         $category_object = get_taxonomy( 'category' );
  169.         if ( ! current_user_can( $category_object->cap->assign_terms ) ) {
  170.             unset( $post_data['post_category'] );
  171.         }
  172.     }
  173.  
  174.     return $post_data;
  175. }
  176.  
  177. /**
  178.  * Update an existing post with values provided in $_POST.
  179.  *
  180.  * @since 1.5.0
  181.  *
  182.  * @global wpdb $wpdb WordPress database abstraction object.
  183.  *
  184.  * @param array $post_data Optional.
  185.  * @return int Post ID.
  186.  */
  187. function edit_post( $post_data = null ) {
  188.     global $wpdb;
  189.  
  190.     if ( empty($post_data) )
  191.         $post_data = &$_POST;
  192.  
  193.     // Clear out any data in internal vars.
  194.     unset( $post_data['filter'] );
  195.  
  196.     $post_ID = (int) $post_data['post_ID'];
  197.     $post = get_post( $post_ID );
  198.     $post_data['post_type'] = $post->post_type;
  199.     $post_data['post_mime_type'] = $post->post_mime_type;
  200.  
  201.     if ( ! empty( $post_data['post_status'] ) ) {
  202.         $post_data['post_status'] = sanitize_key( $post_data['post_status'] );
  203.  
  204.         if ( 'inherit' == $post_data['post_status'] ) {
  205.             unset( $post_data['post_status'] );
  206.         }
  207.     }
  208.  
  209.     $ptype = get_post_type_object($post_data['post_type']);
  210.     if ( !current_user_can( 'edit_post', $post_ID ) ) {
  211.         if ( 'page' == $post_data['post_type'] )
  212.             wp_die( __('Sorry, you are not allowed to edit this page.' ));
  213.         else
  214.             wp_die( __('Sorry, you are not allowed to edit this post.' ));
  215.     }
  216.  
  217.     if ( post_type_supports( $ptype->name, 'revisions' ) ) {
  218.         $revisions = wp_get_post_revisions( $post_ID, array( 'order' => 'ASC', 'posts_per_page' => 1 ) );
  219.         $revision = current( $revisions );
  220.  
  221.         // Check if the revisions have been upgraded
  222.         if ( $revisions && _wp_get_post_revision_version( $revision ) < 1 )
  223.             _wp_upgrade_revisions_of_post( $post, wp_get_post_revisions( $post_ID ) );
  224.     }
  225.  
  226.     if ( isset($post_data['visibility']) ) {
  227.         switch ( $post_data['visibility'] ) {
  228.             case 'public' :
  229.                 $post_data['post_password'] = '';
  230.                 break;
  231.             case 'password' :
  232.                 unset( $post_data['sticky'] );
  233.                 break;
  234.             case 'private' :
  235.                 $post_data['post_status'] = 'private';
  236.                 $post_data['post_password'] = '';
  237.                 unset( $post_data['sticky'] );
  238.                 break;
  239.         }
  240.     }
  241.  
  242.     $post_data = _wp_translate_postdata( true, $post_data );
  243.     if ( is_wp_error($post_data) )
  244.         wp_die( $post_data->get_error_message() );
  245.  
  246.     // Post Formats
  247.     if ( isset( $post_data['post_format'] ) )
  248.         set_post_format( $post_ID, $post_data['post_format'] );
  249.  
  250.     $format_meta_urls = array( 'url', 'link_url', 'quote_source_url' );
  251.     foreach ( $format_meta_urls as $format_meta_url ) {
  252.         $keyed = '_format_' . $format_meta_url;
  253.         if ( isset( $post_data[ $keyed ] ) )
  254.             update_post_meta( $post_ID, $keyed, wp_slash( esc_url_raw( wp_unslash( $post_data[ $keyed ] ) ) ) );
  255.     }
  256.  
  257.     $format_keys = array( 'quote', 'quote_source_name', 'image', 'gallery', 'audio_embed', 'video_embed' );
  258.  
  259.     foreach ( $format_keys as $key ) {
  260.         $keyed = '_format_' . $key;
  261.         if ( isset( $post_data[ $keyed ] ) ) {
  262.             if ( current_user_can( 'unfiltered_html' ) )
  263.                 update_post_meta( $post_ID, $keyed, $post_data[ $keyed ] );
  264.             else
  265.                 update_post_meta( $post_ID, $keyed, wp_filter_post_kses( $post_data[ $keyed ] ) );
  266.         }
  267.     }
  268.  
  269.     if ( 'attachment' === $post_data['post_type'] && preg_match( '#^(audio|video)/#', $post_data['post_mime_type'] ) ) {
  270.         $id3data = wp_get_attachment_metadata( $post_ID );
  271.         if ( ! is_array( $id3data ) ) {
  272.             $id3data = array();
  273.         }
  274.  
  275.         foreach ( wp_get_attachment_id3_keys( $post, 'edit' ) as $key => $label ) {
  276.             if ( isset( $post_data[ 'id3_' . $key ] ) ) {
  277.                 $id3data[ $key ] = sanitize_text_field( wp_unslash( $post_data[ 'id3_' . $key ] ) );
  278.             }
  279.         }
  280.         wp_update_attachment_metadata( $post_ID, $id3data );
  281.     }
  282.  
  283.     // Meta Stuff
  284.     if ( isset($post_data['meta']) && $post_data['meta'] ) {
  285.         foreach ( $post_data['meta'] as $key => $value ) {
  286.             if ( !$meta = get_post_meta_by_id( $key ) )
  287.                 continue;
  288.             if ( $meta->post_id != $post_ID )
  289.                 continue;
  290.             if ( is_protected_meta( $meta->meta_key, 'post' ) || ! current_user_can( 'edit_post_meta', $post_ID, $meta->meta_key ) )
  291.                 continue;
  292.             if ( is_protected_meta( $value['key'], 'post' ) || ! current_user_can( 'edit_post_meta', $post_ID, $value['key'] ) )
  293.                 continue;
  294.             update_meta( $key, $value['key'], $value['value'] );
  295.         }
  296.     }
  297.  
  298.     if ( isset($post_data['deletemeta']) && $post_data['deletemeta'] ) {
  299.         foreach ( $post_data['deletemeta'] as $key => $value ) {
  300.             if ( !$meta = get_post_meta_by_id( $key ) )
  301.                 continue;
  302.             if ( $meta->post_id != $post_ID )
  303.                 continue;
  304.             if ( is_protected_meta( $meta->meta_key, 'post' ) || ! current_user_can( 'delete_post_meta', $post_ID, $meta->meta_key ) )
  305.                 continue;
  306.             delete_meta( $key );
  307.         }
  308.     }
  309.  
  310.     // Attachment stuff
  311.     if ( 'attachment' == $post_data['post_type'] ) {
  312.         if ( isset( $post_data[ '_wp_attachment_image_alt' ] ) ) {
  313.             $image_alt = wp_unslash( $post_data['_wp_attachment_image_alt'] );
  314.             if ( $image_alt != get_post_meta( $post_ID, '_wp_attachment_image_alt', true ) ) {
  315.                 $image_alt = wp_strip_all_tags( $image_alt, true );
  316.                 // update_meta expects slashed.
  317.                 update_post_meta( $post_ID, '_wp_attachment_image_alt', wp_slash( $image_alt ) );
  318.             }
  319.         }
  320.  
  321.         $attachment_data = isset( $post_data['attachments'][ $post_ID ] ) ? $post_data['attachments'][ $post_ID ] : array();
  322.  
  323.         /** This filter is documented in wp-admin/includes/media.php */
  324.         $post_data = apply_filters( 'attachment_fields_to_save', $post_data, $attachment_data );
  325.     }
  326.  
  327.     // Convert taxonomy input to term IDs, to avoid ambiguity.
  328.     if ( isset( $post_data['tax_input'] ) ) {
  329.         foreach ( (array) $post_data['tax_input'] as $taxonomy => $terms ) {
  330.             // Hierarchical taxonomy data is already sent as term IDs, so no conversion is necessary.
  331.             if ( is_taxonomy_hierarchical( $taxonomy ) ) {
  332.                 continue;
  333.             }
  334.  
  335.             /*
  336.              * Assume that a 'tax_input' string is a comma-separated list of term names.
  337.              * Some languages may use a character other than a comma as a delimiter, so we standardize on
  338.              * commas before parsing the list.
  339.              */
  340.             if ( ! is_array( $terms ) ) {
  341.                 $comma = _x( ',', 'tag delimiter' );
  342.                 if ( ',' !== $comma ) {
  343.                     $terms = str_replace( $comma, ',', $terms );
  344.                 }
  345.                 $terms = explode( ',', trim( $terms, " \n\t\r\0\x0B," ) );
  346.             }
  347.  
  348.             $clean_terms = array();
  349.             foreach ( $terms as $term ) {
  350.                 // Empty terms are invalid input.
  351.                 if ( empty( $term ) ) {
  352.                     continue;
  353.                 }
  354.  
  355.                 $_term = get_terms( $taxonomy, array(
  356.                     'name' => $term,
  357.                     'fields' => 'ids',
  358.                     'hide_empty' => false,
  359.                 ) );
  360.  
  361.                 if ( ! empty( $_term ) ) {
  362.                     $clean_terms[] = intval( $_term[0] );
  363.                 } else {
  364.                     // No existing term was found, so pass the string. A new term will be created.
  365.                     $clean_terms[] = $term;
  366.                 }
  367.             }
  368.  
  369.             $post_data['tax_input'][ $taxonomy ] = $clean_terms;
  370.         }
  371.     }
  372.  
  373.     add_meta( $post_ID );
  374.  
  375.     update_post_meta( $post_ID, '_edit_last', get_current_user_id() );
  376.  
  377.     $success = wp_update_post( $post_data );
  378.     // If the save failed, see if we can sanity check the main fields and try again
  379.     if ( ! $success && is_callable( array( $wpdb, 'strip_invalid_text_for_column' ) ) ) {
  380.         $fields = array( 'post_title', 'post_content', 'post_excerpt' );
  381.  
  382.         foreach ( $fields as $field ) {
  383.             if ( isset( $post_data[ $field ] ) ) {
  384.                 $post_data[ $field ] = $wpdb->strip_invalid_text_for_column( $wpdb->posts, $field, $post_data[ $field ] );
  385.             }
  386.         }
  387.  
  388.         wp_update_post( $post_data );
  389.     }
  390.  
  391.     // Now that we have an ID we can fix any attachment anchor hrefs
  392.     _fix_attachment_links( $post_ID );
  393.  
  394.     wp_set_post_lock( $post_ID );
  395.  
  396.     if ( current_user_can( $ptype->cap->edit_others_posts ) && current_user_can( $ptype->cap->publish_posts ) ) {
  397.         if ( ! empty( $post_data['sticky'] ) )
  398.             stick_post( $post_ID );
  399.         else
  400.             unstick_post( $post_ID );
  401.     }
  402.  
  403.     return $post_ID;
  404. }
  405.  
  406. /**
  407.  * Process the post data for the bulk editing of posts.
  408.  *
  409.  * Updates all bulk edited posts/pages, adding (but not removing) tags and
  410.  * categories. Skips pages when they would be their own parent or child.
  411.  *
  412.  * @since 2.7.0
  413.  *
  414.  * @global wpdb $wpdb WordPress database abstraction object.
  415.  *
  416.  * @param array $post_data Optional, the array of post data to process if not provided will use $_POST superglobal.
  417.  * @return array
  418.  */
  419. function bulk_edit_posts( $post_data = null ) {
  420.     global $wpdb;
  421.  
  422.     if ( empty($post_data) )
  423.         $post_data = &$_POST;
  424.  
  425.     if ( isset($post_data['post_type']) )
  426.         $ptype = get_post_type_object($post_data['post_type']);
  427.     else
  428.         $ptype = get_post_type_object('post');
  429.  
  430.     if ( !current_user_can( $ptype->cap->edit_posts ) ) {
  431.         if ( 'page' == $ptype->name )
  432.             wp_die( __('Sorry, you are not allowed to edit pages.'));
  433.         else
  434.             wp_die( __('Sorry, you are not allowed to edit posts.'));
  435.     }
  436.  
  437.     if ( -1 == $post_data['_status'] ) {
  438.         $post_data['post_status'] = null;
  439.         unset($post_data['post_status']);
  440.     } else {
  441.         $post_data['post_status'] = $post_data['_status'];
  442.     }
  443.     unset($post_data['_status']);
  444.  
  445.     if ( ! empty( $post_data['post_status'] ) ) {
  446.         $post_data['post_status'] = sanitize_key( $post_data['post_status'] );
  447.  
  448.         if ( 'inherit' == $post_data['post_status'] ) {
  449.             unset( $post_data['post_status'] );
  450.         }
  451.     }
  452.  
  453.     $post_IDs = array_map( 'intval', (array) $post_data['post'] );
  454.  
  455.     $reset = array(
  456.         'post_author', 'post_status', 'post_password',
  457.         'post_parent', 'page_template', 'comment_status',
  458.         'ping_status', 'keep_private', 'tax_input',
  459.         'post_category', 'sticky', 'post_format',
  460.     );
  461.  
  462.     foreach ( $reset as $field ) {
  463.         if ( isset($post_data[$field]) && ( '' == $post_data[$field] || -1 == $post_data[$field] ) )
  464.             unset($post_data[$field]);
  465.     }
  466.  
  467.     if ( isset($post_data['post_category']) ) {
  468.         if ( is_array($post_data['post_category']) && ! empty($post_data['post_category']) )
  469.             $new_cats = array_map( 'absint', $post_data['post_category'] );
  470.         else
  471.             unset($post_data['post_category']);
  472.     }
  473.  
  474.     $tax_input = array();
  475.     if ( isset($post_data['tax_input'])) {
  476.         foreach ( $post_data['tax_input'] as $tax_name => $terms ) {
  477.             if ( empty($terms) )
  478.                 continue;
  479.             if ( is_taxonomy_hierarchical( $tax_name ) ) {
  480.                 $tax_input[ $tax_name ] = array_map( 'absint', $terms );
  481.             } else {
  482.                 $comma = _x( ',', 'tag delimiter' );
  483.                 if ( ',' !== $comma )
  484.                     $terms = str_replace( $comma, ',', $terms );
  485.                 $tax_input[ $tax_name ] = explode( ',', trim( $terms, " \n\t\r\0\x0B," ) );
  486.             }
  487.         }
  488.     }
  489.  
  490.     if ( isset($post_data['post_parent']) && ($parent = (int) $post_data['post_parent']) ) {
  491.         $pages = $wpdb->get_results("SELECT ID, post_parent FROM $wpdb->posts WHERE post_type = 'page'");
  492.         $children = array();
  493.  
  494.         for ( $i = 0; $i < 50 && $parent > 0; $i++ ) {
  495.             $children[] = $parent;
  496.  
  497.             foreach ( $pages as $page ) {
  498.                 if ( $page->ID == $parent ) {
  499.                     $parent = $page->post_parent;
  500.                     break;
  501.                 }
  502.             }
  503.         }
  504.     }
  505.  
  506.     $updated = $skipped = $locked = array();
  507.     $shared_post_data = $post_data;
  508.  
  509.     foreach ( $post_IDs as $post_ID ) {
  510.         // Start with fresh post data with each iteration.
  511.         $post_data = $shared_post_data;
  512.  
  513.         $post_type_object = get_post_type_object( get_post_type( $post_ID ) );
  514.  
  515.         if ( !isset( $post_type_object ) || ( isset($children) && in_array($post_ID, $children) ) || !current_user_can( 'edit_post', $post_ID ) ) {
  516.             $skipped[] = $post_ID;
  517.             continue;
  518.         }
  519.  
  520.         if ( wp_check_post_lock( $post_ID ) ) {
  521.             $locked[] = $post_ID;
  522.             continue;
  523.         }
  524.  
  525.         $post = get_post( $post_ID );
  526.         $tax_names = get_object_taxonomies( $post );
  527.         foreach ( $tax_names as $tax_name ) {
  528.             $taxonomy_obj = get_taxonomy($tax_name);
  529.             if ( isset( $tax_input[$tax_name]) && current_user_can( $taxonomy_obj->cap->assign_terms ) )
  530.                 $new_terms = $tax_input[$tax_name];
  531.             else
  532.                 $new_terms = array();
  533.  
  534.             if ( $taxonomy_obj->hierarchical )
  535.                 $current_terms = (array) wp_get_object_terms( $post_ID, $tax_name, array('fields' => 'ids') );
  536.             else
  537.                 $current_terms = (array) wp_get_object_terms( $post_ID, $tax_name, array('fields' => 'names') );
  538.  
  539.             $post_data['tax_input'][$tax_name] = array_merge( $current_terms, $new_terms );
  540.         }
  541.  
  542.         if ( isset($new_cats) && in_array( 'category', $tax_names ) ) {
  543.             $cats = (array) wp_get_post_categories($post_ID);
  544.             $post_data['post_category'] = array_unique( array_merge($cats, $new_cats) );
  545.             unset( $post_data['tax_input']['category'] );
  546.         }
  547.  
  548.         $post_data['post_type'] = $post->post_type;
  549.         $post_data['post_mime_type'] = $post->post_mime_type;
  550.         $post_data['guid'] = $post->guid;
  551.  
  552.         foreach ( array( 'comment_status', 'ping_status', 'post_author' ) as $field ) {
  553.             if ( ! isset( $post_data[ $field ] ) ) {
  554.                 $post_data[ $field ] = $post->$field;
  555.             }
  556.         }
  557.  
  558.         $post_data['ID'] = $post_ID;
  559.         $post_data['post_ID'] = $post_ID;
  560.  
  561.         $post_data = _wp_translate_postdata( true, $post_data );
  562.         if ( is_wp_error( $post_data ) ) {
  563.             $skipped[] = $post_ID;
  564.             continue;
  565.         }
  566.  
  567.         if ( isset( $post_data['post_format'] ) ) {
  568.             set_post_format( $post_ID, $post_data['post_format'] );
  569.             unset( $post_data['tax_input']['post_format'] );
  570.         }
  571.  
  572.         $updated[] = wp_update_post( $post_data );
  573.  
  574.         if ( isset( $post_data['sticky'] ) && current_user_can( $ptype->cap->edit_others_posts ) ) {
  575.             if ( 'sticky' == $post_data['sticky'] )
  576.                 stick_post( $post_ID );
  577.             else
  578.                 unstick_post( $post_ID );
  579.         }
  580.     }
  581.  
  582.     return array( 'updated' => $updated, 'skipped' => $skipped, 'locked' => $locked );
  583. }
  584.  
  585. /**
  586.  * Default post information to use when populating the "Write Post" form.
  587.  *
  588.  * @since 2.0.0
  589.  *
  590.  * @param string $post_type    Optional. A post type string. Default 'post'.
  591.  * @param bool   $create_in_db Optional. Whether to insert the post into database. Default false.
  592.  * @return WP_Post Post object containing all the default post data as attributes
  593.  */
  594. function get_default_post_to_edit( $post_type = 'post', $create_in_db = false ) {
  595.     $post_title = '';
  596.     if ( !empty( $_REQUEST['post_title'] ) )
  597.         $post_title = esc_html( wp_unslash( $_REQUEST['post_title'] ));
  598.  
  599.     $post_content = '';
  600.     if ( !empty( $_REQUEST['content'] ) )
  601.         $post_content = esc_html( wp_unslash( $_REQUEST['content'] ));
  602.  
  603.     $post_excerpt = '';
  604.     if ( !empty( $_REQUEST['excerpt'] ) )
  605.         $post_excerpt = esc_html( wp_unslash( $_REQUEST['excerpt'] ));
  606.  
  607.     if ( $create_in_db ) {
  608.         $post_id = wp_insert_post( array( 'post_title' => __( 'Auto Draft' ), 'post_type' => $post_type, 'post_status' => 'auto-draft' ) );
  609.         $post = get_post( $post_id );
  610.         if ( current_theme_supports( 'post-formats' ) && post_type_supports( $post->post_type, 'post-formats' ) && get_option( 'default_post_format' ) )
  611.             set_post_format( $post, get_option( 'default_post_format' ) );
  612.     } else {
  613.         $post = new stdClass;
  614.         $post->ID = 0;
  615.         $post->post_author = '';
  616.         $post->post_date = '';
  617.         $post->post_date_gmt = '';
  618.         $post->post_password = '';
  619.         $post->post_name = '';
  620.         $post->post_type = $post_type;
  621.         $post->post_status = 'draft';
  622.         $post->to_ping = '';
  623.         $post->pinged = '';
  624.         $post->comment_status = get_default_comment_status( $post_type );
  625.         $post->ping_status = get_default_comment_status( $post_type, 'pingback' );
  626.         $post->post_pingback = get_option( 'default_pingback_flag' );
  627.         $post->post_category = get_option( 'default_category' );
  628.         $post->page_template = 'default';
  629.         $post->post_parent = 0;
  630.         $post->menu_order = 0;
  631.         $post = new WP_Post( $post );
  632.     }
  633.  
  634.     /**
  635.      * Filters the default post content initially used in the "Write Post" form.
  636.      *
  637.      * @since 1.5.0
  638.      *
  639.      * @param string  $post_content Default post content.
  640.      * @param WP_Post $post         Post object.
  641.      */
  642.     $post->post_content = apply_filters( 'default_content', $post_content, $post );
  643.  
  644.     /**
  645.      * Filters the default post title initially used in the "Write Post" form.
  646.      *
  647.      * @since 1.5.0
  648.      *
  649.      * @param string  $post_title Default post title.
  650.      * @param WP_Post $post       Post object.
  651.      */
  652.     $post->post_title = apply_filters( 'default_title', $post_title, $post );
  653.  
  654.     /**
  655.      * Filters the default post excerpt initially used in the "Write Post" form.
  656.      *
  657.      * @since 1.5.0
  658.      *
  659.      * @param string  $post_excerpt Default post excerpt.
  660.      * @param WP_Post $post         Post object.
  661.      */
  662.     $post->post_excerpt = apply_filters( 'default_excerpt', $post_excerpt, $post );
  663.  
  664.     return $post;
  665. }
  666.  
  667. /**
  668.  * Determine if a post exists based on title, content, and date
  669.  *
  670.  * @since 2.0.0
  671.  *
  672.  * @global wpdb $wpdb WordPress database abstraction object.
  673.  *
  674.  * @param string $title Post title
  675.  * @param string $content Optional post content
  676.  * @param string $date Optional post date
  677.  * @return int Post ID if post exists, 0 otherwise.
  678.  */
  679. function post_exists($title, $content = '', $date = '') {
  680.     global $wpdb;
  681.  
  682.     $post_title = wp_unslash( sanitize_post_field( 'post_title', $title, 0, 'db' ) );
  683.     $post_content = wp_unslash( sanitize_post_field( 'post_content', $content, 0, 'db' ) );
  684.     $post_date = wp_unslash( sanitize_post_field( 'post_date', $date, 0, 'db' ) );
  685.  
  686.     $query = "SELECT ID FROM $wpdb->posts WHERE 1=1";
  687.     $args = array();
  688.  
  689.     if ( !empty ( $date ) ) {
  690.         $query .= ' AND post_date = %s';
  691.         $args[] = $post_date;
  692.     }
  693.  
  694.     if ( !empty ( $title ) ) {
  695.         $query .= ' AND post_title = %s';
  696.         $args[] = $post_title;
  697.     }
  698.  
  699.     if ( !empty ( $content ) ) {
  700.         $query .= ' AND post_content = %s';
  701.         $args[] = $post_content;
  702.     }
  703.  
  704.     if ( !empty ( $args ) )
  705.         return (int) $wpdb->get_var( $wpdb->prepare($query, $args) );
  706.  
  707.     return 0;
  708. }
  709.  
  710. /**
  711.  * Creates a new post from the "Write Post" form using $_POST information.
  712.  *
  713.  * @since 2.1.0
  714.  *
  715.  * @global WP_User $current_user
  716.  *
  717.  * @return int|WP_Error
  718.  */
  719. function wp_write_post() {
  720.     if ( isset($_POST['post_type']) )
  721.         $ptype = get_post_type_object($_POST['post_type']);
  722.     else
  723.         $ptype = get_post_type_object('post');
  724.  
  725.     if ( !current_user_can( $ptype->cap->edit_posts ) ) {
  726.         if ( 'page' == $ptype->name )
  727.             return new WP_Error( 'edit_pages', __( 'Sorry, you are not allowed to create pages on this site.' ) );
  728.         else
  729.             return new WP_Error( 'edit_posts', __( 'Sorry, you are not allowed to create posts or drafts on this site.' ) );
  730.     }
  731.  
  732.     $_POST['post_mime_type'] = '';
  733.  
  734.     // Clear out any data in internal vars.
  735.     unset( $_POST['filter'] );
  736.  
  737.     // Edit don't write if we have a post id.
  738.     if ( isset( $_POST['post_ID'] ) )
  739.         return edit_post();
  740.  
  741.     if ( isset($_POST['visibility']) ) {
  742.         switch ( $_POST['visibility'] ) {
  743.             case 'public' :
  744.                 $_POST['post_password'] = '';
  745.                 break;
  746.             case 'password' :
  747.                 unset( $_POST['sticky'] );
  748.                 break;
  749.             case 'private' :
  750.                 $_POST['post_status'] = 'private';
  751.                 $_POST['post_password'] = '';
  752.                 unset( $_POST['sticky'] );
  753.                 break;
  754.         }
  755.     }
  756.  
  757.     $translated = _wp_translate_postdata( false );
  758.     if ( is_wp_error($translated) )
  759.         return $translated;
  760.  
  761.     // Create the post.
  762.     $post_ID = wp_insert_post( $_POST );
  763.     if ( is_wp_error( $post_ID ) )
  764.         return $post_ID;
  765.  
  766.     if ( empty($post_ID) )
  767.         return 0;
  768.  
  769.     add_meta( $post_ID );
  770.  
  771.     add_post_meta( $post_ID, '_edit_last', $GLOBALS['current_user']->ID );
  772.  
  773.     // Now that we have an ID we can fix any attachment anchor hrefs
  774.     _fix_attachment_links( $post_ID );
  775.  
  776.     wp_set_post_lock( $post_ID );
  777.  
  778.     return $post_ID;
  779. }
  780.  
  781. /**
  782.  * Calls wp_write_post() and handles the errors.
  783.  *
  784.  * @since 2.0.0
  785.  *
  786.  * @return int|null
  787.  */
  788. function write_post() {
  789.     $result = wp_write_post();
  790.     if ( is_wp_error( $result ) )
  791.         wp_die( $result->get_error_message() );
  792.     else
  793.         return $result;
  794. }
  795.  
  796. //
  797. // Post Meta
  798. //
  799.  
  800. /**
  801.  * Add post meta data defined in $_POST superglobal for post with given ID.
  802.  *
  803.  * @since 1.2.0
  804.  *
  805.  * @param int $post_ID
  806.  * @return int|bool
  807.  */
  808. function add_meta( $post_ID ) {
  809.     $post_ID = (int) $post_ID;
  810.  
  811.     $metakeyselect = isset($_POST['metakeyselect']) ? wp_unslash( trim( $_POST['metakeyselect'] ) ) : '';
  812.     $metakeyinput = isset($_POST['metakeyinput']) ? wp_unslash( trim( $_POST['metakeyinput'] ) ) : '';
  813.     $metavalue = isset($_POST['metavalue']) ? $_POST['metavalue'] : '';
  814.     if ( is_string( $metavalue ) )
  815.         $metavalue = trim( $metavalue );
  816.  
  817.     if ( ('0' === $metavalue || ! empty ( $metavalue ) ) && ( ( ( '#NONE#' != $metakeyselect ) && !empty ( $metakeyselect) ) || !empty ( $metakeyinput ) ) ) {
  818.         /*
  819.          * We have a key/value pair. If both the select and the input
  820.          * for the key have data, the input takes precedence.
  821.          */
  822.          if ( '#NONE#' != $metakeyselect )
  823.             $metakey = $metakeyselect;
  824.  
  825.         if ( $metakeyinput )
  826.             $metakey = $metakeyinput; // default
  827.  
  828.         if ( is_protected_meta( $metakey, 'post' ) || ! current_user_can( 'add_post_meta', $post_ID, $metakey ) )
  829.             return false;
  830.  
  831.         $metakey = wp_slash( $metakey );
  832.  
  833.         return add_post_meta( $post_ID, $metakey, $metavalue );
  834.     }
  835.  
  836.     return false;
  837. } // add_meta
  838.  
  839. /**
  840.  * Delete post meta data by meta ID.
  841.  *
  842.  * @since 1.2.0
  843.  *
  844.  * @param int $mid
  845.  * @return bool
  846.  */
  847. function delete_meta( $mid ) {
  848.     return delete_metadata_by_mid( 'post' , $mid );
  849. }
  850.  
  851. /**
  852.  * Get a list of previously defined keys.
  853.  *
  854.  * @since 1.2.0
  855.  *
  856.  * @global wpdb $wpdb WordPress database abstraction object.
  857.  *
  858.  * @return mixed
  859.  */
  860. function get_meta_keys() {
  861.     global $wpdb;
  862.  
  863.     $keys = $wpdb->get_col( "
  864.             SELECT meta_key
  865.             FROM $wpdb->postmeta
  866.             GROUP BY meta_key
  867.             ORDER BY meta_key" );
  868.  
  869.     return $keys;
  870. }
  871.  
  872. /**
  873.  * Get post meta data by meta ID.
  874.  *
  875.  * @since 2.1.0
  876.  *
  877.  * @param int $mid
  878.  * @return object|bool
  879.  */
  880. function get_post_meta_by_id( $mid ) {
  881.     return get_metadata_by_mid( 'post', $mid );
  882. }
  883.  
  884. /**
  885.  * Get meta data for the given post ID.
  886.  *
  887.  * @since 1.2.0
  888.  *
  889.  * @global wpdb $wpdb WordPress database abstraction object.
  890.  *
  891.  * @param int $postid
  892.  * @return mixed
  893.  */
  894. function has_meta( $postid ) {
  895.     global $wpdb;
  896.  
  897.     return $wpdb->get_results( $wpdb->prepare("SELECT meta_key, meta_value, meta_id, post_id
  898.             FROM $wpdb->postmeta WHERE post_id = %d
  899.             ORDER BY meta_key,meta_id", $postid), ARRAY_A );
  900. }
  901.  
  902. /**
  903.  * Update post meta data by meta ID.
  904.  *
  905.  * @since 1.2.0
  906.  *
  907.  * @param int    $meta_id
  908.  * @param string $meta_key Expect Slashed
  909.  * @param string $meta_value Expect Slashed
  910.  * @return bool
  911.  */
  912. function update_meta( $meta_id, $meta_key, $meta_value ) {
  913.     $meta_key = wp_unslash( $meta_key );
  914.     $meta_value = wp_unslash( $meta_value );
  915.  
  916.     return update_metadata_by_mid( 'post', $meta_id, $meta_value, $meta_key );
  917. }
  918.  
  919. //
  920. // Private
  921. //
  922.  
  923. /**
  924.  * Replace hrefs of attachment anchors with up-to-date permalinks.
  925.  *
  926.  * @since 2.3.0
  927.  * @access private
  928.  *
  929.  * @param int|object $post Post ID or post object.
  930.  * @return void|int|WP_Error Void if nothing fixed. 0 or WP_Error on update failure. The post ID on update success.
  931.  */
  932. function _fix_attachment_links( $post ) {
  933.     $post = get_post( $post, ARRAY_A );
  934.     $content = $post['post_content'];
  935.  
  936.     // Don't run if no pretty permalinks or post is not published, scheduled, or privately published.
  937.     if ( ! get_option( 'permalink_structure' ) || ! in_array( $post['post_status'], array( 'publish', 'future', 'private' ) ) )
  938.         return;
  939.  
  940.     // Short if there aren't any links or no '?attachment_id=' strings (strpos cannot be zero)
  941.     if ( !strpos($content, '?attachment_id=') || !preg_match_all( '/<a ([^>]+)>[\s\S]+?<\/a>/', $content, $link_matches ) )
  942.         return;
  943.  
  944.     $site_url = get_bloginfo('url');
  945.     $site_url = substr( $site_url, (int) strpos($site_url, '://') ); // remove the http(s)
  946.     $replace = '';
  947.  
  948.     foreach ( $link_matches[1] as $key => $value ) {
  949.         if ( !strpos($value, '?attachment_id=') || !strpos($value, 'wp-att-')
  950.             || !preg_match( '/href=(["\'])[^"\']*\?attachment_id=(\d+)[^"\']*\\1/', $value, $url_match )
  951.             || !preg_match( '/rel=["\'][^"\']*wp-att-(\d+)/', $value, $rel_match ) )
  952.                 continue;
  953.  
  954.         $quote = $url_match[1]; // the quote (single or double)
  955.         $url_id = (int) $url_match[2];
  956.         $rel_id = (int) $rel_match[1];
  957.  
  958.         if ( !$url_id || !$rel_id || $url_id != $rel_id || strpos($url_match[0], $site_url) === false )
  959.             continue;
  960.  
  961.         $link = $link_matches[0][$key];
  962.         $replace = str_replace( $url_match[0], 'href=' . $quote . get_attachment_link( $url_id ) . $quote, $link );
  963.  
  964.         $content = str_replace( $link, $replace, $content );
  965.     }
  966.  
  967.     if ( $replace ) {
  968.         $post['post_content'] = $content;
  969.         // Escape data pulled from DB.
  970.         $post = add_magic_quotes($post);
  971.  
  972.         return wp_update_post($post);
  973.     }
  974. }
  975.  
  976. /**
  977.  * Get all the possible statuses for a post_type
  978.  *
  979.  * @since 2.5.0
  980.  *
  981.  * @param string $type The post_type you want the statuses for
  982.  * @return array As array of all the statuses for the supplied post type
  983.  */
  984. function get_available_post_statuses($type = 'post') {
  985.     $stati = wp_count_posts($type);
  986.  
  987.     return array_keys(get_object_vars($stati));
  988. }
  989.  
  990. /**
  991.  * Run the wp query to fetch the posts for listing on the edit posts page
  992.  *
  993.  * @since 2.5.0
  994.  *
  995.  * @param array|bool $q Array of query variables to use to build the query or false to use $_GET superglobal.
  996.  * @return array
  997.  */
  998. function wp_edit_posts_query( $q = false ) {
  999.     if ( false === $q )
  1000.         $q = $_GET;
  1001.     $q['m'] = isset($q['m']) ? (int) $q['m'] : 0;
  1002.     $q['cat'] = isset($q['cat']) ? (int) $q['cat'] : 0;
  1003.     $post_stati  = get_post_stati();
  1004.  
  1005.     if ( isset($q['post_type']) && in_array( $q['post_type'], get_post_types() ) )
  1006.         $post_type = $q['post_type'];
  1007.     else
  1008.         $post_type = 'post';
  1009.  
  1010.     $avail_post_stati = get_available_post_statuses($post_type);
  1011.  
  1012.     if ( isset($q['post_status']) && in_array( $q['post_status'], $post_stati ) ) {
  1013.         $post_status = $q['post_status'];
  1014.         $perm = 'readable';
  1015.     }
  1016.  
  1017.     if ( isset( $q['orderby'] ) ) {
  1018.         $orderby = $q['orderby'];
  1019.     } elseif ( isset( $q['post_status'] ) && in_array( $q['post_status'], array( 'pending', 'draft' ) ) ) {
  1020.         $orderby = 'modified';
  1021.     }
  1022.  
  1023.     if ( isset( $q['order'] ) ) {
  1024.         $order = $q['order'];
  1025.     } elseif ( isset( $q['post_status'] ) && 'pending' == $q['post_status'] ) {
  1026.         $order = 'ASC';
  1027.     }
  1028.  
  1029.     $per_page = "edit_{$post_type}_per_page";
  1030.     $posts_per_page = (int) get_user_option( $per_page );
  1031.     if ( empty( $posts_per_page ) || $posts_per_page < 1 )
  1032.         $posts_per_page = 20;
  1033.  
  1034.     /**
  1035.      * Filters the number of items per page to show for a specific 'per_page' type.
  1036.      *
  1037.      * The dynamic portion of the hook name, `$post_type`, refers to the post type.
  1038.      *
  1039.      * Some examples of filter hooks generated here include: 'edit_attachment_per_page',
  1040.      * 'edit_post_per_page', 'edit_page_per_page', etc.
  1041.      *
  1042.      * @since 3.0.0
  1043.      *
  1044.      * @param int $posts_per_page Number of posts to display per page for the given post
  1045.      *                            type. Default 20.
  1046.      */
  1047.     $posts_per_page = apply_filters( "edit_{$post_type}_per_page", $posts_per_page );
  1048.  
  1049.     /**
  1050.      * Filters the number of posts displayed per page when specifically listing "posts".
  1051.      *
  1052.      * @since 2.8.0
  1053.      *
  1054.      * @param int    $posts_per_page Number of posts to be displayed. Default 20.
  1055.      * @param string $post_type      The post type.
  1056.      */
  1057.     $posts_per_page = apply_filters( 'edit_posts_per_page', $posts_per_page, $post_type );
  1058.  
  1059.     $query = compact('post_type', 'post_status', 'perm', 'order', 'orderby', 'posts_per_page');
  1060.  
  1061.     // Hierarchical types require special args.
  1062.     if ( is_post_type_hierarchical( $post_type ) && !isset($orderby) ) {
  1063.         $query['orderby'] = 'menu_order title';
  1064.         $query['order'] = 'asc';
  1065.         $query['posts_per_page'] = -1;
  1066.         $query['posts_per_archive_page'] = -1;
  1067.         $query['fields'] = 'id=>parent';
  1068.     }
  1069.  
  1070.     if ( ! empty( $q['show_sticky'] ) )
  1071.         $query['post__in'] = (array) get_option( 'sticky_posts' );
  1072.  
  1073.     wp( $query );
  1074.  
  1075.     return $avail_post_stati;
  1076. }
  1077.  
  1078. /**
  1079.  * Get all available post MIME types for a given post type.
  1080.  *
  1081.  * @since 2.5.0
  1082.  *
  1083.  * @global wpdb $wpdb WordPress database abstraction object.
  1084.  *
  1085.  * @param string $type
  1086.  * @return mixed
  1087.  */
  1088. function get_available_post_mime_types($type = 'attachment') {
  1089.     global $wpdb;
  1090.  
  1091.     $types = $wpdb->get_col($wpdb->prepare("SELECT DISTINCT post_mime_type FROM $wpdb->posts WHERE post_type = %s", $type));
  1092.     return $types;
  1093. }
  1094.  
  1095. /**
  1096.  * Get the query variables for the current attachments request.
  1097.  *
  1098.  * @since 4.2.0
  1099.  *
  1100.  * @param array|false $q Optional. Array of query variables to use to build the query or false
  1101.  *                       to use $_GET superglobal. Default false.
  1102.  * @return array The parsed query vars.
  1103.  */
  1104. function wp_edit_attachments_query_vars( $q = false ) {
  1105.     if ( false === $q ) {
  1106.         $q = $_GET;
  1107.     }
  1108.     $q['m']   = isset( $q['m'] ) ? (int) $q['m'] : 0;
  1109.     $q['cat'] = isset( $q['cat'] ) ? (int) $q['cat'] : 0;
  1110.     $q['post_type'] = 'attachment';
  1111.     $post_type = get_post_type_object( 'attachment' );
  1112.     $states = 'inherit';
  1113.     if ( current_user_can( $post_type->cap->read_private_posts ) ) {
  1114.         $states .= ',private';
  1115.     }
  1116.  
  1117.     $q['post_status'] = isset( $q['status'] ) && 'trash' == $q['status'] ? 'trash' : $states;
  1118.     $q['post_status'] = isset( $q['attachment-filter'] ) && 'trash' == $q['attachment-filter'] ? 'trash' : $states;
  1119.  
  1120.     $media_per_page = (int) get_user_option( 'upload_per_page' );
  1121.     if ( empty( $media_per_page ) || $media_per_page < 1 ) {
  1122.         $media_per_page = 20;
  1123.     }
  1124.  
  1125.     /**
  1126.      * Filters the number of items to list per page when listing media items.
  1127.      *
  1128.      * @since 2.9.0
  1129.      *
  1130.      * @param int $media_per_page Number of media to list. Default 20.
  1131.      */
  1132.     $q['posts_per_page'] = apply_filters( 'upload_per_page', $media_per_page );
  1133.  
  1134.     $post_mime_types = get_post_mime_types();
  1135.     if ( isset($q['post_mime_type']) && !array_intersect( (array) $q['post_mime_type'], array_keys($post_mime_types) ) ) {
  1136.         unset($q['post_mime_type']);
  1137.     }
  1138.  
  1139.     foreach ( array_keys( $post_mime_types ) as $type ) {
  1140.         if ( isset( $q['attachment-filter'] ) && "post_mime_type:$type" == $q['attachment-filter'] ) {
  1141.             $q['post_mime_type'] = $type;
  1142.             break;
  1143.         }
  1144.     }
  1145.  
  1146.     if ( isset( $q['detached'] ) || ( isset( $q['attachment-filter'] ) && 'detached' == $q['attachment-filter'] ) ) {
  1147.         $q['post_parent'] = 0;
  1148.     }
  1149.  
  1150.     // Filter query clauses to include filenames.
  1151.     if ( isset( $q['s'] ) ) {
  1152.         add_filter( 'posts_clauses', '_filter_query_attachment_filenames' );
  1153.     }
  1154.  
  1155.     return $q;
  1156. }
  1157.  
  1158. /**
  1159.  * Executes a query for attachments. An array of WP_Query arguments
  1160.  * can be passed in, which will override the arguments set by this function.
  1161.  *
  1162.  * @since 2.5.0
  1163.  *
  1164.  * @param array|false $q Array of query variables to use to build the query or false to use $_GET superglobal.
  1165.  * @return array
  1166.  */
  1167. function wp_edit_attachments_query( $q = false ) {
  1168.     wp( wp_edit_attachments_query_vars( $q ) );
  1169.  
  1170.     $post_mime_types = get_post_mime_types();
  1171.     $avail_post_mime_types = get_available_post_mime_types( 'attachment' );
  1172.  
  1173.     return array( $post_mime_types, $avail_post_mime_types );
  1174. }
  1175.  
  1176. /**
  1177.  * Returns the list of classes to be used by a meta box.
  1178.  *
  1179.  * @since 2.5.0
  1180.  *
  1181.  * @param string $id
  1182.  * @param string $page
  1183.  * @return string
  1184.  */
  1185. function postbox_classes( $id, $page ) {
  1186.     if ( isset( $_GET['edit'] ) && $_GET['edit'] == $id ) {
  1187.         $classes = array( '' );
  1188.     } elseif ( $closed = get_user_option('closedpostboxes_'.$page ) ) {
  1189.         if ( !is_array( $closed ) ) {
  1190.             $classes = array( '' );
  1191.         } else {
  1192.             $classes = in_array( $id, $closed ) ? array( 'closed' ) : array( '' );
  1193.         }
  1194.     } else {
  1195.         $classes = array( '' );
  1196.     }
  1197.  
  1198.     /**
  1199.      * Filters the postbox classes for a specific screen and screen ID combo.
  1200.      *
  1201.      * The dynamic portions of the hook name, `$page` and `$id`, refer to
  1202.      * the screen and screen ID, respectively.
  1203.      *
  1204.      * @since 3.2.0
  1205.      *
  1206.      * @param array $classes An array of postbox classes.
  1207.      */
  1208.     $classes = apply_filters( "postbox_classes_{$page}_{$id}", $classes );
  1209.     return implode( ' ', $classes );
  1210. }
  1211.  
  1212. /**
  1213.  * Get a sample permalink based off of the post name.
  1214.  *
  1215.  * @since 2.5.0
  1216.  *
  1217.  * @param int    $id    Post ID or post object.
  1218.  * @param string $title Optional. Title to override the post's current title when generating the post name. Default null.
  1219.  * @param string $name  Optional. Name to override the post name. Default null.
  1220.  * @return array Array containing the sample permalink with placeholder for the post name, and the post name.
  1221.  */
  1222. function get_sample_permalink($id, $title = null, $name = null) {
  1223.     $post = get_post( $id );
  1224.     if ( ! $post )
  1225.         return array( '', '' );
  1226.  
  1227.     $ptype = get_post_type_object($post->post_type);
  1228.  
  1229.     $original_status = $post->post_status;
  1230.     $original_date = $post->post_date;
  1231.     $original_name = $post->post_name;
  1232.  
  1233.     // Hack: get_permalink() would return ugly permalink for drafts, so we will fake that our post is published.
  1234.     if ( in_array( $post->post_status, array( 'draft', 'pending', 'future' ) ) ) {
  1235.         $post->post_status = 'publish';
  1236.         $post->post_name = sanitize_title($post->post_name ? $post->post_name : $post->post_title, $post->ID);
  1237.     }
  1238.  
  1239.     // If the user wants to set a new name -- override the current one
  1240.     // Note: if empty name is supplied -- use the title instead, see #6072
  1241.     if ( !is_null($name) )
  1242.         $post->post_name = sanitize_title($name ? $name : $title, $post->ID);
  1243.  
  1244.     $post->post_name = wp_unique_post_slug($post->post_name, $post->ID, $post->post_status, $post->post_type, $post->post_parent);
  1245.  
  1246.     $post->filter = 'sample';
  1247.  
  1248.     $permalink = get_permalink($post, true);
  1249.  
  1250.     // Replace custom post_type Token with generic pagename token for ease of use.
  1251.     $permalink = str_replace("%$post->post_type%", '%pagename%', $permalink);
  1252.  
  1253.     // Handle page hierarchy
  1254.     if ( $ptype->hierarchical ) {
  1255.         $uri = get_page_uri($post);
  1256.         if ( $uri ) {
  1257.             $uri = untrailingslashit($uri);
  1258.             $uri = strrev( stristr( strrev( $uri ), '/' ) );
  1259.             $uri = untrailingslashit($uri);
  1260.         }
  1261.  
  1262.         /** This filter is documented in wp-admin/edit-tag-form.php */
  1263.         $uri = apply_filters( 'editable_slug', $uri, $post );
  1264.         if ( !empty($uri) )
  1265.             $uri .= '/';
  1266.         $permalink = str_replace('%pagename%', "{$uri}%pagename%", $permalink);
  1267.     }
  1268.  
  1269.     /** This filter is documented in wp-admin/edit-tag-form.php */
  1270.     $permalink = array( $permalink, apply_filters( 'editable_slug', $post->post_name, $post ) );
  1271.     $post->post_status = $original_status;
  1272.     $post->post_date = $original_date;
  1273.     $post->post_name = $original_name;
  1274.     unset($post->filter);
  1275.  
  1276.     /**
  1277.      * Filters the sample permalink.
  1278.      *
  1279.      * @since 4.4.0
  1280.      *
  1281.      * @param array   $permalink Array containing the sample permalink with placeholder for the post name, and the post name.
  1282.      * @param int     $post_id   Post ID.
  1283.      * @param string  $title     Post title.
  1284.      * @param string  $name      Post name (slug).
  1285.      * @param WP_Post $post      Post object.
  1286.      */
  1287.     return apply_filters( 'get_sample_permalink', $permalink, $post->ID, $title, $name, $post );
  1288. }
  1289.  
  1290. /**
  1291.  * Returns the HTML of the sample permalink slug editor.
  1292.  *
  1293.  * @since 2.5.0
  1294.  *
  1295.  * @param int    $id        Post ID or post object.
  1296.  * @param string $new_title Optional. New title. Default null.
  1297.  * @param string $new_slug  Optional. New slug. Default null.
  1298.  * @return string The HTML of the sample permalink slug editor.
  1299.  */
  1300. function get_sample_permalink_html( $id, $new_title = null, $new_slug = null ) {
  1301.     $post = get_post( $id );
  1302.     if ( ! $post )
  1303.         return '';
  1304.  
  1305.     list($permalink, $post_name) = get_sample_permalink($post->ID, $new_title, $new_slug);
  1306.  
  1307.     $view_link = false;
  1308.     $preview_target = '';
  1309.  
  1310.     if ( current_user_can( 'read_post', $post->ID ) ) {
  1311.         if ( 'draft' === $post->post_status || empty( $post->post_name ) ) {
  1312.             $view_link = get_preview_post_link( $post );
  1313.             $preview_target = " target='wp-preview-{$post->ID}'";
  1314.         } else {
  1315.             if ( 'publish' === $post->post_status || 'attachment' === $post->post_type ) {
  1316.                 $view_link = get_permalink( $post );
  1317.             } else {
  1318.                 // Allow non-published (private, future) to be viewed at a pretty permalink, in case $post->post_name is set
  1319.                 $view_link = str_replace( array( '%pagename%', '%postname%' ), $post->post_name, $permalink );
  1320.             }
  1321.         }
  1322.     }
  1323.  
  1324.     // Permalinks without a post/page name placeholder don't have anything to edit
  1325.     if ( false === strpos( $permalink, '%postname%' ) && false === strpos( $permalink, '%pagename%' ) ) {
  1326.         $return = '<strong>' . __( 'Permalink:' ) . "</strong>\n";
  1327.  
  1328.         if ( false !== $view_link ) {
  1329.             $display_link = urldecode( $view_link );
  1330.             $return .= '<a id="sample-permalink" href="' . esc_url( $view_link ) . '"' . $preview_target . '>' . esc_html( $display_link ) . "</a>\n";
  1331.         } else {
  1332.             $return .= '<span id="sample-permalink">' . $permalink . "</span>\n";
  1333.         }
  1334.  
  1335.         // Encourage a pretty permalink setting
  1336.         if ( '' == get_option( 'permalink_structure' ) && current_user_can( 'manage_options' ) && !( 'page' == get_option('show_on_front') && $id == get_option('page_on_front') ) ) {
  1337.             $return .= '<span id="change-permalinks"><a href="options-permalink.php" class="button button-small" target="_blank">' . __('Change Permalinks') . "</a></span>\n";
  1338.         }
  1339.     } else {
  1340.         if ( mb_strlen( $post_name ) > 34 ) {
  1341.             $post_name_abridged = mb_substr( $post_name, 0, 16 ) . '…' . mb_substr( $post_name, -16 );
  1342.         } else {
  1343.             $post_name_abridged = $post_name;
  1344.         }
  1345.  
  1346.         $post_name_html = '<span id="editable-post-name">' . esc_html( $post_name_abridged ) . '</span>';
  1347.         $display_link = str_replace( array( '%pagename%', '%postname%' ), $post_name_html, esc_html( urldecode( $permalink ) ) );
  1348.  
  1349.         $return = '<strong>' . __( 'Permalink:' ) . "</strong>\n";
  1350.         $return .= '<span id="sample-permalink"><a href="' . esc_url( $view_link ) . '"' . $preview_target . '>' . $display_link . "</a></span>\n";
  1351.         $return .= '‎'; // Fix bi-directional text display defect in RTL languages.
  1352.         $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";
  1353.         $return .= '<span id="editable-post-name-full">' . esc_html( $post_name ) . "</span>\n";
  1354.     }
  1355.  
  1356.     /**
  1357.      * Filters the sample permalink HTML markup.
  1358.      *
  1359.      * @since 2.9.0
  1360.      * @since 4.4.0 Added `$post` parameter.
  1361.      *
  1362.      * @param string  $return    Sample permalink HTML markup.
  1363.      * @param int     $post_id   Post ID.
  1364.      * @param string  $new_title New sample permalink title.
  1365.      * @param string  $new_slug  New sample permalink slug.
  1366.      * @param WP_Post $post      Post object.
  1367.      */
  1368.     $return = apply_filters( 'get_sample_permalink_html', $return, $post->ID, $new_title, $new_slug, $post );
  1369.  
  1370.     return $return;
  1371. }
  1372.  
  1373. /**
  1374.  * Output HTML for the post thumbnail meta-box.
  1375.  *
  1376.  * @since 2.9.0
  1377.  *
  1378.  * @param int $thumbnail_id ID of the attachment used for thumbnail
  1379.  * @param mixed $post The post ID or object associated with the thumbnail, defaults to global $post.
  1380.  * @return string html
  1381.  */
  1382. function _wp_post_thumbnail_html( $thumbnail_id = null, $post = null ) {
  1383.     $_wp_additional_image_sizes = wp_get_additional_image_sizes();
  1384.  
  1385.     $post               = get_post( $post );
  1386.     $post_type_object   = get_post_type_object( $post->post_type );
  1387.     $set_thumbnail_link = '<p class="hide-if-no-js"><a href="%s" id="set-post-thumbnail"%s class="thickbox">%s</a></p>';
  1388.     $upload_iframe_src  = get_upload_iframe_src( 'image', $post->ID );
  1389.  
  1390.     $content = sprintf( $set_thumbnail_link,
  1391.         esc_url( $upload_iframe_src ),
  1392.         '', // Empty when there's no featured image set, `aria-describedby` attribute otherwise.
  1393.         esc_html( $post_type_object->labels->set_featured_image )
  1394.     );
  1395.  
  1396.     if ( $thumbnail_id && get_post( $thumbnail_id ) ) {
  1397.         $size = isset( $_wp_additional_image_sizes['post-thumbnail'] ) ? 'post-thumbnail' : array( 266, 266 );
  1398.  
  1399.         /**
  1400.          * Filters the size used to display the post thumbnail image in the 'Featured Image' meta box.
  1401.          *
  1402.          * Note: When a theme adds 'post-thumbnail' support, a special 'post-thumbnail'
  1403.          * image size is registered, which differs from the 'thumbnail' image size
  1404.          * managed via the Settings > Media screen. See the `$size` parameter description
  1405.          * for more information on default values.
  1406.          *
  1407.          * @since 4.4.0
  1408.          *
  1409.          * @param string|array $size         Post thumbnail image size to display in the meta box. Accepts any valid
  1410.          *                                   image size, or an array of width and height values in pixels (in that order).
  1411.          *                                   If the 'post-thumbnail' size is set, default is 'post-thumbnail'. Otherwise,
  1412.          *                                   default is an array with 266 as both the height and width values.
  1413.          * @param int          $thumbnail_id Post thumbnail attachment ID.
  1414.          * @param WP_Post      $post         The post object associated with the thumbnail.
  1415.          */
  1416.         $size = apply_filters( 'admin_post_thumbnail_size', $size, $thumbnail_id, $post );
  1417.  
  1418.         $thumbnail_html = wp_get_attachment_image( $thumbnail_id, $size );
  1419.  
  1420.         if ( ! empty( $thumbnail_html ) ) {
  1421.             $content = sprintf( $set_thumbnail_link,
  1422.                 esc_url( $upload_iframe_src ),
  1423.                 ' aria-describedby="set-post-thumbnail-desc"',
  1424.                 $thumbnail_html
  1425.             );
  1426.             $content .= '<p class="hide-if-no-js howto" id="set-post-thumbnail-desc">' . __( 'Click the image to edit or update' ) . '</p>';
  1427.             $content .= '<p class="hide-if-no-js"><a href="#" id="remove-post-thumbnail">' . esc_html( $post_type_object->labels->remove_featured_image ) . '</a></p>';
  1428.         }
  1429.     }
  1430.  
  1431.     $content .= '<input type="hidden" id="_thumbnail_id" name="_thumbnail_id" value="' . esc_attr( $thumbnail_id ? $thumbnail_id : '-1' ) . '" />';
  1432.  
  1433.     /**
  1434.      * Filters the admin post thumbnail HTML markup to return.
  1435.      *
  1436.      * @since 2.9.0
  1437.      * @since 3.5.0 Added the `$post_id` parameter.
  1438.      * @since 4.6.0 Added the `$thumbnail_id` parameter.
  1439.      *
  1440.      * @param string $content      Admin post thumbnail HTML markup.
  1441.      * @param int    $post_id      Post ID.
  1442.      * @param int    $thumbnail_id Thumbnail ID.
  1443.      */
  1444.     return apply_filters( 'admin_post_thumbnail_html', $content, $post->ID, $thumbnail_id );
  1445. }
  1446.  
  1447. /**
  1448.  * Check to see if the post is currently being edited by another user.
  1449.  *
  1450.  * @since 2.5.0
  1451.  *
  1452.  * @param int $post_id ID of the post to check for editing.
  1453.  * @return int|false ID of the user with lock. False if the post does not exist, post is not locked,
  1454.  *                   the user with lock does not exist, or the post is locked by current user.
  1455.  */
  1456. function wp_check_post_lock( $post_id ) {
  1457.     if ( ! $post = get_post( $post_id ) ) {
  1458.         return false;
  1459.     }
  1460.  
  1461.     if ( ! $lock = get_post_meta( $post->ID, '_edit_lock', true ) ) {
  1462.         return false;
  1463.     }
  1464.  
  1465.     $lock = explode( ':', $lock );
  1466.     $time = $lock[0];
  1467.     $user = isset( $lock[1] ) ? $lock[1] : get_post_meta( $post->ID, '_edit_last', true );
  1468.  
  1469.     if ( ! get_userdata( $user ) ) {
  1470.         return false;
  1471.     }
  1472.  
  1473.     /** This filter is documented in wp-admin/includes/ajax-actions.php */
  1474.     $time_window = apply_filters( 'wp_check_post_lock_window', 150 );
  1475.  
  1476.     if ( $time && $time > time() - $time_window && $user != get_current_user_id() ) {
  1477.         return $user;
  1478.     }
  1479.  
  1480.     return false;
  1481. }
  1482.  
  1483. /**
  1484.  * Mark the post as currently being edited by the current user
  1485.  *
  1486.  * @since 2.5.0
  1487.  *
  1488.  * @param int $post_id ID of the post being edited.
  1489.  * @return array|false Array of the lock time and user ID. False if the post does not exist, or
  1490.  *                     there is no current user.
  1491.  */
  1492. function wp_set_post_lock( $post_id ) {
  1493.     if ( ! $post = get_post( $post_id ) ) {
  1494.         return false;
  1495.     }
  1496.  
  1497.     if ( 0 == ( $user_id = get_current_user_id() ) ) {
  1498.         return false;
  1499.     }
  1500.  
  1501.     $now = time();
  1502.     $lock = "$now:$user_id";
  1503.  
  1504.     update_post_meta( $post->ID, '_edit_lock', $lock );
  1505.  
  1506.     return array( $now, $user_id );
  1507. }
  1508.  
  1509. /**
  1510.  * Outputs the HTML for the notice to say that someone else is editing or has taken over editing of this post.
  1511.  *
  1512.  * @since 2.8.5
  1513.  * @return none
  1514.  */
  1515. function _admin_notice_post_locked() {
  1516.     if ( ! $post = get_post() )
  1517.         return;
  1518.  
  1519.     $user = null;
  1520.     if (  $user_id = wp_check_post_lock( $post->ID ) )
  1521.         $user = get_userdata( $user_id );
  1522.  
  1523.     if ( $user ) {
  1524.  
  1525.         /**
  1526.          * Filters whether to show the post locked dialog.
  1527.          *
  1528.          * Returning a falsey value to the filter will short-circuit displaying the dialog.
  1529.          *
  1530.          * @since 3.6.0
  1531.          *
  1532.          * @param bool         $display Whether to display the dialog. Default true.
  1533.          * @param WP_Post      $post    Post object.
  1534.          * @param WP_User|bool $user    WP_User object on success, false otherwise.
  1535.          */
  1536.         if ( ! apply_filters( 'show_post_locked_dialog', true, $post, $user ) )
  1537.             return;
  1538.  
  1539.         $locked = true;
  1540.     } else {
  1541.         $locked = false;
  1542.     }
  1543.  
  1544.     if ( $locked && ( $sendback = wp_get_referer() ) &&
  1545.         false === strpos( $sendback, 'post.php' ) && false === strpos( $sendback, 'post-new.php' ) ) {
  1546.  
  1547.         $sendback_text = __('Go back');
  1548.     } else {
  1549.         $sendback = admin_url( 'edit.php' );
  1550.  
  1551.         if ( 'post' != $post->post_type )
  1552.             $sendback = add_query_arg( 'post_type', $post->post_type, $sendback );
  1553.  
  1554.         $sendback_text = get_post_type_object( $post->post_type )->labels->all_items;
  1555.     }
  1556.  
  1557.     $hidden = $locked ? '' : ' hidden';
  1558.  
  1559.     ?>
  1560.     <div id="post-lock-dialog" class="notification-dialog-wrap<?php echo $hidden; ?>">
  1561.     <div class="notification-dialog-background"></div>
  1562.     <div class="notification-dialog">
  1563.     <?php
  1564.  
  1565.     if ( $locked ) {
  1566.         $query_args = array();
  1567.         if ( get_post_type_object( $post->post_type )->public ) {
  1568.             if ( 'publish' == $post->post_status || $user->ID != $post->post_author ) {
  1569.                 // Latest content is in autosave
  1570.                 $nonce = wp_create_nonce( 'post_preview_' . $post->ID );
  1571.                 $query_args['preview_id'] = $post->ID;
  1572.                 $query_args['preview_nonce'] = $nonce;
  1573.             }
  1574.         }
  1575.  
  1576.         $preview_link = get_preview_post_link( $post->ID, $query_args );
  1577.  
  1578.         /**
  1579.          * Filters whether to allow the post lock to be overridden.
  1580.          *
  1581.          * Returning a falsey value to the filter will disable the ability
  1582.          * to override the post lock.
  1583.          *
  1584.          * @since 3.6.0
  1585.          *
  1586.          * @param bool    $override Whether to allow overriding post locks. Default true.
  1587.          * @param WP_Post $post     Post object.
  1588.          * @param WP_User $user     User object.
  1589.          */
  1590.         $override = apply_filters( 'override_post_lock', true, $post, $user );
  1591.         $tab_last = $override ? '' : ' wp-tab-last';
  1592.  
  1593.         ?>
  1594.         <div class="post-locked-message">
  1595.         <div class="post-locked-avatar"><?php echo get_avatar( $user->ID, 64 ); ?></div>
  1596.         <p class="currently-editing wp-tab-first" tabindex="0">
  1597.         <?php
  1598.             if ( $override ) {
  1599.                 /* translators: %s: user's display name */
  1600.                 printf( __( '%s is already editing this post. Do you want to take over?' ), esc_html( $user->display_name ) );
  1601.             } else {
  1602.                 /* translators: %s: user's display name */
  1603.                 printf( __( '%s is already editing this post.' ), esc_html( $user->display_name ) );
  1604.             }
  1605.         ?>
  1606.         </p>
  1607.         <?php
  1608.         /**
  1609.          * Fires inside the post locked dialog before the buttons are displayed.
  1610.          *
  1611.          * @since 3.6.0
  1612.          *
  1613.          * @param WP_Post $post Post object.
  1614.          */
  1615.         do_action( 'post_locked_dialog', $post );
  1616.         ?>
  1617.         <p>
  1618.         <a class="button" href="<?php echo esc_url( $sendback ); ?>"><?php echo $sendback_text; ?></a>
  1619.         <?php if ( $preview_link ) { ?>
  1620.         <a class="button<?php echo $tab_last; ?>" href="<?php echo esc_url( $preview_link ); ?>"><?php _e('Preview'); ?></a>
  1621.         <?php
  1622.         }
  1623.  
  1624.         // Allow plugins to prevent some users overriding the post lock
  1625.         if ( $override ) {
  1626.             ?>
  1627.             <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>
  1628.             <?php
  1629.         }
  1630.  
  1631.         ?>
  1632.         </p>
  1633.         </div>
  1634.         <?php
  1635.     } else {
  1636.         ?>
  1637.         <div class="post-taken-over">
  1638.             <div class="post-locked-avatar"></div>
  1639.             <p class="wp-tab-first" tabindex="0">
  1640.             <span class="currently-editing"></span><br />
  1641.             <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…' ); ?></span>
  1642.             <span class="locked-saved hidden"><?php _e('Your latest changes were saved as a revision.'); ?></span>
  1643.             </p>
  1644.             <?php
  1645.             /**
  1646.              * Fires inside the dialog displayed when a user has lost the post lock.
  1647.              *
  1648.              * @since 3.6.0
  1649.              *
  1650.              * @param WP_Post $post Post object.
  1651.              */
  1652.             do_action( 'post_lock_lost_dialog', $post );
  1653.             ?>
  1654.             <p><a class="button button-primary wp-tab-last" href="<?php echo esc_url( $sendback ); ?>"><?php echo $sendback_text; ?></a></p>
  1655.         </div>
  1656.         <?php
  1657.     }
  1658.  
  1659.     ?>
  1660.     </div>
  1661.     </div>
  1662.     <?php
  1663. }
  1664.  
  1665. /**
  1666.  * Creates autosave data for the specified post from $_POST data.
  1667.  *
  1668.  * @since 2.6.0
  1669.  *
  1670.  * @param mixed $post_data Associative array containing the post data or int post ID.
  1671.  * @return mixed The autosave revision ID. WP_Error or 0 on error.
  1672.  */
  1673. function wp_create_post_autosave( $post_data ) {
  1674.     if ( is_numeric( $post_data ) ) {
  1675.         $post_id = $post_data;
  1676.         $post_data = $_POST;
  1677.     } else {
  1678.         $post_id = (int) $post_data['post_ID'];
  1679.     }
  1680.  
  1681.     $post_data = _wp_translate_postdata( true, $post_data );
  1682.     if ( is_wp_error( $post_data ) )
  1683.         return $post_data;
  1684.  
  1685.     $post_author = get_current_user_id();
  1686.  
  1687.     // Store one autosave per author. If there is already an autosave, overwrite it.
  1688.     if ( $old_autosave = wp_get_post_autosave( $post_id, $post_author ) ) {
  1689.         $new_autosave = _wp_post_revision_data( $post_data, true );
  1690.         $new_autosave['ID'] = $old_autosave->ID;
  1691.         $new_autosave['post_author'] = $post_author;
  1692.  
  1693.         // If the new autosave has the same content as the post, delete the autosave.
  1694.         $post = get_post( $post_id );
  1695.         $autosave_is_different = false;
  1696.         foreach ( array_intersect( array_keys( $new_autosave ), array_keys( _wp_post_revision_fields( $post ) ) ) as $field ) {
  1697.             if ( normalize_whitespace( $new_autosave[ $field ] ) != normalize_whitespace( $post->$field ) ) {
  1698.                 $autosave_is_different = true;
  1699.                 break;
  1700.             }
  1701.         }
  1702.  
  1703.         if ( ! $autosave_is_different ) {
  1704.             wp_delete_post_revision( $old_autosave->ID );
  1705.             return 0;
  1706.         }
  1707.  
  1708.         /**
  1709.          * Fires before an autosave is stored.
  1710.          *
  1711.          * @since 4.1.0
  1712.          *
  1713.          * @param array $new_autosave Post array - the autosave that is about to be saved.
  1714.          */
  1715.         do_action( 'wp_creating_autosave', $new_autosave );
  1716.  
  1717.         return wp_update_post( $new_autosave );
  1718.     }
  1719.  
  1720.     // _wp_put_post_revision() expects unescaped.
  1721.     $post_data = wp_unslash( $post_data );
  1722.  
  1723.     // Otherwise create the new autosave as a special post revision
  1724.     return _wp_put_post_revision( $post_data, true );
  1725. }
  1726.  
  1727. /**
  1728.  * Saves a draft or manually autosaves for the purpose of showing a post preview.
  1729.  *
  1730.  * @since 2.7.0
  1731.  *
  1732.  * @return string URL to redirect to show the preview.
  1733.  */
  1734. function post_preview() {
  1735.  
  1736.     $post_ID = (int) $_POST['post_ID'];
  1737.     $_POST['ID'] = $post_ID;
  1738.  
  1739.     if ( ! $post = get_post( $post_ID ) ) {
  1740.         wp_die( __( 'Sorry, you are not allowed to edit this post.' ) );
  1741.     }
  1742.  
  1743.     if ( ! current_user_can( 'edit_post', $post->ID ) ) {
  1744.         wp_die( __( 'Sorry, you are not allowed to edit this post.' ) );
  1745.     }
  1746.  
  1747.     $is_autosave = false;
  1748.  
  1749.     if ( ! wp_check_post_lock( $post->ID ) && get_current_user_id() == $post->post_author && ( 'draft' == $post->post_status || 'auto-draft' == $post->post_status ) ) {
  1750.         $saved_post_id = edit_post();
  1751.     } else {
  1752.         $is_autosave = true;
  1753.  
  1754.         if ( isset( $_POST['post_status'] ) && 'auto-draft' == $_POST['post_status'] )
  1755.             $_POST['post_status'] = 'draft';
  1756.  
  1757.         $saved_post_id = wp_create_post_autosave( $post->ID );
  1758.     }
  1759.  
  1760.     if ( is_wp_error( $saved_post_id ) )
  1761.         wp_die( $saved_post_id->get_error_message() );
  1762.  
  1763.     $query_args = array();
  1764.  
  1765.     if ( $is_autosave && $saved_post_id ) {
  1766.         $query_args['preview_id'] = $post->ID;
  1767.         $query_args['preview_nonce'] = wp_create_nonce( 'post_preview_' . $post->ID );
  1768.  
  1769.         if ( isset( $_POST['post_format'] ) ) {
  1770.             $query_args['post_format'] = empty( $_POST['post_format'] ) ? 'standard' : sanitize_key( $_POST['post_format'] );
  1771.         }
  1772.  
  1773.         if ( isset( $_POST['_thumbnail_id'] ) ) {
  1774.             $query_args['_thumbnail_id'] = ( intval( $_POST['_thumbnail_id'] ) <= 0 ) ? '-1' : intval( $_POST['_thumbnail_id'] );
  1775.         }
  1776.     }
  1777.  
  1778.     return get_preview_post_link( $post, $query_args );
  1779. }
  1780.  
  1781. /**
  1782.  * Save a post submitted with XHR
  1783.  *
  1784.  * Intended for use with heartbeat and autosave.js
  1785.  *
  1786.  * @since 3.9.0
  1787.  *
  1788.  * @param array $post_data Associative array of the submitted post data.
  1789.  * @return mixed The value 0 or WP_Error on failure. The saved post ID on success.
  1790.  *               The ID can be the draft post_id or the autosave revision post_id.
  1791.  */
  1792. function wp_autosave( $post_data ) {
  1793.     // Back-compat
  1794.     if ( ! defined( 'DOING_AUTOSAVE' ) )
  1795.         define( 'DOING_AUTOSAVE', true );
  1796.  
  1797.     $post_id = (int) $post_data['post_id'];
  1798.     $post_data['ID'] = $post_data['post_ID'] = $post_id;
  1799.  
  1800.     if ( false === wp_verify_nonce( $post_data['_wpnonce'], 'update-post_' . $post_id ) ) {
  1801.         return new WP_Error( 'invalid_nonce', __( 'Error while saving.' ) );
  1802.     }
  1803.  
  1804.     $post = get_post( $post_id );
  1805.  
  1806.     if ( ! current_user_can( 'edit_post', $post->ID ) ) {
  1807.         return new WP_Error( 'edit_posts', __( 'Sorry, you are not allowed to edit this item.' ) );
  1808.     }
  1809.  
  1810.     if ( 'auto-draft' == $post->post_status )
  1811.         $post_data['post_status'] = 'draft';
  1812.  
  1813.     if ( $post_data['post_type'] != 'page' && ! empty( $post_data['catslist'] ) )
  1814.         $post_data['post_category'] = explode( ',', $post_data['catslist'] );
  1815.  
  1816.     if ( ! wp_check_post_lock( $post->ID ) && get_current_user_id() == $post->post_author && ( 'auto-draft' == $post->post_status || 'draft' == $post->post_status ) ) {
  1817.         // Drafts and auto-drafts are just overwritten by autosave for the same user if the post is not locked
  1818.         return edit_post( wp_slash( $post_data ) );
  1819.     } else {
  1820.         // Non drafts or other users drafts are not overwritten. The autosave is stored in a special post revision for each user.
  1821.         return wp_create_post_autosave( wp_slash( $post_data ) );
  1822.     }
  1823. }
  1824.  
  1825. /**
  1826.  * Redirect to previous page.
  1827.  *
  1828.  * @param int $post_id Optional. Post ID.
  1829.  */
  1830. function redirect_post($post_id = '') {
  1831.     if ( isset($_POST['save']) || isset($_POST['publish']) ) {
  1832.         $status = get_post_status( $post_id );
  1833.  
  1834.         if ( isset( $_POST['publish'] ) ) {
  1835.             switch ( $status ) {
  1836.                 case 'pending':
  1837.                     $message = 8;
  1838.                     break;
  1839.                 case 'future':
  1840.                     $message = 9;
  1841.                     break;
  1842.                 default:
  1843.                     $message = 6;
  1844.             }
  1845.         } else {
  1846.             $message = 'draft' == $status ? 10 : 1;
  1847.         }
  1848.  
  1849.         $location = add_query_arg( 'message', $message, get_edit_post_link( $post_id, 'url' ) );
  1850.     } elseif ( isset($_POST['addmeta']) && $_POST['addmeta'] ) {
  1851.         $location = add_query_arg( 'message', 2, wp_get_referer() );
  1852.         $location = explode('#', $location);
  1853.         $location = $location[0] . '#postcustom';
  1854.     } elseif ( isset($_POST['deletemeta']) && $_POST['deletemeta'] ) {
  1855.         $location = add_query_arg( 'message', 3, wp_get_referer() );
  1856.         $location = explode('#', $location);
  1857.         $location = $location[0] . '#postcustom';
  1858.     } else {
  1859.         $location = add_query_arg( 'message', 4, get_edit_post_link( $post_id, 'url' ) );
  1860.     }
  1861.  
  1862.     /**
  1863.      * Filters the post redirect destination URL.
  1864.      *
  1865.      * @since 2.9.0
  1866.      *
  1867.      * @param string $location The destination URL.
  1868.      * @param int    $post_id  The post ID.
  1869.      */
  1870.     wp_redirect( apply_filters( 'redirect_post_location', $location, $post_id ) );
  1871.     exit;
  1872. }
  1873.