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