]> scripts.mit.edu Git - autoinstalls/wordpress.git/blob - wp-includes/post.php
WordPress 4.4.1
[autoinstalls/wordpress.git] / wp-includes / post.php
1 <?php
2 /**
3  * Core Post API
4  *
5  * @package WordPress
6  * @subpackage Post
7  */
8
9 //
10 // Post Type Registration
11 //
12
13 /**
14  * Creates the initial post types when 'init' action is fired.
15  *
16  * @since 2.9.0
17  */
18 function create_initial_post_types() {
19         register_post_type( 'post', array(
20                 'labels' => array(
21                         'name_admin_bar' => _x( 'Post', 'add new on admin bar' ),
22                 ),
23                 'public'  => true,
24                 '_builtin' => true, /* internal use only. don't use this when registering your own post type. */
25                 '_edit_link' => 'post.php?post=%d', /* internal use only. don't use this when registering your own post type. */
26                 'capability_type' => 'post',
27                 'map_meta_cap' => true,
28                 'menu_position' => 5,
29                 'hierarchical' => false,
30                 'rewrite' => false,
31                 'query_var' => false,
32                 'delete_with_user' => true,
33                 'supports' => array( 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'trackbacks', 'custom-fields', 'comments', 'revisions', 'post-formats' ),
34         ) );
35
36         register_post_type( 'page', array(
37                 'labels' => array(
38                         'name_admin_bar' => _x( 'Page', 'add new on admin bar' ),
39                 ),
40                 'public' => true,
41                 'publicly_queryable' => false,
42                 '_builtin' => true, /* internal use only. don't use this when registering your own post type. */
43                 '_edit_link' => 'post.php?post=%d', /* internal use only. don't use this when registering your own post type. */
44                 'capability_type' => 'page',
45                 'map_meta_cap' => true,
46                 'menu_position' => 20,
47                 'hierarchical' => true,
48                 'rewrite' => false,
49                 'query_var' => false,
50                 'delete_with_user' => true,
51                 'supports' => array( 'title', 'editor', 'author', 'thumbnail', 'page-attributes', 'custom-fields', 'comments', 'revisions' ),
52         ) );
53
54         register_post_type( 'attachment', array(
55                 'labels' => array(
56                         'name' => _x('Media', 'post type general name'),
57                         'name_admin_bar' => _x( 'Media', 'add new from admin bar' ),
58                         'add_new' => _x( 'Add New', 'add new media' ),
59                         'edit_item' => __( 'Edit Media' ),
60                         'view_item' => __( 'View Attachment Page' ),
61                 ),
62                 'public' => true,
63                 'show_ui' => true,
64                 '_builtin' => true, /* internal use only. don't use this when registering your own post type. */
65                 '_edit_link' => 'post.php?post=%d', /* internal use only. don't use this when registering your own post type. */
66                 'capability_type' => 'post',
67                 'capabilities' => array(
68                         'create_posts' => 'upload_files',
69                 ),
70                 'map_meta_cap' => true,
71                 'hierarchical' => false,
72                 'rewrite' => false,
73                 'query_var' => false,
74                 'show_in_nav_menus' => false,
75                 'delete_with_user' => true,
76                 'supports' => array( 'title', 'author', 'comments' ),
77         ) );
78         add_post_type_support( 'attachment:audio', 'thumbnail' );
79         add_post_type_support( 'attachment:video', 'thumbnail' );
80
81         register_post_type( 'revision', array(
82                 'labels' => array(
83                         'name' => __( 'Revisions' ),
84                         'singular_name' => __( 'Revision' ),
85                 ),
86                 'public' => false,
87                 '_builtin' => true, /* internal use only. don't use this when registering your own post type. */
88                 '_edit_link' => 'revision.php?revision=%d', /* internal use only. don't use this when registering your own post type. */
89                 'capability_type' => 'post',
90                 'map_meta_cap' => true,
91                 'hierarchical' => false,
92                 'rewrite' => false,
93                 'query_var' => false,
94                 'can_export' => false,
95                 'delete_with_user' => true,
96                 'supports' => array( 'author' ),
97         ) );
98
99         register_post_type( 'nav_menu_item', array(
100                 'labels' => array(
101                         'name' => __( 'Navigation Menu Items' ),
102                         'singular_name' => __( 'Navigation Menu Item' ),
103                 ),
104                 'public' => false,
105                 '_builtin' => true, /* internal use only. don't use this when registering your own post type. */
106                 'hierarchical' => false,
107                 'rewrite' => false,
108                 'delete_with_user' => false,
109                 'query_var' => false,
110         ) );
111
112         register_post_status( 'publish', array(
113                 'label'       => _x( 'Published', 'post' ),
114                 'public'      => true,
115                 '_builtin'    => true, /* internal use only. */
116                 'label_count' => _n_noop( 'Published <span class="count">(%s)</span>', 'Published <span class="count">(%s)</span>' ),
117         ) );
118
119         register_post_status( 'future', array(
120                 'label'       => _x( 'Scheduled', 'post' ),
121                 'protected'   => true,
122                 '_builtin'    => true, /* internal use only. */
123                 'label_count' => _n_noop('Scheduled <span class="count">(%s)</span>', 'Scheduled <span class="count">(%s)</span>' ),
124         ) );
125
126         register_post_status( 'draft', array(
127                 'label'       => _x( 'Draft', 'post' ),
128                 'protected'   => true,
129                 '_builtin'    => true, /* internal use only. */
130                 'label_count' => _n_noop( 'Draft <span class="count">(%s)</span>', 'Drafts <span class="count">(%s)</span>' ),
131         ) );
132
133         register_post_status( 'pending', array(
134                 'label'       => _x( 'Pending', 'post' ),
135                 'protected'   => true,
136                 '_builtin'    => true, /* internal use only. */
137                 'label_count' => _n_noop( 'Pending <span class="count">(%s)</span>', 'Pending <span class="count">(%s)</span>' ),
138         ) );
139
140         register_post_status( 'private', array(
141                 'label'       => _x( 'Private', 'post' ),
142                 'private'     => true,
143                 '_builtin'    => true, /* internal use only. */
144                 'label_count' => _n_noop( 'Private <span class="count">(%s)</span>', 'Private <span class="count">(%s)</span>' ),
145         ) );
146
147         register_post_status( 'trash', array(
148                 'label'       => _x( 'Trash', 'post' ),
149                 'internal'    => true,
150                 '_builtin'    => true, /* internal use only. */
151                 'label_count' => _n_noop( 'Trash <span class="count">(%s)</span>', 'Trash <span class="count">(%s)</span>' ),
152                 'show_in_admin_status_list' => true,
153         ) );
154
155         register_post_status( 'auto-draft', array(
156                 'label'    => 'auto-draft',
157                 'internal' => true,
158                 '_builtin' => true, /* internal use only. */
159         ) );
160
161         register_post_status( 'inherit', array(
162                 'label'    => 'inherit',
163                 'internal' => true,
164                 '_builtin' => true, /* internal use only. */
165                 'exclude_from_search' => false,
166         ) );
167 }
168
169 /**
170  * Retrieve attached file path based on attachment ID.
171  *
172  * By default the path will go through the 'get_attached_file' filter, but
173  * passing a true to the $unfiltered argument of get_attached_file() will
174  * return the file path unfiltered.
175  *
176  * The function works by getting the single post meta name, named
177  * '_wp_attached_file' and returning it. This is a convenience function to
178  * prevent looking up the meta name and provide a mechanism for sending the
179  * attached filename through a filter.
180  *
181  * @since 2.0.0
182  *
183  * @param int  $attachment_id Attachment ID.
184  * @param bool $unfiltered    Optional. Whether to apply filters. Default false.
185  * @return string|false The file path to where the attached file should be, false otherwise.
186  */
187 function get_attached_file( $attachment_id, $unfiltered = false ) {
188         $file = get_post_meta( $attachment_id, '_wp_attached_file', true );
189         // If the file is relative, prepend upload dir.
190         if ( $file && 0 !== strpos($file, '/') && !preg_match('|^.:\\\|', $file) && ( ($uploads = wp_upload_dir()) && false === $uploads['error'] ) )
191                 $file = $uploads['basedir'] . "/$file";
192         if ( $unfiltered )
193                 return $file;
194
195         /**
196          * Filter the attached file based on the given ID.
197          *
198          * @since 2.1.0
199          *
200          * @param string $file          Path to attached file.
201          * @param int    $attachment_id Attachment ID.
202          */
203         return apply_filters( 'get_attached_file', $file, $attachment_id );
204 }
205
206 /**
207  * Update attachment file path based on attachment ID.
208  *
209  * Used to update the file path of the attachment, which uses post meta name
210  * '_wp_attached_file' to store the path of the attachment.
211  *
212  * @since 2.1.0
213  *
214  * @param int    $attachment_id Attachment ID.
215  * @param string $file          File path for the attachment.
216  * @return bool True on success, false on failure.
217  */
218 function update_attached_file( $attachment_id, $file ) {
219         if ( !get_post( $attachment_id ) )
220                 return false;
221
222         /**
223          * Filter the path to the attached file to update.
224          *
225          * @since 2.1.0
226          *
227          * @param string $file          Path to the attached file to update.
228          * @param int    $attachment_id Attachment ID.
229          */
230         $file = apply_filters( 'update_attached_file', $file, $attachment_id );
231
232         if ( $file = _wp_relative_upload_path( $file ) )
233                 return update_post_meta( $attachment_id, '_wp_attached_file', $file );
234         else
235                 return delete_post_meta( $attachment_id, '_wp_attached_file' );
236 }
237
238 /**
239  * Return relative path to an uploaded file.
240  *
241  * The path is relative to the current upload dir.
242  *
243  * @since 2.9.0
244  *
245  * @param string $path Full path to the file.
246  * @return string Relative path on success, unchanged path on failure.
247  */
248 function _wp_relative_upload_path( $path ) {
249         $new_path = $path;
250
251         $uploads = wp_upload_dir();
252         if ( 0 === strpos( $new_path, $uploads['basedir'] ) ) {
253                         $new_path = str_replace( $uploads['basedir'], '', $new_path );
254                         $new_path = ltrim( $new_path, '/' );
255         }
256
257         /**
258          * Filter the relative path to an uploaded file.
259          *
260          * @since 2.9.0
261          *
262          * @param string $new_path Relative path to the file.
263          * @param string $path     Full path to the file.
264          */
265         return apply_filters( '_wp_relative_upload_path', $new_path, $path );
266 }
267
268 /**
269  * Retrieve all children of the post parent ID.
270  *
271  * Normally, without any enhancements, the children would apply to pages. In the
272  * context of the inner workings of WordPress, pages, posts, and attachments
273  * share the same table, so therefore the functionality could apply to any one
274  * of them. It is then noted that while this function does not work on posts, it
275  * does not mean that it won't work on posts. It is recommended that you know
276  * what context you wish to retrieve the children of.
277  *
278  * Attachments may also be made the child of a post, so if that is an accurate
279  * statement (which needs to be verified), it would then be possible to get
280  * all of the attachments for a post. Attachments have since changed since
281  * version 2.5, so this is most likely inaccurate, but serves generally as an
282  * example of what is possible.
283  *
284  * The arguments listed as defaults are for this function and also of the
285  * {@link get_posts()} function. The arguments are combined with the
286  * get_children defaults and are then passed to the {@link get_posts()}
287  * function, which accepts additional arguments. You can replace the defaults in
288  * this function, listed below and the additional arguments listed in the
289  * {@link get_posts()} function.
290  *
291  * The 'post_parent' is the most important argument and important attention
292  * needs to be paid to the $args parameter. If you pass either an object or an
293  * integer (number), then just the 'post_parent' is grabbed and everything else
294  * is lost. If you don't specify any arguments, then it is assumed that you are
295  * in The Loop and the post parent will be grabbed for from the current post.
296  *
297  * The 'post_parent' argument is the ID to get the children. The 'numberposts'
298  * is the amount of posts to retrieve that has a default of '-1', which is
299  * used to get all of the posts. Giving a number higher than 0 will only
300  * retrieve that amount of posts.
301  *
302  * The 'post_type' and 'post_status' arguments can be used to choose what
303  * criteria of posts to retrieve. The 'post_type' can be anything, but WordPress
304  * post types are 'post', 'pages', and 'attachments'. The 'post_status'
305  * argument will accept any post status within the write administration panels.
306  *
307  * @since 2.0.0
308  *
309  * @see get_posts()
310  * @todo Check validity of description.
311  *
312  * @global WP_Post $post
313  *
314  * @param mixed  $args   Optional. User defined arguments for replacing the defaults. Default empty.
315  * @param string $output Optional. Constant for return type. Accepts OBJECT, ARRAY_A, ARRAY_N.
316  *                       Default OBJECT.
317  * @return array Array of children, where the type of each element is determined by $output parameter.
318  *               Empty array on failure.
319  */
320 function get_children( $args = '', $output = OBJECT ) {
321         $kids = array();
322         if ( empty( $args ) ) {
323                 if ( isset( $GLOBALS['post'] ) ) {
324                         $args = array('post_parent' => (int) $GLOBALS['post']->post_parent );
325                 } else {
326                         return $kids;
327                 }
328         } elseif ( is_object( $args ) ) {
329                 $args = array('post_parent' => (int) $args->post_parent );
330         } elseif ( is_numeric( $args ) ) {
331                 $args = array('post_parent' => (int) $args);
332         }
333
334         $defaults = array(
335                 'numberposts' => -1, 'post_type' => 'any',
336                 'post_status' => 'any', 'post_parent' => 0,
337         );
338
339         $r = wp_parse_args( $args, $defaults );
340
341         $children = get_posts( $r );
342
343         if ( ! $children )
344                 return $kids;
345
346         if ( ! empty( $r['fields'] ) )
347                 return $children;
348
349         update_post_cache($children);
350
351         foreach ( $children as $key => $child )
352                 $kids[$child->ID] = $children[$key];
353
354         if ( $output == OBJECT ) {
355                 return $kids;
356         } elseif ( $output == ARRAY_A ) {
357                 $weeuns = array();
358                 foreach ( (array) $kids as $kid ) {
359                         $weeuns[$kid->ID] = get_object_vars($kids[$kid->ID]);
360                 }
361                 return $weeuns;
362         } elseif ( $output == ARRAY_N ) {
363                 $babes = array();
364                 foreach ( (array) $kids as $kid ) {
365                         $babes[$kid->ID] = array_values(get_object_vars($kids[$kid->ID]));
366                 }
367                 return $babes;
368         } else {
369                 return $kids;
370         }
371 }
372
373 /**
374  * Get extended entry info (<!--more-->).
375  *
376  * There should not be any space after the second dash and before the word
377  * 'more'. There can be text or space(s) after the word 'more', but won't be
378  * referenced.
379  *
380  * The returned array has 'main', 'extended', and 'more_text' keys. Main has the text before
381  * the `<!--more-->`. The 'extended' key has the content after the
382  * `<!--more-->` comment. The 'more_text' key has the custom "Read More" text.
383  *
384  * @since 1.0.0
385  *
386  * @param string $post Post content.
387  * @return array Post before ('main'), after ('extended'), and custom read more ('more_text').
388  */
389 function get_extended( $post ) {
390         //Match the new style more links.
391         if ( preg_match('/<!--more(.*?)?-->/', $post, $matches) ) {
392                 list($main, $extended) = explode($matches[0], $post, 2);
393                 $more_text = $matches[1];
394         } else {
395                 $main = $post;
396                 $extended = '';
397                 $more_text = '';
398         }
399
400         //  leading and trailing whitespace.
401         $main = preg_replace('/^[\s]*(.*)[\s]*$/', '\\1', $main);
402         $extended = preg_replace('/^[\s]*(.*)[\s]*$/', '\\1', $extended);
403         $more_text = preg_replace('/^[\s]*(.*)[\s]*$/', '\\1', $more_text);
404
405         return array( 'main' => $main, 'extended' => $extended, 'more_text' => $more_text );
406 }
407
408 /**
409  * Retrieves post data given a post ID or post object.
410  *
411  * See {@link sanitize_post()} for optional $filter values. Also, the parameter
412  * $post, must be given as a variable, since it is passed by reference.
413  *
414  * @since 1.5.1
415  *
416  * @global WP_Post $post
417  *
418  * @param int|WP_Post|null $post   Optional. Post ID or post object. Defaults to global $post.
419  * @param string           $output Optional, default is Object. Accepts OBJECT, ARRAY_A, or ARRAY_N.
420  *                                 Default OBJECT.
421  * @param string           $filter Optional. Type of filter to apply. Accepts 'raw', 'edit', 'db',
422  *                                 or 'display'. Default 'raw'.
423  * @return WP_Post|array|null Type corresponding to $output on success or null on failure.
424  *                            When $output is OBJECT, a `WP_Post` instance is returned.
425  */
426 function get_post( $post = null, $output = OBJECT, $filter = 'raw' ) {
427         if ( empty( $post ) && isset( $GLOBALS['post'] ) )
428                 $post = $GLOBALS['post'];
429
430         if ( $post instanceof WP_Post ) {
431                 $_post = $post;
432         } elseif ( is_object( $post ) ) {
433                 if ( empty( $post->filter ) ) {
434                         $_post = sanitize_post( $post, 'raw' );
435                         $_post = new WP_Post( $_post );
436                 } elseif ( 'raw' == $post->filter ) {
437                         $_post = new WP_Post( $post );
438                 } else {
439                         $_post = WP_Post::get_instance( $post->ID );
440                 }
441         } else {
442                 $_post = WP_Post::get_instance( $post );
443         }
444
445         if ( ! $_post )
446                 return null;
447
448         $_post = $_post->filter( $filter );
449
450         if ( $output == ARRAY_A )
451                 return $_post->to_array();
452         elseif ( $output == ARRAY_N )
453                 return array_values( $_post->to_array() );
454
455         return $_post;
456 }
457
458 /**
459  * Retrieve ancestors of a post.
460  *
461  * @since 2.5.0
462  *
463  * @param int|WP_Post $post Post ID or post object.
464  * @return array Ancestor IDs or empty array if none are found.
465  */
466 function get_post_ancestors( $post ) {
467         $post = get_post( $post );
468
469         if ( ! $post || empty( $post->post_parent ) || $post->post_parent == $post->ID )
470                 return array();
471
472         $ancestors = array();
473
474         $id = $ancestors[] = $post->post_parent;
475
476         while ( $ancestor = get_post( $id ) ) {
477                 // Loop detection: If the ancestor has been seen before, break.
478                 if ( empty( $ancestor->post_parent ) || ( $ancestor->post_parent == $post->ID ) || in_array( $ancestor->post_parent, $ancestors ) )
479                         break;
480
481                 $id = $ancestors[] = $ancestor->post_parent;
482         }
483
484         return $ancestors;
485 }
486
487 /**
488  * Retrieve data from a post field based on Post ID.
489  *
490  * Examples of the post field will be, 'post_type', 'post_status', 'post_content',
491  * etc and based off of the post object property or key names.
492  *
493  * The context values are based off of the taxonomy filter functions and
494  * supported values are found within those functions.
495  *
496  * @since 2.3.0
497  *
498  * @see sanitize_post_field()
499  *
500  * @param string      $field   Post field name.
501  * @param int|WP_Post $post    Post ID or post object.
502  * @param string      $context Optional. How to filter the field. Accepts 'raw', 'edit', 'db',
503  *                             or 'display'. Default 'display'.
504  * @return string The value of the post field on success, empty string on failure.
505  */
506 function get_post_field( $field, $post, $context = 'display' ) {
507         $post = get_post( $post );
508
509         if ( !$post )
510                 return '';
511
512         if ( !isset($post->$field) )
513                 return '';
514
515         return sanitize_post_field($field, $post->$field, $post->ID, $context);
516 }
517
518 /**
519  * Retrieve the mime type of an attachment based on the ID.
520  *
521  * This function can be used with any post type, but it makes more sense with
522  * attachments.
523  *
524  * @since 2.0.0
525  *
526  * @param int|WP_Post $ID Optional. Post ID or post object. Default empty.
527  * @return string|false The mime type on success, false on failure.
528  */
529 function get_post_mime_type( $ID = '' ) {
530         $post = get_post($ID);
531
532         if ( is_object($post) )
533                 return $post->post_mime_type;
534
535         return false;
536 }
537
538 /**
539  * Retrieve the post status based on the Post ID.
540  *
541  * If the post ID is of an attachment, then the parent post status will be given
542  * instead.
543  *
544  * @since 2.0.0
545  *
546  * @param int|WP_Post $ID Optional. Post ID or post object. Default empty.
547  * @return string|false Post status on success, false on failure.
548  */
549 function get_post_status( $ID = '' ) {
550         $post = get_post($ID);
551
552         if ( !is_object($post) )
553                 return false;
554
555         if ( 'attachment' == $post->post_type ) {
556                 if ( 'private' == $post->post_status )
557                         return 'private';
558
559                 // Unattached attachments are assumed to be published.
560                 if ( ( 'inherit' == $post->post_status ) && ( 0 == $post->post_parent) )
561                         return 'publish';
562
563                 // Inherit status from the parent.
564                 if ( $post->post_parent && ( $post->ID != $post->post_parent ) ) {
565                         $parent_post_status = get_post_status( $post->post_parent );
566                         if ( 'trash' == $parent_post_status ) {
567                                 return get_post_meta( $post->post_parent, '_wp_trash_meta_status', true );
568                         } else {
569                                 return $parent_post_status;
570                         }
571                 }
572
573         }
574
575         /**
576          * Filter the post status.
577          *
578          * @since 4.4.0
579          *
580          * @param string  $post_status The post status.
581          * @param WP_Post $post        The post object.
582          */
583         return apply_filters( 'get_post_status', $post->post_status, $post );
584 }
585
586 /**
587  * Retrieve all of the WordPress supported post statuses.
588  *
589  * Posts have a limited set of valid status values, this provides the
590  * post_status values and descriptions.
591  *
592  * @since 2.5.0
593  *
594  * @return array List of post statuses.
595  */
596 function get_post_statuses() {
597         $status = array(
598                 'draft'   => __( 'Draft' ),
599                 'pending' => __( 'Pending Review' ),
600                 'private' => __( 'Private' ),
601                 'publish' => __( 'Published' )
602         );
603
604         return $status;
605 }
606
607 /**
608  * Retrieve all of the WordPress support page statuses.
609  *
610  * Pages have a limited set of valid status values, this provides the
611  * post_status values and descriptions.
612  *
613  * @since 2.5.0
614  *
615  * @return array List of page statuses.
616  */
617 function get_page_statuses() {
618         $status = array(
619                 'draft'   => __( 'Draft' ),
620                 'private' => __( 'Private' ),
621                 'publish' => __( 'Published' )
622         );
623
624         return $status;
625 }
626
627 /**
628  * Register a post status. Do not use before init.
629  *
630  * A simple function for creating or modifying a post status based on the
631  * parameters given. The function will accept an array (second optional
632  * parameter), along with a string for the post status name.
633  *
634  * Arguments prefixed with an _underscore shouldn't be used by plugins and themes.
635  *
636  * @since 3.0.0
637  * @global array $wp_post_statuses Inserts new post status object into the list
638  *
639  * @param string $post_status Name of the post status.
640  * @param array|string $args {
641  *     Optional. Array or string of post status arguments.
642  *
643  *     @type bool|string $label                     A descriptive name for the post status marked
644  *                                                  for translation. Defaults to value of $post_status.
645  *     @type bool|array  $label_count               Descriptive text to use for nooped plurals.
646  *                                                  Default array of $label, twice
647  *     @type bool        $exclude_from_search       Whether to exclude posts with this post status
648  *                                                  from search results. Default is value of $internal.
649  *     @type bool        $_builtin                  Whether the status is built-in. Core-use only.
650  *                                                  Default false.
651  *     @type bool        $public                    Whether posts of this status should be shown
652  *                                                  in the front end of the site. Default false.
653  *     @type bool        $internal                  Whether the status is for internal use only.
654  *                                                  Default false.
655  *     @type bool        $protected                 Whether posts with this status should be protected.
656  *                                                  Default false.
657  *     @type bool        $private                   Whether posts with this status should be private.
658  *                                                  Default false.
659  *     @type bool        $publicly_queryable        Whether posts with this status should be publicly-
660  *                                                  queryable. Default is value of $public.
661  *     @type bool        $show_in_admin_all_list    Whether to include posts in the edit listing for
662  *                                                  their post type. Default is value of $internal.
663  *     @type bool        $show_in_admin_status_list Show in the list of statuses with post counts at
664  *                                                  the top of the edit listings,
665  *                                                  e.g. All (12) | Published (9) | My Custom Status (2)
666  *                                                  Default is value of $internal.
667  * }
668  * @return object
669  */
670 function register_post_status( $post_status, $args = array() ) {
671         global $wp_post_statuses;
672
673         if (!is_array($wp_post_statuses))
674                 $wp_post_statuses = array();
675
676         // Args prefixed with an underscore are reserved for internal use.
677         $defaults = array(
678                 'label' => false,
679                 'label_count' => false,
680                 'exclude_from_search' => null,
681                 '_builtin' => false,
682                 'public' => null,
683                 'internal' => null,
684                 'protected' => null,
685                 'private' => null,
686                 'publicly_queryable' => null,
687                 'show_in_admin_status_list' => null,
688                 'show_in_admin_all_list' => null,
689         );
690         $args = wp_parse_args($args, $defaults);
691         $args = (object) $args;
692
693         $post_status = sanitize_key($post_status);
694         $args->name = $post_status;
695
696         // Set various defaults.
697         if ( null === $args->public && null === $args->internal && null === $args->protected && null === $args->private )
698                 $args->internal = true;
699
700         if ( null === $args->public  )
701                 $args->public = false;
702
703         if ( null === $args->private  )
704                 $args->private = false;
705
706         if ( null === $args->protected  )
707                 $args->protected = false;
708
709         if ( null === $args->internal  )
710                 $args->internal = false;
711
712         if ( null === $args->publicly_queryable )
713                 $args->publicly_queryable = $args->public;
714
715         if ( null === $args->exclude_from_search )
716                 $args->exclude_from_search = $args->internal;
717
718         if ( null === $args->show_in_admin_all_list )
719                 $args->show_in_admin_all_list = !$args->internal;
720
721         if ( null === $args->show_in_admin_status_list )
722                 $args->show_in_admin_status_list = !$args->internal;
723
724         if ( false === $args->label )
725                 $args->label = $post_status;
726
727         if ( false === $args->label_count )
728                 $args->label_count = array( $args->label, $args->label );
729
730         $wp_post_statuses[$post_status] = $args;
731
732         return $args;
733 }
734
735 /**
736  * Retrieve a post status object by name.
737  *
738  * @since 3.0.0
739  *
740  * @global array $wp_post_statuses List of post statuses.
741  *
742  * @see register_post_status()
743  *
744  * @param string $post_status The name of a registered post status.
745  * @return object|null A post status object.
746  */
747 function get_post_status_object( $post_status ) {
748         global $wp_post_statuses;
749
750         if ( empty($wp_post_statuses[$post_status]) )
751                 return null;
752
753         return $wp_post_statuses[$post_status];
754 }
755
756 /**
757  * Get a list of post statuses.
758  *
759  * @since 3.0.0
760  *
761  * @global array $wp_post_statuses List of post statuses.
762  *
763  * @see register_post_status()
764  *
765  * @param array|string $args     Optional. Array or string of post status arguments to compare against
766  *                               properties of the global `$wp_post_statuses objects`. Default empty array.
767  * @param string       $output   Optional. The type of output to return, either 'names' or 'objects'. Default 'names'.
768  * @param string       $operator Optional. The logical operation to perform. 'or' means only one element
769  *                               from the array needs to match; 'and' means all elements must match.
770  *                               Default 'and'.
771  * @return array A list of post status names or objects.
772  */
773 function get_post_stati( $args = array(), $output = 'names', $operator = 'and' ) {
774         global $wp_post_statuses;
775
776         $field = ('names' == $output) ? 'name' : false;
777
778         return wp_filter_object_list($wp_post_statuses, $args, $operator, $field);
779 }
780
781 /**
782  * Whether the post type is hierarchical.
783  *
784  * A false return value might also mean that the post type does not exist.
785  *
786  * @since 3.0.0
787  *
788  * @see get_post_type_object()
789  *
790  * @param string $post_type Post type name
791  * @return bool Whether post type is hierarchical.
792  */
793 function is_post_type_hierarchical( $post_type ) {
794         if ( ! post_type_exists( $post_type ) )
795                 return false;
796
797         $post_type = get_post_type_object( $post_type );
798         return $post_type->hierarchical;
799 }
800
801 /**
802  * Check if a post type is registered.
803  *
804  * @since 3.0.0
805  *
806  * @see get_post_type_object()
807  *
808  * @param string $post_type Post type name.
809  * @return bool Whether post type is registered.
810  */
811 function post_type_exists( $post_type ) {
812         return (bool) get_post_type_object( $post_type );
813 }
814
815 /**
816  * Retrieve the post type of the current post or of a given post.
817  *
818  * @since 2.1.0
819  *
820  * @param int|WP_Post|null $post Optional. Post ID or post object. Default is global $post.
821  * @return string|false          Post type on success, false on failure.
822  */
823 function get_post_type( $post = null ) {
824         if ( $post = get_post( $post ) )
825                 return $post->post_type;
826
827         return false;
828 }
829
830 /**
831  * Retrieve a post type object by name.
832  *
833  * @since 3.0.0
834  *
835  * @global array $wp_post_types List of post types.
836  *
837  * @see register_post_type()
838  *
839  * @param string $post_type The name of a registered post type.
840  * @return object|null A post type object.
841  */
842 function get_post_type_object( $post_type ) {
843         global $wp_post_types;
844
845         if ( ! is_scalar( $post_type ) || empty( $wp_post_types[ $post_type ] ) ) {
846                 return null;
847         }
848
849         return $wp_post_types[ $post_type ];
850 }
851
852 /**
853  * Get a list of all registered post type objects.
854  *
855  * @since 2.9.0
856  *
857  * @global array $wp_post_types List of post types.
858  *
859  * @see register_post_type() for accepted arguments.
860  *
861  * @param array|string $args     Optional. An array of key => value arguments to match against
862  *                               the post type objects. Default empty array.
863  * @param string       $output   Optional. The type of output to return. Accepts post type 'names'
864  *                               or 'objects'. Default 'names'.
865  * @param string       $operator Optional. The logical operation to perform. 'or' means only one
866  *                               element from the array needs to match; 'and' means all elements
867  *                               must match. Accepts 'or' or 'and'. Default 'and'.
868  * @return array A list of post type names or objects.
869  */
870 function get_post_types( $args = array(), $output = 'names', $operator = 'and' ) {
871         global $wp_post_types;
872
873         $field = ('names' == $output) ? 'name' : false;
874
875         return wp_filter_object_list($wp_post_types, $args, $operator, $field);
876 }
877
878 /**
879  * Register a post type. Do not use before init.
880  *
881  * A function for creating or modifying a post type based on the
882  * parameters given. The function will accept an array (second optional
883  * parameter), along with a string for the post type name.
884  *
885  * @since 2.9.0
886  * @since 3.0.0 The `show_ui` argument is now enforced on the new post screen.
887  * @since 4.4.0 The `show_ui` argument is now enforced on the post type listing screen and post editing screen.
888  *
889  * @global array      $wp_post_types List of post types.
890  * @global WP_Rewrite $wp_rewrite    Used for default feeds.
891  * @global WP         $wp            Used to add query vars.
892  *
893  * @param string $post_type Post type key, must not exceed 20 characters.
894  * @param array|string $args {
895  *     Array or string of arguments for registering a post type.
896  *
897  *     @type string      $label                Name of the post type shown in the menu. Usually plural.
898  *                                             Default is value of $labels['name'].
899  *     @type array       $labels               An array of labels for this post type. If not set, post
900  *                                             labels are inherited for non-hierarchical types and page
901  *                                             labels for hierarchical ones. {@see get_post_type_labels()}.
902  *     @type string      $description          A short descriptive summary of what the post type is.
903  *                                             Default empty.
904  *     @type bool        $public               Whether a post type is intended for use publicly either via
905  *                                             the admin interface or by front-end users. While the default
906  *                                             settings of $exclude_from_search, $publicly_queryable, $show_ui,
907  *                                             and $show_in_nav_menus are inherited from public, each does not
908  *                                             rely on this relationship and controls a very specific intention.
909  *                                             Default false.
910  *     @type bool        $hierarchical         Whether the post type is hierarchical (e.g. page). Default false.
911  *     @type bool        $exclude_from_search  Whether to exclude posts with this post type from front end search
912  *                                             results. Default is the opposite value of $public.
913  *     @type bool        $publicly_queryable   Whether queries can be performed on the front end for the post type
914  *                                             as part of {@see parse_request()}. Endpoints would include:
915  *                                             * ?post_type={post_type_key}
916  *                                             * ?{post_type_key}={single_post_slug}
917  *                                             * ?{post_type_query_var}={single_post_slug}
918  *                                             If not set, the default is inherited from $public.
919  *     @type bool        $show_ui              Whether to generate and allow a UI for managing this post type in the
920  *                                             admin. Default is value of $public.
921  *     @type bool        $show_in_menu         Where to show the post type in the admin menu. To work, $show_ui
922  *                                             must be true. If true, the post type is shown in its own top level
923  *                                             menu. If false, no menu is shown. If a string of an existing top
924  *                                             level menu (eg. 'tools.php' or 'edit.php?post_type=page'), the post
925  *                                             type will be placed as a sub-menu of that.
926  *                                             Default is value of $show_ui.
927  *     @type bool        $show_in_nav_menus    Makes this post type available for selection in navigation menus.
928  *                                             Default is value $public.
929  *     @type bool        $show_in_admin_bar    Makes this post type available via the admin bar. Default is value
930  *                                             of $show_in_menu.
931  *     @type int         $menu_position        The position in the menu order the post type should appear. To work,
932  *                                             $show_in_menu must be true. Default null (at the bottom).
933  *     @type string      $menu_icon            The url to the icon to be used for this menu. Pass a base64-encoded
934  *                                             SVG using a data URI, which will be colored to match the color scheme
935  *                                             -- this should begin with 'data:image/svg+xml;base64,'. Pass the name
936  *                                             of a Dashicons helper class to use a font icon, e.g.
937  *                                             'dashicons-chart-pie'. Pass 'none' to leave div.wp-menu-image empty
938  *                                             so an icon can be added via CSS. Defaults to use the posts icon.
939  *     @type string      $capability_type      The string to use to build the read, edit, and delete capabilities.
940  *                                             May be passed as an array to allow for alternative plurals when using
941  *                                             this argument as a base to construct the capabilities, e.g.
942  *                                             array('story', 'stories'). Default 'post'.
943  *     @type array       $capabilities         Array of capabilities for this post type. $capability_type is used
944  *                                             as a base to construct capabilities by default.
945  *                                             {@see get_post_type_capabilities()}.
946  *     @type bool        $map_meta_cap         Whether to use the internal default meta capability handling.
947  *                                             Default false.
948  *     @type array       $supports             An alias for calling {@see add_post_type_support()} directly.
949  *                                             Defaults to array containing 'title' & 'editor'.
950  *     @type callable    $register_meta_box_cb Provide a callback function that sets up the meta boxes for the
951  *                                             edit form. Do remove_meta_box() and add_meta_box() calls in the
952  *                                             callback. Default null.
953  *     @type array       $taxonomies           An array of taxonomy identifiers that will be registered for the
954  *                                             post type. Taxonomies can be registered later with
955  *                                             {@see register_taxonomy()} or {@see register_taxonomy_for_object_type()}.
956  *                                             Default empty array.
957  *     @type bool|string $has_archive          Whether there should be post type archives, or if a string, the
958  *                                             archive slug to use. Will generate the proper rewrite rules if
959  *                                             $rewrite is enabled. Default false.
960  *     @type bool|array  $rewrite              {
961  *         Triggers the handling of rewrites for this post type. To prevent rewrite, set to false.
962  *         Defaults to true, using $post_type as slug. To specify rewrite rules, an array can be
963  *         passed with any of these keys:
964  *
965  *         @type string $slug       Customize the permastruct slug. Defaults to $post_type key.
966  *         @type bool   $with_front Whether the permastruct should be prepended with WP_Rewrite::$front.
967  *                                  Default true.
968  *         @type bool   $feeds      Whether the feed permastruct should be built for this post type.
969  *                                  Default is value of $has_archive.
970  *         @type bool   $pages      Whether the permastruct should provide for pagination. Default true.
971  *         @type const  $ep_mask    Endpoint mask to assign. If not specified and permalink_epmask is set,
972  *                                  inherits from $permalink_epmask. If not specified and permalink_epmask
973  *                                  is not set, defaults to EP_PERMALINK.
974  *     }
975  *     @type string|bool $query_var            Sets the query_var key for this post type. Defaults to $post_type
976  *                                             key. If false, a post type cannot be loaded at
977  *                                             ?{query_var}={post_slug}. If specified as a string, the query
978  *                                             ?{query_var_string}={post_slug} will be valid.
979  *     @type bool        $can_export           Whether to allow this post type to be exported. Default true.
980  *     @type bool        $delete_with_user     Whether to delete posts of this type when deleting a user. If true,
981  *                                             posts of this type belonging to the user will be moved to trash
982  *                                             when then user is deleted. If false, posts of this type belonging
983  *                                             to the user will *not* be trashed or deleted. If not set (the default),
984  *                                             posts are trashed if post_type_supports('author'). Otherwise posts
985  *                                             are not trashed or deleted. Default null.
986  *     @type bool        $_builtin             FOR INTERNAL USE ONLY! True if this post type is a native or
987  *                                             "built-in" post_type. Default false.
988  *     @type string      $_edit_link           FOR INTERNAL USE ONLY! URL segment to use for edit link of
989  *                                             this post type. Default 'post.php?post=%d'.
990  * }
991  * @return object|WP_Error The registered post type object, or an error object.
992  */
993 function register_post_type( $post_type, $args = array() ) {
994         global $wp_post_types, $wp_rewrite, $wp;
995
996         if ( ! is_array( $wp_post_types ) ) {
997                 $wp_post_types = array();
998         }
999
1000         // Sanitize post type name
1001         $post_type = sanitize_key( $post_type );
1002         $args      = wp_parse_args( $args );
1003
1004         /**
1005          * Filter the arguments for registering a post type.
1006          *
1007          * @since 4.4.0
1008          *
1009          * @param array  $args      Array of arguments for registering a post type.
1010          * @param string $post_type Post type key.
1011          */
1012         $args = apply_filters( 'register_post_type_args', $args, $post_type );
1013
1014         $has_edit_link = ! empty( $args['_edit_link'] );
1015
1016         // Args prefixed with an underscore are reserved for internal use.
1017         $defaults = array(
1018                 'labels'               => array(),
1019                 'description'          => '',
1020                 'public'               => false,
1021                 'hierarchical'         => false,
1022                 'exclude_from_search'  => null,
1023                 'publicly_queryable'   => null,
1024                 'show_ui'              => null,
1025                 'show_in_menu'         => null,
1026                 'show_in_nav_menus'    => null,
1027                 'show_in_admin_bar'    => null,
1028                 'menu_position'        => null,
1029                 'menu_icon'            => null,
1030                 'capability_type'      => 'post',
1031                 'capabilities'         => array(),
1032                 'map_meta_cap'         => null,
1033                 'supports'             => array(),
1034                 'register_meta_box_cb' => null,
1035                 'taxonomies'           => array(),
1036                 'has_archive'          => false,
1037                 'rewrite'              => true,
1038                 'query_var'            => true,
1039                 'can_export'           => true,
1040                 'delete_with_user'     => null,
1041                 '_builtin'             => false,
1042                 '_edit_link'           => 'post.php?post=%d',
1043         );
1044         $args = array_merge( $defaults, $args );
1045         $args = (object) $args;
1046
1047         $args->name = $post_type;
1048
1049         if ( empty( $post_type ) || strlen( $post_type ) > 20 ) {
1050                 _doing_it_wrong( __FUNCTION__, __( 'Post type names must be between 1 and 20 characters in length.' ), '4.2' );
1051                 return new WP_Error( 'post_type_length_invalid', __( 'Post type names must be between 1 and 20 characters in length.' ) );
1052         }
1053
1054         // If not set, default to the setting for public.
1055         if ( null === $args->publicly_queryable )
1056                 $args->publicly_queryable = $args->public;
1057
1058         // If not set, default to the setting for public.
1059         if ( null === $args->show_ui )
1060                 $args->show_ui = $args->public;
1061
1062         // If not set, default to the setting for show_ui.
1063         if ( null === $args->show_in_menu || ! $args->show_ui )
1064                 $args->show_in_menu = $args->show_ui;
1065
1066         // If not set, default to the whether the full UI is shown.
1067         if ( null === $args->show_in_admin_bar )
1068                 $args->show_in_admin_bar = (bool) $args->show_in_menu;
1069
1070         // If not set, default to the setting for public.
1071         if ( null === $args->show_in_nav_menus )
1072                 $args->show_in_nav_menus = $args->public;
1073
1074         // If not set, default to true if not public, false if public.
1075         if ( null === $args->exclude_from_search )
1076                 $args->exclude_from_search = !$args->public;
1077
1078         // Back compat with quirky handling in version 3.0. #14122.
1079         if ( empty( $args->capabilities ) && null === $args->map_meta_cap && in_array( $args->capability_type, array( 'post', 'page' ) ) )
1080                 $args->map_meta_cap = true;
1081
1082         // If not set, default to false.
1083         if ( null === $args->map_meta_cap )
1084                 $args->map_meta_cap = false;
1085
1086         // If there's no specified edit link and no UI, remove the edit link.
1087         if ( ! $args->show_ui && ! $has_edit_link ) {
1088                 $args->_edit_link = '';
1089         }
1090
1091         $args->cap = get_post_type_capabilities( $args );
1092         unset( $args->capabilities );
1093
1094         if ( is_array( $args->capability_type ) )
1095                 $args->capability_type = $args->capability_type[0];
1096
1097         if ( ! empty( $args->supports ) ) {
1098                 add_post_type_support( $post_type, $args->supports );
1099                 unset( $args->supports );
1100         } elseif ( false !== $args->supports ) {
1101                 // Add default features
1102                 add_post_type_support( $post_type, array( 'title', 'editor' ) );
1103         }
1104
1105         if ( false !== $args->query_var ) {
1106                 if ( true === $args->query_var )
1107                         $args->query_var = $post_type;
1108                 else
1109                         $args->query_var = sanitize_title_with_dashes( $args->query_var );
1110
1111                 if ( $wp && is_post_type_viewable( $args ) ) {
1112                         $wp->add_query_var( $args->query_var );
1113                 }
1114         }
1115
1116         if ( false !== $args->rewrite && ( is_admin() || '' != get_option( 'permalink_structure' ) ) ) {
1117                 if ( ! is_array( $args->rewrite ) )
1118                         $args->rewrite = array();
1119                 if ( empty( $args->rewrite['slug'] ) )
1120                         $args->rewrite['slug'] = $post_type;
1121                 if ( ! isset( $args->rewrite['with_front'] ) )
1122                         $args->rewrite['with_front'] = true;
1123                 if ( ! isset( $args->rewrite['pages'] ) )
1124                         $args->rewrite['pages'] = true;
1125                 if ( ! isset( $args->rewrite['feeds'] ) || ! $args->has_archive )
1126                         $args->rewrite['feeds'] = (bool) $args->has_archive;
1127                 if ( ! isset( $args->rewrite['ep_mask'] ) ) {
1128                         if ( isset( $args->permalink_epmask ) )
1129                                 $args->rewrite['ep_mask'] = $args->permalink_epmask;
1130                         else
1131                                 $args->rewrite['ep_mask'] = EP_PERMALINK;
1132                 }
1133
1134                 if ( $args->hierarchical )
1135                         add_rewrite_tag( "%$post_type%", '(.+?)', $args->query_var ? "{$args->query_var}=" : "post_type=$post_type&pagename=" );
1136                 else
1137                         add_rewrite_tag( "%$post_type%", '([^/]+)', $args->query_var ? "{$args->query_var}=" : "post_type=$post_type&name=" );
1138
1139                 if ( $args->has_archive ) {
1140                         $archive_slug = $args->has_archive === true ? $args->rewrite['slug'] : $args->has_archive;
1141                         if ( $args->rewrite['with_front'] )
1142                                 $archive_slug = substr( $wp_rewrite->front, 1 ) . $archive_slug;
1143                         else
1144                                 $archive_slug = $wp_rewrite->root . $archive_slug;
1145
1146                         add_rewrite_rule( "{$archive_slug}/?$", "index.php?post_type=$post_type", 'top' );
1147                         if ( $args->rewrite['feeds'] && $wp_rewrite->feeds ) {
1148                                 $feeds = '(' . trim( implode( '|', $wp_rewrite->feeds ) ) . ')';
1149                                 add_rewrite_rule( "{$archive_slug}/feed/$feeds/?$", "index.php?post_type=$post_type" . '&feed=$matches[1]', 'top' );
1150                                 add_rewrite_rule( "{$archive_slug}/$feeds/?$", "index.php?post_type=$post_type" . '&feed=$matches[1]', 'top' );
1151                         }
1152                         if ( $args->rewrite['pages'] )
1153                                 add_rewrite_rule( "{$archive_slug}/{$wp_rewrite->pagination_base}/([0-9]{1,})/?$", "index.php?post_type=$post_type" . '&paged=$matches[1]', 'top' );
1154                 }
1155
1156                 $permastruct_args = $args->rewrite;
1157                 $permastruct_args['feed'] = $permastruct_args['feeds'];
1158                 add_permastruct( $post_type, "{$args->rewrite['slug']}/%$post_type%", $permastruct_args );
1159         }
1160
1161         // Register the post type meta box if a custom callback was specified.
1162         if ( $args->register_meta_box_cb )
1163                 add_action( 'add_meta_boxes_' . $post_type, $args->register_meta_box_cb, 10, 1 );
1164
1165         $args->labels = get_post_type_labels( $args );
1166         $args->label = $args->labels->name;
1167
1168         $wp_post_types[ $post_type ] = $args;
1169
1170         add_action( 'future_' . $post_type, '_future_post_hook', 5, 2 );
1171
1172         foreach ( $args->taxonomies as $taxonomy ) {
1173                 register_taxonomy_for_object_type( $taxonomy, $post_type );
1174         }
1175
1176         /**
1177          * Fires after a post type is registered.
1178          *
1179          * @since 3.3.0
1180          *
1181          * @param string $post_type Post type.
1182          * @param object $args      Arguments used to register the post type.
1183          */
1184         do_action( 'registered_post_type', $post_type, $args );
1185
1186         return $args;
1187 }
1188
1189 /**
1190  * Build an object with all post type capabilities out of a post type object
1191  *
1192  * Post type capabilities use the 'capability_type' argument as a base, if the
1193  * capability is not set in the 'capabilities' argument array or if the
1194  * 'capabilities' argument is not supplied.
1195  *
1196  * The capability_type argument can optionally be registered as an array, with
1197  * the first value being singular and the second plural, e.g. array('story, 'stories')
1198  * Otherwise, an 's' will be added to the value for the plural form. After
1199  * registration, capability_type will always be a string of the singular value.
1200  *
1201  * By default, seven keys are accepted as part of the capabilities array:
1202  *
1203  * - edit_post, read_post, and delete_post are meta capabilities, which are then
1204  *   generally mapped to corresponding primitive capabilities depending on the
1205  *   context, which would be the post being edited/read/deleted and the user or
1206  *   role being checked. Thus these capabilities would generally not be granted
1207  *   directly to users or roles.
1208  *
1209  * - edit_posts - Controls whether objects of this post type can be edited.
1210  * - edit_others_posts - Controls whether objects of this type owned by other users
1211  *   can be edited. If the post type does not support an author, then this will
1212  *   behave like edit_posts.
1213  * - publish_posts - Controls publishing objects of this post type.
1214  * - read_private_posts - Controls whether private objects can be read.
1215  *
1216  * These four primitive capabilities are checked in core in various locations.
1217  * There are also seven other primitive capabilities which are not referenced
1218  * directly in core, except in map_meta_cap(), which takes the three aforementioned
1219  * meta capabilities and translates them into one or more primitive capabilities
1220  * that must then be checked against the user or role, depending on the context.
1221  *
1222  * - read - Controls whether objects of this post type can be read.
1223  * - delete_posts - Controls whether objects of this post type can be deleted.
1224  * - delete_private_posts - Controls whether private objects can be deleted.
1225  * - delete_published_posts - Controls whether published objects can be deleted.
1226  * - delete_others_posts - Controls whether objects owned by other users can be
1227  *   can be deleted. If the post type does not support an author, then this will
1228  *   behave like delete_posts.
1229  * - edit_private_posts - Controls whether private objects can be edited.
1230  * - edit_published_posts - Controls whether published objects can be edited.
1231  *
1232  * These additional capabilities are only used in map_meta_cap(). Thus, they are
1233  * only assigned by default if the post type is registered with the 'map_meta_cap'
1234  * argument set to true (default is false).
1235  *
1236  * @since 3.0.0
1237  *
1238  * @see register_post_type()
1239  * @see map_meta_cap()
1240  *
1241  * @param object $args Post type registration arguments.
1242  * @return object object with all the capabilities as member variables.
1243  */
1244 function get_post_type_capabilities( $args ) {
1245         if ( ! is_array( $args->capability_type ) )
1246                 $args->capability_type = array( $args->capability_type, $args->capability_type . 's' );
1247
1248         // Singular base for meta capabilities, plural base for primitive capabilities.
1249         list( $singular_base, $plural_base ) = $args->capability_type;
1250
1251         $default_capabilities = array(
1252                 // Meta capabilities
1253                 'edit_post'          => 'edit_'         . $singular_base,
1254                 'read_post'          => 'read_'         . $singular_base,
1255                 'delete_post'        => 'delete_'       . $singular_base,
1256                 // Primitive capabilities used outside of map_meta_cap():
1257                 'edit_posts'         => 'edit_'         . $plural_base,
1258                 'edit_others_posts'  => 'edit_others_'  . $plural_base,
1259                 'publish_posts'      => 'publish_'      . $plural_base,
1260                 'read_private_posts' => 'read_private_' . $plural_base,
1261         );
1262
1263         // Primitive capabilities used within map_meta_cap():
1264         if ( $args->map_meta_cap ) {
1265                 $default_capabilities_for_mapping = array(
1266                         'read'                   => 'read',
1267                         'delete_posts'           => 'delete_'           . $plural_base,
1268                         'delete_private_posts'   => 'delete_private_'   . $plural_base,
1269                         'delete_published_posts' => 'delete_published_' . $plural_base,
1270                         'delete_others_posts'    => 'delete_others_'    . $plural_base,
1271                         'edit_private_posts'     => 'edit_private_'     . $plural_base,
1272                         'edit_published_posts'   => 'edit_published_'   . $plural_base,
1273                 );
1274                 $default_capabilities = array_merge( $default_capabilities, $default_capabilities_for_mapping );
1275         }
1276
1277         $capabilities = array_merge( $default_capabilities, $args->capabilities );
1278
1279         // Post creation capability simply maps to edit_posts by default:
1280         if ( ! isset( $capabilities['create_posts'] ) )
1281                 $capabilities['create_posts'] = $capabilities['edit_posts'];
1282
1283         // Remember meta capabilities for future reference.
1284         if ( $args->map_meta_cap )
1285                 _post_type_meta_capabilities( $capabilities );
1286
1287         return (object) $capabilities;
1288 }
1289
1290 /**
1291  * Store or return a list of post type meta caps for map_meta_cap().
1292  *
1293  * @since 3.1.0
1294  * @access private
1295  *
1296  * @staticvar array $meta_caps
1297  *
1298  * @param array|void $capabilities Post type meta capabilities.
1299  */
1300 function _post_type_meta_capabilities( $capabilities = null ) {
1301         static $meta_caps = array();
1302         if ( null === $capabilities )
1303                 return $meta_caps;
1304         foreach ( $capabilities as $core => $custom ) {
1305                 if ( in_array( $core, array( 'read_post', 'delete_post', 'edit_post' ) ) )
1306                         $meta_caps[ $custom ] = $core;
1307         }
1308 }
1309
1310 /**
1311  * Build an object with all post type labels out of a post type object
1312  *
1313  * Accepted keys of the label array in the post type object:
1314  *
1315  * - name - general name for the post type, usually plural. The same and overridden
1316  *          by $post_type_object->label. Default is Posts/Pages
1317  * - singular_name - name for one object of this post type. Default is Post/Page
1318  * - add_new - Default is Add New for both hierarchical and non-hierarchical types.
1319  *             When internationalizing this string, please use a gettext context
1320  *             {@link https://codex.wordpress.org/I18n_for_WordPress_Developers#Disambiguation_by_context}
1321  *             matching your post type. Example: `_x( 'Add New', 'product' );`.
1322  * - add_new_item - Default is Add New Post/Add New Page.
1323  * - edit_item - Default is Edit Post/Edit Page.
1324  * - new_item - Default is New Post/New Page.
1325  * - view_item - Default is View Post/View Page.
1326  * - search_items - Default is Search Posts/Search Pages.
1327  * - not_found - Default is No posts found/No pages found.
1328  * - not_found_in_trash - Default is No posts found in Trash/No pages found in Trash.
1329  * - parent_item_colon - This string isn't used on non-hierarchical types. In hierarchical
1330  *                       ones the default is 'Parent Page:'.
1331  * - all_items - String for the submenu. Default is All Posts/All Pages.
1332  * - archives - String for use with archives in nav menus. Default is Post Archives/Page Archives.
1333  * - insert_into_item - String for the media frame button. Default is Insert into post/Insert into page.
1334  * - uploaded_to_this_item - String for the media frame filter. Default is Uploaded to this post/Uploaded to this page.
1335  * - featured_image - Default is Featured Image.
1336  * - set_featured_image - Default is Set featured image.
1337  * - remove_featured_image - Default is Remove featured image.
1338  * - use_featured_image - Default is Use as featured image.
1339  * - menu_name - Default is the same as `name`.
1340  * - filter_items_list - String for the table views hidden heading.
1341  * - items_list_navigation - String for the table pagination hidden heading.
1342  * - items_list - String for the table hidden heading.
1343  *
1344  * Above, the first default value is for non-hierarchical post types (like posts)
1345  * and the second one is for hierarchical post types (like pages).
1346  *
1347  * @since 3.0.0
1348  * @since 4.3.0 Added the `featured_image`, `set_featured_image`, `remove_featured_image`,
1349  *              and `use_featured_image` labels.
1350  * @since 4.4.0 Added the `insert_into_item`, `uploaded_to_this_item`, `filter_items_list`,
1351  *              `items_list_navigation`, and `items_list` labels.
1352  *
1353  * @access private
1354  *
1355  * @param object $post_type_object Post type object.
1356  * @return object object with all the labels as member variables.
1357  */
1358 function get_post_type_labels( $post_type_object ) {
1359         $nohier_vs_hier_defaults = array(
1360                 'name' => array( _x('Posts', 'post type general name'), _x('Pages', 'post type general name') ),
1361                 'singular_name' => array( _x('Post', 'post type singular name'), _x('Page', 'post type singular name') ),
1362                 'add_new' => array( _x('Add New', 'post'), _x('Add New', 'page') ),
1363                 'add_new_item' => array( __('Add New Post'), __('Add New Page') ),
1364                 'edit_item' => array( __('Edit Post'), __('Edit Page') ),
1365                 'new_item' => array( __('New Post'), __('New Page') ),
1366                 'view_item' => array( __('View Post'), __('View Page') ),
1367                 'search_items' => array( __('Search Posts'), __('Search Pages') ),
1368                 'not_found' => array( __('No posts found.'), __('No pages found.') ),
1369                 'not_found_in_trash' => array( __('No posts found in Trash.'), __('No pages found in Trash.') ),
1370                 'parent_item_colon' => array( null, __('Parent Page:') ),
1371                 'all_items' => array( __( 'All Posts' ), __( 'All Pages' ) ),
1372                 'archives' => array( __( 'Post Archives' ), __( 'Page Archives' ) ),
1373                 'insert_into_item' => array( __( 'Insert into post' ), __( 'Insert into page' ) ),
1374                 'uploaded_to_this_item' => array( __( 'Uploaded to this post' ), __( 'Uploaded to this page' ) ),
1375                 'featured_image' => array( __( 'Featured Image' ), __( 'Featured Image' ) ),
1376                 'set_featured_image' => array( __( 'Set featured image' ), __( 'Set featured image' ) ),
1377                 'remove_featured_image' => array( __( 'Remove featured image' ), __( 'Remove featured image' ) ),
1378                 'use_featured_image' => array( __( 'Use as featured image' ), __( 'Use as featured image' ) ),
1379                 'filter_items_list' => array( __( 'Filter posts list' ), __( 'Filter pages list' ) ),
1380                 'items_list_navigation' => array( __( 'Posts list navigation' ), __( 'Pages list navigation' ) ),
1381                 'items_list' => array( __( 'Posts list' ), __( 'Pages list' ) ),
1382         );
1383         $nohier_vs_hier_defaults['menu_name'] = $nohier_vs_hier_defaults['name'];
1384
1385         $labels = _get_custom_object_labels( $post_type_object, $nohier_vs_hier_defaults );
1386
1387         $post_type = $post_type_object->name;
1388
1389         $default_labels = clone $labels;
1390
1391         /**
1392          * Filter the labels of a specific post type.
1393          *
1394          * The dynamic portion of the hook name, `$post_type`, refers to
1395          * the post type slug.
1396          *
1397          * @since 3.5.0
1398          *
1399          * @see get_post_type_labels() for the full list of labels.
1400          *
1401          * @param object $labels Object with labels for the post type as member variables.
1402          */
1403         $labels = apply_filters( "post_type_labels_{$post_type}", $labels );
1404
1405         // Ensure that the filtered labels contain all required default values.
1406         $labels = (object) array_merge( (array) $default_labels, (array) $labels );
1407
1408         return $labels;
1409 }
1410
1411 /**
1412  * Build an object with custom-something object (post type, taxonomy) labels
1413  * out of a custom-something object
1414  *
1415  * @since 3.0.0
1416  * @access private
1417  *
1418  * @param object $object                  A custom-something object.
1419  * @param array  $nohier_vs_hier_defaults Hierarchical vs non-hierarchical default labels.
1420  * @return object Object containing labels for the given custom-something object.
1421  */
1422 function _get_custom_object_labels( $object, $nohier_vs_hier_defaults ) {
1423         $object->labels = (array) $object->labels;
1424
1425         if ( isset( $object->label ) && empty( $object->labels['name'] ) )
1426                 $object->labels['name'] = $object->label;
1427
1428         if ( !isset( $object->labels['singular_name'] ) && isset( $object->labels['name'] ) )
1429                 $object->labels['singular_name'] = $object->labels['name'];
1430
1431         if ( ! isset( $object->labels['name_admin_bar'] ) )
1432                 $object->labels['name_admin_bar'] = isset( $object->labels['singular_name'] ) ? $object->labels['singular_name'] : $object->name;
1433
1434         if ( !isset( $object->labels['menu_name'] ) && isset( $object->labels['name'] ) )
1435                 $object->labels['menu_name'] = $object->labels['name'];
1436
1437         if ( !isset( $object->labels['all_items'] ) && isset( $object->labels['menu_name'] ) )
1438                 $object->labels['all_items'] = $object->labels['menu_name'];
1439
1440         if ( !isset( $object->labels['archives'] ) && isset( $object->labels['all_items'] ) ) {
1441                 $object->labels['archives'] = $object->labels['all_items'];
1442         }
1443
1444         $defaults = array();
1445         foreach ( $nohier_vs_hier_defaults as $key => $value ) {
1446                 $defaults[$key] = $object->hierarchical ? $value[1] : $value[0];
1447         }
1448         $labels = array_merge( $defaults, $object->labels );
1449         $object->labels = (object) $object->labels;
1450
1451         return (object) $labels;
1452 }
1453
1454 /**
1455  * Add submenus for post types.
1456  *
1457  * @access private
1458  * @since 3.1.0
1459  */
1460 function _add_post_type_submenus() {
1461         foreach ( get_post_types( array( 'show_ui' => true ) ) as $ptype ) {
1462                 $ptype_obj = get_post_type_object( $ptype );
1463                 // Sub-menus only.
1464                 if ( ! $ptype_obj->show_in_menu || $ptype_obj->show_in_menu === true )
1465                         continue;
1466                 add_submenu_page( $ptype_obj->show_in_menu, $ptype_obj->labels->name, $ptype_obj->labels->all_items, $ptype_obj->cap->edit_posts, "edit.php?post_type=$ptype" );
1467         }
1468 }
1469
1470 /**
1471  * Register support of certain features for a post type.
1472  *
1473  * All core features are directly associated with a functional area of the edit
1474  * screen, such as the editor or a meta box. Features include: 'title', 'editor',
1475  * 'comments', 'revisions', 'trackbacks', 'author', 'excerpt', 'page-attributes',
1476  * 'thumbnail', 'custom-fields', and 'post-formats'.
1477  *
1478  * Additionally, the 'revisions' feature dictates whether the post type will
1479  * store revisions, and the 'comments' feature dictates whether the comments
1480  * count will show on the edit screen.
1481  *
1482  * @since 3.0.0
1483  *
1484  * @global array $_wp_post_type_features
1485  *
1486  * @param string       $post_type The post type for which to add the feature.
1487  * @param string|array $feature   The feature being added, accepts an array of
1488  *                                feature strings or a single string.
1489  */
1490 function add_post_type_support( $post_type, $feature ) {
1491         global $_wp_post_type_features;
1492
1493         $features = (array) $feature;
1494         foreach ($features as $feature) {
1495                 if ( func_num_args() == 2 )
1496                         $_wp_post_type_features[$post_type][$feature] = true;
1497                 else
1498                         $_wp_post_type_features[$post_type][$feature] = array_slice( func_get_args(), 2 );
1499         }
1500 }
1501
1502 /**
1503  * Remove support for a feature from a post type.
1504  *
1505  * @since 3.0.0
1506  *
1507  * @global array $_wp_post_type_features
1508  *
1509  * @param string $post_type The post type for which to remove the feature.
1510  * @param string $feature   The feature being removed.
1511  */
1512 function remove_post_type_support( $post_type, $feature ) {
1513         global $_wp_post_type_features;
1514
1515         unset( $_wp_post_type_features[ $post_type ][ $feature ] );
1516 }
1517
1518 /**
1519  * Get all the post type features
1520  *
1521  * @since 3.4.0
1522  *
1523  * @global array $_wp_post_type_features
1524  *
1525  * @param string $post_type The post type.
1526  * @return array Post type supports list.
1527  */
1528 function get_all_post_type_supports( $post_type ) {
1529         global $_wp_post_type_features;
1530
1531         if ( isset( $_wp_post_type_features[$post_type] ) )
1532                 return $_wp_post_type_features[$post_type];
1533
1534         return array();
1535 }
1536
1537 /**
1538  * Check a post type's support for a given feature.
1539  *
1540  * @since 3.0.0
1541  *
1542  * @global array $_wp_post_type_features
1543  *
1544  * @param string $post_type The post type being checked.
1545  * @param string $feature   The feature being checked.
1546  * @return bool Whether the post type supports the given feature.
1547  */
1548 function post_type_supports( $post_type, $feature ) {
1549         global $_wp_post_type_features;
1550
1551         return ( isset( $_wp_post_type_features[$post_type][$feature] ) );
1552 }
1553
1554 /**
1555  * Update the post type for the post ID.
1556  *
1557  * The page or post cache will be cleaned for the post ID.
1558  *
1559  * @since 2.5.0
1560  *
1561  * @global wpdb $wpdb WordPress database abstraction object.
1562  *
1563  * @param int    $post_id   Optional. Post ID to change post type. Default 0.
1564  * @param string $post_type Optional. Post type. Accepts 'post' or 'page' to
1565  *                          name a few. Default 'post'.
1566  * @return int|false Amount of rows changed. Should be 1 for success and 0 for failure.
1567  */
1568 function set_post_type( $post_id = 0, $post_type = 'post' ) {
1569         global $wpdb;
1570
1571         $post_type = sanitize_post_field('post_type', $post_type, $post_id, 'db');
1572         $return = $wpdb->update( $wpdb->posts, array('post_type' => $post_type), array('ID' => $post_id) );
1573
1574         clean_post_cache( $post_id );
1575
1576         return $return;
1577 }
1578
1579 /**
1580  * Determines whether a post type is considered "viewable".
1581  *
1582  * For built-in post types such as posts and pages, the 'public' value will be evaluated.
1583  * For all others, the 'publicly_queryable' value will be used.
1584  *
1585  * @since 4.4.0
1586  *
1587  * @param object $post_type_object Post type object.
1588  * @return bool Whether the post type should be considered viewable.
1589  */
1590 function is_post_type_viewable( $post_type_object ) {
1591         return $post_type_object->publicly_queryable || ( $post_type_object->_builtin && $post_type_object->public );
1592 }
1593
1594 /**
1595  * Retrieve list of latest posts or posts matching criteria.
1596  *
1597  * The defaults are as follows:
1598  *
1599  * @since 1.2.0
1600  *
1601  * @see WP_Query::parse_query()
1602  *
1603  * @param array $args {
1604  *     Optional. Arguments to retrieve posts. See WP_Query::parse_query() for all
1605  *     available arguments.
1606  *
1607  *     @type int        $numberposts      Total number of posts to retrieve. Is an alias of $posts_per_page
1608  *                                        in WP_Query. Accepts -1 for all. Default 5.
1609  *     @type int|string $category         Category ID or comma-separated list of IDs (this or any children).
1610  *                                        Is an alias of $cat in WP_Query. Default 0.
1611  *     @type array      $include          An array of post IDs to retrieve, sticky posts will be included.
1612  *                                        Is an alias of $post__in in WP_Query. Default empty array.
1613  *     @type array      $exclude          An array of post IDs not to retrieve. Default empty array.
1614  *     @type bool       $suppress_filters Whether to suppress filters. Default true.
1615  * }
1616  * @return array List of posts.
1617  */
1618 function get_posts( $args = null ) {
1619         $defaults = array(
1620                 'numberposts' => 5,
1621                 'category' => 0, 'orderby' => 'date',
1622                 'order' => 'DESC', 'include' => array(),
1623                 'exclude' => array(), 'meta_key' => '',
1624                 'meta_value' =>'', 'post_type' => 'post',
1625                 'suppress_filters' => true
1626         );
1627
1628         $r = wp_parse_args( $args, $defaults );
1629         if ( empty( $r['post_status'] ) )
1630                 $r['post_status'] = ( 'attachment' == $r['post_type'] ) ? 'inherit' : 'publish';
1631         if ( ! empty($r['numberposts']) && empty($r['posts_per_page']) )
1632                 $r['posts_per_page'] = $r['numberposts'];
1633         if ( ! empty($r['category']) )
1634                 $r['cat'] = $r['category'];
1635         if ( ! empty($r['include']) ) {
1636                 $incposts = wp_parse_id_list( $r['include'] );
1637                 $r['posts_per_page'] = count($incposts);  // only the number of posts included
1638                 $r['post__in'] = $incposts;
1639         } elseif ( ! empty($r['exclude']) )
1640                 $r['post__not_in'] = wp_parse_id_list( $r['exclude'] );
1641
1642         $r['ignore_sticky_posts'] = true;
1643         $r['no_found_rows'] = true;
1644
1645         $get_posts = new WP_Query;
1646         return $get_posts->query($r);
1647
1648 }
1649
1650 //
1651 // Post meta functions
1652 //
1653
1654 /**
1655  * Add meta data field to a post.
1656  *
1657  * Post meta data is called "Custom Fields" on the Administration Screen.
1658  *
1659  * @since 1.5.0
1660  *
1661  * @param int    $post_id    Post ID.
1662  * @param string $meta_key   Metadata name.
1663  * @param mixed  $meta_value Metadata value. Must be serializable if non-scalar.
1664  * @param bool   $unique     Optional. Whether the same key should not be added.
1665  *                           Default false.
1666  * @return int|false Meta ID on success, false on failure.
1667  */
1668 function add_post_meta( $post_id, $meta_key, $meta_value, $unique = false ) {
1669         // Make sure meta is added to the post, not a revision.
1670         if ( $the_post = wp_is_post_revision($post_id) )
1671                 $post_id = $the_post;
1672
1673         return add_metadata('post', $post_id, $meta_key, $meta_value, $unique);
1674 }
1675
1676 /**
1677  * Remove metadata matching criteria from a post.
1678  *
1679  * You can match based on the key, or key and value. Removing based on key and
1680  * value, will keep from removing duplicate metadata with the same key. It also
1681  * allows removing all metadata matching key, if needed.
1682  *
1683  * @since 1.5.0
1684  *
1685  * @param int    $post_id    Post ID.
1686  * @param string $meta_key   Metadata name.
1687  * @param mixed  $meta_value Optional. Metadata value. Must be serializable if
1688  *                           non-scalar. Default empty.
1689  * @return bool True on success, false on failure.
1690  */
1691 function delete_post_meta( $post_id, $meta_key, $meta_value = '' ) {
1692         // Make sure meta is added to the post, not a revision.
1693         if ( $the_post = wp_is_post_revision($post_id) )
1694                 $post_id = $the_post;
1695
1696         return delete_metadata('post', $post_id, $meta_key, $meta_value);
1697 }
1698
1699 /**
1700  * Retrieve post meta field for a post.
1701  *
1702  * @since 1.5.0
1703  *
1704  * @param int    $post_id Post ID.
1705  * @param string $key     Optional. The meta key to retrieve. By default, returns
1706  *                        data for all keys. Default empty.
1707  * @param bool   $single  Optional. Whether to return a single value. Default false.
1708  * @return mixed Will be an array if $single is false. Will be value of meta data
1709  *               field if $single is true.
1710  */
1711 function get_post_meta( $post_id, $key = '', $single = false ) {
1712         return get_metadata('post', $post_id, $key, $single);
1713 }
1714
1715 /**
1716  * Update post meta field based on post ID.
1717  *
1718  * Use the $prev_value parameter to differentiate between meta fields with the
1719  * same key and post ID.
1720  *
1721  * If the meta field for the post does not exist, it will be added.
1722  *
1723  * @since 1.5.0
1724  *
1725  * @param int    $post_id    Post ID.
1726  * @param string $meta_key   Metadata key.
1727  * @param mixed  $meta_value Metadata value. Must be serializable if non-scalar.
1728  * @param mixed  $prev_value Optional. Previous value to check before removing.
1729  *                           Default empty.
1730  * @return int|bool Meta ID if the key didn't exist, true on successful update,
1731  *                  false on failure.
1732  */
1733 function update_post_meta( $post_id, $meta_key, $meta_value, $prev_value = '' ) {
1734         // Make sure meta is added to the post, not a revision.
1735         if ( $the_post = wp_is_post_revision($post_id) )
1736                 $post_id = $the_post;
1737
1738         return update_metadata('post', $post_id, $meta_key, $meta_value, $prev_value);
1739 }
1740
1741 /**
1742  * Delete everything from post meta matching meta key.
1743  *
1744  * @since 2.3.0
1745  *
1746  * @param string $post_meta_key Key to search for when deleting.
1747  * @return bool Whether the post meta key was deleted from the database.
1748  */
1749 function delete_post_meta_by_key( $post_meta_key ) {
1750         return delete_metadata( 'post', null, $post_meta_key, '', true );
1751 }
1752
1753 /**
1754  * Retrieve post meta fields, based on post ID.
1755  *
1756  * The post meta fields are retrieved from the cache where possible,
1757  * so the function is optimized to be called more than once.
1758  *
1759  * @since 1.2.0
1760  *
1761  * @param int $post_id Optional. Post ID. Default is ID of the global $post.
1762  * @return array Post meta for the given post.
1763  */
1764 function get_post_custom( $post_id = 0 ) {
1765         $post_id = absint( $post_id );
1766         if ( ! $post_id )
1767                 $post_id = get_the_ID();
1768
1769         return get_post_meta( $post_id );
1770 }
1771
1772 /**
1773  * Retrieve meta field names for a post.
1774  *
1775  * If there are no meta fields, then nothing (null) will be returned.
1776  *
1777  * @since 1.2.0
1778  *
1779  * @param int $post_id Optional. Post ID. Default is ID of the global $post.
1780  * @return array|void Array of the keys, if retrieved.
1781  */
1782 function get_post_custom_keys( $post_id = 0 ) {
1783         $custom = get_post_custom( $post_id );
1784
1785         if ( !is_array($custom) )
1786                 return;
1787
1788         if ( $keys = array_keys($custom) )
1789                 return $keys;
1790 }
1791
1792 /**
1793  * Retrieve values for a custom post field.
1794  *
1795  * The parameters must not be considered optional. All of the post meta fields
1796  * will be retrieved and only the meta field key values returned.
1797  *
1798  * @since 1.2.0
1799  *
1800  * @param string $key     Optional. Meta field key. Default empty.
1801  * @param int    $post_id Optional. Post ID. Default is ID of the global $post.
1802  * @return array|null Meta field values.
1803  */
1804 function get_post_custom_values( $key = '', $post_id = 0 ) {
1805         if ( !$key )
1806                 return null;
1807
1808         $custom = get_post_custom($post_id);
1809
1810         return isset($custom[$key]) ? $custom[$key] : null;
1811 }
1812
1813 /**
1814  * Check if post is sticky.
1815  *
1816  * Sticky posts should remain at the top of The Loop. If the post ID is not
1817  * given, then The Loop ID for the current post will be used.
1818  *
1819  * @since 2.7.0
1820  *
1821  * @param int $post_id Optional. Post ID. Default is ID of the global $post.
1822  * @return bool Whether post is sticky.
1823  */
1824 function is_sticky( $post_id = 0 ) {
1825         $post_id = absint( $post_id );
1826
1827         if ( ! $post_id )
1828                 $post_id = get_the_ID();
1829
1830         $stickies = get_option( 'sticky_posts' );
1831
1832         if ( ! is_array( $stickies ) )
1833                 return false;
1834
1835         if ( in_array( $post_id, $stickies ) )
1836                 return true;
1837
1838         return false;
1839 }
1840
1841 /**
1842  * Sanitize every post field.
1843  *
1844  * If the context is 'raw', then the post object or array will get minimal
1845  * sanitization of the integer fields.
1846  *
1847  * @since 2.3.0
1848  *
1849  * @see sanitize_post_field()
1850  *
1851  * @param object|WP_Post|array $post    The Post Object or Array
1852  * @param string               $context Optional. How to sanitize post fields.
1853  *                                      Accepts 'raw', 'edit', 'db', or 'display'.
1854  *                                      Default 'display'.
1855  * @return object|WP_Post|array The now sanitized Post Object or Array (will be the
1856  *                              same type as $post).
1857  */
1858 function sanitize_post( $post, $context = 'display' ) {
1859         if ( is_object($post) ) {
1860                 // Check if post already filtered for this context.
1861                 if ( isset($post->filter) && $context == $post->filter )
1862                         return $post;
1863                 if ( !isset($post->ID) )
1864                         $post->ID = 0;
1865                 foreach ( array_keys(get_object_vars($post)) as $field )
1866                         $post->$field = sanitize_post_field($field, $post->$field, $post->ID, $context);
1867                 $post->filter = $context;
1868         } elseif ( is_array( $post ) ) {
1869                 // Check if post already filtered for this context.
1870                 if ( isset($post['filter']) && $context == $post['filter'] )
1871                         return $post;
1872                 if ( !isset($post['ID']) )
1873                         $post['ID'] = 0;
1874                 foreach ( array_keys($post) as $field )
1875                         $post[$field] = sanitize_post_field($field, $post[$field], $post['ID'], $context);
1876                 $post['filter'] = $context;
1877         }
1878         return $post;
1879 }
1880
1881 /**
1882  * Sanitize post field based on context.
1883  *
1884  * Possible context values are:  'raw', 'edit', 'db', 'display', 'attribute' and
1885  * 'js'. The 'display' context is used by default. 'attribute' and 'js' contexts
1886  * are treated like 'display' when calling filters.
1887  *
1888  * @since 2.3.0
1889  * @since 4.4.0 Like `sanitize_post()`, `$context` defaults to 'display'.
1890  *
1891  * @param string $field   The Post Object field name.
1892  * @param mixed  $value   The Post Object value.
1893  * @param int    $post_id Post ID.
1894  * @param string $context Optional. How to sanitize post fields. Looks for 'raw', 'edit',
1895  *                        'db', 'display', 'attribute' and 'js'. Default 'display'.
1896  * @return mixed Sanitized value.
1897  */
1898 function sanitize_post_field( $field, $value, $post_id, $context = 'display' ) {
1899         $int_fields = array('ID', 'post_parent', 'menu_order');
1900         if ( in_array($field, $int_fields) )
1901                 $value = (int) $value;
1902
1903         // Fields which contain arrays of integers.
1904         $array_int_fields = array( 'ancestors' );
1905         if ( in_array($field, $array_int_fields) ) {
1906                 $value = array_map( 'absint', $value);
1907                 return $value;
1908         }
1909
1910         if ( 'raw' == $context )
1911                 return $value;
1912
1913         $prefixed = false;
1914         if ( false !== strpos($field, 'post_') ) {
1915                 $prefixed = true;
1916                 $field_no_prefix = str_replace('post_', '', $field);
1917         }
1918
1919         if ( 'edit' == $context ) {
1920                 $format_to_edit = array('post_content', 'post_excerpt', 'post_title', 'post_password');
1921
1922                 if ( $prefixed ) {
1923
1924                         /**
1925                          * Filter the value of a specific post field to edit.
1926                          *
1927                          * The dynamic portion of the hook name, `$field`, refers to the post
1928                          * field name.
1929                          *
1930                          * @since 2.3.0
1931                          *
1932                          * @param mixed $value   Value of the post field.
1933                          * @param int   $post_id Post ID.
1934                          */
1935                         $value = apply_filters( "edit_{$field}", $value, $post_id );
1936
1937                         /**
1938                          * Filter the value of a specific post field to edit.
1939                          *
1940                          * The dynamic portion of the hook name, `$field_no_prefix`, refers to
1941                          * the post field name.
1942                          *
1943                          * @since 2.3.0
1944                          *
1945                          * @param mixed $value   Value of the post field.
1946                          * @param int   $post_id Post ID.
1947                          */
1948                         $value = apply_filters( "{$field_no_prefix}_edit_pre", $value, $post_id );
1949                 } else {
1950                         $value = apply_filters( "edit_post_{$field}", $value, $post_id );
1951                 }
1952
1953                 if ( in_array($field, $format_to_edit) ) {
1954                         if ( 'post_content' == $field )
1955                                 $value = format_to_edit($value, user_can_richedit());
1956                         else
1957                                 $value = format_to_edit($value);
1958                 } else {
1959                         $value = esc_attr($value);
1960                 }
1961         } elseif ( 'db' == $context ) {
1962                 if ( $prefixed ) {
1963
1964                         /**
1965                          * Filter the value of a specific post field before saving.
1966                          *
1967                          * The dynamic portion of the hook name, `$field`, refers to the post
1968                          * field name.
1969                          *
1970                          * @since 2.3.0
1971                          *
1972                          * @param mixed $value Value of the post field.
1973                          */
1974                         $value = apply_filters( "pre_{$field}", $value );
1975
1976                         /**
1977                          * Filter the value of a specific field before saving.
1978                          *
1979                          * The dynamic portion of the hook name, `$field_no_prefix`, refers
1980                          * to the post field name.
1981                          *
1982                          * @since 2.3.0
1983                          *
1984                          * @param mixed $value Value of the post field.
1985                          */
1986                         $value = apply_filters( "{$field_no_prefix}_save_pre", $value );
1987                 } else {
1988                         $value = apply_filters( "pre_post_{$field}", $value );
1989
1990                         /**
1991                          * Filter the value of a specific post field before saving.
1992                          *
1993                          * The dynamic portion of the hook name, `$field`, refers to the post
1994                          * field name.
1995                          *
1996                          * @since 2.3.0
1997                          *
1998                          * @param mixed $value Value of the post field.
1999                          */
2000                         $value = apply_filters( "{$field}_pre", $value );
2001                 }
2002         } else {
2003
2004                 // Use display filters by default.
2005                 if ( $prefixed ) {
2006
2007                         /**
2008                          * Filter the value of a specific post field for display.
2009                          *
2010                          * The dynamic portion of the hook name, `$field`, refers to the post
2011                          * field name.
2012                          *
2013                          * @since 2.3.0
2014                          *
2015                          * @param mixed  $value   Value of the prefixed post field.
2016                          * @param int    $post_id Post ID.
2017                          * @param string $context Context for how to sanitize the field. Possible
2018                          *                        values include 'raw', 'edit', 'db', 'display',
2019                          *                        'attribute' and 'js'.
2020                          */
2021                         $value = apply_filters( $field, $value, $post_id, $context );
2022                 } else {
2023                         $value = apply_filters( "post_{$field}", $value, $post_id, $context );
2024                 }
2025         }
2026
2027         if ( 'attribute' == $context )
2028                 $value = esc_attr($value);
2029         elseif ( 'js' == $context )
2030                 $value = esc_js($value);
2031
2032         return $value;
2033 }
2034
2035 /**
2036  * Make a post sticky.
2037  *
2038  * Sticky posts should be displayed at the top of the front page.
2039  *
2040  * @since 2.7.0
2041  *
2042  * @param int $post_id Post ID.
2043  */
2044 function stick_post( $post_id ) {
2045         $stickies = get_option('sticky_posts');
2046
2047         if ( !is_array($stickies) )
2048                 $stickies = array($post_id);
2049
2050         if ( ! in_array($post_id, $stickies) )
2051                 $stickies[] = $post_id;
2052
2053         update_option('sticky_posts', $stickies);
2054 }
2055
2056 /**
2057  * Un-stick a post.
2058  *
2059  * Sticky posts should be displayed at the top of the front page.
2060  *
2061  * @since 2.7.0
2062  *
2063  * @param int $post_id Post ID.
2064  */
2065 function unstick_post( $post_id ) {
2066         $stickies = get_option('sticky_posts');
2067
2068         if ( !is_array($stickies) )
2069                 return;
2070
2071         if ( ! in_array($post_id, $stickies) )
2072                 return;
2073
2074         $offset = array_search($post_id, $stickies);
2075         if ( false === $offset )
2076                 return;
2077
2078         array_splice($stickies, $offset, 1);
2079
2080         update_option('sticky_posts', $stickies);
2081 }
2082
2083 /**
2084  * Return the cache key for wp_count_posts() based on the passed arguments.
2085  *
2086  * @since 3.9.0
2087  *
2088  * @param string $type Optional. Post type to retrieve count Default 'post'.
2089  * @param string $perm Optional. 'readable' or empty. Default empty.
2090  * @return string The cache key.
2091  */
2092 function _count_posts_cache_key( $type = 'post', $perm = '' ) {
2093         $cache_key = 'posts-' . $type;
2094         if ( 'readable' == $perm && is_user_logged_in() ) {
2095                 $post_type_object = get_post_type_object( $type );
2096                 if ( $post_type_object && ! current_user_can( $post_type_object->cap->read_private_posts ) ) {
2097                         $cache_key .= '_' . $perm . '_' . get_current_user_id();
2098                 }
2099         }
2100         return $cache_key;
2101 }
2102
2103 /**
2104  * Count number of posts of a post type and if user has permissions to view.
2105  *
2106  * This function provides an efficient method of finding the amount of post's
2107  * type a blog has. Another method is to count the amount of items in
2108  * get_posts(), but that method has a lot of overhead with doing so. Therefore,
2109  * when developing for 2.5+, use this function instead.
2110  *
2111  * The $perm parameter checks for 'readable' value and if the user can read
2112  * private posts, it will display that for the user that is signed in.
2113  *
2114  * @since 2.5.0
2115  *
2116  * @global wpdb $wpdb WordPress database abstraction object.
2117  *
2118  * @param string $type Optional. Post type to retrieve count. Default 'post'.
2119  * @param string $perm Optional. 'readable' or empty. Default empty.
2120  * @return object Number of posts for each status.
2121  */
2122 function wp_count_posts( $type = 'post', $perm = '' ) {
2123         global $wpdb;
2124
2125         if ( ! post_type_exists( $type ) )
2126                 return new stdClass;
2127
2128         $cache_key = _count_posts_cache_key( $type, $perm );
2129
2130         $counts = wp_cache_get( $cache_key, 'counts' );
2131         if ( false !== $counts ) {
2132                 /** This filter is documented in wp-includes/post.php */
2133                 return apply_filters( 'wp_count_posts', $counts, $type, $perm );
2134         }
2135
2136         $query = "SELECT post_status, COUNT( * ) AS num_posts FROM {$wpdb->posts} WHERE post_type = %s";
2137         if ( 'readable' == $perm && is_user_logged_in() ) {
2138                 $post_type_object = get_post_type_object($type);
2139                 if ( ! current_user_can( $post_type_object->cap->read_private_posts ) ) {
2140                         $query .= $wpdb->prepare( " AND (post_status != 'private' OR ( post_author = %d AND post_status = 'private' ))",
2141                                 get_current_user_id()
2142                         );
2143                 }
2144         }
2145         $query .= ' GROUP BY post_status';
2146
2147         $results = (array) $wpdb->get_results( $wpdb->prepare( $query, $type ), ARRAY_A );
2148         $counts = array_fill_keys( get_post_stati(), 0 );
2149
2150         foreach ( $results as $row ) {
2151                 $counts[ $row['post_status'] ] = $row['num_posts'];
2152         }
2153
2154         $counts = (object) $counts;
2155         wp_cache_set( $cache_key, $counts, 'counts' );
2156
2157         /**
2158          * Modify returned post counts by status for the current post type.
2159          *
2160          * @since 3.7.0
2161          *
2162          * @param object $counts An object containing the current post_type's post
2163          *                       counts by status.
2164          * @param string $type   Post type.
2165          * @param string $perm   The permission to determine if the posts are 'readable'
2166          *                       by the current user.
2167          */
2168         return apply_filters( 'wp_count_posts', $counts, $type, $perm );
2169 }
2170
2171 /**
2172  * Count number of attachments for the mime type(s).
2173  *
2174  * If you set the optional mime_type parameter, then an array will still be
2175  * returned, but will only have the item you are looking for. It does not give
2176  * you the number of attachments that are children of a post. You can get that
2177  * by counting the number of children that post has.
2178  *
2179  * @since 2.5.0
2180  *
2181  * @global wpdb $wpdb WordPress database abstraction object.
2182  *
2183  * @param string|array $mime_type Optional. Array or comma-separated list of
2184  *                                MIME patterns. Default empty.
2185  * @return object An object containing the attachment counts by mime type.
2186  */
2187 function wp_count_attachments( $mime_type = '' ) {
2188         global $wpdb;
2189
2190         $and = wp_post_mime_type_where( $mime_type );
2191         $count = $wpdb->get_results( "SELECT post_mime_type, COUNT( * ) AS num_posts FROM $wpdb->posts WHERE post_type = 'attachment' AND post_status != 'trash' $and GROUP BY post_mime_type", ARRAY_A );
2192
2193         $counts = array();
2194         foreach ( (array) $count as $row ) {
2195                 $counts[ $row['post_mime_type'] ] = $row['num_posts'];
2196         }
2197         $counts['trash'] = $wpdb->get_var( "SELECT COUNT( * ) FROM $wpdb->posts WHERE post_type = 'attachment' AND post_status = 'trash' $and");
2198
2199         /**
2200          * Modify returned attachment counts by mime type.
2201          *
2202          * @since 3.7.0
2203          *
2204          * @param object $counts    An object containing the attachment counts by
2205          *                          mime type.
2206          * @param string $mime_type The mime type pattern used to filter the attachments
2207          *                          counted.
2208          */
2209         return apply_filters( 'wp_count_attachments', (object) $counts, $mime_type );
2210 }
2211
2212 /**
2213  * Get default post mime types.
2214  *
2215  * @since 2.9.0
2216  *
2217  * @return array List of post mime types.
2218  */
2219 function get_post_mime_types() {
2220         $post_mime_types = array(       //      array( adj, noun )
2221                 'image' => array(__('Images'), __('Manage Images'), _n_noop('Image <span class="count">(%s)</span>', 'Images <span class="count">(%s)</span>')),
2222                 'audio' => array(__('Audio'), __('Manage Audio'), _n_noop('Audio <span class="count">(%s)</span>', 'Audio <span class="count">(%s)</span>')),
2223                 'video' => array(__('Video'), __('Manage Video'), _n_noop('Video <span class="count">(%s)</span>', 'Video <span class="count">(%s)</span>')),
2224         );
2225
2226         /**
2227          * Filter the default list of post mime types.
2228          *
2229          * @since 2.5.0
2230          *
2231          * @param array $post_mime_types Default list of post mime types.
2232          */
2233         return apply_filters( 'post_mime_types', $post_mime_types );
2234 }
2235
2236 /**
2237  * Check a MIME-Type against a list.
2238  *
2239  * If the wildcard_mime_types parameter is a string, it must be comma separated
2240  * list. If the real_mime_types is a string, it is also comma separated to
2241  * create the list.
2242  *
2243  * @since 2.5.0
2244  *
2245  * @param string|array $wildcard_mime_types Mime types, e.g. audio/mpeg or image (same as image/*)
2246  *                                          or flash (same as *flash*).
2247  * @param string|array $real_mime_types     Real post mime type values.
2248  * @return array array(wildcard=>array(real types)).
2249  */
2250 function wp_match_mime_types( $wildcard_mime_types, $real_mime_types ) {
2251         $matches = array();
2252         if ( is_string( $wildcard_mime_types ) ) {
2253                 $wildcard_mime_types = array_map( 'trim', explode( ',', $wildcard_mime_types ) );
2254         }
2255         if ( is_string( $real_mime_types ) ) {
2256                 $real_mime_types = array_map( 'trim', explode( ',', $real_mime_types ) );
2257         }
2258
2259         $patternses = array();
2260         $wild = '[-._a-z0-9]*';
2261
2262         foreach ( (array) $wildcard_mime_types as $type ) {
2263                 $mimes = array_map( 'trim', explode( ',', $type ) );
2264                 foreach ( $mimes as $mime ) {
2265                         $regex = str_replace( '__wildcard__', $wild, preg_quote( str_replace( '*', '__wildcard__', $mime ) ) );
2266                         $patternses[][$type] = "^$regex$";
2267                         if ( false === strpos( $mime, '/' ) ) {
2268                                 $patternses[][$type] = "^$regex/";
2269                                 $patternses[][$type] = $regex;
2270                         }
2271                 }
2272         }
2273         asort( $patternses );
2274
2275         foreach ( $patternses as $patterns ) {
2276                 foreach ( $patterns as $type => $pattern ) {
2277                         foreach ( (array) $real_mime_types as $real ) {
2278                                 if ( preg_match( "#$pattern#", $real ) && ( empty( $matches[$type] ) || false === array_search( $real, $matches[$type] ) ) ) {
2279                                         $matches[$type][] = $real;
2280                                 }
2281                         }
2282                 }
2283         }
2284         return $matches;
2285 }
2286
2287 /**
2288  * Convert MIME types into SQL.
2289  *
2290  * @since 2.5.0
2291  *
2292  * @param string|array $post_mime_types List of mime types or comma separated string
2293  *                                      of mime types.
2294  * @param string       $table_alias     Optional. Specify a table alias, if needed.
2295  *                                      Default empty.
2296  * @return string The SQL AND clause for mime searching.
2297  */
2298 function wp_post_mime_type_where( $post_mime_types, $table_alias = '' ) {
2299         $where = '';
2300         $wildcards = array('', '%', '%/%');
2301         if ( is_string($post_mime_types) )
2302                 $post_mime_types = array_map('trim', explode(',', $post_mime_types));
2303
2304         $wheres = array();
2305
2306         foreach ( (array) $post_mime_types as $mime_type ) {
2307                 $mime_type = preg_replace('/\s/', '', $mime_type);
2308                 $slashpos = strpos($mime_type, '/');
2309                 if ( false !== $slashpos ) {
2310                         $mime_group = preg_replace('/[^-*.a-zA-Z0-9]/', '', substr($mime_type, 0, $slashpos));
2311                         $mime_subgroup = preg_replace('/[^-*.+a-zA-Z0-9]/', '', substr($mime_type, $slashpos + 1));
2312                         if ( empty($mime_subgroup) )
2313                                 $mime_subgroup = '*';
2314                         else
2315                                 $mime_subgroup = str_replace('/', '', $mime_subgroup);
2316                         $mime_pattern = "$mime_group/$mime_subgroup";
2317                 } else {
2318                         $mime_pattern = preg_replace('/[^-*.a-zA-Z0-9]/', '', $mime_type);
2319                         if ( false === strpos($mime_pattern, '*') )
2320                                 $mime_pattern .= '/*';
2321                 }
2322
2323                 $mime_pattern = preg_replace('/\*+/', '%', $mime_pattern);
2324
2325                 if ( in_array( $mime_type, $wildcards ) )
2326                         return '';
2327
2328                 if ( false !== strpos($mime_pattern, '%') )
2329                         $wheres[] = empty($table_alias) ? "post_mime_type LIKE '$mime_pattern'" : "$table_alias.post_mime_type LIKE '$mime_pattern'";
2330                 else
2331                         $wheres[] = empty($table_alias) ? "post_mime_type = '$mime_pattern'" : "$table_alias.post_mime_type = '$mime_pattern'";
2332         }
2333         if ( !empty($wheres) )
2334                 $where = ' AND (' . join(' OR ', $wheres) . ') ';
2335         return $where;
2336 }
2337
2338 /**
2339  * Trash or delete a post or page.
2340  *
2341  * When the post and page is permanently deleted, everything that is tied to
2342  * it is deleted also. This includes comments, post meta fields, and terms
2343  * associated with the post.
2344  *
2345  * The post or page is moved to trash instead of permanently deleted unless
2346  * trash is disabled, item is already in the trash, or $force_delete is true.
2347  *
2348  * @since 1.0.0
2349  *
2350  * @global wpdb $wpdb WordPress database abstraction object.
2351  * @see wp_delete_attachment()
2352  * @see wp_trash_post()
2353  *
2354  * @param int  $postid       Optional. Post ID. Default 0.
2355  * @param bool $force_delete Optional. Whether to bypass trash and force deletion.
2356  *                           Default false.
2357  * @return array|false|WP_Post False on failure.
2358  */
2359 function wp_delete_post( $postid = 0, $force_delete = false ) {
2360         global $wpdb;
2361
2362         if ( !$post = $wpdb->get_row($wpdb->prepare("SELECT * FROM $wpdb->posts WHERE ID = %d", $postid)) )
2363                 return $post;
2364
2365         if ( !$force_delete && ( $post->post_type == 'post' || $post->post_type == 'page') && get_post_status( $postid ) != 'trash' && EMPTY_TRASH_DAYS )
2366                 return wp_trash_post( $postid );
2367
2368         if ( $post->post_type == 'attachment' )
2369                 return wp_delete_attachment( $postid, $force_delete );
2370
2371         /**
2372          * Filter whether a post deletion should take place.
2373          *
2374          * @since 4.4.0
2375          *
2376          * @param bool    $delete       Whether to go forward with deletion.
2377          * @param WP_Post $post         Post object.
2378          * @param bool    $force_delete Whether to bypass the trash.
2379          */
2380         $check = apply_filters( 'pre_delete_post', null, $post, $force_delete );
2381         if ( null !== $check ) {
2382                 return $check;
2383         }
2384
2385         /**
2386          * Fires before a post is deleted, at the start of wp_delete_post().
2387          *
2388          * @since 3.2.0
2389          *
2390          * @see wp_delete_post()
2391          *
2392          * @param int $postid Post ID.
2393          */
2394         do_action( 'before_delete_post', $postid );
2395
2396         delete_post_meta($postid,'_wp_trash_meta_status');
2397         delete_post_meta($postid,'_wp_trash_meta_time');
2398
2399         wp_delete_object_term_relationships($postid, get_object_taxonomies($post->post_type));
2400
2401         $parent_data = array( 'post_parent' => $post->post_parent );
2402         $parent_where = array( 'post_parent' => $postid );
2403
2404         if ( is_post_type_hierarchical( $post->post_type ) ) {
2405                 // Point children of this page to its parent, also clean the cache of affected children.
2406                 $children_query = $wpdb->prepare( "SELECT * FROM $wpdb->posts WHERE post_parent = %d AND post_type = %s", $postid, $post->post_type );
2407                 $children = $wpdb->get_results( $children_query );
2408
2409                 $wpdb->update( $wpdb->posts, $parent_data, $parent_where + array( 'post_type' => $post->post_type ) );
2410         }
2411
2412         // Do raw query. wp_get_post_revisions() is filtered.
2413         $revision_ids = $wpdb->get_col( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_parent = %d AND post_type = 'revision'", $postid ) );
2414         // Use wp_delete_post (via wp_delete_post_revision) again. Ensures any meta/misplaced data gets cleaned up.
2415         foreach ( $revision_ids as $revision_id )
2416                 wp_delete_post_revision( $revision_id );
2417
2418         // Point all attachments to this post up one level.
2419         $wpdb->update( $wpdb->posts, $parent_data, $parent_where + array( 'post_type' => 'attachment' ) );
2420
2421         wp_defer_comment_counting( true );
2422
2423         $comment_ids = $wpdb->get_col( $wpdb->prepare( "SELECT comment_ID FROM $wpdb->comments WHERE comment_post_ID = %d", $postid ));
2424         foreach ( $comment_ids as $comment_id ) {
2425                 wp_delete_comment( $comment_id, true );
2426         }
2427
2428         wp_defer_comment_counting( false );
2429
2430         $post_meta_ids = $wpdb->get_col( $wpdb->prepare( "SELECT meta_id FROM $wpdb->postmeta WHERE post_id = %d ", $postid ));
2431         foreach ( $post_meta_ids as $mid )
2432                 delete_metadata_by_mid( 'post', $mid );
2433
2434         /**
2435          * Fires immediately before a post is deleted from the database.
2436          *
2437          * @since 1.2.0
2438          *
2439          * @param int $postid Post ID.
2440          */
2441         do_action( 'delete_post', $postid );
2442         $result = $wpdb->delete( $wpdb->posts, array( 'ID' => $postid ) );
2443         if ( ! $result ) {
2444                 return false;
2445         }
2446
2447         /**
2448          * Fires immediately after a post is deleted from the database.
2449          *
2450          * @since 2.2.0
2451          *
2452          * @param int $postid Post ID.
2453          */
2454         do_action( 'deleted_post', $postid );
2455
2456         clean_post_cache( $post );
2457
2458         if ( is_post_type_hierarchical( $post->post_type ) && $children ) {
2459                 foreach ( $children as $child )
2460                         clean_post_cache( $child );
2461         }
2462
2463         wp_clear_scheduled_hook('publish_future_post', array( $postid ) );
2464
2465         /**
2466          * Fires after a post is deleted, at the conclusion of wp_delete_post().
2467          *
2468          * @since 3.2.0
2469          *
2470          * @see wp_delete_post()
2471          *
2472          * @param int $postid Post ID.
2473          */
2474         do_action( 'after_delete_post', $postid );
2475
2476         return $post;
2477 }
2478
2479 /**
2480  * Reset the page_on_front, show_on_front, and page_for_post settings when
2481  * a linked page is deleted or trashed.
2482  *
2483  * Also ensures the post is no longer sticky.
2484  *
2485  * @since 3.7.0
2486  * @access private
2487  *
2488  * @param int $post_id Post ID.
2489  */
2490 function _reset_front_page_settings_for_post( $post_id ) {
2491         $post = get_post( $post_id );
2492         if ( 'page' == $post->post_type ) {
2493                 /*
2494                  * If the page is defined in option page_on_front or post_for_posts,
2495                  * adjust the corresponding options.
2496                  */
2497                 if ( get_option( 'page_on_front' ) == $post->ID ) {
2498                         update_option( 'show_on_front', 'posts' );
2499                         update_option( 'page_on_front', 0 );
2500                 }
2501                 if ( get_option( 'page_for_posts' ) == $post->ID ) {
2502                         delete_option( 'page_for_posts', 0 );
2503                 }
2504         }
2505         unstick_post( $post->ID );
2506 }
2507
2508 /**
2509  * Move a post or page to the Trash
2510  *
2511  * If trash is disabled, the post or page is permanently deleted.
2512  *
2513  * @since 2.9.0
2514  *
2515  * @see wp_delete_post()
2516  *
2517  * @param int $post_id Optional. Post ID. Default is ID of the global $post
2518  *                     if EMPTY_TRASH_DAYS equals true.
2519  * @return false|array|WP_Post|null Post data array, otherwise false.
2520  */
2521 function wp_trash_post( $post_id = 0 ) {
2522         if ( !EMPTY_TRASH_DAYS )
2523                 return wp_delete_post($post_id, true);
2524
2525         if ( !$post = get_post($post_id, ARRAY_A) )
2526                 return $post;
2527
2528         if ( $post['post_status'] == 'trash' )
2529                 return false;
2530
2531         /**
2532          * Fires before a post is sent to the trash.
2533          *
2534          * @since 3.3.0
2535          *
2536          * @param int $post_id Post ID.
2537          */
2538         do_action( 'wp_trash_post', $post_id );
2539
2540         add_post_meta($post_id,'_wp_trash_meta_status', $post['post_status']);
2541         add_post_meta($post_id,'_wp_trash_meta_time', time());
2542
2543         $post['post_status'] = 'trash';
2544         wp_insert_post( wp_slash( $post ) );
2545
2546         wp_trash_post_comments($post_id);
2547
2548         /**
2549          * Fires after a post is sent to the trash.
2550          *
2551          * @since 2.9.0
2552          *
2553          * @param int $post_id Post ID.
2554          */
2555         do_action( 'trashed_post', $post_id );
2556
2557         return $post;
2558 }
2559
2560 /**
2561  * Restore a post or page from the Trash.
2562  *
2563  * @since 2.9.0
2564  *
2565  * @param int $post_id Optional. Post ID. Default is ID of the global $post.
2566  * @return WP_Post|false WP_Post object. False on failure.
2567  */
2568 function wp_untrash_post( $post_id = 0 ) {
2569         if ( !$post = get_post($post_id, ARRAY_A) )
2570                 return $post;
2571
2572         if ( $post['post_status'] != 'trash' )
2573                 return false;
2574
2575         /**
2576          * Fires before a post is restored from the trash.
2577          *
2578          * @since 2.9.0
2579          *
2580          * @param int $post_id Post ID.
2581          */
2582         do_action( 'untrash_post', $post_id );
2583
2584         $post_status = get_post_meta($post_id, '_wp_trash_meta_status', true);
2585
2586         $post['post_status'] = $post_status;
2587
2588         delete_post_meta($post_id, '_wp_trash_meta_status');
2589         delete_post_meta($post_id, '_wp_trash_meta_time');
2590
2591         wp_insert_post( wp_slash( $post ) );
2592
2593         wp_untrash_post_comments($post_id);
2594
2595         /**
2596          * Fires after a post is restored from the trash.
2597          *
2598          * @since 2.9.0
2599          *
2600          * @param int $post_id Post ID.
2601          */
2602         do_action( 'untrashed_post', $post_id );
2603
2604         return $post;
2605 }
2606
2607 /**
2608  * Moves comments for a post to the trash.
2609  *
2610  * @since 2.9.0
2611  *
2612  * @global wpdb $wpdb WordPress database abstraction object.
2613  *
2614  * @param int|WP_Post|null $post Optional. Post ID or post object. Defaults to global $post.
2615  * @return mixed|void False on failure.
2616  */
2617 function wp_trash_post_comments( $post = null ) {
2618         global $wpdb;
2619
2620         $post = get_post($post);
2621         if ( empty($post) )
2622                 return;
2623
2624         $post_id = $post->ID;
2625
2626         /**
2627          * Fires before comments are sent to the trash.
2628          *
2629          * @since 2.9.0
2630          *
2631          * @param int $post_id Post ID.
2632          */
2633         do_action( 'trash_post_comments', $post_id );
2634
2635         $comments = $wpdb->get_results( $wpdb->prepare("SELECT comment_ID, comment_approved FROM $wpdb->comments WHERE comment_post_ID = %d", $post_id) );
2636         if ( empty($comments) )
2637                 return;
2638
2639         // Cache current status for each comment.
2640         $statuses = array();
2641         foreach ( $comments as $comment )
2642                 $statuses[$comment->comment_ID] = $comment->comment_approved;
2643         add_post_meta($post_id, '_wp_trash_meta_comments_status', $statuses);
2644
2645         // Set status for all comments to post-trashed.
2646         $result = $wpdb->update($wpdb->comments, array('comment_approved' => 'post-trashed'), array('comment_post_ID' => $post_id));
2647
2648         clean_comment_cache( array_keys($statuses) );
2649
2650         /**
2651          * Fires after comments are sent to the trash.
2652          *
2653          * @since 2.9.0
2654          *
2655          * @param int   $post_id  Post ID.
2656          * @param array $statuses Array of comment statuses.
2657          */
2658         do_action( 'trashed_post_comments', $post_id, $statuses );
2659
2660         return $result;
2661 }
2662
2663 /**
2664  * Restore comments for a post from the trash.
2665  *
2666  * @since 2.9.0
2667  *
2668  * @global wpdb $wpdb WordPress database abstraction object.
2669  *
2670  * @param int|WP_Post|null $post Optional. Post ID or post object. Defaults to global $post.
2671  * @return true|void
2672  */
2673 function wp_untrash_post_comments( $post = null ) {
2674         global $wpdb;
2675
2676         $post = get_post($post);
2677         if ( empty($post) )
2678                 return;
2679
2680         $post_id = $post->ID;
2681
2682         $statuses = get_post_meta($post_id, '_wp_trash_meta_comments_status', true);
2683
2684         if ( empty($statuses) )
2685                 return true;
2686
2687         /**
2688          * Fires before comments are restored for a post from the trash.
2689          *
2690          * @since 2.9.0
2691          *
2692          * @param int $post_id Post ID.
2693          */
2694         do_action( 'untrash_post_comments', $post_id );
2695
2696         // Restore each comment to its original status.
2697         $group_by_status = array();
2698         foreach ( $statuses as $comment_id => $comment_status )
2699                 $group_by_status[$comment_status][] = $comment_id;
2700
2701         foreach ( $group_by_status as $status => $comments ) {
2702                 // Sanity check. This shouldn't happen.
2703                 if ( 'post-trashed' == $status ) {
2704                         $status = '0';
2705                 }
2706                 $comments_in = implode( ', ', array_map( 'intval', $comments ) );
2707                 $wpdb->query( $wpdb->prepare( "UPDATE $wpdb->comments SET comment_approved = %s WHERE comment_ID IN ($comments_in)", $status ) );
2708         }
2709
2710         clean_comment_cache( array_keys($statuses) );
2711
2712         delete_post_meta($post_id, '_wp_trash_meta_comments_status');
2713
2714         /**
2715          * Fires after comments are restored for a post from the trash.
2716          *
2717          * @since 2.9.0
2718          *
2719          * @param int $post_id Post ID.
2720          */
2721         do_action( 'untrashed_post_comments', $post_id );
2722 }
2723
2724 /**
2725  * Retrieve the list of categories for a post.
2726  *
2727  * Compatibility layer for themes and plugins. Also an easy layer of abstraction
2728  * away from the complexity of the taxonomy layer.
2729  *
2730  * @since 2.1.0
2731  *
2732  * @see wp_get_object_terms()
2733  *
2734  * @param int   $post_id Optional. The Post ID. Does not default to the ID of the
2735  *                       global $post. Default 0.
2736  * @param array $args    Optional. Category arguments. Default empty.
2737  * @return array List of categories.
2738  */
2739 function wp_get_post_categories( $post_id = 0, $args = array() ) {
2740         $post_id = (int) $post_id;
2741
2742         $defaults = array('fields' => 'ids');
2743         $args = wp_parse_args( $args, $defaults );
2744
2745         $cats = wp_get_object_terms($post_id, 'category', $args);
2746         return $cats;
2747 }
2748
2749 /**
2750  * Retrieve the tags for a post.
2751  *
2752  * There is only one default for this function, called 'fields' and by default
2753  * is set to 'all'. There are other defaults that can be overridden in
2754  * {@link wp_get_object_terms()}.
2755  *
2756  * @since 2.3.0
2757  *
2758  * @param int   $post_id Optional. The Post ID. Does not default to the ID of the
2759  *                       global $post. Default 0.
2760  * @param array $args Optional. Overwrite the defaults
2761  * @return array List of post tags.
2762  */
2763 function wp_get_post_tags( $post_id = 0, $args = array() ) {
2764         return wp_get_post_terms( $post_id, 'post_tag', $args);
2765 }
2766
2767 /**
2768  * Retrieve the terms for a post.
2769  *
2770  * There is only one default for this function, called 'fields' and by default
2771  * is set to 'all'. There are other defaults that can be overridden in
2772  * {@link wp_get_object_terms()}.
2773  *
2774  * @since 2.8.0
2775  *
2776  * @param int    $post_id  Optional. The Post ID. Does not default to the ID of the
2777  *                         global $post. Default 0.
2778  * @param string $taxonomy Optional. The taxonomy for which to retrieve terms. Default 'post_tag'.
2779  * @param array  $args     Optional. {@link wp_get_object_terms()} arguments. Default empty array.
2780  * @return array|WP_Error  List of post terms or empty array if no terms were found. WP_Error object
2781  *                         if `$taxonomy` doesn't exist.
2782  */
2783 function wp_get_post_terms( $post_id = 0, $taxonomy = 'post_tag', $args = array() ) {
2784         $post_id = (int) $post_id;
2785
2786         $defaults = array('fields' => 'all');
2787         $args = wp_parse_args( $args, $defaults );
2788
2789         $tags = wp_get_object_terms($post_id, $taxonomy, $args);
2790
2791         return $tags;
2792 }
2793
2794 /**
2795  * Retrieve a number of recent posts.
2796  *
2797  * @since 1.0.0
2798  *
2799  * @see get_posts()
2800  *
2801  * @param array  $args       Optional. Arguments to retrieve posts. Default empty array.
2802  * @param string $output     Optional. Type of output. Accepts ARRAY_A or ''. Default ARRAY_A.
2803  * @return array|false Associative array if $output equals ARRAY_A, array or false if no results.
2804  */
2805 function wp_get_recent_posts( $args = array(), $output = ARRAY_A ) {
2806
2807         if ( is_numeric( $args ) ) {
2808                 _deprecated_argument( __FUNCTION__, '3.1', __( 'Passing an integer number of posts is deprecated. Pass an array of arguments instead.' ) );
2809                 $args = array( 'numberposts' => absint( $args ) );
2810         }
2811
2812         // Set default arguments.
2813         $defaults = array(
2814                 'numberposts' => 10, 'offset' => 0,
2815                 'category' => 0, 'orderby' => 'post_date',
2816                 'order' => 'DESC', 'include' => '',
2817                 'exclude' => '', 'meta_key' => '',
2818                 'meta_value' =>'', 'post_type' => 'post', 'post_status' => 'draft, publish, future, pending, private',
2819                 'suppress_filters' => true
2820         );
2821
2822         $r = wp_parse_args( $args, $defaults );
2823
2824         $results = get_posts( $r );
2825
2826         // Backward compatibility. Prior to 3.1 expected posts to be returned in array.
2827         if ( ARRAY_A == $output ){
2828                 foreach ( $results as $key => $result ) {
2829                         $results[$key] = get_object_vars( $result );
2830                 }
2831                 return $results ? $results : array();
2832         }
2833
2834         return $results ? $results : false;
2835
2836 }
2837
2838 /**
2839  * Insert or update a post.
2840  *
2841  * If the $postarr parameter has 'ID' set to a value, then post will be updated.
2842  *
2843  * You can set the post date manually, by setting the values for 'post_date'
2844  * and 'post_date_gmt' keys. You can close the comments or open the comments by
2845  * setting the value for 'comment_status' key.
2846  *
2847  * @since 1.0.0
2848  * @since 4.2.0 Support was added for encoding emoji in the post title, content, and excerpt.
2849  * @since 4.4.0 A 'meta_input' array can now be passed to `$postarr` to add post meta data.
2850  *
2851  * @see sanitize_post()
2852  * @global wpdb $wpdb WordPress database abstraction object.
2853  *
2854  * @param array $postarr {
2855  *     An array of elements that make up a post to update or insert.
2856  *
2857  *     @type int    $ID                    The post ID. If equal to something other than 0,
2858  *                                         the post with that ID will be updated. Default 0.
2859  *     @type int    $post_author           The ID of the user who added the post. Default is
2860  *                                         the current user ID.
2861  *     @type string $post_date             The date of the post. Default is the current time.
2862  *     @type string $post_date_gmt         The date of the post in the GMT timezone. Default is
2863  *                                         the value of `$post_date`.
2864  *     @type mixed  $post_content          The post content. Default empty.
2865  *     @type string $post_content_filtered The filtered post content. Default empty.
2866  *     @type string $post_title            The post title. Default empty.
2867  *     @type string $post_excerpt          The post excerpt. Default empty.
2868  *     @type string $post_status           The post status. Default 'draft'.
2869  *     @type string $post_type             The post type. Default 'post'.
2870  *     @type string $comment_status        Whether the post can accept comments. Accepts 'open' or 'closed'.
2871  *                                         Default is the value of 'default_comment_status' option.
2872  *     @type string $ping_status           Whether the post can accept pings. Accepts 'open' or 'closed'.
2873  *                                         Default is the value of 'default_ping_status' option.
2874  *     @type string $post_password         The password to access the post. Default empty.
2875  *     @type string $post_name             The post name. Default is the sanitized post title.
2876  *     @type string $to_ping               Space or carriage return-separated list of URLs to ping.
2877  *                                         Default empty.
2878  *     @type string $pinged                Space or carriage return-separated list of URLs that have
2879  *                                         been pinged. Default empty.
2880  *     @type string $post_modified         The date when the post was last modified. Default is
2881  *                                         the current time.
2882  *     @type string $post_modified_gmt     The date when the post was last modified in the GMT
2883  *                                         timezone. Default is the current time.
2884  *     @type int    $post_parent           Set this for the post it belongs to, if any. Default 0.
2885  *     @type int    $menu_order            The order the post should be displayed in. Default 0.
2886  *     @type string $post_mime_type        The mime type of the post. Default empty.
2887  *     @type string $guid                  Global Unique ID for referencing the post. Default empty.
2888  *     @type array  $tax_input             Array of taxonomy terms keyed by their taxonomy name. Default empty.
2889  *     @type array  $meta_input            Array of post meta values keyed by their post meta key. Default empty.
2890  * }
2891  * @param bool  $wp_error Optional. Whether to allow return of WP_Error on failure. Default false.
2892  * @return int|WP_Error The post ID on success. The value 0 or WP_Error on failure.
2893  */
2894 function wp_insert_post( $postarr, $wp_error = false ) {
2895         global $wpdb;
2896
2897         $user_id = get_current_user_id();
2898
2899         $defaults = array(
2900                 'post_author' => $user_id,
2901                 'post_content' => '',
2902                 'post_content_filtered' => '',
2903                 'post_title' => '',
2904                 'post_excerpt' => '',
2905                 'post_status' => 'draft',
2906                 'post_type' => 'post',
2907                 'comment_status' => '',
2908                 'ping_status' => '',
2909                 'post_password' => '',
2910                 'to_ping' =>  '',
2911                 'pinged' => '',
2912                 'post_parent' => 0,
2913                 'menu_order' => 0,
2914                 'guid' => '',
2915                 'import_id' => 0,
2916                 'context' => '',
2917         );
2918
2919         $postarr = wp_parse_args($postarr, $defaults);
2920
2921         unset( $postarr[ 'filter' ] );
2922
2923         $postarr = sanitize_post($postarr, 'db');
2924
2925         // Are we updating or creating?
2926         $post_ID = 0;
2927         $update = false;
2928         $guid = $postarr['guid'];
2929
2930         if ( ! empty( $postarr['ID'] ) ) {
2931                 $update = true;
2932
2933                 // Get the post ID and GUID.
2934                 $post_ID = $postarr['ID'];
2935                 $post_before = get_post( $post_ID );
2936                 if ( is_null( $post_before ) ) {
2937                         if ( $wp_error ) {
2938                                 return new WP_Error( 'invalid_post', __( 'Invalid post ID.' ) );
2939                         }
2940                         return 0;
2941                 }
2942
2943                 $guid = get_post_field( 'guid', $post_ID );
2944                 $previous_status = get_post_field('post_status', $post_ID );
2945         } else {
2946                 $previous_status = 'new';
2947         }
2948
2949         $post_type = empty( $postarr['post_type'] ) ? 'post' : $postarr['post_type'];
2950
2951         $post_title = $postarr['post_title'];
2952         $post_content = $postarr['post_content'];
2953         $post_excerpt = $postarr['post_excerpt'];
2954         if ( isset( $postarr['post_name'] ) ) {
2955                 $post_name = $postarr['post_name'];
2956         }
2957
2958         $maybe_empty = 'attachment' !== $post_type
2959                 && ! $post_content && ! $post_title && ! $post_excerpt
2960                 && post_type_supports( $post_type, 'editor' )
2961                 && post_type_supports( $post_type, 'title' )
2962                 && post_type_supports( $post_type, 'excerpt' );
2963
2964         /**
2965          * Filter whether the post should be considered "empty".
2966          *
2967          * The post is considered "empty" if both:
2968          * 1. The post type supports the title, editor, and excerpt fields
2969          * 2. The title, editor, and excerpt fields are all empty
2970          *
2971          * Returning a truthy value to the filter will effectively short-circuit
2972          * the new post being inserted, returning 0. If $wp_error is true, a WP_Error
2973          * will be returned instead.
2974          *
2975          * @since 3.3.0
2976          *
2977          * @param bool  $maybe_empty Whether the post should be considered "empty".
2978          * @param array $postarr     Array of post data.
2979          */
2980         if ( apply_filters( 'wp_insert_post_empty_content', $maybe_empty, $postarr ) ) {
2981                 if ( $wp_error ) {
2982                         return new WP_Error( 'empty_content', __( 'Content, title, and excerpt are empty.' ) );
2983                 } else {
2984                         return 0;
2985                 }
2986         }
2987
2988         $post_status = empty( $postarr['post_status'] ) ? 'draft' : $postarr['post_status'];
2989         if ( 'attachment' === $post_type && ! in_array( $post_status, array( 'inherit', 'private', 'trash' ) ) ) {
2990                 $post_status = 'inherit';
2991         }
2992
2993         if ( ! empty( $postarr['post_category'] ) ) {
2994                 // Filter out empty terms.
2995                 $post_category = array_filter( $postarr['post_category'] );
2996         }
2997
2998         // Make sure we set a valid category.
2999         if ( empty( $post_category ) || 0 == count( $post_category ) || ! is_array( $post_category ) ) {
3000                 // 'post' requires at least one category.
3001                 if ( 'post' == $post_type && 'auto-draft' != $post_status ) {
3002                         $post_category = array( get_option('default_category') );
3003                 } else {
3004                         $post_category = array();
3005                 }
3006         }
3007
3008         // Don't allow contributors to set the post slug for pending review posts.
3009         if ( 'pending' == $post_status && !current_user_can( 'publish_posts' ) ) {
3010                 $post_name = '';
3011         }
3012
3013         /*
3014          * Create a valid post name. Drafts and pending posts are allowed to have
3015          * an empty post name.
3016          */
3017         if ( empty($post_name) ) {
3018                 if ( !in_array( $post_status, array( 'draft', 'pending', 'auto-draft' ) ) ) {
3019                         $post_name = sanitize_title($post_title);
3020                 } else {
3021                         $post_name = '';
3022                 }
3023         } else {
3024                 // On updates, we need to check to see if it's using the old, fixed sanitization context.
3025                 $check_name = sanitize_title( $post_name, '', 'old-save' );
3026                 if ( $update && strtolower( urlencode( $post_name ) ) == $check_name && get_post_field( 'post_name', $post_ID ) == $check_name ) {
3027                         $post_name = $check_name;
3028                 } else { // new post, or slug has changed.
3029                         $post_name = sanitize_title($post_name);
3030                 }
3031         }
3032
3033         /*
3034          * If the post date is empty (due to having been new or a draft) and status
3035          * is not 'draft' or 'pending', set date to now.
3036          */
3037         if ( empty( $postarr['post_date'] ) || '0000-00-00 00:00:00' == $postarr['post_date'] ) {
3038                 if ( empty( $postarr['post_date_gmt'] ) || '0000-00-00 00:00:00' == $postarr['post_date_gmt'] ) {
3039                         $post_date = current_time( 'mysql' );
3040                 } else {
3041                         $post_date = get_date_from_gmt( $postarr['post_date_gmt'] );
3042                 }
3043         } else {
3044                 $post_date = $postarr['post_date'];
3045         }
3046
3047         // Validate the date.
3048         $mm = substr( $post_date, 5, 2 );
3049         $jj = substr( $post_date, 8, 2 );
3050         $aa = substr( $post_date, 0, 4 );
3051         $valid_date = wp_checkdate( $mm, $jj, $aa, $post_date );
3052         if ( ! $valid_date ) {
3053                 if ( $wp_error ) {
3054                         return new WP_Error( 'invalid_date', __( 'Whoops, the provided date is invalid.' ) );
3055                 } else {
3056                         return 0;
3057                 }
3058         }
3059
3060         if ( empty( $postarr['post_date_gmt'] ) || '0000-00-00 00:00:00' == $postarr['post_date_gmt'] ) {
3061                 if ( ! in_array( $post_status, array( 'draft', 'pending', 'auto-draft' ) ) ) {
3062                         $post_date_gmt = get_gmt_from_date( $post_date );
3063                 } else {
3064                         $post_date_gmt = '0000-00-00 00:00:00';
3065                 }
3066         } else {
3067                 $post_date_gmt = $postarr['post_date_gmt'];
3068         }
3069
3070         if ( $update || '0000-00-00 00:00:00' == $post_date ) {
3071                 $post_modified     = current_time( 'mysql' );
3072                 $post_modified_gmt = current_time( 'mysql', 1 );
3073         } else {
3074                 $post_modified     = $post_date;
3075                 $post_modified_gmt = $post_date_gmt;
3076         }
3077
3078         if ( 'attachment' !== $post_type ) {
3079                 if ( 'publish' == $post_status ) {
3080                         $now = gmdate('Y-m-d H:i:59');
3081                         if ( mysql2date('U', $post_date_gmt, false) > mysql2date('U', $now, false) ) {
3082                                 $post_status = 'future';
3083                         }
3084                 } elseif ( 'future' == $post_status ) {
3085                         $now = gmdate('Y-m-d H:i:59');
3086                         if ( mysql2date('U', $post_date_gmt, false) <= mysql2date('U', $now, false) ) {
3087                                 $post_status = 'publish';
3088                         }
3089                 }
3090         }
3091
3092         // Comment status.
3093         if ( empty( $postarr['comment_status'] ) ) {
3094                 if ( $update ) {
3095                         $comment_status = 'closed';
3096                 } else {
3097                         $comment_status = get_default_comment_status( $post_type );
3098                 }
3099         } else {
3100                 $comment_status = $postarr['comment_status'];
3101         }
3102
3103         // These variables are needed by compact() later.
3104         $post_content_filtered = $postarr['post_content_filtered'];
3105         $post_author = isset( $postarr['post_author'] ) ? $postarr['post_author'] : $user_id;
3106         $ping_status = empty( $postarr['ping_status'] ) ? get_default_comment_status( $post_type, 'pingback' ) : $postarr['ping_status'];
3107         $to_ping = isset( $postarr['to_ping'] ) ? sanitize_trackback_urls( $postarr['to_ping'] ) : '';
3108         $pinged = isset( $postarr['pinged'] ) ? $postarr['pinged'] : '';
3109         $import_id = isset( $postarr['import_id'] ) ? $postarr['import_id'] : 0;
3110
3111         /*
3112          * The 'wp_insert_post_parent' filter expects all variables to be present.
3113          * Previously, these variables would have already been extracted
3114          */
3115         if ( isset( $postarr['menu_order'] ) ) {
3116                 $menu_order = (int) $postarr['menu_order'];
3117         } else {
3118                 $menu_order = 0;
3119         }
3120
3121         $post_password = isset( $postarr['post_password'] ) ? $postarr['post_password'] : '';
3122         if ( 'private' == $post_status ) {
3123                 $post_password = '';
3124         }
3125
3126         if ( isset( $postarr['post_parent'] ) ) {
3127                 $post_parent = (int) $postarr['post_parent'];
3128         } else {
3129                 $post_parent = 0;
3130         }
3131
3132         /**
3133          * Filter the post parent -- used to check for and prevent hierarchy loops.
3134          *
3135          * @since 3.1.0
3136          *
3137          * @param int   $post_parent Post parent ID.
3138          * @param int   $post_ID     Post ID.
3139          * @param array $new_postarr Array of parsed post data.
3140          * @param array $postarr     Array of sanitized, but otherwise unmodified post data.
3141          */
3142         $post_parent = apply_filters( 'wp_insert_post_parent', $post_parent, $post_ID, compact( array_keys( $postarr ) ), $postarr );
3143
3144         $post_name = wp_unique_post_slug( $post_name, $post_ID, $post_status, $post_type, $post_parent );
3145
3146         // Don't unslash.
3147         $post_mime_type = isset( $postarr['post_mime_type'] ) ? $postarr['post_mime_type'] : '';
3148
3149         // Expected_slashed (everything!).
3150         $data = compact( 'post_author', 'post_date', 'post_date_gmt', 'post_content', 'post_content_filtered', 'post_title', 'post_excerpt', 'post_status', 'post_type', 'comment_status', 'ping_status', 'post_password', 'post_name', 'to_ping', 'pinged', 'post_modified', 'post_modified_gmt', 'post_parent', 'menu_order', 'post_mime_type', 'guid' );
3151
3152         $emoji_fields = array( 'post_title', 'post_content', 'post_excerpt' );
3153
3154         foreach ( $emoji_fields as $emoji_field ) {
3155                 if ( isset( $data[ $emoji_field ] ) ) {
3156                         $charset = $wpdb->get_col_charset( $wpdb->posts, $emoji_field );
3157                         if ( 'utf8' === $charset ) {
3158                                 $data[ $emoji_field ] = wp_encode_emoji( $data[ $emoji_field ] );
3159                         }
3160                 }
3161         }
3162
3163         if ( 'attachment' === $post_type ) {
3164                 /**
3165                  * Filter attachment post data before it is updated in or added to the database.
3166                  *
3167                  * @since 3.9.0
3168                  *
3169                  * @param array $data    An array of sanitized attachment post data.
3170                  * @param array $postarr An array of unsanitized attachment post data.
3171                  */
3172                 $data = apply_filters( 'wp_insert_attachment_data', $data, $postarr );
3173         } else {
3174                 /**
3175                  * Filter slashed post data just before it is inserted into the database.
3176                  *
3177                  * @since 2.7.0
3178                  *
3179                  * @param array $data    An array of slashed post data.
3180                  * @param array $postarr An array of sanitized, but otherwise unmodified post data.
3181                  */
3182                 $data = apply_filters( 'wp_insert_post_data', $data, $postarr );
3183         }
3184         $data = wp_unslash( $data );
3185         $where = array( 'ID' => $post_ID );
3186
3187         if ( $update ) {
3188                 /**
3189                  * Fires immediately before an existing post is updated in the database.
3190                  *
3191                  * @since 2.5.0
3192                  *
3193                  * @param int   $post_ID Post ID.
3194                  * @param array $data    Array of unslashed post data.
3195                  */
3196                 do_action( 'pre_post_update', $post_ID, $data );
3197                 if ( false === $wpdb->update( $wpdb->posts, $data, $where ) ) {
3198                         if ( $wp_error ) {
3199                                 return new WP_Error('db_update_error', __('Could not update post in the database'), $wpdb->last_error);
3200                         } else {
3201                                 return 0;
3202                         }
3203                 }
3204         } else {
3205                 // If there is a suggested ID, use it if not already present.
3206                 if ( ! empty( $import_id ) ) {
3207                         $import_id = (int) $import_id;
3208                         if ( ! $wpdb->get_var( $wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE ID = %d", $import_id) ) ) {
3209                                 $data['ID'] = $import_id;
3210                         }
3211                 }
3212                 if ( false === $wpdb->insert( $wpdb->posts, $data ) ) {
3213                         if ( $wp_error ) {
3214                                 return new WP_Error('db_insert_error', __('Could not insert post into the database'), $wpdb->last_error);
3215                         } else {
3216                                 return 0;
3217                         }
3218                 }
3219                 $post_ID = (int) $wpdb->insert_id;
3220
3221                 // Use the newly generated $post_ID.
3222                 $where = array( 'ID' => $post_ID );
3223         }
3224
3225         if ( empty( $data['post_name'] ) && ! in_array( $data['post_status'], array( 'draft', 'pending', 'auto-draft' ) ) ) {
3226                 $data['post_name'] = wp_unique_post_slug( sanitize_title( $data['post_title'], $post_ID ), $post_ID, $data['post_status'], $post_type, $post_parent );
3227                 $wpdb->update( $wpdb->posts, array( 'post_name' => $data['post_name'] ), $where );
3228                 clean_post_cache( $post_ID );
3229         }
3230
3231         if ( is_object_in_taxonomy( $post_type, 'category' ) ) {
3232                 wp_set_post_categories( $post_ID, $post_category );
3233         }
3234
3235         if ( isset( $postarr['tags_input'] ) && is_object_in_taxonomy( $post_type, 'post_tag' ) ) {
3236                 wp_set_post_tags( $post_ID, $postarr['tags_input'] );
3237         }
3238
3239         // New-style support for all custom taxonomies.
3240         if ( ! empty( $postarr['tax_input'] ) ) {
3241                 foreach ( $postarr['tax_input'] as $taxonomy => $tags ) {
3242                         $taxonomy_obj = get_taxonomy($taxonomy);
3243                         if ( ! $taxonomy_obj ) {
3244                                 /* translators: %s: taxonomy name */
3245                                 _doing_it_wrong( __FUNCTION__, sprintf( __( 'Invalid taxonomy: %s.' ), $taxonomy ), '4.4.0' );
3246                                 continue;
3247                         }
3248
3249                         // array = hierarchical, string = non-hierarchical.
3250                         if ( is_array( $tags ) ) {
3251                                 $tags = array_filter($tags);
3252                         }
3253                         if ( current_user_can( $taxonomy_obj->cap->assign_terms ) ) {
3254                                 wp_set_post_terms( $post_ID, $tags, $taxonomy );
3255                         }
3256                 }
3257         }
3258
3259         if ( ! empty( $postarr['meta_input'] ) ) {
3260                 foreach ( $postarr['meta_input'] as $field => $value ) {
3261                         update_post_meta( $post_ID, $field, $value );
3262                 }
3263         }
3264
3265         $current_guid = get_post_field( 'guid', $post_ID );
3266
3267         // Set GUID.
3268         if ( ! $update && '' == $current_guid ) {
3269                 $wpdb->update( $wpdb->posts, array( 'guid' => get_permalink( $post_ID ) ), $where );
3270         }
3271
3272         if ( 'attachment' === $postarr['post_type'] ) {
3273                 if ( ! empty( $postarr['file'] ) ) {
3274                         update_attached_file( $post_ID, $postarr['file'] );
3275                 }
3276
3277                 if ( ! empty( $postarr['context'] ) ) {
3278                         add_post_meta( $post_ID, '_wp_attachment_context', $postarr['context'], true );
3279                 }
3280         }
3281
3282         clean_post_cache( $post_ID );
3283
3284         $post = get_post( $post_ID );
3285
3286         if ( ! empty( $postarr['page_template'] ) && 'page' == $data['post_type'] ) {
3287                 $post->page_template = $postarr['page_template'];
3288                 $page_templates = wp_get_theme()->get_page_templates( $post );
3289                 if ( 'default' != $postarr['page_template'] && ! isset( $page_templates[ $postarr['page_template'] ] ) ) {
3290                         if ( $wp_error ) {
3291                                 return new WP_Error('invalid_page_template', __('The page template is invalid.'));
3292                         }
3293                         update_post_meta( $post_ID, '_wp_page_template', 'default' );
3294                 } else {
3295                         update_post_meta( $post_ID, '_wp_page_template', $postarr['page_template'] );
3296                 }
3297         }
3298
3299         if ( 'attachment' !== $postarr['post_type'] ) {
3300                 wp_transition_post_status( $data['post_status'], $previous_status, $post );
3301         } else {
3302                 if ( $update ) {
3303                         /**
3304                          * Fires once an existing attachment has been updated.
3305                          *
3306                          * @since 2.0.0
3307                          *
3308                          * @param int $post_ID Attachment ID.
3309                          */
3310                         do_action( 'edit_attachment', $post_ID );
3311                         $post_after = get_post( $post_ID );
3312
3313                         /**
3314                          * Fires once an existing attachment has been updated.
3315                          *
3316                          * @since 4.4.0
3317                          *
3318                          * @param int     $post_ID      Post ID.
3319                          * @param WP_Post $post_after   Post object following the update.
3320                          * @param WP_Post $post_before  Post object before the update.
3321                          */
3322                         do_action( 'attachment_updated', $post_ID, $post_after, $post_before );
3323                 } else {
3324
3325                         /**
3326                          * Fires once an attachment has been added.
3327                          *
3328                          * @since 2.0.0
3329                          *
3330                          * @param int $post_ID Attachment ID.
3331                          */
3332                         do_action( 'add_attachment', $post_ID );
3333                 }
3334
3335                 return $post_ID;
3336         }
3337
3338         if ( $update ) {
3339                 /**
3340                  * Fires once an existing post has been updated.
3341                  *
3342                  * @since 1.2.0
3343                  *
3344                  * @param int     $post_ID Post ID.
3345                  * @param WP_Post $post    Post object.
3346                  */
3347                 do_action( 'edit_post', $post_ID, $post );
3348                 $post_after = get_post($post_ID);
3349
3350                 /**
3351                  * Fires once an existing post has been updated.
3352                  *
3353                  * @since 3.0.0
3354                  *
3355                  * @param int     $post_ID      Post ID.
3356                  * @param WP_Post $post_after   Post object following the update.
3357                  * @param WP_Post $post_before  Post object before the update.
3358                  */
3359                 do_action( 'post_updated', $post_ID, $post_after, $post_before);
3360         }
3361
3362         /**
3363          * Fires once a post has been saved.
3364          *
3365          * The dynamic portion of the hook name, `$post->post_type`, refers to
3366          * the post type slug.
3367          *
3368          * @since 3.7.0
3369          *
3370          * @param int     $post_ID Post ID.
3371          * @param WP_Post $post    Post object.
3372          * @param bool    $update  Whether this is an existing post being updated or not.
3373          */
3374         do_action( "save_post_{$post->post_type}", $post_ID, $post, $update );
3375
3376         /**
3377          * Fires once a post has been saved.
3378          *
3379          * @since 1.5.0
3380          *
3381          * @param int     $post_ID Post ID.
3382          * @param WP_Post $post    Post object.
3383          * @param bool    $update  Whether this is an existing post being updated or not.
3384          */
3385         do_action( 'save_post', $post_ID, $post, $update );
3386
3387         /**
3388          * Fires once a post has been saved.
3389          *
3390          * @since 2.0.0
3391          *
3392          * @param int     $post_ID Post ID.
3393          * @param WP_Post $post    Post object.
3394          * @param bool    $update  Whether this is an existing post being updated or not.
3395          */
3396         do_action( 'wp_insert_post', $post_ID, $post, $update );
3397
3398         return $post_ID;
3399 }
3400
3401 /**
3402  * Update a post with new post data.
3403  *
3404  * The date does not have to be set for drafts. You can set the date and it will
3405  * not be overridden.
3406  *
3407  * @since 1.0.0
3408  *
3409  * @param array|object $postarr  Optional. Post data. Arrays are expected to be escaped,
3410  *                               objects are not. Default array.
3411  * @param bool         $wp_error Optional. Allow return of WP_Error on failure. Default false.
3412  * @return int|WP_Error The value 0 or WP_Error on failure. The post ID on success.
3413  */
3414 function wp_update_post( $postarr = array(), $wp_error = false ) {
3415         if ( is_object($postarr) ) {
3416                 // Non-escaped post was passed.
3417                 $postarr = get_object_vars($postarr);
3418                 $postarr = wp_slash($postarr);
3419         }
3420
3421         // First, get all of the original fields.
3422         $post = get_post($postarr['ID'], ARRAY_A);
3423
3424         if ( is_null( $post ) ) {
3425                 if ( $wp_error )
3426                         return new WP_Error( 'invalid_post', __( 'Invalid post ID.' ) );
3427                 return 0;
3428         }
3429
3430         // Escape data pulled from DB.
3431         $post = wp_slash($post);
3432
3433         // Passed post category list overwrites existing category list if not empty.
3434         if ( isset($postarr['post_category']) && is_array($postarr['post_category'])
3435                          && 0 != count($postarr['post_category']) )
3436                 $post_cats = $postarr['post_category'];
3437         else
3438                 $post_cats = $post['post_category'];
3439
3440         // Drafts shouldn't be assigned a date unless explicitly done so by the user.
3441         if ( isset( $post['post_status'] ) && in_array($post['post_status'], array('draft', 'pending', 'auto-draft')) && empty($postarr['edit_date']) &&
3442                          ('0000-00-00 00:00:00' == $post['post_date_gmt']) )
3443                 $clear_date = true;
3444         else
3445                 $clear_date = false;
3446
3447         // Merge old and new fields with new fields overwriting old ones.
3448         $postarr = array_merge($post, $postarr);
3449         $postarr['post_category'] = $post_cats;
3450         if ( $clear_date ) {
3451                 $postarr['post_date'] = current_time('mysql');
3452                 $postarr['post_date_gmt'] = '';
3453         }
3454
3455         if ($postarr['post_type'] == 'attachment')
3456                 return wp_insert_attachment($postarr);
3457
3458         return wp_insert_post( $postarr, $wp_error );
3459 }
3460
3461 /**
3462  * Publish a post by transitioning the post status.
3463  *
3464  * @since 2.1.0
3465  *
3466  * @global wpdb $wpdb WordPress database abstraction object.
3467  *
3468  * @param int|WP_Post $post Post ID or post object.
3469  */
3470 function wp_publish_post( $post ) {
3471         global $wpdb;
3472
3473         if ( ! $post = get_post( $post ) )
3474                 return;
3475
3476         if ( 'publish' == $post->post_status )
3477                 return;
3478
3479         $wpdb->update( $wpdb->posts, array( 'post_status' => 'publish' ), array( 'ID' => $post->ID ) );
3480
3481         clean_post_cache( $post->ID );
3482
3483         $old_status = $post->post_status;
3484         $post->post_status = 'publish';
3485         wp_transition_post_status( 'publish', $old_status, $post );
3486
3487         /** This action is documented in wp-includes/post.php */
3488         do_action( 'edit_post', $post->ID, $post );
3489
3490         /** This action is documented in wp-includes/post.php */
3491         do_action( "save_post_{$post->post_type}", $post->ID, $post, true );
3492
3493         /** This action is documented in wp-includes/post.php */
3494         do_action( 'save_post', $post->ID, $post, true );
3495
3496         /** This action is documented in wp-includes/post.php */
3497         do_action( 'wp_insert_post', $post->ID, $post, true );
3498 }
3499
3500 /**
3501  * Publish future post and make sure post ID has future post status.
3502  *
3503  * Invoked by cron 'publish_future_post' event. This safeguard prevents cron
3504  * from publishing drafts, etc.
3505  *
3506  * @since 2.5.0
3507  *
3508  * @param int|WP_Post $post_id Post ID or post object.
3509  */
3510 function check_and_publish_future_post( $post_id ) {
3511         $post = get_post($post_id);
3512
3513         if ( empty($post) )
3514                 return;
3515
3516         if ( 'future' != $post->post_status )
3517                 return;
3518
3519         $time = strtotime( $post->post_date_gmt . ' GMT' );
3520
3521         // Uh oh, someone jumped the gun!
3522         if ( $time > time() ) {
3523                 wp_clear_scheduled_hook( 'publish_future_post', array( $post_id ) ); // clear anything else in the system
3524                 wp_schedule_single_event( $time, 'publish_future_post', array( $post_id ) );
3525                 return;
3526         }
3527
3528         // wp_publish_post(_ returns no meaningful value.
3529         wp_publish_post( $post_id );
3530 }
3531
3532 /**
3533  * Computes a unique slug for the post, when given the desired slug and some post details.
3534  *
3535  * @since 2.8.0
3536  *
3537  * @global wpdb       $wpdb WordPress database abstraction object.
3538  * @global WP_Rewrite $wp_rewrite
3539  *
3540  * @param string $slug        The desired slug (post_name).
3541  * @param int    $post_ID     Post ID.
3542  * @param string $post_status No uniqueness checks are made if the post is still draft or pending.
3543  * @param string $post_type   Post type.
3544  * @param int    $post_parent Post parent ID.
3545  * @return string Unique slug for the post, based on $post_name (with a -1, -2, etc. suffix)
3546  */
3547 function wp_unique_post_slug( $slug, $post_ID, $post_status, $post_type, $post_parent ) {
3548         if ( in_array( $post_status, array( 'draft', 'pending', 'auto-draft' ) ) || ( 'inherit' == $post_status && 'revision' == $post_type ) )
3549                 return $slug;
3550
3551         global $wpdb, $wp_rewrite;
3552
3553         $original_slug = $slug;
3554
3555         $feeds = $wp_rewrite->feeds;
3556         if ( ! is_array( $feeds ) )
3557                 $feeds = array();
3558
3559         if ( 'attachment' == $post_type ) {
3560                 // Attachment slugs must be unique across all types.
3561                 $check_sql = "SELECT post_name FROM $wpdb->posts WHERE post_name = %s AND ID != %d LIMIT 1";
3562                 $post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $slug, $post_ID ) );
3563
3564                 /**
3565                  * Filter whether the post slug would make a bad attachment slug.
3566                  *
3567                  * @since 3.1.0
3568                  *
3569                  * @param bool   $bad_slug Whether the slug would be bad as an attachment slug.
3570                  * @param string $slug     The post slug.
3571                  */
3572                 if ( $post_name_check || in_array( $slug, $feeds ) || apply_filters( 'wp_unique_post_slug_is_bad_attachment_slug', false, $slug ) ) {
3573                         $suffix = 2;
3574                         do {
3575                                 $alt_post_name = _truncate_post_slug( $slug, 200 - ( strlen( $suffix ) + 1 ) ) . "-$suffix";
3576                                 $post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $alt_post_name, $post_ID ) );
3577                                 $suffix++;
3578                         } while ( $post_name_check );
3579                         $slug = $alt_post_name;
3580                 }
3581         } elseif ( is_post_type_hierarchical( $post_type ) ) {
3582                 if ( 'nav_menu_item' == $post_type )
3583                         return $slug;
3584
3585                 /*
3586                  * Page slugs must be unique within their own trees. Pages are in a separate
3587                  * namespace than posts so page slugs are allowed to overlap post slugs.
3588                  */
3589                 $check_sql = "SELECT post_name FROM $wpdb->posts WHERE post_name = %s AND post_type IN ( %s, 'attachment' ) AND ID != %d AND post_parent = %d LIMIT 1";
3590                 $post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $slug, $post_type, $post_ID, $post_parent ) );
3591
3592                 /**
3593                  * Filter whether the post slug would make a bad hierarchical post slug.
3594                  *
3595                  * @since 3.1.0
3596                  *
3597                  * @param bool   $bad_slug    Whether the post slug would be bad in a hierarchical post context.
3598                  * @param string $slug        The post slug.
3599                  * @param string $post_type   Post type.
3600                  * @param int    $post_parent Post parent ID.
3601                  */
3602                 if ( $post_name_check || in_array( $slug, $feeds ) || preg_match( "@^($wp_rewrite->pagination_base)?\d+$@", $slug )  || apply_filters( 'wp_unique_post_slug_is_bad_hierarchical_slug', false, $slug, $post_type, $post_parent ) ) {
3603                         $suffix = 2;
3604                         do {
3605                                 $alt_post_name = _truncate_post_slug( $slug, 200 - ( strlen( $suffix ) + 1 ) ) . "-$suffix";
3606                                 $post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $alt_post_name, $post_type, $post_ID, $post_parent ) );
3607                                 $suffix++;
3608                         } while ( $post_name_check );
3609                         $slug = $alt_post_name;
3610                 }
3611         } else {
3612                 // Post slugs must be unique across all posts.
3613                 $check_sql = "SELECT post_name FROM $wpdb->posts WHERE post_name = %s AND post_type = %s AND ID != %d LIMIT 1";
3614                 $post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $slug, $post_type, $post_ID ) );
3615
3616                 // Prevent new post slugs that could result in URLs that conflict with date archives.
3617                 $post = get_post( $post_ID );
3618                 $conflicts_with_date_archive = false;
3619                 if ( 'post' === $post_type && ( ! $post || $post->post_name !== $slug ) && preg_match( '/^[0-9]+$/', $slug ) && $slug_num = intval( $slug ) ) {
3620                         $permastructs   = array_values( array_filter( explode( '/', get_option( 'permalink_structure' ) ) ) );
3621                         $postname_index = array_search( '%postname%', $permastructs );
3622
3623                         /*
3624                          * Potential date clashes are as follows:
3625                          *
3626                          * - Any integer in the first permastruct position could be a year.
3627                          * - An integer between 1 and 12 that follows 'year' conflicts with 'monthnum'.
3628                          * - An integer between 1 and 31 that follows 'monthnum' conflicts with 'day'.
3629                          */
3630                         if ( 0 === $postname_index ||
3631                                 ( $postname_index && '%year%' === $permastructs[ $postname_index - 1 ] && 13 > $slug_num ) ||
3632                                 ( $postname_index && '%monthnum%' === $permastructs[ $postname_index - 1 ] && 32 > $slug_num )
3633                         ) {
3634                                 $conflicts_with_date_archive = true;
3635                         }
3636                 }
3637
3638                 /**
3639                  * Filter whether the post slug would be bad as a flat slug.
3640                  *
3641                  * @since 3.1.0
3642                  *
3643                  * @param bool   $bad_slug  Whether the post slug would be bad as a flat slug.
3644                  * @param string $slug      The post slug.
3645                  * @param string $post_type Post type.
3646                  */
3647                 if ( $post_name_check || in_array( $slug, $feeds ) || $conflicts_with_date_archive || apply_filters( 'wp_unique_post_slug_is_bad_flat_slug', false, $slug, $post_type ) ) {
3648                         $suffix = 2;
3649                         do {
3650                                 $alt_post_name = _truncate_post_slug( $slug, 200 - ( strlen( $suffix ) + 1 ) ) . "-$suffix";
3651                                 $post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $alt_post_name, $post_type, $post_ID ) );
3652                                 $suffix++;
3653                         } while ( $post_name_check );
3654                         $slug = $alt_post_name;
3655                 }
3656         }
3657
3658         /**
3659          * Filter the unique post slug.
3660          *
3661          * @since 3.3.0
3662          *
3663          * @param string $slug          The post slug.
3664          * @param int    $post_ID       Post ID.
3665          * @param string $post_status   The post status.
3666          * @param string $post_type     Post type.
3667          * @param int    $post_parent   Post parent ID
3668          * @param string $original_slug The original post slug.
3669          */
3670         return apply_filters( 'wp_unique_post_slug', $slug, $post_ID, $post_status, $post_type, $post_parent, $original_slug );
3671 }
3672
3673 /**
3674  * Truncate a post slug.
3675  *
3676  * @since 3.6.0
3677  * @access private
3678  *
3679  * @see utf8_uri_encode()
3680  *
3681  * @param string $slug   The slug to truncate.
3682  * @param int    $length Optional. Max length of the slug. Default 200 (characters).
3683  * @return string The truncated slug.
3684  */
3685 function _truncate_post_slug( $slug, $length = 200 ) {
3686         if ( strlen( $slug ) > $length ) {
3687                 $decoded_slug = urldecode( $slug );
3688                 if ( $decoded_slug === $slug )
3689                         $slug = substr( $slug, 0, $length );
3690                 else
3691                         $slug = utf8_uri_encode( $decoded_slug, $length );
3692         }
3693
3694         return rtrim( $slug, '-' );
3695 }
3696
3697 /**
3698  * Add tags to a post.
3699  *
3700  * @see wp_set_post_tags()
3701  *
3702  * @since 2.3.0
3703  *
3704  * @param int          $post_id Optional. The Post ID. Does not default to the ID of the global $post.
3705  * @param string|array $tags    Optional. An array of tags to set for the post, or a string of tags
3706  *                              separated by commas. Default empty.
3707  * @return array|false|WP_Error Array of affected term IDs. WP_Error or false on failure.
3708  */
3709 function wp_add_post_tags( $post_id = 0, $tags = '' ) {
3710         return wp_set_post_tags($post_id, $tags, true);
3711 }
3712
3713 /**
3714  * Set the tags for a post.
3715  *
3716  * @since 2.3.0
3717  *
3718  * @see wp_set_object_terms()
3719  *
3720  * @param int          $post_id Optional. The Post ID. Does not default to the ID of the global $post.
3721  * @param string|array $tags    Optional. An array of tags to set for the post, or a string of tags
3722  *                              separated by commas. Default empty.
3723  * @param bool         $append  Optional. If true, don't delete existing tags, just add on. If false,
3724  *                              replace the tags with the new tags. Default false.
3725  * @return array|false|WP_Error Array of affected term IDs. WP_Error or false on failure.
3726  */
3727 function wp_set_post_tags( $post_id = 0, $tags = '', $append = false ) {
3728         return wp_set_post_terms( $post_id, $tags, 'post_tag', $append);
3729 }
3730
3731 /**
3732  * Set the terms for a post.
3733  *
3734  * @since 2.8.0
3735  *
3736  * @see wp_set_object_terms()
3737  *
3738  * @param int          $post_id  Optional. The Post ID. Does not default to the ID of the global $post.
3739  * @param string|array $tags     Optional. An array of terms to set for the post, or a string of terms
3740  *                               separated by commas. Default empty.
3741  * @param string       $taxonomy Optional. Taxonomy name. Default 'post_tag'.
3742  * @param bool         $append   Optional. If true, don't delete existing terms, just add on. If false,
3743  *                               replace the terms with the new terms. Default false.
3744  * @return array|false|WP_Error Array of affected term IDs. WP_Error or false on failure.
3745  */
3746 function wp_set_post_terms( $post_id = 0, $tags = '', $taxonomy = 'post_tag', $append = false ) {
3747         $post_id = (int) $post_id;
3748
3749         if ( !$post_id )
3750                 return false;
3751
3752         if ( empty($tags) )
3753                 $tags = array();
3754
3755         if ( ! is_array( $tags ) ) {
3756                 $comma = _x( ',', 'tag delimiter' );
3757                 if ( ',' !== $comma )
3758                         $tags = str_replace( $comma, ',', $tags );
3759                 $tags = explode( ',', trim( $tags, " \n\t\r\0\x0B," ) );
3760         }
3761
3762         /*
3763          * Hierarchical taxonomies must always pass IDs rather than names so that
3764          * children with the same names but different parents aren't confused.
3765          */
3766         if ( is_taxonomy_hierarchical( $taxonomy ) ) {
3767                 $tags = array_unique( array_map( 'intval', $tags ) );
3768         }
3769
3770         return wp_set_object_terms( $post_id, $tags, $taxonomy, $append );
3771 }
3772
3773 /**
3774  * Set categories for a post.
3775  *
3776  * If the post categories parameter is not set, then the default category is
3777  * going used.
3778  *
3779  * @since 2.1.0
3780  *
3781  * @param int       $post_ID         Optional. The Post ID. Does not default to the ID
3782  *                                   of the global $post. Default 0.
3783  * @param array|int $post_categories Optional. List of categories or ID of category.
3784  *                                   Default empty array.
3785  * @param bool      $append         If true, don't delete existing categories, just add on.
3786  *                                  If false, replace the categories with the new categories.
3787  * @return array|bool|WP_Error
3788  */
3789 function wp_set_post_categories( $post_ID = 0, $post_categories = array(), $append = false ) {
3790         $post_ID = (int) $post_ID;
3791         $post_type = get_post_type( $post_ID );
3792         $post_status = get_post_status( $post_ID );
3793         // If $post_categories isn't already an array, make it one:
3794         $post_categories = (array) $post_categories;
3795         if ( empty( $post_categories ) ) {
3796                 if ( 'post' == $post_type && 'auto-draft' != $post_status ) {
3797                         $post_categories = array( get_option('default_category') );
3798                         $append = false;
3799                 } else {
3800                         $post_categories = array();
3801                 }
3802         } elseif ( 1 == count( $post_categories ) && '' == reset( $post_categories ) ) {
3803                 return true;
3804         }
3805
3806         return wp_set_post_terms( $post_ID, $post_categories, 'category', $append );
3807 }
3808
3809 /**
3810  * Fires actions related to the transitioning of a post's status.
3811  *
3812  * When a post is saved, the post status is "transitioned" from one status to another,
3813  * though this does not always mean the status has actually changed before and after
3814  * the save. This function fires a number of action hooks related to that transition:
3815  * the generic 'transition_post_status' action, as well as the dynamic hooks
3816  * `"{$old_status}_to_{$new_status}"` and `"{$new_status}_{$post->post_type}"`. Note
3817  * that the function does not transition the post object in the database.
3818  *
3819  * For instance: When publishing a post for the first time, the post status may transition
3820  * from 'draft' â€“ or some other status â€“ to 'publish'. However, if a post is already
3821  * published and is simply being updated, the "old" and "new" statuses may both be 'publish'
3822  * before and after the transition.
3823  *
3824  * @since 2.3.0
3825  *
3826  * @param string  $new_status Transition to this post status.
3827  * @param string  $old_status Previous post status.
3828  * @param WP_Post $post Post data.
3829  */
3830 function wp_transition_post_status( $new_status, $old_status, $post ) {
3831         /**
3832          * Fires when a post is transitioned from one status to another.
3833          *
3834          * @since 2.3.0
3835          *
3836          * @param string  $new_status New post status.
3837          * @param string  $old_status Old post status.
3838          * @param WP_Post $post       Post object.
3839          */
3840         do_action( 'transition_post_status', $new_status, $old_status, $post );
3841
3842         /**
3843          * Fires when a post is transitioned from one status to another.
3844          *
3845          * The dynamic portions of the hook name, `$new_status` and `$old status`,
3846          * refer to the old and new post statuses, respectively.
3847          *
3848          * @since 2.3.0
3849          *
3850          * @param WP_Post $post Post object.
3851          */
3852         do_action( "{$old_status}_to_{$new_status}", $post );
3853
3854         /**
3855          * Fires when a post is transitioned from one status to another.
3856          *
3857          * The dynamic portions of the hook name, `$new_status` and `$post->post_type`,
3858          * refer to the new post status and post type, respectively.
3859          *
3860          * Please note: When this action is hooked using a particular post status (like
3861          * 'publish', as `publish_{$post->post_type}`), it will fire both when a post is
3862          * first transitioned to that status from something else, as well as upon
3863          * subsequent post updates (old and new status are both the same).
3864          *
3865          * Therefore, if you are looking to only fire a callback when a post is first
3866          * transitioned to a status, use the {@see 'transition_post_status'} hook instead.
3867          *
3868          * @since 2.3.0
3869          *
3870          * @param int     $post_id Post ID.
3871          * @param WP_Post $post    Post object.
3872          */
3873         do_action( "{$new_status}_{$post->post_type}", $post->ID, $post );
3874 }
3875
3876 //
3877 // Comment, trackback, and pingback functions.
3878 //
3879
3880 /**
3881  * Add a URL to those already pinged.
3882  *
3883  * @since 1.5.0
3884  *
3885  * @global wpdb $wpdb WordPress database abstraction object.
3886  *
3887  * @param int    $post_id Post ID.
3888  * @param string $uri     Ping URI.
3889  * @return int|false How many rows were updated.
3890  */
3891 function add_ping( $post_id, $uri ) {
3892         global $wpdb;
3893         $pung = $wpdb->get_var( $wpdb->prepare( "SELECT pinged FROM $wpdb->posts WHERE ID = %d", $post_id ));
3894         $pung = trim($pung);
3895         $pung = preg_split('/\s/', $pung);
3896         $pung[] = $uri;
3897         $new = implode("\n", $pung);
3898
3899         /**
3900          * Filter the new ping URL to add for the given post.
3901          *
3902          * @since 2.0.0
3903          *
3904          * @param string $new New ping URL to add.
3905          */
3906         $new = apply_filters( 'add_ping', $new );
3907
3908         // expected_slashed ($new).
3909         $new = wp_unslash($new);
3910         return $wpdb->update( $wpdb->posts, array( 'pinged' => $new ), array( 'ID' => $post_id ) );
3911 }
3912
3913 /**
3914  * Retrieve enclosures already enclosed for a post.
3915  *
3916  * @since 1.5.0
3917  *
3918  * @param int $post_id Post ID.
3919  * @return array List of enclosures.
3920  */
3921 function get_enclosed( $post_id ) {
3922         $custom_fields = get_post_custom( $post_id );
3923         $pung = array();
3924         if ( !is_array( $custom_fields ) )
3925                 return $pung;
3926
3927         foreach ( $custom_fields as $key => $val ) {
3928                 if ( 'enclosure' != $key || !is_array( $val ) )
3929                         continue;
3930                 foreach ( $val as $enc ) {
3931                         $enclosure = explode( "\n", $enc );
3932                         $pung[] = trim( $enclosure[ 0 ] );
3933                 }
3934         }
3935
3936         /**
3937          * Filter the list of enclosures already enclosed for the given post.
3938          *
3939          * @since 2.0.0
3940          *
3941          * @param array $pung    Array of enclosures for the given post.
3942          * @param int   $post_id Post ID.
3943          */
3944         return apply_filters( 'get_enclosed', $pung, $post_id );
3945 }
3946
3947 /**
3948  * Retrieve URLs already pinged for a post.
3949  *
3950  * @since 1.5.0
3951  *
3952  * @global wpdb $wpdb WordPress database abstraction object.
3953  *
3954  * @param int $post_id Post ID.
3955  * @return array
3956  */
3957 function get_pung( $post_id ) {
3958         global $wpdb;
3959         $pung = $wpdb->get_var( $wpdb->prepare( "SELECT pinged FROM $wpdb->posts WHERE ID = %d", $post_id ));
3960         $pung = trim($pung);
3961         $pung = preg_split('/\s/', $pung);
3962
3963         /**
3964          * Filter the list of already-pinged URLs for the given post.
3965          *
3966          * @since 2.0.0
3967          *
3968          * @param array $pung Array of URLs already pinged for the given post.
3969          */
3970         return apply_filters( 'get_pung', $pung );
3971 }
3972
3973 /**
3974  * Retrieve URLs that need to be pinged.
3975  *
3976  * @since 1.5.0
3977  *
3978  * @global wpdb $wpdb WordPress database abstraction object.
3979  *
3980  * @param int $post_id Post ID
3981  * @return array
3982  */
3983 function get_to_ping( $post_id ) {
3984         global $wpdb;
3985         $to_ping = $wpdb->get_var( $wpdb->prepare( "SELECT to_ping FROM $wpdb->posts WHERE ID = %d", $post_id ));
3986         $to_ping = sanitize_trackback_urls( $to_ping );
3987         $to_ping = preg_split('/\s/', $to_ping, -1, PREG_SPLIT_NO_EMPTY);
3988
3989         /**
3990          * Filter the list of URLs yet to ping for the given post.
3991          *
3992          * @since 2.0.0
3993          *
3994          * @param array $to_ping List of URLs yet to ping.
3995          */
3996         return apply_filters( 'get_to_ping', $to_ping );
3997 }
3998
3999 /**
4000  * Do trackbacks for a list of URLs.
4001  *
4002  * @since 1.0.0
4003  *
4004  * @param string $tb_list Comma separated list of URLs.
4005  * @param int    $post_id Post ID.
4006  */
4007 function trackback_url_list( $tb_list, $post_id ) {
4008         if ( ! empty( $tb_list ) ) {
4009                 // Get post data.
4010                 $postdata = get_post( $post_id, ARRAY_A );
4011
4012                 // Form an excerpt.
4013                 $excerpt = strip_tags( $postdata['post_excerpt'] ? $postdata['post_excerpt'] : $postdata['post_content'] );
4014
4015                 if ( strlen( $excerpt ) > 255 ) {
4016                         $excerpt = substr( $excerpt, 0, 252 ) . '&hellip;';
4017                 }
4018
4019                 $trackback_urls = explode( ',', $tb_list );
4020                 foreach ( (array) $trackback_urls as $tb_url ) {
4021                         $tb_url = trim( $tb_url );
4022                         trackback( $tb_url, wp_unslash( $postdata['post_title'] ), $excerpt, $post_id );
4023                 }
4024         }
4025 }
4026
4027 //
4028 // Page functions
4029 //
4030
4031 /**
4032  * Get a list of page IDs.
4033  *
4034  * @since 2.0.0
4035  *
4036  * @global wpdb $wpdb WordPress database abstraction object.
4037  *
4038  * @return array List of page IDs.
4039  */
4040 function get_all_page_ids() {
4041         global $wpdb;
4042
4043         $page_ids = wp_cache_get('all_page_ids', 'posts');
4044         if ( ! is_array( $page_ids ) ) {
4045                 $page_ids = $wpdb->get_col("SELECT ID FROM $wpdb->posts WHERE post_type = 'page'");
4046                 wp_cache_add('all_page_ids', $page_ids, 'posts');
4047         }
4048
4049         return $page_ids;
4050 }
4051
4052 /**
4053  * Retrieves page data given a page ID or page object.
4054  *
4055  * Use get_post() instead of get_page().
4056  *
4057  * @since 1.5.1
4058  * @deprecated 3.5.0 Use get_post()
4059  *
4060  * @param mixed  $page   Page object or page ID. Passed by reference.
4061  * @param string $output Optional. What to output. Accepts OBJECT, ARRAY_A, or ARRAY_N.
4062  *                       Default OBJECT.
4063  * @param string $filter Optional. How the return value should be filtered. Accepts 'raw',
4064  *                       'edit', 'db', 'display'. Default 'raw'.
4065  * @return WP_Post|array|null WP_Post on success or null on failure.
4066  */
4067 function get_page( $page, $output = OBJECT, $filter = 'raw') {
4068         return get_post( $page, $output, $filter );
4069 }
4070
4071 /**
4072  * Retrieves a page given its path.
4073  *
4074  * @since 2.1.0
4075  *
4076  * @global wpdb $wpdb WordPress database abstraction object.
4077  *
4078  * @param string       $page_path Page path.
4079  * @param string       $output    Optional. Output type. Accepts OBJECT, ARRAY_N, or ARRAY_A.
4080  *                                Default OBJECT.
4081  * @param string|array $post_type Optional. Post type or array of post types. Default 'page'.
4082  * @return WP_Post|array|void WP_Post on success.
4083  */
4084 function get_page_by_path( $page_path, $output = OBJECT, $post_type = 'page' ) {
4085         global $wpdb;
4086
4087         $page_path = rawurlencode(urldecode($page_path));
4088         $page_path = str_replace('%2F', '/', $page_path);
4089         $page_path = str_replace('%20', ' ', $page_path);
4090         $parts = explode( '/', trim( $page_path, '/' ) );
4091         $parts = esc_sql( $parts );
4092         $parts = array_map( 'sanitize_title_for_query', $parts );
4093
4094         $in_string = "'" . implode( "','", $parts ) . "'";
4095
4096         if ( is_array( $post_type ) ) {
4097                 $post_types = $post_type;
4098         } else {
4099                 $post_types = array( $post_type, 'attachment' );
4100         }
4101
4102         $post_types = esc_sql( $post_types );
4103         $post_type_in_string = "'" . implode( "','", $post_types ) . "'";
4104         $sql = "
4105                 SELECT ID, post_name, post_parent, post_type
4106                 FROM $wpdb->posts
4107                 WHERE post_name IN ($in_string)
4108                 AND post_type IN ($post_type_in_string)
4109         ";
4110
4111         $pages = $wpdb->get_results( $sql, OBJECT_K );
4112
4113         $revparts = array_reverse( $parts );
4114
4115         $foundid = 0;
4116         foreach ( (array) $pages as $page ) {
4117                 if ( $page->post_name == $revparts[0] ) {
4118                         $count = 0;
4119                         $p = $page;
4120                         while ( $p->post_parent != 0 && isset( $pages[ $p->post_parent ] ) ) {
4121                                 $count++;
4122                                 $parent = $pages[ $p->post_parent ];
4123                                 if ( ! isset( $revparts[ $count ] ) || $parent->post_name != $revparts[ $count ] )
4124                                         break;
4125                                 $p = $parent;
4126                         }
4127
4128                         if ( $p->post_parent == 0 && $count+1 == count( $revparts ) && $p->post_name == $revparts[ $count ] ) {
4129                                 $foundid = $page->ID;
4130                                 if ( $page->post_type == $post_type )
4131                                         break;
4132                         }
4133                 }
4134         }
4135
4136         if ( $foundid ) {
4137                 return get_post( $foundid, $output );
4138         }
4139 }
4140
4141 /**
4142  * Retrieve a page given its title.
4143  *
4144  * @since 2.1.0
4145  *
4146  * @global wpdb $wpdb WordPress database abstraction object.
4147  *
4148  * @param string       $page_title Page title
4149  * @param string       $output     Optional. Output type. OBJECT, ARRAY_N, or ARRAY_A.
4150  *                                 Default OBJECT.
4151  * @param string|array $post_type  Optional. Post type or array of post types. Default 'page'.
4152  * @return WP_Post|array|void WP_Post on success or null on failure
4153  */
4154 function get_page_by_title( $page_title, $output = OBJECT, $post_type = 'page' ) {
4155         global $wpdb;
4156
4157         if ( is_array( $post_type ) ) {
4158                 $post_type = esc_sql( $post_type );
4159                 $post_type_in_string = "'" . implode( "','", $post_type ) . "'";
4160                 $sql = $wpdb->prepare( "
4161                         SELECT ID
4162                         FROM $wpdb->posts
4163                         WHERE post_title = %s
4164                         AND post_type IN ($post_type_in_string)
4165                 ", $page_title );
4166         } else {
4167                 $sql = $wpdb->prepare( "
4168                         SELECT ID
4169                         FROM $wpdb->posts
4170                         WHERE post_title = %s
4171                         AND post_type = %s
4172                 ", $page_title, $post_type );
4173         }
4174
4175         $page = $wpdb->get_var( $sql );
4176
4177         if ( $page ) {
4178                 return get_post( $page, $output );
4179         }
4180 }
4181
4182 /**
4183  * Identify descendants of a given page ID in a list of page objects.
4184  *
4185  * Descendants are identified from the `$pages` array passed to the function. No database queries are performed.
4186  *
4187  * @since 1.5.1
4188  *
4189  * @param int   $page_id Page ID.
4190  * @param array $pages   List of page objects from which descendants should be identified.
4191  * @return array List of page children.
4192  */
4193 function get_page_children( $page_id, $pages ) {
4194         // Build a hash of ID -> children.
4195         $children = array();
4196         foreach ( (array) $pages as $page ) {
4197                 $children[ intval( $page->post_parent ) ][] = $page;
4198         }
4199
4200         $page_list = array();
4201
4202         // Start the search by looking at immediate children.
4203         if ( isset( $children[ $page_id ] ) ) {
4204                 // Always start at the end of the stack in order to preserve original `$pages` order.
4205                 $to_look = array_reverse( $children[ $page_id ] );
4206
4207                 while ( $to_look ) {
4208                         $p = array_pop( $to_look );
4209                         $page_list[] = $p;
4210                         if ( isset( $children[ $p->ID ] ) ) {
4211                                 foreach ( array_reverse( $children[ $p->ID ] ) as $child ) {
4212                                         // Append to the `$to_look` stack to descend the tree.
4213                                         $to_look[] = $child;
4214                                 }
4215                         }
4216                 }
4217         }
4218
4219         return $page_list;
4220 }
4221
4222 /**
4223  * Order the pages with children under parents in a flat list.
4224  *
4225  * It uses auxiliary structure to hold parent-children relationships and
4226  * runs in O(N) complexity
4227  *
4228  * @since 2.0.0
4229  *
4230  * @param array $pages   Posts array, passed by reference.
4231  * @param int   $page_id Optional. Parent page ID. Default 0.
4232  * @return array A list arranged by hierarchy. Children immediately follow their parents.
4233  */
4234 function get_page_hierarchy( &$pages, $page_id = 0 ) {
4235         if ( empty( $pages ) ) {
4236                 return array();
4237         }
4238
4239         $children = array();
4240         foreach ( (array) $pages as $p ) {
4241                 $parent_id = intval( $p->post_parent );
4242                 $children[ $parent_id ][] = $p;
4243         }
4244
4245         $result = array();
4246         _page_traverse_name( $page_id, $children, $result );
4247
4248         return $result;
4249 }
4250
4251 /**
4252  * Traverse and return all the nested children post names of a root page.
4253  *
4254  * $children contains parent-children relations
4255  *
4256  * @since 2.9.0
4257  *
4258  * @see _page_traverse_name()
4259  *
4260  * @param int   $page_id   Page ID.
4261  * @param array &$children Parent-children relations, passed by reference.
4262  * @param array &$result   Result, passed by reference.
4263  */
4264 function _page_traverse_name( $page_id, &$children, &$result ){
4265         if ( isset( $children[ $page_id ] ) ){
4266                 foreach ( (array)$children[ $page_id ] as $child ) {
4267                         $result[ $child->ID ] = $child->post_name;
4268                         _page_traverse_name( $child->ID, $children, $result );
4269                 }
4270         }
4271 }
4272
4273 /**
4274  * Build URI for a page.
4275  *
4276  * Sub pages will be in the "directory" under the parent page post name.
4277  *
4278  * @since 1.5.0
4279  *
4280  * @param WP_Post|object|int $page Page object or page ID.
4281  * @return string|false Page URI, false on error.
4282  */
4283 function get_page_uri( $page ) {
4284         $page = get_post( $page );
4285
4286         if ( ! $page )
4287                 return false;
4288
4289         $uri = $page->post_name;
4290
4291         foreach ( $page->ancestors as $parent ) {
4292                 $parent = get_post( $parent );
4293                 if ( $parent ) {
4294                         $uri = $parent->post_name . '/' . $uri;
4295                 }
4296         }
4297
4298         /**
4299          * Filter the URI for a page.
4300          *
4301          * @since 4.4.0
4302          *
4303          * @param string  $uri  Page URI.
4304          * @param WP_Post $page Page object.
4305          */
4306         return apply_filters( 'get_page_uri', $uri, $page );
4307 }
4308
4309 /**
4310  * Retrieve a list of pages.
4311  *
4312  * @global wpdb $wpdb WordPress database abstraction object.
4313  *
4314  * @since 1.5.0
4315  *
4316  * @param array|string $args {
4317  *     Optional. Array or string of arguments to retrieve pages.
4318  *
4319  *     @type int          $child_of     Page ID to return child and grandchild pages of. Note: The value
4320  *                                      of `$hierarchical` has no bearing on whether `$child_of` returns
4321  *                                      hierarchical results. Default 0, or no restriction.
4322  *     @type string       $sort_order   How to sort retrieved pages. Accepts 'ASC', 'DESC'. Default 'ASC'.
4323  *     @type string       $sort_column  What columns to sort pages by, comma-separated. Accepts 'post_author',
4324  *                                      'post_date', 'post_title', 'post_name', 'post_modified', 'menu_order',
4325  *                                      'post_modified_gmt', 'post_parent', 'ID', 'rand', 'comment_count'.
4326  *                                      'post_' can be omitted for any values that start with it.
4327  *                                      Default 'post_title'.
4328  *     @type bool         $hierarchical Whether to return pages hierarchically. If false in conjunction with
4329  *                                      `$child_of` also being false, both arguments will be disregarded.
4330  *                                      Default true.
4331  *     @type array        $exclude      Array of page IDs to exclude. Default empty array.
4332  *     @type array        $include      Array of page IDs to include. Cannot be used with `$child_of`,
4333  *                                      `$parent`, `$exclude`, `$meta_key`, `$meta_value`, or `$hierarchical`.
4334  *                                      Default empty array.
4335  *     @type string       $meta_key     Only include pages with this meta key. Default empty.
4336  *     @type string       $meta_value   Only include pages with this meta value. Requires `$meta_key`.
4337  *                                      Default empty.
4338  *     @type string       $authors      A comma-separated list of author IDs. Default empty.
4339  *     @type int          $parent       Page ID to return direct children of. Default -1, or no restriction.
4340  *     @type string|array $exclude_tree Comma-separated string or array of page IDs to exclude.
4341  *                                      Default empty array.
4342  *     @type int          $number       The number of pages to return. Default 0, or all pages.
4343  *     @type int          $offset       The number of pages to skip before returning. Requires `$number`.
4344  *                                      Default 0.
4345  *     @type string       $post_type    The post type to query. Default 'page'.
4346  *     @type string       $post_status  A comma-separated list of post status types to include.
4347  *                                      Default 'publish'.
4348  * }
4349  * @return array|false List of pages matching defaults or `$args`.
4350  */
4351 function get_pages( $args = array() ) {
4352         global $wpdb;
4353
4354         $defaults = array(
4355                 'child_of' => 0, 'sort_order' => 'ASC',
4356                 'sort_column' => 'post_title', 'hierarchical' => 1,
4357                 'exclude' => array(), 'include' => array(),
4358                 'meta_key' => '', 'meta_value' => '',
4359                 'authors' => '', 'parent' => -1, 'exclude_tree' => array(),
4360                 'number' => '', 'offset' => 0,
4361                 'post_type' => 'page', 'post_status' => 'publish',
4362         );
4363
4364         $r = wp_parse_args( $args, $defaults );
4365
4366         $number = (int) $r['number'];
4367         $offset = (int) $r['offset'];
4368         $child_of = (int) $r['child_of'];
4369         $hierarchical = $r['hierarchical'];
4370         $exclude = $r['exclude'];
4371         $meta_key = $r['meta_key'];
4372         $meta_value = $r['meta_value'];
4373         $parent = $r['parent'];
4374         $post_status = $r['post_status'];
4375
4376         // Make sure the post type is hierarchical.
4377         $hierarchical_post_types = get_post_types( array( 'hierarchical' => true ) );
4378         if ( ! in_array( $r['post_type'], $hierarchical_post_types ) ) {
4379                 return false;
4380         }
4381
4382         if ( $parent > 0 && ! $child_of ) {
4383                 $hierarchical = false;
4384         }
4385
4386         // Make sure we have a valid post status.
4387         if ( ! is_array( $post_status ) ) {
4388                 $post_status = explode( ',', $post_status );
4389         }
4390         if ( array_diff( $post_status, get_post_stati() ) ) {
4391                 return false;
4392         }
4393
4394         // $args can be whatever, only use the args defined in defaults to compute the key.
4395         $key = md5( serialize( wp_array_slice_assoc( $r, array_keys( $defaults ) ) ) );
4396         $last_changed = wp_cache_get( 'last_changed', 'posts' );
4397         if ( ! $last_changed ) {
4398                 $last_changed = microtime();
4399                 wp_cache_set( 'last_changed', $last_changed, 'posts' );
4400         }
4401
4402         $cache_key = "get_pages:$key:$last_changed";
4403         if ( $cache = wp_cache_get( $cache_key, 'posts' ) ) {
4404                 // Convert to WP_Post instances.
4405                 $pages = array_map( 'get_post', $cache );
4406                 /** This filter is documented in wp-includes/post.php */
4407                 $pages = apply_filters( 'get_pages', $pages, $r );
4408                 return $pages;
4409         }
4410
4411         $inclusions = '';
4412         if ( ! empty( $r['include'] ) ) {
4413                 $child_of = 0; //ignore child_of, parent, exclude, meta_key, and meta_value params if using include
4414                 $parent = -1;
4415                 $exclude = '';
4416                 $meta_key = '';
4417                 $meta_value = '';
4418                 $hierarchical = false;
4419                 $incpages = wp_parse_id_list( $r['include'] );
4420                 if ( ! empty( $incpages ) ) {
4421                         $inclusions = ' AND ID IN (' . implode( ',', $incpages ) .  ')';
4422                 }
4423         }
4424
4425         $exclusions = '';
4426         if ( ! empty( $exclude ) ) {
4427                 $expages = wp_parse_id_list( $exclude );
4428                 if ( ! empty( $expages ) ) {
4429                         $exclusions = ' AND ID NOT IN (' . implode( ',', $expages ) .  ')';
4430                 }
4431         }
4432
4433         $author_query = '';
4434         if ( ! empty( $r['authors'] ) ) {
4435                 $post_authors = preg_split( '/[\s,]+/', $r['authors'] );
4436
4437                 if ( ! empty( $post_authors ) ) {
4438                         foreach ( $post_authors as $post_author ) {
4439                                 //Do we have an author id or an author login?
4440                                 if ( 0 == intval($post_author) ) {
4441                                         $post_author = get_user_by('login', $post_author);
4442                                         if ( empty( $post_author ) ) {
4443                                                 continue;
4444                                         }
4445                                         if ( empty( $post_author->ID ) ) {
4446                                                 continue;
4447                                         }
4448                                         $post_author = $post_author->ID;
4449                                 }
4450
4451                                 if ( '' == $author_query ) {
4452                                         $author_query = $wpdb->prepare(' post_author = %d ', $post_author);
4453                                 } else {
4454                                         $author_query .= $wpdb->prepare(' OR post_author = %d ', $post_author);
4455                                 }
4456                         }
4457                         if ( '' != $author_query ) {
4458                                 $author_query = " AND ($author_query)";
4459                         }
4460                 }
4461         }
4462
4463         $join = '';
4464         $where = "$exclusions $inclusions ";
4465         if ( '' !== $meta_key || '' !== $meta_value ) {
4466                 $join = " LEFT JOIN $wpdb->postmeta ON ( $wpdb->posts.ID = $wpdb->postmeta.post_id )";
4467
4468                 // meta_key and meta_value might be slashed
4469                 $meta_key = wp_unslash($meta_key);
4470                 $meta_value = wp_unslash($meta_value);
4471                 if ( '' !== $meta_key ) {
4472                         $where .= $wpdb->prepare(" AND $wpdb->postmeta.meta_key = %s", $meta_key);
4473                 }
4474                 if ( '' !== $meta_value ) {
4475                         $where .= $wpdb->prepare(" AND $wpdb->postmeta.meta_value = %s", $meta_value);
4476                 }
4477
4478         }
4479
4480         if ( is_array( $parent ) ) {
4481                 $post_parent__in = implode( ',', array_map( 'absint', (array) $parent ) );
4482                 if ( ! empty( $post_parent__in ) ) {
4483                         $where .= " AND post_parent IN ($post_parent__in)";
4484                 }
4485         } elseif ( $parent >= 0 ) {
4486                 $where .= $wpdb->prepare(' AND post_parent = %d ', $parent);
4487         }
4488
4489         if ( 1 == count( $post_status ) ) {
4490                 $where_post_type = $wpdb->prepare( "post_type = %s AND post_status = %s", $r['post_type'], reset( $post_status ) );
4491         } else {
4492                 $post_status = implode( "', '", $post_status );
4493                 $where_post_type = $wpdb->prepare( "post_type = %s AND post_status IN ('$post_status')", $r['post_type'] );
4494         }
4495
4496         $orderby_array = array();
4497         $allowed_keys = array( 'author', 'post_author', 'date', 'post_date', 'title', 'post_title', 'name', 'post_name', 'modified',
4498                 'post_modified', 'modified_gmt', 'post_modified_gmt', 'menu_order', 'parent', 'post_parent',
4499                 'ID', 'rand', 'comment_count' );
4500
4501         foreach ( explode( ',', $r['sort_column'] ) as $orderby ) {
4502                 $orderby = trim( $orderby );
4503                 if ( ! in_array( $orderby, $allowed_keys ) ) {
4504                         continue;
4505                 }
4506
4507                 switch ( $orderby ) {
4508                         case 'menu_order':
4509                                 break;
4510                         case 'ID':
4511                                 $orderby = "$wpdb->posts.ID";
4512                                 break;
4513                         case 'rand':
4514                                 $orderby = 'RAND()';
4515                                 break;
4516                         case 'comment_count':
4517                                 $orderby = "$wpdb->posts.comment_count";
4518                                 break;
4519                         default:
4520                                 if ( 0 === strpos( $orderby, 'post_' ) ) {
4521                                         $orderby = "$wpdb->posts." . $orderby;
4522                                 } else {
4523                                         $orderby = "$wpdb->posts.post_" . $orderby;
4524                                 }
4525                 }
4526
4527                 $orderby_array[] = $orderby;
4528
4529         }
4530         $sort_column = ! empty( $orderby_array ) ? implode( ',', $orderby_array ) : "$wpdb->posts.post_title";
4531
4532         $sort_order = strtoupper( $r['sort_order'] );
4533         if ( '' !== $sort_order && ! in_array( $sort_order, array( 'ASC', 'DESC' ) ) ) {
4534                 $sort_order = 'ASC';
4535         }
4536
4537         $query = "SELECT * FROM $wpdb->posts $join WHERE ($where_post_type) $where ";
4538         $query .= $author_query;
4539         $query .= " ORDER BY " . $sort_column . " " . $sort_order ;
4540
4541         if ( ! empty( $number ) ) {
4542                 $query .= ' LIMIT ' . $offset . ',' . $number;
4543         }
4544
4545         $pages = $wpdb->get_results($query);
4546
4547         if ( empty($pages) ) {
4548                 /** This filter is documented in wp-includes/post.php */
4549                 $pages = apply_filters( 'get_pages', array(), $r );
4550                 return $pages;
4551         }
4552
4553         // Sanitize before caching so it'll only get done once.
4554         $num_pages = count($pages);
4555         for ($i = 0; $i < $num_pages; $i++) {
4556                 $pages[$i] = sanitize_post($pages[$i], 'raw');
4557         }
4558
4559         // Update cache.
4560         update_post_cache( $pages );
4561
4562         if ( $child_of || $hierarchical ) {
4563                 $pages = get_page_children($child_of, $pages);
4564         }
4565
4566         if ( ! empty( $r['exclude_tree'] ) ) {
4567                 $exclude = wp_parse_id_list( $r['exclude_tree'] );
4568                 foreach ( $exclude as $id ) {
4569                         $children = get_page_children( $id, $pages );
4570                         foreach ( $children as $child ) {
4571                                 $exclude[] = $child->ID;
4572                         }
4573                 }
4574
4575                 $num_pages = count( $pages );
4576                 for ( $i = 0; $i < $num_pages; $i++ ) {
4577                         if ( in_array( $pages[$i]->ID, $exclude ) ) {
4578                                 unset( $pages[$i] );
4579                         }
4580                 }
4581         }
4582
4583         $page_structure = array();
4584         foreach ( $pages as $page ) {
4585                 $page_structure[] = $page->ID;
4586         }
4587
4588         wp_cache_set( $cache_key, $page_structure, 'posts' );
4589
4590         // Convert to WP_Post instances
4591         $pages = array_map( 'get_post', $pages );
4592
4593         /**
4594          * Filter the retrieved list of pages.
4595          *
4596          * @since 2.1.0
4597          *
4598          * @param array $pages List of pages to retrieve.
4599          * @param array $r     Array of get_pages() arguments.
4600          */
4601         return apply_filters( 'get_pages', $pages, $r );
4602 }
4603
4604 //
4605 // Attachment functions
4606 //
4607
4608 /**
4609  * Check if the attachment URI is local one and is really an attachment.
4610  *
4611  * @since 2.0.0
4612  *
4613  * @param string $url URL to check
4614  * @return bool True on success, false on failure.
4615  */
4616 function is_local_attachment($url) {
4617         if (strpos($url, home_url()) === false)
4618                 return false;
4619         if (strpos($url, home_url('/?attachment_id=')) !== false)
4620                 return true;
4621         if ( $id = url_to_postid($url) ) {
4622                 $post = get_post($id);
4623                 if ( 'attachment' == $post->post_type )
4624                         return true;
4625         }
4626         return false;
4627 }
4628
4629 /**
4630  * Insert an attachment.
4631  *
4632  * If you set the 'ID' in the $args parameter, it will mean that you are
4633  * updating and attempt to update the attachment. You can also set the
4634  * attachment name or title by setting the key 'post_name' or 'post_title'.
4635  *
4636  * You can set the dates for the attachment manually by setting the 'post_date'
4637  * and 'post_date_gmt' keys' values.
4638  *
4639  * By default, the comments will use the default settings for whether the
4640  * comments are allowed. You can close them manually or keep them open by
4641  * setting the value for the 'comment_status' key.
4642  *
4643  * @since 2.0.0
4644  *
4645  * @see wp_insert_post()
4646  *
4647  * @param string|array $args   Arguments for inserting an attachment.
4648  * @param string       $file   Optional. Filename.
4649  * @param int          $parent Optional. Parent post ID.
4650  * @return int Attachment ID.
4651  */
4652 function wp_insert_attachment( $args, $file = false, $parent = 0 ) {
4653         $defaults = array(
4654                 'file'        => $file,
4655                 'post_parent' => 0
4656         );
4657
4658         $data = wp_parse_args( $args, $defaults );
4659
4660         if ( ! empty( $parent ) ) {
4661                 $data['post_parent'] = $parent;
4662         }
4663
4664         $data['post_type'] = 'attachment';
4665
4666         return wp_insert_post( $data );
4667 }
4668
4669 /**
4670  * Trash or delete an attachment.
4671  *
4672  * When an attachment is permanently deleted, the file will also be removed.
4673  * Deletion removes all post meta fields, taxonomy, comments, etc. associated
4674  * with the attachment (except the main post).
4675  *
4676  * The attachment is moved to the trash instead of permanently deleted unless trash
4677  * for media is disabled, item is already in the trash, or $force_delete is true.
4678  *
4679  * @since 2.0.0
4680  *
4681  * @global wpdb $wpdb WordPress database abstraction object.
4682  *
4683  * @param int  $post_id      Attachment ID.
4684  * @param bool $force_delete Optional. Whether to bypass trash and force deletion.
4685  *                           Default false.
4686  * @return mixed False on failure. Post data on success.
4687  */
4688 function wp_delete_attachment( $post_id, $force_delete = false ) {
4689         global $wpdb;
4690
4691         if ( !$post = $wpdb->get_row( $wpdb->prepare("SELECT * FROM $wpdb->posts WHERE ID = %d", $post_id) ) )
4692                 return $post;
4693
4694         if ( 'attachment' != $post->post_type )
4695                 return false;
4696
4697         if ( !$force_delete && EMPTY_TRASH_DAYS && MEDIA_TRASH && 'trash' != $post->post_status )
4698                 return wp_trash_post( $post_id );
4699
4700         delete_post_meta($post_id, '_wp_trash_meta_status');
4701         delete_post_meta($post_id, '_wp_trash_meta_time');
4702
4703         $meta = wp_get_attachment_metadata( $post_id );
4704         $backup_sizes = get_post_meta( $post->ID, '_wp_attachment_backup_sizes', true );
4705         $file = get_attached_file( $post_id );
4706
4707         if ( is_multisite() )
4708                 delete_transient( 'dirsize_cache' );
4709
4710         /**
4711          * Fires before an attachment is deleted, at the start of wp_delete_attachment().
4712          *
4713          * @since 2.0.0
4714          *
4715          * @param int $post_id Attachment ID.
4716          */
4717         do_action( 'delete_attachment', $post_id );
4718
4719         wp_delete_object_term_relationships($post_id, array('category', 'post_tag'));
4720         wp_delete_object_term_relationships($post_id, get_object_taxonomies($post->post_type));
4721
4722         // Delete all for any posts.
4723         delete_metadata( 'post', null, '_thumbnail_id', $post_id, true );
4724
4725         wp_defer_comment_counting( true );
4726
4727         $comment_ids = $wpdb->get_col( $wpdb->prepare( "SELECT comment_ID FROM $wpdb->comments WHERE comment_post_ID = %d", $post_id ));
4728         foreach ( $comment_ids as $comment_id ) {
4729                 wp_delete_comment( $comment_id, true );
4730         }
4731
4732         wp_defer_comment_counting( false );
4733
4734         $post_meta_ids = $wpdb->get_col( $wpdb->prepare( "SELECT meta_id FROM $wpdb->postmeta WHERE post_id = %d ", $post_id ));
4735         foreach ( $post_meta_ids as $mid )
4736                 delete_metadata_by_mid( 'post', $mid );
4737
4738         /** This action is documented in wp-includes/post.php */
4739         do_action( 'delete_post', $post_id );
4740         $result = $wpdb->delete( $wpdb->posts, array( 'ID' => $post_id ) );
4741         if ( ! $result ) {
4742                 return false;
4743         }
4744         /** This action is documented in wp-includes/post.php */
4745         do_action( 'deleted_post', $post_id );
4746
4747         $uploadpath = wp_upload_dir();
4748
4749         if ( ! empty($meta['thumb']) ) {
4750                 // Don't delete the thumb if another attachment uses it.
4751                 if (! $wpdb->get_row( $wpdb->prepare( "SELECT meta_id FROM $wpdb->postmeta WHERE meta_key = '_wp_attachment_metadata' AND meta_value LIKE %s AND post_id <> %d", '%' . $wpdb->esc_like( $meta['thumb'] ) . '%', $post_id)) ) {
4752                         $thumbfile = str_replace(basename($file), $meta['thumb'], $file);
4753                         /** This filter is documented in wp-includes/functions.php */
4754                         $thumbfile = apply_filters( 'wp_delete_file', $thumbfile );
4755                         @ unlink( path_join($uploadpath['basedir'], $thumbfile) );
4756                 }
4757         }
4758
4759         // Remove intermediate and backup images if there are any.
4760         if ( isset( $meta['sizes'] ) && is_array( $meta['sizes'] ) ) {
4761                 foreach ( $meta['sizes'] as $size => $sizeinfo ) {
4762                         $intermediate_file = str_replace( basename( $file ), $sizeinfo['file'], $file );
4763                         /** This filter is documented in wp-includes/functions.php */
4764                         $intermediate_file = apply_filters( 'wp_delete_file', $intermediate_file );
4765                         @ unlink( path_join( $uploadpath['basedir'], $intermediate_file ) );
4766                 }
4767         }
4768
4769         if ( is_array($backup_sizes) ) {
4770                 foreach ( $backup_sizes as $size ) {
4771                         $del_file = path_join( dirname($meta['file']), $size['file'] );
4772                         /** This filter is documented in wp-includes/functions.php */
4773                         $del_file = apply_filters( 'wp_delete_file', $del_file );
4774                         @ unlink( path_join($uploadpath['basedir'], $del_file) );
4775                 }
4776         }
4777
4778         wp_delete_file( $file );
4779
4780         clean_post_cache( $post );
4781
4782         return $post;
4783 }
4784
4785 /**
4786  * Retrieve attachment meta field for attachment ID.
4787  *
4788  * @since 2.1.0
4789  *
4790  * @param int  $post_id    Attachment ID. Default 0.
4791  * @param bool $unfiltered Optional. If true, filters are not run. Default false.
4792  * @return mixed Attachment meta field. False on failure.
4793  */
4794 function wp_get_attachment_metadata( $post_id = 0, $unfiltered = false ) {
4795         $post_id = (int) $post_id;
4796         if ( !$post = get_post( $post_id ) )
4797                 return false;
4798
4799         $data = get_post_meta( $post->ID, '_wp_attachment_metadata', true );
4800
4801         if ( $unfiltered )
4802                 return $data;
4803
4804         /**
4805          * Filter the attachment meta data.
4806          *
4807          * @since 2.1.0
4808          *
4809          * @param array|bool $data    Array of meta data for the given attachment, or false
4810          *                            if the object does not exist.
4811          * @param int        $post_id Attachment ID.
4812          */
4813         return apply_filters( 'wp_get_attachment_metadata', $data, $post->ID );
4814 }
4815
4816 /**
4817  * Update metadata for an attachment.
4818  *
4819  * @since 2.1.0
4820  *
4821  * @param int   $post_id Attachment ID.
4822  * @param array $data    Attachment data.
4823  * @return int|bool False if $post is invalid.
4824  */
4825 function wp_update_attachment_metadata( $post_id, $data ) {
4826         $post_id = (int) $post_id;
4827         if ( !$post = get_post( $post_id ) )
4828                 return false;
4829
4830         /**
4831          * Filter the updated attachment meta data.
4832          *
4833          * @since 2.1.0
4834          *
4835          * @param array $data    Array of updated attachment meta data.
4836          * @param int   $post_id Attachment ID.
4837          */
4838         if ( $data = apply_filters( 'wp_update_attachment_metadata', $data, $post->ID ) )
4839                 return update_post_meta( $post->ID, '_wp_attachment_metadata', $data );
4840         else
4841                 return delete_post_meta( $post->ID, '_wp_attachment_metadata' );
4842 }
4843
4844 /**
4845  * Retrieve the URL for an attachment.
4846  *
4847  * @since 2.1.0
4848  *
4849  * @global string $pagenow
4850  *
4851  * @param int $post_id Optional. Attachment ID. Default 0.
4852  * @return string|false Attachment URL, otherwise false.
4853  */
4854 function wp_get_attachment_url( $post_id = 0 ) {
4855         $post_id = (int) $post_id;
4856         if ( !$post = get_post( $post_id ) )
4857                 return false;
4858
4859         if ( 'attachment' != $post->post_type )
4860                 return false;
4861
4862         $url = '';
4863         // Get attached file.
4864         if ( $file = get_post_meta( $post->ID, '_wp_attached_file', true) ) {
4865                 // Get upload directory.
4866                 if ( ($uploads = wp_upload_dir()) && false === $uploads['error'] ) {
4867                         // Check that the upload base exists in the file location.
4868                         if ( 0 === strpos( $file, $uploads['basedir'] ) ) {
4869                                 // Replace file location with url location.
4870                                 $url = str_replace($uploads['basedir'], $uploads['baseurl'], $file);
4871                         } elseif ( false !== strpos($file, 'wp-content/uploads') ) {
4872                                 // Get the directory name relative to the basedir (back compat for pre-2.7 uploads)
4873                                 $url = trailingslashit( $uploads['baseurl'] . '/' . _wp_get_attachment_relative_path( $file ) ) . basename( $file );
4874                         } else {
4875                                 // It's a newly-uploaded file, therefore $file is relative to the basedir.
4876                                 $url = $uploads['baseurl'] . "/$file";
4877                         }
4878                 }
4879         }
4880
4881         /*
4882          * If any of the above options failed, Fallback on the GUID as used pre-2.7,
4883          * not recommended to rely upon this.
4884          */
4885         if ( empty($url) ) {
4886                 $url = get_the_guid( $post->ID );
4887         }
4888
4889         // On SSL front-end, URLs should be HTTPS.
4890         if ( is_ssl() && ! is_admin() && 'wp-login.php' !== $GLOBALS['pagenow'] ) {
4891                 $url = set_url_scheme( $url );
4892         }
4893
4894         /**
4895          * Filter the attachment URL.
4896          *
4897          * @since 2.1.0
4898          *
4899          * @param string $url     URL for the given attachment.
4900          * @param int    $post_id Attachment ID.
4901          */
4902         $url = apply_filters( 'wp_get_attachment_url', $url, $post->ID );
4903
4904         if ( empty( $url ) )
4905                 return false;
4906
4907         return $url;
4908 }
4909
4910 /**
4911  * Retrieve thumbnail for an attachment.
4912  *
4913  * @since 2.1.0
4914  *
4915  * @param int $post_id Optional. Attachment ID. Default 0.
4916  * @return string|false False on failure. Thumbnail file path on success.
4917  */
4918 function wp_get_attachment_thumb_file( $post_id = 0 ) {
4919         $post_id = (int) $post_id;
4920         if ( !$post = get_post( $post_id ) )
4921                 return false;
4922         if ( !is_array( $imagedata = wp_get_attachment_metadata( $post->ID ) ) )
4923                 return false;
4924
4925         $file = get_attached_file( $post->ID );
4926
4927         if ( !empty($imagedata['thumb']) && ($thumbfile = str_replace(basename($file), $imagedata['thumb'], $file)) && file_exists($thumbfile) ) {
4928                 /**
4929                  * Filter the attachment thumbnail file path.
4930                  *
4931                  * @since 2.1.0
4932                  *
4933                  * @param string $thumbfile File path to the attachment thumbnail.
4934                  * @param int    $post_id   Attachment ID.
4935                  */
4936                 return apply_filters( 'wp_get_attachment_thumb_file', $thumbfile, $post->ID );
4937         }
4938         return false;
4939 }
4940
4941 /**
4942  * Retrieve URL for an attachment thumbnail.
4943  *
4944  * @since 2.1.0
4945  *
4946  * @param int $post_id Optional. Attachment ID. Default 0.
4947  * @return string|false False on failure. Thumbnail URL on success.
4948  */
4949 function wp_get_attachment_thumb_url( $post_id = 0 ) {
4950         $post_id = (int) $post_id;
4951         if ( !$post = get_post( $post_id ) )
4952                 return false;
4953         if ( !$url = wp_get_attachment_url( $post->ID ) )
4954                 return false;
4955
4956         $sized = image_downsize( $post_id, 'thumbnail' );
4957         if ( $sized )
4958                 return $sized[0];
4959
4960         if ( !$thumb = wp_get_attachment_thumb_file( $post->ID ) )
4961                 return false;
4962
4963         $url = str_replace(basename($url), basename($thumb), $url);
4964
4965         /**
4966          * Filter the attachment thumbnail URL.
4967          *
4968          * @since 2.1.0
4969          *
4970          * @param string $url     URL for the attachment thumbnail.
4971          * @param int    $post_id Attachment ID.
4972          */
4973         return apply_filters( 'wp_get_attachment_thumb_url', $url, $post->ID );
4974 }
4975
4976 /**
4977  * Verifies an attachment is of a given type.
4978  *
4979  * @since 4.2.0
4980  *
4981  * @param string      $type    Attachment type. Accepts 'image', 'audio', or 'video'.
4982  * @param int|WP_Post $post_id Optional. Attachment ID. Default 0.
4983  * @return bool True if one of the accepted types, false otherwise.
4984  */
4985 function wp_attachment_is( $type, $post_id = 0 ) {
4986         if ( ! $post = get_post( $post_id ) ) {
4987                 return false;
4988         }
4989
4990         if ( ! $file = get_attached_file( $post->ID ) ) {
4991                 return false;
4992         }
4993
4994         if ( 0 === strpos( $post->post_mime_type, $type . '/' ) ) {
4995                 return true;
4996         }
4997
4998         $check = wp_check_filetype( $file );
4999         if ( empty( $check['ext'] ) ) {
5000                 return false;
5001         }
5002
5003         $ext = $check['ext'];
5004
5005         if ( 'import' !== $post->post_mime_type ) {
5006                 return $type === $ext;
5007         }
5008
5009         switch ( $type ) {
5010         case 'image':
5011                 $image_exts = array( 'jpg', 'jpeg', 'jpe', 'gif', 'png' );
5012                 return in_array( $ext, $image_exts );
5013
5014         case 'audio':
5015                 return in_array( $ext, wp_get_audio_extensions() );
5016
5017         case 'video':
5018                 return in_array( $ext, wp_get_video_extensions() );
5019
5020         default:
5021                 return $type === $ext;
5022         }
5023 }
5024
5025 /**
5026  * Checks if the attachment is an image.
5027  *
5028  * @since 2.1.0
5029  * @since 4.2.0 Modified into wrapper for wp_attachment_is() and
5030  *              allowed WP_Post object to be passed.
5031  *
5032  * @param int|WP_Post $post Optional. Attachment ID. Default 0.
5033  * @return bool Whether the attachment is an image.
5034  */
5035 function wp_attachment_is_image( $post = 0 ) {
5036         return wp_attachment_is( 'image', $post );
5037 }
5038
5039 /**
5040  * Retrieve the icon for a MIME type.
5041  *
5042  * @since 2.1.0
5043  *
5044  * @param string|int $mime MIME type or attachment ID.
5045  * @return string|false Icon, false otherwise.
5046  */
5047 function wp_mime_type_icon( $mime = 0 ) {
5048         if ( !is_numeric($mime) )
5049                 $icon = wp_cache_get("mime_type_icon_$mime");
5050
5051         $post_id = 0;
5052         if ( empty($icon) ) {
5053                 $post_mimes = array();
5054                 if ( is_numeric($mime) ) {
5055                         $mime = (int) $mime;
5056                         if ( $post = get_post( $mime ) ) {
5057                                 $post_id = (int) $post->ID;
5058                                 $file = get_attached_file( $post_id );
5059                                 $ext = preg_replace('/^.+?\.([^.]+)$/', '$1', $file);
5060                                 if ( !empty($ext) ) {
5061                                         $post_mimes[] = $ext;
5062                                         if ( $ext_type = wp_ext2type( $ext ) )
5063                                                 $post_mimes[] = $ext_type;
5064                                 }
5065                                 $mime = $post->post_mime_type;
5066                         } else {
5067                                 $mime = 0;
5068                         }
5069                 } else {
5070                         $post_mimes[] = $mime;
5071                 }
5072
5073                 $icon_files = wp_cache_get('icon_files');
5074
5075                 if ( !is_array($icon_files) ) {
5076                         /**
5077                          * Filter the icon directory path.
5078                          *
5079                          * @since 2.0.0
5080                          *
5081                          * @param string $path Icon directory absolute path.
5082                          */
5083                         $icon_dir = apply_filters( 'icon_dir', ABSPATH . WPINC . '/images/media' );
5084
5085                         /**
5086                          * Filter the icon directory URI.
5087                          *
5088                          * @since 2.0.0
5089                          *
5090                          * @param string $uri Icon directory URI.
5091                          */
5092                         $icon_dir_uri = apply_filters( 'icon_dir_uri', includes_url( 'images/media' ) );
5093
5094                         /**
5095                          * Filter the list of icon directory URIs.
5096                          *
5097                          * @since 2.5.0
5098                          *
5099                          * @param array $uris List of icon directory URIs.
5100                          */
5101                         $dirs = apply_filters( 'icon_dirs', array( $icon_dir => $icon_dir_uri ) );
5102                         $icon_files = array();
5103                         while ( $dirs ) {
5104                                 $keys = array_keys( $dirs );
5105                                 $dir = array_shift( $keys );
5106                                 $uri = array_shift($dirs);
5107                                 if ( $dh = opendir($dir) ) {
5108                                         while ( false !== $file = readdir($dh) ) {
5109                                                 $file = basename($file);
5110                                                 if ( substr($file, 0, 1) == '.' )
5111                                                         continue;
5112                                                 if ( !in_array(strtolower(substr($file, -4)), array('.png', '.gif', '.jpg') ) ) {
5113                                                         if ( is_dir("$dir/$file") )
5114                                                                 $dirs["$dir/$file"] = "$uri/$file";
5115                                                         continue;
5116                                                 }
5117                                                 $icon_files["$dir/$file"] = "$uri/$file";
5118                                         }
5119                                         closedir($dh);
5120                                 }
5121                         }
5122                         wp_cache_add( 'icon_files', $icon_files, 'default', 600 );
5123                 }
5124
5125                 $types = array();
5126                 // Icon basename - extension = MIME wildcard.
5127                 foreach ( $icon_files as $file => $uri )
5128                         $types[ preg_replace('/^([^.]*).*$/', '$1', basename($file)) ] =& $icon_files[$file];
5129
5130                 if ( ! empty($mime) ) {
5131                         $post_mimes[] = substr($mime, 0, strpos($mime, '/'));
5132                         $post_mimes[] = substr($mime, strpos($mime, '/') + 1);
5133                         $post_mimes[] = str_replace('/', '_', $mime);
5134                 }
5135
5136                 $matches = wp_match_mime_types(array_keys($types), $post_mimes);
5137                 $matches['default'] = array('default');
5138
5139                 foreach ( $matches as $match => $wilds ) {
5140                         foreach ( $wilds as $wild ) {
5141                                 if ( ! isset( $types[ $wild ] ) ) {
5142                                         continue;
5143                                 }
5144
5145                                 $icon = $types[ $wild ];
5146                                 if ( ! is_numeric( $mime ) ) {
5147                                         wp_cache_add( "mime_type_icon_$mime", $icon );
5148                                 }
5149                                 break 2;
5150                         }
5151                 }
5152         }
5153
5154         /**
5155          * Filter the mime type icon.
5156          *
5157          * @since 2.1.0
5158          *
5159          * @param string $icon    Path to the mime type icon.
5160          * @param string $mime    Mime type.
5161          * @param int    $post_id Attachment ID. Will equal 0 if the function passed
5162          *                        the mime type.
5163          */
5164         return apply_filters( 'wp_mime_type_icon', $icon, $mime, $post_id );
5165 }
5166
5167 /**
5168  * Check for changed slugs for published post objects and save the old slug.
5169  *
5170  * The function is used when a post object of any type is updated,
5171  * by comparing the current and previous post objects.
5172  *
5173  * If the slug was changed and not already part of the old slugs then it will be
5174  * added to the post meta field ('_wp_old_slug') for storing old slugs for that
5175  * post.
5176  *
5177  * The most logically usage of this function is redirecting changed post objects, so
5178  * that those that linked to an changed post will be redirected to the new post.
5179  *
5180  * @since 2.1.0
5181  *
5182  * @param int     $post_id     Post ID.
5183  * @param WP_Post $post        The Post Object
5184  * @param WP_Post $post_before The Previous Post Object
5185  */
5186 function wp_check_for_changed_slugs( $post_id, $post, $post_before ) {
5187         // Don't bother if it hasn't changed.
5188         if ( $post->post_name == $post_before->post_name ) {
5189                 return;
5190         }
5191
5192         // We're only concerned with published, non-hierarchical objects.
5193         if ( ! ( 'publish' === $post->post_status || ( 'attachment' === get_post_type( $post ) && 'inherit' === $post->post_status ) ) || is_post_type_hierarchical( $post->post_type ) ) {
5194                 return;
5195         }
5196
5197         $old_slugs = (array) get_post_meta( $post_id, '_wp_old_slug' );
5198
5199         // If we haven't added this old slug before, add it now.
5200         if ( ! empty( $post_before->post_name ) && ! in_array( $post_before->post_name, $old_slugs ) ) {
5201                 add_post_meta( $post_id, '_wp_old_slug', $post_before->post_name );
5202         }
5203
5204         // If the new slug was used previously, delete it from the list.
5205         if ( in_array( $post->post_name, $old_slugs ) ) {
5206                 delete_post_meta( $post_id, '_wp_old_slug', $post->post_name );
5207         }
5208 }
5209
5210 /**
5211  * Retrieve the private post SQL based on capability.
5212  *
5213  * This function provides a standardized way to appropriately select on the
5214  * post_status of a post type. The function will return a piece of SQL code
5215  * that can be added to a WHERE clause; this SQL is constructed to allow all
5216  * published posts, and all private posts to which the user has access.
5217  *
5218  * @since 2.2.0
5219  * @since 4.3.0 Added the ability to pass an array to `$post_type`.
5220  *
5221  * @param string|array $post_type Single post type or an array of post types. Currently only supports 'post' or 'page'.
5222  * @return string SQL code that can be added to a where clause.
5223  */
5224 function get_private_posts_cap_sql( $post_type ) {
5225         return get_posts_by_author_sql( $post_type, false );
5226 }
5227
5228 /**
5229  * Retrieve the post SQL based on capability, author, and type.
5230  *
5231  * @since 3.0.0
5232  * @since 4.3.0 Introduced the ability to pass an array of post types to `$post_type`.
5233  *
5234  * @see get_private_posts_cap_sql()
5235  * @global wpdb $wpdb WordPress database abstraction object.
5236  *
5237  * @param array|string   $post_type   Single post type or an array of post types.
5238  * @param bool           $full        Optional. Returns a full WHERE statement instead of just
5239  *                                    an 'andalso' term. Default true.
5240  * @param int            $post_author Optional. Query posts having a single author ID. Default null.
5241  * @param bool           $public_only Optional. Only return public posts. Skips cap checks for
5242  *                                    $current_user.  Default false.
5243  * @return string SQL WHERE code that can be added to a query.
5244  */
5245 function get_posts_by_author_sql( $post_type, $full = true, $post_author = null, $public_only = false ) {
5246         global $wpdb;
5247
5248         if ( is_array( $post_type ) ) {
5249                 $post_types = $post_type;
5250         } else {
5251                 $post_types = array( $post_type );
5252         }
5253
5254         $post_type_clauses = array();
5255         foreach ( $post_types as $post_type ) {
5256                 $post_type_obj = get_post_type_object( $post_type );
5257                 if ( ! $post_type_obj ) {
5258                         continue;
5259                 }
5260
5261                 /**
5262                  * Filter the capability to read private posts for a custom post type
5263                  * when generating SQL for getting posts by author.
5264                  *
5265                  * @since 2.2.0
5266                  * @deprecated 3.2.0 The hook transitioned from "somewhat useless" to "totally useless".
5267                  *
5268                  * @param string $cap Capability.
5269                  */
5270                 if ( ! $cap = apply_filters( 'pub_priv_sql_capability', '' ) ) {
5271                         $cap = current_user_can( $post_type_obj->cap->read_private_posts );
5272                 }
5273
5274                 // Only need to check the cap if $public_only is false.
5275                 $post_status_sql = "post_status = 'publish'";
5276                 if ( false === $public_only ) {
5277                         if ( $cap ) {
5278                                 // Does the user have the capability to view private posts? Guess so.
5279                                 $post_status_sql .= " OR post_status = 'private'";
5280                         } elseif ( is_user_logged_in() ) {
5281                                 // Users can view their own private posts.
5282                                 $id = get_current_user_id();
5283                                 if ( null === $post_author || ! $full ) {
5284                                         $post_status_sql .= " OR post_status = 'private' AND post_author = $id";
5285                                 } elseif ( $id == (int) $post_author ) {
5286                                         $post_status_sql .= " OR post_status = 'private'";
5287                                 } // else none
5288                         } // else none
5289                 }
5290
5291                 $post_type_clauses[] = "( post_type = '" . $post_type . "' AND ( $post_status_sql ) )";
5292         }
5293
5294         if ( empty( $post_type_clauses ) ) {
5295                 return $full ? 'WHERE 1 = 0' : '1 = 0';
5296         }
5297
5298         $sql = '( '. implode( ' OR ', $post_type_clauses ) . ' )';
5299
5300         if ( null !== $post_author ) {
5301                 $sql .= $wpdb->prepare( ' AND post_author = %d', $post_author );
5302         }
5303
5304         if ( $full ) {
5305                 $sql = 'WHERE ' . $sql;
5306         }
5307
5308         return $sql;
5309 }
5310
5311 /**
5312  * Retrieve the date that the last post was published.
5313  *
5314  * The server timezone is the default and is the difference between GMT and
5315  * server time. The 'blog' value is the date when the last post was posted. The
5316  * 'gmt' is when the last post was posted in GMT formatted date.
5317  *
5318  * @since 0.71
5319  * @since 4.4.0 The `$post_type` argument was added.
5320  *
5321  * @param string $timezone  Optional. The timezone for the timestamp. Accepts 'server', 'blog', or 'gmt'.
5322  *                          'server' uses the server's internal timezone.
5323  *                          'blog' uses the `post_modified` field, which proxies to the timezone set for the site.
5324  *                          'gmt' uses the `post_modified_gmt` field.
5325  *                          Default 'server'.
5326  * @param string $post_type Optional. The post type to check. Default 'any'.
5327  * @return string The date of the last post.
5328  */
5329 function get_lastpostdate( $timezone = 'server', $post_type = 'any' ) {
5330         /**
5331          * Filter the date the last post was published.
5332          *
5333          * @since 2.3.0
5334          *
5335          * @param string $date     Date the last post was published.
5336          * @param string $timezone Location to use for getting the post published date.
5337          *                         See {@see get_lastpostdate()} for accepted `$timezone` values.
5338          */
5339         return apply_filters( 'get_lastpostdate', _get_last_post_time( $timezone, 'date', $post_type ), $timezone );
5340 }
5341
5342 /**
5343  * Get the timestamp of the last time any post was modified.
5344  *
5345  * The server timezone is the default and is the difference between GMT and
5346  * server time. The 'blog' value is just when the last post was modified. The
5347  * 'gmt' is when the last post was modified in GMT time.
5348  *
5349  * @since 1.2.0
5350  * @since 4.4.0 The `$post_type` argument was added.
5351  *
5352  * @param string $timezone  Optional. The timezone for the timestamp. See {@see get_lastpostdate()}
5353  *                          for information on accepted values.
5354  *                          Default 'server'.
5355  * @param string $post_type Optional. The post type to check. Default 'any'.
5356  * @return string The timestamp.
5357  */
5358 function get_lastpostmodified( $timezone = 'server', $post_type = 'any' ) {
5359         /**
5360          * Pre-filter the return value of get_lastpostmodified() before the query is run.
5361          *
5362          * @since 4.4.0
5363          *
5364          * @param string $lastpostmodified Date the last post was modified.
5365          *                                 Returning anything other than false will short-circuit the function.
5366          * @param string $timezone         Location to use for getting the post modified date.
5367          *                                 See {@see get_lastpostdate()} for accepted `$timezone` values.
5368          * @param string $post_type        The post type to check.
5369          */
5370         $lastpostmodified = apply_filters( 'pre_get_lastpostmodified', false, $timezone, $post_type );
5371         if ( false !== $lastpostmodified ) {
5372                 return $lastpostmodified;
5373         }
5374
5375         $lastpostmodified = _get_last_post_time( $timezone, 'modified', $post_type );
5376
5377         $lastpostdate = get_lastpostdate($timezone);
5378         if ( $lastpostdate > $lastpostmodified ) {
5379                 $lastpostmodified = $lastpostdate;
5380         }
5381
5382         /**
5383          * Filter the date the last post was modified.
5384          *
5385          * @since 2.3.0
5386          *
5387          * @param string $lastpostmodified Date the last post was modified.
5388          * @param string $timezone         Location to use for getting the post modified date.
5389          *                                 See {@see get_lastpostdate()} for accepted `$timezone` values.
5390          */
5391         return apply_filters( 'get_lastpostmodified', $lastpostmodified, $timezone );
5392 }
5393
5394 /**
5395  * Get the timestamp of the last time any post was modified or published.
5396  *
5397  * @since 3.1.0
5398  * @since 4.4.0 The `$post_type` argument was added.
5399  * @access private
5400  *
5401  * @global wpdb $wpdb WordPress database abstraction object.
5402  *
5403  * @param string $timezone  The timezone for the timestamp. See get_lastpostdate().
5404  *                          for information on accepted values.
5405  * @param string $field     Post field to check. Accepts 'date' or 'modified'.
5406  * @param string $post_type Optional. The post type to check. Default 'any'.
5407  * @return string|false The timestamp.
5408  */
5409 function _get_last_post_time( $timezone, $field, $post_type = 'any' ) {
5410         global $wpdb;
5411
5412         if ( ! in_array( $field, array( 'date', 'modified' ) ) ) {
5413                 return false;
5414         }
5415
5416         $timezone = strtolower( $timezone );
5417
5418         $key = "lastpost{$field}:$timezone";
5419         if ( 'any' !== $post_type ) {
5420                 $key .= ':' . sanitize_key( $post_type );
5421         }
5422
5423         $date = wp_cache_get( $key, 'timeinfo' );
5424
5425         if ( ! $date ) {
5426                 if ( 'any' === $post_type ) {
5427                         $post_types = get_post_types( array( 'public' => true ) );
5428                         array_walk( $post_types, array( $wpdb, 'escape_by_ref' ) );
5429                         $post_types = "'" . implode( "', '", $post_types ) . "'";
5430                 } else {
5431                         $post_types = "'" . sanitize_key( $post_type ) . "'";
5432                 }
5433
5434                 switch ( $timezone ) {
5435                         case 'gmt':
5436                                 $date = $wpdb->get_var("SELECT post_{$field}_gmt FROM $wpdb->posts WHERE post_status = 'publish' AND post_type IN ({$post_types}) ORDER BY post_{$field}_gmt DESC LIMIT 1");
5437                                 break;
5438                         case 'blog':
5439                                 $date = $wpdb->get_var("SELECT post_{$field} FROM $wpdb->posts WHERE post_status = 'publish' AND post_type IN ({$post_types}) ORDER BY post_{$field}_gmt DESC LIMIT 1");
5440                                 break;
5441                         case 'server':
5442                                 $add_seconds_server = date( 'Z' );
5443                                 $date = $wpdb->get_var("SELECT DATE_ADD(post_{$field}_gmt, INTERVAL '$add_seconds_server' SECOND) FROM $wpdb->posts WHERE post_status = 'publish' AND post_type IN ({$post_types}) ORDER BY post_{$field}_gmt DESC LIMIT 1");
5444                                 break;
5445                 }
5446
5447                 if ( $date ) {
5448                         wp_cache_set( $key, $date, 'timeinfo' );
5449                 }
5450         }
5451
5452         return $date;
5453 }
5454
5455 /**
5456  * Updates posts in cache.
5457  *
5458  * @since 1.5.1
5459  *
5460  * @param array $posts Array of post objects, passed by reference.
5461  */
5462 function update_post_cache( &$posts ) {
5463         if ( ! $posts )
5464                 return;
5465
5466         foreach ( $posts as $post )
5467                 wp_cache_add( $post->ID, $post, 'posts' );
5468 }
5469
5470 /**
5471  * Will clean the post in the cache.
5472  *
5473  * Cleaning means delete from the cache of the post. Will call to clean the term
5474  * object cache associated with the post ID.
5475  *
5476  * This function not run if $_wp_suspend_cache_invalidation is not empty. See
5477  * wp_suspend_cache_invalidation().
5478  *
5479  * @since 2.0.0
5480  *
5481  * @global bool $_wp_suspend_cache_invalidation
5482  *
5483  * @param int|WP_Post $post Post ID or post object to remove from the cache.
5484  */
5485 function clean_post_cache( $post ) {
5486         global $_wp_suspend_cache_invalidation;
5487
5488         if ( ! empty( $_wp_suspend_cache_invalidation ) )
5489                 return;
5490
5491         $post = get_post( $post );
5492         if ( empty( $post ) )
5493                 return;
5494
5495         wp_cache_delete( $post->ID, 'posts' );
5496         wp_cache_delete( $post->ID, 'post_meta' );
5497
5498         clean_object_term_cache( $post->ID, $post->post_type );
5499
5500         wp_cache_delete( 'wp_get_archives', 'general' );
5501
5502         /**
5503          * Fires immediately after the given post's cache is cleaned.
5504          *
5505          * @since 2.5.0
5506          *
5507          * @param int     $post_id Post ID.
5508          * @param WP_Post $post    Post object.
5509          */
5510         do_action( 'clean_post_cache', $post->ID, $post );
5511
5512         if ( 'page' == $post->post_type ) {
5513                 wp_cache_delete( 'all_page_ids', 'posts' );
5514
5515                 /**
5516                  * Fires immediately after the given page's cache is cleaned.
5517                  *
5518                  * @since 2.5.0
5519                  *
5520                  * @param int $post_id Post ID.
5521                  */
5522                 do_action( 'clean_page_cache', $post->ID );
5523         }
5524
5525         wp_cache_set( 'last_changed', microtime(), 'posts' );
5526 }
5527
5528 /**
5529  * Call major cache updating functions for list of Post objects.
5530  *
5531  * @since 1.5.0
5532  *
5533  * @param array  $posts             Array of Post objects
5534  * @param string $post_type         Optional. Post type. Default 'post'.
5535  * @param bool   $update_term_cache Optional. Whether to update the term cache. Default true.
5536  * @param bool   $update_meta_cache Optional. Whether to update the meta cache. Default true.
5537  */
5538 function update_post_caches( &$posts, $post_type = 'post', $update_term_cache = true, $update_meta_cache = true ) {
5539         // No point in doing all this work if we didn't match any posts.
5540         if ( !$posts )
5541                 return;
5542
5543         update_post_cache($posts);
5544
5545         $post_ids = array();
5546         foreach ( $posts as $post )
5547                 $post_ids[] = $post->ID;
5548
5549         if ( ! $post_type )
5550                 $post_type = 'any';
5551
5552         if ( $update_term_cache ) {
5553                 if ( is_array($post_type) ) {
5554                         $ptypes = $post_type;
5555                 } elseif ( 'any' == $post_type ) {
5556                         $ptypes = array();
5557                         // Just use the post_types in the supplied posts.
5558                         foreach ( $posts as $post ) {
5559                                 $ptypes[] = $post->post_type;
5560                         }
5561                         $ptypes = array_unique($ptypes);
5562                 } else {
5563                         $ptypes = array($post_type);
5564                 }
5565
5566                 if ( ! empty($ptypes) )
5567                         update_object_term_cache($post_ids, $ptypes);
5568         }
5569
5570         if ( $update_meta_cache )
5571                 update_postmeta_cache($post_ids);
5572 }
5573
5574 /**
5575  * Updates metadata cache for list of post IDs.
5576  *
5577  * Performs SQL query to retrieve the metadata for the post IDs and updates the
5578  * metadata cache for the posts. Therefore, the functions, which call this
5579  * function, do not need to perform SQL queries on their own.
5580  *
5581  * @since 2.1.0
5582  *
5583  * @param array $post_ids List of post IDs.
5584  * @return array|false Returns false if there is nothing to update or an array
5585  *                     of metadata.
5586  */
5587 function update_postmeta_cache( $post_ids ) {
5588         return update_meta_cache('post', $post_ids);
5589 }
5590
5591 /**
5592  * Will clean the attachment in the cache.
5593  *
5594  * Cleaning means delete from the cache. Optionally will clean the term
5595  * object cache associated with the attachment ID.
5596  *
5597  * This function will not run if $_wp_suspend_cache_invalidation is not empty.
5598  *
5599  * @since 3.0.0
5600  *
5601  * @global bool $_wp_suspend_cache_invalidation
5602  *
5603  * @param int  $id          The attachment ID in the cache to clean.
5604  * @param bool $clean_terms Optional. Whether to clean terms cache. Default false.
5605  */
5606 function clean_attachment_cache( $id, $clean_terms = false ) {
5607         global $_wp_suspend_cache_invalidation;
5608
5609         if ( !empty($_wp_suspend_cache_invalidation) )
5610                 return;
5611
5612         $id = (int) $id;
5613
5614         wp_cache_delete($id, 'posts');
5615         wp_cache_delete($id, 'post_meta');
5616
5617         if ( $clean_terms )
5618                 clean_object_term_cache($id, 'attachment');
5619
5620         /**
5621          * Fires after the given attachment's cache is cleaned.
5622          *
5623          * @since 3.0.0
5624          *
5625          * @param int $id Attachment ID.
5626          */
5627         do_action( 'clean_attachment_cache', $id );
5628 }
5629
5630 //
5631 // Hooks
5632 //
5633
5634 /**
5635  * Hook for managing future post transitions to published.
5636  *
5637  * @since 2.3.0
5638  * @access private
5639  *
5640  * @see wp_clear_scheduled_hook()
5641  * @global wpdb $wpdb WordPress database abstraction object.
5642  *
5643  * @param string  $new_status New post status.
5644  * @param string  $old_status Previous post status.
5645  * @param WP_Post $post       Post object.
5646  */
5647 function _transition_post_status( $new_status, $old_status, $post ) {
5648         global $wpdb;
5649
5650         if ( $old_status != 'publish' && $new_status == 'publish' ) {
5651                 // Reset GUID if transitioning to publish and it is empty.
5652                 if ( '' == get_the_guid($post->ID) )
5653                         $wpdb->update( $wpdb->posts, array( 'guid' => get_permalink( $post->ID ) ), array( 'ID' => $post->ID ) );
5654
5655                 /**
5656                  * Fires when a post's status is transitioned from private to published.
5657                  *
5658                  * @since 1.5.0
5659                  * @deprecated 2.3.0 Use 'private_to_publish' instead.
5660                  *
5661                  * @param int $post_id Post ID.
5662                  */
5663                 do_action('private_to_published', $post->ID);
5664         }
5665
5666         // If published posts changed clear the lastpostmodified cache.
5667         if ( 'publish' == $new_status || 'publish' == $old_status) {
5668                 foreach ( array( 'server', 'gmt', 'blog' ) as $timezone ) {
5669                         wp_cache_delete( "lastpostmodified:$timezone", 'timeinfo' );
5670                         wp_cache_delete( "lastpostdate:$timezone", 'timeinfo' );
5671                         wp_cache_delete( "lastpostdate:$timezone:{$post->post_type}", 'timeinfo' );
5672                 }
5673         }
5674
5675         if ( $new_status !== $old_status ) {
5676                 wp_cache_delete( _count_posts_cache_key( $post->post_type ), 'counts' );
5677                 wp_cache_delete( _count_posts_cache_key( $post->post_type, 'readable' ), 'counts' );
5678         }
5679
5680         // Always clears the hook in case the post status bounced from future to draft.
5681         wp_clear_scheduled_hook('publish_future_post', array( $post->ID ) );
5682 }
5683
5684 /**
5685  * Hook used to schedule publication for a post marked for the future.
5686  *
5687  * The $post properties used and must exist are 'ID' and 'post_date_gmt'.
5688  *
5689  * @since 2.3.0
5690  * @access private
5691  *
5692  * @param int     $deprecated Not used. Can be set to null. Never implemented. Not marked
5693  *                            as deprecated with _deprecated_argument() as it conflicts with
5694  *                            wp_transition_post_status() and the default filter for
5695  *                            {@see _future_post_hook()}.
5696  * @param WP_Post $post       Post object.
5697  */
5698 function _future_post_hook( $deprecated, $post ) {
5699         wp_clear_scheduled_hook( 'publish_future_post', array( $post->ID ) );
5700         wp_schedule_single_event( strtotime( get_gmt_from_date( $post->post_date ) . ' GMT') , 'publish_future_post', array( $post->ID ) );
5701 }
5702
5703 /**
5704  * Hook to schedule pings and enclosures when a post is published.
5705  *
5706  * Uses XMLRPC_REQUEST and WP_IMPORTING constants.
5707  *
5708  * @since 2.3.0
5709  * @access private
5710  *
5711  * @param int $post_id The ID in the database table of the post being published.
5712  */
5713 function _publish_post_hook( $post_id ) {
5714         if ( defined( 'XMLRPC_REQUEST' ) ) {
5715                 /**
5716                  * Fires when _publish_post_hook() is called during an XML-RPC request.
5717                  *
5718                  * @since 2.1.0
5719                  *
5720                  * @param int $post_id Post ID.
5721                  */
5722                 do_action( 'xmlrpc_publish_post', $post_id );
5723         }
5724
5725         if ( defined('WP_IMPORTING') )
5726                 return;
5727
5728         if ( get_option('default_pingback_flag') )
5729                 add_post_meta( $post_id, '_pingme', '1' );
5730         add_post_meta( $post_id, '_encloseme', '1' );
5731
5732         wp_schedule_single_event(time(), 'do_pings');
5733 }
5734
5735 /**
5736  * Return the post's parent's post_ID
5737  *
5738  * @since 3.1.0
5739  *
5740  * @param int $post_ID
5741  *
5742  * @return int|false Post parent ID, otherwise false.
5743  */
5744 function wp_get_post_parent_id( $post_ID ) {
5745         $post = get_post( $post_ID );
5746         if ( !$post || is_wp_error( $post ) )
5747                 return false;
5748         return (int) $post->post_parent;
5749 }
5750
5751 /**
5752  * Check the given subset of the post hierarchy for hierarchy loops.
5753  *
5754  * Prevents loops from forming and breaks those that it finds. Attached
5755  * to the 'wp_insert_post_parent' filter.
5756  *
5757  * @since 3.1.0
5758  *
5759  * @see wp_find_hierarchy_loop()
5760  *
5761  * @param int $post_parent ID of the parent for the post we're checking.
5762  * @param int $post_ID     ID of the post we're checking.
5763  * @return int The new post_parent for the post, 0 otherwise.
5764  */
5765 function wp_check_post_hierarchy_for_loops( $post_parent, $post_ID ) {
5766         // Nothing fancy here - bail.
5767         if ( !$post_parent )
5768                 return 0;
5769
5770         // New post can't cause a loop.
5771         if ( empty( $post_ID ) )
5772                 return $post_parent;
5773
5774         // Can't be its own parent.
5775         if ( $post_parent == $post_ID )
5776                 return 0;
5777
5778         // Now look for larger loops.
5779         if ( !$loop = wp_find_hierarchy_loop( 'wp_get_post_parent_id', $post_ID, $post_parent ) )
5780                 return $post_parent; // No loop
5781
5782         // Setting $post_parent to the given value causes a loop.
5783         if ( isset( $loop[$post_ID] ) )
5784                 return 0;
5785
5786         // There's a loop, but it doesn't contain $post_ID. Break the loop.
5787         foreach ( array_keys( $loop ) as $loop_member )
5788                 wp_update_post( array( 'ID' => $loop_member, 'post_parent' => 0 ) );
5789
5790         return $post_parent;
5791 }
5792
5793 /**
5794  * Set a post thumbnail.
5795  *
5796  * @since 3.1.0
5797  *
5798  * @param int|WP_Post $post         Post ID or post object where thumbnail should be attached.
5799  * @param int         $thumbnail_id Thumbnail to attach.
5800  * @return int|bool True on success, false on failure.
5801  */
5802 function set_post_thumbnail( $post, $thumbnail_id ) {
5803         $post = get_post( $post );
5804         $thumbnail_id = absint( $thumbnail_id );
5805         if ( $post && $thumbnail_id && get_post( $thumbnail_id ) ) {
5806                 if ( wp_get_attachment_image( $thumbnail_id, 'thumbnail' ) )
5807                         return update_post_meta( $post->ID, '_thumbnail_id', $thumbnail_id );
5808                 else
5809                         return delete_post_meta( $post->ID, '_thumbnail_id' );
5810         }
5811         return false;
5812 }
5813
5814 /**
5815  * Remove a post thumbnail.
5816  *
5817  * @since 3.3.0
5818  *
5819  * @param int|WP_Post $post Post ID or post object where thumbnail should be removed from.
5820  * @return bool True on success, false on failure.
5821  */
5822 function delete_post_thumbnail( $post ) {
5823         $post = get_post( $post );
5824         if ( $post )
5825                 return delete_post_meta( $post->ID, '_thumbnail_id' );
5826         return false;
5827 }
5828
5829 /**
5830  * Delete auto-drafts for new posts that are > 7 days old.
5831  *
5832  * @since 3.4.0
5833  *
5834  * @global wpdb $wpdb WordPress database abstraction object.
5835  */
5836 function wp_delete_auto_drafts() {
5837         global $wpdb;
5838
5839         // Cleanup old auto-drafts more than 7 days old.
5840         $old_posts = $wpdb->get_col( "SELECT ID FROM $wpdb->posts WHERE post_status = 'auto-draft' AND DATE_SUB( NOW(), INTERVAL 7 DAY ) > post_date" );
5841         foreach ( (array) $old_posts as $delete ) {
5842                 // Force delete.
5843                 wp_delete_post( $delete, true );
5844         }
5845 }
5846
5847 /**
5848  * Update the custom taxonomies' term counts when a post's status is changed.
5849  *
5850  * For example, default posts term counts (for custom taxonomies) don't include
5851  * private / draft posts.
5852  *
5853  * @since 3.3.0
5854  * @access private
5855  *
5856  * @param string  $new_status New post status.
5857  * @param string  $old_status Old post status.
5858  * @param WP_Post $post       Post object.
5859  */
5860 function _update_term_count_on_transition_post_status( $new_status, $old_status, $post ) {
5861         // Update counts for the post's terms.
5862         foreach ( (array) get_object_taxonomies( $post->post_type ) as $taxonomy ) {
5863                 $tt_ids = wp_get_object_terms( $post->ID, $taxonomy, array( 'fields' => 'tt_ids' ) );
5864                 wp_update_term_count( $tt_ids, $taxonomy );
5865         }
5866 }
5867
5868 /**
5869  * Adds any posts from the given ids to the cache that do not already exist in cache
5870  *
5871  * @since 3.4.0
5872  * @access private
5873  *
5874  * @see update_post_caches()
5875  *
5876  * @global wpdb $wpdb WordPress database abstraction object.
5877  *
5878  * @param array $ids               ID list.
5879  * @param bool  $update_term_cache Optional. Whether to update the term cache. Default true.
5880  * @param bool  $update_meta_cache Optional. Whether to update the meta cache. Default true.
5881  */
5882 function _prime_post_caches( $ids, $update_term_cache = true, $update_meta_cache = true ) {
5883         global $wpdb;
5884
5885         $non_cached_ids = _get_non_cached_ids( $ids, 'posts' );
5886         if ( !empty( $non_cached_ids ) ) {
5887                 $fresh_posts = $wpdb->get_results( sprintf( "SELECT $wpdb->posts.* FROM $wpdb->posts WHERE ID IN (%s)", join( ",", $non_cached_ids ) ) );
5888
5889                 update_post_caches( $fresh_posts, 'any', $update_term_cache, $update_meta_cache );
5890         }
5891 }