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