Make WordPress Core

source: trunk/wp-includes/post.php @ 16422

Last change on this file since 16422 was 16422, checked in by nacin, 14 years ago

Don't check post_type_supports in map_meta_cap. see #14122.

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