-
+ 3DD810BFA384766F87C0F0E679841B0DBD923EBC85CA0316BB314C574042CDE2330C91FC7350DABA4665896719822282DE2E961DBD35FF331F5B6090A4F28AE6
mp-wp/wp-includes/post.php
(0 . 0)(1 . 3623)
141137 <?php
141138 /**
141139 * Post functions and post utility function.
141140 *
141141 * @package WordPress
141142 * @subpackage Post
141143 * @since 1.5.0
141144 */
141145
141146 /**
141147 * Retrieve attached file path based on attachment ID.
141148 *
141149 * You can optionally send it through the 'get_attached_file' filter, but by
141150 * default it will just return the file path unfiltered.
141151 *
141152 * The function works by getting the single post meta name, named
141153 * '_wp_attached_file' and returning it. This is a convenience function to
141154 * prevent looking up the meta name and provide a mechanism for sending the
141155 * attached filename through a filter.
141156 *
141157 * @since 2.0.0
141158 * @uses apply_filters() Calls 'get_attached_file' on file path and attachment ID.
141159 *
141160 * @param int $attachment_id Attachment ID.
141161 * @param bool $unfiltered Whether to apply filters or not.
141162 * @return string The file path to the attached file.
141163 */
141164 function get_attached_file( $attachment_id, $unfiltered = false ) {
141165 $file = get_post_meta( $attachment_id, '_wp_attached_file', true );
141166 // If the file is relative, prepend upload dir
141167 if ( 0 !== strpos($file, '/') && !preg_match('|^.:\\\|', $file) && ( ($uploads = wp_upload_dir()) && false === $uploads['error'] ) )
141168 $file = $uploads['basedir'] . "/$file";
141169 if ( $unfiltered )
141170 return $file;
141171 return apply_filters( 'get_attached_file', $file, $attachment_id );
141172 }
141173
141174 /**
141175 * Update attachment file path based on attachment ID.
141176 *
141177 * Used to update the file path of the attachment, which uses post meta name
141178 * '_wp_attached_file' to store the path of the attachment.
141179 *
141180 * @since 2.1.0
141181 * @uses apply_filters() Calls 'update_attached_file' on file path and attachment ID.
141182 *
141183 * @param int $attachment_id Attachment ID
141184 * @param string $file File path for the attachment
141185 * @return bool False on failure, true on success.
141186 */
141187 function update_attached_file( $attachment_id, $file ) {
141188 if ( !get_post( $attachment_id ) )
141189 return false;
141190
141191 $file = apply_filters( 'update_attached_file', $file, $attachment_id );
141192
141193 // Make the file path relative to the upload dir
141194 if ( ($uploads = wp_upload_dir()) && false === $uploads['error'] ) { // Get upload directory
141195 if ( 0 === strpos($file, $uploads['basedir']) ) {// Check that the upload base exists in the file path
141196 $file = str_replace($uploads['basedir'], '', $file); // Remove upload dir from the file path
141197 $file = ltrim($file, '/');
141198 }
141199 }
141200
141201 return update_post_meta( $attachment_id, '_wp_attached_file', $file );
141202 }
141203
141204 /**
141205 * Retrieve all children of the post parent ID.
141206 *
141207 * Normally, without any enhancements, the children would apply to pages. In the
141208 * context of the inner workings of WordPress, pages, posts, and attachments
141209 * share the same table, so therefore the functionality could apply to any one
141210 * of them. It is then noted that while this function does not work on posts, it
141211 * does not mean that it won't work on posts. It is recommended that you know
141212 * what context you wish to retrieve the children of.
141213 *
141214 * Attachments may also be made the child of a post, so if that is an accurate
141215 * statement (which needs to be verified), it would then be possible to get
141216 * all of the attachments for a post. Attachments have since changed since
141217 * version 2.5, so this is most likely unaccurate, but serves generally as an
141218 * example of what is possible.
141219 *
141220 * The arguments listed as defaults are for this function and also of the
141221 * {@link get_posts()} function. The arguments are combined with the
141222 * get_children defaults and are then passed to the {@link get_posts()}
141223 * function, which accepts additional arguments. You can replace the defaults in
141224 * this function, listed below and the additional arguments listed in the
141225 * {@link get_posts()} function.
141226 *
141227 * The 'post_parent' is the most important argument and important attention
141228 * needs to be paid to the $args parameter. If you pass either an object or an
141229 * integer (number), then just the 'post_parent' is grabbed and everything else
141230 * is lost. If you don't specify any arguments, then it is assumed that you are
141231 * in The Loop and the post parent will be grabbed for from the current post.
141232 *
141233 * The 'post_parent' argument is the ID to get the children. The 'numberposts'
141234 * is the amount of posts to retrieve that has a default of '-1', which is
141235 * used to get all of the posts. Giving a number higher than 0 will only
141236 * retrieve that amount of posts.
141237 *
141238 * The 'post_type' and 'post_status' arguments can be used to choose what
141239 * criteria of posts to retrieve. The 'post_type' can be anything, but WordPress
141240 * post types are 'post', 'pages', and 'attachments'. The 'post_status'
141241 * argument will accept any post status within the write administration panels.
141242 *
141243 * @see get_posts() Has additional arguments that can be replaced.
141244 * @internal Claims made in the long description might be inaccurate.
141245 *
141246 * @since 2.0.0
141247 *
141248 * @param mixed $args Optional. User defined arguments for replacing the defaults.
141249 * @param string $output Optional. Constant for return type, either OBJECT (default), ARRAY_A, ARRAY_N.
141250 * @return array|bool False on failure and the type will be determined by $output parameter.
141251 */
141252 function &get_children($args = '', $output = OBJECT) {
141253 if ( empty( $args ) ) {
141254 if ( isset( $GLOBALS['post'] ) ) {
141255 $args = array('post_parent' => (int) $GLOBALS['post']->post_parent );
141256 } else {
141257 return false;
141258 }
141259 } elseif ( is_object( $args ) ) {
141260 $args = array('post_parent' => (int) $args->post_parent );
141261 } elseif ( is_numeric( $args ) ) {
141262 $args = array('post_parent' => (int) $args);
141263 }
141264
141265 $defaults = array(
141266 'numberposts' => -1, 'post_type' => 'any',
141267 'post_status' => 'any', 'post_parent' => 0,
141268 );
141269
141270 $r = wp_parse_args( $args, $defaults );
141271
141272 $children = get_posts( $r );
141273 if ( !$children ) {
141274 $kids = false;
141275 return $kids;
141276 }
141277
141278 update_post_cache($children);
141279
141280 foreach ( $children as $key => $child )
141281 $kids[$child->ID] =& $children[$key];
141282
141283 if ( $output == OBJECT ) {
141284 return $kids;
141285 } elseif ( $output == ARRAY_A ) {
141286 foreach ( (array) $kids as $kid )
141287 $weeuns[$kid->ID] = get_object_vars($kids[$kid->ID]);
141288 return $weeuns;
141289 } elseif ( $output == ARRAY_N ) {
141290 foreach ( (array) $kids as $kid )
141291 $babes[$kid->ID] = array_values(get_object_vars($kids[$kid->ID]));
141292 return $babes;
141293 } else {
141294 return $kids;
141295 }
141296 }
141297
141298 /**
141299 * Get extended entry info (<!--more-->).
141300 *
141301 * There should not be any space after the second dash and before the word
141302 * 'more'. There can be text or space(s) after the word 'more', but won't be
141303 * referenced.
141304 *
141305 * The returned array has 'main' and 'extended' keys. Main has the text before
141306 * the <code><!--more--></code>. The 'extended' key has the content after the
141307 * <code><!--more--></code> comment.
141308 *
141309 * @since 1.0.0
141310 *
141311 * @param string $post Post content.
141312 * @return array Post before ('main') and after ('extended').
141313 */
141314 function get_extended($post) {
141315 //Match the new style more links
141316 if ( preg_match('/<!--more(.*?)?-->/', $post, $matches) ) {
141317 list($main, $extended) = explode($matches[0], $post, 2);
141318 } else {
141319 $main = $post;
141320 $extended = '';
141321 }
141322
141323 // Strip leading and trailing whitespace
141324 $main = preg_replace('/^[\s]*(.*)[\s]*$/', '\\1', $main);
141325 $extended = preg_replace('/^[\s]*(.*)[\s]*$/', '\\1', $extended);
141326
141327 return array('main' => $main, 'extended' => $extended);
141328 }
141329
141330 /**
141331 * Retrieves post data given a post ID or post object.
141332 *
141333 * See {@link sanitize_post()} for optional $filter values. Also, the parameter
141334 * $post, must be given as a variable, since it is passed by reference.
141335 *
141336 * @since 1.5.1
141337 * @uses $wpdb
141338 * @link http://codex.wordpress.org/Function_Reference/get_post
141339 *
141340 * @param int|object $post Post ID or post object.
141341 * @param string $output Optional, default is Object. Either OBJECT, ARRAY_A, or ARRAY_N.
141342 * @param string $filter Optional, default is raw.
141343 * @return mixed Post data
141344 */
141345 function &get_post(&$post, $output = OBJECT, $filter = 'raw') {
141346 global $wpdb;
141347 $null = null;
141348
141349 if ( empty($post) ) {
141350 if ( isset($GLOBALS['post']) )
141351 $_post = & $GLOBALS['post'];
141352 else
141353 return $null;
141354 } elseif ( is_object($post) ) {
141355 _get_post_ancestors($post);
141356 wp_cache_add($post->ID, $post, 'posts');
141357 $_post = &$post;
141358 } else {
141359 $post = (int) $post;
141360 if ( ! $_post = wp_cache_get($post, 'posts') ) {
141361 $_post = $wpdb->get_row($wpdb->prepare("SELECT * FROM $wpdb->posts WHERE ID = %d LIMIT 1", $post));
141362 if ( ! $_post )
141363 return $null;
141364 _get_post_ancestors($_post);
141365 wp_cache_add($_post->ID, $_post, 'posts');
141366 }
141367 }
141368
141369 $_post = sanitize_post($_post, $filter);
141370
141371 if ( $output == OBJECT ) {
141372 return $_post;
141373 } elseif ( $output == ARRAY_A ) {
141374 $__post = get_object_vars($_post);
141375 return $__post;
141376 } elseif ( $output == ARRAY_N ) {
141377 $__post = array_values(get_object_vars($_post));
141378 return $__post;
141379 } else {
141380 return $_post;
141381 }
141382 }
141383
141384 /**
141385 * Retrieve ancestors of a post.
141386 *
141387 * @since 2.5.0
141388 *
141389 * @param int|object $post Post ID or post object
141390 * @return array Ancestor IDs or empty array if none are found.
141391 */
141392 function get_post_ancestors($post) {
141393 $post = get_post($post);
141394
141395 if ( !empty($post->ancestors) )
141396 return $post->ancestors;
141397
141398 return array();
141399 }
141400
141401 /**
141402 * Retrieve data from a post field based on Post ID.
141403 *
141404 * Examples of the post field will be, 'post_type', 'post_status', 'content',
141405 * etc and based off of the post object property or key names.
141406 *
141407 * The context values are based off of the taxonomy filter functions and
141408 * supported values are found within those functions.
141409 *
141410 * @since 2.3.0
141411 * @uses sanitize_post_field() See for possible $context values.
141412 *
141413 * @param string $field Post field name
141414 * @param id $post Post ID
141415 * @param string $context Optional. How to filter the field. Default is display.
141416 * @return WP_Error|string Value in post field or WP_Error on failure
141417 */
141418 function get_post_field( $field, $post, $context = 'display' ) {
141419 $post = (int) $post;
141420 $post = get_post( $post );
141421
141422 if ( is_wp_error($post) )
141423 return $post;
141424
141425 if ( !is_object($post) )
141426 return '';
141427
141428 if ( !isset($post->$field) )
141429 return '';
141430
141431 return sanitize_post_field($field, $post->$field, $post->ID, $context);
141432 }
141433
141434 /**
141435 * Retrieve the mime type of an attachment based on the ID.
141436 *
141437 * This function can be used with any post type, but it makes more sense with
141438 * attachments.
141439 *
141440 * @since 2.0.0
141441 *
141442 * @param int $ID Optional. Post ID.
141443 * @return bool|string False on failure or returns the mime type
141444 */
141445 function get_post_mime_type($ID = '') {
141446 $post = & get_post($ID);
141447
141448 if ( is_object($post) )
141449 return $post->post_mime_type;
141450
141451 return false;
141452 }
141453
141454 /**
141455 * Retrieve the post status based on the Post ID.
141456 *
141457 * If the post ID is of an attachment, then the parent post status will be given
141458 * instead.
141459 *
141460 * @since 2.0.0
141461 *
141462 * @param int $ID Post ID
141463 * @return string|bool Post status or false on failure.
141464 */
141465 function get_post_status($ID = '') {
141466 $post = get_post($ID);
141467
141468 if ( is_object($post) ) {
141469 if ( ('attachment' == $post->post_type) && $post->post_parent && ($post->ID != $post->post_parent) )
141470 return get_post_status($post->post_parent);
141471 else
141472 return $post->post_status;
141473 }
141474
141475 return false;
141476 }
141477
141478 /**
141479 * Retrieve all of the WordPress supported post statuses.
141480 *
141481 * Posts have a limited set of valid status values, this provides the
141482 * post_status values and descriptions.
141483 *
141484 * @since 2.5.0
141485 *
141486 * @return array List of post statuses.
141487 */
141488 function get_post_statuses( ) {
141489 $status = array(
141490 'draft' => __('Draft'),
141491 'pending' => __('Pending Review'),
141492 'private' => __('Private'),
141493 'publish' => __('Published')
141494 );
141495
141496 return $status;
141497 }
141498
141499 /**
141500 * Retrieve all of the WordPress support page statuses.
141501 *
141502 * Pages have a limited set of valid status values, this provides the
141503 * post_status values and descriptions.
141504 *
141505 * @since 2.5.0
141506 *
141507 * @return array List of page statuses.
141508 */
141509 function get_page_statuses( ) {
141510 $status = array(
141511 'draft' => __('Draft'),
141512 'private' => __('Private'),
141513 'publish' => __('Published')
141514 );
141515
141516 return $status;
141517 }
141518
141519 /**
141520 * Retrieve the post type of the current post or of a given post.
141521 *
141522 * @since 2.1.0
141523 *
141524 * @uses $wpdb
141525 * @uses $posts The Loop post global
141526 *
141527 * @param mixed $post Optional. Post object or post ID.
141528 * @return bool|string post type or false on failure.
141529 */
141530 function get_post_type($post = false) {
141531 global $posts;
141532
141533 if ( false === $post )
141534 $post = $posts[0];
141535 elseif ( (int) $post )
141536 $post = get_post($post, OBJECT);
141537
141538 if ( is_object($post) )
141539 return $post->post_type;
141540
141541 return false;
141542 }
141543
141544 /**
141545 * Updates the post type for the post ID.
141546 *
141547 * The page or post cache will be cleaned for the post ID.
141548 *
141549 * @since 2.5.0
141550 *
141551 * @uses $wpdb
141552 *
141553 * @param int $post_id Post ID to change post type. Not actually optional.
141554 * @param string $post_type Optional, default is post. Supported values are 'post' or 'page' to name a few.
141555 * @return int Amount of rows changed. Should be 1 for success and 0 for failure.
141556 */
141557 function set_post_type( $post_id = 0, $post_type = 'post' ) {
141558 global $wpdb;
141559
141560 $post_type = sanitize_post_field('post_type', $post_type, $post_id, 'db');
141561 $return = $wpdb->query( $wpdb->prepare("UPDATE $wpdb->posts SET post_type = %s WHERE ID = %d", $post_type, $post_id) );
141562
141563 if ( 'page' == $post_type )
141564 clean_page_cache($post_id);
141565 else
141566 clean_post_cache($post_id);
141567
141568 return $return;
141569 }
141570
141571 /**
141572 * Retrieve list of latest posts or posts matching criteria.
141573 *
141574 * The defaults are as follows:
141575 * 'numberposts' - Default is 5. Total number of posts to retrieve.
141576 * 'offset' - Default is 0. See {@link WP_Query::query()} for more.
141577 * 'category' - What category to pull the posts from.
141578 * 'orderby' - Default is 'post_date'. How to order the posts.
141579 * 'order' - Default is 'DESC'. The order to retrieve the posts.
141580 * 'include' - See {@link WP_Query::query()} for more.
141581 * 'exclude' - See {@link WP_Query::query()} for more.
141582 * 'meta_key' - See {@link WP_Query::query()} for more.
141583 * 'meta_value' - See {@link WP_Query::query()} for more.
141584 * 'post_type' - Default is 'post'. Can be 'page', or 'attachment' to name a few.
141585 * 'post_parent' - The parent of the post or post type.
141586 * 'post_status' - Default is 'published'. Post status to retrieve.
141587 *
141588 * @since 1.2.0
141589 * @uses $wpdb
141590 * @uses WP_Query::query() See for more default arguments and information.
141591 * @link http://codex.wordpress.org/Template_Tags/get_posts
141592 *
141593 * @param array $args Optional. Override defaults.
141594 * @return array List of posts.
141595 */
141596 function get_posts($args = null) {
141597 $defaults = array(
141598 'numberposts' => 5, 'offset' => 0,
141599 'category' => 0, 'orderby' => 'post_date',
141600 'order' => 'DESC', 'include' => '',
141601 'exclude' => '', 'meta_key' => '',
141602 'meta_value' =>'', 'post_type' => 'post',
141603 'suppress_filters' => true
141604 );
141605
141606 $r = wp_parse_args( $args, $defaults );
141607 if ( empty( $r['post_status'] ) )
141608 $r['post_status'] = ( 'attachment' == $r['post_type'] ) ? 'inherit' : 'publish';
141609 if ( ! empty($r['numberposts']) )
141610 $r['posts_per_page'] = $r['numberposts'];
141611 if ( ! empty($r['category']) )
141612 $r['cat'] = $r['category'];
141613 if ( ! empty($r['include']) ) {
141614 $incposts = preg_split('/[\s,]+/',$r['include']);
141615 $r['posts_per_page'] = count($incposts); // only the number of posts included
141616 $r['post__in'] = $incposts;
141617 } elseif ( ! empty($r['exclude']) )
141618 $r['post__not_in'] = preg_split('/[\s,]+/',$r['exclude']);
141619
141620 $r['caller_get_posts'] = true;
141621
141622 $get_posts = new WP_Query;
141623 return $get_posts->query($r);
141624
141625 }
141626
141627 //
141628 // Post meta functions
141629 //
141630
141631 /**
141632 * Add meta data field to a post.
141633 *
141634 * Post meta data is called "Custom Fields" on the Administration Panels.
141635 *
141636 * @since 1.5.0
141637 * @uses $wpdb
141638 * @link http://codex.wordpress.org/Function_Reference/add_post_meta
141639 *
141640 * @param int $post_id Post ID.
141641 * @param string $key Metadata name.
141642 * @param mixed $value Metadata value.
141643 * @param bool $unique Optional, default is false. Whether the same key should not be added.
141644 * @return bool False for failure. True for success.
141645 */
141646 function add_post_meta($post_id, $meta_key, $meta_value, $unique = false) {
141647 global $wpdb;
141648
141649 // make sure meta is added to the post, not a revision
141650 if ( $the_post = wp_is_post_revision($post_id) )
141651 $post_id = $the_post;
141652
141653 // expected_slashed ($meta_key)
141654 $meta_key = stripslashes($meta_key);
141655
141656 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 ) ) )
141657 return false;
141658
141659 $meta_value = maybe_serialize( stripslashes_deep($meta_value) );
141660
141661 $wpdb->insert( $wpdb->postmeta, compact( 'post_id', 'meta_key', 'meta_value' ) );
141662
141663 wp_cache_delete($post_id, 'post_meta');
141664
141665 return true;
141666 }
141667
141668 /**
141669 * Remove metadata matching criteria from a post.
141670 *
141671 * You can match based on the key, or key and value. Removing based on key and
141672 * value, will keep from removing duplicate metadata with the same key. It also
141673 * allows removing all metadata matching key, if needed.
141674 *
141675 * @since 1.5.0
141676 * @uses $wpdb
141677 * @link http://codex.wordpress.org/Function_Reference/delete_post_meta
141678 *
141679 * @param int $post_id post ID
141680 * @param string $meta_key Metadata name.
141681 * @param mixed $meta_value Optional. Metadata value.
141682 * @return bool False for failure. True for success.
141683 */
141684 function delete_post_meta($post_id, $meta_key, $meta_value = '') {
141685 global $wpdb;
141686
141687 // make sure meta is added to the post, not a revision
141688 if ( $the_post = wp_is_post_revision($post_id) )
141689 $post_id = $the_post;
141690
141691 // expected_slashed ($meta_key, $meta_value)
141692 $meta_key = stripslashes( $meta_key );
141693 $meta_value = maybe_serialize( stripslashes_deep($meta_value) );
141694
141695 if ( empty( $meta_value ) )
141696 $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 ) );
141697 else
141698 $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 ) );
141699
141700 if ( !$meta_id )
141701 return false;
141702
141703 if ( empty( $meta_value ) )
141704 $wpdb->query( $wpdb->prepare( "DELETE FROM $wpdb->postmeta WHERE post_id = %d AND meta_key = %s", $post_id, $meta_key ) );
141705 else
141706 $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 ) );
141707
141708 wp_cache_delete($post_id, 'post_meta');
141709
141710 return true;
141711 }
141712
141713 /**
141714 * Retrieve post meta field for a post.
141715 *
141716 * @since 1.5.0
141717 * @uses $wpdb
141718 * @link http://codex.wordpress.org/Function_Reference/get_post_meta
141719 *
141720 * @param int $post_id Post ID.
141721 * @param string $key The meta key to retrieve.
141722 * @param bool $single Whether to return a single value.
141723 * @return mixed Will be an array if $single is false. Will be value of meta data field if $single is true.
141724 */
141725 function get_post_meta($post_id, $key, $single = false) {
141726 $post_id = (int) $post_id;
141727
141728 $meta_cache = wp_cache_get($post_id, 'post_meta');
141729
141730 if ( !$meta_cache ) {
141731 update_postmeta_cache($post_id);
141732 $meta_cache = wp_cache_get($post_id, 'post_meta');
141733 }
141734
141735 if ( isset($meta_cache[$key]) ) {
141736 if ( $single ) {
141737 return maybe_unserialize( $meta_cache[$key][0] );
141738 } else {
141739 return array_map('maybe_unserialize', $meta_cache[$key]);
141740 }
141741 }
141742
141743 return '';
141744 }
141745
141746 /**
141747 * Update post meta field based on post ID.
141748 *
141749 * Use the $prev_value parameter to differentiate between meta fields with the
141750 * same key and post ID.
141751 *
141752 * If the meta field for the post does not exist, it will be added.
141753 *
141754 * @since 1.5
141755 * @uses $wpdb
141756 * @link http://codex.wordpress.org/Function_Reference/update_post_meta
141757 *
141758 * @param int $post_id Post ID.
141759 * @param string $key Metadata key.
141760 * @param mixed $value Metadata value.
141761 * @param mixed $prev_value Optional. Previous value to check before removing.
141762 * @return bool False on failure, true if success.
141763 */
141764 function update_post_meta($post_id, $meta_key, $meta_value, $prev_value = '') {
141765 global $wpdb;
141766
141767 // make sure meta is added to the post, not a revision
141768 if ( $the_post = wp_is_post_revision($post_id) )
141769 $post_id = $the_post;
141770
141771 // expected_slashed ($meta_key)
141772 $meta_key = stripslashes($meta_key);
141773
141774 if ( ! $wpdb->get_var( $wpdb->prepare( "SELECT meta_key FROM $wpdb->postmeta WHERE meta_key = %s AND post_id = %d", $meta_key, $post_id ) ) ) {
141775 return add_post_meta($post_id, $meta_key, $meta_value);
141776 }
141777
141778 $meta_value = maybe_serialize( stripslashes_deep($meta_value) );
141779
141780 $data = compact( 'meta_value' );
141781 $where = compact( 'meta_key', 'post_id' );
141782
141783 if ( !empty( $prev_value ) ) {
141784 $prev_value = maybe_serialize($prev_value);
141785 $where['meta_value'] = $prev_value;
141786 }
141787
141788 $wpdb->update( $wpdb->postmeta, $data, $where );
141789 wp_cache_delete($post_id, 'post_meta');
141790 return true;
141791 }
141792
141793 /**
141794 * Delete everything from post meta matching meta key.
141795 *
141796 * @since 2.3.0
141797 * @uses $wpdb
141798 *
141799 * @param string $post_meta_key Key to search for when deleting.
141800 * @return bool Whether the post meta key was deleted from the database
141801 */
141802 function delete_post_meta_by_key($post_meta_key) {
141803 global $wpdb;
141804 if ( $wpdb->query($wpdb->prepare("DELETE FROM $wpdb->postmeta WHERE meta_key = %s", $post_meta_key)) ) {
141805 /** @todo Get post_ids and delete cache */
141806 // wp_cache_delete($post_id, 'post_meta');
141807 return true;
141808 }
141809 return false;
141810 }
141811
141812 /**
141813 * Retrieve post meta fields, based on post ID.
141814 *
141815 * The post meta fields are retrieved from the cache, so the function is
141816 * optimized to be called more than once. It also applies to the functions, that
141817 * use this function.
141818 *
141819 * @since 1.2.0
141820 * @link http://codex.wordpress.org/Function_Reference/get_post_custom
141821 *
141822 * @uses $id Current Loop Post ID
141823 *
141824 * @param int $post_id post ID
141825 * @return array
141826 */
141827 function get_post_custom($post_id = 0) {
141828 global $id;
141829
141830 if ( !$post_id )
141831 $post_id = (int) $id;
141832
141833 $post_id = (int) $post_id;
141834
141835 if ( ! wp_cache_get($post_id, 'post_meta') )
141836 update_postmeta_cache($post_id);
141837
141838 return wp_cache_get($post_id, 'post_meta');
141839 }
141840
141841 /**
141842 * Retrieve meta field names for a post.
141843 *
141844 * If there are no meta fields, then nothing (null) will be returned.
141845 *
141846 * @since 1.2.0
141847 * @link http://codex.wordpress.org/Function_Reference/get_post_custom_keys
141848 *
141849 * @param int $post_id post ID
141850 * @return array|null Either array of the keys, or null if keys could not be retrieved.
141851 */
141852 function get_post_custom_keys( $post_id = 0 ) {
141853 $custom = get_post_custom( $post_id );
141854
141855 if ( !is_array($custom) )
141856 return;
141857
141858 if ( $keys = array_keys($custom) )
141859 return $keys;
141860 }
141861
141862 /**
141863 * Retrieve values for a custom post field.
141864 *
141865 * The parameters must not be considered optional. All of the post meta fields
141866 * will be retrieved and only the meta field key values returned.
141867 *
141868 * @since 1.2.0
141869 * @link http://codex.wordpress.org/Function_Reference/get_post_custom_values
141870 *
141871 * @param string $key Meta field key.
141872 * @param int $post_id Post ID
141873 * @return array Meta field values.
141874 */
141875 function get_post_custom_values( $key = '', $post_id = 0 ) {
141876 $custom = get_post_custom($post_id);
141877
141878 return $custom[$key];
141879 }
141880
141881 /**
141882 * Check if post is sticky.
141883 *
141884 * Sticky posts should remain at the top of The Loop. If the post ID is not
141885 * given, then The Loop ID for the current post will be used.
141886 *
141887 * @since 2.7.0
141888 *
141889 * @param int $post_id Optional. Post ID.
141890 * @return bool Whether post is sticky (true) or not sticky (false).
141891 */
141892 function is_sticky($post_id = null) {
141893 global $id;
141894
141895 $post_id = absint($post_id);
141896
141897 if ( !$post_id )
141898 $post_id = absint($id);
141899
141900 $stickies = get_option('sticky_posts');
141901
141902 if ( !is_array($stickies) )
141903 return false;
141904
141905 if ( in_array($post_id, $stickies) )
141906 return true;
141907
141908 return false;
141909 }
141910
141911 /**
141912 * Sanitize every post field.
141913 *
141914 * If the context is 'raw', then the post object or array will just be returned.
141915 *
141916 * @since 2.3.0
141917 * @uses sanitize_post_field() Used to sanitize the fields.
141918 *
141919 * @param object|array $post The Post Object or Array
141920 * @param string $context Optional, default is 'display'. How to sanitize post fields.
141921 * @return object|array The now sanitized Post Object or Array (will be the same type as $post)
141922 */
141923 function sanitize_post($post, $context = 'display') {
141924 if ( 'raw' == $context )
141925 return $post;
141926 if ( is_object($post) ) {
141927 if ( !isset($post->ID) )
141928 $post->ID = 0;
141929 foreach ( array_keys(get_object_vars($post)) as $field )
141930 $post->$field = sanitize_post_field($field, $post->$field, $post->ID, $context);
141931 } else {
141932 if ( !isset($post['ID']) )
141933 $post['ID'] = 0;
141934 foreach ( array_keys($post) as $field )
141935 $post[$field] = sanitize_post_field($field, $post[$field], $post['ID'], $context);
141936 }
141937 return $post;
141938 }
141939
141940 /**
141941 * Sanitize post field based on context.
141942 *
141943 * Possible context values are: raw, edit, db, attribute, js, and display. The
141944 * display context is used by default.
141945 *
141946 * @since 2.3.0
141947 *
141948 * @param string $field The Post Object field name.
141949 * @param mixed $value The Post Object value.
141950 * @param int $post_id Post ID.
141951 * @param string $context How to sanitize post fields.
141952 * @return mixed Sanitized value.
141953 */
141954 function sanitize_post_field($field, $value, $post_id, $context) {
141955 $int_fields = array('ID', 'post_parent', 'menu_order');
141956 if ( in_array($field, $int_fields) )
141957 $value = (int) $value;
141958
141959 if ( 'raw' == $context )
141960 return $value;
141961
141962 $prefixed = false;
141963 if ( false !== strpos($field, 'post_') ) {
141964 $prefixed = true;
141965 $field_no_prefix = str_replace('post_', '', $field);
141966 }
141967
141968 if ( 'edit' == $context ) {
141969 $format_to_edit = array('post_content', 'post_excerpt', 'post_title', 'post_password');
141970
141971 if ( $prefixed ) {
141972 $value = apply_filters("edit_$field", $value, $post_id);
141973 // Old school
141974 $value = apply_filters("${field_no_prefix}_edit_pre", $value, $post_id);
141975 } else {
141976 $value = apply_filters("edit_post_$field", $value, $post_id);
141977 }
141978
141979 if ( in_array($field, $format_to_edit) ) {
141980 if ( 'post_content' == $field )
141981 $value = format_to_edit($value, user_can_richedit());
141982 else
141983 $value = format_to_edit($value);
141984 } else {
141985 $value = attribute_escape($value);
141986 }
141987 } else if ( 'db' == $context ) {
141988 if ( $prefixed ) {
141989 $value = apply_filters("pre_$field", $value);
141990 $value = apply_filters("${field_no_prefix}_save_pre", $value);
141991 } else {
141992 $value = apply_filters("pre_post_$field", $value);
141993 $value = apply_filters("${field}_pre", $value);
141994 }
141995 } else {
141996 // Use display filters by default.
141997 if ( $prefixed )
141998 $value = apply_filters($field, $value, $post_id, $context);
141999 else
142000 $value = apply_filters("post_$field", $value, $post_id, $context);
142001 }
142002
142003 if ( 'attribute' == $context )
142004 $value = attribute_escape($value);
142005 else if ( 'js' == $context )
142006 $value = js_escape($value);
142007
142008 return $value;
142009 }
142010
142011 /**
142012 * Make a post sticky.
142013 *
142014 * Sticky posts should be displayed at the top of the front page.
142015 *
142016 * @since 2.7.0
142017 *
142018 * @param int $post_id Post ID.
142019 */
142020 function stick_post($post_id) {
142021 $stickies = get_option('sticky_posts');
142022
142023 if ( !is_array($stickies) )
142024 $stickies = array($post_id);
142025
142026 if ( ! in_array($post_id, $stickies) )
142027 $stickies[] = $post_id;
142028
142029 update_option('sticky_posts', $stickies);
142030 }
142031
142032 /**
142033 * Unstick a post.
142034 *
142035 * Sticky posts should be displayed at the top of the front page.
142036 *
142037 * @since 2.7.0
142038 *
142039 * @param int $post_id Post ID.
142040 */
142041 function unstick_post($post_id) {
142042 $stickies = get_option('sticky_posts');
142043
142044 if ( !is_array($stickies) )
142045 return;
142046
142047 if ( ! in_array($post_id, $stickies) )
142048 return;
142049
142050 $offset = array_search($post_id, $stickies);
142051 if ( false === $offset )
142052 return;
142053
142054 array_splice($stickies, $offset, 1);
142055
142056 update_option('sticky_posts', $stickies);
142057 }
142058
142059 /**
142060 * Count number of posts of a post type and is user has permissions to view.
142061 *
142062 * This function provides an efficient method of finding the amount of post's
142063 * type a blog has. Another method is to count the amount of items in
142064 * get_posts(), but that method has a lot of overhead with doing so. Therefore,
142065 * when developing for 2.5+, use this function instead.
142066 *
142067 * The $perm parameter checks for 'readable' value and if the user can read
142068 * private posts, it will display that for the user that is signed in.
142069 *
142070 * @since 2.5.0
142071 * @link http://codex.wordpress.org/Template_Tags/wp_count_posts
142072 *
142073 * @param string $type Optional. Post type to retrieve count
142074 * @param string $perm Optional. 'readable' or empty.
142075 * @return object Number of posts for each status
142076 */
142077 function wp_count_posts( $type = 'post', $perm = '' ) {
142078 global $wpdb;
142079
142080 $user = wp_get_current_user();
142081
142082 $cache_key = $type;
142083
142084 $query = "SELECT post_status, COUNT( * ) AS num_posts FROM {$wpdb->posts} WHERE post_type = %s";
142085 if ( 'readable' == $perm && is_user_logged_in() ) {
142086 if ( !current_user_can("read_private_{$type}s") ) {
142087 $cache_key .= '_' . $perm . '_' . $user->ID;
142088 $query .= " AND (post_status != 'private' OR ( post_author = '$user->ID' AND post_status = 'private' ))";
142089 }
142090 }
142091 $query .= ' GROUP BY post_status';
142092
142093 $count = wp_cache_get($cache_key, 'counts');
142094 if ( false !== $count )
142095 return $count;
142096
142097 $count = $wpdb->get_results( $wpdb->prepare( $query, $type ), ARRAY_A );
142098
142099 $stats = array( );
142100 foreach( (array) $count as $row_num => $row ) {
142101 $stats[$row['post_status']] = $row['num_posts'];
142102 }
142103
142104 $stats = (object) $stats;
142105 wp_cache_set($cache_key, $stats, 'counts');
142106
142107 return $stats;
142108 }
142109
142110
142111 /**
142112 * Count number of attachments for the mime type(s).
142113 *
142114 * If you set the optional mime_type parameter, then an array will still be
142115 * returned, but will only have the item you are looking for. It does not give
142116 * you the number of attachments that are children of a post. You can get that
142117 * by counting the number of children that post has.
142118 *
142119 * @since 2.5.0
142120 *
142121 * @param string|array $mime_type Optional. Array or comma-separated list of MIME patterns.
142122 * @return array Number of posts for each mime type.
142123 */
142124 function wp_count_attachments( $mime_type = '' ) {
142125 global $wpdb;
142126
142127 $and = wp_post_mime_type_where( $mime_type );
142128 $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 );
142129
142130 $stats = array( );
142131 foreach( (array) $count as $row ) {
142132 $stats[$row['post_mime_type']] = $row['num_posts'];
142133 }
142134
142135 return (object) $stats;
142136 }
142137
142138 /**
142139 * Check a MIME-Type against a list.
142140 *
142141 * If the wildcard_mime_types parameter is a string, it must be comma separated
142142 * list. If the real_mime_types is a string, it is also comma separated to
142143 * create the list.
142144 *
142145 * @since 2.5.0
142146 *
142147 * @param string|array $wildcard_mime_types e.g. audio/mpeg or image (same as image/*) or flash (same as *flash*)
142148 * @param string|array $real_mime_types post_mime_type values
142149 * @return array array(wildcard=>array(real types))
142150 */
142151 function wp_match_mime_types($wildcard_mime_types, $real_mime_types) {
142152 $matches = array();
142153 if ( is_string($wildcard_mime_types) )
142154 $wildcard_mime_types = array_map('trim', explode(',', $wildcard_mime_types));
142155 if ( is_string($real_mime_types) )
142156 $real_mime_types = array_map('trim', explode(',', $real_mime_types));
142157 $wild = '[-._a-z0-9]*';
142158 foreach ( (array) $wildcard_mime_types as $type ) {
142159 $type = str_replace('*', $wild, $type);
142160 $patternses[1][$type] = "^$type$";
142161 if ( false === strpos($type, '/') ) {
142162 $patternses[2][$type] = "^$type/";
142163 $patternses[3][$type] = $type;
142164 }
142165 }
142166 asort($patternses);
142167 foreach ( $patternses as $patterns )
142168 foreach ( $patterns as $type => $pattern )
142169 foreach ( (array) $real_mime_types as $real )
142170 if ( preg_match("#$pattern#", $real) && ( empty($matches[$type]) || false === array_search($real, $matches[$type]) ) )
142171 $matches[$type][] = $real;
142172 return $matches;
142173 }
142174
142175 /**
142176 * Convert MIME types into SQL.
142177 *
142178 * @since 2.5.0
142179 *
142180 * @param string|array $mime_types List of mime types or comma separated string of mime types.
142181 * @return string The SQL AND clause for mime searching.
142182 */
142183 function wp_post_mime_type_where($post_mime_types) {
142184 $where = '';
142185 $wildcards = array('', '%', '%/%');
142186 if ( is_string($post_mime_types) )
142187 $post_mime_types = array_map('trim', explode(',', $post_mime_types));
142188 foreach ( (array) $post_mime_types as $mime_type ) {
142189 $mime_type = preg_replace('/\s/', '', $mime_type);
142190 $slashpos = strpos($mime_type, '/');
142191 if ( false !== $slashpos ) {
142192 $mime_group = preg_replace('/[^-*.a-zA-Z0-9]/', '', substr($mime_type, 0, $slashpos));
142193 $mime_subgroup = preg_replace('/[^-*.a-zA-Z0-9]/', '', substr($mime_type, $slashpos + 1));
142194 if ( empty($mime_subgroup) )
142195 $mime_subgroup = '*';
142196 else
142197 $mime_subgroup = str_replace('/', '', $mime_subgroup);
142198 $mime_pattern = "$mime_group/$mime_subgroup";
142199 } else {
142200 $mime_pattern = preg_replace('/[^-*.a-zA-Z0-9]/', '', $mime_type);
142201 if ( false === strpos($mime_pattern, '*') )
142202 $mime_pattern .= '/*';
142203 }
142204
142205 $mime_pattern = preg_replace('/\*+/', '%', $mime_pattern);
142206
142207 if ( in_array( $mime_type, $wildcards ) )
142208 return '';
142209
142210 if ( false !== strpos($mime_pattern, '%') )
142211 $wheres[] = "post_mime_type LIKE '$mime_pattern'";
142212 else
142213 $wheres[] = "post_mime_type = '$mime_pattern'";
142214 }
142215 if ( !empty($wheres) )
142216 $where = ' AND (' . join(' OR ', $wheres) . ') ';
142217 return $where;
142218 }
142219
142220 /**
142221 * Removes a post, attachment, or page.
142222 *
142223 * When the post and page goes, everything that is tied to it is deleted also.
142224 * This includes comments, post meta fields, and terms associated with the post.
142225 *
142226 * @since 1.0.0
142227 * @uses do_action() Calls 'deleted_post' hook on post ID.
142228 *
142229 * @param int $postid Post ID.
142230 * @return mixed
142231 */
142232 function wp_delete_post($postid = 0) {
142233 global $wpdb, $wp_rewrite;
142234
142235 if ( !$post = $wpdb->get_row($wpdb->prepare("SELECT * FROM $wpdb->posts WHERE ID = %d", $postid)) )
142236 return $post;
142237
142238 if ( 'attachment' == $post->post_type )
142239 return wp_delete_attachment($postid);
142240
142241 do_action('delete_post', $postid);
142242
142243 /** @todo delete for pluggable post taxonomies too */
142244 wp_delete_object_term_relationships($postid, array('category', 'post_tag'));
142245
142246 $parent_data = array( 'post_parent' => $post->post_parent );
142247 $parent_where = array( 'post_parent' => $postid );
142248
142249 if ( 'page' == $post->post_type) {
142250 // if the page is defined in option page_on_front or post_for_posts,
142251 // adjust the corresponding options
142252 if ( get_option('page_on_front') == $postid ) {
142253 update_option('show_on_front', 'posts');
142254 delete_option('page_on_front');
142255 }
142256 if ( get_option('page_for_posts') == $postid ) {
142257 delete_option('page_for_posts');
142258 }
142259
142260 // Point children of this page to its parent, also clean the cache of affected children
142261 $children_query = $wpdb->prepare("SELECT * FROM $wpdb->posts WHERE post_parent = %d AND post_type='page'", $postid);
142262 $children = $wpdb->get_results($children_query);
142263
142264 $wpdb->update( $wpdb->posts, $parent_data, $parent_where + array( 'post_type' => 'page' ) );
142265 }
142266
142267 // Do raw query. wp_get_post_revisions() is filtered
142268 $revision_ids = $wpdb->get_col( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_parent = %d AND post_type = 'revision'", $postid ) );
142269 // Use wp_delete_post (via wp_delete_post_revision) again. Ensures any meta/misplaced data gets cleaned up.
142270 foreach ( $revision_ids as $revision_id )
142271 wp_delete_post_revision( $revision_id );
142272
142273 // Point all attachments to this post up one level
142274 $wpdb->update( $wpdb->posts, $parent_data, $parent_where + array( 'post_type' => 'attachment' ) );
142275
142276 $wpdb->query( $wpdb->prepare( "DELETE FROM $wpdb->posts WHERE ID = %d", $postid ));
142277
142278 $wpdb->query( $wpdb->prepare( "DELETE FROM $wpdb->comments WHERE comment_post_ID = %d", $postid ));
142279
142280 $wpdb->query( $wpdb->prepare( "DELETE FROM $wpdb->postmeta WHERE post_id = %d", $postid ));
142281
142282 if ( 'page' == $post->post_type ) {
142283 clean_page_cache($postid);
142284
142285 foreach ( (array) $children as $child )
142286 clean_page_cache($child->ID);
142287
142288 $wp_rewrite->flush_rules();
142289 } else {
142290 clean_post_cache($postid);
142291 }
142292
142293 do_action('deleted_post', $postid);
142294
142295 return $post;
142296 }
142297
142298 /**
142299 * Retrieve the list of categories for a post.
142300 *
142301 * Compatibility layer for themes and plugins. Also an easy layer of abstraction
142302 * away from the complexity of the taxonomy layer.
142303 *
142304 * @since 2.1.0
142305 *
142306 * @uses wp_get_object_terms() Retrieves the categories. Args details can be found here.
142307 *
142308 * @param int $post_id Optional. The Post ID.
142309 * @param array $args Optional. Overwrite the defaults.
142310 * @return array
142311 */
142312 function wp_get_post_categories( $post_id = 0, $args = array() ) {
142313 $post_id = (int) $post_id;
142314
142315 $defaults = array('fields' => 'ids');
142316 $args = wp_parse_args( $args, $defaults );
142317
142318 $cats = wp_get_object_terms($post_id, 'category', $args);
142319 return $cats;
142320 }
142321
142322 /**
142323 * Retrieve the tags for a post.
142324 *
142325 * There is only one default for this function, called 'fields' and by default
142326 * is set to 'all'. There are other defaults that can be override in
142327 * {@link wp_get_object_terms()}.
142328 *
142329 * @package WordPress
142330 * @subpackage Post
142331 * @since 2.3.0
142332 *
142333 * @uses wp_get_object_terms() Gets the tags for returning. Args can be found here
142334 *
142335 * @param int $post_id Optional. The Post ID
142336 * @param array $args Optional. Overwrite the defaults
142337 * @return array List of post tags.
142338 */
142339 function wp_get_post_tags( $post_id = 0, $args = array() ) {
142340 $post_id = (int) $post_id;
142341
142342 $defaults = array('fields' => 'all');
142343 $args = wp_parse_args( $args, $defaults );
142344
142345 $tags = wp_get_object_terms($post_id, 'post_tag', $args);
142346
142347 return $tags;
142348 }
142349
142350 /**
142351 * Retrieve number of recent posts.
142352 *
142353 * @since 1.0.0
142354 * @uses $wpdb
142355 *
142356 * @param int $num Optional, default is 10. Number of posts to get.
142357 * @return array List of posts.
142358 */
142359 function wp_get_recent_posts($num = 10) {
142360 global $wpdb;
142361
142362 // Set the limit clause, if we got a limit
142363 $num = (int) $num;
142364 if ($num) {
142365 $limit = "LIMIT $num";
142366 }
142367
142368 $sql = "SELECT * FROM $wpdb->posts WHERE post_type = 'post' ORDER BY post_date DESC $limit";
142369 $result = $wpdb->get_results($sql,ARRAY_A);
142370
142371 return $result ? $result : array();
142372 }
142373
142374 /**
142375 * Retrieve a single post, based on post ID.
142376 *
142377 * Has categories in 'post_category' property or key. Has tags in 'tags_input'
142378 * property or key.
142379 *
142380 * @since 1.0.0
142381 *
142382 * @param int $postid Post ID.
142383 * @param string $mode How to return result, either OBJECT, ARRAY_N, or ARRAY_A.
142384 * @return object|array Post object or array holding post contents and information
142385 */
142386 function wp_get_single_post($postid = 0, $mode = OBJECT) {
142387 $postid = (int) $postid;
142388
142389 $post = get_post($postid, $mode);
142390
142391 // Set categories and tags
142392 if($mode == OBJECT) {
142393 $post->post_category = wp_get_post_categories($postid);
142394 $post->tags_input = wp_get_post_tags($postid, array('fields' => 'names'));
142395 }
142396 else {
142397 $post['post_category'] = wp_get_post_categories($postid);
142398 $post['tags_input'] = wp_get_post_tags($postid, array('fields' => 'names'));
142399 }
142400
142401 return $post;
142402 }
142403
142404 /**
142405 * Insert a post.
142406 *
142407 * If the $postarr parameter has 'ID' set to a value, then post will be updated.
142408 *
142409 * You can set the post date manually, but setting the values for 'post_date'
142410 * and 'post_date_gmt' keys. You can close the comments or open the comments by
142411 * setting the value for 'comment_status' key.
142412 *
142413 * The defaults for the parameter $postarr are:
142414 * 'post_status' - Default is 'draft'.
142415 * 'post_type' - Default is 'post'.
142416 * 'post_author' - Default is current user ID. The ID of the user, who added
142417 * the post.
142418 * 'ping_status' - Default is the value in default ping status option.
142419 * Whether the attachment can accept pings.
142420 * 'post_parent' - Default is 0. Set this for the post it belongs to, if
142421 * any.
142422 * 'menu_order' - Default is 0. The order it is displayed.
142423 * 'to_ping' - Whether to ping.
142424 * 'pinged' - Default is empty string.
142425 * 'post_password' - Default is empty string. The password to access the
142426 * attachment.
142427 * 'guid' - Global Unique ID for referencing the attachment.
142428 * 'post_content_filtered' - Post content filtered.
142429 * 'post_excerpt' - Post excerpt.
142430 *
142431 * @since 1.0.0
142432 * @uses $wpdb
142433 * @uses $wp_rewrite
142434 * @uses $user_ID
142435 *
142436 * @param array $postarr Optional. Override defaults.
142437 * @param bool $wp_error Optional. Allow return of WP_Error on failure.
142438 * @return int|WP_Error The value 0 or WP_Error on failure. The post ID on success.
142439 */
142440 function wp_insert_post($postarr = array(), $wp_error = false) {
142441 global $wpdb, $wp_rewrite, $user_ID;
142442
142443 $defaults = array('post_status' => 'draft', 'post_type' => 'post', 'post_author' => $user_ID,
142444 'ping_status' => get_option('default_ping_status'), 'post_parent' => 0,
142445 'menu_order' => 0, 'to_ping' => '', 'pinged' => '', 'post_password' => '',
142446 'guid' => '', 'post_content_filtered' => '', 'post_excerpt' => '', 'import_id' => 0);
142447
142448 $postarr = wp_parse_args($postarr, $defaults);
142449 $postarr = sanitize_post($postarr, 'db');
142450
142451 // export array as variables
142452 extract($postarr, EXTR_SKIP);
142453
142454 // Are we updating or creating?
142455 $update = false;
142456 if ( !empty($ID) ) {
142457 $update = true;
142458 $previous_status = get_post_field('post_status', $ID);
142459 } else {
142460 $previous_status = 'new';
142461 }
142462
142463 if ( ('' == $post_content) && ('' == $post_title) && ('' == $post_excerpt) ) {
142464 if ( $wp_error )
142465 return new WP_Error('empty_content', __('Content, title, and excerpt are empty.'));
142466 else
142467 return 0;
142468 }
142469
142470 // Make sure we set a valid category
142471 if ( empty($post_category) || 0 == count($post_category) || !is_array($post_category) ) {
142472 $post_category = array(get_option('default_category'));
142473 }
142474
142475 //Set the default tag list
142476 if ( !isset($tags_input) )
142477 $tags_input = array();
142478
142479 if ( empty($post_author) )
142480 $post_author = $user_ID;
142481
142482 if ( empty($post_status) )
142483 $post_status = 'draft';
142484
142485 if ( empty($post_type) )
142486 $post_type = 'post';
142487
142488 $post_ID = 0;
142489
142490 // Get the post ID and GUID
142491 if ( $update ) {
142492 $post_ID = (int) $ID;
142493 $guid = get_post_field( 'guid', $post_ID );
142494 }
142495
142496 // Don't allow contributors to set to set the post slug for pending review posts
142497 if ( 'pending' == $post_status && !current_user_can( 'publish_posts' ) )
142498 $post_name = '';
142499
142500 // Create a valid post name. Drafts and pending posts are allowed to have an empty
142501 // post name.
142502 if ( empty($post_name) ) {
142503 if ( !in_array( $post_status, array( 'draft', 'pending' ) ) )
142504 $post_name = sanitize_title($post_title);
142505 } else {
142506 $post_name = sanitize_title($post_name);
142507 }
142508
142509 // 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
142510 if ( empty($post_date) || '0000-00-00 00:00:00' == $post_date )
142511 $post_date = current_time('mysql');
142512
142513 if ( empty($post_date_gmt) || '0000-00-00 00:00:00' == $post_date_gmt ) {
142514 if ( !in_array( $post_status, array( 'draft', 'pending' ) ) )
142515 $post_date_gmt = get_gmt_from_date($post_date);
142516 else
142517 $post_date_gmt = '0000-00-00 00:00:00';
142518 }
142519
142520 if ( $update || '0000-00-00 00:00:00' == $post_date ) {
142521 $post_modified = current_time( 'mysql' );
142522 $post_modified_gmt = current_time( 'mysql', 1 );
142523 } else {
142524 $post_modified = $post_date;
142525 $post_modified_gmt = $post_date_gmt;
142526 }
142527
142528 if ( 'publish' == $post_status ) {
142529 $now = gmdate('Y-m-d H:i:59');
142530 if ( mysql2date('U', $post_date_gmt) > mysql2date('U', $now) )
142531 $post_status = 'future';
142532 }
142533
142534 if ( empty($comment_status) ) {
142535 if ( $update )
142536 $comment_status = 'closed';
142537 else
142538 $comment_status = get_option('default_comment_status');
142539 }
142540 if ( empty($ping_status) )
142541 $ping_status = get_option('default_ping_status');
142542
142543 if ( isset($to_ping) )
142544 $to_ping = preg_replace('|\s+|', "\n", $to_ping);
142545 else
142546 $to_ping = '';
142547
142548 if ( ! isset($pinged) )
142549 $pinged = '';
142550
142551 if ( isset($post_parent) )
142552 $post_parent = (int) $post_parent;
142553 else
142554 $post_parent = 0;
142555
142556 if ( !empty($post_ID) ) {
142557 if ( $post_parent == $post_ID ) {
142558 // Post can't be its own parent
142559 $post_parent = 0;
142560 } elseif ( !empty($post_parent) ) {
142561 $parent_post = get_post($post_parent);
142562 // Check for circular dependency
142563 if ( $parent_post->post_parent == $post_ID )
142564 $post_parent = 0;
142565 }
142566 }
142567
142568 if ( isset($menu_order) )
142569 $menu_order = (int) $menu_order;
142570 else
142571 $menu_order = 0;
142572
142573 if ( !isset($post_password) || 'private' == $post_status )
142574 $post_password = '';
142575
142576 if ( !in_array( $post_status, array( 'draft', 'pending' ) ) ) {
142577 $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));
142578
142579 if ($post_name_check || in_array($post_name, $wp_rewrite->feeds) ) {
142580 $suffix = 2;
142581 do {
142582 $alt_post_name = substr($post_name, 0, 200-(strlen($suffix)+1)). "-$suffix";
142583 $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));
142584 $suffix++;
142585 } while ($post_name_check);
142586 $post_name = $alt_post_name;
142587 }
142588 }
142589
142590 // expected_slashed (everything!)
142591 $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' ) );
142592 $data = apply_filters('wp_insert_post_data', $data, $postarr);
142593 $data = stripslashes_deep( $data );
142594 $where = array( 'ID' => $post_ID );
142595
142596 if ($update) {
142597 do_action( 'pre_post_update', $post_ID );
142598 if ( false === $wpdb->update( $wpdb->posts, $data, $where ) ) {
142599 if ( $wp_error )
142600 return new WP_Error('db_update_error', __('Could not update post in the database'), $wpdb->last_error);
142601 else
142602 return 0;
142603 }
142604 } else {
142605 if ( isset($post_mime_type) )
142606 $data['post_mime_type'] = stripslashes( $post_mime_type ); // This isn't in the update
142607 // If there is a suggested ID, use it if not already present
142608 if ( !empty($import_id) ) {
142609 $import_id = (int) $import_id;
142610 if ( ! $wpdb->get_var( $wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE ID = %d", $import_id) ) ) {
142611 $data['ID'] = $import_id;
142612 }
142613 }
142614 if ( false === $wpdb->insert( $wpdb->posts, $data ) ) {
142615 if ( $wp_error )
142616 return new WP_Error('db_insert_error', __('Could not insert post into the database'), $wpdb->last_error);
142617 else
142618 return 0;
142619 }
142620 $post_ID = (int) $wpdb->insert_id;
142621
142622 // use the newly generated $post_ID
142623 $where = array( 'ID' => $post_ID );
142624 }
142625
142626 if ( empty($post_name) && !in_array( $post_status, array( 'draft', 'pending' ) ) ) {
142627 $post_name = sanitize_title($post_title, $post_ID);
142628 $wpdb->update( $wpdb->posts, compact( 'post_name' ), $where );
142629 }
142630
142631 wp_set_post_categories( $post_ID, $post_category );
142632 wp_set_post_tags( $post_ID, $tags_input );
142633
142634 $current_guid = get_post_field( 'guid', $post_ID );
142635
142636 if ( 'page' == $post_type )
142637 clean_page_cache($post_ID);
142638 else
142639 clean_post_cache($post_ID);
142640
142641 // Set GUID
142642 if ( !$update && '' == $current_guid )
142643 $wpdb->update( $wpdb->posts, array( 'guid' => get_permalink( $post_ID ) ), $where );
142644
142645 $post = get_post($post_ID);
142646
142647 if ( !empty($page_template) && 'page' == $post_type ) {
142648 $post->page_template = $page_template;
142649 $page_templates = get_page_templates();
142650 if ( 'default' != $page_template && !in_array($page_template, $page_templates) ) {
142651 if ( $wp_error )
142652 return new WP_Error('invalid_page_template', __('The page template is invalid.'));
142653 else
142654 return 0;
142655 }
142656 update_post_meta($post_ID, '_wp_page_template', $page_template);
142657 }
142658
142659 wp_transition_post_status($post_status, $previous_status, $post);
142660
142661 if ( $update)
142662 do_action('edit_post', $post_ID, $post);
142663
142664 do_action('save_post', $post_ID, $post);
142665 do_action('wp_insert_post', $post_ID, $post);
142666
142667 return $post_ID;
142668 }
142669
142670 /**
142671 * Update a post with new post data.
142672 *
142673 * The date does not have to be set for drafts. You can set the date and it will
142674 * not be overridden.
142675 *
142676 * @since 1.0.0
142677 *
142678 * @param array|object $postarr Post data.
142679 * @return int 0 on failure, Post ID on success.
142680 */
142681 function wp_update_post($postarr = array()) {
142682 if ( is_object($postarr) )
142683 $postarr = get_object_vars($postarr);
142684
142685 // First, get all of the original fields
142686 $post = wp_get_single_post($postarr['ID'], ARRAY_A);
142687
142688 // Escape data pulled from DB.
142689 $post = add_magic_quotes($post);
142690
142691 // Passed post category list overwrites existing category list if not empty.
142692 if ( isset($postarr['post_category']) && is_array($postarr['post_category'])
142693 && 0 != count($postarr['post_category']) )
142694 $post_cats = $postarr['post_category'];
142695 else
142696 $post_cats = $post['post_category'];
142697
142698 // Drafts shouldn't be assigned a date unless explicitly done so by the user
142699 if ( in_array($post['post_status'], array('draft', 'pending')) && empty($postarr['edit_date']) &&
142700 ('0000-00-00 00:00:00' == $post['post_date_gmt']) )
142701 $clear_date = true;
142702 else
142703 $clear_date = false;
142704
142705 // Merge old and new fields with new fields overwriting old ones.
142706 $postarr = array_merge($post, $postarr);
142707 $postarr['post_category'] = $post_cats;
142708 if ( $clear_date ) {
142709 $postarr['post_date'] = current_time('mysql');
142710 $postarr['post_date_gmt'] = '';
142711 }
142712
142713 if ($postarr['post_type'] == 'attachment')
142714 return wp_insert_attachment($postarr);
142715
142716 return wp_insert_post($postarr);
142717 }
142718
142719 /**
142720 * Publish a post by transitioning the post status.
142721 *
142722 * @since 2.1.0
142723 * @uses $wpdb
142724 * @uses do_action() Calls 'edit_post', 'save_post', and 'wp_insert_post' on post_id and post data.
142725 *
142726 * @param int $post_id Post ID.
142727 * @return null
142728 */
142729 function wp_publish_post($post_id) {
142730 global $wpdb;
142731
142732 $post = get_post($post_id);
142733
142734 if ( empty($post) )
142735 return;
142736
142737 if ( 'publish' == $post->post_status )
142738 return;
142739
142740 $wpdb->update( $wpdb->posts, array( 'post_status' => 'publish' ), array( 'ID' => $post_id ) );
142741
142742 $old_status = $post->post_status;
142743 $post->post_status = 'publish';
142744 wp_transition_post_status('publish', $old_status, $post);
142745
142746 // Update counts for the post's terms.
142747 foreach ( (array) get_object_taxonomies('post') as $taxonomy ) {
142748 $tt_ids = wp_get_object_terms($post_id, $taxonomy, 'fields=tt_ids');
142749 wp_update_term_count($tt_ids, $taxonomy);
142750 }
142751
142752 do_action('edit_post', $post_id, $post);
142753 do_action('save_post', $post_id, $post);
142754 do_action('wp_insert_post', $post_id, $post);
142755 }
142756
142757 /**
142758 * Publish future post and make sure post ID has future post status.
142759 *
142760 * Invoked by cron 'publish_future_post' event. This safeguard prevents cron
142761 * from publishing drafts, etc.
142762 *
142763 * @since 2.5.0
142764 *
142765 * @param int $post_id Post ID.
142766 * @return null Nothing is returned. Which can mean that no action is required or post was published.
142767 */
142768 function check_and_publish_future_post($post_id) {
142769
142770 $post = get_post($post_id);
142771
142772 if ( empty($post) )
142773 return;
142774
142775 if ( 'future' != $post->post_status )
142776 return;
142777
142778 $time = strtotime( $post->post_date_gmt . ' GMT' );
142779
142780 if ( $time > time() ) { // Uh oh, someone jumped the gun!
142781 wp_clear_scheduled_hook( 'publish_future_post', $post_id ); // clear anything else in the system
142782 wp_schedule_single_event( $time, 'publish_future_post', array( $post_id ) );
142783 return;
142784 }
142785
142786 return wp_publish_post($post_id);
142787 }
142788
142789 /**
142790 * Adds tags to a post.
142791 *
142792 * @uses wp_set_post_tags() Same first two parameters, but the last parameter is always set to true.
142793 *
142794 * @package WordPress
142795 * @subpackage Post
142796 * @since 2.3.0
142797 *
142798 * @param int $post_id Post ID
142799 * @param string $tags The tags to set for the post, separated by commas.
142800 * @return bool|null Will return false if $post_id is not an integer or is 0. Will return null otherwise
142801 */
142802 function wp_add_post_tags($post_id = 0, $tags = '') {
142803 return wp_set_post_tags($post_id, $tags, true);
142804 }
142805
142806
142807 /**
142808 * Set the tags for a post.
142809 *
142810 * @since 2.3.0
142811 * @uses wp_set_object_terms() Sets the tags for the post.
142812 *
142813 * @param int $post_id Post ID.
142814 * @param string $tags The tags to set for the post, separated by commas.
142815 * @param bool $append If true, don't delete existing tags, just add on. If false, replace the tags with the new tags.
142816 * @return bool|null Will return false if $post_id is not an integer or is 0. Will return null otherwise
142817 */
142818 function wp_set_post_tags( $post_id = 0, $tags = '', $append = false ) {
142819
142820 $post_id = (int) $post_id;
142821
142822 if ( !$post_id )
142823 return false;
142824
142825 if ( empty($tags) )
142826 $tags = array();
142827 $tags = (is_array($tags)) ? $tags : explode( ',', trim($tags, " \n\t\r\0\x0B,") );
142828 wp_set_object_terms($post_id, $tags, 'post_tag', $append);
142829 }
142830
142831 /**
142832 * Set categories for a post.
142833 *
142834 * If the post categories parameter is not set, then the default category is
142835 * going used.
142836 *
142837 * @since 2.1.0
142838 *
142839 * @param int $post_ID Post ID.
142840 * @param array $post_categories Optional. List of categories.
142841 * @return bool|mixed
142842 */
142843 function wp_set_post_categories($post_ID = 0, $post_categories = array()) {
142844 $post_ID = (int) $post_ID;
142845 // If $post_categories isn't already an array, make it one:
142846 if (!is_array($post_categories) || 0 == count($post_categories) || empty($post_categories))
142847 $post_categories = array(get_option('default_category'));
142848 else if ( 1 == count($post_categories) && '' == $post_categories[0] )
142849 return true;
142850
142851 $post_categories = array_map('intval', $post_categories);
142852 $post_categories = array_unique($post_categories);
142853
142854 return wp_set_object_terms($post_ID, $post_categories, 'category');
142855 }
142856
142857 /**
142858 * Transition the post status of a post.
142859 *
142860 * Calls hooks to transition post status. If the new post status is not the same
142861 * as the previous post status, then two hooks will be ran, the first is
142862 * 'transition_post_status' with new status, old status, and post data. The
142863 * next action called is 'OLDSTATUS_to_NEWSTATUS' the NEWSTATUS is the
142864 * $new_status parameter and the OLDSTATUS is $old_status parameter; it has the
142865 * post data.
142866 *
142867 * The final action will run whether or not the post statuses are the same. The
142868 * action is named 'NEWSTATUS_POSTTYPE', NEWSTATUS is from the $new_status
142869 * parameter and POSTTYPE is post_type post data.
142870 *
142871 * @since 2.3.0
142872 *
142873 * @param string $new_status Transition to this post status.
142874 * @param string $old_status Previous post status.
142875 * @param object $post Post data.
142876 */
142877 function wp_transition_post_status($new_status, $old_status, $post) {
142878 if ( $new_status != $old_status ) {
142879 do_action('transition_post_status', $new_status, $old_status, $post);
142880 do_action("${old_status}_to_$new_status", $post);
142881 }
142882 do_action("${new_status}_$post->post_type", $post->ID, $post);
142883 }
142884
142885 //
142886 // Trackback and ping functions
142887 //
142888
142889 /**
142890 * Add a URL to those already pung.
142891 *
142892 * @since 1.5.0
142893 * @uses $wpdb
142894 *
142895 * @param int $post_id Post ID.
142896 * @param string $uri Ping URI.
142897 * @return int How many rows were updated.
142898 */
142899 function add_ping($post_id, $uri) {
142900 global $wpdb;
142901 $pung = $wpdb->get_var( $wpdb->prepare( "SELECT pinged FROM $wpdb->posts WHERE ID = %d", $post_id ));
142902 $pung = trim($pung);
142903 $pung = preg_split('/\s/', $pung);
142904 $pung[] = $uri;
142905 $new = implode("\n", $pung);
142906 $new = apply_filters('add_ping', $new);
142907 // expected_slashed ($new)
142908 $new = stripslashes($new);
142909 return $wpdb->update( $wpdb->posts, array( 'pinged' => $new ), array( 'ID' => $post_id ) );
142910 }
142911
142912 /**
142913 * Retrieve enclosures already enclosed for a post.
142914 *
142915 * @since 1.5.0
142916 * @uses $wpdb
142917 *
142918 * @param int $post_id Post ID.
142919 * @return array List of enclosures
142920 */
142921 function get_enclosed($post_id) {
142922 $custom_fields = get_post_custom( $post_id );
142923 $pung = array();
142924 if ( !is_array( $custom_fields ) )
142925 return $pung;
142926
142927 foreach ( $custom_fields as $key => $val ) {
142928 if ( 'enclosure' != $key || !is_array( $val ) )
142929 continue;
142930 foreach( $val as $enc ) {
142931 $enclosure = split( "\n", $enc );
142932 $pung[] = trim( $enclosure[ 0 ] );
142933 }
142934 }
142935 $pung = apply_filters('get_enclosed', $pung);
142936 return $pung;
142937 }
142938
142939 /**
142940 * Retrieve URLs already pinged for a post.
142941 *
142942 * @since 1.5.0
142943 * @uses $wpdb
142944 *
142945 * @param int $post_id Post ID.
142946 * @return array
142947 */
142948 function get_pung($post_id) {
142949 global $wpdb;
142950 $pung = $wpdb->get_var( $wpdb->prepare( "SELECT pinged FROM $wpdb->posts WHERE ID = %d", $post_id ));
142951 $pung = trim($pung);
142952 $pung = preg_split('/\s/', $pung);
142953 $pung = apply_filters('get_pung', $pung);
142954 return $pung;
142955 }
142956
142957 /**
142958 * Retrieve URLs that need to be pinged.
142959 *
142960 * @since 1.5.0
142961 * @uses $wpdb
142962 *
142963 * @param int $post_id Post ID
142964 * @return array
142965 */
142966 function get_to_ping($post_id) {
142967 global $wpdb;
142968 $to_ping = $wpdb->get_var( $wpdb->prepare( "SELECT to_ping FROM $wpdb->posts WHERE ID = %d", $post_id ));
142969 $to_ping = trim($to_ping);
142970 $to_ping = preg_split('/\s/', $to_ping, -1, PREG_SPLIT_NO_EMPTY);
142971 $to_ping = apply_filters('get_to_ping', $to_ping);
142972 return $to_ping;
142973 }
142974
142975 /**
142976 * Do trackbacks for a list of URLs.
142977 *
142978 * @since 1.0.0
142979 *
142980 * @param string $tb_list Comma separated list of URLs
142981 * @param int $post_id Post ID
142982 */
142983 function trackback_url_list($tb_list, $post_id) {
142984 if ( ! empty( $tb_list ) ) {
142985 // get post data
142986 $postdata = wp_get_single_post($post_id, ARRAY_A);
142987
142988 // import postdata as variables
142989 extract($postdata, EXTR_SKIP);
142990
142991 // form an excerpt
142992 $excerpt = strip_tags($post_excerpt ? $post_excerpt : $post_content);
142993
142994 if (strlen($excerpt) > 255) {
142995 $excerpt = substr($excerpt,0,252) . '...';
142996 }
142997
142998 $trackback_urls = explode(',', $tb_list);
142999 foreach( (array) $trackback_urls as $tb_url) {
143000 $tb_url = trim($tb_url);
143001 trackback($tb_url, stripslashes($post_title), $excerpt, $post_id);
143002 }
143003 }
143004 }
143005
143006 //
143007 // Page functions
143008 //
143009
143010 /**
143011 * Get a list of page IDs.
143012 *
143013 * @since 2.0.0
143014 * @uses $wpdb
143015 *
143016 * @return array List of page IDs.
143017 */
143018 function get_all_page_ids() {
143019 global $wpdb;
143020
143021 if ( ! $page_ids = wp_cache_get('all_page_ids', 'posts') ) {
143022 $page_ids = $wpdb->get_col("SELECT ID FROM $wpdb->posts WHERE post_type = 'page'");
143023 wp_cache_add('all_page_ids', $page_ids, 'posts');
143024 }
143025
143026 return $page_ids;
143027 }
143028
143029 /**
143030 * Retrieves page data given a page ID or page object.
143031 *
143032 * @since 1.5.1
143033 *
143034 * @param mixed $page Page object or page ID. Passed by reference.
143035 * @param string $output What to output. OBJECT, ARRAY_A, or ARRAY_N.
143036 * @param string $filter How the return value should be filtered.
143037 * @return mixed Page data.
143038 */
143039 function &get_page(&$page, $output = OBJECT, $filter = 'raw') {
143040 if ( empty($page) ) {
143041 if ( isset( $GLOBALS['page'] ) && isset( $GLOBALS['page']->ID ) ) {
143042 return get_post($GLOBALS['page'], $output, $filter);
143043 } else {
143044 $page = null;
143045 return $page;
143046 }
143047 }
143048
143049 $the_page = get_post($page, $output, $filter);
143050 return $the_page;
143051 }
143052
143053 /**
143054 * Retrieves a page given its path.
143055 *
143056 * @since 2.1.0
143057 * @uses $wpdb
143058 *
143059 * @param string $page_path Page path
143060 * @param string $output Optional. Output type. OBJECT, ARRAY_N, or ARRAY_A.
143061 * @return mixed Null when complete.
143062 */
143063 function get_page_by_path($page_path, $output = OBJECT) {
143064 global $wpdb;
143065 $page_path = rawurlencode(urldecode($page_path));
143066 $page_path = str_replace('%2F', '/', $page_path);
143067 $page_path = str_replace('%20', ' ', $page_path);
143068 $page_paths = '/' . trim($page_path, '/');
143069 $leaf_path = sanitize_title(basename($page_paths));
143070 $page_paths = explode('/', $page_paths);
143071 $full_path = '';
143072 foreach( (array) $page_paths as $pathdir)
143073 $full_path .= ($pathdir!=''?'/':'') . sanitize_title($pathdir);
143074
143075 $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 ));
143076
143077 if ( empty($pages) )
143078 return null;
143079
143080 foreach ($pages as $page) {
143081 $path = '/' . $leaf_path;
143082 $curpage = $page;
143083 while ($curpage->post_parent != 0) {
143084 $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 ));
143085 $path = '/' . $curpage->post_name . $path;
143086 }
143087
143088 if ( $path == $full_path )
143089 return get_page($page->ID, $output);
143090 }
143091
143092 return null;
143093 }
143094
143095 /**
143096 * Retrieve a page given its title.
143097 *
143098 * @since 2.1.0
143099 * @uses $wpdb
143100 *
143101 * @param string $page_title Page title
143102 * @param string $output Optional. Output type. OBJECT, ARRAY_N, or ARRAY_A.
143103 * @return mixed
143104 */
143105 function get_page_by_title($page_title, $output = OBJECT) {
143106 global $wpdb;
143107 $page = $wpdb->get_var( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_title = %s AND post_type='page'", $page_title ));
143108 if ( $page )
143109 return get_page($page, $output);
143110
143111 return null;
143112 }
143113
143114 /**
143115 * Retrieve child pages from list of pages matching page ID.
143116 *
143117 * Matches against the pages parameter against the page ID. Also matches all
143118 * children for the same to retrieve all children of a page. Does not make any
143119 * SQL queries to get the children.
143120 *
143121 * @since 1.5.1
143122 *
143123 * @param int $page_id Page ID.
143124 * @param array $pages List of pages' objects.
143125 * @return array
143126 */
143127 function &get_page_children($page_id, $pages) {
143128 $page_list = array();
143129 foreach ( (array) $pages as $page ) {
143130 if ( $page->post_parent == $page_id ) {
143131 $page_list[] = $page;
143132 if ( $children = get_page_children($page->ID, $pages) )
143133 $page_list = array_merge($page_list, $children);
143134 }
143135 }
143136 return $page_list;
143137 }
143138
143139 /**
143140 * Order the pages with children under parents in a flat list.
143141 *
143142 * Fetches the pages returned as a FLAT list, but arranged in order of their
143143 * hierarchy, i.e., child parents immediately follow their parents.
143144 *
143145 * @since 2.0.0
143146 *
143147 * @param array $posts Posts array.
143148 * @param int $parent Parent page ID.
143149 * @return array
143150 */
143151 function get_page_hierarchy($posts, $parent = 0) {
143152 $result = array ( );
143153 if ($posts) { foreach ( (array) $posts as $post) {
143154 if ($post->post_parent == $parent) {
143155 $result[$post->ID] = $post->post_name;
143156 $children = get_page_hierarchy($posts, $post->ID);
143157 $result += $children; //append $children to $result
143158 }
143159 } }
143160 return $result;
143161 }
143162
143163 /**
143164 * Builds URI for a page.
143165 *
143166 * Sub pages will be in the "directory" under the parent page post name.
143167 *
143168 * @since 1.5.0
143169 *
143170 * @param int $page_id Page ID.
143171 * @return string Page URI.
143172 */
143173 function get_page_uri($page_id) {
143174 $page = get_page($page_id);
143175 $uri = $page->post_name;
143176
143177 // A page cannot be it's own parent.
143178 if ( $page->post_parent == $page->ID )
143179 return $uri;
143180
143181 while ($page->post_parent != 0) {
143182 $page = get_page($page->post_parent);
143183 $uri = $page->post_name . "/" . $uri;
143184 }
143185
143186 return $uri;
143187 }
143188
143189 /**
143190 * Retrieve a list of pages.
143191 *
143192 * The defaults that can be overridden are the following: 'child_of',
143193 * 'sort_order', 'sort_column', 'post_title', 'hierarchical', 'exclude',
143194 * 'include', 'meta_key', 'meta_value', and 'authors'.
143195 *
143196 * @since 1.5.0
143197 * @uses $wpdb
143198 *
143199 * @param mixed $args Optional. Array or string of options that overrides defaults.
143200 * @return array List of pages matching defaults or $args
143201 */
143202 function &get_pages($args = '') {
143203 global $wpdb;
143204
143205 $defaults = array(
143206 'child_of' => 0, 'sort_order' => 'ASC',
143207 'sort_column' => 'post_title', 'hierarchical' => 1,
143208 'exclude' => '', 'include' => '',
143209 'meta_key' => '', 'meta_value' => '',
143210 'authors' => '', 'parent' => -1, 'exclude_tree' => ''
143211 );
143212
143213 $r = wp_parse_args( $args, $defaults );
143214 extract( $r, EXTR_SKIP );
143215
143216 $key = md5( serialize( compact(array_keys($defaults)) ) );
143217 if ( $cache = wp_cache_get( 'get_pages', 'posts' ) ) {
143218 if ( isset( $cache[ $key ] ) ) {
143219 $pages = apply_filters('get_pages', $cache[ $key ], $r );
143220 return $pages;
143221 }
143222 }
143223
143224 $inclusions = '';
143225 if ( !empty($include) ) {
143226 $child_of = 0; //ignore child_of, parent, exclude, meta_key, and meta_value params if using include
143227 $parent = -1;
143228 $exclude = '';
143229 $meta_key = '';
143230 $meta_value = '';
143231 $hierarchical = false;
143232 $incpages = preg_split('/[\s,]+/',$include);
143233 if ( count($incpages) ) {
143234 foreach ( $incpages as $incpage ) {
143235 if (empty($inclusions))
143236 $inclusions = $wpdb->prepare(' AND ( ID = %d ', $incpage);
143237 else
143238 $inclusions .= $wpdb->prepare(' OR ID = %d ', $incpage);
143239 }
143240 }
143241 }
143242 if (!empty($inclusions))
143243 $inclusions .= ')';
143244
143245 $exclusions = '';
143246 if ( !empty($exclude) ) {
143247 $expages = preg_split('/[\s,]+/',$exclude);
143248 if ( count($expages) ) {
143249 foreach ( $expages as $expage ) {
143250 if (empty($exclusions))
143251 $exclusions = $wpdb->prepare(' AND ( ID <> %d ', $expage);
143252 else
143253 $exclusions .= $wpdb->prepare(' AND ID <> %d ', $expage);
143254 }
143255 }
143256 }
143257 if (!empty($exclusions))
143258 $exclusions .= ')';
143259
143260 $author_query = '';
143261 if (!empty($authors)) {
143262 $post_authors = preg_split('/[\s,]+/',$authors);
143263
143264 if ( count($post_authors) ) {
143265 foreach ( $post_authors as $post_author ) {
143266 //Do we have an author id or an author login?
143267 if ( 0 == intval($post_author) ) {
143268 $post_author = get_userdatabylogin($post_author);
143269 if ( empty($post_author) )
143270 continue;
143271 if ( empty($post_author->ID) )
143272 continue;
143273 $post_author = $post_author->ID;
143274 }
143275
143276 if ( '' == $author_query )
143277 $author_query = $wpdb->prepare(' post_author = %d ', $post_author);
143278 else
143279 $author_query .= $wpdb->prepare(' OR post_author = %d ', $post_author);
143280 }
143281 if ( '' != $author_query )
143282 $author_query = " AND ($author_query)";
143283 }
143284 }
143285
143286 $join = '';
143287 $where = "$exclusions $inclusions ";
143288 if ( ! empty( $meta_key ) || ! empty( $meta_value ) ) {
143289 $join = " LEFT JOIN $wpdb->postmeta ON ( $wpdb->posts.ID = $wpdb->postmeta.post_id )";
143290
143291 // meta_key and meta_value might be slashed
143292 $meta_key = stripslashes($meta_key);
143293 $meta_value = stripslashes($meta_value);
143294 if ( ! empty( $meta_key ) )
143295 $where .= $wpdb->prepare(" AND $wpdb->postmeta.meta_key = %s", $meta_key);
143296 if ( ! empty( $meta_value ) )
143297 $where .= $wpdb->prepare(" AND $wpdb->postmeta.meta_value = %s", $meta_value);
143298
143299 }
143300
143301 if ( $parent >= 0 )
143302 $where .= $wpdb->prepare(' AND post_parent = %d ', $parent);
143303
143304 $query = "SELECT * FROM $wpdb->posts $join WHERE (post_type = 'page' AND post_status = 'publish') $where ";
143305 $query .= $author_query;
143306 $query .= " ORDER BY " . $sort_column . " " . $sort_order ;
143307
143308 $pages = $wpdb->get_results($query);
143309
143310 if ( empty($pages) ) {
143311 $pages = apply_filters('get_pages', array(), $r);
143312 return $pages;
143313 }
143314
143315 // Update cache.
143316 update_page_cache($pages);
143317
143318 if ( $child_of || $hierarchical )
143319 $pages = & get_page_children($child_of, $pages);
143320
143321 if ( !empty($exclude_tree) ) {
143322 $exclude = array();
143323
143324 $exclude = (int) $exclude_tree;
143325 $children = get_page_children($exclude, $pages);
143326 $excludes = array();
143327 foreach ( $children as $child )
143328 $excludes[] = $child->ID;
143329 $excludes[] = $exclude;
143330 $total = count($pages);
143331 for ( $i = 0; $i < $total; $i++ ) {
143332 if ( in_array($pages[$i]->ID, $excludes) )
143333 unset($pages[$i]);
143334 }
143335 }
143336
143337 $cache[ $key ] = $pages;
143338 wp_cache_set( 'get_pages', $cache, 'posts' );
143339
143340 $pages = apply_filters('get_pages', $pages, $r);
143341
143342 return $pages;
143343 }
143344
143345 //
143346 // Attachment functions
143347 //
143348
143349 /**
143350 * Check if the attachment URI is local one and is really an attachment.
143351 *
143352 * @since 2.0.0
143353 *
143354 * @param string $url URL to check
143355 * @return bool True on success, false on failure.
143356 */
143357 function is_local_attachment($url) {
143358 if (strpos($url, get_bloginfo('url')) === false)
143359 return false;
143360 if (strpos($url, get_bloginfo('url') . '/?attachment_id=') !== false)
143361 return true;
143362 if ( $id = url_to_postid($url) ) {
143363 $post = & get_post($id);
143364 if ( 'attachment' == $post->post_type )
143365 return true;
143366 }
143367 return false;
143368 }
143369
143370 /**
143371 * Insert an attachment.
143372 *
143373 * If you set the 'ID' in the $object parameter, it will mean that you are
143374 * updating and attempt to update the attachment. You can also set the
143375 * attachment name or title by setting the key 'post_name' or 'post_title'.
143376 *
143377 * You can set the dates for the attachment manually by setting the 'post_date'
143378 * and 'post_date_gmt' keys' values.
143379 *
143380 * By default, the comments will use the default settings for whether the
143381 * comments are allowed. You can close them manually or keep them open by
143382 * setting the value for the 'comment_status' key.
143383 *
143384 * The $object parameter can have the following:
143385 * 'post_status' - Default is 'draft'. Can not be override, set the same as
143386 * parent post.
143387 * 'post_type' - Default is 'post', will be set to attachment. Can not
143388 * override.
143389 * 'post_author' - Default is current user ID. The ID of the user, who added
143390 * the attachment.
143391 * 'ping_status' - Default is the value in default ping status option.
143392 * Whether the attachment can accept pings.
143393 * 'post_parent' - Default is 0. Can use $parent parameter or set this for
143394 * the post it belongs to, if any.
143395 * 'menu_order' - Default is 0. The order it is displayed.
143396 * 'to_ping' - Whether to ping.
143397 * 'pinged' - Default is empty string.
143398 * 'post_password' - Default is empty string. The password to access the
143399 * attachment.
143400 * 'guid' - Global Unique ID for referencing the attachment.
143401 * 'post_content_filtered' - Attachment post content filtered.
143402 * 'post_excerpt' - Attachment excerpt.
143403 *
143404 * @since 2.0.0
143405 * @uses $wpdb
143406 * @uses $user_ID
143407 *
143408 * @param string|array $object Arguments to override defaults.
143409 * @param string $file Optional filename.
143410 * @param int $post_parent Parent post ID.
143411 * @return int Attachment ID.
143412 */
143413 function wp_insert_attachment($object, $file = false, $parent = 0) {
143414 global $wpdb, $user_ID;
143415
143416 $defaults = array('post_status' => 'draft', 'post_type' => 'post', 'post_author' => $user_ID,
143417 'ping_status' => get_option('default_ping_status'), 'post_parent' => 0,
143418 'menu_order' => 0, 'to_ping' => '', 'pinged' => '', 'post_password' => '',
143419 'guid' => '', 'post_content_filtered' => '', 'post_excerpt' => '', 'import_id' => 0);
143420
143421 $object = wp_parse_args($object, $defaults);
143422 if ( !empty($parent) )
143423 $object['post_parent'] = $parent;
143424
143425 $object = sanitize_post($object, 'db');
143426
143427 // export array as variables
143428 extract($object, EXTR_SKIP);
143429
143430 // Make sure we set a valid category
143431 if ( !isset($post_category) || 0 == count($post_category) || !is_array($post_category)) {
143432 $post_category = array(get_option('default_category'));
143433 }
143434
143435 if ( empty($post_author) )
143436 $post_author = $user_ID;
143437
143438 $post_type = 'attachment';
143439 $post_status = 'inherit';
143440
143441 // Are we updating or creating?
143442 if ( !empty($ID) ) {
143443 $update = true;
143444 $post_ID = (int) $ID;
143445 } else {
143446 $update = false;
143447 $post_ID = 0;
143448 }
143449
143450 // Create a valid post name.
143451 if ( empty($post_name) )
143452 $post_name = sanitize_title($post_title);
143453 else
143454 $post_name = sanitize_title($post_name);
143455
143456 // expected_slashed ($post_name)
143457 $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));
143458
143459 if ($post_name_check) {
143460 $suffix = 2;
143461 while ($post_name_check) {
143462 $alt_post_name = $post_name . "-$suffix";
143463 // expected_slashed ($alt_post_name, $post_name)
143464 $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));
143465 $suffix++;
143466 }
143467 $post_name = $alt_post_name;
143468 }
143469
143470 if ( empty($post_date) )
143471 $post_date = current_time('mysql');
143472 if ( empty($post_date_gmt) )
143473 $post_date_gmt = current_time('mysql', 1);
143474
143475 if ( empty($post_modified) )
143476 $post_modified = $post_date;
143477 if ( empty($post_modified_gmt) )
143478 $post_modified_gmt = $post_date_gmt;
143479
143480 if ( empty($comment_status) ) {
143481 if ( $update )
143482 $comment_status = 'closed';
143483 else
143484 $comment_status = get_option('default_comment_status');
143485 }
143486 if ( empty($ping_status) )
143487 $ping_status = get_option('default_ping_status');
143488
143489 if ( isset($to_ping) )
143490 $to_ping = preg_replace('|\s+|', "\n", $to_ping);
143491 else
143492 $to_ping = '';
143493
143494 if ( isset($post_parent) )
143495 $post_parent = (int) $post_parent;
143496 else
143497 $post_parent = 0;
143498
143499 if ( isset($menu_order) )
143500 $menu_order = (int) $menu_order;
143501 else
143502 $menu_order = 0;
143503
143504 if ( !isset($post_password) )
143505 $post_password = '';
143506
143507 if ( ! isset($pinged) )
143508 $pinged = '';
143509
143510 // expected_slashed (everything!)
143511 $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' ) );
143512 $data = stripslashes_deep( $data );
143513
143514 if ( $update ) {
143515 $wpdb->update( $wpdb->posts, $data, array( 'ID' => $post_ID ) );
143516 } else {
143517 // If there is a suggested ID, use it if not already present
143518 if ( !empty($import_id) ) {
143519 $import_id = (int) $import_id;
143520 if ( ! $wpdb->get_var( $wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE ID = %d", $import_id) ) ) {
143521 $data['ID'] = $import_id;
143522 }
143523 }
143524
143525 $wpdb->insert( $wpdb->posts, $data );
143526 $post_ID = (int) $wpdb->insert_id;
143527 }
143528
143529 if ( empty($post_name) ) {
143530 $post_name = sanitize_title($post_title, $post_ID);
143531 $wpdb->update( $wpdb->posts, compact("post_name"), array( 'ID' => $post_ID ) );
143532 }
143533
143534 wp_set_post_categories($post_ID, $post_category);
143535
143536 if ( $file )
143537 update_attached_file( $post_ID, $file );
143538
143539 clean_post_cache($post_ID);
143540
143541 if ( $update) {
143542 do_action('edit_attachment', $post_ID);
143543 } else {
143544 do_action('add_attachment', $post_ID);
143545 }
143546
143547 return $post_ID;
143548 }
143549
143550 /**
143551 * Delete an attachment.
143552 *
143553 * Will remove the file also, when the attachment is removed. Removes all post
143554 * meta fields, taxonomy, comments, etc associated with the attachment (except
143555 * the main post).
143556 *
143557 * @since 2.0.0
143558 * @uses $wpdb
143559 * @uses do_action() Calls 'delete_attachment' hook on Attachment ID.
143560 *
143561 * @param int $postid Attachment ID.
143562 * @return mixed False on failure. Post data on success.
143563 */
143564 function wp_delete_attachment($postid) {
143565 global $wpdb;
143566
143567 if ( !$post = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $wpdb->posts WHERE ID = %d", $postid)) )
143568 return $post;
143569
143570 if ( 'attachment' != $post->post_type )
143571 return false;
143572
143573 $meta = wp_get_attachment_metadata( $postid );
143574 $file = get_attached_file( $postid );
143575
143576 /** @todo Delete for pluggable post taxonomies too */
143577 wp_delete_object_term_relationships($postid, array('category', 'post_tag'));
143578
143579 $wpdb->query( $wpdb->prepare( "DELETE FROM $wpdb->posts WHERE ID = %d", $postid ));
143580
143581 $wpdb->query( $wpdb->prepare( "DELETE FROM $wpdb->comments WHERE comment_post_ID = %d", $postid ));
143582
143583 $wpdb->query( $wpdb->prepare( "DELETE FROM $wpdb->postmeta WHERE post_id = %d ", $postid ));
143584
143585 $uploadPath = wp_upload_dir();
143586
143587 if ( ! empty($meta['thumb']) ) {
143588 // Don't delete the thumb if another attachment uses it
143589 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)) ) {
143590 $thumbfile = str_replace(basename($file), $meta['thumb'], $file);
143591 $thumbfile = apply_filters('wp_delete_file', $thumbfile);
143592 @ unlink( path_join($uploadPath['basedir'], $thumbfile) );
143593 }
143594 }
143595
143596 // remove intermediate images if there are any
143597 $sizes = apply_filters('intermediate_image_sizes', array('thumbnail', 'medium', 'large'));
143598 foreach ( $sizes as $size ) {
143599 if ( $intermediate = image_get_intermediate_size($postid, $size) ) {
143600 $intermediate_file = apply_filters('wp_delete_file', $intermediate['path']);
143601 @ unlink( path_join($uploadPath['basedir'], $intermediate_file) );
143602 }
143603 }
143604
143605 $file = apply_filters('wp_delete_file', $file);
143606
143607 if ( ! empty($file) )
143608 @ unlink($file);
143609
143610 clean_post_cache($postid);
143611
143612 do_action('delete_attachment', $postid);
143613
143614 return $post;
143615 }
143616
143617 /**
143618 * Retrieve attachment meta field for attachment ID.
143619 *
143620 * @since 2.1.0
143621 *
143622 * @param int $post_id Attachment ID
143623 * @param bool $unfiltered Optional, default is false. If true, filters are not run.
143624 * @return string|bool Attachment meta field. False on failure.
143625 */
143626 function wp_get_attachment_metadata( $post_id, $unfiltered = false ) {
143627 $post_id = (int) $post_id;
143628 if ( !$post =& get_post( $post_id ) )
143629 return false;
143630
143631 $data = get_post_meta( $post->ID, '_wp_attachment_metadata', true );
143632 if ( $unfiltered )
143633 return $data;
143634 return apply_filters( 'wp_get_attachment_metadata', $data, $post->ID );
143635 }
143636
143637 /**
143638 * Update metadata for an attachment.
143639 *
143640 * @since 2.1.0
143641 *
143642 * @param int $post_id Attachment ID.
143643 * @param array $data Attachment data.
143644 * @return int
143645 */
143646 function wp_update_attachment_metadata( $post_id, $data ) {
143647 $post_id = (int) $post_id;
143648 if ( !$post =& get_post( $post_id ) )
143649 return false;
143650
143651 $data = apply_filters( 'wp_update_attachment_metadata', $data, $post->ID );
143652
143653 return update_post_meta( $post->ID, '_wp_attachment_metadata', $data);
143654 }
143655
143656 /**
143657 * Retrieve the URL for an attachment.
143658 *
143659 * @since 2.1.0
143660 *
143661 * @param int $post_id Attachment ID.
143662 * @return string
143663 */
143664 function wp_get_attachment_url( $post_id = 0 ) {
143665 $post_id = (int) $post_id;
143666 if ( !$post =& get_post( $post_id ) )
143667 return false;
143668
143669 $url = '';
143670 if ( $file = get_post_meta( $post->ID, '_wp_attached_file', true) ) { //Get attached file
143671 if ( ($uploads = wp_upload_dir()) && false === $uploads['error'] ) { //Get upload directory
143672 if ( 0 === strpos($file, $uploads['basedir']) ) //Check that the upload base exists in the file location
143673 $url = str_replace($uploads['basedir'], $uploads['baseurl'], $file); //replace file location with url location
143674 }
143675 }
143676
143677 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.
143678 $url = get_the_guid( $post->ID );
143679
143680 if ( 'attachment' != $post->post_type || empty($url) )
143681 return false;
143682
143683 return apply_filters( 'wp_get_attachment_url', $url, $post->ID );
143684 }
143685
143686 /**
143687 * Retrieve thumbnail for an attachment.
143688 *
143689 * @since 2.1.0
143690 *
143691 * @param int $post_id Attachment ID.
143692 * @return mixed False on failure. Thumbnail file path on success.
143693 */
143694 function wp_get_attachment_thumb_file( $post_id = 0 ) {
143695 $post_id = (int) $post_id;
143696 if ( !$post =& get_post( $post_id ) )
143697 return false;
143698 if ( !is_array( $imagedata = wp_get_attachment_metadata( $post->ID ) ) )
143699 return false;
143700
143701 $file = get_attached_file( $post->ID );
143702
143703 if ( !empty($imagedata['thumb']) && ($thumbfile = str_replace(basename($file), $imagedata['thumb'], $file)) && file_exists($thumbfile) )
143704 return apply_filters( 'wp_get_attachment_thumb_file', $thumbfile, $post->ID );
143705 return false;
143706 }
143707
143708 /**
143709 * Retrieve URL for an attachment thumbnail.
143710 *
143711 * @since 2.1.0
143712 *
143713 * @param int $post_id Attachment ID
143714 * @return string|bool False on failure. Thumbnail URL on success.
143715 */
143716 function wp_get_attachment_thumb_url( $post_id = 0 ) {
143717 $post_id = (int) $post_id;
143718 if ( !$post =& get_post( $post_id ) )
143719 return false;
143720 if ( !$url = wp_get_attachment_url( $post->ID ) )
143721 return false;
143722
143723 $sized = image_downsize( $post_id, 'thumbnail' );
143724 if ( $sized )
143725 return $sized[0];
143726
143727 if ( !$thumb = wp_get_attachment_thumb_file( $post->ID ) )
143728 return false;
143729
143730 $url = str_replace(basename($url), basename($thumb), $url);
143731
143732 return apply_filters( 'wp_get_attachment_thumb_url', $url, $post->ID );
143733 }
143734
143735 /**
143736 * Check if the attachment is an image.
143737 *
143738 * @since 2.1.0
143739 *
143740 * @param int $post_id Attachment ID
143741 * @return bool
143742 */
143743 function wp_attachment_is_image( $post_id = 0 ) {
143744 $post_id = (int) $post_id;
143745 if ( !$post =& get_post( $post_id ) )
143746 return false;
143747
143748 if ( !$file = get_attached_file( $post->ID ) )
143749 return false;
143750
143751 $ext = preg_match('/\.([^.]+)$/', $file, $matches) ? strtolower($matches[1]) : false;
143752
143753 $image_exts = array('jpg', 'jpeg', 'gif', 'png');
143754
143755 if ( 'image/' == substr($post->post_mime_type, 0, 6) || $ext && 'import' == $post->post_mime_type && in_array($ext, $image_exts) )
143756 return true;
143757 return false;
143758 }
143759
143760 /**
143761 * Retrieve the icon for a MIME type.
143762 *
143763 * @since 2.1.0
143764 *
143765 * @param string $mime MIME type
143766 * @return string|bool
143767 */
143768 function wp_mime_type_icon( $mime = 0 ) {
143769 if ( !is_numeric($mime) )
143770 $icon = wp_cache_get("mime_type_icon_$mime");
143771 if ( empty($icon) ) {
143772 $post_id = 0;
143773 $post_mimes = array();
143774 if ( is_numeric($mime) ) {
143775 $mime = (int) $mime;
143776 if ( $post =& get_post( $mime ) ) {
143777 $post_id = (int) $post->ID;
143778 $ext = preg_replace('/^.+?\.([^.]+)$/', '$1', $post->guid);
143779 if ( !empty($ext) ) {
143780 $post_mimes[] = $ext;
143781 if ( $ext_type = wp_ext2type( $ext ) )
143782 $post_mimes[] = $ext_type;
143783 }
143784 $mime = $post->post_mime_type;
143785 } else {
143786 $mime = 0;
143787 }
143788 } else {
143789 $post_mimes[] = $mime;
143790 }
143791
143792 $icon_files = wp_cache_get('icon_files');
143793
143794 if ( !is_array($icon_files) ) {
143795 $icon_dir = apply_filters( 'icon_dir', ABSPATH . WPINC . '/images/crystal' );
143796 $icon_dir_uri = apply_filters( 'icon_dir_uri', includes_url('images/crystal') );
143797 $dirs = apply_filters( 'icon_dirs', array($icon_dir => $icon_dir_uri) );
143798 $icon_files = array();
143799 while ( $dirs ) {
143800 $dir = array_shift($keys = array_keys($dirs));
143801 $uri = array_shift($dirs);
143802 if ( $dh = opendir($dir) ) {
143803 while ( false !== $file = readdir($dh) ) {
143804 $file = basename($file);
143805 if ( substr($file, 0, 1) == '.' )
143806 continue;
143807 if ( !in_array(strtolower(substr($file, -4)), array('.png', '.gif', '.jpg') ) ) {
143808 if ( is_dir("$dir/$file") )
143809 $dirs["$dir/$file"] = "$uri/$file";
143810 continue;
143811 }
143812 $icon_files["$dir/$file"] = "$uri/$file";
143813 }
143814 closedir($dh);
143815 }
143816 }
143817 wp_cache_set('icon_files', $icon_files, 600);
143818 }
143819
143820 // Icon basename - extension = MIME wildcard
143821 foreach ( $icon_files as $file => $uri )
143822 $types[ preg_replace('/^([^.]*).*$/', '$1', basename($file)) ] =& $icon_files[$file];
143823
143824 if ( ! empty($mime) ) {
143825 $post_mimes[] = substr($mime, 0, strpos($mime, '/'));
143826 $post_mimes[] = substr($mime, strpos($mime, '/') + 1);
143827 $post_mimes[] = str_replace('/', '_', $mime);
143828 }
143829
143830 $matches = wp_match_mime_types(array_keys($types), $post_mimes);
143831 $matches['default'] = array('default');
143832
143833 foreach ( $matches as $match => $wilds ) {
143834 if ( isset($types[$wilds[0]])) {
143835 $icon = $types[$wilds[0]];
143836 if ( !is_numeric($mime) )
143837 wp_cache_set("mime_type_icon_$mime", $icon);
143838 break;
143839 }
143840 }
143841 }
143842
143843 return apply_filters( 'wp_mime_type_icon', $icon, $mime, $post_id ); // Last arg is 0 if function pass mime type.
143844 }
143845
143846 /**
143847 * Checked for changed slugs for published posts and save old slug.
143848 *
143849 * The function is used along with form POST data. It checks for the wp-old-slug
143850 * POST field. Will only be concerned with published posts and the slug actually
143851 * changing.
143852 *
143853 * If the slug was changed and not already part of the old slugs then it will be
143854 * added to the post meta field ('_wp_old_slug') for storing old slugs for that
143855 * post.
143856 *
143857 * The most logically usage of this function is redirecting changed posts, so
143858 * that those that linked to an changed post will be redirected to the new post.
143859 *
143860 * @since 2.1.0
143861 *
143862 * @param int $post_id Post ID.
143863 * @return int Same as $post_id
143864 */
143865 function wp_check_for_changed_slugs($post_id) {
143866 if ( !isset($_POST['wp-old-slug']) || !strlen($_POST['wp-old-slug']) )
143867 return $post_id;
143868
143869 $post = &get_post($post_id);
143870
143871 // we're only concerned with published posts
143872 if ( $post->post_status != 'publish' || $post->post_type != 'post' )
143873 return $post_id;
143874
143875 // only bother if the slug has changed
143876 if ( $post->post_name == $_POST['wp-old-slug'] )
143877 return $post_id;
143878
143879 $old_slugs = (array) get_post_meta($post_id, '_wp_old_slug');
143880
143881 // if we haven't added this old slug before, add it now
143882 if ( !count($old_slugs) || !in_array($_POST['wp-old-slug'], $old_slugs) )
143883 add_post_meta($post_id, '_wp_old_slug', $_POST['wp-old-slug']);
143884
143885 // if the new slug was used previously, delete it from the list
143886 if ( in_array($post->post_name, $old_slugs) )
143887 delete_post_meta($post_id, '_wp_old_slug', $post->post_name);
143888
143889 return $post_id;
143890 }
143891
143892 /**
143893 * Retrieve the private post SQL based on capability.
143894 *
143895 * This function provides a standardized way to appropriately select on the
143896 * post_status of posts/pages. The function will return a piece of SQL code that
143897 * can be added to a WHERE clause; this SQL is constructed to allow all
143898 * published posts, and all private posts to which the user has access.
143899 *
143900 * It also allows plugins that define their own post type to control the cap by
143901 * using the hook 'pub_priv_sql_capability'. The plugin is expected to return
143902 * the capability the user must have to read the private post type.
143903 *
143904 * @since 2.2.0
143905 *
143906 * @uses $user_ID
143907 * @uses apply_filters() Call 'pub_priv_sql_capability' filter for plugins with different post types.
143908 *
143909 * @param string $post_type currently only supports 'post' or 'page'.
143910 * @return string SQL code that can be added to a where clause.
143911 */
143912 function get_private_posts_cap_sql($post_type) {
143913 global $user_ID;
143914 $cap = '';
143915
143916 // Private posts
143917 if ($post_type == 'post') {
143918 $cap = 'read_private_posts';
143919 // Private pages
143920 } elseif ($post_type == 'page') {
143921 $cap = 'read_private_pages';
143922 // Dunno what it is, maybe plugins have their own post type?
143923 } else {
143924 $cap = apply_filters('pub_priv_sql_capability', $cap);
143925
143926 if (empty($cap)) {
143927 // We don't know what it is, filters don't change anything,
143928 // so set the SQL up to return nothing.
143929 return '1 = 0';
143930 }
143931 }
143932
143933 $sql = '(post_status = \'publish\'';
143934
143935 if (current_user_can($cap)) {
143936 // Does the user have the capability to view private posts? Guess so.
143937 $sql .= ' OR post_status = \'private\'';
143938 } elseif (is_user_logged_in()) {
143939 // Users can view their own private posts.
143940 $sql .= ' OR post_status = \'private\' AND post_author = \'' . $user_ID . '\'';
143941 }
143942
143943 $sql .= ')';
143944
143945 return $sql;
143946 }
143947
143948 /**
143949 * Retrieve the date the the last post was published.
143950 *
143951 * The server timezone is the default and is the difference between GMT and
143952 * server time. The 'blog' value is the date when the last post was posted. The
143953 * 'gmt' is when the last post was posted in GMT formatted date.
143954 *
143955 * @since 0.71
143956 *
143957 * @uses $wpdb
143958 * @uses $blog_id
143959 * @uses apply_filters() Calls 'get_lastpostdate' filter
143960 *
143961 * @global mixed $cache_lastpostdate Stores the last post date
143962 * @global mixed $pagenow The current page being viewed
143963 *
143964 * @param string $timezone The location to get the time. Can be 'gmt', 'blog', or 'server'.
143965 * @return string The date of the last post.
143966 */
143967 function get_lastpostdate($timezone = 'server') {
143968 global $cache_lastpostdate, $wpdb, $blog_id;
143969 $add_seconds_server = date('Z');
143970 if ( !isset($cache_lastpostdate[$blog_id][$timezone]) ) {
143971 switch(strtolower($timezone)) {
143972 case 'gmt':
143973 $lastpostdate = $wpdb->get_var("SELECT post_date_gmt FROM $wpdb->posts WHERE post_status = 'publish' ORDER BY post_date_gmt DESC LIMIT 1");
143974 break;
143975 case 'blog':
143976 $lastpostdate = $wpdb->get_var("SELECT post_date FROM $wpdb->posts WHERE post_status = 'publish' ORDER BY post_date_gmt DESC LIMIT 1");
143977 break;
143978 case 'server':
143979 $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");
143980 break;
143981 }
143982 $cache_lastpostdate[$blog_id][$timezone] = $lastpostdate;
143983 } else {
143984 $lastpostdate = $cache_lastpostdate[$blog_id][$timezone];
143985 }
143986 return apply_filters( 'get_lastpostdate', $lastpostdate, $timezone );
143987 }
143988
143989 /**
143990 * Retrieve last post modified date depending on timezone.
143991 *
143992 * The server timezone is the default and is the difference between GMT and
143993 * server time. The 'blog' value is just when the last post was modified. The
143994 * 'gmt' is when the last post was modified in GMT time.
143995 *
143996 * @since 1.2.0
143997 * @uses $wpdb
143998 * @uses $blog_id
143999 * @uses apply_filters() Calls 'get_lastpostmodified' filter
144000 *
144001 * @global mixed $cache_lastpostmodified Stores the date the last post was modified
144002 *
144003 * @param string $timezone The location to get the time. Can be 'gmt', 'blog', or 'server'.
144004 * @return string The date the post was last modified.
144005 */
144006 function get_lastpostmodified($timezone = 'server') {
144007 global $cache_lastpostmodified, $wpdb, $blog_id;
144008 $add_seconds_server = date('Z');
144009 if ( !isset($cache_lastpostmodified[$blog_id][$timezone]) ) {
144010 switch(strtolower($timezone)) {
144011 case 'gmt':
144012 $lastpostmodified = $wpdb->get_var("SELECT post_modified_gmt FROM $wpdb->posts WHERE post_status = 'publish' ORDER BY post_modified_gmt DESC LIMIT 1");
144013 break;
144014 case 'blog':
144015 $lastpostmodified = $wpdb->get_var("SELECT post_modified FROM $wpdb->posts WHERE post_status = 'publish' ORDER BY post_modified_gmt DESC LIMIT 1");
144016 break;
144017 case 'server':
144018 $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");
144019 break;
144020 }
144021 $lastpostdate = get_lastpostdate($timezone);
144022 if ( $lastpostdate > $lastpostmodified ) {
144023 $lastpostmodified = $lastpostdate;
144024 }
144025 $cache_lastpostmodified[$blog_id][$timezone] = $lastpostmodified;
144026 } else {
144027 $lastpostmodified = $cache_lastpostmodified[$blog_id][$timezone];
144028 }
144029 return apply_filters( 'get_lastpostmodified', $lastpostmodified, $timezone );
144030 }
144031
144032 /**
144033 * Updates posts in cache.
144034 *
144035 * @usedby update_page_cache() Aliased by this function.
144036 *
144037 * @package WordPress
144038 * @subpackage Cache
144039 * @since 1.5.1
144040 *
144041 * @param array $posts Array of post objects
144042 */
144043 function update_post_cache(&$posts) {
144044 if ( !$posts )
144045 return;
144046
144047 foreach ( $posts as $post )
144048 wp_cache_add($post->ID, $post, 'posts');
144049 }
144050
144051 /**
144052 * Will clean the post in the cache.
144053 *
144054 * Cleaning means delete from the cache of the post. Will call to clean the term
144055 * object cache associated with the post ID.
144056 *
144057 * @package WordPress
144058 * @subpackage Cache
144059 * @since 2.0.0
144060 *
144061 * @uses do_action() Will call the 'clean_post_cache' hook action.
144062 *
144063 * @param int $id The Post ID in the cache to clean
144064 */
144065 function clean_post_cache($id) {
144066 global $_wp_suspend_cache_invalidation, $wpdb;
144067
144068 if ( !empty($_wp_suspend_cache_invalidation) )
144069 return;
144070
144071 $id = (int) $id;
144072
144073 wp_cache_delete($id, 'posts');
144074 wp_cache_delete($id, 'post_meta');
144075
144076 clean_object_term_cache($id, 'post');
144077
144078 wp_cache_delete( 'wp_get_archives', 'general' );
144079
144080 do_action('clean_post_cache', $id);
144081
144082 if ( $children = $wpdb->get_col( $wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE post_parent = %d", $id) ) ) {
144083 foreach( $children as $cid )
144084 clean_post_cache( $cid );
144085 }
144086 }
144087
144088 /**
144089 * Alias of update_post_cache().
144090 *
144091 * @see update_post_cache() Posts and pages are the same, alias is intentional
144092 *
144093 * @package WordPress
144094 * @subpackage Cache
144095 * @since 1.5.1
144096 *
144097 * @param array $pages list of page objects
144098 */
144099 function update_page_cache(&$pages) {
144100 update_post_cache($pages);
144101 }
144102
144103 /**
144104 * Will clean the page in the cache.
144105 *
144106 * Clean (read: delete) page from cache that matches $id. Will also clean cache
144107 * associated with 'all_page_ids' and 'get_pages'.
144108 *
144109 * @package WordPress
144110 * @subpackage Cache
144111 * @since 2.0.0
144112 *
144113 * @uses do_action() Will call the 'clean_page_cache' hook action.
144114 *
144115 * @param int $id Page ID to clean
144116 */
144117 function clean_page_cache($id) {
144118 clean_post_cache($id);
144119
144120 wp_cache_delete( 'all_page_ids', 'posts' );
144121 wp_cache_delete( 'get_pages', 'posts' );
144122
144123 do_action('clean_page_cache', $id);
144124 }
144125
144126 /**
144127 * Call major cache updating functions for list of Post objects.
144128 *
144129 * @package WordPress
144130 * @subpackage Cache
144131 * @since 1.5.0
144132 *
144133 * @uses $wpdb
144134 * @uses update_post_cache()
144135 * @uses update_object_term_cache()
144136 * @uses update_postmeta_cache()
144137 *
144138 * @param array $posts Array of Post objects
144139 */
144140 function update_post_caches(&$posts) {
144141 // No point in doing all this work if we didn't match any posts.
144142 if ( !$posts )
144143 return;
144144
144145 update_post_cache($posts);
144146
144147 $post_ids = array();
144148
144149 for ($i = 0; $i < count($posts); $i++)
144150 $post_ids[] = $posts[$i]->ID;
144151
144152 update_object_term_cache($post_ids, 'post');
144153
144154 update_postmeta_cache($post_ids);
144155 }
144156
144157 /**
144158 * Updates metadata cache for list of post IDs.
144159 *
144160 * Performs SQL query to retrieve the metadata for the post IDs and updates the
144161 * metadata cache for the posts. Therefore, the functions, which call this
144162 * function, do not need to perform SQL queries on their own.
144163 *
144164 * @package WordPress
144165 * @subpackage Cache
144166 * @since 2.1.0
144167 *
144168 * @uses $wpdb
144169 *
144170 * @param array $post_ids List of post IDs.
144171 * @return bool|array Returns false if there is nothing to update or an array of metadata.
144172 */
144173 function update_postmeta_cache($post_ids) {
144174 global $wpdb;
144175
144176 if ( empty( $post_ids ) )
144177 return false;
144178
144179 if ( !is_array($post_ids) ) {
144180 $post_ids = preg_replace('|[^0-9,]|', '', $post_ids);
144181 $post_ids = explode(',', $post_ids);
144182 }
144183
144184 $post_ids = array_map('intval', $post_ids);
144185
144186 $ids = array();
144187 foreach ( (array) $post_ids as $id ) {
144188 if ( false === wp_cache_get($id, 'post_meta') )
144189 $ids[] = $id;
144190 }
144191
144192 if ( empty( $ids ) )
144193 return false;
144194
144195 // Get post-meta info
144196 $id_list = join(',', $ids);
144197 $cache = array();
144198 if ( $meta_list = $wpdb->get_results("SELECT post_id, meta_key, meta_value FROM $wpdb->postmeta WHERE post_id IN ($id_list)", ARRAY_A) ) {
144199 foreach ( (array) $meta_list as $metarow) {
144200 $mpid = (int) $metarow['post_id'];
144201 $mkey = $metarow['meta_key'];
144202 $mval = $metarow['meta_value'];
144203
144204 // Force subkeys to be array type:
144205 if ( !isset($cache[$mpid]) || !is_array($cache[$mpid]) )
144206 $cache[$mpid] = array();
144207 if ( !isset($cache[$mpid][$mkey]) || !is_array($cache[$mpid][$mkey]) )
144208 $cache[$mpid][$mkey] = array();
144209
144210 // Add a value to the current pid/key:
144211 $cache[$mpid][$mkey][] = $mval;
144212 }
144213 }
144214
144215 foreach ( (array) $ids as $id ) {
144216 if ( ! isset($cache[$id]) )
144217 $cache[$id] = array();
144218 }
144219
144220 foreach ( (array) array_keys($cache) as $post)
144221 wp_cache_set($post, $cache[$post], 'post_meta');
144222
144223 return $cache;
144224 }
144225
144226 //
144227 // Hooks
144228 //
144229
144230 /**
144231 * Hook for managing future post transitions to published.
144232 *
144233 * @since 2.3.0
144234 * @access private
144235 * @uses $wpdb
144236 *
144237 * @param string $new_status New post status
144238 * @param string $old_status Previous post status
144239 * @param object $post Object type containing the post information
144240 */
144241 function _transition_post_status($new_status, $old_status, $post) {
144242 global $wpdb;
144243
144244 if ( $old_status != 'publish' && $new_status == 'publish' ) {
144245 // Reset GUID if transitioning to publish and it is empty
144246 if ( '' == get_the_guid($post->ID) )
144247 $wpdb->update( $wpdb->posts, array( 'guid' => get_permalink( $post->ID ) ), array( 'ID' => $post->ID ) );
144248 do_action('private_to_published', $post->ID); // Deprecated, use private_to_publish
144249 }
144250
144251 // Always clears the hook in case the post status bounced from future to draft.
144252 wp_clear_scheduled_hook('publish_future_post', $post->ID);
144253 }
144254
144255 /**
144256 * Hook used to schedule publication for a post marked for the future.
144257 *
144258 * The $post properties used and must exist are 'ID' and 'post_date_gmt'.
144259 *
144260 * @since 2.3.0
144261 *
144262 * @param int $deprecated Not Used. Can be set to null.
144263 * @param object $post Object type containing the post information
144264 */
144265 function _future_post_hook($deprecated = '', $post) {
144266 wp_clear_scheduled_hook( 'publish_future_post', $post->ID );
144267 wp_schedule_single_event(strtotime($post->post_date_gmt. ' GMT'), 'publish_future_post', array($post->ID));
144268 }
144269
144270 /**
144271 * Hook to schedule pings and enclosures when a post is published.
144272 *
144273 * @since 2.3.0
144274 * @uses $wpdb
144275 * @uses XMLRPC_REQUEST
144276 * @uses APP_REQUEST
144277 * @uses do_action Calls 'xmlprc_publish_post' action if XMLRPC_REQUEST is defined. Calls 'app_publish_post'
144278 * action if APP_REQUEST is defined.
144279 *
144280 * @param int $post_id The ID in the database table of the post being published
144281 */
144282 function _publish_post_hook($post_id) {
144283 global $wpdb;
144284
144285 if ( defined('XMLRPC_REQUEST') )
144286 do_action('xmlrpc_publish_post', $post_id);
144287 if ( defined('APP_REQUEST') )
144288 do_action('app_publish_post', $post_id);
144289
144290 if ( defined('WP_IMPORTING') )
144291 return;
144292
144293 $data = array( 'post_id' => $post_id, 'meta_value' => '1' );
144294 if ( get_option('default_pingback_flag') )
144295 $wpdb->insert( $wpdb->postmeta, $data + array( 'meta_key' => '_pingme' ) );
144296 $wpdb->insert( $wpdb->postmeta, $data + array( 'meta_key' => '_encloseme' ) );
144297 wp_schedule_single_event(time(), 'do_pings');
144298 }
144299
144300 /**
144301 * Hook used to prevent page/post cache and rewrite rules from staying dirty.
144302 *
144303 * Does two things. If the post is a page and has a template then it will
144304 * update/add that template to the meta. For both pages and posts, it will clean
144305 * the post cache to make sure that the cache updates to the changes done
144306 * recently. For pages, the rewrite rules of WordPress are flushed to allow for
144307 * any changes.
144308 *
144309 * The $post parameter, only uses 'post_type' property and 'page_template'
144310 * property.
144311 *
144312 * @since 2.3.0
144313 * @uses $wp_rewrite Flushes Rewrite Rules.
144314 *
144315 * @param int $post_id The ID in the database table for the $post
144316 * @param object $post Object type containing the post information
144317 */
144318 function _save_post_hook($post_id, $post) {
144319 if ( $post->post_type == 'page' ) {
144320 clean_page_cache($post_id);
144321 // Avoid flushing rules for every post during import.
144322 if ( !defined('WP_IMPORTING') ) {
144323 global $wp_rewrite;
144324 $wp_rewrite->flush_rules();
144325 }
144326 } else {
144327 clean_post_cache($post_id);
144328 }
144329 }
144330
144331 /**
144332 * Retrieve post ancestors and append to post ancestors property.
144333 *
144334 * Will only retrieve ancestors once, if property is already set, then nothing
144335 * will be done. If there is not a parent post, or post ID and post parent ID
144336 * are the same then nothing will be done.
144337 *
144338 * The parameter is passed by reference, so nothing needs to be returned. The
144339 * property will be updated and can be referenced after the function is
144340 * complete. The post parent will be an ancestor and the parent of the post
144341 * parent will be an ancestor. There will only be two ancestors at the most.
144342 *
144343 * @access private
144344 * @since unknown
144345 * @uses $wpdb
144346 *
144347 * @param object $_post Post data.
144348 * @return null When nothing needs to be done.
144349 */
144350 function _get_post_ancestors(&$_post) {
144351 global $wpdb;
144352
144353 if ( isset($_post->ancestors) )
144354 return;
144355
144356 $_post->ancestors = array();
144357
144358 if ( empty($_post->post_parent) || $_post->ID == $_post->post_parent )
144359 return;
144360
144361 $id = $_post->ancestors[] = $_post->post_parent;
144362 while ( $ancestor = $wpdb->get_var( $wpdb->prepare("SELECT `post_parent` FROM $wpdb->posts WHERE ID = %d LIMIT 1", $id) ) ) {
144363 if ( $id == $ancestor )
144364 break;
144365 $id = $_post->ancestors[] = $ancestor;
144366 }
144367 }
144368
144369 /**
144370 * Determines which fields of posts are to be saved in revisions.
144371 *
144372 * Does two things. If passed a post *array*, it will return a post array ready
144373 * to be insterted into the posts table as a post revision. Otherwise, returns
144374 * an array whose keys are the post fields to be saved for post revisions.
144375 *
144376 * @package WordPress
144377 * @subpackage Post_Revisions
144378 * @since 2.6.0
144379 * @access private
144380 *
144381 * @param array $post Optional a post array to be processed for insertion as a post revision.
144382 * @param bool $autosave optional Is the revision an autosave?
144383 * @return array Post array ready to be inserted as a post revision or array of fields that can be versioned.
144384 */
144385 function _wp_post_revision_fields( $post = null, $autosave = false ) {
144386 static $fields = false;
144387
144388 if ( !$fields ) {
144389 // Allow these to be versioned
144390 $fields = array(
144391 'post_title' => __( 'Title' ),
144392 'post_content' => __( 'Content' ),
144393 'post_excerpt' => __( 'Excerpt' ),
144394 );
144395
144396 // Runs only once
144397 $fields = apply_filters( '_wp_post_revision_fields', $fields );
144398
144399 // WP uses these internally either in versioning or elsewhere - they cannot be versioned
144400 foreach ( array( 'ID', 'post_name', 'post_parent', 'post_date', 'post_date_gmt', 'post_status', 'post_type', 'comment_count', 'post_author' ) as $protect )
144401 unset( $fields[$protect] );
144402 }
144403
144404 if ( !is_array($post) )
144405 return $fields;
144406
144407 $return = array();
144408 foreach ( array_intersect( array_keys( $post ), array_keys( $fields ) ) as $field )
144409 $return[$field] = $post[$field];
144410
144411 $return['post_parent'] = $post['ID'];
144412 $return['post_status'] = 'inherit';
144413 $return['post_type'] = 'revision';
144414 $return['post_name'] = $autosave ? "$post[ID]-autosave" : "$post[ID]-revision";
144415 $return['post_date'] = isset($post['post_modified']) ? $post['post_modified'] : '';
144416 $return['post_date_gmt'] = isset($post['post_modified_gmt']) ? $post['post_modified_gmt'] : '';
144417
144418 return $return;
144419 }
144420
144421 /**
144422 * Saves an already existing post as a post revision.
144423 *
144424 * Typically used immediately prior to post updates.
144425 *
144426 * @package WordPress
144427 * @subpackage Post_Revisions
144428 * @since 2.6.0
144429 *
144430 * @uses _wp_put_post_revision()
144431 *
144432 * @param int $post_id The ID of the post to save as a revision.
144433 * @return mixed Null or 0 if error, new revision ID, if success.
144434 */
144435 function wp_save_post_revision( $post_id ) {
144436 // We do autosaves manually with wp_create_post_autosave()
144437 if ( @constant( 'DOING_AUTOSAVE' ) )
144438 return;
144439
144440 // WP_POST_REVISIONS = 0, false
144441 if ( !constant('WP_POST_REVISIONS') )
144442 return;
144443
144444 if ( !$post = get_post( $post_id, ARRAY_A ) )
144445 return;
144446
144447 if ( !in_array( $post['post_type'], array( 'post', 'page' ) ) )
144448 return;
144449
144450 $return = _wp_put_post_revision( $post );
144451
144452 // WP_POST_REVISIONS = true (default), -1
144453 if ( !is_numeric( WP_POST_REVISIONS ) || WP_POST_REVISIONS < 0 )
144454 return $return;
144455
144456 // all revisions and (possibly) one autosave
144457 $revisions = wp_get_post_revisions( $post_id, array( 'order' => 'ASC' ) );
144458
144459 // WP_POST_REVISIONS = (int) (# of autasaves to save)
144460 $delete = count($revisions) - WP_POST_REVISIONS;
144461
144462 if ( $delete < 1 )
144463 return $return;
144464
144465 $revisions = array_slice( $revisions, 0, $delete );
144466
144467 for ( $i = 0; isset($revisions[$i]); $i++ ) {
144468 if ( false !== strpos( $revisions[$i]->post_name, 'autosave' ) )
144469 continue;
144470 wp_delete_post_revision( $revisions[$i]->ID );
144471 }
144472
144473 return $return;
144474 }
144475
144476 /**
144477 * Retrieve the autosaved data of the specified post.
144478 *
144479 * Returns a post object containing the information that was autosaved for the
144480 * specified post.
144481 *
144482 * @package WordPress
144483 * @subpackage Post_Revisions
144484 * @since 2.6.0
144485 *
144486 * @param int $post_id The post ID.
144487 * @return object|bool The autosaved data or false on failure or when no autosave exists.
144488 */
144489 function wp_get_post_autosave( $post_id ) {
144490
144491 if ( !$post = get_post( $post_id ) )
144492 return false;
144493
144494 $q = array(
144495 'name' => "{$post->ID}-autosave",
144496 'post_parent' => $post->ID,
144497 'post_type' => 'revision',
144498 'post_status' => 'inherit'
144499 );
144500
144501 // Use WP_Query so that the result gets cached
144502 $autosave_query = new WP_Query;
144503
144504 add_action( 'parse_query', '_wp_get_post_autosave_hack' );
144505 $autosave = $autosave_query->query( $q );
144506 remove_action( 'parse_query', '_wp_get_post_autosave_hack' );
144507
144508 if ( $autosave && is_array($autosave) && is_object($autosave[0]) )
144509 return $autosave[0];
144510
144511 return false;
144512 }
144513
144514 /**
144515 * Internally used to hack WP_Query into submission.
144516 *
144517 * @package WordPress
144518 * @subpackage Post_Revisions
144519 * @since 2.6.0
144520 *
144521 * @param object $query WP_Query object
144522 */
144523 function _wp_get_post_autosave_hack( $query ) {
144524 $query->is_single = false;
144525 }
144526
144527 /**
144528 * Determines if the specified post is a revision.
144529 *
144530 * @package WordPress
144531 * @subpackage Post_Revisions
144532 * @since 2.6.0
144533 *
144534 * @param int|object $post Post ID or post object.
144535 * @return bool|int False if not a revision, ID of revision's parent otherwise.
144536 */
144537 function wp_is_post_revision( $post ) {
144538 if ( !$post = wp_get_post_revision( $post ) )
144539 return false;
144540 return (int) $post->post_parent;
144541 }
144542
144543 /**
144544 * Determines if the specified post is an autosave.
144545 *
144546 * @package WordPress
144547 * @subpackage Post_Revisions
144548 * @since 2.6.0
144549 *
144550 * @param int|object $post Post ID or post object.
144551 * @return bool|int False if not a revision, ID of autosave's parent otherwise
144552 */
144553 function wp_is_post_autosave( $post ) {
144554 if ( !$post = wp_get_post_revision( $post ) )
144555 return false;
144556 if ( "{$post->post_parent}-autosave" !== $post->post_name )
144557 return false;
144558 return (int) $post->post_parent;
144559 }
144560
144561 /**
144562 * Inserts post data into the posts table as a post revision.
144563 *
144564 * @package WordPress
144565 * @subpackage Post_Revisions
144566 * @since 2.6.0
144567 *
144568 * @uses wp_insert_post()
144569 *
144570 * @param int|object|array $post Post ID, post object OR post array.
144571 * @param bool $autosave Optional. Is the revision an autosave?
144572 * @return mixed Null or 0 if error, new revision ID if success.
144573 */
144574 function _wp_put_post_revision( $post = null, $autosave = false ) {
144575 if ( is_object($post) )
144576 $post = get_object_vars( $post );
144577 elseif ( !is_array($post) )
144578 $post = get_post($post, ARRAY_A);
144579 if ( !$post || empty($post['ID']) )
144580 return;
144581
144582 if ( isset($post['post_type']) && 'revision' == $post['post_type'] )
144583 return new WP_Error( 'post_type', __( 'Cannot create a revision of a revision' ) );
144584
144585 $post = _wp_post_revision_fields( $post, $autosave );
144586
144587 $revision_id = wp_insert_post( $post );
144588 if ( is_wp_error($revision_id) )
144589 return $revision_id;
144590
144591 if ( $revision_id )
144592 do_action( '_wp_put_post_revision', $revision_id );
144593 return $revision_id;
144594 }
144595
144596 /**
144597 * Gets a post revision.
144598 *
144599 * @package WordPress
144600 * @subpackage Post_Revisions
144601 * @since 2.6.0
144602 *
144603 * @uses get_post()
144604 *
144605 * @param int|object $post Post ID or post object
144606 * @param string $output Optional. OBJECT, ARRAY_A, or ARRAY_N.
144607 * @param string $filter Optional sanitation filter. @see sanitize_post()
144608 * @return mixed Null if error or post object if success
144609 */
144610 function &wp_get_post_revision(&$post, $output = OBJECT, $filter = 'raw') {
144611 $null = null;
144612 if ( !$revision = get_post( $post, OBJECT, $filter ) )
144613 return $revision;
144614 if ( 'revision' !== $revision->post_type )
144615 return $null;
144616
144617 if ( $output == OBJECT ) {
144618 return $revision;
144619 } elseif ( $output == ARRAY_A ) {
144620 $_revision = get_object_vars($revision);
144621 return $_revision;
144622 } elseif ( $output == ARRAY_N ) {
144623 $_revision = array_values(get_object_vars($revision));
144624 return $_revision;
144625 }
144626
144627 return $revision;
144628 }
144629
144630 /**
144631 * Restores a post to the specified revision.
144632 *
144633 * Can restore a past using all fields of the post revision, or only selected
144634 * fields.
144635 *
144636 * @package WordPress
144637 * @subpackage Post_Revisions
144638 * @since 2.6.0
144639 *
144640 * @uses wp_get_post_revision()
144641 * @uses wp_update_post()
144642 *
144643 * @param int|object $revision_id Revision ID or revision object.
144644 * @param array $fields Optional. What fields to restore from. Defaults to all.
144645 * @return mixed Null if error, false if no fields to restore, (int) post ID if success.
144646 */
144647 function wp_restore_post_revision( $revision_id, $fields = null ) {
144648 if ( !$revision = wp_get_post_revision( $revision_id, ARRAY_A ) )
144649 return $revision;
144650
144651 if ( !is_array( $fields ) )
144652 $fields = array_keys( _wp_post_revision_fields() );
144653
144654 $update = array();
144655 foreach( array_intersect( array_keys( $revision ), $fields ) as $field )
144656 $update[$field] = $revision[$field];
144657
144658 if ( !$update )
144659 return false;
144660
144661 $update['ID'] = $revision['post_parent'];
144662
144663 $post_id = wp_update_post( $update );
144664 if ( is_wp_error( $post_id ) )
144665 return $post_id;
144666
144667 if ( $post_id )
144668 do_action( 'wp_restore_post_revision', $post_id, $revision['ID'] );
144669
144670 return $post_id;
144671 }
144672
144673 /**
144674 * Deletes a revision.
144675 *
144676 * Deletes the row from the posts table corresponding to the specified revision.
144677 *
144678 * @package WordPress
144679 * @subpackage Post_Revisions
144680 * @since 2.6.0
144681 *
144682 * @uses wp_get_post_revision()
144683 * @uses wp_delete_post()
144684 *
144685 * @param int|object $revision_id Revision ID or revision object.
144686 * @param array $fields Optional. What fields to restore from. Defaults to all.
144687 * @return mixed Null if error, false if no fields to restore, (int) post ID if success.
144688 */
144689 function wp_delete_post_revision( $revision_id ) {
144690 if ( !$revision = wp_get_post_revision( $revision_id ) )
144691 return $revision;
144692
144693 $delete = wp_delete_post( $revision->ID );
144694 if ( is_wp_error( $delete ) )
144695 return $delete;
144696
144697 if ( $delete )
144698 do_action( 'wp_delete_post_revision', $revision->ID, $revision );
144699
144700 return $delete;
144701 }
144702
144703 /**
144704 * Returns all revisions of specified post.
144705 *
144706 * @package WordPress
144707 * @subpackage Post_Revisions
144708 * @since 2.6.0
144709 *
144710 * @uses get_children()
144711 *
144712 * @param int|object $post_id Post ID or post object
144713 * @return array empty if no revisions
144714 */
144715 function wp_get_post_revisions( $post_id = 0, $args = null ) {
144716 if ( !constant('WP_POST_REVISIONS') )
144717 return array();
144718 if ( ( !$post = get_post( $post_id ) ) || empty( $post->ID ) )
144719 return array();
144720
144721 $defaults = array( 'order' => 'DESC', 'orderby' => 'date' );
144722 $args = wp_parse_args( $args, $defaults );
144723 $args = array_merge( $args, array( 'post_parent' => $post->ID, 'post_type' => 'revision', 'post_status' => 'inherit' ) );
144724
144725 if ( !$revisions = get_children( $args ) )
144726 return array();
144727 return $revisions;
144728 }
144729
144730 function _set_preview($post) {
144731
144732 if ( ! is_object($post) )
144733 return $post;
144734
144735 $preview = wp_get_post_autosave($post->ID);
144736
144737 if ( ! is_object($preview) )
144738 return $post;
144739
144740 $preview = sanitize_post($preview);
144741
144742 $post->post_content = $preview->post_content;
144743 $post->post_title = $preview->post_title;
144744 $post->post_excerpt = $preview->post_excerpt;
144745
144746 return $post;
144747 }
144748
144749 function _show_post_preview() {
144750
144751 if ( isset($_GET['preview_id']) && isset($_GET['preview_nonce']) ) {
144752 $id = (int) $_GET['preview_id'];
144753
144754 if ( false == wp_verify_nonce( $_GET['preview_nonce'], 'post_preview_' . $id ) )
144755 wp_die( __('You do not have permission to preview drafts.') );
144756
144757 add_filter('the_preview', '_set_preview');
144758 }
144759 }