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