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