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