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