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