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