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