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