]> scripts.mit.edu Git - autoinstalls/wordpress.git/blob - wp-includes/meta.php
Wordpress 3.1.4-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  * @uses do_action() Calls 'added_{$meta_type}_meta' with meta_id of added metadata entry,
20  *              object ID, meta key, and meta value
21  *
22  * @param string $meta_type Type of object metadata is for (e.g., comment, post, or user)
23  * @param int $object_id ID of the object metadata is for
24  * @param string $meta_key Metadata key
25  * @param string $meta_value Metadata value
26  * @param bool $unique Optional, default is false.  Whether the specified metadata key should be
27  *              unique for the object.  If true, and the object already has a value for the specified
28  *              metadata key, no change will be made
29  * @return bool True on successful update, false on failure.
30  */
31 function add_metadata($meta_type, $object_id, $meta_key, $meta_value, $unique = false) {
32         if ( !$meta_type || !$meta_key )
33                 return false;
34
35         if ( !$object_id = absint($object_id) )
36                 return false;
37
38         if ( ! $table = _get_meta_table($meta_type) )
39                 return false;
40
41         global $wpdb;
42
43         $column = esc_sql($meta_type . '_id');
44
45         // expected_slashed ($meta_key)
46         $meta_key = stripslashes($meta_key);
47         $meta_value = stripslashes_deep($meta_value);
48         $meta_value = sanitize_meta( $meta_key, $meta_value, $meta_type );
49
50         $check = apply_filters( "add_{$meta_type}_metadata", null, $object_id, $meta_key, $meta_value, $unique );
51         if ( null !== $check )
52                 return (bool) $check;
53
54         if ( $unique && $wpdb->get_var( $wpdb->prepare(
55                 "SELECT COUNT(*) FROM $table WHERE meta_key = %s AND $column = %d",
56                 $meta_key, $object_id ) ) )
57                 return false;
58
59         $_meta_value = $meta_value;
60         $meta_value = maybe_serialize( $meta_value );
61
62         do_action( "add_{$meta_type}_meta", $object_id, $meta_key, $_meta_value );
63
64         $wpdb->insert( $table, array(
65                 $column => $object_id,
66                 'meta_key' => $meta_key,
67                 'meta_value' => $meta_value
68         ) );
69
70         wp_cache_delete($object_id, $meta_type . '_meta');
71         // users cache stores usermeta that must be cleared.
72         if ( 'user' == $meta_type )
73                 clean_user_cache($object_id);
74
75         do_action( "added_{$meta_type}_meta", $wpdb->insert_id, $object_id, $meta_key, $_meta_value );
76
77         return true;
78 }
79
80 /**
81  * Update metadata for the specified object.  If no value already exists for the specified object
82  * ID and metadata key, the metadata will be added.
83  *
84  * @since 2.9.0
85  * @uses $wpdb WordPress database object for queries.
86  * @uses do_action() Calls 'update_{$meta_type}_meta' before updating metadata with meta_id of
87  *              metadata entry to update, object ID, meta key, and meta value
88  * @uses do_action() Calls 'updated_{$meta_type}_meta' after updating metadata with meta_id of
89  *              updated metadata entry, object ID, meta key, and meta value
90  *
91  * @param string $meta_type Type of object metadata is for (e.g., comment, post, or user)
92  * @param int $object_id ID of the object metadata is for
93  * @param string $meta_key Metadata key
94  * @param string $meta_value Metadata value
95  * @param string $prev_value Optional.  If specified, only update existing metadata entries with
96  *              the specified value.  Otherwise, update all entries.
97  * @return bool True on successful update, false on failure.
98  */
99 function update_metadata($meta_type, $object_id, $meta_key, $meta_value, $prev_value = '') {
100         if ( !$meta_type || !$meta_key )
101                 return false;
102
103         if ( !$object_id = absint($object_id) )
104                 return false;
105
106         if ( ! $table = _get_meta_table($meta_type) )
107                 return false;
108
109         global $wpdb;
110
111         $column = esc_sql($meta_type . '_id');
112         $id_column = 'user' == $meta_type ? 'umeta_id' : 'meta_id';
113
114         // expected_slashed ($meta_key)
115         $meta_key = stripslashes($meta_key);
116         $meta_value = stripslashes_deep($meta_value);
117         $meta_value = sanitize_meta( $meta_key, $meta_value, $meta_type );
118
119         $check = apply_filters( "update_{$meta_type}_metadata", null, $object_id, $meta_key, $meta_value, $prev_value );
120         if ( null !== $check )
121                 return (bool) $check;
122
123         if ( ! $meta_id = $wpdb->get_var( $wpdb->prepare( "SELECT $id_column FROM $table WHERE meta_key = %s AND $column = %d", $meta_key, $object_id ) ) )
124                 return add_metadata($meta_type, $object_id, $meta_key, $meta_value);
125
126         // Compare existing value to new value if no prev value given and the key exists only once.
127         if ( empty($prev_value) ) {
128                 $old_value = get_metadata($meta_type, $object_id, $meta_key);
129                 if ( count($old_value) == 1 ) {
130                         if ( $old_value[0] === $meta_value )
131                                 return false;
132                 }
133         }
134
135         $_meta_value = $meta_value;
136         $meta_value = maybe_serialize( $meta_value );
137
138         $data  = compact( 'meta_value' );
139         $where = array( $column => $object_id, 'meta_key' => $meta_key );
140
141         if ( !empty( $prev_value ) ) {
142                 $prev_value = maybe_serialize($prev_value);
143                 $where['meta_value'] = $prev_value;
144         }
145
146         do_action( "update_{$meta_type}_meta", $meta_id, $object_id, $meta_key, $_meta_value );
147
148         $wpdb->update( $table, $data, $where );
149         wp_cache_delete($object_id, $meta_type . '_meta');
150         // users cache stores usermeta that must be cleared.
151         if ( 'user' == $meta_type )
152                 clean_user_cache($object_id);
153
154         do_action( "updated_{$meta_type}_meta", $meta_id, $object_id, $meta_key, $_meta_value );
155
156         return true;
157 }
158
159 /**
160  * Delete metadata for the specified object.
161  *
162  * @since 2.9.0
163  * @uses $wpdb WordPress database object for queries.
164  * @uses do_action() Calls 'deleted_{$meta_type}_meta' after deleting with meta_id of
165  *              deleted metadata entries, object ID, meta key, and meta value
166  *
167  * @param string $meta_type Type of object metadata is for (e.g., comment, post, or user)
168  * @param int $object_id ID of the object metadata is for
169  * @param string $meta_key Metadata key
170  * @param string $meta_value Optional. Metadata value.  If specified, only delete metadata entries
171  *              with this value.  Otherwise, delete all entries with the specified meta_key.
172  * @param bool $delete_all Optional, default is false.  If true, delete matching metadata entries
173  *              for all objects, ignoring the specified object_id.  Otherwise, only delete matching
174  *              metadata entries for the specified object_id.
175  * @return bool True on successful delete, false on failure.
176  */
177 function delete_metadata($meta_type, $object_id, $meta_key, $meta_value = '', $delete_all = false) {
178         if ( !$meta_type || !$meta_key )
179                 return false;
180
181         if ( (!$object_id = absint($object_id)) && !$delete_all )
182                 return false;
183
184         if ( ! $table = _get_meta_table($meta_type) )
185                 return false;
186
187         global $wpdb;
188
189         $type_column = esc_sql($meta_type . '_id');
190         $id_column = 'user' == $meta_type ? 'umeta_id' : 'meta_id';
191         // expected_slashed ($meta_key)
192         $meta_key = stripslashes($meta_key);
193         $meta_value = stripslashes_deep($meta_value);
194
195         $check = apply_filters( "delete_{$meta_type}_metadata", null, $object_id, $meta_key, $meta_value, $delete_all );
196         if ( null !== $check )
197                 return (bool) $check;
198
199         $_meta_value = $meta_value;
200         $meta_value = maybe_serialize( $meta_value );
201
202         $query = $wpdb->prepare( "SELECT $id_column FROM $table WHERE meta_key = %s", $meta_key );
203
204         if ( !$delete_all )
205                 $query .= $wpdb->prepare(" AND $type_column = %d", $object_id );
206
207         if ( $meta_value )
208                 $query .= $wpdb->prepare(" AND meta_value = %s", $meta_value );
209
210         $meta_ids = $wpdb->get_col( $query );
211         if ( !count( $meta_ids ) )
212                 return false;
213
214         do_action( "delete_{$meta_type}_meta", $meta_ids, $object_id, $meta_key, $_meta_value );
215
216         $query = "DELETE FROM $table WHERE $id_column IN( " . implode( ',', $meta_ids ) . " )";
217
218         $count = $wpdb->query($query);
219
220         if ( !$count )
221                 return false;
222
223         wp_cache_delete($object_id, $meta_type . '_meta');
224         // users cache stores usermeta that must be cleared.
225         if ( 'user' == $meta_type )
226                 clean_user_cache($object_id);
227
228         do_action( "deleted_{$meta_type}_meta", $meta_ids, $object_id, $meta_key, $_meta_value );
229
230         return true;
231 }
232
233 /**
234  * Retrieve metadata for the specified object.
235  *
236  * @since 2.9.0
237  *
238  * @param string $meta_type Type of object metadata is for (e.g., comment, post, or user)
239  * @param int $object_id ID of the object metadata is for
240  * @param string $meta_key Optional.  Metadata key.  If not specified, retrieve all metadata for
241  *              the specified object.
242  * @param bool $single Optional, default is false.  If true, return only the first value of the
243  *              specified meta_key.  This parameter has no effect if meta_key is not specified.
244  * @return string|array Single metadata value, or array of values
245  */
246 function get_metadata($meta_type, $object_id, $meta_key = '', $single = false) {
247         if ( !$meta_type )
248                 return false;
249
250         if ( !$object_id = absint($object_id) )
251                 return false;
252
253         $check = apply_filters( "get_{$meta_type}_metadata", null, $object_id, $meta_key, $single );
254         if ( null !== $check ) {
255                 if ( $single && is_array( $check ) )
256                         return $check[0];
257                 else
258                         return $check;
259         }
260
261         $meta_cache = wp_cache_get($object_id, $meta_type . '_meta');
262
263         if ( !$meta_cache ) {
264                 $meta_cache = update_meta_cache( $meta_type, array( $object_id ) );
265                 $meta_cache = $meta_cache[$object_id];
266         }
267
268         if ( !$meta_key )
269                 return $meta_cache;
270
271         if ( isset($meta_cache[$meta_key]) ) {
272                 if ( $single )
273                         return maybe_unserialize( $meta_cache[$meta_key][0] );
274                 else
275                         return array_map('maybe_unserialize', $meta_cache[$meta_key]);
276         }
277
278         if ($single)
279                 return '';
280         else
281                 return array();
282 }
283
284 /**
285  * Update the metadata cache for the specified objects.
286  *
287  * @since 2.9.0
288  * @uses $wpdb WordPress database object for queries.
289  *
290  * @param string $meta_type Type of object metadata is for (e.g., comment, post, or user)
291  * @param int|array $object_ids array or comma delimited list of object IDs to update cache for
292  * @return mixed Metadata cache for the specified objects, or false on failure.
293  */
294 function update_meta_cache($meta_type, $object_ids) {
295         if ( empty( $meta_type ) || empty( $object_ids ) )
296                 return false;
297
298         if ( ! $table = _get_meta_table($meta_type) )
299                 return false;
300
301         $column = esc_sql($meta_type . '_id');
302
303         global $wpdb;
304
305         if ( !is_array($object_ids) ) {
306                 $object_ids = preg_replace('|[^0-9,]|', '', $object_ids);
307                 $object_ids = explode(',', $object_ids);
308         }
309
310         $object_ids = array_map('intval', $object_ids);
311
312         $cache_key = $meta_type . '_meta';
313         $ids = array();
314         $cache = array();
315         foreach ( $object_ids as $id ) {
316                 $cached_object = wp_cache_get( $id, $cache_key );
317                 if ( false === $cached_object )
318                         $ids[] = $id;
319                 else
320                         $cache[$id] = $cached_object;
321         }
322
323         if ( empty( $ids ) )
324                 return $cache;
325
326         // Get meta info
327         $id_list = join(',', $ids);
328         $meta_list = $wpdb->get_results( $wpdb->prepare("SELECT $column, meta_key, meta_value FROM $table WHERE $column IN ($id_list)",
329                 $meta_type), ARRAY_A );
330
331         if ( !empty($meta_list) ) {
332                 foreach ( $meta_list as $metarow) {
333                         $mpid = intval($metarow[$column]);
334                         $mkey = $metarow['meta_key'];
335                         $mval = $metarow['meta_value'];
336
337                         // Force subkeys to be array type:
338                         if ( !isset($cache[$mpid]) || !is_array($cache[$mpid]) )
339                                 $cache[$mpid] = array();
340                         if ( !isset($cache[$mpid][$mkey]) || !is_array($cache[$mpid][$mkey]) )
341                                 $cache[$mpid][$mkey] = array();
342
343                         // Add a value to the current pid/key:
344                         $cache[$mpid][$mkey][] = $mval;
345                 }
346         }
347
348         foreach ( $ids as $id ) {
349                 if ( ! isset($cache[$id]) )
350                         $cache[$id] = array();
351                 wp_cache_add( $id, $cache[$id], $cache_key );
352         }
353
354         return $cache;
355 }
356
357 /**
358  * Given a meta query, generates SQL clauses to be appended to a main query
359  *
360  * @since 3.1.0
361  * @access private
362  *
363  * @param array $meta_query List of metadata queries. A single query is an associative array:
364  * - 'key' string The meta key
365  * - 'value' string|array The meta value
366  * - 'compare' (optional) string How to compare the key to the value.
367  *              Possible values: '=', '!=', '>', '>=', '<', '<=', 'LIKE', 'NOT LIKE', 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN'.
368  *              Default: '='
369  * - 'type' string (optional) The type of the value.
370  *              Possible values: 'NUMERIC', 'BINARY', 'CHAR', 'DATE', 'DATETIME', 'DECIMAL', 'SIGNED', 'TIME', 'UNSIGNED'.
371  *              Default: 'CHAR'
372  *
373  * @param string $type Type of meta
374  * @param string $primary_table
375  * @param string $primary_id_column
376  * @param object $context (optional) The main query object
377  * @return array( 'join' => $join_sql, 'where' => $where_sql )
378  */
379 function _get_meta_sql( $meta_query, $type, $primary_table, $primary_id_column, $context = null ) {
380         global $wpdb;
381
382         if ( ! $meta_table = _get_meta_table( $type ) )
383                 return false;
384
385         $meta_id_column = esc_sql( $type . '_id' );
386
387         $join = '';
388         $where = '';
389         $i = 0;
390         foreach ( $meta_query as $q ) {
391                 $meta_key = isset( $q['key'] ) ? trim( $q['key'] ) : '';
392                 $meta_value = isset( $q['value'] ) ? $q['value'] : '';
393                 $meta_compare = isset( $q['compare'] ) ? strtoupper( $q['compare'] ) : '=';
394                 $meta_type = isset( $q['type'] ) ? strtoupper( $q['type'] ) : 'CHAR';
395
396                 if ( ! in_array( $meta_compare, array( '=', '!=', '>', '>=', '<', '<=', 'LIKE', 'NOT LIKE', 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN' ) ) )
397                         $meta_compare = '=';
398
399                 if ( 'NUMERIC' == $meta_type )
400                         $meta_type = 'SIGNED';
401                 elseif ( ! in_array( $meta_type, array( 'BINARY', 'CHAR', 'DATE', 'DATETIME', 'DECIMAL', 'SIGNED', 'TIME', 'UNSIGNED' ) ) )
402                         $meta_type = 'CHAR';
403
404                 if ( empty( $meta_key ) && empty( $meta_value ) )
405                         continue;
406
407                 $alias = $i ? 'mt' . $i : $meta_table;
408
409                 $join .= "\nINNER JOIN $meta_table";
410                 $join .= $i ? " AS $alias" : '';
411                 $join .= " ON ($primary_table.$primary_id_column = $alias.$meta_id_column)";
412
413                 $i++;
414
415                 if ( !empty( $meta_key ) )
416                         $where .= $wpdb->prepare( " AND $alias.meta_key = %s", $meta_key );
417
418                 if ( in_array( $meta_compare, array( 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN' ) ) ) {
419                         if ( ! is_array( $meta_value ) )
420                                 $meta_value = preg_split( '/[,\s]+/', $meta_value );
421                 } else {
422                         $meta_value = trim( $meta_value );
423                 }
424
425                 if ( empty( $meta_value ) )
426                         continue;
427
428                 if ( 'IN' == substr( $meta_compare, -2) ) {
429                         $meta_compare_string = '(' . substr( str_repeat( ',%s', count( $meta_value ) ), 1 ) . ')';
430                 } elseif ( 'BETWEEN' == substr( $meta_compare, -7) ) {
431                         $meta_value = array_slice( $meta_value, 0, 2 );
432                         $meta_compare_string = '%s AND %s';
433                 } elseif ( 'LIKE' == substr( $meta_compare, -4 ) ) {
434                         $meta_value = '%' . like_escape( $meta_value ) . '%';
435                         $meta_compare_string = '%s';
436                 } else {
437                         $meta_compare_string = '%s';
438                 }
439
440                 // @todo Temporary hack to support empty values. Do not use outside of core.
441                 if ( '_wp_zero_value' == $meta_value )
442                         $meta_value = 0;
443
444                 $where .= $wpdb->prepare( " AND CAST($alias.meta_value AS {$meta_type}) {$meta_compare} {$meta_compare_string}", $meta_value );
445         }
446
447         return apply_filters_ref_array( 'get_meta_sql', array( compact( 'join', 'where' ), $meta_query, $type, $primary_table, $primary_id_column, &$context ) );
448 }
449
450 /**
451  * Populates the $meta_query property
452  *
453  * @access private
454  * @since 3.1.0
455  *
456  * @param array $qv The query variables
457  */
458 function _parse_meta_query( &$qv ) {
459         $meta_query = array();
460
461         // Simple query needs to be first for orderby=meta_value to work correctly
462         foreach ( array( 'key', 'value', 'compare', 'type' ) as $key ) {
463                 if ( !empty( $qv[ "meta_$key" ] ) )
464                         $meta_query[0][ $key ] = $qv[ "meta_$key" ];
465         }
466
467         if ( !empty( $qv['meta_query'] ) && is_array( $qv['meta_query'] ) ) {
468                 $meta_query = array_merge( $meta_query, $qv['meta_query'] );
469         }
470
471         $qv['meta_query'] = $meta_query;
472 }
473
474 /**
475  * Retrieve the name of the metadata table for the specified object type.
476  *
477  * @since 2.9.0
478  * @uses $wpdb WordPress database object for queries.
479  *
480  * @param string $type Type of object to get metadata table for (e.g., comment, post, or user)
481  * @return mixed Metadata table name, or false if no metadata table exists
482  */
483 function _get_meta_table($type) {
484         global $wpdb;
485
486         $table_name = $type . 'meta';
487
488         if ( empty($wpdb->$table_name) )
489                 return false;
490
491         return $wpdb->$table_name;
492 }
493
494 /**
495  * Determine whether a meta key is protected
496  *
497  * @since 3.1.3
498  *
499  * @param string $meta_key Meta key
500  * @return bool True if the key is protected, false otherwise.
501  */
502 function is_protected_meta( $meta_key, $meta_type = null ) {
503         $protected = (  '_' == $meta_key[0] );
504
505         return apply_filters( 'is_protected_meta', $protected, $meta_key, $meta_type );
506 }
507
508 /**
509  * Sanitize meta value
510  *
511  * @since 3.1.3
512  *
513  * @param string $meta_key Meta key
514  * @param mixed $meta_value Meta value to sanitize
515  * @param string $meta_type Type of meta
516  * @return mixed Sanitized $meta_value
517  */
518 function sanitize_meta( $meta_key, $meta_value, $meta_type = null ) {
519         return apply_filters( 'sanitize_meta', $meta_value, $meta_key, $meta_type );
520 }
521
522 ?>