Projects : mp-wp : mp-wp_svg-screenshots-and-errorreporting-r2

mp-wp/wp-includes/post.php

Dir - Raw

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