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