]> scripts.mit.edu Git - autoinstalls/wordpress.git/blob - wp-includes/post.php
Wordpress 2.8.2
[autoinstalls/wordpress.git] / wp-includes / post.php
1 <?php
2 /**
3  * Post functions and post utility function.
4  *
5  * @package WordPress
6  * @subpackage Post
7  * @since 1.5.0
8  */
9
10 /**
11  * Retrieve attached file path based on attachment ID.
12  *
13  * You can optionally send it through the 'get_attached_file' filter, but by
14  * default it will just return the file path unfiltered.
15  *
16  * The function works by getting the single post meta name, named
17  * '_wp_attached_file' and returning it. This is a convenience function to
18  * prevent looking up the meta name and provide a mechanism for sending the
19  * attached filename through a filter.
20  *
21  * @since 2.0.0
22  * @uses apply_filters() Calls 'get_attached_file' on file path and attachment ID.
23  *
24  * @param int $attachment_id Attachment ID.
25  * @param bool $unfiltered Whether to apply filters or not.
26  * @return string The file path to the attached file.
27  */
28 function get_attached_file( $attachment_id, $unfiltered = false ) {
29         $file = get_post_meta( $attachment_id, '_wp_attached_file', true );
30         // If the file is relative, prepend upload dir
31         if ( 0 !== strpos($file, '/') && !preg_match('|^.:\\\|', $file) && ( ($uploads = wp_upload_dir()) && false === $uploads['error'] ) )
32                 $file = $uploads['basedir'] . "/$file";
33         if ( $unfiltered )
34                 return $file;
35         return apply_filters( 'get_attached_file', $file, $attachment_id );
36 }
37
38 /**
39  * Update attachment file path based on attachment ID.
40  *
41  * Used to update the file path of the attachment, which uses post meta name
42  * '_wp_attached_file' to store the path of the attachment.
43  *
44  * @since 2.1.0
45  * @uses apply_filters() Calls 'update_attached_file' on file path and attachment ID.
46  *
47  * @param int $attachment_id Attachment ID
48  * @param string $file File path for the attachment
49  * @return bool False on failure, true on success.
50  */
51 function update_attached_file( $attachment_id, $file ) {
52         if ( !get_post( $attachment_id ) )
53                 return false;
54
55         $file = apply_filters( 'update_attached_file', $file, $attachment_id );
56
57         // Make the file path relative to the upload dir
58         if ( ($uploads = wp_upload_dir()) && false === $uploads['error'] ) { // Get upload directory
59                 if ( 0 === strpos($file, $uploads['basedir']) ) {// Check that the upload base exists in the file path
60                                 $file = str_replace($uploads['basedir'], '', $file); // Remove upload dir from the file path
61                                 $file = ltrim($file, '/');
62                 }
63         }
64
65         return update_post_meta( $attachment_id, '_wp_attached_file', $file );
66 }
67
68 /**
69  * Retrieve all children of the post parent ID.
70  *
71  * Normally, without any enhancements, the children would apply to pages. In the
72  * context of the inner workings of WordPress, pages, posts, and attachments
73  * share the same table, so therefore the functionality could apply to any one
74  * of them. It is then noted that while this function does not work on posts, it
75  * does not mean that it won't work on posts. It is recommended that you know
76  * what context you wish to retrieve the children of.
77  *
78  * Attachments may also be made the child of a post, so if that is an accurate
79  * statement (which needs to be verified), it would then be possible to get
80  * all of the attachments for a post. Attachments have since changed since
81  * version 2.5, so this is most likely unaccurate, but serves generally as an
82  * example of what is possible.
83  *
84  * The arguments listed as defaults are for this function and also of the
85  * {@link get_posts()} function. The arguments are combined with the
86  * get_children defaults and are then passed to the {@link get_posts()}
87  * function, which accepts additional arguments. You can replace the defaults in
88  * this function, listed below and the additional arguments listed in the
89  * {@link get_posts()} function.
90  *
91  * The 'post_parent' is the most important argument and important attention
92  * needs to be paid to the $args parameter. If you pass either an object or an
93  * integer (number), then just the 'post_parent' is grabbed and everything else
94  * is lost. If you don't specify any arguments, then it is assumed that you are
95  * in The Loop and the post parent will be grabbed for from the current post.
96  *
97  * The 'post_parent' argument is the ID to get the children. The 'numberposts'
98  * is the amount of posts to retrieve that has a default of '-1', which is
99  * used to get all of the posts. Giving a number higher than 0 will only
100  * retrieve that amount of posts.
101  *
102  * The 'post_type' and 'post_status' arguments can be used to choose what
103  * criteria of posts to retrieve. The 'post_type' can be anything, but WordPress
104  * post types are 'post', 'pages', and 'attachments'. The 'post_status'
105  * argument will accept any post status within the write administration panels.
106  *
107  * @see get_posts() Has additional arguments that can be replaced.
108  * @internal Claims made in the long description might be inaccurate.
109  *
110  * @since 2.0.0
111  *
112  * @param mixed $args Optional. User defined arguments for replacing the defaults.
113  * @param string $output Optional. Constant for return type, either OBJECT (default), ARRAY_A, ARRAY_N.
114  * @return array|bool False on failure and the type will be determined by $output parameter.
115  */
116 function &get_children($args = '', $output = OBJECT) {
117         if ( empty( $args ) ) {
118                 if ( isset( $GLOBALS['post'] ) ) {
119                         $args = array('post_parent' => (int) $GLOBALS['post']->post_parent );
120                 } else {
121                         return false;
122                 }
123         } elseif ( is_object( $args ) ) {
124                 $args = array('post_parent' => (int) $args->post_parent );
125         } elseif ( is_numeric( $args ) ) {
126                 $args = array('post_parent' => (int) $args);
127         }
128
129         $defaults = array(
130                 'numberposts' => -1, 'post_type' => 'any',
131                 'post_status' => 'any', 'post_parent' => 0,
132         );
133
134         $r = wp_parse_args( $args, $defaults );
135
136         $children = get_posts( $r );
137         if ( !$children ) {
138                 $kids = false;
139                 return $kids;
140         }
141
142         update_post_cache($children);
143
144         foreach ( $children as $key => $child )
145                 $kids[$child->ID] =& $children[$key];
146
147         if ( $output == OBJECT ) {
148                 return $kids;
149         } elseif ( $output == ARRAY_A ) {
150                 foreach ( (array) $kids as $kid )
151                         $weeuns[$kid->ID] = get_object_vars($kids[$kid->ID]);
152                 return $weeuns;
153         } elseif ( $output == ARRAY_N ) {
154                 foreach ( (array) $kids as $kid )
155                         $babes[$kid->ID] = array_values(get_object_vars($kids[$kid->ID]));
156                 return $babes;
157         } else {
158                 return $kids;
159         }
160 }
161
162 /**
163  * Get extended entry info (<!--more-->).
164  *
165  * There should not be any space after the second dash and before the word
166  * 'more'. There can be text or space(s) after the word 'more', but won't be
167  * referenced.
168  *
169  * The returned array has 'main' and 'extended' keys. Main has the text before
170  * the <code><!--more--></code>. The 'extended' key has the content after the
171  * <code><!--more--></code> comment.
172  *
173  * @since 1.0.0
174  *
175  * @param string $post Post content.
176  * @return array Post before ('main') and after ('extended').
177  */
178 function get_extended($post) {
179         //Match the new style more links
180         if ( preg_match('/<!--more(.*?)?-->/', $post, $matches) ) {
181                 list($main, $extended) = explode($matches[0], $post, 2);
182         } else {
183                 $main = $post;
184                 $extended = '';
185         }
186
187         // Strip leading and trailing whitespace
188         $main = preg_replace('/^[\s]*(.*)[\s]*$/', '\\1', $main);
189         $extended = preg_replace('/^[\s]*(.*)[\s]*$/', '\\1', $extended);
190
191         return array('main' => $main, 'extended' => $extended);
192 }
193
194 /**
195  * Retrieves post data given a post ID or post object.
196  *
197  * See {@link sanitize_post()} for optional $filter values. Also, the parameter
198  * $post, must be given as a variable, since it is passed by reference.
199  *
200  * @since 1.5.1
201  * @uses $wpdb
202  * @link http://codex.wordpress.org/Function_Reference/get_post
203  *
204  * @param int|object $post Post ID or post object.
205  * @param string $output Optional, default is Object. Either OBJECT, ARRAY_A, or ARRAY_N.
206  * @param string $filter Optional, default is raw.
207  * @return mixed Post data
208  */
209 function &get_post(&$post, $output = OBJECT, $filter = 'raw') {
210         global $wpdb;
211         $null = null;
212
213         if ( empty($post) ) {
214                 if ( isset($GLOBALS['post']) )
215                         $_post = & $GLOBALS['post'];
216                 else
217                         return $null;
218         } elseif ( is_object($post) && empty($post->filter) ) {
219                 _get_post_ancestors($post);
220                 wp_cache_add($post->ID, $post, 'posts');
221                 $_post = &$post;
222         } else {
223                 if ( is_object($post) )
224                         $post = $post->ID;
225                 $post = (int) $post;
226                 if ( ! $_post = wp_cache_get($post, 'posts') ) {
227                         $_post = $wpdb->get_row($wpdb->prepare("SELECT * FROM $wpdb->posts WHERE ID = %d LIMIT 1", $post));
228                         if ( ! $_post )
229                                 return $null;
230                         _get_post_ancestors($_post);
231                         wp_cache_add($_post->ID, $_post, 'posts');
232                 }
233         }
234
235         $_post = sanitize_post($_post, $filter);
236
237         if ( $output == OBJECT ) {
238                 return $_post;
239         } elseif ( $output == ARRAY_A ) {
240                 $__post = get_object_vars($_post);
241                 return $__post;
242         } elseif ( $output == ARRAY_N ) {
243                 $__post = array_values(get_object_vars($_post));
244                 return $__post;
245         } else {
246                 return $_post;
247         }
248 }
249
250 /**
251  * Retrieve ancestors of a post.
252  *
253  * @since 2.5.0
254  *
255  * @param int|object $post Post ID or post object
256  * @return array Ancestor IDs or empty array if none are found.
257  */
258 function get_post_ancestors($post) {
259         $post = get_post($post);
260
261         if ( !empty($post->ancestors) )
262                 return $post->ancestors;
263
264         return array();
265 }
266
267 /**
268  * Retrieve data from a post field based on Post ID.
269  *
270  * Examples of the post field will be, 'post_type', 'post_status', 'content',
271  * etc and based off of the post object property or key names.
272  *
273  * The context values are based off of the taxonomy filter functions and
274  * supported values are found within those functions.
275  *
276  * @since 2.3.0
277  * @uses sanitize_post_field() See for possible $context values.
278  *
279  * @param string $field Post field name
280  * @param id $post Post ID
281  * @param string $context Optional. How to filter the field. Default is display.
282  * @return WP_Error|string Value in post field or WP_Error on failure
283  */
284 function get_post_field( $field, $post, $context = 'display' ) {
285         $post = (int) $post;
286         $post = get_post( $post );
287
288         if ( is_wp_error($post) )
289                 return $post;
290
291         if ( !is_object($post) )
292                 return '';
293
294         if ( !isset($post->$field) )
295                 return '';
296
297         return sanitize_post_field($field, $post->$field, $post->ID, $context);
298 }
299
300 /**
301  * Retrieve the mime type of an attachment based on the ID.
302  *
303  * This function can be used with any post type, but it makes more sense with
304  * attachments.
305  *
306  * @since 2.0.0
307  *
308  * @param int $ID Optional. Post ID.
309  * @return bool|string False on failure or returns the mime type
310  */
311 function get_post_mime_type($ID = '') {
312         $post = & get_post($ID);
313
314         if ( is_object($post) )
315                 return $post->post_mime_type;
316
317         return false;
318 }
319
320 /**
321  * Retrieve the post status based on the Post ID.
322  *
323  * If the post ID is of an attachment, then the parent post status will be given
324  * instead.
325  *
326  * @since 2.0.0
327  *
328  * @param int $ID Post ID
329  * @return string|bool Post status or false on failure.
330  */
331 function get_post_status($ID = '') {
332         $post = get_post($ID);
333
334         if ( is_object($post) ) {
335                 if ( ('attachment' == $post->post_type) && $post->post_parent && ($post->ID != $post->post_parent) )
336                         return get_post_status($post->post_parent);
337                 else
338                         return $post->post_status;
339         }
340
341         return false;
342 }
343
344 /**
345  * Retrieve all of the WordPress supported post statuses.
346  *
347  * Posts have a limited set of valid status values, this provides the
348  * post_status values and descriptions.
349  *
350  * @since 2.5.0
351  *
352  * @return array List of post statuses.
353  */
354 function get_post_statuses( ) {
355         $status = array(
356                 'draft'                 => __('Draft'),
357                 'pending'               => __('Pending Review'),
358                 'private'               => __('Private'),
359                 'publish'               => __('Published')
360         );
361
362         return $status;
363 }
364
365 /**
366  * Retrieve all of the WordPress support page statuses.
367  *
368  * Pages have a limited set of valid status values, this provides the
369  * post_status values and descriptions.
370  *
371  * @since 2.5.0
372  *
373  * @return array List of page statuses.
374  */
375 function get_page_statuses( ) {
376         $status = array(
377                 'draft'                 => __('Draft'),
378                 'private'               => __('Private'),
379                 'publish'               => __('Published')
380         );
381
382         return $status;
383 }
384
385 /**
386  * Retrieve the post type of the current post or of a given post.
387  *
388  * @since 2.1.0
389  *
390  * @uses $wpdb
391  * @uses $posts The Loop post global
392  *
393  * @param mixed $post Optional. Post object or post ID.
394  * @return bool|string post type or false on failure.
395  */
396 function get_post_type($post = false) {
397         global $posts;
398
399         if ( false === $post )
400                 $post = $posts[0];
401         elseif ( (int) $post )
402                 $post = get_post($post, OBJECT);
403
404         if ( is_object($post) )
405                 return $post->post_type;
406
407         return false;
408 }
409
410 /**
411  * Updates the post type for the post ID.
412  *
413  * The page or post cache will be cleaned for the post ID.
414  *
415  * @since 2.5.0
416  *
417  * @uses $wpdb
418  *
419  * @param int $post_id Post ID to change post type. Not actually optional.
420  * @param string $post_type Optional, default is post. Supported values are 'post' or 'page' to
421  *  name a few.
422  * @return int Amount of rows changed. Should be 1 for success and 0 for failure.
423  */
424 function set_post_type( $post_id = 0, $post_type = 'post' ) {
425         global $wpdb;
426
427         $post_type = sanitize_post_field('post_type', $post_type, $post_id, 'db');
428         $return = $wpdb->update($wpdb->posts, array('post_type' => $post_type), array('ID' => $post_id) );
429
430         if ( 'page' == $post_type )
431                 clean_page_cache($post_id);
432         else
433                 clean_post_cache($post_id);
434
435         return $return;
436 }
437
438 /**
439  * Retrieve list of latest posts or posts matching criteria.
440  *
441  * The defaults are as follows:
442  *     'numberposts' - Default is 5. Total number of posts to retrieve.
443  *     'offset' - Default is 0. See {@link WP_Query::query()} for more.
444  *     'category' - What category to pull the posts from.
445  *     'orderby' - Default is 'post_date'. How to order the posts.
446  *     'order' - Default is 'DESC'. The order to retrieve the posts.
447  *     'include' - See {@link WP_Query::query()} for more.
448  *     'exclude' - See {@link WP_Query::query()} for more.
449  *     'meta_key' - See {@link WP_Query::query()} for more.
450  *     'meta_value' - See {@link WP_Query::query()} for more.
451  *     'post_type' - Default is 'post'. Can be 'page', or 'attachment' to name a few.
452  *     'post_parent' - The parent of the post or post type.
453  *     'post_status' - Default is 'published'. Post status to retrieve.
454  *
455  * @since 1.2.0
456  * @uses $wpdb
457  * @uses WP_Query::query() See for more default arguments and information.
458  * @link http://codex.wordpress.org/Template_Tags/get_posts
459  *
460  * @param array $args Optional. Overrides defaults.
461  * @return array List of posts.
462  */
463 function get_posts($args = null) {
464         $defaults = array(
465                 'numberposts' => 5, 'offset' => 0,
466                 'category' => 0, 'orderby' => 'post_date',
467                 'order' => 'DESC', 'include' => '',
468                 'exclude' => '', 'meta_key' => '',
469                 'meta_value' =>'', 'post_type' => 'post',
470                 'suppress_filters' => true
471         );
472
473         $r = wp_parse_args( $args, $defaults );
474         if ( empty( $r['post_status'] ) )
475                 $r['post_status'] = ( 'attachment' == $r['post_type'] ) ? 'inherit' : 'publish';
476         if ( ! empty($r['numberposts']) )
477                 $r['posts_per_page'] = $r['numberposts'];
478         if ( ! empty($r['category']) )
479                 $r['cat'] = $r['category'];
480         if ( ! empty($r['include']) ) {
481                 $incposts = preg_split('/[\s,]+/',$r['include']);
482                 $r['posts_per_page'] = count($incposts);  // only the number of posts included
483                 $r['post__in'] = $incposts;
484         } elseif ( ! empty($r['exclude']) )
485                 $r['post__not_in'] = preg_split('/[\s,]+/',$r['exclude']);
486
487         $r['caller_get_posts'] = true;
488
489         $get_posts = new WP_Query;
490         return $get_posts->query($r);
491
492 }
493
494 //
495 // Post meta functions
496 //
497
498 /**
499  * Add meta data field to a post.
500  *
501  * Post meta data is called "Custom Fields" on the Administration Panels.
502  *
503  * @since 1.5.0
504  * @uses $wpdb
505  * @link http://codex.wordpress.org/Function_Reference/add_post_meta
506  *
507  * @param int $post_id Post ID.
508  * @param string $key Metadata name.
509  * @param mixed $value Metadata value.
510  * @param bool $unique Optional, default is false. Whether the same key should not be added.
511  * @return bool False for failure. True for success.
512  */
513 function add_post_meta($post_id, $meta_key, $meta_value, $unique = false) {
514         if ( !$meta_key )
515                 return false;
516
517         global $wpdb;
518
519         // make sure meta is added to the post, not a revision
520         if ( $the_post = wp_is_post_revision($post_id) )
521                 $post_id = $the_post;
522
523         // expected_slashed ($meta_key)
524         $meta_key = stripslashes($meta_key);
525
526         if ( $unique && $wpdb->get_var( $wpdb->prepare( "SELECT meta_key FROM $wpdb->postmeta WHERE meta_key = %s AND post_id = %d", $meta_key, $post_id ) ) )
527                 return false;
528
529         $meta_value = maybe_serialize( stripslashes_deep($meta_value) );
530
531         $wpdb->insert( $wpdb->postmeta, compact( 'post_id', 'meta_key', 'meta_value' ) );
532
533         wp_cache_delete($post_id, 'post_meta');
534
535         return true;
536 }
537
538 /**
539  * Remove metadata matching criteria from a post.
540  *
541  * You can match based on the key, or key and value. Removing based on key and
542  * value, will keep from removing duplicate metadata with the same key. It also
543  * allows removing all metadata matching key, if needed.
544  *
545  * @since 1.5.0
546  * @uses $wpdb
547  * @link http://codex.wordpress.org/Function_Reference/delete_post_meta
548  *
549  * @param int $post_id post ID
550  * @param string $meta_key Metadata name.
551  * @param mixed $meta_value Optional. Metadata value.
552  * @return bool False for failure. True for success.
553  */
554 function delete_post_meta($post_id, $meta_key, $meta_value = '') {
555         global $wpdb;
556
557         // make sure meta is added to the post, not a revision
558         if ( $the_post = wp_is_post_revision($post_id) )
559                 $post_id = $the_post;
560
561         // expected_slashed ($meta_key, $meta_value)
562         $meta_key = stripslashes( $meta_key );
563         $meta_value = maybe_serialize( stripslashes_deep($meta_value) );
564
565         if ( !$meta_key )
566                 return false;
567
568         if ( empty( $meta_value ) )
569                 $meta_id = $wpdb->get_var( $wpdb->prepare( "SELECT meta_id FROM $wpdb->postmeta WHERE post_id = %d AND meta_key = %s", $post_id, $meta_key ) );
570         else
571                 $meta_id = $wpdb->get_var( $wpdb->prepare( "SELECT meta_id FROM $wpdb->postmeta WHERE post_id = %d AND meta_key = %s AND meta_value = %s", $post_id, $meta_key, $meta_value ) );
572
573         if ( !$meta_id )
574                 return false;
575
576         if ( empty( $meta_value ) )
577                 $wpdb->query( $wpdb->prepare( "DELETE FROM $wpdb->postmeta WHERE post_id = %d AND meta_key = %s", $post_id, $meta_key ) );
578         else
579                 $wpdb->query( $wpdb->prepare( "DELETE FROM $wpdb->postmeta WHERE post_id = %d AND meta_key = %s AND meta_value = %s", $post_id, $meta_key, $meta_value ) );
580
581         wp_cache_delete($post_id, 'post_meta');
582
583         return true;
584 }
585
586 /**
587  * Retrieve post meta field for a post.
588  *
589  * @since 1.5.0
590  * @uses $wpdb
591  * @link http://codex.wordpress.org/Function_Reference/get_post_meta
592  *
593  * @param int $post_id Post ID.
594  * @param string $key The meta key to retrieve.
595  * @param bool $single Whether to return a single value.
596  * @return mixed Will be an array if $single is false. Will be value of meta data field if $single
597  *  is true.
598  */
599 function get_post_meta($post_id, $key, $single = false) {
600         if ( !$key )
601                 return '';
602
603         $post_id = (int) $post_id;
604
605         $meta_cache = wp_cache_get($post_id, 'post_meta');
606
607         if ( !$meta_cache ) {
608                 update_postmeta_cache($post_id);
609                 $meta_cache = wp_cache_get($post_id, 'post_meta');
610         }
611
612         if ( isset($meta_cache[$key]) ) {
613                 if ( $single ) {
614                         return maybe_unserialize( $meta_cache[$key][0] );
615                 } else {
616                         return array_map('maybe_unserialize', $meta_cache[$key]);
617                 }
618         }
619
620         return '';
621 }
622
623 /**
624  * Update post meta field based on post ID.
625  *
626  * Use the $prev_value parameter to differentiate between meta fields with the
627  * same key and post ID.
628  *
629  * If the meta field for the post does not exist, it will be added.
630  *
631  * @since 1.5
632  * @uses $wpdb
633  * @link http://codex.wordpress.org/Function_Reference/update_post_meta
634  *
635  * @param int $post_id Post ID.
636  * @param string $key Metadata key.
637  * @param mixed $value Metadata value.
638  * @param mixed $prev_value Optional. Previous value to check before removing.
639  * @return bool False on failure, true if success.
640  */
641 function update_post_meta($post_id, $meta_key, $meta_value, $prev_value = '') {
642         global $wpdb;
643
644         // make sure meta is added to the post, not a revision
645         if ( $the_post = wp_is_post_revision($post_id) )
646                 $post_id = $the_post;
647
648         // expected_slashed ($meta_key)
649         $meta_key = stripslashes($meta_key);
650
651         if ( !$meta_key )
652                 return false;
653
654         if ( ! $wpdb->get_var( $wpdb->prepare( "SELECT meta_key FROM $wpdb->postmeta WHERE meta_key = %s AND post_id = %d", $meta_key, $post_id ) ) ) {
655                 return add_post_meta($post_id, $meta_key, $meta_value);
656         }
657
658         $meta_value = maybe_serialize( stripslashes_deep($meta_value) );
659
660         $data  = compact( 'meta_value' );
661         $where = compact( 'meta_key', 'post_id' );
662
663         if ( !empty( $prev_value ) ) {
664                 $prev_value = maybe_serialize($prev_value);
665                 $where['meta_value'] = $prev_value;
666         }
667
668         $wpdb->update( $wpdb->postmeta, $data, $where );
669         wp_cache_delete($post_id, 'post_meta');
670         return true;
671 }
672
673 /**
674  * Delete everything from post meta matching meta key.
675  *
676  * @since 2.3.0
677  * @uses $wpdb
678  *
679  * @param string $post_meta_key Key to search for when deleting.
680  * @return bool Whether the post meta key was deleted from the database
681  */
682 function delete_post_meta_by_key($post_meta_key) {
683         if ( !$post_meta_key )
684                 return false;
685
686         global $wpdb;
687         $post_ids = $wpdb->get_col($wpdb->prepare("SELECT DISTINCT post_id FROM $wpdb->postmeta WHERE meta_key = %s", $post_meta_key));
688         if ( $post_ids ) {
689                 $wpdb->query($wpdb->prepare("DELETE FROM $wpdb->postmeta WHERE meta_key = %s", $post_meta_key));
690                 foreach ( $post_ids as $post_id )
691                         wp_cache_delete($post_id, 'post_meta');
692                 return true;
693         }
694         return false;
695 }
696
697 /**
698  * Retrieve post meta fields, based on post ID.
699  *
700  * The post meta fields are retrieved from the cache, so the function is
701  * optimized to be called more than once. It also applies to the functions, that
702  * use this function.
703  *
704  * @since 1.2.0
705  * @link http://codex.wordpress.org/Function_Reference/get_post_custom
706  *
707  * @uses $id Current Loop Post ID
708  *
709  * @param int $post_id post ID
710  * @return array
711  */
712 function get_post_custom($post_id = 0) {
713         global $id;
714
715         if ( !$post_id )
716                 $post_id = (int) $id;
717
718         $post_id = (int) $post_id;
719
720         if ( ! wp_cache_get($post_id, 'post_meta') )
721                 update_postmeta_cache($post_id);
722
723         return wp_cache_get($post_id, 'post_meta');
724 }
725
726 /**
727  * Retrieve meta field names for a post.
728  *
729  * If there are no meta fields, then nothing (null) will be returned.
730  *
731  * @since 1.2.0
732  * @link http://codex.wordpress.org/Function_Reference/get_post_custom_keys
733  *
734  * @param int $post_id post ID
735  * @return array|null Either array of the keys, or null if keys could not be retrieved.
736  */
737 function get_post_custom_keys( $post_id = 0 ) {
738         $custom = get_post_custom( $post_id );
739
740         if ( !is_array($custom) )
741                 return;
742
743         if ( $keys = array_keys($custom) )
744                 return $keys;
745 }
746
747 /**
748  * Retrieve values for a custom post field.
749  *
750  * The parameters must not be considered optional. All of the post meta fields
751  * will be retrieved and only the meta field key values returned.
752  *
753  * @since 1.2.0
754  * @link http://codex.wordpress.org/Function_Reference/get_post_custom_values
755  *
756  * @param string $key Meta field key.
757  * @param int $post_id Post ID
758  * @return array Meta field values.
759  */
760 function get_post_custom_values( $key = '', $post_id = 0 ) {
761         if ( !$key )
762                 return null;
763
764         $custom = get_post_custom($post_id);
765
766         return isset($custom[$key]) ? $custom[$key] : null;
767 }
768
769 /**
770  * Check if post is sticky.
771  *
772  * Sticky posts should remain at the top of The Loop. If the post ID is not
773  * given, then The Loop ID for the current post will be used.
774  *
775  * @since 2.7.0
776  *
777  * @param int $post_id Optional. Post ID.
778  * @return bool Whether post is sticky (true) or not sticky (false).
779  */
780 function is_sticky($post_id = null) {
781         global $id;
782
783         $post_id = absint($post_id);
784
785         if ( !$post_id )
786                 $post_id = absint($id);
787
788         $stickies = get_option('sticky_posts');
789
790         if ( !is_array($stickies) )
791                 return false;
792
793         if ( in_array($post_id, $stickies) )
794                 return true;
795
796         return false;
797 }
798
799 /**
800  * Sanitize every post field.
801  *
802  * If the context is 'raw', then the post object or array will get minimal santization of the int fields.
803  *
804  * @since 2.3.0
805  * @uses sanitize_post_field() Used to sanitize the fields.
806  *
807  * @param object|array $post The Post Object or Array
808  * @param string $context Optional, default is 'display'. How to sanitize post fields.
809  * @return object|array The now sanitized Post Object or Array (will be the same type as $post)
810  */
811 function sanitize_post($post, $context = 'display') {
812         if ( is_object($post) ) {
813                 if ( !isset($post->ID) )
814                         $post->ID = 0;
815                 foreach ( array_keys(get_object_vars($post)) as $field )
816                         $post->$field = sanitize_post_field($field, $post->$field, $post->ID, $context);
817                 $post->filter = $context;
818         } else {
819                 if ( !isset($post['ID']) )
820                         $post['ID'] = 0;
821                 foreach ( array_keys($post) as $field )
822                         $post[$field] = sanitize_post_field($field, $post[$field], $post['ID'], $context);
823                 $post['filter'] = $context;
824         }
825
826         return $post;
827 }
828
829 /**
830  * Sanitize post field based on context.
831  *
832  * Possible context values are:  'raw', 'edit', 'db', 'display', 'attribute' and 'js'. The
833  * 'display' context is used by default. 'attribute' and 'js' contexts are treated like 'display'
834  * when calling filters.
835  *
836  * @since 2.3.0
837  * @uses apply_filters() Calls 'edit_$field' and '${field_no_prefix}_edit_pre' passing $value and
838  *  $post_id if $context == 'edit' and field name prefix == 'post_'.
839  *
840  * @uses apply_filters() Calls 'edit_post_$field' passing $value and $post_id if $context == 'db'.
841  * @uses apply_filters() Calls 'pre_$field' passing $value if $context == 'db' and field name prefix == 'post_'.
842  * @uses apply_filters() Calls '${field}_pre' passing $value if $context == 'db' and field name prefix != 'post_'.
843  *
844  * @uses apply_filters() Calls '$field' passing $value, $post_id and $context if $context == anything
845  *  other than 'raw', 'edit' and 'db' and field name prefix == 'post_'.
846  * @uses apply_filters() Calls 'post_$field' passing $value if $context == anything other than 'raw',
847  *  'edit' and 'db' and field name prefix != 'post_'.
848  *
849  * @param string $field The Post Object field name.
850  * @param mixed $value The Post Object value.
851  * @param int $post_id Post ID.
852  * @param string $context How to sanitize post fields. Looks for 'raw', 'edit', 'db', 'display',
853  *               'attribute' and 'js'.
854  * @return mixed Sanitized value.
855  */
856 function sanitize_post_field($field, $value, $post_id, $context) {
857         $int_fields = array('ID', 'post_parent', 'menu_order');
858         if ( in_array($field, $int_fields) )
859                 $value = (int) $value;
860
861         if ( 'raw' == $context )
862                 return $value;
863
864         $prefixed = false;
865         if ( false !== strpos($field, 'post_') ) {
866                 $prefixed = true;
867                 $field_no_prefix = str_replace('post_', '', $field);
868         }
869
870         if ( 'edit' == $context ) {
871                 $format_to_edit = array('post_content', 'post_excerpt', 'post_title', 'post_password');
872
873                 if ( $prefixed ) {
874                         $value = apply_filters("edit_$field", $value, $post_id);
875                         // Old school
876                         $value = apply_filters("${field_no_prefix}_edit_pre", $value, $post_id);
877                 } else {
878                         $value = apply_filters("edit_post_$field", $value, $post_id);
879                 }
880
881                 if ( in_array($field, $format_to_edit) ) {
882                         if ( 'post_content' == $field )
883                                 $value = format_to_edit($value, user_can_richedit());
884                         else
885                                 $value = format_to_edit($value);
886                 } else {
887                         $value = esc_attr($value);
888                 }
889         } else if ( 'db' == $context ) {
890                 if ( $prefixed ) {
891                         $value = apply_filters("pre_$field", $value);
892                         $value = apply_filters("${field_no_prefix}_save_pre", $value);
893                 } else {
894                         $value = apply_filters("pre_post_$field", $value);
895                         $value = apply_filters("${field}_pre", $value);
896                 }
897         } else {
898                 // Use display filters by default.
899                 if ( $prefixed )
900                         $value = apply_filters($field, $value, $post_id, $context);
901                 else
902                         $value = apply_filters("post_$field", $value, $post_id, $context);
903         }
904
905         if ( 'attribute' == $context )
906                 $value = esc_attr($value);
907         else if ( 'js' == $context )
908                 $value = esc_js($value);
909
910         return $value;
911 }
912
913 /**
914  * Make a post sticky.
915  *
916  * Sticky posts should be displayed at the top of the front page.
917  *
918  * @since 2.7.0
919  *
920  * @param int $post_id Post ID.
921  */
922 function stick_post($post_id) {
923         $stickies = get_option('sticky_posts');
924
925         if ( !is_array($stickies) )
926                 $stickies = array($post_id);
927
928         if ( ! in_array($post_id, $stickies) )
929                 $stickies[] = $post_id;
930
931         update_option('sticky_posts', $stickies);
932 }
933
934 /**
935  * Unstick a post.
936  *
937  * Sticky posts should be displayed at the top of the front page.
938  *
939  * @since 2.7.0
940  *
941  * @param int $post_id Post ID.
942  */
943 function unstick_post($post_id) {
944         $stickies = get_option('sticky_posts');
945
946         if ( !is_array($stickies) )
947                 return;
948
949         if ( ! in_array($post_id, $stickies) )
950                 return;
951
952         $offset = array_search($post_id, $stickies);
953         if ( false === $offset )
954                 return;
955
956         array_splice($stickies, $offset, 1);
957
958         update_option('sticky_posts', $stickies);
959 }
960
961 /**
962  * Count number of posts of a post type and is user has permissions to view.
963  *
964  * This function provides an efficient method of finding the amount of post's
965  * type a blog has. Another method is to count the amount of items in
966  * get_posts(), but that method has a lot of overhead with doing so. Therefore,
967  * when developing for 2.5+, use this function instead.
968  *
969  * The $perm parameter checks for 'readable' value and if the user can read
970  * private posts, it will display that for the user that is signed in.
971  *
972  * @since 2.5.0
973  * @link http://codex.wordpress.org/Template_Tags/wp_count_posts
974  *
975  * @param string $type Optional. Post type to retrieve count
976  * @param string $perm Optional. 'readable' or empty.
977  * @return object Number of posts for each status
978  */
979 function wp_count_posts( $type = 'post', $perm = '' ) {
980         global $wpdb;
981
982         $user = wp_get_current_user();
983
984         $cache_key = $type;
985
986         $query = "SELECT post_status, COUNT( * ) AS num_posts FROM {$wpdb->posts} WHERE post_type = %s";
987         if ( 'readable' == $perm && is_user_logged_in() ) {
988                 if ( !current_user_can("read_private_{$type}s") ) {
989                         $cache_key .= '_' . $perm . '_' . $user->ID;
990                         $query .= " AND (post_status != 'private' OR ( post_author = '$user->ID' AND post_status = 'private' ))";
991                 }
992         }
993         $query .= ' GROUP BY post_status';
994
995         $count = wp_cache_get($cache_key, 'counts');
996         if ( false !== $count )
997                 return $count;
998
999         $count = $wpdb->get_results( $wpdb->prepare( $query, $type ), ARRAY_A );
1000
1001         $stats = array( 'publish' => 0, 'private' => 0, 'draft' => 0, 'pending' => 0, 'future' => 0 );
1002         foreach( (array) $count as $row_num => $row ) {
1003                 $stats[$row['post_status']] = $row['num_posts'];
1004         }
1005
1006         $stats = (object) $stats;
1007         wp_cache_set($cache_key, $stats, 'counts');
1008
1009         return $stats;
1010 }
1011
1012
1013 /**
1014  * Count number of attachments for the mime type(s).
1015  *
1016  * If you set the optional mime_type parameter, then an array will still be
1017  * returned, but will only have the item you are looking for. It does not give
1018  * you the number of attachments that are children of a post. You can get that
1019  * by counting the number of children that post has.
1020  *
1021  * @since 2.5.0
1022  *
1023  * @param string|array $mime_type Optional. Array or comma-separated list of MIME patterns.
1024  * @return array Number of posts for each mime type.
1025  */
1026 function wp_count_attachments( $mime_type = '' ) {
1027         global $wpdb;
1028
1029         $and = wp_post_mime_type_where( $mime_type );
1030         $count = $wpdb->get_results( "SELECT post_mime_type, COUNT( * ) AS num_posts FROM $wpdb->posts WHERE post_type = 'attachment' $and GROUP BY post_mime_type", ARRAY_A );
1031
1032         $stats = array( );
1033         foreach( (array) $count as $row ) {
1034                 $stats[$row['post_mime_type']] = $row['num_posts'];
1035         }
1036
1037         return (object) $stats;
1038 }
1039
1040 /**
1041  * Check a MIME-Type against a list.
1042  *
1043  * If the wildcard_mime_types parameter is a string, it must be comma separated
1044  * list. If the real_mime_types is a string, it is also comma separated to
1045  * create the list.
1046  *
1047  * @since 2.5.0
1048  *
1049  * @param string|array $wildcard_mime_types e.g. audio/mpeg or image (same as image/*) or
1050  *  flash (same as *flash*).
1051  * @param string|array $real_mime_types post_mime_type values
1052  * @return array array(wildcard=>array(real types))
1053  */
1054 function wp_match_mime_types($wildcard_mime_types, $real_mime_types) {
1055         $matches = array();
1056         if ( is_string($wildcard_mime_types) )
1057                 $wildcard_mime_types = array_map('trim', explode(',', $wildcard_mime_types));
1058         if ( is_string($real_mime_types) )
1059                 $real_mime_types = array_map('trim', explode(',', $real_mime_types));
1060         $wild = '[-._a-z0-9]*';
1061         foreach ( (array) $wildcard_mime_types as $type ) {
1062                 $type = str_replace('*', $wild, $type);
1063                 $patternses[1][$type] = "^$type$";
1064                 if ( false === strpos($type, '/') ) {
1065                         $patternses[2][$type] = "^$type/";
1066                         $patternses[3][$type] = $type;
1067                 }
1068         }
1069         asort($patternses);
1070         foreach ( $patternses as $patterns )
1071                 foreach ( $patterns as $type => $pattern )
1072                         foreach ( (array) $real_mime_types as $real )
1073                                 if ( preg_match("#$pattern#", $real) && ( empty($matches[$type]) || false === array_search($real, $matches[$type]) ) )
1074                                         $matches[$type][] = $real;
1075         return $matches;
1076 }
1077
1078 /**
1079  * Convert MIME types into SQL.
1080  *
1081  * @since 2.5.0
1082  *
1083  * @param string|array $mime_types List of mime types or comma separated string of mime types.
1084  * @return string The SQL AND clause for mime searching.
1085  */
1086 function wp_post_mime_type_where($post_mime_types) {
1087         $where = '';
1088         $wildcards = array('', '%', '%/%');
1089         if ( is_string($post_mime_types) )
1090                 $post_mime_types = array_map('trim', explode(',', $post_mime_types));
1091         foreach ( (array) $post_mime_types as $mime_type ) {
1092                 $mime_type = preg_replace('/\s/', '', $mime_type);
1093                 $slashpos = strpos($mime_type, '/');
1094                 if ( false !== $slashpos ) {
1095                         $mime_group = preg_replace('/[^-*.a-zA-Z0-9]/', '', substr($mime_type, 0, $slashpos));
1096                         $mime_subgroup = preg_replace('/[^-*.+a-zA-Z0-9]/', '', substr($mime_type, $slashpos + 1));
1097                         if ( empty($mime_subgroup) )
1098                                 $mime_subgroup = '*';
1099                         else
1100                                 $mime_subgroup = str_replace('/', '', $mime_subgroup);
1101                         $mime_pattern = "$mime_group/$mime_subgroup";
1102                 } else {
1103                         $mime_pattern = preg_replace('/[^-*.a-zA-Z0-9]/', '', $mime_type);
1104                         if ( false === strpos($mime_pattern, '*') )
1105                                 $mime_pattern .= '/*';
1106                 }
1107
1108                 $mime_pattern = preg_replace('/\*+/', '%', $mime_pattern);
1109
1110                 if ( in_array( $mime_type, $wildcards ) )
1111                         return '';
1112
1113                 if ( false !== strpos($mime_pattern, '%') )
1114                         $wheres[] = "post_mime_type LIKE '$mime_pattern'";
1115                 else
1116                         $wheres[] = "post_mime_type = '$mime_pattern'";
1117         }
1118         if ( !empty($wheres) )
1119                 $where = ' AND (' . join(' OR ', $wheres) . ') ';
1120         return $where;
1121 }
1122
1123 /**
1124  * Removes a post, attachment, or page.
1125  *
1126  * When the post and page goes, everything that is tied to it is deleted also.
1127  * This includes comments, post meta fields, and terms associated with the post.
1128  *
1129  * @since 1.0.0
1130  * @uses do_action() on 'delete_post' before deletion unless post type is 'attachment'.
1131  * @uses do_action() on 'deleted_post' after deletion unless post type is 'attachment'.
1132  * @uses wp_delete_attachment() if post type is 'attachment'.
1133  *
1134  * @param int $postid Post ID.
1135  * @return mixed False on failure
1136  */
1137 function wp_delete_post($postid = 0) {
1138         global $wpdb, $wp_rewrite;
1139
1140         if ( !$post = $wpdb->get_row($wpdb->prepare("SELECT * FROM $wpdb->posts WHERE ID = %d", $postid)) )
1141                 return $post;
1142
1143         if ( 'attachment' == $post->post_type )
1144                 return wp_delete_attachment($postid);
1145
1146         do_action('delete_post', $postid);
1147
1148         /** @todo delete for pluggable post taxonomies too */
1149         wp_delete_object_term_relationships($postid, array('category', 'post_tag'));
1150
1151         $parent_data = array( 'post_parent' => $post->post_parent );
1152         $parent_where = array( 'post_parent' => $postid );
1153
1154         if ( 'page' == $post->post_type) {
1155                 // if the page is defined in option page_on_front or post_for_posts,
1156                 // adjust the corresponding options
1157                 if ( get_option('page_on_front') == $postid ) {
1158                         update_option('show_on_front', 'posts');
1159                         delete_option('page_on_front');
1160                 }
1161                 if ( get_option('page_for_posts') == $postid ) {
1162                         delete_option('page_for_posts');
1163                 }
1164
1165                 // Point children of this page to its parent, also clean the cache of affected children
1166                 $children_query = $wpdb->prepare("SELECT * FROM $wpdb->posts WHERE post_parent = %d AND post_type='page'", $postid);
1167                 $children = $wpdb->get_results($children_query);
1168
1169                 $wpdb->update( $wpdb->posts, $parent_data, $parent_where + array( 'post_type' => 'page' ) );
1170         } else {
1171                 unstick_post($postid);
1172         }
1173
1174         // Do raw query.  wp_get_post_revisions() is filtered
1175         $revision_ids = $wpdb->get_col( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_parent = %d AND post_type = 'revision'", $postid ) );
1176         // Use wp_delete_post (via wp_delete_post_revision) again.  Ensures any meta/misplaced data gets cleaned up.
1177         foreach ( $revision_ids as $revision_id )
1178                 wp_delete_post_revision( $revision_id );
1179
1180         // Point all attachments to this post up one level
1181         $wpdb->update( $wpdb->posts, $parent_data, $parent_where + array( 'post_type' => 'attachment' ) );
1182
1183         $wpdb->query( $wpdb->prepare( "DELETE FROM $wpdb->comments WHERE comment_post_ID = %d", $postid ));
1184
1185         $wpdb->query( $wpdb->prepare( "DELETE FROM $wpdb->postmeta WHERE post_id = %d", $postid ));
1186
1187         $wpdb->query( $wpdb->prepare( "DELETE FROM $wpdb->posts WHERE ID = %d", $postid ));
1188
1189         if ( 'page' == $post->post_type ) {
1190                 clean_page_cache($postid);
1191
1192                 foreach ( (array) $children as $child )
1193                         clean_page_cache($child->ID);
1194
1195                 $wp_rewrite->flush_rules(false);
1196         } else {
1197                 clean_post_cache($postid);
1198         }
1199
1200         wp_clear_scheduled_hook('publish_future_post', $postid);
1201
1202         do_action('deleted_post', $postid);
1203
1204         return $post;
1205 }
1206
1207 /**
1208  * Retrieve the list of categories for a post.
1209  *
1210  * Compatibility layer for themes and plugins. Also an easy layer of abstraction
1211  * away from the complexity of the taxonomy layer.
1212  *
1213  * @since 2.1.0
1214  *
1215  * @uses wp_get_object_terms() Retrieves the categories. Args details can be found here.
1216  *
1217  * @param int $post_id Optional. The Post ID.
1218  * @param array $args Optional. Overwrite the defaults.
1219  * @return array
1220  */
1221 function wp_get_post_categories( $post_id = 0, $args = array() ) {
1222         $post_id = (int) $post_id;
1223
1224         $defaults = array('fields' => 'ids');
1225         $args = wp_parse_args( $args, $defaults );
1226
1227         $cats = wp_get_object_terms($post_id, 'category', $args);
1228         return $cats;
1229 }
1230
1231 /**
1232  * Retrieve the tags for a post.
1233  *
1234  * There is only one default for this function, called 'fields' and by default
1235  * is set to 'all'. There are other defaults that can be overridden in
1236  * {@link wp_get_object_terms()}.
1237  *
1238  * @package WordPress
1239  * @subpackage Post
1240  * @since 2.3.0
1241  *
1242  * @uses wp_get_object_terms() Gets the tags for returning. Args can be found here
1243  *
1244  * @param int $post_id Optional. The Post ID
1245  * @param array $args Optional. Overwrite the defaults
1246  * @return array List of post tags.
1247  */
1248 function wp_get_post_tags( $post_id = 0, $args = array() ) {
1249         return wp_get_post_terms( $post_id, 'post_tag', $args);
1250 }
1251
1252 /**
1253  * Retrieve the terms for a post.
1254  *
1255  * There is only one default for this function, called 'fields' and by default
1256  * is set to 'all'. There are other defaults that can be overridden in
1257  * {@link wp_get_object_terms()}.
1258  *
1259  * @package WordPress
1260  * @subpackage Post
1261  * @since 2.8.0
1262  *
1263  * @uses wp_get_object_terms() Gets the tags for returning. Args can be found here
1264  *
1265  * @param int $post_id Optional. The Post ID
1266  * @param string $taxonomy The taxonomy for which to retrieve terms. Defaults to post_tag.
1267  * @param array $args Optional. Overwrite the defaults
1268  * @return array List of post tags.
1269  */
1270 function wp_get_post_terms( $post_id = 0, $taxonomy = 'post_tag', $args = array() ) {
1271         $post_id = (int) $post_id;
1272
1273         $defaults = array('fields' => 'all');
1274         $args = wp_parse_args( $args, $defaults );
1275
1276         $tags = wp_get_object_terms($post_id, $taxonomy, $args);
1277
1278         return $tags;
1279 }
1280
1281 /**
1282  * Retrieve number of recent posts.
1283  *
1284  * @since 1.0.0
1285  * @uses $wpdb
1286  *
1287  * @param int $num Optional, default is 10. Number of posts to get.
1288  * @return array List of posts.
1289  */
1290 function wp_get_recent_posts($num = 10) {
1291         global $wpdb;
1292
1293         // Set the limit clause, if we got a limit
1294         $num = (int) $num;
1295         if ($num) {
1296                 $limit = "LIMIT $num";
1297         }
1298
1299         $sql = "SELECT * FROM $wpdb->posts WHERE post_type = 'post' ORDER BY post_date DESC $limit";
1300         $result = $wpdb->get_results($sql,ARRAY_A);
1301
1302         return $result ? $result : array();
1303 }
1304
1305 /**
1306  * Retrieve a single post, based on post ID.
1307  *
1308  * Has categories in 'post_category' property or key. Has tags in 'tags_input'
1309  * property or key.
1310  *
1311  * @since 1.0.0
1312  *
1313  * @param int $postid Post ID.
1314  * @param string $mode How to return result, either OBJECT, ARRAY_N, or ARRAY_A.
1315  * @return object|array Post object or array holding post contents and information
1316  */
1317 function wp_get_single_post($postid = 0, $mode = OBJECT) {
1318         $postid = (int) $postid;
1319
1320         $post = get_post($postid, $mode);
1321
1322         // Set categories and tags
1323         if($mode == OBJECT) {
1324                 $post->post_category = wp_get_post_categories($postid);
1325                 $post->tags_input = wp_get_post_tags($postid, array('fields' => 'names'));
1326         }
1327         else {
1328                 $post['post_category'] = wp_get_post_categories($postid);
1329                 $post['tags_input'] = wp_get_post_tags($postid, array('fields' => 'names'));
1330         }
1331
1332         return $post;
1333 }
1334
1335 /**
1336  * Insert a post.
1337  *
1338  * If the $postarr parameter has 'ID' set to a value, then post will be updated.
1339  *
1340  * You can set the post date manually, but setting the values for 'post_date'
1341  * and 'post_date_gmt' keys. You can close the comments or open the comments by
1342  * setting the value for 'comment_status' key.
1343  *
1344  * The defaults for the parameter $postarr are:
1345  *     'post_status'   - Default is 'draft'.
1346  *     'post_type'     - Default is 'post'.
1347  *     'post_author'   - Default is current user ID ($user_ID). The ID of the user who added the post.
1348  *     'ping_status'   - Default is the value in 'default_ping_status' option.
1349  *                       Whether the attachment can accept pings.
1350  *     'post_parent'   - Default is 0. Set this for the post it belongs to, if any.
1351  *     'menu_order'    - Default is 0. The order it is displayed.
1352  *     'to_ping'       - Whether to ping.
1353  *     'pinged'        - Default is empty string.
1354  *     'post_password' - Default is empty string. The password to access the attachment.
1355  *     'guid'          - Global Unique ID for referencing the attachment.
1356  *     'post_content_filtered' - Post content filtered.
1357  *     'post_excerpt'  - Post excerpt.
1358  *
1359  * @since 1.0.0
1360  * @link http://core.trac.wordpress.org/ticket/9084 Bug report on 'wp_insert_post_data' filter.
1361  * @uses $wpdb
1362  * @uses $wp_rewrite
1363  * @uses $user_ID
1364  *
1365  * @uses do_action() Calls 'pre_post_update' on post ID if this is an update.
1366  * @uses do_action() Calls 'edit_post' action on post ID and post data if this is an update.
1367  * @uses do_action() Calls 'save_post' and 'wp_insert_post' on post id and post data just before
1368  *                   returning.
1369  *
1370  * @uses apply_filters() Calls 'wp_insert_post_data' passing $data, $postarr prior to database
1371  *                       update or insert.
1372  * @uses wp_transition_post_status()
1373  *
1374  * @param array $postarr Optional. Overrides defaults.
1375  * @param bool $wp_error Optional. Allow return of WP_Error on failure.
1376  * @return int|WP_Error The value 0 or WP_Error on failure. The post ID on success.
1377  */
1378 function wp_insert_post($postarr = array(), $wp_error = false) {
1379         global $wpdb, $wp_rewrite, $user_ID;
1380
1381         $defaults = array('post_status' => 'draft', 'post_type' => 'post', 'post_author' => $user_ID,
1382                 'ping_status' => get_option('default_ping_status'), 'post_parent' => 0,
1383                 'menu_order' => 0, 'to_ping' =>  '', 'pinged' => '', 'post_password' => '',
1384                 'guid' => '', 'post_content_filtered' => '', 'post_excerpt' => '', 'import_id' => 0);
1385
1386         $postarr = wp_parse_args($postarr, $defaults);
1387         $postarr = sanitize_post($postarr, 'db');
1388
1389         // export array as variables
1390         extract($postarr, EXTR_SKIP);
1391
1392         // Are we updating or creating?
1393         $update = false;
1394         if ( !empty($ID) ) {
1395                 $update = true;
1396                 $previous_status = get_post_field('post_status', $ID);
1397         } else {
1398                 $previous_status = 'new';
1399         }
1400
1401         if ( ('' == $post_content) && ('' == $post_title) && ('' == $post_excerpt) ) {
1402                 if ( $wp_error )
1403                         return new WP_Error('empty_content', __('Content, title, and excerpt are empty.'));
1404                 else
1405                         return 0;
1406         }
1407
1408         // Make sure we set a valid category
1409         if ( empty($post_category) || 0 == count($post_category) || !is_array($post_category) ) {
1410                 $post_category = array(get_option('default_category'));
1411         }
1412
1413         //Set the default tag list
1414         if ( !isset($tags_input) )
1415                 $tags_input = array();
1416
1417         if ( empty($post_author) )
1418                 $post_author = $user_ID;
1419
1420         if ( empty($post_status) )
1421                 $post_status = 'draft';
1422
1423         if ( empty($post_type) )
1424                 $post_type = 'post';
1425
1426         $post_ID = 0;
1427
1428         // Get the post ID and GUID
1429         if ( $update ) {
1430                 $post_ID = (int) $ID;
1431                 $guid = get_post_field( 'guid', $post_ID );
1432         }
1433
1434         // Don't allow contributors to set to set the post slug for pending review posts
1435         if ( 'pending' == $post_status && !current_user_can( 'publish_posts' ) )
1436                 $post_name = '';
1437
1438         // Create a valid post name.  Drafts and pending posts are allowed to have an empty
1439         // post name.
1440         if ( !isset($post_name) || empty($post_name) ) {
1441                 if ( !in_array( $post_status, array( 'draft', 'pending' ) ) )
1442                         $post_name = sanitize_title($post_title);
1443                 else
1444                         $post_name = '';
1445         } else {
1446                 $post_name = sanitize_title($post_name);
1447         }
1448
1449         // 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
1450         if ( empty($post_date) || '0000-00-00 00:00:00' == $post_date )
1451                 $post_date = current_time('mysql');
1452
1453         if ( empty($post_date_gmt) || '0000-00-00 00:00:00' == $post_date_gmt ) {
1454                 if ( !in_array( $post_status, array( 'draft', 'pending' ) ) )
1455                         $post_date_gmt = get_gmt_from_date($post_date);
1456                 else
1457                         $post_date_gmt = '0000-00-00 00:00:00';
1458         }
1459
1460         if ( $update || '0000-00-00 00:00:00' == $post_date ) {
1461                 $post_modified     = current_time( 'mysql' );
1462                 $post_modified_gmt = current_time( 'mysql', 1 );
1463         } else {
1464                 $post_modified     = $post_date;
1465                 $post_modified_gmt = $post_date_gmt;
1466         }
1467
1468         if ( 'publish' == $post_status ) {
1469                 $now = gmdate('Y-m-d H:i:59');
1470                 if ( mysql2date('U', $post_date_gmt, false) > mysql2date('U', $now, false) )
1471                         $post_status = 'future';
1472         }
1473
1474         if ( empty($comment_status) ) {
1475                 if ( $update )
1476                         $comment_status = 'closed';
1477                 else
1478                         $comment_status = get_option('default_comment_status');
1479         }
1480         if ( empty($ping_status) )
1481                 $ping_status = get_option('default_ping_status');
1482
1483         if ( isset($to_ping) )
1484                 $to_ping = preg_replace('|\s+|', "\n", $to_ping);
1485         else
1486                 $to_ping = '';
1487
1488         if ( ! isset($pinged) )
1489                 $pinged = '';
1490
1491         if ( isset($post_parent) )
1492                 $post_parent = (int) $post_parent;
1493         else
1494                 $post_parent = 0;
1495
1496         if ( !empty($post_ID) ) {
1497                 if ( $post_parent == $post_ID ) {
1498                         // Post can't be its own parent
1499                         $post_parent = 0;
1500                 } elseif ( !empty($post_parent) ) {
1501                         $parent_post = get_post($post_parent);
1502                         // Check for circular dependency
1503                         if ( $parent_post->post_parent == $post_ID )
1504                                 $post_parent = 0;
1505                 }
1506         }
1507
1508         if ( isset($menu_order) )
1509                 $menu_order = (int) $menu_order;
1510         else
1511                 $menu_order = 0;
1512
1513         if ( !isset($post_password) || 'private' == $post_status )
1514                 $post_password = '';
1515
1516         $post_name = wp_unique_post_slug($post_name, $post_ID, $post_status, $post_type, $post_parent);
1517
1518         // expected_slashed (everything!)
1519         $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' ) );
1520         $data = apply_filters('wp_insert_post_data', $data, $postarr);
1521         $data = stripslashes_deep( $data );
1522         $where = array( 'ID' => $post_ID );
1523
1524         if ($update) {
1525                 do_action( 'pre_post_update', $post_ID );
1526                 if ( false === $wpdb->update( $wpdb->posts, $data, $where ) ) {
1527                         if ( $wp_error )
1528                                 return new WP_Error('db_update_error', __('Could not update post in the database'), $wpdb->last_error);
1529                         else
1530                                 return 0;
1531                 }
1532         } else {
1533                 if ( isset($post_mime_type) )
1534                         $data['post_mime_type'] = stripslashes( $post_mime_type ); // This isn't in the update
1535                 // If there is a suggested ID, use it if not already present
1536                 if ( !empty($import_id) ) {
1537                         $import_id = (int) $import_id;
1538                         if ( ! $wpdb->get_var( $wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE ID = %d", $import_id) ) ) {
1539                                 $data['ID'] = $import_id;
1540                         }
1541                 }
1542                 if ( false === $wpdb->insert( $wpdb->posts, $data ) ) {
1543                         if ( $wp_error )
1544                                 return new WP_Error('db_insert_error', __('Could not insert post into the database'), $wpdb->last_error);
1545                         else
1546                                 return 0;
1547                 }
1548                 $post_ID = (int) $wpdb->insert_id;
1549
1550                 // use the newly generated $post_ID
1551                 $where = array( 'ID' => $post_ID );
1552         }
1553
1554         if ( empty($data['post_name']) && !in_array( $data['post_status'], array( 'draft', 'pending' ) ) ) {
1555                 $data['post_name'] = sanitize_title($data['post_title'], $post_ID);
1556                 $wpdb->update( $wpdb->posts, array( 'post_name' => $data['post_name'] ), $where );
1557         }
1558
1559         wp_set_post_categories( $post_ID, $post_category );
1560         // old-style tags_input
1561         if ( !empty($tags_input) )
1562                 wp_set_post_tags( $post_ID, $tags_input );
1563         // new-style support for all tag-like taxonomies
1564         if ( !empty($tax_input) ) {
1565                 foreach ( $tax_input as $taxonomy => $tags ) {
1566                         wp_set_post_terms( $post_ID, $tags, $taxonomy );
1567                 }
1568         }
1569
1570         $current_guid = get_post_field( 'guid', $post_ID );
1571
1572         if ( 'page' == $data['post_type'] )
1573                 clean_page_cache($post_ID);
1574         else
1575                 clean_post_cache($post_ID);
1576
1577         // Set GUID
1578         if ( !$update && '' == $current_guid )
1579                 $wpdb->update( $wpdb->posts, array( 'guid' => get_permalink( $post_ID ) ), $where );
1580
1581         $post = get_post($post_ID);
1582
1583         if ( !empty($page_template) && 'page' == $data['post_type'] ) {
1584                 $post->page_template = $page_template;
1585                 $page_templates = get_page_templates();
1586                 if ( 'default' != $page_template && !in_array($page_template, $page_templates) ) {
1587                         if ( $wp_error )
1588                                 return new WP_Error('invalid_page_template', __('The page template is invalid.'));
1589                         else
1590                                 return 0;
1591                 }
1592                 update_post_meta($post_ID, '_wp_page_template',  $page_template);
1593         }
1594
1595         wp_transition_post_status($data['post_status'], $previous_status, $post);
1596
1597         if ( $update)
1598                 do_action('edit_post', $post_ID, $post);
1599
1600         do_action('save_post', $post_ID, $post);
1601         do_action('wp_insert_post', $post_ID, $post);
1602
1603         return $post_ID;
1604 }
1605
1606 /**
1607  * Update a post with new post data.
1608  *
1609  * The date does not have to be set for drafts. You can set the date and it will
1610  * not be overridden.
1611  *
1612  * @since 1.0.0
1613  *
1614  * @param array|object $postarr Post data. Arrays are expected to be escaped, objects are not.
1615  * @return int 0 on failure, Post ID on success.
1616  */
1617 function wp_update_post($postarr = array()) {
1618         if ( is_object($postarr) ) {
1619                 // non-escaped post was passed
1620                 $postarr = get_object_vars($postarr);
1621                 $postarr = add_magic_quotes($postarr);
1622         }
1623
1624         // First, get all of the original fields
1625         $post = wp_get_single_post($postarr['ID'], ARRAY_A);
1626
1627         // Escape data pulled from DB.
1628         $post = add_magic_quotes($post);
1629
1630         // Passed post category list overwrites existing category list if not empty.
1631         if ( isset($postarr['post_category']) && is_array($postarr['post_category'])
1632                          && 0 != count($postarr['post_category']) )
1633                 $post_cats = $postarr['post_category'];
1634         else
1635                 $post_cats = $post['post_category'];
1636
1637         // Drafts shouldn't be assigned a date unless explicitly done so by the user
1638         if ( in_array($post['post_status'], array('draft', 'pending')) && empty($postarr['edit_date']) &&
1639                          ('0000-00-00 00:00:00' == $post['post_date_gmt']) )
1640                 $clear_date = true;
1641         else
1642                 $clear_date = false;
1643
1644         // Merge old and new fields with new fields overwriting old ones.
1645         $postarr = array_merge($post, $postarr);
1646         $postarr['post_category'] = $post_cats;
1647         if ( $clear_date ) {
1648                 $postarr['post_date'] = current_time('mysql');
1649                 $postarr['post_date_gmt'] = '';
1650         }
1651
1652         if ($postarr['post_type'] == 'attachment')
1653                 return wp_insert_attachment($postarr);
1654
1655         return wp_insert_post($postarr);
1656 }
1657
1658 /**
1659  * Publish a post by transitioning the post status.
1660  *
1661  * @since 2.1.0
1662  * @uses $wpdb
1663  * @uses do_action() Calls 'edit_post', 'save_post', and 'wp_insert_post' on post_id and post data.
1664  *
1665  * @param int $post_id Post ID.
1666  * @return null
1667  */
1668 function wp_publish_post($post_id) {
1669         global $wpdb;
1670
1671         $post = get_post($post_id);
1672
1673         if ( empty($post) )
1674                 return;
1675
1676         if ( 'publish' == $post->post_status )
1677                 return;
1678
1679         $wpdb->update( $wpdb->posts, array( 'post_status' => 'publish' ), array( 'ID' => $post_id ) );
1680
1681         $old_status = $post->post_status;
1682         $post->post_status = 'publish';
1683         wp_transition_post_status('publish', $old_status, $post);
1684
1685         // Update counts for the post's terms.
1686         foreach ( (array) get_object_taxonomies('post') as $taxonomy ) {
1687                 $tt_ids = wp_get_object_terms($post_id, $taxonomy, 'fields=tt_ids');
1688                 wp_update_term_count($tt_ids, $taxonomy);
1689         }
1690
1691         do_action('edit_post', $post_id, $post);
1692         do_action('save_post', $post_id, $post);
1693         do_action('wp_insert_post', $post_id, $post);
1694 }
1695
1696 /**
1697  * Publish future post and make sure post ID has future post status.
1698  *
1699  * Invoked by cron 'publish_future_post' event. This safeguard prevents cron
1700  * from publishing drafts, etc.
1701  *
1702  * @since 2.5.0
1703  *
1704  * @param int $post_id Post ID.
1705  * @return null Nothing is returned. Which can mean that no action is required or post was published.
1706  */
1707 function check_and_publish_future_post($post_id) {
1708
1709         $post = get_post($post_id);
1710
1711         if ( empty($post) )
1712                 return;
1713
1714         if ( 'future' != $post->post_status )
1715                 return;
1716
1717         $time = strtotime( $post->post_date_gmt . ' GMT' );
1718
1719         if ( $time > time() ) { // Uh oh, someone jumped the gun!
1720                 wp_clear_scheduled_hook( 'publish_future_post', $post_id ); // clear anything else in the system
1721                 wp_schedule_single_event( $time, 'publish_future_post', array( $post_id ) );
1722                 return;
1723         }
1724
1725         return wp_publish_post($post_id);
1726 }
1727
1728
1729 /**
1730  * Given the desired slug and some post details computes a unique slug for the post.
1731  *
1732  * @param string $slug the desired slug (post_name)
1733  * @param integer $post_ID
1734  * @param string $post_status no uniqueness checks are made if the post is still draft or pending
1735  * @param string $post_type
1736  * @param integer $post_parent
1737  * @return string unique slug for the post, based on $post_name (with a -1, -2, etc. suffix)
1738  */
1739 function wp_unique_post_slug($slug, $post_ID, $post_status, $post_type, $post_parent) {
1740         if ( in_array( $post_status, array( 'draft', 'pending' ) ) )
1741                 return $slug;
1742         
1743         global $wpdb, $wp_rewrite;
1744         $hierarchical_post_types = apply_filters('hierarchical_post_types', array('page'));
1745         if ( 'attachment' == $post_type ) {
1746                 // Attachment slugs must be unique across all types.
1747                 $check_sql = "SELECT post_name FROM $wpdb->posts WHERE post_name = %s AND ID != %d LIMIT 1";
1748                 $post_name_check = $wpdb->get_var($wpdb->prepare($check_sql, $slug, $post_ID));
1749                 
1750                 if ( $post_name_check || in_array($slug, $wp_rewrite->feeds) ) {
1751                         $suffix = 2;
1752                         do {
1753                                 $alt_post_name = substr($slug, 0, 200-(strlen($suffix)+1)). "-$suffix";
1754                                 $post_name_check = $wpdb->get_var($wpdb->prepare($check_sql, $alt_post_name, $post_ID));
1755                                 $suffix++;
1756                         } while ($post_name_check);
1757                         $slug = $alt_post_name;
1758                 }
1759         } elseif ( in_array($post_type, $hierarchical_post_types) ) {
1760                 // Page slugs must be unique within their own trees.  Pages are in a
1761                 // separate namespace than posts so page slugs are allowed to overlap post slugs.
1762                 $check_sql = "SELECT post_name FROM $wpdb->posts WHERE post_name = %s AND post_type IN ( '" . implode("', '", $wpdb->escape($hierarchical_post_types)) . "' ) AND ID != %d AND post_parent = %d LIMIT 1";
1763                 $post_name_check = $wpdb->get_var($wpdb->prepare($check_sql, $slug, $post_ID, $post_parent));
1764                 
1765                 if ( $post_name_check || in_array($slug, $wp_rewrite->feeds) ) {
1766                         $suffix = 2;
1767                         do {
1768                                 $alt_post_name = substr($slug, 0, 200-(strlen($suffix)+1)). "-$suffix";
1769                                 $post_name_check = $wpdb->get_var($wpdb->prepare($check_sql, $alt_post_name, $post_ID, $post_parent));
1770                                 $suffix++;
1771                         } while ($post_name_check);
1772                         $slug = $alt_post_name;
1773                 }
1774         } else {
1775                 // Post slugs must be unique across all posts.
1776                 $check_sql = "SELECT post_name FROM $wpdb->posts WHERE post_name = %s AND post_type = %s AND ID != %d LIMIT 1";
1777                 $post_name_check = $wpdb->get_var($wpdb->prepare($check_sql, $slug, $post_type, $post_ID));
1778                 
1779                 if ( $post_name_check || in_array($slug, $wp_rewrite->feeds) ) {
1780                         $suffix = 2;
1781                         do {
1782                                 $alt_post_name = substr($slug, 0, 200-(strlen($suffix)+1)). "-$suffix";
1783                                 $post_name_check = $wpdb->get_var($wpdb->prepare($check_sql, $alt_post_name, $post_type, $post_ID));
1784                                 $suffix++;
1785                         } while ($post_name_check);
1786                         $slug = $alt_post_name;
1787                 }
1788         }
1789
1790         return $slug;
1791 }
1792
1793 /**
1794  * Adds tags to a post.
1795  *
1796  * @uses wp_set_post_tags() Same first two parameters, but the last parameter is always set to true.
1797  *
1798  * @package WordPress
1799  * @subpackage Post
1800  * @since 2.3.0
1801  *
1802  * @param int $post_id Post ID
1803  * @param string $tags The tags to set for the post, separated by commas.
1804  * @return bool|null Will return false if $post_id is not an integer or is 0. Will return null otherwise
1805  */
1806 function wp_add_post_tags($post_id = 0, $tags = '') {
1807         return wp_set_post_tags($post_id, $tags, true);
1808 }
1809
1810
1811 /**
1812  * Set the tags for a post.
1813  *
1814  * @since 2.3.0
1815  * @uses wp_set_object_terms() Sets the tags for the post.
1816  *
1817  * @param int $post_id Post ID.
1818  * @param string $tags The tags to set for the post, separated by commas.
1819  * @param bool $append If true, don't delete existing tags, just add on. If false, replace the tags with the new tags.
1820  * @return bool|null Will return false if $post_id is not an integer or is 0. Will return null otherwise
1821  */
1822 function wp_set_post_tags( $post_id = 0, $tags = '', $append = false ) {
1823         return wp_set_post_terms( $post_id, $tags, 'post_tag', $append);
1824 }
1825
1826 /**
1827  * Set the terms for a post.
1828  *
1829  * @since 2.8.0
1830  * @uses wp_set_object_terms() Sets the tags for the post.
1831  *
1832  * @param int $post_id Post ID.
1833  * @param string $tags The tags to set for the post, separated by commas.
1834  * @param bool $append If true, don't delete existing tags, just add on. If false, replace the tags with the new tags.
1835  * @return bool|null Will return false if $post_id is not an integer or is 0. Will return null otherwise
1836  */
1837 function wp_set_post_terms( $post_id = 0, $tags = '', $taxonomy = 'post_tag', $append = false ) {
1838         $post_id = (int) $post_id;
1839
1840         if ( !$post_id )
1841                 return false;
1842
1843         if ( empty($tags) )
1844                 $tags = array();
1845
1846         $tags = is_array($tags) ? $tags : explode( ',', trim($tags, " \n\t\r\0\x0B,") );
1847         wp_set_object_terms($post_id, $tags, $taxonomy, $append);
1848 }
1849
1850 /**
1851  * Set categories for a post.
1852  *
1853  * If the post categories parameter is not set, then the default category is
1854  * going used.
1855  *
1856  * @since 2.1.0
1857  *
1858  * @param int $post_ID Post ID.
1859  * @param array $post_categories Optional. List of categories.
1860  * @return bool|mixed
1861  */
1862 function wp_set_post_categories($post_ID = 0, $post_categories = array()) {
1863         $post_ID = (int) $post_ID;
1864         // If $post_categories isn't already an array, make it one:
1865         if (!is_array($post_categories) || 0 == count($post_categories) || empty($post_categories))
1866                 $post_categories = array(get_option('default_category'));
1867         else if ( 1 == count($post_categories) && '' == $post_categories[0] )
1868                 return true;
1869
1870         $post_categories = array_map('intval', $post_categories);
1871         $post_categories = array_unique($post_categories);
1872
1873         return wp_set_object_terms($post_ID, $post_categories, 'category');
1874 }
1875
1876 /**
1877  * Transition the post status of a post.
1878  *
1879  * Calls hooks to transition post status.
1880  *
1881  * The first is 'transition_post_status' with new status, old status, and post data.
1882  *
1883  * The next action called is 'OLDSTATUS_to_NEWSTATUS' the 'NEWSTATUS' is the
1884  * $new_status parameter and the 'OLDSTATUS' is $old_status parameter; it has the
1885  * post data.
1886  *
1887  * The final action is named 'NEWSTATUS_POSTTYPE', 'NEWSTATUS' is from the $new_status
1888  * parameter and POSTTYPE is post_type post data.
1889  *
1890  * @since 2.3.0
1891  * @link http://codex.wordpress.org/Post_Status_Transitions
1892  *
1893  * @uses do_action() Calls 'transition_post_status' on $new_status, $old_status and
1894  *  $post if there is a status change.
1895  * @uses do_action() Calls '${old_status}_to_$new_status' on $post if there is a status change.
1896  * @uses do_action() Calls '${new_status}_$post->post_type' on post ID and $post.
1897  *
1898  * @param string $new_status Transition to this post status.
1899  * @param string $old_status Previous post status.
1900  * @param object $post Post data.
1901  */
1902 function wp_transition_post_status($new_status, $old_status, $post) {
1903         do_action('transition_post_status', $new_status, $old_status, $post);
1904         do_action("${old_status}_to_$new_status", $post);
1905         do_action("${new_status}_$post->post_type", $post->ID, $post);
1906 }
1907
1908 //
1909 // Trackback and ping functions
1910 //
1911
1912 /**
1913  * Add a URL to those already pung.
1914  *
1915  * @since 1.5.0
1916  * @uses $wpdb
1917  *
1918  * @param int $post_id Post ID.
1919  * @param string $uri Ping URI.
1920  * @return int How many rows were updated.
1921  */
1922 function add_ping($post_id, $uri) {
1923         global $wpdb;
1924         $pung = $wpdb->get_var( $wpdb->prepare( "SELECT pinged FROM $wpdb->posts WHERE ID = %d", $post_id ));
1925         $pung = trim($pung);
1926         $pung = preg_split('/\s/', $pung);
1927         $pung[] = $uri;
1928         $new = implode("\n", $pung);
1929         $new = apply_filters('add_ping', $new);
1930         // expected_slashed ($new)
1931         $new = stripslashes($new);
1932         return $wpdb->update( $wpdb->posts, array( 'pinged' => $new ), array( 'ID' => $post_id ) );
1933 }
1934
1935 /**
1936  * Retrieve enclosures already enclosed for a post.
1937  *
1938  * @since 1.5.0
1939  * @uses $wpdb
1940  *
1941  * @param int $post_id Post ID.
1942  * @return array List of enclosures
1943  */
1944 function get_enclosed($post_id) {
1945         $custom_fields = get_post_custom( $post_id );
1946         $pung = array();
1947         if ( !is_array( $custom_fields ) )
1948                 return $pung;
1949
1950         foreach ( $custom_fields as $key => $val ) {
1951                 if ( 'enclosure' != $key || !is_array( $val ) )
1952                         continue;
1953                 foreach( $val as $enc ) {
1954                         $enclosure = split( "\n", $enc );
1955                         $pung[] = trim( $enclosure[ 0 ] );
1956                 }
1957         }
1958         $pung = apply_filters('get_enclosed', $pung);
1959         return $pung;
1960 }
1961
1962 /**
1963  * Retrieve URLs already pinged for a post.
1964  *
1965  * @since 1.5.0
1966  * @uses $wpdb
1967  *
1968  * @param int $post_id Post ID.
1969  * @return array
1970  */
1971 function get_pung($post_id) {
1972         global $wpdb;
1973         $pung = $wpdb->get_var( $wpdb->prepare( "SELECT pinged FROM $wpdb->posts WHERE ID = %d", $post_id ));
1974         $pung = trim($pung);
1975         $pung = preg_split('/\s/', $pung);
1976         $pung = apply_filters('get_pung', $pung);
1977         return $pung;
1978 }
1979
1980 /**
1981  * Retrieve URLs that need to be pinged.
1982  *
1983  * @since 1.5.0
1984  * @uses $wpdb
1985  *
1986  * @param int $post_id Post ID
1987  * @return array
1988  */
1989 function get_to_ping($post_id) {
1990         global $wpdb;
1991         $to_ping = $wpdb->get_var( $wpdb->prepare( "SELECT to_ping FROM $wpdb->posts WHERE ID = %d", $post_id ));
1992         $to_ping = trim($to_ping);
1993         $to_ping = preg_split('/\s/', $to_ping, -1, PREG_SPLIT_NO_EMPTY);
1994         $to_ping = apply_filters('get_to_ping',  $to_ping);
1995         return $to_ping;
1996 }
1997
1998 /**
1999  * Do trackbacks for a list of URLs.
2000  *
2001  * @since 1.0.0
2002  *
2003  * @param string $tb_list Comma separated list of URLs
2004  * @param int $post_id Post ID
2005  */
2006 function trackback_url_list($tb_list, $post_id) {
2007         if ( ! empty( $tb_list ) ) {
2008                 // get post data
2009                 $postdata = wp_get_single_post($post_id, ARRAY_A);
2010
2011                 // import postdata as variables
2012                 extract($postdata, EXTR_SKIP);
2013
2014                 // form an excerpt
2015                 $excerpt = strip_tags($post_excerpt ? $post_excerpt : $post_content);
2016
2017                 if (strlen($excerpt) > 255) {
2018                         $excerpt = substr($excerpt,0,252) . '...';
2019                 }
2020
2021                 $trackback_urls = explode(',', $tb_list);
2022                 foreach( (array) $trackback_urls as $tb_url) {
2023                         $tb_url = trim($tb_url);
2024                         trackback($tb_url, stripslashes($post_title), $excerpt, $post_id);
2025                 }
2026         }
2027 }
2028
2029 //
2030 // Page functions
2031 //
2032
2033 /**
2034  * Get a list of page IDs.
2035  *
2036  * @since 2.0.0
2037  * @uses $wpdb
2038  *
2039  * @return array List of page IDs.
2040  */
2041 function get_all_page_ids() {
2042         global $wpdb;
2043
2044         if ( ! $page_ids = wp_cache_get('all_page_ids', 'posts') ) {
2045                 $page_ids = $wpdb->get_col("SELECT ID FROM $wpdb->posts WHERE post_type = 'page'");
2046                 wp_cache_add('all_page_ids', $page_ids, 'posts');
2047         }
2048
2049         return $page_ids;
2050 }
2051
2052 /**
2053  * Retrieves page data given a page ID or page object.
2054  *
2055  * @since 1.5.1
2056  *
2057  * @param mixed $page Page object or page ID. Passed by reference.
2058  * @param string $output What to output. OBJECT, ARRAY_A, or ARRAY_N.
2059  * @param string $filter How the return value should be filtered.
2060  * @return mixed Page data.
2061  */
2062 function &get_page(&$page, $output = OBJECT, $filter = 'raw') {
2063         if ( empty($page) ) {
2064                 if ( isset( $GLOBALS['page'] ) && isset( $GLOBALS['page']->ID ) ) {
2065                         return get_post($GLOBALS['page'], $output, $filter);
2066                 } else {
2067                         $page = null;
2068                         return $page;
2069                 }
2070         }
2071
2072         $the_page = get_post($page, $output, $filter);
2073         return $the_page;
2074 }
2075
2076 /**
2077  * Retrieves a page given its path.
2078  *
2079  * @since 2.1.0
2080  * @uses $wpdb
2081  *
2082  * @param string $page_path Page path
2083  * @param string $output Optional. Output type. OBJECT, ARRAY_N, or ARRAY_A.
2084  * @return mixed Null when complete.
2085  */
2086 function get_page_by_path($page_path, $output = OBJECT) {
2087         global $wpdb;
2088         $page_path = rawurlencode(urldecode($page_path));
2089         $page_path = str_replace('%2F', '/', $page_path);
2090         $page_path = str_replace('%20', ' ', $page_path);
2091         $page_paths = '/' . trim($page_path, '/');
2092         $leaf_path  = sanitize_title(basename($page_paths));
2093         $page_paths = explode('/', $page_paths);
2094         $full_path = '';
2095         foreach( (array) $page_paths as $pathdir)
2096                 $full_path .= ($pathdir!=''?'/':'') . sanitize_title($pathdir);
2097
2098         $pages = $wpdb->get_results( $wpdb->prepare( "SELECT ID, post_name, post_parent FROM $wpdb->posts WHERE post_name = %s AND (post_type = 'page' OR post_type = 'attachment')", $leaf_path ));
2099
2100         if ( empty($pages) )
2101                 return null;
2102
2103         foreach ($pages as $page) {
2104                 $path = '/' . $leaf_path;
2105                 $curpage = $page;
2106                 while ($curpage->post_parent != 0) {
2107                         $curpage = $wpdb->get_row( $wpdb->prepare( "SELECT ID, post_name, post_parent FROM $wpdb->posts WHERE ID = %d and post_type='page'", $curpage->post_parent ));
2108                         $path = '/' . $curpage->post_name . $path;
2109                 }
2110
2111                 if ( $path == $full_path )
2112                         return get_page($page->ID, $output);
2113         }
2114
2115         return null;
2116 }
2117
2118 /**
2119  * Retrieve a page given its title.
2120  *
2121  * @since 2.1.0
2122  * @uses $wpdb
2123  *
2124  * @param string $page_title Page title
2125  * @param string $output Optional. Output type. OBJECT, ARRAY_N, or ARRAY_A.
2126  * @return mixed
2127  */
2128 function get_page_by_title($page_title, $output = OBJECT) {
2129         global $wpdb;
2130         $page = $wpdb->get_var( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_title = %s AND post_type='page'", $page_title ));
2131         if ( $page )
2132                 return get_page($page, $output);
2133
2134         return null;
2135 }
2136
2137 /**
2138  * Retrieve child pages from list of pages matching page ID.
2139  *
2140  * Matches against the pages parameter against the page ID. Also matches all
2141  * children for the same to retrieve all children of a page. Does not make any
2142  * SQL queries to get the children.
2143  *
2144  * @since 1.5.1
2145  *
2146  * @param int $page_id Page ID.
2147  * @param array $pages List of pages' objects.
2148  * @return array
2149  */
2150 function &get_page_children($page_id, $pages) {
2151         $page_list = array();
2152         foreach ( (array) $pages as $page ) {
2153                 if ( $page->post_parent == $page_id ) {
2154                         $page_list[] = $page;
2155                         if ( $children = get_page_children($page->ID, $pages) )
2156                                 $page_list = array_merge($page_list, $children);
2157                 }
2158         }
2159         return $page_list;
2160 }
2161
2162 /**
2163  * Order the pages with children under parents in a flat list.
2164  *
2165  * @since 2.0.0
2166  *
2167  * @param array $posts Posts array.
2168  * @param int $parent Parent page ID.
2169  * @return array A list arranged by hierarchy. Children immediately follow their parents.
2170  */
2171 function get_page_hierarchy($posts, $parent = 0) {
2172         $result = array ( );
2173         if ($posts) { foreach ( (array) $posts as $post) {
2174                 if ($post->post_parent == $parent) {
2175                         $result[$post->ID] = $post->post_name;
2176                         $children = get_page_hierarchy($posts, $post->ID);
2177                         $result += $children; //append $children to $result
2178                 }
2179         } }
2180         return $result;
2181 }
2182
2183 /**
2184  * Builds URI for a page.
2185  *
2186  * Sub pages will be in the "directory" under the parent page post name.
2187  *
2188  * @since 1.5.0
2189  *
2190  * @param int $page_id Page ID.
2191  * @return string Page URI.
2192  */
2193 function get_page_uri($page_id) {
2194         $page = get_page($page_id);
2195         $uri = $page->post_name;
2196
2197         // A page cannot be it's own parent.
2198         if ( $page->post_parent == $page->ID )
2199                 return $uri;
2200
2201         while ($page->post_parent != 0) {
2202                 $page = get_page($page->post_parent);
2203                 $uri = $page->post_name . "/" . $uri;
2204         }
2205
2206         return $uri;
2207 }
2208
2209 /**
2210  * Retrieve a list of pages.
2211  *
2212  * The defaults that can be overridden are the following: 'child_of',
2213  * 'sort_order', 'sort_column', 'post_title', 'hierarchical', 'exclude',
2214  * 'include', 'meta_key', 'meta_value','authors', 'number', and 'offset'.
2215  *
2216  * @since 1.5.0
2217  * @uses $wpdb
2218  *
2219  * @param mixed $args Optional. Array or string of options that overrides defaults.
2220  * @return array List of pages matching defaults or $args
2221  */
2222 function &get_pages($args = '') {
2223         global $wpdb;
2224
2225         $defaults = array(
2226                 'child_of' => 0, 'sort_order' => 'ASC',
2227                 'sort_column' => 'post_title', 'hierarchical' => 1,
2228                 'exclude' => '', 'include' => '',
2229                 'meta_key' => '', 'meta_value' => '',
2230                 'authors' => '', 'parent' => -1, 'exclude_tree' => '',
2231                 'number' => '', 'offset' => 0
2232         );
2233
2234         $r = wp_parse_args( $args, $defaults );
2235         extract( $r, EXTR_SKIP );
2236         $number = (int) $number;
2237         $offset = (int) $offset;
2238
2239         $cache = array();
2240         $key = md5( serialize( compact(array_keys($defaults)) ) );
2241         if ( $cache = wp_cache_get( 'get_pages', 'posts' ) ) {
2242                 if ( is_array($cache) && isset( $cache[ $key ] ) ) {
2243                         $pages = apply_filters('get_pages', $cache[ $key ], $r );
2244                         return $pages;
2245                 }
2246         }
2247
2248         if ( !is_array($cache) )
2249                 $cache = array();
2250
2251         $inclusions = '';
2252         if ( !empty($include) ) {
2253                 $child_of = 0; //ignore child_of, parent, exclude, meta_key, and meta_value params if using include
2254                 $parent = -1;
2255                 $exclude = '';
2256                 $meta_key = '';
2257                 $meta_value = '';
2258                 $hierarchical = false;
2259                 $incpages = preg_split('/[\s,]+/',$include);
2260                 if ( count($incpages) ) {
2261                         foreach ( $incpages as $incpage ) {
2262                                 if (empty($inclusions))
2263                                         $inclusions = $wpdb->prepare(' AND ( ID = %d ', $incpage);
2264                                 else
2265                                         $inclusions .= $wpdb->prepare(' OR ID = %d ', $incpage);
2266                         }
2267                 }
2268         }
2269         if (!empty($inclusions))
2270                 $inclusions .= ')';
2271
2272         $exclusions = '';
2273         if ( !empty($exclude) ) {
2274                 $expages = preg_split('/[\s,]+/',$exclude);
2275                 if ( count($expages) ) {
2276                         foreach ( $expages as $expage ) {
2277                                 if (empty($exclusions))
2278                                         $exclusions = $wpdb->prepare(' AND ( ID <> %d ', $expage);
2279                                 else
2280                                         $exclusions .= $wpdb->prepare(' AND ID <> %d ', $expage);
2281                         }
2282                 }
2283         }
2284         if (!empty($exclusions))
2285                 $exclusions .= ')';
2286
2287         $author_query = '';
2288         if (!empty($authors)) {
2289                 $post_authors = preg_split('/[\s,]+/',$authors);
2290
2291                 if ( count($post_authors) ) {
2292                         foreach ( $post_authors as $post_author ) {
2293                                 //Do we have an author id or an author login?
2294                                 if ( 0 == intval($post_author) ) {
2295                                         $post_author = get_userdatabylogin($post_author);
2296                                         if ( empty($post_author) )
2297                                                 continue;
2298                                         if ( empty($post_author->ID) )
2299                                                 continue;
2300                                         $post_author = $post_author->ID;
2301                                 }
2302
2303                                 if ( '' == $author_query )
2304                                         $author_query = $wpdb->prepare(' post_author = %d ', $post_author);
2305                                 else
2306                                         $author_query .= $wpdb->prepare(' OR post_author = %d ', $post_author);
2307                         }
2308                         if ( '' != $author_query )
2309                                 $author_query = " AND ($author_query)";
2310                 }
2311         }
2312
2313         $join = '';
2314         $where = "$exclusions $inclusions ";
2315         if ( ! empty( $meta_key ) || ! empty( $meta_value ) ) {
2316                 $join = " LEFT JOIN $wpdb->postmeta ON ( $wpdb->posts.ID = $wpdb->postmeta.post_id )";
2317
2318                 // meta_key and meta_value might be slashed
2319                 $meta_key = stripslashes($meta_key);
2320                 $meta_value = stripslashes($meta_value);
2321                 if ( ! empty( $meta_key ) )
2322                         $where .= $wpdb->prepare(" AND $wpdb->postmeta.meta_key = %s", $meta_key);
2323                 if ( ! empty( $meta_value ) )
2324                         $where .= $wpdb->prepare(" AND $wpdb->postmeta.meta_value = %s", $meta_value);
2325
2326         }
2327
2328         if ( $parent >= 0 )
2329                 $where .= $wpdb->prepare(' AND post_parent = %d ', $parent);
2330
2331         $query = "SELECT * FROM $wpdb->posts $join WHERE (post_type = 'page' AND post_status = 'publish') $where ";
2332         $query .= $author_query;
2333         $query .= " ORDER BY " . $sort_column . " " . $sort_order ;
2334
2335         if ( !empty($number) )
2336                 $query .= ' LIMIT ' . $offset . ',' . $number;
2337
2338         $pages = $wpdb->get_results($query);
2339
2340         if ( empty($pages) ) {
2341                 $pages = apply_filters('get_pages', array(), $r);
2342                 return $pages;
2343         }
2344
2345         // Update cache.
2346         update_page_cache($pages);
2347
2348         if ( $child_of || $hierarchical )
2349                 $pages = & get_page_children($child_of, $pages);
2350
2351         if ( !empty($exclude_tree) ) {
2352                 $exclude = array();
2353
2354                 $exclude = (int) $exclude_tree;
2355                 $children = get_page_children($exclude, $pages);
2356                 $excludes = array();
2357                 foreach ( $children as $child )
2358                         $excludes[] = $child->ID;
2359                 $excludes[] = $exclude;
2360                 $total = count($pages);
2361                 for ( $i = 0; $i < $total; $i++ ) {
2362                         if ( in_array($pages[$i]->ID, $excludes) )
2363                                 unset($pages[$i]);
2364                 }
2365         }
2366
2367         $cache[ $key ] = $pages;
2368         wp_cache_set( 'get_pages', $cache, 'posts' );
2369
2370         $pages = apply_filters('get_pages', $pages, $r);
2371
2372         return $pages;
2373 }
2374
2375 //
2376 // Attachment functions
2377 //
2378
2379 /**
2380  * Check if the attachment URI is local one and is really an attachment.
2381  *
2382  * @since 2.0.0
2383  *
2384  * @param string $url URL to check
2385  * @return bool True on success, false on failure.
2386  */
2387 function is_local_attachment($url) {
2388         if (strpos($url, get_bloginfo('url')) === false)
2389                 return false;
2390         if (strpos($url, get_bloginfo('url') . '/?attachment_id=') !== false)
2391                 return true;
2392         if ( $id = url_to_postid($url) ) {
2393                 $post = & get_post($id);
2394                 if ( 'attachment' == $post->post_type )
2395                         return true;
2396         }
2397         return false;
2398 }
2399
2400 /**
2401  * Insert an attachment.
2402  *
2403  * If you set the 'ID' in the $object parameter, it will mean that you are
2404  * updating and attempt to update the attachment. You can also set the
2405  * attachment name or title by setting the key 'post_name' or 'post_title'.
2406  *
2407  * You can set the dates for the attachment manually by setting the 'post_date'
2408  * and 'post_date_gmt' keys' values.
2409  *
2410  * By default, the comments will use the default settings for whether the
2411  * comments are allowed. You can close them manually or keep them open by
2412  * setting the value for the 'comment_status' key.
2413  *
2414  * The $object parameter can have the following:
2415  *     'post_status'   - Default is 'draft'. Can not be overridden, set the same as parent post.
2416  *     'post_type'     - Default is 'post', will be set to attachment. Can not override.
2417  *     'post_author'   - Default is current user ID. The ID of the user, who added the attachment.
2418  *     'ping_status'   - Default is the value in default ping status option. Whether the attachment
2419  *                       can accept pings.
2420  *     'post_parent'   - Default is 0. Can use $parent parameter or set this for the post it belongs
2421  *                       to, if any.
2422  *     'menu_order'    - Default is 0. The order it is displayed.
2423  *     'to_ping'       - Whether to ping.
2424  *     'pinged'        - Default is empty string.
2425  *     'post_password' - Default is empty string. The password to access the attachment.
2426  *     'guid'          - Global Unique ID for referencing the attachment.
2427  *     'post_content_filtered' - Attachment post content filtered.
2428  *     'post_excerpt'  - Attachment excerpt.
2429  *
2430  * @since 2.0.0
2431  * @uses $wpdb
2432  * @uses $user_ID
2433  * @uses do_action() Calls 'edit_attachment' on $post_ID if this is an update.
2434  * @uses do_action() Calls 'add_attachment' on $post_ID if this is not an update.
2435  *
2436  * @param string|array $object Arguments to override defaults.
2437  * @param string $file Optional filename.
2438  * @param int $post_parent Parent post ID.
2439  * @return int Attachment ID.
2440  */
2441 function wp_insert_attachment($object, $file = false, $parent = 0) {
2442         global $wpdb, $user_ID;
2443
2444         $defaults = array('post_status' => 'draft', 'post_type' => 'post', 'post_author' => $user_ID,
2445                 'ping_status' => get_option('default_ping_status'), 'post_parent' => 0,
2446                 'menu_order' => 0, 'to_ping' =>  '', 'pinged' => '', 'post_password' => '',
2447                 'guid' => '', 'post_content_filtered' => '', 'post_excerpt' => '', 'import_id' => 0);
2448
2449         $object = wp_parse_args($object, $defaults);
2450         if ( !empty($parent) )
2451                 $object['post_parent'] = $parent;
2452
2453         $object = sanitize_post($object, 'db');
2454
2455         // export array as variables
2456         extract($object, EXTR_SKIP);
2457
2458         // Make sure we set a valid category
2459         if ( !isset($post_category) || 0 == count($post_category) || !is_array($post_category)) {
2460                 $post_category = array(get_option('default_category'));
2461         }
2462
2463         if ( empty($post_author) )
2464                 $post_author = $user_ID;
2465
2466         $post_type = 'attachment';
2467         $post_status = 'inherit';
2468
2469         // Are we updating or creating?
2470         if ( !empty($ID) ) {
2471                 $update = true;
2472                 $post_ID = (int) $ID;
2473         } else {
2474                 $update = false;
2475                 $post_ID = 0;
2476         }
2477
2478         // Create a valid post name.
2479         if ( empty($post_name) )
2480                 $post_name = sanitize_title($post_title);
2481         else
2482                 $post_name = sanitize_title($post_name);
2483
2484         // expected_slashed ($post_name)
2485         $post_name = wp_unique_post_slug($post_name, $post_ID, $post_status, $post_type, $post_parent);
2486
2487         if ( empty($post_date) )
2488                 $post_date = current_time('mysql');
2489         if ( empty($post_date_gmt) )
2490                 $post_date_gmt = current_time('mysql', 1);
2491
2492         if ( empty($post_modified) )
2493                 $post_modified = $post_date;
2494         if ( empty($post_modified_gmt) )
2495                 $post_modified_gmt = $post_date_gmt;
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($post_parent) )
2512                 $post_parent = (int) $post_parent;
2513         else
2514                 $post_parent = 0;
2515
2516         if ( isset($menu_order) )
2517                 $menu_order = (int) $menu_order;
2518         else
2519                 $menu_order = 0;
2520
2521         if ( !isset($post_password) )
2522                 $post_password = '';
2523
2524         if ( ! isset($pinged) )
2525                 $pinged = '';
2526
2527         // expected_slashed (everything!)
2528         $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' ) );
2529         $data = stripslashes_deep( $data );
2530
2531         if ( $update ) {
2532                 $wpdb->update( $wpdb->posts, $data, array( 'ID' => $post_ID ) );
2533         } else {
2534                 // If there is a suggested ID, use it if not already present
2535                 if ( !empty($import_id) ) {
2536                         $import_id = (int) $import_id;
2537                         if ( ! $wpdb->get_var( $wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE ID = %d", $import_id) ) ) {
2538                                 $data['ID'] = $import_id;
2539                         }
2540                 }
2541
2542                 $wpdb->insert( $wpdb->posts, $data );
2543                 $post_ID = (int) $wpdb->insert_id;
2544         }
2545
2546         if ( empty($post_name) ) {
2547                 $post_name = sanitize_title($post_title, $post_ID);
2548                 $wpdb->update( $wpdb->posts, compact("post_name"), array( 'ID' => $post_ID ) );
2549         }
2550
2551         wp_set_post_categories($post_ID, $post_category);
2552
2553         if ( $file )
2554                 update_attached_file( $post_ID, $file );
2555
2556         clean_post_cache($post_ID);
2557
2558         if ( $update) {
2559                 do_action('edit_attachment', $post_ID);
2560         } else {
2561                 do_action('add_attachment', $post_ID);
2562         }
2563
2564         return $post_ID;
2565 }
2566
2567 /**
2568  * Delete an attachment.
2569  *
2570  * Will remove the file also, when the attachment is removed. Removes all post
2571  * meta fields, taxonomy, comments, etc associated with the attachment (except
2572  * the main post).
2573  *
2574  * @since 2.0.0
2575  * @uses $wpdb
2576  * @uses do_action() Calls 'delete_attachment' hook on Attachment ID.
2577  *
2578  * @param int $postid Attachment ID.
2579  * @return mixed False on failure. Post data on success.
2580  */
2581 function wp_delete_attachment($postid) {
2582         global $wpdb;
2583
2584         if ( !$post = $wpdb->get_row(  $wpdb->prepare( "SELECT * FROM $wpdb->posts WHERE ID = %d", $postid)) )
2585                 return $post;
2586
2587         if ( 'attachment' != $post->post_type )
2588                 return false;
2589
2590         $meta = wp_get_attachment_metadata( $postid );
2591         $file = get_attached_file( $postid );
2592
2593         do_action('delete_attachment', $postid);
2594
2595         /** @todo Delete for pluggable post taxonomies too */
2596         wp_delete_object_term_relationships($postid, array('category', 'post_tag'));
2597
2598         $wpdb->query( $wpdb->prepare( "DELETE FROM $wpdb->comments WHERE comment_post_ID = %d", $postid ));
2599
2600         $wpdb->query( $wpdb->prepare( "DELETE FROM $wpdb->postmeta WHERE post_id = %d ", $postid ));
2601
2602         $wpdb->query( $wpdb->prepare( "DELETE FROM $wpdb->posts WHERE ID = %d", $postid ));
2603
2604         $uploadPath = wp_upload_dir();
2605
2606         if ( ! empty($meta['thumb']) ) {
2607                 // Don't delete the thumb if another attachment uses it
2608                 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'].'%', $postid)) ) {
2609                         $thumbfile = str_replace(basename($file), $meta['thumb'], $file);
2610                         $thumbfile = apply_filters('wp_delete_file', $thumbfile);
2611                         @ unlink( path_join($uploadPath['basedir'], $thumbfile) );
2612                 }
2613         }
2614
2615         // remove intermediate images if there are any
2616         $sizes = apply_filters('intermediate_image_sizes', array('thumbnail', 'medium', 'large'));
2617         foreach ( $sizes as $size ) {
2618                 if ( $intermediate = image_get_intermediate_size($postid, $size) ) {
2619                         $intermediate_file = apply_filters('wp_delete_file', $intermediate['path']);
2620                         @ unlink( path_join($uploadPath['basedir'], $intermediate_file) );
2621                 }
2622         }
2623
2624         $file = apply_filters('wp_delete_file', $file);
2625
2626         if ( ! empty($file) )
2627                 @ unlink($file);
2628
2629         clean_post_cache($postid);
2630
2631         return $post;
2632 }
2633
2634 /**
2635  * Retrieve attachment meta field for attachment ID.
2636  *
2637  * @since 2.1.0
2638  *
2639  * @param int $post_id Attachment ID
2640  * @param bool $unfiltered Optional, default is false. If true, filters are not run.
2641  * @return string|bool Attachment meta field. False on failure.
2642  */
2643 function wp_get_attachment_metadata( $post_id, $unfiltered = false ) {
2644         $post_id = (int) $post_id;
2645         if ( !$post =& get_post( $post_id ) )
2646                 return false;
2647
2648         $data = get_post_meta( $post->ID, '_wp_attachment_metadata', true );
2649         if ( $unfiltered )
2650                 return $data;
2651         return apply_filters( 'wp_get_attachment_metadata', $data, $post->ID );
2652 }
2653
2654 /**
2655  * Update metadata for an attachment.
2656  *
2657  * @since 2.1.0
2658  *
2659  * @param int $post_id Attachment ID.
2660  * @param array $data Attachment data.
2661  * @return int
2662  */
2663 function wp_update_attachment_metadata( $post_id, $data ) {
2664         $post_id = (int) $post_id;
2665         if ( !$post =& get_post( $post_id ) )
2666                 return false;
2667
2668         $data = apply_filters( 'wp_update_attachment_metadata', $data, $post->ID );
2669
2670         return update_post_meta( $post->ID, '_wp_attachment_metadata', $data);
2671 }
2672
2673 /**
2674  * Retrieve the URL for an attachment.
2675  *
2676  * @since 2.1.0
2677  *
2678  * @param int $post_id Attachment ID.
2679  * @return string
2680  */
2681 function wp_get_attachment_url( $post_id = 0 ) {
2682         $post_id = (int) $post_id;
2683         if ( !$post =& get_post( $post_id ) )
2684                 return false;
2685
2686         $url = '';
2687         if ( $file = get_post_meta( $post->ID, '_wp_attached_file', true) ) { //Get attached file
2688                 if ( ($uploads = wp_upload_dir()) && false === $uploads['error'] ) { //Get upload directory
2689                         if ( 0 === strpos($file, $uploads['basedir']) ) //Check that the upload base exists in the file location
2690                                 $url = str_replace($uploads['basedir'], $uploads['baseurl'], $file); //replace file location with url location
2691                         elseif ( false !== strpos($file, 'wp-content/uploads') )
2692                                 $url = $uploads['baseurl'] . substr( $file, strpos($file, 'wp-content/uploads') + 18 );
2693                         else
2694                                 $url = $uploads['baseurl'] . "/$file"; //Its a newly uploaded file, therefor $file is relative to the basedir.
2695                 }
2696         }
2697
2698         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.
2699                 $url = get_the_guid( $post->ID );
2700
2701         if ( 'attachment' != $post->post_type || empty($url) )
2702                 return false;
2703
2704         return apply_filters( 'wp_get_attachment_url', $url, $post->ID );
2705 }
2706
2707 /**
2708  * Retrieve thumbnail for an attachment.
2709  *
2710  * @since 2.1.0
2711  *
2712  * @param int $post_id Attachment ID.
2713  * @return mixed False on failure. Thumbnail file path on success.
2714  */
2715 function wp_get_attachment_thumb_file( $post_id = 0 ) {
2716         $post_id = (int) $post_id;
2717         if ( !$post =& get_post( $post_id ) )
2718                 return false;
2719         if ( !is_array( $imagedata = wp_get_attachment_metadata( $post->ID ) ) )
2720                 return false;
2721
2722         $file = get_attached_file( $post->ID );
2723
2724         if ( !empty($imagedata['thumb']) && ($thumbfile = str_replace(basename($file), $imagedata['thumb'], $file)) && file_exists($thumbfile) )
2725                 return apply_filters( 'wp_get_attachment_thumb_file', $thumbfile, $post->ID );
2726         return false;
2727 }
2728
2729 /**
2730  * Retrieve URL for an attachment thumbnail.
2731  *
2732  * @since 2.1.0
2733  *
2734  * @param int $post_id Attachment ID
2735  * @return string|bool False on failure. Thumbnail URL on success.
2736  */
2737 function wp_get_attachment_thumb_url( $post_id = 0 ) {
2738         $post_id = (int) $post_id;
2739         if ( !$post =& get_post( $post_id ) )
2740                 return false;
2741         if ( !$url = wp_get_attachment_url( $post->ID ) )
2742                 return false;
2743
2744         $sized = image_downsize( $post_id, 'thumbnail' );
2745         if ( $sized )
2746                 return $sized[0];
2747
2748         if ( !$thumb = wp_get_attachment_thumb_file( $post->ID ) )
2749                 return false;
2750
2751         $url = str_replace(basename($url), basename($thumb), $url);
2752
2753         return apply_filters( 'wp_get_attachment_thumb_url', $url, $post->ID );
2754 }
2755
2756 /**
2757  * Check if the attachment is an image.
2758  *
2759  * @since 2.1.0
2760  *
2761  * @param int $post_id Attachment ID
2762  * @return bool
2763  */
2764 function wp_attachment_is_image( $post_id = 0 ) {
2765         $post_id = (int) $post_id;
2766         if ( !$post =& get_post( $post_id ) )
2767                 return false;
2768
2769         if ( !$file = get_attached_file( $post->ID ) )
2770                 return false;
2771
2772         $ext = preg_match('/\.([^.]+)$/', $file, $matches) ? strtolower($matches[1]) : false;
2773
2774         $image_exts = array('jpg', 'jpeg', 'gif', 'png');
2775
2776         if ( 'image/' == substr($post->post_mime_type, 0, 6) || $ext && 'import' == $post->post_mime_type && in_array($ext, $image_exts) )
2777                 return true;
2778         return false;
2779 }
2780
2781 /**
2782  * Retrieve the icon for a MIME type.
2783  *
2784  * @since 2.1.0
2785  *
2786  * @param string $mime MIME type
2787  * @return string|bool
2788  */
2789 function wp_mime_type_icon( $mime = 0 ) {
2790         if ( !is_numeric($mime) )
2791                 $icon = wp_cache_get("mime_type_icon_$mime");
2792         if ( empty($icon) ) {
2793                 $post_id = 0;
2794                 $post_mimes = array();
2795                 if ( is_numeric($mime) ) {
2796                         $mime = (int) $mime;
2797                         if ( $post =& get_post( $mime ) ) {
2798                                 $post_id = (int) $post->ID;
2799                                 $ext = preg_replace('/^.+?\.([^.]+)$/', '$1', $post->guid);
2800                                 if ( !empty($ext) ) {
2801                                         $post_mimes[] = $ext;
2802                                         if ( $ext_type = wp_ext2type( $ext ) )
2803                                                 $post_mimes[] = $ext_type;
2804                                 }
2805                                 $mime = $post->post_mime_type;
2806                         } else {
2807                                 $mime = 0;
2808                         }
2809                 } else {
2810                         $post_mimes[] = $mime;
2811                 }
2812
2813                 $icon_files = wp_cache_get('icon_files');
2814
2815                 if ( !is_array($icon_files) ) {
2816                         $icon_dir = apply_filters( 'icon_dir', ABSPATH . WPINC . '/images/crystal' );
2817                         $icon_dir_uri = apply_filters( 'icon_dir_uri', includes_url('images/crystal') );
2818                         $dirs = apply_filters( 'icon_dirs', array($icon_dir => $icon_dir_uri) );
2819                         $icon_files = array();
2820                         while ( $dirs ) {
2821                                 $dir = array_shift($keys = array_keys($dirs));
2822                                 $uri = array_shift($dirs);
2823                                 if ( $dh = opendir($dir) ) {
2824                                         while ( false !== $file = readdir($dh) ) {
2825                                                 $file = basename($file);
2826                                                 if ( substr($file, 0, 1) == '.' )
2827                                                         continue;
2828                                                 if ( !in_array(strtolower(substr($file, -4)), array('.png', '.gif', '.jpg') ) ) {
2829                                                         if ( is_dir("$dir/$file") )
2830                                                                 $dirs["$dir/$file"] = "$uri/$file";
2831                                                         continue;
2832                                                 }
2833                                                 $icon_files["$dir/$file"] = "$uri/$file";
2834                                         }
2835                                         closedir($dh);
2836                                 }
2837                         }
2838                         wp_cache_set('icon_files', $icon_files, 600);
2839                 }
2840
2841                 // Icon basename - extension = MIME wildcard
2842                 foreach ( $icon_files as $file => $uri )
2843                         $types[ preg_replace('/^([^.]*).*$/', '$1', basename($file)) ] =& $icon_files[$file];
2844
2845                 if ( ! empty($mime) ) {
2846                         $post_mimes[] = substr($mime, 0, strpos($mime, '/'));
2847                         $post_mimes[] = substr($mime, strpos($mime, '/') + 1);
2848                         $post_mimes[] = str_replace('/', '_', $mime);
2849                 }
2850
2851                 $matches = wp_match_mime_types(array_keys($types), $post_mimes);
2852                 $matches['default'] = array('default');
2853
2854                 foreach ( $matches as $match => $wilds ) {
2855                         if ( isset($types[$wilds[0]])) {
2856                                 $icon = $types[$wilds[0]];
2857                                 if ( !is_numeric($mime) )
2858                                         wp_cache_set("mime_type_icon_$mime", $icon);
2859                                 break;
2860                         }
2861                 }
2862         }
2863
2864         return apply_filters( 'wp_mime_type_icon', $icon, $mime, $post_id ); // Last arg is 0 if function pass mime type.
2865 }
2866
2867 /**
2868  * Checked for changed slugs for published posts and save old slug.
2869  *
2870  * The function is used along with form POST data. It checks for the wp-old-slug
2871  * POST field. Will only be concerned with published posts and the slug actually
2872  * changing.
2873  *
2874  * If the slug was changed and not already part of the old slugs then it will be
2875  * added to the post meta field ('_wp_old_slug') for storing old slugs for that
2876  * post.
2877  *
2878  * The most logically usage of this function is redirecting changed posts, so
2879  * that those that linked to an changed post will be redirected to the new post.
2880  *
2881  * @since 2.1.0
2882  *
2883  * @param int $post_id Post ID.
2884  * @return int Same as $post_id
2885  */
2886 function wp_check_for_changed_slugs($post_id) {
2887         if ( !isset($_POST['wp-old-slug']) || !strlen($_POST['wp-old-slug']) )
2888                 return $post_id;
2889
2890         $post = &get_post($post_id);
2891
2892         // we're only concerned with published posts
2893         if ( $post->post_status != 'publish' || $post->post_type != 'post' )
2894                 return $post_id;
2895
2896         // only bother if the slug has changed
2897         if ( $post->post_name == $_POST['wp-old-slug'] )
2898                 return $post_id;
2899
2900         $old_slugs = (array) get_post_meta($post_id, '_wp_old_slug');
2901
2902         // if we haven't added this old slug before, add it now
2903         if ( !count($old_slugs) || !in_array($_POST['wp-old-slug'], $old_slugs) )
2904                 add_post_meta($post_id, '_wp_old_slug', $_POST['wp-old-slug']);
2905
2906         // if the new slug was used previously, delete it from the list
2907         if ( in_array($post->post_name, $old_slugs) )
2908                 delete_post_meta($post_id, '_wp_old_slug', $post->post_name);
2909
2910         return $post_id;
2911 }
2912
2913 /**
2914  * Retrieve the private post SQL based on capability.
2915  *
2916  * This function provides a standardized way to appropriately select on the
2917  * post_status of posts/pages. The function will return a piece of SQL code that
2918  * can be added to a WHERE clause; this SQL is constructed to allow all
2919  * published posts, and all private posts to which the user has access.
2920  *
2921  * It also allows plugins that define their own post type to control the cap by
2922  * using the hook 'pub_priv_sql_capability'. The plugin is expected to return
2923  * the capability the user must have to read the private post type.
2924  *
2925  * @since 2.2.0
2926  *
2927  * @uses $user_ID
2928  * @uses apply_filters() Call 'pub_priv_sql_capability' filter for plugins with different post types.
2929  *
2930  * @param string $post_type currently only supports 'post' or 'page'.
2931  * @return string SQL code that can be added to a where clause.
2932  */
2933 function get_private_posts_cap_sql($post_type) {
2934         global $user_ID;
2935         $cap = '';
2936
2937         // Private posts
2938         if ($post_type == 'post') {
2939                 $cap = 'read_private_posts';
2940         // Private pages
2941         } elseif ($post_type == 'page') {
2942                 $cap = 'read_private_pages';
2943         // Dunno what it is, maybe plugins have their own post type?
2944         } else {
2945                 $cap = apply_filters('pub_priv_sql_capability', $cap);
2946
2947                 if (empty($cap)) {
2948                         // We don't know what it is, filters don't change anything,
2949                         // so set the SQL up to return nothing.
2950                         return '1 = 0';
2951                 }
2952         }
2953
2954         $sql = '(post_status = \'publish\'';
2955
2956         if (current_user_can($cap)) {
2957                 // Does the user have the capability to view private posts? Guess so.
2958                 $sql .= ' OR post_status = \'private\'';
2959         } elseif (is_user_logged_in()) {
2960                 // Users can view their own private posts.
2961                 $sql .= ' OR post_status = \'private\' AND post_author = \'' . $user_ID . '\'';
2962         }
2963
2964         $sql .= ')';
2965
2966         return $sql;
2967 }
2968
2969 /**
2970  * Retrieve the date the the last post was published.
2971  *
2972  * The server timezone is the default and is the difference between GMT and
2973  * server time. The 'blog' value is the date when the last post was posted. The
2974  * 'gmt' is when the last post was posted in GMT formatted date.
2975  *
2976  * @since 0.71
2977  *
2978  * @uses $wpdb
2979  * @uses $blog_id
2980  * @uses apply_filters() Calls 'get_lastpostdate' filter
2981  *
2982  * @global mixed $cache_lastpostdate Stores the last post date
2983  * @global mixed $pagenow The current page being viewed
2984  *
2985  * @param string $timezone The location to get the time. Can be 'gmt', 'blog', or 'server'.
2986  * @return string The date of the last post.
2987  */
2988 function get_lastpostdate($timezone = 'server') {
2989         global $cache_lastpostdate, $wpdb, $blog_id;
2990         $add_seconds_server = date('Z');
2991         if ( !isset($cache_lastpostdate[$blog_id][$timezone]) ) {
2992                 switch(strtolower($timezone)) {
2993                         case 'gmt':
2994                                 $lastpostdate = $wpdb->get_var("SELECT post_date_gmt FROM $wpdb->posts WHERE post_status = 'publish' AND post_type = 'post' ORDER BY post_date_gmt DESC LIMIT 1");
2995                                 break;
2996                         case 'blog':
2997                                 $lastpostdate = $wpdb->get_var("SELECT post_date FROM $wpdb->posts WHERE post_status = 'publish' AND post_type = 'post' ORDER BY post_date_gmt DESC LIMIT 1");
2998                                 break;
2999                         case 'server':
3000                                 $lastpostdate = $wpdb->get_var("SELECT DATE_ADD(post_date_gmt, INTERVAL '$add_seconds_server' SECOND) FROM $wpdb->posts WHERE post_status = 'publish' AND post_type = 'post' ORDER BY post_date_gmt DESC LIMIT 1");
3001                                 break;
3002                 }
3003                 $cache_lastpostdate[$blog_id][$timezone] = $lastpostdate;
3004         } else {
3005                 $lastpostdate = $cache_lastpostdate[$blog_id][$timezone];
3006         }
3007         return apply_filters( 'get_lastpostdate', $lastpostdate, $timezone );
3008 }
3009
3010 /**
3011  * Retrieve last post modified date depending on timezone.
3012  *
3013  * The server timezone is the default and is the difference between GMT and
3014  * server time. The 'blog' value is just when the last post was modified. The
3015  * 'gmt' is when the last post was modified in GMT time.
3016  *
3017  * @since 1.2.0
3018  * @uses $wpdb
3019  * @uses $blog_id
3020  * @uses apply_filters() Calls 'get_lastpostmodified' filter
3021  *
3022  * @global mixed $cache_lastpostmodified Stores the date the last post was modified
3023  *
3024  * @param string $timezone The location to get the time. Can be 'gmt', 'blog', or 'server'.
3025  * @return string The date the post was last modified.
3026  */
3027 function get_lastpostmodified($timezone = 'server') {
3028         global $cache_lastpostmodified, $wpdb, $blog_id;
3029         $add_seconds_server = date('Z');
3030         if ( !isset($cache_lastpostmodified[$blog_id][$timezone]) ) {
3031                 switch(strtolower($timezone)) {
3032                         case 'gmt':
3033                                 $lastpostmodified = $wpdb->get_var("SELECT post_modified_gmt FROM $wpdb->posts WHERE post_status = 'publish' AND post_type = 'post' ORDER BY post_modified_gmt DESC LIMIT 1");
3034                                 break;
3035                         case 'blog':
3036                                 $lastpostmodified = $wpdb->get_var("SELECT post_modified FROM $wpdb->posts WHERE post_status = 'publish' AND post_type = 'post' ORDER BY post_modified_gmt DESC LIMIT 1");
3037                                 break;
3038                         case 'server':
3039                                 $lastpostmodified = $wpdb->get_var("SELECT DATE_ADD(post_modified_gmt, INTERVAL '$add_seconds_server' SECOND) FROM $wpdb->posts WHERE post_status = 'publish' AND post_type = 'post' ORDER BY post_modified_gmt DESC LIMIT 1");
3040                                 break;
3041                 }
3042                 $lastpostdate = get_lastpostdate($timezone);
3043                 if ( $lastpostdate > $lastpostmodified ) {
3044                         $lastpostmodified = $lastpostdate;
3045                 }
3046                 $cache_lastpostmodified[$blog_id][$timezone] = $lastpostmodified;
3047         } else {
3048                 $lastpostmodified = $cache_lastpostmodified[$blog_id][$timezone];
3049         }
3050         return apply_filters( 'get_lastpostmodified', $lastpostmodified, $timezone );
3051 }
3052
3053 /**
3054  * Updates posts in cache.
3055  *
3056  * @usedby update_page_cache() Aliased by this function.
3057  *
3058  * @package WordPress
3059  * @subpackage Cache
3060  * @since 1.5.1
3061  *
3062  * @param array $posts Array of post objects
3063  */
3064 function update_post_cache(&$posts) {
3065         if ( !$posts )
3066                 return;
3067
3068         foreach ( $posts as $post )
3069                 wp_cache_add($post->ID, $post, 'posts');
3070 }
3071
3072 /**
3073  * Will clean the post in the cache.
3074  *
3075  * Cleaning means delete from the cache of the post. Will call to clean the term
3076  * object cache associated with the post ID.
3077  *
3078  * clean_post_cache() will call itself recursively for each child post.
3079  *
3080  * This function not run if $_wp_suspend_cache_invalidation is not empty. See
3081  * wp_suspend_cache_invalidation().
3082  *
3083  * @package WordPress
3084  * @subpackage Cache
3085  * @since 2.0.0
3086  *
3087  * @uses do_action() Calls 'clean_post_cache' on $id before adding children (if any).
3088  *
3089  * @param int $id The Post ID in the cache to clean
3090  */
3091 function clean_post_cache($id) {
3092         global $_wp_suspend_cache_invalidation, $wpdb;
3093
3094         if ( !empty($_wp_suspend_cache_invalidation) )
3095                 return;
3096
3097         $id = (int) $id;
3098
3099         wp_cache_delete($id, 'posts');
3100         wp_cache_delete($id, 'post_meta');
3101
3102         clean_object_term_cache($id, 'post');
3103
3104         wp_cache_delete( 'wp_get_archives', 'general' );
3105
3106         do_action('clean_post_cache', $id);
3107
3108         if ( $children = $wpdb->get_col( $wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE post_parent = %d", $id) ) ) {
3109                 foreach( $children as $cid )
3110                         clean_post_cache( $cid );
3111         }
3112 }
3113
3114 /**
3115  * Alias of update_post_cache().
3116  *
3117  * @see update_post_cache() Posts and pages are the same, alias is intentional
3118  *
3119  * @package WordPress
3120  * @subpackage Cache
3121  * @since 1.5.1
3122  *
3123  * @param array $pages list of page objects
3124  */
3125 function update_page_cache(&$pages) {
3126         update_post_cache($pages);
3127 }
3128
3129 /**
3130  * Will clean the page in the cache.
3131  *
3132  * Clean (read: delete) page from cache that matches $id. Will also clean cache
3133  * associated with 'all_page_ids' and 'get_pages'.
3134  *
3135  * @package WordPress
3136  * @subpackage Cache
3137  * @since 2.0.0
3138  *
3139  * @uses do_action() Will call the 'clean_page_cache' hook action.
3140  *
3141  * @param int $id Page ID to clean
3142  */
3143 function clean_page_cache($id) {
3144         clean_post_cache($id);
3145
3146         wp_cache_delete( 'all_page_ids', 'posts' );
3147         wp_cache_delete( 'get_pages', 'posts' );
3148
3149         do_action('clean_page_cache', $id);
3150 }
3151
3152 /**
3153  * Call major cache updating functions for list of Post objects.
3154  *
3155  * @package WordPress
3156  * @subpackage Cache
3157  * @since 1.5.0
3158  *
3159  * @uses $wpdb
3160  * @uses update_post_cache()
3161  * @uses update_object_term_cache()
3162  * @uses update_postmeta_cache()
3163  *
3164  * @param array $posts Array of Post objects
3165  */
3166 function update_post_caches(&$posts) {
3167         // No point in doing all this work if we didn't match any posts.
3168         if ( !$posts )
3169                 return;
3170
3171         update_post_cache($posts);
3172
3173         $post_ids = array();
3174
3175         for ($i = 0; $i < count($posts); $i++)
3176                 $post_ids[] = $posts[$i]->ID;
3177
3178         update_object_term_cache($post_ids, 'post');
3179
3180         update_postmeta_cache($post_ids);
3181 }
3182
3183 /**
3184  * Updates metadata cache for list of post IDs.
3185  *
3186  * Performs SQL query to retrieve the metadata for the post IDs and updates the
3187  * metadata cache for the posts. Therefore, the functions, which call this
3188  * function, do not need to perform SQL queries on their own.
3189  *
3190  * @package WordPress
3191  * @subpackage Cache
3192  * @since 2.1.0
3193  *
3194  * @uses $wpdb
3195  *
3196  * @param array $post_ids List of post IDs.
3197  * @return bool|array Returns false if there is nothing to update or an array of metadata.
3198  */
3199 function update_postmeta_cache($post_ids) {
3200         global $wpdb;
3201
3202         if ( empty( $post_ids ) )
3203                 return false;
3204
3205         if ( !is_array($post_ids) ) {
3206                 $post_ids = preg_replace('|[^0-9,]|', '', $post_ids);
3207                 $post_ids = explode(',', $post_ids);
3208         }
3209
3210         $post_ids = array_map('intval', $post_ids);
3211
3212         $ids = array();
3213         foreach ( (array) $post_ids as $id ) {
3214                 if ( false === wp_cache_get($id, 'post_meta') )
3215                         $ids[] = $id;
3216         }
3217
3218         if ( empty( $ids ) )
3219                 return false;
3220
3221         // Get post-meta info
3222         $id_list = join(',', $ids);
3223         $cache = array();
3224         if ( $meta_list = $wpdb->get_results("SELECT post_id, meta_key, meta_value FROM $wpdb->postmeta WHERE post_id IN ($id_list)", ARRAY_A) ) {
3225                 foreach ( (array) $meta_list as $metarow) {
3226                         $mpid = (int) $metarow['post_id'];
3227                         $mkey = $metarow['meta_key'];
3228                         $mval = $metarow['meta_value'];
3229
3230                         // Force subkeys to be array type:
3231                         if ( !isset($cache[$mpid]) || !is_array($cache[$mpid]) )
3232                                 $cache[$mpid] = array();
3233                         if ( !isset($cache[$mpid][$mkey]) || !is_array($cache[$mpid][$mkey]) )
3234                                 $cache[$mpid][$mkey] = array();
3235
3236                         // Add a value to the current pid/key:
3237                         $cache[$mpid][$mkey][] = $mval;
3238                 }
3239         }
3240
3241         foreach ( (array) $ids as $id ) {
3242                 if ( ! isset($cache[$id]) )
3243                         $cache[$id] = array();
3244         }
3245
3246         foreach ( (array) array_keys($cache) as $post)
3247                 wp_cache_set($post, $cache[$post], 'post_meta');
3248
3249         return $cache;
3250 }
3251
3252 //
3253 // Hooks
3254 //
3255
3256 /**
3257  * Hook for managing future post transitions to published.
3258  *
3259  * @since 2.3.0
3260  * @access private
3261  * @uses $wpdb
3262  * @uses do_action() Calls 'private_to_published' on post ID if this is a 'private_to_published' call.
3263  * @uses wp_clear_scheduled_hook() with 'publish_future_post' and post ID.
3264  *
3265  * @param string $new_status New post status
3266  * @param string $old_status Previous post status
3267  * @param object $post Object type containing the post information
3268  */
3269 function _transition_post_status($new_status, $old_status, $post) {
3270         global $wpdb;
3271
3272         if ( $old_status != 'publish' && $new_status == 'publish' ) {
3273                 // Reset GUID if transitioning to publish and it is empty
3274                 if ( '' == get_the_guid($post->ID) )
3275                         $wpdb->update( $wpdb->posts, array( 'guid' => get_permalink( $post->ID ) ), array( 'ID' => $post->ID ) );
3276                 do_action('private_to_published', $post->ID);  // Deprecated, use private_to_publish
3277                 // do generic pings once per hour at most
3278                 if ( !wp_next_scheduled('do_generic_ping') )
3279                         wp_schedule_single_event(time() + 3600, 'do_generic_ping');
3280         }
3281
3282         // Always clears the hook in case the post status bounced from future to draft.
3283         wp_clear_scheduled_hook('publish_future_post', $post->ID);
3284 }
3285
3286 /**
3287  * Hook used to schedule publication for a post marked for the future.
3288  *
3289  * The $post properties used and must exist are 'ID' and 'post_date_gmt'.
3290  *
3291  * @since 2.3.0
3292  * @access private
3293  *
3294  * @param int $deprecated Not Used. Can be set to null.
3295  * @param object $post Object type containing the post information
3296  */
3297 function _future_post_hook($deprecated = '', $post) {
3298         wp_clear_scheduled_hook( 'publish_future_post', $post->ID );
3299         wp_schedule_single_event(strtotime($post->post_date_gmt. ' GMT'), 'publish_future_post', array($post->ID));
3300 }
3301
3302 /**
3303  * Hook to schedule pings and enclosures when a post is published.
3304  *
3305  * @since 2.3.0
3306  * @access private
3307  * @uses $wpdb
3308  * @uses XMLRPC_REQUEST and APP_REQUEST constants.
3309  * @uses do_action() Calls 'xmlprc_publish_post' on post ID if XMLRPC_REQUEST is defined.
3310  * @uses do_action() Calls 'app_publish_post' on post ID if APP_REQUEST is defined.
3311  *
3312  * @param int $post_id The ID in the database table of the post being published
3313  */
3314 function _publish_post_hook($post_id) {
3315         global $wpdb;
3316
3317         if ( defined('XMLRPC_REQUEST') )
3318                 do_action('xmlrpc_publish_post', $post_id);
3319         if ( defined('APP_REQUEST') )
3320                 do_action('app_publish_post', $post_id);
3321
3322         if ( defined('WP_IMPORTING') )
3323                 return;
3324
3325         $data = array( 'post_id' => $post_id, 'meta_value' => '1' );
3326         if ( get_option('default_pingback_flag') )
3327                 $wpdb->insert( $wpdb->postmeta, $data + array( 'meta_key' => '_pingme' ) );
3328         $wpdb->insert( $wpdb->postmeta, $data + array( 'meta_key' => '_encloseme' ) );
3329         wp_schedule_single_event(time(), 'do_pings');
3330 }
3331
3332 /**
3333  * Hook used to prevent page/post cache and rewrite rules from staying dirty.
3334  *
3335  * Does two things. If the post is a page and has a template then it will
3336  * update/add that template to the meta. For both pages and posts, it will clean
3337  * the post cache to make sure that the cache updates to the changes done
3338  * recently. For pages, the rewrite rules of WordPress are flushed to allow for
3339  * any changes.
3340  *
3341  * The $post parameter, only uses 'post_type' property and 'page_template'
3342  * property.
3343  *
3344  * @since 2.3.0
3345  * @access private
3346  * @uses $wp_rewrite Flushes Rewrite Rules.
3347  *
3348  * @param int $post_id The ID in the database table for the $post
3349  * @param object $post Object type containing the post information
3350  */
3351 function _save_post_hook($post_id, $post) {
3352         if ( $post->post_type == 'page' ) {
3353                 clean_page_cache($post_id);
3354                 // Avoid flushing rules for every post during import.
3355                 if ( !defined('WP_IMPORTING') ) {
3356                         global $wp_rewrite;
3357                         $wp_rewrite->flush_rules(false);
3358                 }
3359         } else {
3360                 clean_post_cache($post_id);
3361         }
3362 }
3363
3364 /**
3365  * Retrieve post ancestors and append to post ancestors property.
3366  *
3367  * Will only retrieve ancestors once, if property is already set, then nothing
3368  * will be done. If there is not a parent post, or post ID and post parent ID
3369  * are the same then nothing will be done.
3370  *
3371  * The parameter is passed by reference, so nothing needs to be returned. The
3372  * property will be updated and can be referenced after the function is
3373  * complete. The post parent will be an ancestor and the parent of the post
3374  * parent will be an ancestor. There will only be two ancestors at the most.
3375  *
3376  * @since unknown
3377  * @access private
3378  * @uses $wpdb
3379  *
3380  * @param object $_post Post data.
3381  * @return null When nothing needs to be done.
3382  */
3383 function _get_post_ancestors(&$_post) {
3384         global $wpdb;
3385
3386         if ( isset($_post->ancestors) )
3387                 return;
3388
3389         $_post->ancestors = array();
3390
3391         if ( empty($_post->post_parent) || $_post->ID == $_post->post_parent )
3392                 return;
3393
3394         $id = $_post->ancestors[] = $_post->post_parent;
3395         while ( $ancestor = $wpdb->get_var( $wpdb->prepare("SELECT `post_parent` FROM $wpdb->posts WHERE ID = %d LIMIT 1", $id) ) ) {
3396                 if ( $id == $ancestor )
3397                         break;
3398                 $id = $_post->ancestors[] = $ancestor;
3399         }
3400 }
3401
3402 /**
3403  * Determines which fields of posts are to be saved in revisions.
3404  *
3405  * Does two things. If passed a post *array*, it will return a post array ready
3406  * to be insterted into the posts table as a post revision. Otherwise, returns
3407  * an array whose keys are the post fields to be saved for post revisions.
3408  *
3409  * @package WordPress
3410  * @subpackage Post_Revisions
3411  * @since 2.6.0
3412  * @access private
3413  * @uses apply_filters() Calls '_wp_post_revision_fields' on 'title', 'content' and 'excerpt' fields.
3414  *
3415  * @param array $post Optional a post array to be processed for insertion as a post revision.
3416  * @param bool $autosave optional Is the revision an autosave?
3417  * @return array Post array ready to be inserted as a post revision or array of fields that can be versioned.
3418  */
3419 function _wp_post_revision_fields( $post = null, $autosave = false ) {
3420         static $fields = false;
3421
3422         if ( !$fields ) {
3423                 // Allow these to be versioned
3424                 $fields = array(
3425                         'post_title' => __( 'Title' ),
3426                         'post_content' => __( 'Content' ),
3427                         'post_excerpt' => __( 'Excerpt' ),
3428                 );
3429
3430                 // Runs only once
3431                 $fields = apply_filters( '_wp_post_revision_fields', $fields );
3432
3433                 // WP uses these internally either in versioning or elsewhere - they cannot be versioned
3434                 foreach ( array( 'ID', 'post_name', 'post_parent', 'post_date', 'post_date_gmt', 'post_status', 'post_type', 'comment_count', 'post_author' ) as $protect )
3435                         unset( $fields[$protect] );
3436         }
3437
3438         if ( !is_array($post) )
3439                 return $fields;
3440
3441         $return = array();
3442         foreach ( array_intersect( array_keys( $post ), array_keys( $fields ) ) as $field )
3443                 $return[$field] = $post[$field];
3444
3445         $return['post_parent']   = $post['ID'];
3446         $return['post_status']   = 'inherit';
3447         $return['post_type']     = 'revision';
3448         $return['post_name']     = $autosave ? "$post[ID]-autosave" : "$post[ID]-revision";
3449         $return['post_date']     = isset($post['post_modified']) ? $post['post_modified'] : '';
3450         $return['post_date_gmt'] = isset($post['post_modified_gmt']) ? $post['post_modified_gmt'] : '';
3451
3452         return $return;
3453 }
3454
3455 /**
3456  * Saves an already existing post as a post revision.
3457  *
3458  * Typically used immediately prior to post updates.
3459  *
3460  * @package WordPress
3461  * @subpackage Post_Revisions
3462  * @since 2.6.0
3463  *
3464  * @uses _wp_put_post_revision()
3465  *
3466  * @param int $post_id The ID of the post to save as a revision.
3467  * @return mixed Null or 0 if error, new revision ID, if success.
3468  */
3469 function wp_save_post_revision( $post_id ) {
3470         // We do autosaves manually with wp_create_post_autosave()
3471         if ( @constant( 'DOING_AUTOSAVE' ) )
3472                 return;
3473
3474         // WP_POST_REVISIONS = 0, false
3475         if ( !constant('WP_POST_REVISIONS') )
3476                 return;
3477
3478         if ( !$post = get_post( $post_id, ARRAY_A ) )
3479                 return;
3480
3481         if ( !in_array( $post['post_type'], array( 'post', 'page' ) ) )
3482                 return;
3483
3484         $return = _wp_put_post_revision( $post );
3485
3486         // WP_POST_REVISIONS = true (default), -1
3487         if ( !is_numeric( WP_POST_REVISIONS ) || WP_POST_REVISIONS < 0 )
3488                 return $return;
3489
3490         // all revisions and (possibly) one autosave
3491         $revisions = wp_get_post_revisions( $post_id, array( 'order' => 'ASC' ) );
3492
3493         // WP_POST_REVISIONS = (int) (# of autasaves to save)
3494         $delete = count($revisions) - WP_POST_REVISIONS;
3495
3496         if ( $delete < 1 )
3497                 return $return;
3498
3499         $revisions = array_slice( $revisions, 0, $delete );
3500
3501         for ( $i = 0; isset($revisions[$i]); $i++ ) {
3502                 if ( false !== strpos( $revisions[$i]->post_name, 'autosave' ) )
3503                         continue;
3504                 wp_delete_post_revision( $revisions[$i]->ID );
3505         }
3506
3507         return $return;
3508 }
3509
3510 /**
3511  * Retrieve the autosaved data of the specified post.
3512  *
3513  * Returns a post object containing the information that was autosaved for the
3514  * specified post.
3515  *
3516  * @package WordPress
3517  * @subpackage Post_Revisions
3518  * @since 2.6.0
3519  *
3520  * @param int $post_id The post ID.
3521  * @return object|bool The autosaved data or false on failure or when no autosave exists.
3522  */
3523 function wp_get_post_autosave( $post_id ) {
3524
3525         if ( !$post = get_post( $post_id ) )
3526                 return false;
3527
3528         $q = array(
3529                 'name' => "{$post->ID}-autosave",
3530                 'post_parent' => $post->ID,
3531                 'post_type' => 'revision',
3532                 'post_status' => 'inherit'
3533         );
3534
3535         // Use WP_Query so that the result gets cached
3536         $autosave_query = new WP_Query;
3537
3538         add_action( 'parse_query', '_wp_get_post_autosave_hack' );
3539         $autosave = $autosave_query->query( $q );
3540         remove_action( 'parse_query', '_wp_get_post_autosave_hack' );
3541
3542         if ( $autosave && is_array($autosave) && is_object($autosave[0]) )
3543                 return $autosave[0];
3544
3545         return false;
3546 }
3547
3548 /**
3549  * Internally used to hack WP_Query into submission.
3550  *
3551  * @package WordPress
3552  * @subpackage Post_Revisions
3553  * @since 2.6.0
3554  *
3555  * @param object $query WP_Query object
3556  */
3557 function _wp_get_post_autosave_hack( $query ) {
3558         $query->is_single = false;
3559 }
3560
3561 /**
3562  * Determines if the specified post is a revision.
3563  *
3564  * @package WordPress
3565  * @subpackage Post_Revisions
3566  * @since 2.6.0
3567  *
3568  * @param int|object $post Post ID or post object.
3569  * @return bool|int False if not a revision, ID of revision's parent otherwise.
3570  */
3571 function wp_is_post_revision( $post ) {
3572         if ( !$post = wp_get_post_revision( $post ) )
3573                 return false;
3574         return (int) $post->post_parent;
3575 }
3576
3577 /**
3578  * Determines if the specified post is an autosave.
3579  *
3580  * @package WordPress
3581  * @subpackage Post_Revisions
3582  * @since 2.6.0
3583  *
3584  * @param int|object $post Post ID or post object.
3585  * @return bool|int False if not a revision, ID of autosave's parent otherwise
3586  */
3587 function wp_is_post_autosave( $post ) {
3588         if ( !$post = wp_get_post_revision( $post ) )
3589                 return false;
3590         if ( "{$post->post_parent}-autosave" !== $post->post_name )
3591                 return false;
3592         return (int) $post->post_parent;
3593 }
3594
3595 /**
3596  * Inserts post data into the posts table as a post revision.
3597  *
3598  * @package WordPress
3599  * @subpackage Post_Revisions
3600  * @since 2.6.0
3601  *
3602  * @uses wp_insert_post()
3603  *
3604  * @param int|object|array $post Post ID, post object OR post array.
3605  * @param bool $autosave Optional. Is the revision an autosave?
3606  * @return mixed Null or 0 if error, new revision ID if success.
3607  */
3608 function _wp_put_post_revision( $post = null, $autosave = false ) {
3609         if ( is_object($post) )
3610                 $post = get_object_vars( $post );
3611         elseif ( !is_array($post) )
3612                 $post = get_post($post, ARRAY_A);
3613         if ( !$post || empty($post['ID']) )
3614                 return;
3615
3616         if ( isset($post['post_type']) && 'revision' == $post['post_type'] )
3617                 return new WP_Error( 'post_type', __( 'Cannot create a revision of a revision' ) );
3618
3619         $post = _wp_post_revision_fields( $post, $autosave );
3620         $post = add_magic_quotes($post); //since data is from db
3621
3622         $revision_id = wp_insert_post( $post );
3623         if ( is_wp_error($revision_id) )
3624                 return $revision_id;
3625
3626         if ( $revision_id )
3627                 do_action( '_wp_put_post_revision', $revision_id );
3628         return $revision_id;
3629 }
3630
3631 /**
3632  * Gets a post revision.
3633  *
3634  * @package WordPress
3635  * @subpackage Post_Revisions
3636  * @since 2.6.0
3637  *
3638  * @uses get_post()
3639  *
3640  * @param int|object $post Post ID or post object
3641  * @param string $output Optional. OBJECT, ARRAY_A, or ARRAY_N.
3642  * @param string $filter Optional sanitation filter.  @see sanitize_post()
3643  * @return mixed Null if error or post object if success
3644  */
3645 function &wp_get_post_revision(&$post, $output = OBJECT, $filter = 'raw') {
3646         $null = null;
3647         if ( !$revision = get_post( $post, OBJECT, $filter ) )
3648                 return $revision;
3649         if ( 'revision' !== $revision->post_type )
3650                 return $null;
3651
3652         if ( $output == OBJECT ) {
3653                 return $revision;
3654         } elseif ( $output == ARRAY_A ) {
3655                 $_revision = get_object_vars($revision);
3656                 return $_revision;
3657         } elseif ( $output == ARRAY_N ) {
3658                 $_revision = array_values(get_object_vars($revision));
3659                 return $_revision;
3660         }
3661
3662         return $revision;
3663 }
3664
3665 /**
3666  * Restores a post to the specified revision.
3667  *
3668  * Can restore a past revision using all fields of the post revision, or only selected fields.
3669  *
3670  * @package WordPress
3671  * @subpackage Post_Revisions
3672  * @since 2.6.0
3673  *
3674  * @uses wp_get_post_revision()
3675  * @uses wp_update_post()
3676  * @uses do_action() Calls 'wp_restore_post_revision' on post ID and revision ID if wp_update_post()
3677  *  is successful.
3678  *
3679  * @param int|object $revision_id Revision ID or revision object.
3680  * @param array $fields Optional. What fields to restore from. Defaults to all.
3681  * @return mixed Null if error, false if no fields to restore, (int) post ID if success.
3682  */
3683 function wp_restore_post_revision( $revision_id, $fields = null ) {
3684         if ( !$revision = wp_get_post_revision( $revision_id, ARRAY_A ) )
3685                 return $revision;
3686
3687         if ( !is_array( $fields ) )
3688                 $fields = array_keys( _wp_post_revision_fields() );
3689
3690         $update = array();
3691         foreach( array_intersect( array_keys( $revision ), $fields ) as $field )
3692                 $update[$field] = $revision[$field];
3693
3694         if ( !$update )
3695                 return false;
3696
3697         $update['ID'] = $revision['post_parent'];
3698
3699         $update = add_magic_quotes( $update ); //since data is from db
3700
3701         $post_id = wp_update_post( $update );
3702         if ( is_wp_error( $post_id ) )
3703                 return $post_id;
3704
3705         if ( $post_id )
3706                 do_action( 'wp_restore_post_revision', $post_id, $revision['ID'] );
3707
3708         return $post_id;
3709 }
3710
3711 /**
3712  * Deletes a revision.
3713  *
3714  * Deletes the row from the posts table corresponding to the specified revision.
3715  *
3716  * @package WordPress
3717  * @subpackage Post_Revisions
3718  * @since 2.6.0
3719  *
3720  * @uses wp_get_post_revision()
3721  * @uses wp_delete_post()
3722  *
3723  * @param int|object $revision_id Revision ID or revision object.
3724  * @param array $fields Optional. What fields to restore from.  Defaults to all.
3725  * @return mixed Null if error, false if no fields to restore, (int) post ID if success.
3726  */
3727 function wp_delete_post_revision( $revision_id ) {
3728         if ( !$revision = wp_get_post_revision( $revision_id ) )
3729                 return $revision;
3730
3731         $delete = wp_delete_post( $revision->ID );
3732         if ( is_wp_error( $delete ) )
3733                 return $delete;
3734
3735         if ( $delete )
3736                 do_action( 'wp_delete_post_revision', $revision->ID, $revision );
3737
3738         return $delete;
3739 }
3740
3741 /**
3742  * Returns all revisions of specified post.
3743  *
3744  * @package WordPress
3745  * @subpackage Post_Revisions
3746  * @since 2.6.0
3747  *
3748  * @uses get_children()
3749  *
3750  * @param int|object $post_id Post ID or post object
3751  * @return array empty if no revisions
3752  */
3753 function wp_get_post_revisions( $post_id = 0, $args = null ) {
3754         if ( !constant('WP_POST_REVISIONS') )
3755                 return array();
3756         if ( ( !$post = get_post( $post_id ) ) || empty( $post->ID ) )
3757                 return array();
3758
3759         $defaults = array( 'order' => 'DESC', 'orderby' => 'date' );
3760         $args = wp_parse_args( $args, $defaults );
3761         $args = array_merge( $args, array( 'post_parent' => $post->ID, 'post_type' => 'revision', 'post_status' => 'inherit' ) );
3762
3763         if ( !$revisions = get_children( $args ) )
3764                 return array();
3765         return $revisions;
3766 }
3767
3768 function _set_preview($post) {
3769
3770         if ( ! is_object($post) )
3771                 return $post;
3772
3773         $preview = wp_get_post_autosave($post->ID);
3774
3775         if ( ! is_object($preview) )
3776                 return $post;
3777
3778         $preview = sanitize_post($preview);
3779
3780         $post->post_content = $preview->post_content;
3781         $post->post_title = $preview->post_title;
3782         $post->post_excerpt = $preview->post_excerpt;
3783
3784         return $post;
3785 }
3786
3787 function _show_post_preview() {
3788
3789         if ( isset($_GET['preview_id']) && isset($_GET['preview_nonce']) ) {
3790                 $id = (int) $_GET['preview_id'];
3791
3792                 if ( false == wp_verify_nonce( $_GET['preview_nonce'], 'post_preview_' . $id ) )
3793                         wp_die( __('You do not have permission to preview drafts.') );
3794
3795                 add_filter('the_preview', '_set_preview');
3796         }
3797 }