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