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