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