]> scripts.mit.edu Git - autoinstalls/wordpress.git/blob - wp-includes/meta.php
WordPress 3.9-scripts
[autoinstalls/wordpress.git] / wp-includes / meta.php
1 <?php
2 /**
3  * Metadata API
4  *
5  * Functions for retrieving and manipulating metadata of various WordPress object types. Metadata
6  * for an object is a represented by a simple key-value pair. Objects may contain multiple
7  * metadata entries that share the same key and differ only in their value.
8  *
9  * @package WordPress
10  * @subpackage Meta
11  * @since 2.9.0
12  */
13
14 /**
15  * Add metadata for the specified object.
16  *
17  * @since 2.9.0
18  * @uses $wpdb WordPress database object for queries.
19  *
20  * @param string $meta_type Type of object metadata is for (e.g., comment, post, or user)
21  * @param int $object_id ID of the object metadata is for
22  * @param string $meta_key Metadata key
23  * @param mixed $meta_value Metadata value. Must be serializable if non-scalar.
24  * @param bool $unique Optional, default is false. Whether the specified metadata key should be
25  *              unique for the object. If true, and the object already has a value for the specified
26  *              metadata key, no change will be made
27  * @return int|bool The meta ID on success, false on failure.
28  */
29 function add_metadata($meta_type, $object_id, $meta_key, $meta_value, $unique = false) {
30         if ( !$meta_type || !$meta_key )
31                 return false;
32
33         if ( !$object_id = absint($object_id) )
34                 return false;
35
36         if ( ! $table = _get_meta_table($meta_type) )
37                 return false;
38
39         global $wpdb;
40
41         $column = sanitize_key($meta_type . '_id');
42
43         // expected_slashed ($meta_key)
44         $meta_key = wp_unslash($meta_key);
45         $meta_value = wp_unslash($meta_value);
46         $meta_value = sanitize_meta( $meta_key, $meta_value, $meta_type );
47
48         /**
49          * Filter whether to add metadata of a specific type.
50          *
51          * The dynamic portion of the hook, $meta_type, refers to the meta
52          * object type (comment, post, or user). Returning a non-null value
53          * will effectively short-circuit the function.
54          *
55          * @since 3.1.0
56          *
57          * @param null|bool $check      Whether to allow adding metadata for the given type.
58          * @param int       $object_id  Object ID.
59          * @param string    $meta_key   Meta key.
60          * @param mixed     $meta_value Meta value. Must be serializable if non-scalar.
61          * @param bool      $unique     Whether the specified meta key should be unique
62          *                              for the object. Optional. Default false.
63          */
64         $check = apply_filters( "add_{$meta_type}_metadata", null, $object_id, $meta_key, $meta_value, $unique );
65         if ( null !== $check )
66                 return $check;
67
68         if ( $unique && $wpdb->get_var( $wpdb->prepare(
69                 "SELECT COUNT(*) FROM $table WHERE meta_key = %s AND $column = %d",
70                 $meta_key, $object_id ) ) )
71                 return false;
72
73         $_meta_value = $meta_value;
74         $meta_value = maybe_serialize( $meta_value );
75
76         /**
77          * Fires immediately before meta of a specific type is added.
78          *
79          * The dynamic portion of the hook, $meta_type, refers to the meta
80          * object type (comment, post, or user).
81          *
82          * @since 3.1.0
83          *
84          * @param int    $object_id  Object ID.
85          * @param string $meta_key   Meta key.
86          * @param mixed  $meta_value Meta value.
87          */
88         do_action( "add_{$meta_type}_meta", $object_id, $meta_key, $_meta_value );
89
90         $result = $wpdb->insert( $table, array(
91                 $column => $object_id,
92                 'meta_key' => $meta_key,
93                 'meta_value' => $meta_value
94         ) );
95
96         if ( ! $result )
97                 return false;
98
99         $mid = (int) $wpdb->insert_id;
100
101         wp_cache_delete($object_id, $meta_type . '_meta');
102
103         /**
104          * Fires immediately after meta of a specific type is added.
105          *
106          * The dynamic portion of the hook, $meta_type, refers to the meta
107          * object type (comment, post, or user).
108          *
109          * @since 2.9.0
110          *
111          * @param int    $mid        The meta ID after successful update.
112          * @param int    $object_id  Object ID.
113          * @param string $meta_key   Meta key.
114          * @param mixed  $meta_value Meta value.
115          */
116         do_action( "added_{$meta_type}_meta", $mid, $object_id, $meta_key, $_meta_value );
117
118         return $mid;
119 }
120
121 /**
122  * Update metadata for the specified object. If no value already exists for the specified object
123  * ID and metadata key, the metadata will be added.
124  *
125  * @since 2.9.0
126  * @uses $wpdb WordPress database object for queries.
127  *
128  * @param string $meta_type Type of object metadata is for (e.g., comment, post, or user)
129  * @param int $object_id ID of the object metadata is for
130  * @param string $meta_key Metadata key
131  * @param mixed $meta_value Metadata value. Must be serializable if non-scalar.
132  * @param mixed $prev_value Optional. If specified, only update existing metadata entries with
133  *              the specified value. Otherwise, update all entries.
134  * @return int|bool Meta ID if the key didn't exist, true on successful update, false on failure.
135  */
136 function update_metadata($meta_type, $object_id, $meta_key, $meta_value, $prev_value = '') {
137         if ( !$meta_type || !$meta_key )
138                 return false;
139
140         if ( !$object_id = absint($object_id) )
141                 return false;
142
143         if ( ! $table = _get_meta_table($meta_type) )
144                 return false;
145
146         global $wpdb;
147
148         $column = sanitize_key($meta_type . '_id');
149         $id_column = 'user' == $meta_type ? 'umeta_id' : 'meta_id';
150
151         // expected_slashed ($meta_key)
152         $meta_key = wp_unslash($meta_key);
153         $passed_value = $meta_value;
154         $meta_value = wp_unslash($meta_value);
155         $meta_value = sanitize_meta( $meta_key, $meta_value, $meta_type );
156
157         /**
158          * Filter whether to update metadata of a specific type.
159          *
160          * The dynamic portion of the hook, $meta_type, refers to the meta
161          * object type (comment, post, or user). Returning a non-null value
162          * will effectively short-circuit the function.
163          *
164          * @since 3.1.0
165          *
166          * @param null|bool $check      Whether to allow updating metadata for the given type.
167          * @param int       $object_id  Object ID.
168          * @param string    $meta_key   Meta key.
169          * @param mixed     $meta_value Meta value. Must be serializable if non-scalar.
170          * @param mixed     $prev_value Optional. If specified, only update existing
171          *                              metadata entries with the specified value.
172          *                              Otherwise, update all entries.
173          */
174         $check = apply_filters( "update_{$meta_type}_metadata", null, $object_id, $meta_key, $meta_value, $prev_value );
175         if ( null !== $check )
176                 return (bool) $check;
177
178         // Compare existing value to new value if no prev value given and the key exists only once.
179         if ( empty($prev_value) ) {
180                 $old_value = get_metadata($meta_type, $object_id, $meta_key);
181                 if ( count($old_value) == 1 ) {
182                         if ( $old_value[0] === $meta_value )
183                                 return false;
184                 }
185         }
186
187         if ( ! $meta_id = $wpdb->get_var( $wpdb->prepare( "SELECT $id_column FROM $table WHERE meta_key = %s AND $column = %d", $meta_key, $object_id ) ) )
188                 return add_metadata($meta_type, $object_id, $meta_key, $passed_value);
189
190         $_meta_value = $meta_value;
191         $meta_value = maybe_serialize( $meta_value );
192
193         $data  = compact( 'meta_value' );
194         $where = array( $column => $object_id, 'meta_key' => $meta_key );
195
196         if ( !empty( $prev_value ) ) {
197                 $prev_value = maybe_serialize($prev_value);
198                 $where['meta_value'] = $prev_value;
199         }
200
201         /**
202          * Fires immediately before updating metadata of a specific type.
203          *
204          * The dynamic portion of the hook, $meta_type, refers to the meta
205          * object type (comment, post, or user).
206          *
207          * @since 2.9.0
208          *
209          * @param int    $meta_id    ID of the metadata entry to update.
210          * @param int    $object_id  Object ID.
211          * @param string $meta_key   Meta key.
212          * @param mixed  $meta_value Meta value.
213          */
214         do_action( "update_{$meta_type}_meta", $meta_id, $object_id, $meta_key, $_meta_value );
215
216         if ( 'post' == $meta_type )
217                 /**
218                  * Fires immediately before updating a post's metadata.
219                  *
220                  * @since 2.9.0
221                  *
222                  * @param int    $meta_id    ID of metadata entry to update.
223                  * @param int    $object_id  Object ID.
224                  * @param string $meta_key   Meta key.
225                  * @param mixed  $meta_value Meta value.
226                  */
227                 do_action( 'update_postmeta', $meta_id, $object_id, $meta_key, $meta_value );
228
229         $result = $wpdb->update( $table, $data, $where );
230         if ( ! $result )
231                 return false;
232
233         wp_cache_delete($object_id, $meta_type . '_meta');
234
235         /**
236          * Fires immediately after updating metadata of a specific type.
237          *
238          * The dynamic portion of the hook, $meta_type, refers to the meta
239          * object type (comment, post, or user).
240          *
241          * @since 2.9.0
242          *
243          * @param int    $meta_id    ID of updated metadata entry.
244          * @param int    $object_id  Object ID.
245          * @param string $meta_key   Meta key.
246          * @param mixed  $meta_value Meta value.
247          */
248         do_action( "updated_{$meta_type}_meta", $meta_id, $object_id, $meta_key, $_meta_value );
249
250         if ( 'post' == $meta_type ) {
251                 /**
252                  * Fires immediately after updating a post's metadata.
253                  *
254                  * @since 2.9.0
255                  *
256                  * @param int    $meta_id    ID of updated metadata entry.
257                  * @param int    $object_id  Object ID.
258                  * @param string $meta_key   Meta key.
259                  * @param mixed  $meta_value Meta value.
260                  */
261                 do_action( 'updated_postmeta', $meta_id, $object_id, $meta_key, $meta_value );
262         }
263
264         return true;
265 }
266
267 /**
268  * Delete metadata for the specified object.
269  *
270  * @since 2.9.0
271  * @uses $wpdb WordPress database object for queries.
272  *
273  * @param string $meta_type Type of object metadata is for (e.g., comment, post, or user)
274  * @param int $object_id ID of the object metadata is for
275  * @param string $meta_key Metadata key
276  * @param mixed $meta_value Optional. Metadata value. Must be serializable if non-scalar. If specified, only delete metadata entries
277  *              with this value. Otherwise, delete all entries with the specified meta_key.
278  * @param bool $delete_all Optional, default is false. If true, delete matching metadata entries
279  *              for all objects, ignoring the specified object_id. Otherwise, only delete matching
280  *              metadata entries for the specified object_id.
281  * @return bool True on successful delete, false on failure.
282  */
283 function delete_metadata($meta_type, $object_id, $meta_key, $meta_value = '', $delete_all = false) {
284         if ( !$meta_type || !$meta_key )
285                 return false;
286
287         if ( (!$object_id = absint($object_id)) && !$delete_all )
288                 return false;
289
290         if ( ! $table = _get_meta_table($meta_type) )
291                 return false;
292
293         global $wpdb;
294
295         $type_column = sanitize_key($meta_type . '_id');
296         $id_column = 'user' == $meta_type ? 'umeta_id' : 'meta_id';
297         // expected_slashed ($meta_key)
298         $meta_key = wp_unslash($meta_key);
299         $meta_value = wp_unslash($meta_value);
300
301         /**
302          * Filter whether to delete metadata of a specific type.
303          *
304          * The dynamic portion of the hook, $meta_type, refers to the meta
305          * object type (comment, post, or user). Returning a non-null value
306          * will effectively short-circuit the function.
307          *
308          * @since 3.1.0
309          *
310          * @param null|bool $delete     Whether to allow metadata deletion of the given type.
311          * @param int       $object_id  Object ID.
312          * @param string    $meta_key   Meta key.
313          * @param mixed     $meta_value Meta value. Must be serializable if non-scalar.
314          * @param bool      $delete_all Whether to delete the matching metadata entries
315          *                              for all objects, ignoring the specified $object_id.
316          *                              Default false.
317          */
318         $check = apply_filters( "delete_{$meta_type}_metadata", null, $object_id, $meta_key, $meta_value, $delete_all );
319         if ( null !== $check )
320                 return (bool) $check;
321
322         $_meta_value = $meta_value;
323         $meta_value = maybe_serialize( $meta_value );
324
325         $query = $wpdb->prepare( "SELECT $id_column FROM $table WHERE meta_key = %s", $meta_key );
326
327         if ( !$delete_all )
328                 $query .= $wpdb->prepare(" AND $type_column = %d", $object_id );
329
330         if ( $meta_value )
331                 $query .= $wpdb->prepare(" AND meta_value = %s", $meta_value );
332
333         $meta_ids = $wpdb->get_col( $query );
334         if ( !count( $meta_ids ) )
335                 return false;
336
337         if ( $delete_all )
338                 $object_ids = $wpdb->get_col( $wpdb->prepare( "SELECT $type_column FROM $table WHERE meta_key = %s", $meta_key ) );
339
340         /**
341          * Fires immediately before deleting metadata of a specific type.
342          *
343          * The dynamic portion of the hook, $meta_type, refers to the meta
344          * object type (comment, post, or user).
345          *
346          * @since 3.1.0
347          *
348          * @param array  $meta_ids   An array of metadata entry IDs to delete.
349          * @param int    $object_id  Object ID.
350          * @param string $meta_key   Meta key.
351          * @param mixed  $meta_value Meta value.
352          */
353         do_action( "delete_{$meta_type}_meta", $meta_ids, $object_id, $meta_key, $_meta_value );
354
355         // Old-style action.
356         if ( 'post' == $meta_type ) {
357                 /**
358                  * Fires immediately before deleting metadata for a post.
359                  *
360                  * @since 2.9.0
361                  *
362                  * @param array $meta_ids An array of post metadata entry IDs to delete.
363                  */
364                 do_action( 'delete_postmeta', $meta_ids );
365         }
366
367         $query = "DELETE FROM $table WHERE $id_column IN( " . implode( ',', $meta_ids ) . " )";
368
369         $count = $wpdb->query($query);
370
371         if ( !$count )
372                 return false;
373
374         if ( $delete_all ) {
375                 foreach ( (array) $object_ids as $o_id ) {
376                         wp_cache_delete($o_id, $meta_type . '_meta');
377                 }
378         } else {
379                 wp_cache_delete($object_id, $meta_type . '_meta');
380         }
381
382         /**
383          * Fires immediately after deleting metadata of a specific type.
384          *
385          * The dynamic portion of the hook name, $meta_type, refers to the meta
386          * object type (comment, post, or user).
387          *
388          * @since 2.9.0
389          *
390          * @param array  $meta_ids   An array of deleted metadata entry IDs.
391          * @param int    $object_id  Object ID.
392          * @param string $meta_key   Meta key.
393          * @param mixed  $meta_value Meta value.
394          */
395         do_action( "deleted_{$meta_type}_meta", $meta_ids, $object_id, $meta_key, $_meta_value );
396
397         // Old-style action.
398         if ( 'post' == $meta_type ) {
399                 /**
400                  * Fires immediately after deleting metadata for a post.
401                  *
402                  * @since 2.9.0
403                  *
404                  * @param array $meta_ids An array of deleted post metadata entry IDs.
405                  */
406                 do_action( 'deleted_postmeta', $meta_ids );
407         }
408
409         return true;
410 }
411
412 /**
413  * Retrieve metadata for the specified object.
414  *
415  * @since 2.9.0
416  *
417  * @param string $meta_type Type of object metadata is for (e.g., comment, post, or user)
418  * @param int $object_id ID of the object metadata is for
419  * @param string $meta_key Optional. Metadata key. If not specified, retrieve all metadata for
420  *              the specified object.
421  * @param bool $single Optional, default is false. If true, return only the first value of the
422  *              specified meta_key. This parameter has no effect if meta_key is not specified.
423  * @return string|array Single metadata value, or array of values
424  */
425 function get_metadata($meta_type, $object_id, $meta_key = '', $single = false) {
426         if ( !$meta_type )
427                 return false;
428
429         if ( !$object_id = absint($object_id) )
430                 return false;
431
432         /**
433          * Filter whether to retrieve metadata of a specific type.
434          *
435          * The dynamic portion of the hook, $meta_type, refers to the meta
436          * object type (comment, post, or user). Returning a non-null value
437          * will effectively short-circuit the function.
438          *
439          * @since 3.1.0
440          *
441          * @param null|array|string $value     The value get_metadata() should
442          *                                     return - a single metadata value,
443          *                                     or an array of values.
444          * @param int               $object_id Object ID.
445          * @param string            $meta_key  Meta key.
446          * @param string|array      $single    Meta value, or an array of values.
447          */
448         $check = apply_filters( "get_{$meta_type}_metadata", null, $object_id, $meta_key, $single );
449         if ( null !== $check ) {
450                 if ( $single && is_array( $check ) )
451                         return $check[0];
452                 else
453                         return $check;
454         }
455
456         $meta_cache = wp_cache_get($object_id, $meta_type . '_meta');
457
458         if ( !$meta_cache ) {
459                 $meta_cache = update_meta_cache( $meta_type, array( $object_id ) );
460                 $meta_cache = $meta_cache[$object_id];
461         }
462
463         if ( !$meta_key )
464                 return $meta_cache;
465
466         if ( isset($meta_cache[$meta_key]) ) {
467                 if ( $single )
468                         return maybe_unserialize( $meta_cache[$meta_key][0] );
469                 else
470                         return array_map('maybe_unserialize', $meta_cache[$meta_key]);
471         }
472
473         if ($single)
474                 return '';
475         else
476                 return array();
477 }
478
479 /**
480  * Determine if a meta key is set for a given object
481  *
482  * @since 3.3.0
483  *
484  * @param string $meta_type Type of object metadata is for (e.g., comment, post, or user)
485  * @param int $object_id ID of the object metadata is for
486  * @param string $meta_key Metadata key.
487  * @return boolean true of the key is set, false if not.
488  */
489 function metadata_exists( $meta_type, $object_id, $meta_key ) {
490         if ( ! $meta_type )
491                 return false;
492
493         if ( ! $object_id = absint( $object_id ) )
494                 return false;
495
496         /** This filter is documented in wp-includes/meta.php */
497         $check = apply_filters( "get_{$meta_type}_metadata", null, $object_id, $meta_key, true );
498         if ( null !== $check )
499                 return (bool) $check;
500
501         $meta_cache = wp_cache_get( $object_id, $meta_type . '_meta' );
502
503         if ( !$meta_cache ) {
504                 $meta_cache = update_meta_cache( $meta_type, array( $object_id ) );
505                 $meta_cache = $meta_cache[$object_id];
506         }
507
508         if ( isset( $meta_cache[ $meta_key ] ) )
509                 return true;
510
511         return false;
512 }
513
514 /**
515  * Get meta data by meta ID
516  *
517  * @since 3.3.0
518  *
519  * @param string $meta_type Type of object metadata is for (e.g., comment, post, or user)
520  * @param int $meta_id ID for a specific meta row
521  * @return object Meta object or false.
522  */
523 function get_metadata_by_mid( $meta_type, $meta_id ) {
524         global $wpdb;
525
526         if ( ! $meta_type )
527                 return false;
528
529         if ( !$meta_id = absint( $meta_id ) )
530                 return false;
531
532         if ( ! $table = _get_meta_table($meta_type) )
533                 return false;
534
535         $id_column = ( 'user' == $meta_type ) ? 'umeta_id' : 'meta_id';
536
537         $meta = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $table WHERE $id_column = %d", $meta_id ) );
538
539         if ( empty( $meta ) )
540                 return false;
541
542         if ( isset( $meta->meta_value ) )
543                 $meta->meta_value = maybe_unserialize( $meta->meta_value );
544
545         return $meta;
546 }
547
548 /**
549  * Update meta data by meta ID
550  *
551  * @since 3.3.0
552  *
553  * @uses get_metadata_by_mid() Calls get_metadata_by_mid() to fetch the meta key, value
554  *              and object_id of the given meta_id.
555  *
556  * @param string $meta_type Type of object metadata is for (e.g., comment, post, or user)
557  * @param int $meta_id ID for a specific meta row
558  * @param string $meta_value Metadata value
559  * @param string $meta_key Optional, you can provide a meta key to update it
560  * @return bool True on successful update, false on failure.
561  */
562 function update_metadata_by_mid( $meta_type, $meta_id, $meta_value, $meta_key = false ) {
563         global $wpdb;
564
565         // Make sure everything is valid.
566         if ( ! $meta_type )
567                 return false;
568
569         if ( ! $meta_id = absint( $meta_id ) )
570                 return false;
571
572         if ( ! $table = _get_meta_table( $meta_type ) )
573                 return false;
574
575         $column = sanitize_key($meta_type . '_id');
576         $id_column = 'user' == $meta_type ? 'umeta_id' : 'meta_id';
577
578         // Fetch the meta and go on if it's found.
579         if ( $meta = get_metadata_by_mid( $meta_type, $meta_id ) ) {
580                 $original_key = $meta->meta_key;
581                 $original_value = $meta->meta_value;
582                 $object_id = $meta->{$column};
583
584                 // If a new meta_key (last parameter) was specified, change the meta key,
585                 // otherwise use the original key in the update statement.
586                 if ( false === $meta_key ) {
587                         $meta_key = $original_key;
588                 } elseif ( ! is_string( $meta_key ) ) {
589                         return false;
590                 }
591
592                 // Sanitize the meta
593                 $_meta_value = $meta_value;
594                 $meta_value = sanitize_meta( $meta_key, $meta_value, $meta_type );
595                 $meta_value = maybe_serialize( $meta_value );
596
597                 // Format the data query arguments.
598                 $data = array(
599                         'meta_key' => $meta_key,
600                         'meta_value' => $meta_value
601                 );
602
603                 // Format the where query arguments.
604                 $where = array();
605                 $where[$id_column] = $meta_id;
606
607                 /** This action is documented in wp-includes/meta.php */
608                 do_action( "update_{$meta_type}_meta", $meta_id, $object_id, $meta_key, $_meta_value );
609
610                 if ( 'post' == $meta_type ) {
611                         /** This action is documented in wp-includes/meta.php */
612                         do_action( 'update_postmeta', $meta_id, $object_id, $meta_key, $meta_value );
613                 }
614
615                 // Run the update query, all fields in $data are %s, $where is a %d.
616                 $result = $wpdb->update( $table, $data, $where, '%s', '%d' );
617                 if ( ! $result )
618                         return false;
619
620                 // Clear the caches.
621                 wp_cache_delete($object_id, $meta_type . '_meta');
622
623                 /** This action is documented in wp-includes/meta.php */
624                 do_action( "updated_{$meta_type}_meta", $meta_id, $object_id, $meta_key, $_meta_value );
625
626                 if ( 'post' == $meta_type ) {
627                         /** This action is documented in wp-includes/meta.php */
628                         do_action( 'updated_postmeta', $meta_id, $object_id, $meta_key, $meta_value );
629                 }
630
631                 return true;
632         }
633
634         // And if the meta was not found.
635         return false;
636 }
637
638 /**
639  * Delete meta data by meta ID
640  *
641  * @since 3.3.0
642  *
643  * @uses get_metadata_by_mid() Calls get_metadata_by_mid() to fetch the meta key, value
644  *              and object_id of the given meta_id.
645  *
646  * @param string $meta_type Type of object metadata is for (e.g., comment, post, or user)
647  * @param int $meta_id ID for a specific meta row
648  * @return bool True on successful delete, false on failure.
649  */
650 function delete_metadata_by_mid( $meta_type, $meta_id ) {
651         global $wpdb;
652
653         // Make sure everything is valid.
654         if ( ! $meta_type )
655                 return false;
656
657         if ( ! $meta_id = absint( $meta_id ) )
658                 return false;
659
660         if ( ! $table = _get_meta_table( $meta_type ) )
661                 return false;
662
663         // object and id columns
664         $column = sanitize_key($meta_type . '_id');
665         $id_column = 'user' == $meta_type ? 'umeta_id' : 'meta_id';
666
667         // Fetch the meta and go on if it's found.
668         if ( $meta = get_metadata_by_mid( $meta_type, $meta_id ) ) {
669                 $object_id = $meta->{$column};
670
671                 /** This action is documented in wp-includes/meta.php */
672                 do_action( "delete_{$meta_type}_meta", (array) $meta_id, $object_id, $meta->meta_key, $meta->meta_value );
673
674                 // Old-style action.
675                 if ( 'post' == $meta_type || 'comment' == $meta_type ) {
676                         /**
677                          * Fires immediately before deleting post or comment metadata of a specific type.
678                          *
679                          * The dynamic portion of the hook, $meta_type, refers to the meta
680                          * object type (post or comment).
681                          *
682                          * @since 3.4.0
683                          *
684                          * @param int $meta_id ID of the metadata entry to delete.
685                          */
686                         do_action( "delete_{$meta_type}meta", $meta_id );
687                 }
688
689                 // Run the query, will return true if deleted, false otherwise
690                 $result = (bool) $wpdb->delete( $table, array( $id_column => $meta_id ) );
691
692                 // Clear the caches.
693                 wp_cache_delete($object_id, $meta_type . '_meta');
694
695                 /** This action is documented in wp-includes/meta.php */
696                 do_action( "deleted_{$meta_type}_meta", (array) $meta_id, $object_id, $meta->meta_key, $meta->meta_value );
697
698                 // Old-style action.
699                 if ( 'post' == $meta_type || 'comment' == $meta_type ) {
700                         /**
701                          * Fires immediately after deleting post or comment metadata of a specific type.
702                          *
703                          * The dynamic portion of the hook, $meta_type, refers to the meta
704                          * object type (post or comment).
705                          *
706                          * @since 3.4.0
707                          *
708                          * @param int $meta_ids Deleted metadata entry ID.
709                          */
710                         do_action( "deleted_{$meta_type}meta", $meta_id );
711                 }
712
713                 return $result;
714
715         }
716
717         // Meta id was not found.
718         return false;
719 }
720
721 /**
722  * Update the metadata cache for the specified objects.
723  *
724  * @since 2.9.0
725  * @uses $wpdb WordPress database object for queries.
726  *
727  * @param string $meta_type Type of object metadata is for (e.g., comment, post, or user)
728  * @param int|array $object_ids array or comma delimited list of object IDs to update cache for
729  * @return mixed Metadata cache for the specified objects, or false on failure.
730  */
731 function update_meta_cache($meta_type, $object_ids) {
732         if ( empty( $meta_type ) || empty( $object_ids ) )
733                 return false;
734
735         if ( ! $table = _get_meta_table($meta_type) )
736                 return false;
737
738         $column = sanitize_key($meta_type . '_id');
739
740         global $wpdb;
741
742         if ( !is_array($object_ids) ) {
743                 $object_ids = preg_replace('|[^0-9,]|', '', $object_ids);
744                 $object_ids = explode(',', $object_ids);
745         }
746
747         $object_ids = array_map('intval', $object_ids);
748
749         $cache_key = $meta_type . '_meta';
750         $ids = array();
751         $cache = array();
752         foreach ( $object_ids as $id ) {
753                 $cached_object = wp_cache_get( $id, $cache_key );
754                 if ( false === $cached_object )
755                         $ids[] = $id;
756                 else
757                         $cache[$id] = $cached_object;
758         }
759
760         if ( empty( $ids ) )
761                 return $cache;
762
763         // Get meta info
764         $id_list = join( ',', $ids );
765         $id_column = 'user' == $meta_type ? 'umeta_id' : 'meta_id';
766         $meta_list = $wpdb->get_results( "SELECT $column, meta_key, meta_value FROM $table WHERE $column IN ($id_list) ORDER BY $id_column ASC", ARRAY_A );
767
768         if ( !empty($meta_list) ) {
769                 foreach ( $meta_list as $metarow) {
770                         $mpid = intval($metarow[$column]);
771                         $mkey = $metarow['meta_key'];
772                         $mval = $metarow['meta_value'];
773
774                         // Force subkeys to be array type:
775                         if ( !isset($cache[$mpid]) || !is_array($cache[$mpid]) )
776                                 $cache[$mpid] = array();
777                         if ( !isset($cache[$mpid][$mkey]) || !is_array($cache[$mpid][$mkey]) )
778                                 $cache[$mpid][$mkey] = array();
779
780                         // Add a value to the current pid/key:
781                         $cache[$mpid][$mkey][] = $mval;
782                 }
783         }
784
785         foreach ( $ids as $id ) {
786                 if ( ! isset($cache[$id]) )
787                         $cache[$id] = array();
788                 wp_cache_add( $id, $cache[$id], $cache_key );
789         }
790
791         return $cache;
792 }
793
794 /**
795  * Given a meta query, generates SQL clauses to be appended to a main query
796  *
797  * @since 3.2.0
798  *
799  * @see WP_Meta_Query
800  *
801  * @param array $meta_query A meta query
802  * @param string $type Type of meta
803  * @param string $primary_table
804  * @param string $primary_id_column
805  * @param object $context (optional) The main query object
806  * @return array( 'join' => $join_sql, 'where' => $where_sql )
807  */
808 function get_meta_sql( $meta_query, $type, $primary_table, $primary_id_column, $context = null ) {
809         $meta_query_obj = new WP_Meta_Query( $meta_query );
810         return $meta_query_obj->get_sql( $type, $primary_table, $primary_id_column, $context );
811 }
812
813 /**
814  * Container class for a multiple metadata query
815  *
816  * @since 3.2.0
817  */
818 class WP_Meta_Query {
819         /**
820         * List of metadata queries. A single query is an associative array:
821         * - 'key' string The meta key
822         * - 'value' string|array The meta value
823         * - 'compare' (optional) string How to compare the key to the value.
824         *              Possible values: '=', '!=', '>', '>=', '<', '<=', 'LIKE', 'NOT LIKE', 'IN', 'NOT IN',
825         *              'BETWEEN', 'NOT BETWEEN', 'REGEXP', 'NOT REGEXP', 'RLIKE'.
826         *              Default: '='
827         * - 'type' string (optional) The type of the value.
828         *              Possible values: 'NUMERIC', 'BINARY', 'CHAR', 'DATE', 'DATETIME', 'DECIMAL', 'SIGNED', 'TIME', 'UNSIGNED'.
829         *              Default: 'CHAR'
830         *
831         * @since 3.2.0
832         * @access public
833         * @var array
834         */
835         public $queries = array();
836
837         /**
838          * The relation between the queries. Can be one of 'AND' or 'OR'.
839          *
840          * @since 3.2.0
841          * @access public
842          * @var string
843          */
844         public $relation;
845
846         /**
847          * Constructor
848          *
849          * @param array $meta_query (optional) A meta query
850          */
851         function __construct( $meta_query = false ) {
852                 if ( !$meta_query )
853                         return;
854
855                 if ( isset( $meta_query['relation'] ) && strtoupper( $meta_query['relation'] ) == 'OR' ) {
856                         $this->relation = 'OR';
857                 } else {
858                         $this->relation = 'AND';
859                 }
860
861                 $this->queries = array();
862
863                 foreach ( $meta_query as $key => $query ) {
864                         if ( ! is_array( $query ) )
865                                 continue;
866
867                         $this->queries[] = $query;
868                 }
869         }
870
871         /**
872          * Constructs a meta query based on 'meta_*' query vars
873          *
874          * @since 3.2.0
875          * @access public
876          *
877          * @param array $qv The query variables
878          */
879         function parse_query_vars( $qv ) {
880                 $meta_query = array();
881
882                 // Simple query needs to be first for orderby=meta_value to work correctly
883                 foreach ( array( 'key', 'compare', 'type' ) as $key ) {
884                         if ( !empty( $qv[ "meta_$key" ] ) )
885                                 $meta_query[0][ $key ] = $qv[ "meta_$key" ];
886                 }
887
888                 // WP_Query sets 'meta_value' = '' by default
889                 if ( isset( $qv[ 'meta_value' ] ) && '' !== $qv[ 'meta_value' ] && ( ! is_array( $qv[ 'meta_value' ] ) || $qv[ 'meta_value' ] ) )
890                         $meta_query[0]['value'] = $qv[ 'meta_value' ];
891
892                 if ( !empty( $qv['meta_query'] ) && is_array( $qv['meta_query'] ) ) {
893                         $meta_query = array_merge( $meta_query, $qv['meta_query'] );
894                 }
895
896                 $this->__construct( $meta_query );
897         }
898
899         /**
900          * Given a meta type, return the appropriate alias if applicable
901          *
902          * @since 3.7.0
903          *
904          * @param string $type MySQL type to cast meta_value
905          * @return string MySQL type
906          */
907         function get_cast_for_type( $type = '' ) {
908                 if ( empty( $type ) )
909                         return 'CHAR';
910
911                 $meta_type = strtoupper( $type );
912
913                 if ( ! preg_match( '/^(?:BINARY|CHAR|DATE|DATETIME|SIGNED|UNSIGNED|TIME|NUMERIC(?:\(\d+(?:,\s?\d+)?\))?|DECIMAL(?:\(\d+(?:,\s?\d+)?\))?)$/', $meta_type ) )
914                         return 'CHAR';
915
916                 if ( 'NUMERIC' == $meta_type )
917                         $meta_type = 'SIGNED';
918
919                 return $meta_type;
920         }
921
922         /**
923          * Generates SQL clauses to be appended to a main query.
924          *
925          * @since 3.2.0
926          * @access public
927          *
928          * @param string $type Type of meta
929          * @param string $primary_table
930          * @param string $primary_id_column
931          * @param object $context (optional) The main query object
932          * @return array( 'join' => $join_sql, 'where' => $where_sql )
933          */
934         function get_sql( $type, $primary_table, $primary_id_column, $context = null ) {
935                 global $wpdb;
936
937                 if ( ! $meta_table = _get_meta_table( $type ) )
938                         return false;
939
940                 $meta_id_column = sanitize_key( $type . '_id' );
941
942                 $join = array();
943                 $where = array();
944
945                 $key_only_queries = array();
946                 $queries = array();
947
948                 // Split out the queries with empty arrays as value
949                 foreach ( $this->queries as $k => $q ) {
950                         if ( isset( $q['value'] ) && is_array( $q['value'] ) && empty( $q['value'] ) ) {
951                                 $key_only_queries[$k] = $q;
952                                 unset( $this->queries[$k] );
953                         }
954                 }
955
956                 // Split out the meta_key only queries (we can only do this for OR)
957                 if ( 'OR' == $this->relation ) {
958                         foreach ( $this->queries as $k => $q ) {
959                                 if ( ( empty( $q['compare'] ) || 'NOT EXISTS' != $q['compare'] ) && ! array_key_exists( 'value', $q ) && ! empty( $q['key'] ) )
960                                         $key_only_queries[$k] = $q;
961                                 else
962                                         $queries[$k] = $q;
963                         }
964                 } else {
965                         $queries = $this->queries;
966                 }
967
968                 // Specify all the meta_key only queries in one go
969                 if ( $key_only_queries ) {
970                         $join[]  = "INNER JOIN $meta_table ON $primary_table.$primary_id_column = $meta_table.$meta_id_column";
971
972                         foreach ( $key_only_queries as $key => $q )
973                                 $where["key-only-$key"] = $wpdb->prepare( "$meta_table.meta_key = %s", trim( $q['key'] ) );
974                 }
975
976                 foreach ( $queries as $k => $q ) {
977                         $meta_key = isset( $q['key'] ) ? trim( $q['key'] ) : '';
978                         $meta_type = $this->get_cast_for_type( isset( $q['type'] ) ? $q['type'] : '' );
979
980                         if ( array_key_exists( 'value', $q ) && is_null( $q['value'] ) )
981                                 $q['value'] = '';
982
983                         $meta_value = isset( $q['value'] ) ? $q['value'] : null;
984
985                         if ( isset( $q['compare'] ) )
986                                 $meta_compare = strtoupper( $q['compare'] );
987                         else
988                                 $meta_compare = is_array( $meta_value ) ? 'IN' : '=';
989
990                         if ( ! in_array( $meta_compare, array(
991                                 '=', '!=', '>', '>=', '<', '<=',
992                                 'LIKE', 'NOT LIKE',
993                                 'IN', 'NOT IN',
994                                 'BETWEEN', 'NOT BETWEEN',
995                                 'NOT EXISTS',
996                                 'REGEXP', 'NOT REGEXP', 'RLIKE'
997                         ) ) )
998                                 $meta_compare = '=';
999
1000                         $i = count( $join );
1001                         $alias = $i ? 'mt' . $i : $meta_table;
1002
1003                         if ( 'NOT EXISTS' == $meta_compare ) {
1004                                 $join[$i]  = "LEFT JOIN $meta_table";
1005                                 $join[$i] .= $i ? " AS $alias" : '';
1006                                 $join[$i] .= " ON ($primary_table.$primary_id_column = $alias.$meta_id_column AND $alias.meta_key = '$meta_key')";
1007
1008                                 $where[$k] = ' ' . $alias . '.' . $meta_id_column . ' IS NULL';
1009
1010                                 continue;
1011                         }
1012
1013                         $join[$i]  = "INNER JOIN $meta_table";
1014                         $join[$i] .= $i ? " AS $alias" : '';
1015                         $join[$i] .= " ON ($primary_table.$primary_id_column = $alias.$meta_id_column)";
1016
1017                         $where[$k] = '';
1018                         if ( !empty( $meta_key ) )
1019                                 $where[$k] = $wpdb->prepare( "$alias.meta_key = %s", $meta_key );
1020
1021                         if ( is_null( $meta_value ) ) {
1022                                 if ( empty( $where[$k] ) )
1023                                         unset( $join[$i] );
1024                                 continue;
1025                         }
1026
1027                         if ( in_array( $meta_compare, array( 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN' ) ) ) {
1028                                 if ( ! is_array( $meta_value ) )
1029                                         $meta_value = preg_split( '/[,\s]+/', $meta_value );
1030
1031                                 if ( empty( $meta_value ) ) {
1032                                         unset( $join[$i] );
1033                                         continue;
1034                                 }
1035                         } else {
1036                                 $meta_value = trim( $meta_value );
1037                         }
1038
1039                         if ( 'IN' == substr( $meta_compare, -2) ) {
1040                                 $meta_compare_string = '(' . substr( str_repeat( ',%s', count( $meta_value ) ), 1 ) . ')';
1041                         } elseif ( 'BETWEEN' == substr( $meta_compare, -7) ) {
1042                                 $meta_value = array_slice( $meta_value, 0, 2 );
1043                                 $meta_compare_string = '%s AND %s';
1044                         } elseif ( 'LIKE' == substr( $meta_compare, -4 ) ) {
1045                                 $meta_value = '%' . like_escape( $meta_value ) . '%';
1046                                 $meta_compare_string = '%s';
1047                         } else {
1048                                 $meta_compare_string = '%s';
1049                         }
1050
1051                         if ( ! empty( $where[$k] ) )
1052                                 $where[$k] .= ' AND ';
1053
1054                         $where[$k] = ' (' . $where[$k] . $wpdb->prepare( "CAST($alias.meta_value AS {$meta_type}) {$meta_compare} {$meta_compare_string})", $meta_value );
1055                 }
1056
1057                 $where = array_filter( $where );
1058
1059                 if ( empty( $where ) )
1060                         $where = '';
1061                 else
1062                         $where = ' AND (' . implode( "\n{$this->relation} ", $where ) . ' )';
1063
1064                 $join = implode( "\n", $join );
1065                 if ( ! empty( $join ) )
1066                         $join = ' ' . $join;
1067
1068                 /**
1069                  * Filter the meta query's generated SQL.
1070                  *
1071                  * @since 3.1.0
1072                  *
1073                  * @param array $args {
1074                  *     An array of arguments.
1075                  *
1076                  *     @type array  $clauses           Array containing the query's JOIN and WHERE clauses.
1077                  *     @type array  $queries           Array of meta queries.
1078                  *     @type string $type              Type of meta.
1079                  *     @type string $primary_table     Primary table.
1080                  *     @type string $primary_id_column Primary column ID.
1081                  *     @type object $context           The main query object.
1082                  * }
1083                  */
1084                 return apply_filters_ref_array( 'get_meta_sql', array( compact( 'join', 'where' ), $this->queries, $type, $primary_table, $primary_id_column, $context ) );
1085         }
1086 }
1087
1088 /**
1089  * Retrieve the name of the metadata table for the specified object type.
1090  *
1091  * @since 2.9.0
1092  * @uses $wpdb WordPress database object for queries.
1093  *
1094  * @param string $type Type of object to get metadata table for (e.g., comment, post, or user)
1095  * @return mixed Metadata table name, or false if no metadata table exists
1096  */
1097 function _get_meta_table($type) {
1098         global $wpdb;
1099
1100         $table_name = $type . 'meta';
1101
1102         if ( empty($wpdb->$table_name) )
1103                 return false;
1104
1105         return $wpdb->$table_name;
1106 }
1107
1108 /**
1109  * Determine whether a meta key is protected.
1110  *
1111  * @since 3.1.3
1112  *
1113  * @param string $meta_key Meta key
1114  * @return bool True if the key is protected, false otherwise.
1115  */
1116 function is_protected_meta( $meta_key, $meta_type = null ) {
1117         $protected = ( '_' == $meta_key[0] );
1118
1119         /**
1120          * Filter whether a meta key is protected.
1121          *
1122          * @since 3.2.0
1123          *
1124          * @param bool   $protected Whether the key is protected. Default false.
1125          * @param string $meta_key  Meta key.
1126          * @param string $meta_type Meta type.
1127          */
1128         return apply_filters( 'is_protected_meta', $protected, $meta_key, $meta_type );
1129 }
1130
1131 /**
1132  * Sanitize meta value.
1133  *
1134  * @since 3.1.3
1135  *
1136  * @param string $meta_key Meta key
1137  * @param mixed $meta_value Meta value to sanitize
1138  * @param string $meta_type Type of meta
1139  * @return mixed Sanitized $meta_value
1140  */
1141 function sanitize_meta( $meta_key, $meta_value, $meta_type ) {
1142
1143         /**
1144          * Filter the sanitization of a specific meta key of a specific meta type.
1145          *
1146          * The dynamic portions of the hook name, $meta_type and $meta_key, refer to the
1147          * metadata object type (comment, post, or user) and the meta key value,
1148          * respectively.
1149          *
1150          * @since 3.3.0
1151          *
1152          * @param mixed  $meta_value Meta value to sanitize.
1153          * @param string $meta_key   Meta key.
1154          * @param string $meta_type  Meta type.
1155          */
1156         return apply_filters( "sanitize_{$meta_type}_meta_{$meta_key}", $meta_value, $meta_key, $meta_type );
1157 }
1158
1159 /**
1160  * Register meta key
1161  *
1162  * @since 3.3.0
1163  *
1164  * @param string $meta_type Type of meta
1165  * @param string $meta_key Meta key
1166  * @param string|array $sanitize_callback A function or method to call when sanitizing the value of $meta_key.
1167  * @param string|array $auth_callback Optional. A function or method to call when performing edit_post_meta, add_post_meta, and delete_post_meta capability checks.
1168  * @param array $args Arguments
1169  */
1170 function register_meta( $meta_type, $meta_key, $sanitize_callback, $auth_callback = null ) {
1171         if ( is_callable( $sanitize_callback ) )
1172                 add_filter( "sanitize_{$meta_type}_meta_{$meta_key}", $sanitize_callback, 10, 3 );
1173
1174         if ( empty( $auth_callback ) ) {
1175                 if ( is_protected_meta( $meta_key, $meta_type ) )
1176                         $auth_callback = '__return_false';
1177                 else
1178                         $auth_callback = '__return_true';
1179         }
1180
1181         if ( is_callable( $auth_callback ) )
1182                 add_filter( "auth_{$meta_type}_meta_{$meta_key}", $auth_callback, 10, 6 );
1183 }