]> scripts.mit.edu Git - autoinstalls/wordpress.git/blob - wp-admin/includes/post.php
Wordpress 3.5.2-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( $ptype->cap->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         if ( !isset($post_data['user_ID']) )
56                 $post_data['user_ID'] = $GLOBALS['user_ID'];
57
58         if (!empty ( $post_data['post_author_override'] ) ) {
59                 $post_data['post_author'] = (int) $post_data['post_author_override'];
60         } else {
61                 if (!empty ( $post_data['post_author'] ) ) {
62                         $post_data['post_author'] = (int) $post_data['post_author'];
63                 } else {
64                         $post_data['post_author'] = (int) $post_data['user_ID'];
65                 }
66         }
67
68         if ( isset( $post_data['user_ID'] ) && ( $post_data['post_author'] != $post_data['user_ID'] )
69                  && ! current_user_can( $ptype->cap->edit_others_posts ) ) {
70                 if ( $update ) {
71                         if ( 'page' == $post_data['post_type'] )
72                                 return new WP_Error( 'edit_others_pages', __( 'You are not allowed to edit pages as this user.' ) );
73                         else
74                                 return new WP_Error( 'edit_others_posts', __( 'You are not allowed to edit posts as this user.' ) );
75                 } else {
76                         if ( 'page' == $post_data['post_type'] )
77                                 return new WP_Error( 'edit_others_pages', __( 'You are not allowed to create pages as this user.' ) );
78                         else
79                                 return new WP_Error( 'edit_others_posts', __( 'You are not allowed to create posts as this user.' ) );
80                 }
81         }
82
83         if ( ! empty( $post_data['post_status'] ) )
84                 $post_data['post_status'] = sanitize_key( $post_data['post_status'] );
85
86         // What to do based on which button they pressed
87         if ( isset($post_data['saveasdraft']) && '' != $post_data['saveasdraft'] )
88                 $post_data['post_status'] = 'draft';
89         if ( isset($post_data['saveasprivate']) && '' != $post_data['saveasprivate'] )
90                 $post_data['post_status'] = 'private';
91         if ( isset($post_data['publish']) && ( '' != $post_data['publish'] ) && ( !isset($post_data['post_status']) || $post_data['post_status'] != 'private' ) )
92                 $post_data['post_status'] = 'publish';
93         if ( isset($post_data['advanced']) && '' != $post_data['advanced'] )
94                 $post_data['post_status'] = 'draft';
95         if ( isset($post_data['pending']) && '' != $post_data['pending'] )
96                 $post_data['post_status'] = 'pending';
97
98         if ( isset( $post_data['ID'] ) )
99                 $post_id = $post_data['ID'];
100         else
101                 $post_id = false;
102         $previous_status = $post_id ? get_post_field( 'post_status', $post_id ) : false;
103
104         $published_statuses = array( 'publish', 'future' );
105
106         // Posts 'submitted for approval' present are submitted to $_POST the same as if they were being published.
107         // Change status from 'publish' to 'pending' if user lacks permissions to publish or to resave published posts.
108         if ( isset($post_data['post_status']) && (in_array( $post_data['post_status'], $published_statuses ) && !current_user_can( $ptype->cap->publish_posts )) )
109                 if ( ! in_array( $previous_status, $published_statuses ) || !current_user_can( 'edit_post', $post_id ) )
110                         $post_data['post_status'] = 'pending';
111
112         if ( ! isset($post_data['post_status']) )
113                 $post_data['post_status'] = $previous_status;
114
115         if (!isset( $post_data['comment_status'] ))
116                 $post_data['comment_status'] = 'closed';
117
118         if (!isset( $post_data['ping_status'] ))
119                 $post_data['ping_status'] = 'closed';
120
121         foreach ( array('aa', 'mm', 'jj', 'hh', 'mn') as $timeunit ) {
122                 if ( !empty( $post_data['hidden_' . $timeunit] ) && $post_data['hidden_' . $timeunit] != $post_data[$timeunit] ) {
123                         $post_data['edit_date'] = '1';
124                         break;
125                 }
126         }
127
128         if ( !empty( $post_data['edit_date'] ) ) {
129                 $aa = $post_data['aa'];
130                 $mm = $post_data['mm'];
131                 $jj = $post_data['jj'];
132                 $hh = $post_data['hh'];
133                 $mn = $post_data['mn'];
134                 $ss = $post_data['ss'];
135                 $aa = ($aa <= 0 ) ? date('Y') : $aa;
136                 $mm = ($mm <= 0 ) ? date('n') : $mm;
137                 $jj = ($jj > 31 ) ? 31 : $jj;
138                 $jj = ($jj <= 0 ) ? date('j') : $jj;
139                 $hh = ($hh > 23 ) ? $hh -24 : $hh;
140                 $mn = ($mn > 59 ) ? $mn -60 : $mn;
141                 $ss = ($ss > 59 ) ? $ss -60 : $ss;
142                 $post_data['post_date'] = sprintf( "%04d-%02d-%02d %02d:%02d:%02d", $aa, $mm, $jj, $hh, $mn, $ss );
143                 $valid_date = wp_checkdate( $mm, $jj, $aa, $post_data['post_date'] );
144                 if ( !$valid_date ) {
145                         return new WP_Error( 'invalid_date', __( 'Whoops, the provided date is invalid.' ) );
146                 }
147                 $post_data['post_date_gmt'] = get_gmt_from_date( $post_data['post_date'] );
148         }
149
150         return $post_data;
151 }
152
153 /**
154  * Update an existing post with values provided in $_POST.
155  *
156  * @since 1.5.0
157  *
158  * @param array $post_data Optional.
159  * @return int Post ID.
160  */
161 function edit_post( $post_data = null ) {
162
163         if ( empty($post_data) )
164                 $post_data = &$_POST;
165
166         // Clear out any data in internal vars.
167         unset( $post_data['filter'] );
168
169         $post_ID = (int) $post_data['post_ID'];
170         $post = get_post( $post_ID );
171         $post_data['post_type'] = $post->post_type;
172         $post_data['post_mime_type'] = $post->post_mime_type;
173
174         $ptype = get_post_type_object($post_data['post_type']);
175         if ( !current_user_can( $ptype->cap->edit_post, $post_ID ) ) {
176                 if ( 'page' == $post_data['post_type'] )
177                         wp_die( __('You are not allowed to edit this page.' ));
178                 else
179                         wp_die( __('You are not allowed to edit this post.' ));
180         }
181
182         $post_data = _wp_translate_postdata( true, $post_data );
183         if ( is_wp_error($post_data) )
184                 wp_die( $post_data->get_error_message() );
185         if ( ( empty( $post_data['action'] ) || 'autosave' != $post_data['action'] ) && 'auto-draft' == $post_data['post_status'] ) {
186                 $post_data['post_status'] = 'draft';
187         }
188
189         if ( isset($post_data['visibility']) ) {
190                 switch ( $post_data['visibility'] ) {
191                         case 'public' :
192                                 $post_data['post_password'] = '';
193                                 break;
194                         case 'password' :
195                                 unset( $post_data['sticky'] );
196                                 break;
197                         case 'private' :
198                                 $post_data['post_status'] = 'private';
199                                 $post_data['post_password'] = '';
200                                 unset( $post_data['sticky'] );
201                                 break;
202                 }
203         }
204
205         // Post Formats
206         if ( isset( $post_data['post_format'] ) ) {
207                 if ( current_theme_supports( 'post-formats', $post_data['post_format'] ) )
208                         set_post_format( $post_ID, $post_data['post_format'] );
209                 elseif ( '0' == $post_data['post_format'] )
210                         set_post_format( $post_ID, false );
211         }
212
213         // Meta Stuff
214         if ( isset($post_data['meta']) && $post_data['meta'] ) {
215                 foreach ( $post_data['meta'] as $key => $value ) {
216                         if ( !$meta = get_post_meta_by_id( $key ) )
217                                 continue;
218                         if ( $meta->post_id != $post_ID )
219                                 continue;
220                         if ( is_protected_meta( $value['key'], 'post' ) || ! current_user_can( 'edit_post_meta', $post_ID, $value['key'] ) )
221                                 continue;
222                         update_meta( $key, $value['key'], $value['value'] );
223                 }
224         }
225
226         if ( isset($post_data['deletemeta']) && $post_data['deletemeta'] ) {
227                 foreach ( $post_data['deletemeta'] as $key => $value ) {
228                         if ( !$meta = get_post_meta_by_id( $key ) )
229                                 continue;
230                         if ( $meta->post_id != $post_ID )
231                                 continue;
232                         if ( is_protected_meta( $meta->meta_key, 'post' ) || ! current_user_can( 'delete_post_meta', $post_ID, $meta->meta_key ) )
233                                 continue;
234                         delete_meta( $key );
235                 }
236         }
237
238         // Attachment stuff
239         if ( 'attachment' == $post_data['post_type'] ) {
240                 if ( isset( $post_data[ '_wp_attachment_image_alt' ] ) ) {
241                         $image_alt = get_post_meta( $post_ID, '_wp_attachment_image_alt', true );
242                         if ( $image_alt != stripslashes( $post_data['_wp_attachment_image_alt'] ) ) {
243                                 $image_alt = wp_strip_all_tags( stripslashes( $post_data['_wp_attachment_image_alt'] ), true );
244                                 // update_meta expects slashed
245                                 update_post_meta( $post_ID, '_wp_attachment_image_alt', addslashes( $image_alt ) );
246                         }
247                 }
248
249                 $attachment_data = isset( $post_data['attachments'][ $post_ID ] ) ? $post_data['attachments'][ $post_ID ] : array();
250                 $post_data = apply_filters( 'attachment_fields_to_save', $post_data, $attachment_data );
251         }
252
253         add_meta( $post_ID );
254
255         update_post_meta( $post_ID, '_edit_last', $GLOBALS['current_user']->ID );
256
257         wp_update_post( $post_data );
258
259         // Now that we have an ID we can fix any attachment anchor hrefs
260         _fix_attachment_links( $post_ID );
261
262         wp_set_post_lock( $post_ID );
263
264         if ( current_user_can( $ptype->cap->edit_others_posts ) ) {
265                 if ( ! empty( $post_data['sticky'] ) )
266                         stick_post( $post_ID );
267                 else
268                         unstick_post( $post_ID );
269         }
270
271         return $post_ID;
272 }
273
274 /**
275  * Process the post data for the bulk editing of posts.
276  *
277  * Updates all bulk edited posts/pages, adding (but not removing) tags and
278  * categories. Skips pages when they would be their own parent or child.
279  *
280  * @since 2.7.0
281  *
282  * @param array $post_data Optional, the array of post data to process if not provided will use $_POST superglobal.
283  * @return array
284  */
285 function bulk_edit_posts( $post_data = null ) {
286         global $wpdb;
287
288         if ( empty($post_data) )
289                 $post_data = &$_POST;
290
291         if ( isset($post_data['post_type']) )
292                 $ptype = get_post_type_object($post_data['post_type']);
293         else
294                 $ptype = get_post_type_object('post');
295
296         if ( !current_user_can( $ptype->cap->edit_posts ) ) {
297                 if ( 'page' == $ptype->name )
298                         wp_die( __('You are not allowed to edit pages.'));
299                 else
300                         wp_die( __('You are not allowed to edit posts.'));
301         }
302
303         if ( -1 == $post_data['_status'] ) {
304                 $post_data['post_status'] = null;
305                 unset($post_data['post_status']);
306         } else {
307                 $post_data['post_status'] = $post_data['_status'];
308         }
309         unset($post_data['_status']);
310
311         $post_IDs = array_map( 'intval', (array) $post_data['post'] );
312
313         $reset = array( 'post_author', 'post_status', 'post_password', 'post_parent', 'page_template', 'comment_status', 'ping_status', 'keep_private', 'tax_input', 'post_category', 'sticky' );
314         foreach ( $reset as $field ) {
315                 if ( isset($post_data[$field]) && ( '' == $post_data[$field] || -1 == $post_data[$field] ) )
316                         unset($post_data[$field]);
317         }
318
319         if ( isset($post_data['post_category']) ) {
320                 if ( is_array($post_data['post_category']) && ! empty($post_data['post_category']) )
321                         $new_cats = array_map( 'absint', $post_data['post_category'] );
322                 else
323                         unset($post_data['post_category']);
324         }
325
326         $tax_input = array();
327         if ( isset($post_data['tax_input'])) {
328                 foreach ( $post_data['tax_input'] as $tax_name => $terms ) {
329                         if ( empty($terms) )
330                                 continue;
331                         if ( is_taxonomy_hierarchical( $tax_name ) ) {
332                                 $tax_input[ $tax_name ] = array_map( 'absint', $terms );
333                         } else {
334                                 $comma = _x( ',', 'tag delimiter' );
335                                 if ( ',' !== $comma )
336                                         $terms = str_replace( $comma, ',', $terms );
337                                 $tax_input[ $tax_name ] = explode( ',', trim( $terms, " \n\t\r\0\x0B," ) );
338                         }
339                 }
340         }
341
342         if ( isset($post_data['post_parent']) && ($parent = (int) $post_data['post_parent']) ) {
343                 $pages = $wpdb->get_results("SELECT ID, post_parent FROM $wpdb->posts WHERE post_type = 'page'");
344                 $children = array();
345
346                 for ( $i = 0; $i < 50 && $parent > 0; $i++ ) {
347                         $children[] = $parent;
348
349                         foreach ( $pages as $page ) {
350                                 if ( $page->ID == $parent ) {
351                                         $parent = $page->post_parent;
352                                         break;
353                                 }
354                         }
355                 }
356         }
357
358         if ( isset( $post_data['post_format'] ) ) {
359                 if ( '0' == $post_data['post_format'] )
360                         $post_data['post_format'] = false;
361                 // don't change the post format if it's not supported or not '0' (standard)
362                 elseif ( ! current_theme_supports( 'post-formats', $post_data['post_format'] ) )
363                         unset( $post_data['post_format'] );
364         }
365
366         $updated = $skipped = $locked = array();
367         foreach ( $post_IDs as $post_ID ) {
368                 $post_type_object = get_post_type_object( get_post_type( $post_ID ) );
369
370                 if ( !isset( $post_type_object ) || ( isset($children) && in_array($post_ID, $children) ) || !current_user_can( $post_type_object->cap->edit_post, $post_ID ) ) {
371                         $skipped[] = $post_ID;
372                         continue;
373                 }
374
375                 if ( wp_check_post_lock( $post_ID ) ) {
376                         $locked[] = $post_ID;
377                         continue;
378                 }
379
380                 $post = get_post( $post_ID );
381                 $tax_names = get_object_taxonomies( $post );
382                 foreach ( $tax_names as $tax_name ) {
383                         $taxonomy_obj = get_taxonomy($tax_name);
384                         if ( isset( $tax_input[$tax_name]) && current_user_can( $taxonomy_obj->cap->assign_terms ) )
385                                 $new_terms = $tax_input[$tax_name];
386                         else
387                                 $new_terms = array();
388
389                         if ( $taxonomy_obj->hierarchical )
390                                 $current_terms = (array) wp_get_object_terms( $post_ID, $tax_name, array('fields' => 'ids') );
391                         else
392                                 $current_terms = (array) wp_get_object_terms( $post_ID, $tax_name, array('fields' => 'names') );
393
394                         $post_data['tax_input'][$tax_name] = array_merge( $current_terms, $new_terms );
395                 }
396
397                 if ( isset($new_cats) && in_array( 'category', $tax_names ) ) {
398                         $cats = (array) wp_get_post_categories($post_ID);
399                         $post_data['post_category'] = array_unique( array_merge($cats, $new_cats) );
400                         unset( $post_data['tax_input']['category'] );
401                 }
402
403                 $post_data['post_mime_type'] = $post->post_mime_type;
404                 $post_data['guid'] = $post->guid;
405
406                 $post_data['ID'] = $post_ID;
407                 $updated[] = wp_update_post( $post_data );
408
409                 if ( isset( $post_data['sticky'] ) && current_user_can( $ptype->cap->edit_others_posts ) ) {
410                         if ( 'sticky' == $post_data['sticky'] )
411                                 stick_post( $post_ID );
412                         else
413                                 unstick_post( $post_ID );
414                 }
415
416                 if ( isset( $post_data['post_format'] ) )
417                         set_post_format( $post_ID, $post_data['post_format'] );
418         }
419
420         return array( 'updated' => $updated, 'skipped' => $skipped, 'locked' => $locked );
421 }
422
423 /**
424  * Default post information to use when populating the "Write Post" form.
425  *
426  * @since 2.0.0
427  *
428  * @param string $post_type A post type string, defaults to 'post'.
429  * @return WP_Post Post object containing all the default post data as attributes
430  */
431 function get_default_post_to_edit( $post_type = 'post', $create_in_db = false ) {
432         global $wpdb;
433
434         $post_title = '';
435         if ( !empty( $_REQUEST['post_title'] ) )
436                 $post_title = esc_html( stripslashes( $_REQUEST['post_title'] ));
437
438         $post_content = '';
439         if ( !empty( $_REQUEST['content'] ) )
440                 $post_content = esc_html( stripslashes( $_REQUEST['content'] ));
441
442         $post_excerpt = '';
443         if ( !empty( $_REQUEST['excerpt'] ) )
444                 $post_excerpt = esc_html( stripslashes( $_REQUEST['excerpt'] ));
445
446         if ( $create_in_db ) {
447                 $post_id = wp_insert_post( array( 'post_title' => __( 'Auto Draft' ), 'post_type' => $post_type, 'post_status' => 'auto-draft' ) );
448                 $post = get_post( $post_id );
449                 if ( current_theme_supports( 'post-formats' ) && post_type_supports( $post->post_type, 'post-formats' ) && get_option( 'default_post_format' ) )
450                         set_post_format( $post, get_option( 'default_post_format' ) );
451         } else {
452                 $post = new stdClass;
453                 $post->ID = 0;
454                 $post->post_author = '';
455                 $post->post_date = '';
456                 $post->post_date_gmt = '';
457                 $post->post_password = '';
458                 $post->post_type = $post_type;
459                 $post->post_status = 'draft';
460                 $post->to_ping = '';
461                 $post->pinged = '';
462                 $post->comment_status = get_option( 'default_comment_status' );
463                 $post->ping_status = get_option( 'default_ping_status' );
464                 $post->post_pingback = get_option( 'default_pingback_flag' );
465                 $post->post_category = get_option( 'default_category' );
466                 $post->page_template = 'default';
467                 $post->post_parent = 0;
468                 $post->menu_order = 0;
469                 $post = new WP_Post( $post );
470         }
471
472         $post->post_content = apply_filters( 'default_content', $post_content, $post );
473         $post->post_title   = apply_filters( 'default_title',   $post_title, $post   );
474         $post->post_excerpt = apply_filters( 'default_excerpt', $post_excerpt, $post );
475         $post->post_name = '';
476
477         return $post;
478 }
479
480 /**
481  * Determine if a post exists based on title, content, and date
482  *
483  * @since 2.0.0
484  *
485  * @param string $title Post title
486  * @param string $content Optional post content
487  * @param string $date Optional post date
488  * @return int Post ID if post exists, 0 otherwise.
489  */
490 function post_exists($title, $content = '', $date = '') {
491         global $wpdb;
492
493         $post_title = stripslashes( sanitize_post_field( 'post_title', $title, 0, 'db' ) );
494         $post_content = stripslashes( sanitize_post_field( 'post_content', $content, 0, 'db' ) );
495         $post_date = stripslashes( sanitize_post_field( 'post_date', $date, 0, 'db' ) );
496
497         $query = "SELECT ID FROM $wpdb->posts WHERE 1=1";
498         $args = array();
499
500         if ( !empty ( $date ) ) {
501                 $query .= ' AND post_date = %s';
502                 $args[] = $post_date;
503         }
504
505         if ( !empty ( $title ) ) {
506                 $query .= ' AND post_title = %s';
507                 $args[] = $post_title;
508         }
509
510         if ( !empty ( $content ) ) {
511                 $query .= 'AND post_content = %s';
512                 $args[] = $post_content;
513         }
514
515         if ( !empty ( $args ) )
516                 return (int) $wpdb->get_var( $wpdb->prepare($query, $args) );
517
518         return 0;
519 }
520
521 /**
522  * Creates a new post from the "Write Post" form using $_POST information.
523  *
524  * @since 2.1.0
525  *
526  * @return unknown
527  */
528 function wp_write_post() {
529         global $user_ID;
530
531         if ( isset($_POST['post_type']) )
532                 $ptype = get_post_type_object($_POST['post_type']);
533         else
534                 $ptype = get_post_type_object('post');
535
536         if ( !current_user_can( $ptype->cap->edit_posts ) ) {
537                 if ( 'page' == $ptype->name )
538                         return new WP_Error( 'edit_pages', __( 'You are not allowed to create pages on this site.' ) );
539                 else
540                         return new WP_Error( 'edit_posts', __( 'You are not allowed to create posts or drafts on this site.' ) );
541         }
542
543         $_POST['post_mime_type'] = '';
544
545         // Clear out any data in internal vars.
546         unset( $_POST['filter'] );
547
548         // Edit don't write if we have a post id.
549         if ( isset( $_POST['post_ID'] ) )
550                 return edit_post();
551
552         $translated = _wp_translate_postdata( false );
553         if ( is_wp_error($translated) )
554                 return $translated;
555
556         if ( isset($_POST['visibility']) ) {
557                 switch ( $_POST['visibility'] ) {
558                         case 'public' :
559                                 $_POST['post_password'] = '';
560                                 break;
561                         case 'password' :
562                                 unset( $_POST['sticky'] );
563                                 break;
564                         case 'private' :
565                                 $_POST['post_status'] = 'private';
566                                 $_POST['post_password'] = '';
567                                 unset( $_POST['sticky'] );
568                                 break;
569                 }
570         }
571
572         // Create the post.
573         $post_ID = wp_insert_post( $_POST );
574         if ( is_wp_error( $post_ID ) )
575                 return $post_ID;
576
577         if ( empty($post_ID) )
578                 return 0;
579
580         add_meta( $post_ID );
581
582         add_post_meta( $post_ID, '_edit_last', $GLOBALS['current_user']->ID );
583
584         // Now that we have an ID we can fix any attachment anchor hrefs
585         _fix_attachment_links( $post_ID );
586
587         wp_set_post_lock( $post_ID );
588
589         return $post_ID;
590 }
591
592 /**
593  * Calls wp_write_post() and handles the errors.
594  *
595  * @since 2.0.0
596
597  * @uses wp_write_post()
598  * @uses is_wp_error()
599  * @uses wp_die()
600  * @return unknown
601  */
602 function write_post() {
603         $result = wp_write_post();
604         if ( is_wp_error( $result ) )
605                 wp_die( $result->get_error_message() );
606         else
607                 return $result;
608 }
609
610 //
611 // Post Meta
612 //
613
614 /**
615  * {@internal Missing Short Description}}
616  *
617  * @since 1.2.0
618  *
619  * @param unknown_type $post_ID
620  * @return unknown
621  */
622 function add_meta( $post_ID ) {
623         global $wpdb;
624         $post_ID = (int) $post_ID;
625
626         $metakeyselect = isset($_POST['metakeyselect']) ? stripslashes( trim( $_POST['metakeyselect'] ) ) : '';
627         $metakeyinput = isset($_POST['metakeyinput']) ? stripslashes( trim( $_POST['metakeyinput'] ) ) : '';
628         $metavalue = isset($_POST['metavalue']) ? $_POST['metavalue'] : '';
629         if ( is_string( $metavalue ) )
630                 $metavalue = trim( $metavalue );
631
632         if ( ('0' === $metavalue || ! empty ( $metavalue ) ) && ( ( ( '#NONE#' != $metakeyselect ) && !empty ( $metakeyselect) ) || !empty ( $metakeyinput ) ) ) {
633                 // We have a key/value pair. If both the select and the
634                 // input for the key have data, the input takes precedence:
635
636                 if ( '#NONE#' != $metakeyselect )
637                         $metakey = $metakeyselect;
638
639                 if ( $metakeyinput )
640                         $metakey = $metakeyinput; // default
641
642                 if ( is_protected_meta( $metakey, 'post' ) || ! current_user_can( 'add_post_meta', $post_ID, $metakey ) )
643                         return false;
644
645                 $metakey = esc_sql( $metakey );
646
647                 return add_post_meta( $post_ID, $metakey, $metavalue );
648         }
649
650         return false;
651 } // add_meta
652
653 /**
654  * {@internal Missing Short Description}}
655  *
656  * @since 1.2.0
657  *
658  * @param unknown_type $mid
659  * @return unknown
660  */
661 function delete_meta( $mid ) {
662         return delete_metadata_by_mid( 'post' , $mid );
663 }
664
665 /**
666  * Get a list of previously defined keys.
667  *
668  * @since 1.2.0
669  *
670  * @return unknown
671  */
672 function get_meta_keys() {
673         global $wpdb;
674
675         $keys = $wpdb->get_col( "
676                         SELECT meta_key
677                         FROM $wpdb->postmeta
678                         GROUP BY meta_key
679                         ORDER BY meta_key" );
680
681         return $keys;
682 }
683
684 /**
685  * {@internal Missing Short Description}}
686  *
687  * @since 2.1.0
688  *
689  * @param unknown_type $mid
690  * @return unknown
691  */
692 function get_post_meta_by_id( $mid ) {
693         return get_metadata_by_mid( 'post', $mid );
694 }
695
696 /**
697  * {@internal Missing Short Description}}
698  *
699  * Some postmeta stuff.
700  *
701  * @since 1.2.0
702  *
703  * @param unknown_type $postid
704  * @return unknown
705  */
706 function has_meta( $postid ) {
707         global $wpdb;
708
709         return $wpdb->get_results( $wpdb->prepare("SELECT meta_key, meta_value, meta_id, post_id
710                         FROM $wpdb->postmeta WHERE post_id = %d
711                         ORDER BY meta_key,meta_id", $postid), ARRAY_A );
712 }
713
714 /**
715  * {@internal Missing Short Description}}
716  *
717  * @since 1.2.0
718  *
719  * @param unknown_type $meta_id
720  * @param unknown_type $meta_key Expect Slashed
721  * @param unknown_type $meta_value Expect Slashed
722  * @return unknown
723  */
724 function update_meta( $meta_id, $meta_key, $meta_value ) {
725         $meta_key = stripslashes( $meta_key );
726         $meta_value = stripslashes_deep( $meta_value );
727
728         return update_metadata_by_mid( 'post', $meta_id, $meta_value, $meta_key );
729 }
730
731 //
732 // Private
733 //
734
735 /**
736  * Replace hrefs of attachment anchors with up-to-date permalinks.
737  *
738  * @since 2.3.0
739  * @access private
740  *
741  * @param unknown_type $post_ID
742  * @return unknown
743  */
744 function _fix_attachment_links( $post_ID ) {
745         $post = get_post( $post_ID, ARRAY_A );
746         $content = $post['post_content'];
747
748         // quick sanity check, don't run if no pretty permalinks or post is not published
749         if ( !get_option('permalink_structure') || $post['post_status'] != 'publish' )
750                 return;
751
752         // Short if there aren't any links or no '?attachment_id=' strings (strpos cannot be zero)
753         if ( !strpos($content, '?attachment_id=') || !preg_match_all( '/<a ([^>]+)>[\s\S]+?<\/a>/', $content, $link_matches ) )
754                 return;
755
756         $site_url = get_bloginfo('url');
757         $site_url = substr( $site_url, (int) strpos($site_url, '://') ); // remove the http(s)
758         $replace = '';
759
760         foreach ( $link_matches[1] as $key => $value ) {
761                 if ( !strpos($value, '?attachment_id=') || !strpos($value, 'wp-att-')
762                         || !preg_match( '/href=(["\'])[^"\']*\?attachment_id=(\d+)[^"\']*\\1/', $value, $url_match )
763                         || !preg_match( '/rel=["\'][^"\']*wp-att-(\d+)/', $value, $rel_match ) )
764                                 continue;
765
766                 $quote = $url_match[1]; // the quote (single or double)
767                 $url_id = (int) $url_match[2];
768                 $rel_id = (int) $rel_match[1];
769
770                 if ( !$url_id || !$rel_id || $url_id != $rel_id || strpos($url_match[0], $site_url) === false )
771                         continue;
772
773                 $link = $link_matches[0][$key];
774                 $replace = str_replace( $url_match[0], 'href=' . $quote . get_attachment_link( $url_id ) . $quote, $link );
775
776                 $content = str_replace( $link, $replace, $content );
777         }
778
779         if ( $replace ) {
780                 $post['post_content'] = $content;
781                 // Escape data pulled from DB.
782                 $post = add_magic_quotes($post);
783
784                 return wp_update_post($post);
785         }
786 }
787
788 /**
789  * Move child posts to a new parent.
790  *
791  * @since 2.3.0
792  * @access private
793  *
794  * @param unknown_type $old_ID
795  * @param unknown_type $new_ID
796  * @return unknown
797  */
798 function _relocate_children( $old_ID, $new_ID ) {
799         global $wpdb;
800         $old_ID = (int) $old_ID;
801         $new_ID = (int) $new_ID;
802
803         $children = $wpdb->get_col( $wpdb->prepare("
804                 SELECT post_id
805                 FROM $wpdb->postmeta
806                 WHERE meta_key = '_wp_attachment_temp_parent'
807                 AND meta_value = %d", $old_ID) );
808
809         foreach ( $children as $child_id ) {
810                 $wpdb->update($wpdb->posts, array('post_parent' => $new_ID), array('ID' => $child_id) );
811                 delete_post_meta($child_id, '_wp_attachment_temp_parent');
812         }
813 }
814
815 /**
816  * Get all the possible statuses for a post_type
817  *
818  * @since 2.5.0
819  *
820  * @param string $type The post_type you want the statuses for
821  * @return array As array of all the statuses for the supplied post type
822  */
823 function get_available_post_statuses($type = 'post') {
824         $stati = wp_count_posts($type);
825
826         return array_keys(get_object_vars($stati));
827 }
828
829 /**
830  * Run the wp query to fetch the posts for listing on the edit posts page
831  *
832  * @since 2.5.0
833  *
834  * @param array|bool $q Array of query variables to use to build the query or false to use $_GET superglobal.
835  * @return array
836  */
837 function wp_edit_posts_query( $q = false ) {
838         if ( false === $q )
839                 $q = $_GET;
840         $q['m'] = isset($q['m']) ? (int) $q['m'] : 0;
841         $q['cat'] = isset($q['cat']) ? (int) $q['cat'] : 0;
842         $post_stati  = get_post_stati();
843
844         if ( isset($q['post_type']) && in_array( $q['post_type'], get_post_types() ) )
845                 $post_type = $q['post_type'];
846         else
847                 $post_type = 'post';
848
849         $avail_post_stati = get_available_post_statuses($post_type);
850
851         if ( isset($q['post_status']) && in_array( $q['post_status'], $post_stati ) ) {
852                 $post_status = $q['post_status'];
853                 $perm = 'readable';
854         }
855
856         if ( isset($q['orderby']) )
857                 $orderby = $q['orderby'];
858         elseif ( isset($q['post_status']) && in_array($q['post_status'], array('pending', 'draft')) )
859                 $orderby = 'modified';
860
861         if ( isset($q['order']) )
862                 $order = $q['order'];
863         elseif ( isset($q['post_status']) && 'pending' == $q['post_status'] )
864                 $order = 'ASC';
865
866         $per_page = 'edit_' . $post_type . '_per_page';
867         $posts_per_page = (int) get_user_option( $per_page );
868         if ( empty( $posts_per_page ) || $posts_per_page < 1 )
869                 $posts_per_page = 20;
870
871         $posts_per_page = apply_filters( $per_page, $posts_per_page );
872         $posts_per_page = apply_filters( 'edit_posts_per_page', $posts_per_page, $post_type );
873
874         $query = compact('post_type', 'post_status', 'perm', 'order', 'orderby', 'posts_per_page');
875
876         // Hierarchical types require special args.
877         if ( is_post_type_hierarchical( $post_type ) && !isset($orderby) ) {
878                 $query['orderby'] = 'menu_order title';
879                 $query['order'] = 'asc';
880                 $query['posts_per_page'] = -1;
881                 $query['posts_per_archive_page'] = -1;
882         }
883
884         if ( ! empty( $q['show_sticky'] ) )
885                 $query['post__in'] = (array) get_option( 'sticky_posts' );
886
887         wp( $query );
888
889         return $avail_post_stati;
890 }
891
892 /**
893  * {@internal Missing Short Description}}
894  *
895  * @since 2.5.0
896  *
897  * @param unknown_type $type
898  * @return unknown
899  */
900 function get_available_post_mime_types($type = 'attachment') {
901         global $wpdb;
902
903         $types = $wpdb->get_col($wpdb->prepare("SELECT DISTINCT post_mime_type FROM $wpdb->posts WHERE post_type = %s", $type));
904         return $types;
905 }
906
907 /**
908  * Executes a query for attachments. An array of WP_Query arguments
909  * can be passed in, which will override the arguments set by this function.
910  *
911  * @since 2.5.0
912  * @uses apply_filters() Calls 'upload_per_page' on posts_per_page argument
913  *
914  * @param array|bool $q Array of query variables to use to build the query or false to use $_GET superglobal.
915  * @return array
916  */
917 function wp_edit_attachments_query( $q = false ) {
918         if ( false === $q )
919                 $q = $_GET;
920
921         $q['m']   = isset( $q['m'] ) ? (int) $q['m'] : 0;
922         $q['cat'] = isset( $q['cat'] ) ? (int) $q['cat'] : 0;
923         $q['post_type'] = 'attachment';
924         $post_type = get_post_type_object( 'attachment' );
925         $states = 'inherit';
926         if ( current_user_can( $post_type->cap->read_private_posts ) )
927                 $states .= ',private';
928
929         $q['post_status'] = isset( $q['status'] ) && 'trash' == $q['status'] ? 'trash' : $states;
930         $media_per_page = (int) get_user_option( 'upload_per_page' );
931         if ( empty( $media_per_page ) || $media_per_page < 1 )
932                 $media_per_page = 20;
933         $q['posts_per_page'] = apply_filters( 'upload_per_page', $media_per_page );
934
935         $post_mime_types = get_post_mime_types();
936         $avail_post_mime_types = get_available_post_mime_types('attachment');
937
938         if ( isset($q['post_mime_type']) && !array_intersect( (array) $q['post_mime_type'], array_keys($post_mime_types) ) )
939                 unset($q['post_mime_type']);
940
941         if ( isset($q['detached']) )
942                 add_filter('posts_where', '_edit_attachments_query_helper');
943
944         wp( $q );
945
946         if ( isset($q['detached']) )
947                 remove_filter('posts_where', '_edit_attachments_query_helper');
948
949         return array($post_mime_types, $avail_post_mime_types);
950 }
951
952 function _edit_attachments_query_helper($where) {
953         global $wpdb;
954         return $where .= " AND {$wpdb->posts}.post_parent < 1";
955 }
956
957 /**
958  * Returns the list of classes to be used by a metabox
959  *
960  * @uses get_user_option()
961  * @since 2.5.0
962  *
963  * @param unknown_type $id
964  * @param unknown_type $page
965  * @return unknown
966  */
967 function postbox_classes( $id, $page ) {
968         if ( isset( $_GET['edit'] ) && $_GET['edit'] == $id ) {
969                 $classes = array( '' );
970         } elseif ( $closed = get_user_option('closedpostboxes_'.$page ) ) {
971                 if ( !is_array( $closed ) ) {
972                         $classes = array( '' );
973                 } else {
974                         $classes = in_array( $id, $closed ) ? array( 'closed' ) : array( '' );
975                 }
976         } else {
977                 $classes = array( '' );
978         }
979
980         $classes = apply_filters( "postbox_classes_{$page}_{$id}", $classes );
981         return implode( ' ', $classes );
982 }
983
984 /**
985  * {@internal Missing Short Description}}
986  *
987  * @since 2.5.0
988  *
989  * @param int|object $id    Post ID or post object.
990  * @param string $title (optional) Title
991  * @param string $name (optional) Name
992  * @return array With two entries of type string
993  */
994 function get_sample_permalink($id, $title = null, $name = null) {
995         $post = get_post($id);
996         if ( !$post->ID )
997                 return array('', '');
998
999         $ptype = get_post_type_object($post->post_type);
1000
1001         $original_status = $post->post_status;
1002         $original_date = $post->post_date;
1003         $original_name = $post->post_name;
1004
1005         // Hack: get_permalink would return ugly permalink for
1006         // drafts, so we will fake, that our post is published
1007         if ( in_array($post->post_status, array('draft', 'pending')) ) {
1008                 $post->post_status = 'publish';
1009                 $post->post_name = sanitize_title($post->post_name ? $post->post_name : $post->post_title, $post->ID);
1010         }
1011
1012         // If the user wants to set a new name -- override the current one
1013         // Note: if empty name is supplied -- use the title instead, see #6072
1014         if ( !is_null($name) )
1015                 $post->post_name = sanitize_title($name ? $name : $title, $post->ID);
1016
1017         $post->post_name = wp_unique_post_slug($post->post_name, $post->ID, $post->post_status, $post->post_type, $post->post_parent);
1018
1019         $post->filter = 'sample';
1020
1021         $permalink = get_permalink($post, true);
1022
1023         // Replace custom post_type Token with generic pagename token for ease of use.
1024         $permalink = str_replace("%$post->post_type%", '%pagename%', $permalink);
1025
1026         // Handle page hierarchy
1027         if ( $ptype->hierarchical ) {
1028                 $uri = get_page_uri($post);
1029                 $uri = untrailingslashit($uri);
1030                 $uri = strrev( stristr( strrev( $uri ), '/' ) );
1031                 $uri = untrailingslashit($uri);
1032                 $uri = apply_filters( 'editable_slug', $uri );
1033                 if ( !empty($uri) )
1034                         $uri .= '/';
1035                 $permalink = str_replace('%pagename%', "{$uri}%pagename%", $permalink);
1036         }
1037
1038         $permalink = array($permalink, apply_filters('editable_slug', $post->post_name));
1039         $post->post_status = $original_status;
1040         $post->post_date = $original_date;
1041         $post->post_name = $original_name;
1042         unset($post->filter);
1043
1044         return $permalink;
1045 }
1046
1047 /**
1048  * Returns the HTML of the sample permalink slug editor.
1049  *
1050  * @since 2.5.0
1051  *
1052  * @param int|object $id Post ID or post object.
1053  * @param string $new_title Optional. New title.
1054  * @param string $new_slug Optional. New slug.
1055  * @return string The HTML of the sample permalink slug editor.
1056  */
1057 function get_sample_permalink_html( $id, $new_title = null, $new_slug = null ) {
1058         global $wpdb;
1059         $post = get_post($id);
1060
1061         list($permalink, $post_name) = get_sample_permalink($post->ID, $new_title, $new_slug);
1062
1063         if ( 'publish' == get_post_status( $post ) ) {
1064                 $ptype = get_post_type_object($post->post_type);
1065                 $view_post = $ptype->labels->view_item;
1066                 $title = __('Click to edit this part of the permalink');
1067         } else {
1068                 $title = __('Temporary permalink. Click to edit this part.');
1069         }
1070
1071         if ( false === strpos($permalink, '%postname%') && false === strpos($permalink, '%pagename%') ) {
1072                 $return = '<strong>' . __('Permalink:') . "</strong>\n" . '<span id="sample-permalink" tabindex="-1">' . $permalink . "</span>\n";
1073                 if ( '' == get_option( 'permalink_structure' ) && current_user_can( 'manage_options' ) && !( 'page' == get_option('show_on_front') && $id == get_option('page_on_front') ) )
1074                         $return .= '<span id="change-permalinks"><a href="options-permalink.php" class="button button-small" target="_blank">' . __('Change Permalinks') . "</a></span>\n";
1075                 if ( isset( $view_post ) )
1076                         $return .= "<span id='view-post-btn'><a href='$permalink' class='button button-small'>$view_post</a></span>\n";
1077
1078                 $return = apply_filters('get_sample_permalink_html', $return, $id, $new_title, $new_slug);
1079
1080                 return $return;
1081         }
1082
1083         if ( function_exists('mb_strlen') ) {
1084                 if ( mb_strlen($post_name) > 30 ) {
1085                         $post_name_abridged = mb_substr($post_name, 0, 14). '&hellip;' . mb_substr($post_name, -14);
1086                 } else {
1087                         $post_name_abridged = $post_name;
1088                 }
1089         } else {
1090                 if ( strlen($post_name) > 30 ) {
1091                         $post_name_abridged = substr($post_name, 0, 14). '&hellip;' . substr($post_name, -14);
1092                 } else {
1093                         $post_name_abridged = $post_name;
1094                 }
1095         }
1096
1097         $post_name_html = '<span id="editable-post-name" title="' . $title . '">' . $post_name_abridged . '</span>';
1098         $display_link = str_replace(array('%pagename%','%postname%'), $post_name_html, $permalink);
1099         $view_link = str_replace(array('%pagename%','%postname%'), $post_name, $permalink);
1100         $return =  '<strong>' . __('Permalink:') . "</strong>\n";
1101         $return .= '<span id="sample-permalink" tabindex="-1">' . $display_link . "</span>\n";
1102         $return .= '&lrm;'; // Fix bi-directional text display defect in RTL languages.
1103         $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";
1104         $return .= '<span id="editable-post-name-full">' . $post_name . "</span>\n";
1105         if ( isset($view_post) )
1106                 $return .= "<span id='view-post-btn'><a href='$view_link' class='button button-small'>$view_post</a></span>\n";
1107
1108         $return = apply_filters('get_sample_permalink_html', $return, $id, $new_title, $new_slug);
1109
1110         return $return;
1111 }
1112
1113 /**
1114  * Output HTML for the post thumbnail meta-box.
1115  *
1116  * @since 2.9.0
1117  *
1118  * @param int $thumbnail_id ID of the attachment used for thumbnail
1119  * @param mixed $post The post ID or object associated with the thumbnail, defaults to global $post.
1120  * @return string html
1121  */
1122 function _wp_post_thumbnail_html( $thumbnail_id = null, $post = null ) {
1123         global $content_width, $_wp_additional_image_sizes;
1124
1125         $post = get_post( $post );
1126
1127         $upload_iframe_src = esc_url( get_upload_iframe_src('image', $post->ID ) );
1128         $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>';
1129         $content = sprintf( $set_thumbnail_link, $upload_iframe_src, esc_html__( 'Set featured image' ) );
1130
1131         if ( $thumbnail_id && get_post( $thumbnail_id ) ) {
1132                 $old_content_width = $content_width;
1133                 $content_width = 266;
1134                 if ( !isset( $_wp_additional_image_sizes['post-thumbnail'] ) )
1135                         $thumbnail_html = wp_get_attachment_image( $thumbnail_id, array( $content_width, $content_width ) );
1136                 else
1137                         $thumbnail_html = wp_get_attachment_image( $thumbnail_id, 'post-thumbnail' );
1138                 if ( !empty( $thumbnail_html ) ) {
1139                         $ajax_nonce = wp_create_nonce( 'set_post_thumbnail-' . $post->ID );
1140                         $content = sprintf( $set_thumbnail_link, $upload_iframe_src, $thumbnail_html );
1141                         $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>';
1142                 }
1143                 $content_width = $old_content_width;
1144         }
1145
1146         return apply_filters( 'admin_post_thumbnail_html', $content, $post->ID );
1147 }
1148
1149 /**
1150  * Check to see if the post is currently being edited by another user.
1151  *
1152  * @since 2.5.0
1153  *
1154  * @param int $post_id ID of the post to check for editing
1155  * @return bool|int False: not locked or locked by current user. Int: user ID of user with lock.
1156  */
1157 function wp_check_post_lock( $post_id ) {
1158         if ( !$post = get_post( $post_id ) )
1159                 return false;
1160
1161         if ( !$lock = get_post_meta( $post->ID, '_edit_lock', true ) )
1162                 return false;
1163
1164         $lock = explode( ':', $lock );
1165         $time = $lock[0];
1166         $user = isset( $lock[1] ) ? $lock[1] : get_post_meta( $post->ID, '_edit_last', true );
1167
1168         $time_window = apply_filters( 'wp_check_post_lock_window', AUTOSAVE_INTERVAL * 2 );
1169
1170         if ( $time && $time > time() - $time_window && $user != get_current_user_id() )
1171                 return $user;
1172         return false;
1173 }
1174
1175 /**
1176  * Mark the post as currently being edited by the current user
1177  *
1178  * @since 2.5.0
1179  *
1180  * @param int $post_id ID of the post to being edited
1181  * @return bool|array Returns false if the post doesn't exist of there is no current user, or
1182  *      an array of the lock time and the user ID.
1183  */
1184 function wp_set_post_lock( $post_id ) {
1185         if ( !$post = get_post( $post_id ) )
1186                 return false;
1187         if ( 0 == ($user_id = get_current_user_id()) )
1188                 return false;
1189
1190         $now = time();
1191         $lock = "$now:$user_id";
1192
1193         update_post_meta( $post->ID, '_edit_lock', $lock );
1194         return array( $now, $user_id );
1195 }
1196
1197 /**
1198  * Outputs the notice message to say that someone else is editing this post at the moment.
1199  *
1200  * @since 2.8.5
1201  * @return none
1202  */
1203 function _admin_notice_post_locked() {
1204         $post = get_post();
1205         $lock = explode( ':', get_post_meta( $post->ID, '_edit_lock', true ) );
1206         $user = isset( $lock[1] ) ? $lock[1] : get_post_meta( $post->ID, '_edit_last', true );
1207         $last_user = get_userdata( $user );
1208         $last_user_name = $last_user ? $last_user->display_name : __('Somebody');
1209
1210         switch ($post->post_type) {
1211                 case 'post':
1212                         $message = __( 'Warning: %s is currently editing this post' );
1213                         break;
1214                 case 'page':
1215                         $message = __( 'Warning: %s is currently editing this page' );
1216                         break;
1217                 default:
1218                         $message = __( 'Warning: %s is currently editing this.' );
1219         }
1220
1221         $message = sprintf( $message, esc_html( $last_user_name ) );
1222         echo "<div class='error'><p>$message</p></div>";
1223 }
1224
1225 /**
1226  * Creates autosave data for the specified post from $_POST data.
1227  *
1228  * @package WordPress
1229  * @subpackage Post_Revisions
1230  * @since 2.6.0
1231  *
1232  * @uses _wp_translate_postdata()
1233  * @uses _wp_post_revision_fields()
1234  *
1235  * @return unknown
1236  */
1237 function wp_create_post_autosave( $post_id ) {
1238         $translated = _wp_translate_postdata( true );
1239         if ( is_wp_error( $translated ) )
1240                 return $translated;
1241
1242         // Only store one autosave. If there is already an autosave, overwrite it.
1243         if ( $old_autosave = wp_get_post_autosave( $post_id ) ) {
1244                 $new_autosave = _wp_post_revision_fields( $_POST, true );
1245                 $new_autosave['ID'] = $old_autosave->ID;
1246                 $new_autosave['post_author'] = get_current_user_id();
1247                 return wp_update_post( $new_autosave );
1248         }
1249
1250         // _wp_put_post_revision() expects unescaped.
1251         $_POST = stripslashes_deep($_POST);
1252
1253         // Otherwise create the new autosave as a special post revision
1254         return _wp_put_post_revision( $_POST, true );
1255 }
1256
1257 /**
1258  * Save draft or manually autosave for showing preview.
1259  *
1260  * @package WordPress
1261  * @since 2.7.0
1262  *
1263  * @uses get_post_status()
1264  * @uses edit_post()
1265  * @uses get_post()
1266  * @uses current_user_can()
1267  * @uses wp_die()
1268  * @uses wp_create_post_autosave()
1269  * @uses add_query_arg()
1270  * @uses wp_create_nonce()
1271  *
1272  * @return str URL to redirect to show the preview
1273  */
1274 function post_preview() {
1275
1276         $post_ID = (int) $_POST['post_ID'];
1277         $status = get_post_status( $post_ID );
1278         if ( 'auto-draft' == $status )
1279                 wp_die( __('Preview not available. Please save as a draft first.') );
1280
1281         if ( isset($_POST['catslist']) )
1282                 $_POST['post_category'] = explode(",", $_POST['catslist']);
1283
1284         if ( isset($_POST['tags_input']) )
1285                 $_POST['tags_input'] = explode(",", $_POST['tags_input']);
1286
1287         if ( $_POST['post_type'] == 'page' || empty($_POST['post_category']) )
1288                 unset($_POST['post_category']);
1289
1290         $_POST['ID'] = $post_ID;
1291         $post = get_post($post_ID);
1292
1293         if ( 'page' == $post->post_type ) {
1294                 if ( !current_user_can('edit_page', $post_ID) )
1295                         wp_die(__('You are not allowed to edit this page.'));
1296         } else {
1297                 if ( !current_user_can('edit_post', $post_ID) )
1298                         wp_die(__('You are not allowed to edit this post.'));
1299         }
1300
1301         if ( 'draft' == $post->post_status ) {
1302                 $id = edit_post();
1303         } else { // Non drafts are not overwritten. The autosave is stored in a special post revision.
1304                 $id = wp_create_post_autosave( $post->ID );
1305                 if ( ! is_wp_error($id) )
1306                         $id = $post->ID;
1307         }
1308
1309         if ( is_wp_error($id) )
1310                 wp_die( $id->get_error_message() );
1311
1312         if ( $_POST['post_status'] == 'draft'  ) {
1313                 $url = add_query_arg( 'preview', 'true', get_permalink($id) );
1314         } else {
1315                 $nonce = wp_create_nonce('post_preview_' . $id);
1316                 $url = add_query_arg( array( 'preview' => 'true', 'preview_id' => $id, 'preview_nonce' => $nonce ), get_permalink($id) );
1317         }
1318
1319         return $url;
1320 }