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