[ XREF Home ] [ Index ]

PHP Cross Reference of WordPress Trunk

Provided by Yoast

title

Body

[close]

/wp-includes/ -> meta.php (source)

   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.2.0
 361   *
 362   * @see WP_Meta_Query
 363   *
 364   * @param array (optional) $meta_query A meta query
 365   * @param string $type Type of meta
 366   * @param string $primary_table
 367   * @param string $primary_id_column
 368   * @param object $context (optional) The main query object
 369   * @return array( 'join' => $join_sql, 'where' => $where_sql )
 370   */
 371  function get_meta_sql( $meta_query = false, $type, $primary_table, $primary_id_column, $context = null ) {
 372      $meta_query_obj = new WP_Meta_Query( $meta_query );
 373      return $meta_query_obj->get_sql( $type, $primary_table, $primary_id_column, $context );
 374  }
 375  
 376  /**
 377   * Container class for a multiple metadata query
 378   *
 379   * @since 3.2
 380   */
 381  class WP_Meta_Query {
 382      /**
 383      * List of metadata queries. A single query is an associative array:
 384      * - 'key' string The meta key
 385      * - 'value' string|array The meta value
 386      * - 'compare' (optional) string How to compare the key to the value.
 387      *              Possible values: '=', '!=', '>', '>=', '<', '<=', 'LIKE', 'NOT LIKE', 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN'.
 388      *              Default: '='
 389      * - 'type' string (optional) The type of the value.
 390      *              Possible values: 'NUMERIC', 'BINARY', 'CHAR', 'DATE', 'DATETIME', 'DECIMAL', 'SIGNED', 'TIME', 'UNSIGNED'.
 391      *              Default: 'CHAR'
 392      *
 393      * @since 3.2
 394      * @access public
 395      * @var array
 396      */
 397      public $queries = array();
 398  
 399      /**
 400       * The relation between the queries. Can be one of 'AND' or 'OR'.
 401       *
 402       * @since 3.2
 403       * @access public
 404       * @var string
 405       */    
 406      public $relation;
 407  
 408      /**
 409       * Constructor
 410       *
 411       * @param array (optional) $meta_query A meta query
 412       */
 413  	function __construct( $meta_query = false ) {
 414          if ( !$meta_query )
 415              return;
 416  
 417          if ( isset( $meta_query['relation'] ) && strtoupper( $meta_query['relation'] ) == 'OR' ) {
 418              $this->relation = 'OR';
 419          } else {
 420              $this->relation = 'AND';
 421          }
 422  
 423          $this->queries = array();
 424  
 425          foreach ( $meta_query as $key => $query ) {
 426              if ( ! is_array( $query ) )
 427                  continue;
 428  
 429              $this->queries[] = $query;
 430          }
 431      }
 432  
 433      /**
 434       * Constructs a meta query based on 'meta_*' query vars
 435       *
 436       * @since 3.2
 437       * @access public
 438       *
 439       * @param array $qv The query variables
 440       */
 441  	function parse_query_vars( $qv ) {
 442          $meta_query = array();
 443  
 444          // Simple query needs to be first for orderby=meta_value to work correctly
 445          foreach ( array( 'key', 'compare', 'type' ) as $key ) {
 446              if ( !empty( $qv[ "meta_$key" ] ) )
 447                  $meta_query[0][ $key ] = $qv[ "meta_$key" ];
 448          }
 449  
 450          // WP_Query sets 'meta_value' = '' by default
 451          if ( isset( $qv[ 'meta_value' ] ) && '' !== $qv[ 'meta_value' ] )
 452              $meta_query[0]['value'] = $qv[ 'meta_value' ];
 453  
 454          if ( !empty( $qv['meta_query'] ) && is_array( $qv['meta_query'] ) ) {
 455              $meta_query = array_merge( $meta_query, $qv['meta_query'] );
 456          }
 457  
 458          $this->__construct( $meta_query );
 459      }
 460  
 461      /**
 462       * Generates SQL clauses to be appended to a main query.
 463       *
 464       * @since 3.2
 465       * @access public
 466       *
 467       * @param string $type Type of meta
 468       * @param string $primary_table
 469       * @param string $primary_id_column
 470       * @param object $context (optional) The main query object
 471       * @return array( 'join' => $join_sql, 'where' => $where_sql )
 472       */
 473  	function get_sql( $type, $primary_table, $primary_id_column, $context = null ) {
 474          global $wpdb;
 475  
 476          if ( ! $meta_table = _get_meta_table( $type ) )
 477              return false;
 478  
 479          $meta_id_column = esc_sql( $type . '_id' );
 480  
 481          $join = array();
 482          $where = array();
 483  
 484          foreach ( $this->queries as $k => $q ) {
 485              $meta_key = isset( $q['key'] ) ? trim( $q['key'] ) : '';
 486              $meta_compare = isset( $q['compare'] ) ? strtoupper( $q['compare'] ) : '=';
 487              $meta_type = isset( $q['type'] ) ? strtoupper( $q['type'] ) : 'CHAR';
 488  
 489              if ( ! in_array( $meta_compare, array( '=', '!=', '>', '>=', '<', '<=', 'LIKE', 'NOT LIKE', 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN' ) ) )
 490                  $meta_compare = '=';
 491  
 492              if ( 'NUMERIC' == $meta_type )
 493                  $meta_type = 'SIGNED';
 494              elseif ( ! in_array( $meta_type, array( 'BINARY', 'CHAR', 'DATE', 'DATETIME', 'DECIMAL', 'SIGNED', 'TIME', 'UNSIGNED' ) ) )
 495                  $meta_type = 'CHAR';
 496  
 497              $i = count( $join );
 498              $alias = $i ? 'mt' . $i : $meta_table;
 499  
 500              // Set JOIN
 501              $join[$i]  = "INNER JOIN $meta_table";
 502              $join[$i] .= $i ? " AS $alias" : '';
 503              $join[$i] .= " ON ($primary_table.$primary_id_column = $alias.$meta_id_column)";
 504  
 505              $where[$k] = '';
 506              if ( !empty( $meta_key ) )
 507                  $where[$k] = $wpdb->prepare( "$alias.meta_key = %s", $meta_key );
 508  
 509              if ( !isset( $q['value'] ) ) {
 510                  if ( empty( $where[$k] ) )
 511                      unset( $join[$i] );
 512                  continue;
 513              }
 514  
 515              $meta_value = $q['value'];
 516  
 517              if ( in_array( $meta_compare, array( 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN' ) ) ) {
 518                  if ( ! is_array( $meta_value ) )
 519                      $meta_value = preg_split( '/[,\s]+/', $meta_value );
 520  
 521                  if ( empty( $meta_value ) ) {
 522                      unset( $join[$i] );
 523                      continue;
 524                  }
 525              } else {
 526                  $meta_value = trim( $meta_value );
 527              }
 528  
 529              if ( 'IN' == substr( $meta_compare, -2) ) {
 530                  $meta_compare_string = '(' . substr( str_repeat( ',%s', count( $meta_value ) ), 1 ) . ')';
 531              } elseif ( 'BETWEEN' == substr( $meta_compare, -7) ) {
 532                  $meta_value = array_slice( $meta_value, 0, 2 );
 533                  $meta_compare_string = '%s AND %s';
 534              } elseif ( 'LIKE' == substr( $meta_compare, -4 ) ) {
 535                  $meta_value = '%' . like_escape( $meta_value ) . '%';
 536                  $meta_compare_string = '%s';
 537              } else {
 538                  $meta_compare_string = '%s';
 539              }
 540  
 541              if ( ! empty( $where[$k] ) )
 542                  $where[$k] .= ' AND ';
 543  
 544              $where[$k] = ' (' . $where[$k] . $wpdb->prepare( "CAST($alias.meta_value AS {$meta_type}) {$meta_compare} {$meta_compare_string})", $meta_value );
 545          }
 546  
 547          $where = array_filter( $where );
 548  
 549          if ( empty( $where ) )
 550              $where = '';
 551          else
 552              $where = ' AND (' . implode( "\n{$this->relation} ", $where ) . ' )';
 553  
 554          $join = implode( "\n", $join );
 555          if ( ! empty( $join ) )
 556              $join = ' ' . $join;
 557  
 558          return apply_filters_ref_array( 'get_meta_sql', array( compact( 'join', 'where' ), $this->queries, $type, $primary_table, $primary_id_column, $context ) );
 559      }
 560  }
 561  
 562  /**
 563   * Retrieve the name of the metadata table for the specified object type.
 564   *
 565   * @since 2.9.0
 566   * @uses $wpdb WordPress database object for queries.
 567   *
 568   * @param string $type Type of object to get metadata table for (e.g., comment, post, or user)
 569   * @return mixed Metadata table name, or false if no metadata table exists
 570   */
 571  function _get_meta_table($type) {
 572      global $wpdb;
 573  
 574      $table_name = $type . 'meta';
 575  
 576      if ( empty($wpdb->$table_name) )
 577          return false;
 578  
 579      return $wpdb->$table_name;
 580  }
 581  
 582  /**
 583   * Determine whether a meta key is protected
 584   *
 585   * @since 3.1.3
 586   *
 587   * @param string $meta_key Meta key
 588   * @return bool True if the key is protected, false otherwise.
 589   */
 590  function is_protected_meta( $meta_key, $meta_type = null ) {
 591      $protected = (  '_' == $meta_key[0] );
 592  
 593      return apply_filters( 'is_protected_meta', $protected, $meta_key, $meta_type );
 594  }
 595  
 596  /**
 597   * Sanitize meta value
 598   *
 599   * @since 3.1.3
 600   *
 601   * @param string $meta_key Meta key
 602   * @param mixed $meta_value Meta value to sanitize
 603   * @param string $meta_type Type of meta
 604   * @return mixed Sanitized $meta_value
 605   */
 606  function sanitize_meta( $meta_key, $meta_value, $meta_type = null ) {
 607      return apply_filters( 'sanitize_meta', $meta_value, $meta_key, $meta_type );
 608  }
 609  
 610  ?>


Generated: Wed Jun 1 08:30:02 2011 Cross-referenced by PHPXref 0.7
Provided by Yoast and awesome WordPress Hosting