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