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