Make WordPress Core

Changeset 33761


Ignore:
Timestamp:
08/26/2015 01:01:22 PM (9 years ago)
Author:
wonderboymusic
Message:

Meta: move WP_Meta_Query into its own file. meta.php loads the new files, so this is 100% BC if someone is loading meta.php directly. New files created using svn cp.

Creates:
class-wp-meta-query.php
meta-functions.php

meta.php contains only top-level code. Class file only contains the class. Functions file only contains functions.

See #33413.

Location:
trunk/src/wp-includes
Files:
1 edited
2 copied

Legend:

Unmodified
Added
Removed
  • trunk/src/wp-includes/class-wp-meta-query.php

    r33758 r33761  
    11<?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  *
    19  * @global wpdb $wpdb WordPress database abstraction object.
    20  *
    21  * @param string $meta_type  Type of object metadata is for (e.g., comment, post, or user)
    22  * @param int    $object_id  ID of the object metadata is for
    23  * @param string $meta_key   Metadata key
    24  * @param mixed  $meta_value Metadata value. Must be serializable if non-scalar.
    25  * @param bool   $unique     Optional, default is false.
    26  *                           Whether the specified metadata key should be unique for the object.
    27  *                           If true, and the object already has a value for the specified metadata key,
    28  *                           no change will be made.
    29  * @return int|false The meta ID on success, false on failure.
    30  */
    31 function add_metadata($meta_type, $object_id, $meta_key, $meta_value, $unique = false) {
    32     global $wpdb;
    33 
    34     if ( ! $meta_type || ! $meta_key || ! is_numeric( $object_id ) ) {
    35         return false;
    36     }
    37 
    38     $object_id = absint( $object_id );
    39     if ( ! $object_id ) {
    40         return false;
    41     }
    42 
    43     $table = _get_meta_table( $meta_type );
    44     if ( ! $table ) {
    45         return false;
    46     }
    47 
    48     $column = sanitize_key($meta_type . '_id');
    49 
    50     // expected_slashed ($meta_key)
    51     $meta_key = wp_unslash($meta_key);
    52     $meta_value = wp_unslash($meta_value);
    53     $meta_value = sanitize_meta( $meta_key, $meta_value, $meta_type );
    54 
    55     /**
    56      * Filter whether to add metadata of a specific type.
    57      *
    58      * The dynamic portion of the hook, `$meta_type`, refers to the meta
    59      * object type (comment, post, or user). Returning a non-null value
    60      * will effectively short-circuit the function.
    61      *
    62      * @since 3.1.0
    63      *
    64      * @param null|bool $check      Whether to allow adding metadata for the given type.
    65      * @param int       $object_id  Object ID.
    66      * @param string    $meta_key   Meta key.
    67      * @param mixed     $meta_value Meta value. Must be serializable if non-scalar.
    68      * @param bool      $unique     Whether the specified meta key should be unique
    69      *                              for the object. Optional. Default false.
    70      */
    71     $check = apply_filters( "add_{$meta_type}_metadata", null, $object_id, $meta_key, $meta_value, $unique );
    72     if ( null !== $check )
    73         return $check;
    74 
    75     if ( $unique && $wpdb->get_var( $wpdb->prepare(
    76         "SELECT COUNT(*) FROM $table WHERE meta_key = %s AND $column = %d",
    77         $meta_key, $object_id ) ) )
    78         return false;
    79 
    80     $_meta_value = $meta_value;
    81     $meta_value = maybe_serialize( $meta_value );
    82 
    83     /**
    84      * Fires immediately before meta of a specific type is added.
    85      *
    86      * The dynamic portion of the hook, `$meta_type`, refers to the meta
    87      * object type (comment, post, or user).
    88      *
    89      * @since 3.1.0
    90      *
    91      * @param int    $object_id  Object ID.
    92      * @param string $meta_key   Meta key.
    93      * @param mixed  $meta_value Meta value.
    94      */
    95     do_action( "add_{$meta_type}_meta", $object_id, $meta_key, $_meta_value );
    96 
    97     $result = $wpdb->insert( $table, array(
    98         $column => $object_id,
    99         'meta_key' => $meta_key,
    100         'meta_value' => $meta_value
    101     ) );
    102 
    103     if ( ! $result )
    104         return false;
    105 
    106     $mid = (int) $wpdb->insert_id;
    107 
    108     wp_cache_delete($object_id, $meta_type . '_meta');
    109 
    110     /**
    111      * Fires immediately after meta of a specific type is added.
    112      *
    113      * The dynamic portion of the hook, `$meta_type`, refers to the meta
    114      * object type (comment, post, or user).
    115      *
    116      * @since 2.9.0
    117      *
    118      * @param int    $mid        The meta ID after successful update.
    119      * @param int    $object_id  Object ID.
    120      * @param string $meta_key   Meta key.
    121      * @param mixed  $meta_value Meta value.
    122      */
    123     do_action( "added_{$meta_type}_meta", $mid, $object_id, $meta_key, $_meta_value );
    124 
    125     return $mid;
    126 }
    127 
    128 /**
    129  * Update metadata for the specified object. If no value already exists for the specified object
    130  * ID and metadata key, the metadata will be added.
    131  *
    132  * @since 2.9.0
    133  *
    134  * @global wpdb $wpdb WordPress database abstraction object.
    135  *
    136  * @param string $meta_type  Type of object metadata is for (e.g., comment, post, or user)
    137  * @param int    $object_id  ID of the object metadata is for
    138  * @param string $meta_key   Metadata key
    139  * @param mixed  $meta_value Metadata value. Must be serializable if non-scalar.
    140  * @param mixed  $prev_value Optional. If specified, only update existing metadata entries with
    141  *                           the specified value. Otherwise, update all entries.
    142  * @return int|bool Meta ID if the key didn't exist, true on successful update, false on failure.
    143  */
    144 function update_metadata($meta_type, $object_id, $meta_key, $meta_value, $prev_value = '') {
    145     global $wpdb;
    146 
    147     if ( ! $meta_type || ! $meta_key || ! is_numeric( $object_id ) ) {
    148         return false;
    149     }
    150 
    151     $object_id = absint( $object_id );
    152     if ( ! $object_id ) {
    153         return false;
    154     }
    155 
    156     $table = _get_meta_table( $meta_type );
    157     if ( ! $table ) {
    158         return false;
    159     }
    160 
    161     $column = sanitize_key($meta_type . '_id');
    162     $id_column = 'user' == $meta_type ? 'umeta_id' : 'meta_id';
    163 
    164     // expected_slashed ($meta_key)
    165     $meta_key = wp_unslash($meta_key);
    166     $passed_value = $meta_value;
    167     $meta_value = wp_unslash($meta_value);
    168     $meta_value = sanitize_meta( $meta_key, $meta_value, $meta_type );
    169 
    170     /**
    171      * Filter whether to update metadata of a specific type.
    172      *
    173      * The dynamic portion of the hook, `$meta_type`, refers to the meta
    174      * object type (comment, post, or user). Returning a non-null value
    175      * will effectively short-circuit the function.
    176      *
    177      * @since 3.1.0
    178      *
    179      * @param null|bool $check      Whether to allow updating metadata for the given type.
    180      * @param int       $object_id  Object ID.
    181      * @param string    $meta_key   Meta key.
    182      * @param mixed     $meta_value Meta value. Must be serializable if non-scalar.
    183      * @param mixed     $prev_value Optional. If specified, only update existing
    184      *                              metadata entries with the specified value.
    185      *                              Otherwise, update all entries.
    186      */
    187     $check = apply_filters( "update_{$meta_type}_metadata", null, $object_id, $meta_key, $meta_value, $prev_value );
    188     if ( null !== $check )
    189         return (bool) $check;
    190 
    191     // Compare existing value to new value if no prev value given and the key exists only once.
    192     if ( empty($prev_value) ) {
    193         $old_value = get_metadata($meta_type, $object_id, $meta_key);
    194         if ( count($old_value) == 1 ) {
    195             if ( $old_value[0] === $meta_value )
    196                 return false;
    197         }
    198     }
    199 
    200     $meta_ids = $wpdb->get_col( $wpdb->prepare( "SELECT $id_column FROM $table WHERE meta_key = %s AND $column = %d", $meta_key, $object_id ) );
    201     if ( empty( $meta_ids ) ) {
    202         return add_metadata($meta_type, $object_id, $meta_key, $passed_value);
    203     }
    204 
    205     $_meta_value = $meta_value;
    206     $meta_value = maybe_serialize( $meta_value );
    207 
    208     $data  = compact( 'meta_value' );
    209     $where = array( $column => $object_id, 'meta_key' => $meta_key );
    210 
    211     if ( !empty( $prev_value ) ) {
    212         $prev_value = maybe_serialize($prev_value);
    213         $where['meta_value'] = $prev_value;
    214     }
    215 
    216     foreach ( $meta_ids as $meta_id ) {
    217         /**
    218          * Fires immediately before updating metadata of a specific type.
    219          *
    220          * The dynamic portion of the hook, `$meta_type`, refers to the meta
    221          * object type (comment, post, or user).
    222          *
    223          * @since 2.9.0
    224          *
    225          * @param int    $meta_id    ID of the metadata entry to update.
    226          * @param int    $object_id  Object ID.
    227          * @param string $meta_key   Meta key.
    228          * @param mixed  $meta_value Meta value.
    229          */
    230         do_action( "update_{$meta_type}_meta", $meta_id, $object_id, $meta_key, $_meta_value );
    231     }
    232 
    233     if ( 'post' == $meta_type ) {
    234         foreach ( $meta_ids as $meta_id ) {
    235             /**
    236              * Fires immediately before updating a post's metadata.
    237              *
    238              * @since 2.9.0
    239              *
    240              * @param int    $meta_id    ID of metadata entry to update.
    241              * @param int    $object_id  Object ID.
    242              * @param string $meta_key   Meta key.
    243              * @param mixed  $meta_value Meta value.
    244              */
    245             do_action( 'update_postmeta', $meta_id, $object_id, $meta_key, $meta_value );
    246         }
    247     }
    248 
    249     $result = $wpdb->update( $table, $data, $where );
    250     if ( ! $result )
    251         return false;
    252 
    253     wp_cache_delete($object_id, $meta_type . '_meta');
    254 
    255     foreach ( $meta_ids as $meta_id ) {
    256         /**
    257          * Fires immediately after updating metadata of a specific type.
    258          *
    259          * The dynamic portion of the hook, `$meta_type`, refers to the meta
    260          * object type (comment, post, or user).
    261          *
    262          * @since 2.9.0
    263          *
    264          * @param int    $meta_id    ID of updated metadata entry.
    265          * @param int    $object_id  Object ID.
    266          * @param string $meta_key   Meta key.
    267          * @param mixed  $meta_value Meta value.
    268          */
    269         do_action( "updated_{$meta_type}_meta", $meta_id, $object_id, $meta_key, $_meta_value );
    270     }
    271 
    272     if ( 'post' == $meta_type ) {
    273         foreach ( $meta_ids as $meta_id ) {
    274             /**
    275              * Fires immediately after updating a post's metadata.
    276              *
    277              * @since 2.9.0
    278              *
    279              * @param int    $meta_id    ID of updated metadata entry.
    280              * @param int    $object_id  Object ID.
    281              * @param string $meta_key   Meta key.
    282              * @param mixed  $meta_value Meta value.
    283              */
    284             do_action( 'updated_postmeta', $meta_id, $object_id, $meta_key, $meta_value );
    285         }
    286     }
    287 
    288     return true;
    289 }
    290 
    291 /**
    292  * Delete metadata for the specified object.
    293  *
    294  * @since 2.9.0
    295  *
    296  * @global wpdb $wpdb WordPress database abstraction object.
    297  *
    298  * @param string $meta_type  Type of object metadata is for (e.g., comment, post, or user)
    299  * @param int    $object_id  ID of the object metadata is for
    300  * @param string $meta_key   Metadata key
    301  * @param mixed  $meta_value Optional. Metadata value. Must be serializable if non-scalar. If specified, only delete
    302  *                           metadata entries with this value. Otherwise, delete all entries with the specified meta_key.
    303  *                           Pass `null, `false`, or an empty string to skip this check. (For backward compatibility,
    304  *                           it is not possible to pass an empty string to delete those entries with an empty string
    305  *                           for a value.)
    306  * @param bool   $delete_all Optional, default is false. If true, delete matching metadata entries for all objects,
    307  *                           ignoring the specified object_id. Otherwise, only delete matching metadata entries for
    308  *                           the specified object_id.
    309  * @return bool True on successful delete, false on failure.
    310  */
    311 function delete_metadata($meta_type, $object_id, $meta_key, $meta_value = '', $delete_all = false) {
    312     global $wpdb;
    313 
    314     if ( ! $meta_type || ! $meta_key || ! is_numeric( $object_id ) && ! $delete_all ) {
    315         return false;
    316     }
    317 
    318     $object_id = absint( $object_id );
    319     if ( ! $object_id && ! $delete_all ) {
    320         return false;
    321     }
    322 
    323     $table = _get_meta_table( $meta_type );
    324     if ( ! $table ) {
    325         return false;
    326     }
    327 
    328     $type_column = sanitize_key($meta_type . '_id');
    329     $id_column = 'user' == $meta_type ? 'umeta_id' : 'meta_id';
    330     // expected_slashed ($meta_key)
    331     $meta_key = wp_unslash($meta_key);
    332     $meta_value = wp_unslash($meta_value);
    333 
    334     /**
    335      * Filter whether to delete metadata of a specific type.
    336      *
    337      * The dynamic portion of the hook, `$meta_type`, refers to the meta
    338      * object type (comment, post, or user). Returning a non-null value
    339      * will effectively short-circuit the function.
    340      *
    341      * @since 3.1.0
    342      *
    343      * @param null|bool $delete     Whether to allow metadata deletion of the given type.
    344      * @param int       $object_id  Object ID.
    345      * @param string    $meta_key   Meta key.
    346      * @param mixed     $meta_value Meta value. Must be serializable if non-scalar.
    347      * @param bool      $delete_all Whether to delete the matching metadata entries
    348      *                              for all objects, ignoring the specified $object_id.
    349      *                              Default false.
    350      */
    351     $check = apply_filters( "delete_{$meta_type}_metadata", null, $object_id, $meta_key, $meta_value, $delete_all );
    352     if ( null !== $check )
    353         return (bool) $check;
    354 
    355     $_meta_value = $meta_value;
    356     $meta_value = maybe_serialize( $meta_value );
    357 
    358     $query = $wpdb->prepare( "SELECT $id_column FROM $table WHERE meta_key = %s", $meta_key );
    359 
    360     if ( !$delete_all )
    361         $query .= $wpdb->prepare(" AND $type_column = %d", $object_id );
    362 
    363     if ( '' !== $meta_value && null !== $meta_value && false !== $meta_value )
    364         $query .= $wpdb->prepare(" AND meta_value = %s", $meta_value );
    365 
    366     $meta_ids = $wpdb->get_col( $query );
    367     if ( !count( $meta_ids ) )
    368         return false;
    369 
    370     if ( $delete_all )
    371         $object_ids = $wpdb->get_col( $wpdb->prepare( "SELECT $type_column FROM $table WHERE meta_key = %s", $meta_key ) );
    372 
    373     /**
    374      * Fires immediately before deleting metadata of a specific type.
    375      *
    376      * The dynamic portion of the hook, `$meta_type`, refers to the meta
    377      * object type (comment, post, or user).
    378      *
    379      * @since 3.1.0
    380      *
    381      * @param array  $meta_ids   An array of metadata entry IDs to delete.
    382      * @param int    $object_id  Object ID.
    383      * @param string $meta_key   Meta key.
    384      * @param mixed  $meta_value Meta value.
    385      */
    386     do_action( "delete_{$meta_type}_meta", $meta_ids, $object_id, $meta_key, $_meta_value );
    387 
    388     // Old-style action.
    389     if ( 'post' == $meta_type ) {
    390         /**
    391          * Fires immediately before deleting metadata for a post.
    392          *
    393          * @since 2.9.0
    394          *
    395          * @param array $meta_ids An array of post metadata entry IDs to delete.
    396          */
    397         do_action( 'delete_postmeta', $meta_ids );
    398     }
    399 
    400     $query = "DELETE FROM $table WHERE $id_column IN( " . implode( ',', $meta_ids ) . " )";
    401 
    402     $count = $wpdb->query($query);
    403 
    404     if ( !$count )
    405         return false;
    406 
    407     if ( $delete_all ) {
    408         foreach ( (array) $object_ids as $o_id ) {
    409             wp_cache_delete($o_id, $meta_type . '_meta');
    410         }
    411     } else {
    412         wp_cache_delete($object_id, $meta_type . '_meta');
    413     }
    414 
    415     /**
    416      * Fires immediately after deleting metadata of a specific type.
    417      *
    418      * The dynamic portion of the hook name, `$meta_type`, refers to the meta
    419      * object type (comment, post, or user).
    420      *
    421      * @since 2.9.0
    422      *
    423      * @param array  $meta_ids   An array of deleted metadata entry IDs.
    424      * @param int    $object_id  Object ID.
    425      * @param string $meta_key   Meta key.
    426      * @param mixed  $meta_value Meta value.
    427      */
    428     do_action( "deleted_{$meta_type}_meta", $meta_ids, $object_id, $meta_key, $_meta_value );
    429 
    430     // Old-style action.
    431     if ( 'post' == $meta_type ) {
    432         /**
    433          * Fires immediately after deleting metadata for a post.
    434          *
    435          * @since 2.9.0
    436          *
    437          * @param array $meta_ids An array of deleted post metadata entry IDs.
    438          */
    439         do_action( 'deleted_postmeta', $meta_ids );
    440     }
    441 
    442     return true;
    443 }
    444 
    445 /**
    446  * Retrieve metadata for the specified object.
    447  *
    448  * @since 2.9.0
    449  *
    450  * @param string $meta_type Type of object metadata is for (e.g., comment, post, or user)
    451  * @param int    $object_id ID of the object metadata is for
    452  * @param string $meta_key  Optional. Metadata key. If not specified, retrieve all metadata for
    453  *                          the specified object.
    454  * @param bool   $single    Optional, default is false.
    455  *                          If true, return only the first value of the specified meta_key.
    456  *                          This parameter has no effect if meta_key is not specified.
    457  * @return mixed Single metadata value, or array of values
    458  */
    459 function get_metadata($meta_type, $object_id, $meta_key = '', $single = false) {
    460     if ( ! $meta_type || ! is_numeric( $object_id ) ) {
    461         return false;
    462     }
    463 
    464     $object_id = absint( $object_id );
    465     if ( ! $object_id ) {
    466         return false;
    467     }
    468 
    469     /**
    470      * Filter whether to retrieve metadata of a specific type.
    471      *
    472      * The dynamic portion of the hook, `$meta_type`, refers to the meta
    473      * object type (comment, post, or user). Returning a non-null value
    474      * will effectively short-circuit the function.
    475      *
    476      * @since 3.1.0
    477      *
    478      * @param null|array|string $value     The value get_metadata() should return - a single metadata value,
    479      *                                     or an array of values.
    480      * @param int               $object_id Object ID.
    481      * @param string            $meta_key  Meta key.
    482      * @param bool              $single    Whether to return only the first value of the specified $meta_key.
    483      */
    484     $check = apply_filters( "get_{$meta_type}_metadata", null, $object_id, $meta_key, $single );
    485     if ( null !== $check ) {
    486         if ( $single && is_array( $check ) )
    487             return $check[0];
    488         else
    489             return $check;
    490     }
    491 
    492     $meta_cache = wp_cache_get($object_id, $meta_type . '_meta');
    493 
    494     if ( !$meta_cache ) {
    495         $meta_cache = update_meta_cache( $meta_type, array( $object_id ) );
    496         $meta_cache = $meta_cache[$object_id];
    497     }
    498 
    499     if ( ! $meta_key ) {
    500         return $meta_cache;
    501     }
    502 
    503     if ( isset($meta_cache[$meta_key]) ) {
    504         if ( $single )
    505             return maybe_unserialize( $meta_cache[$meta_key][0] );
    506         else
    507             return array_map('maybe_unserialize', $meta_cache[$meta_key]);
    508     }
    509 
    510     if ($single)
    511         return '';
    512     else
    513         return array();
    514 }
    515 
    516 /**
    517  * Determine if a meta key is set for a given object
    518  *
    519  * @since 3.3.0
    520  *
    521  * @param string $meta_type Type of object metadata is for (e.g., comment, post, or user)
    522  * @param int    $object_id ID of the object metadata is for
    523  * @param string $meta_key  Metadata key.
    524  * @return bool True of the key is set, false if not.
    525  */
    526 function metadata_exists( $meta_type, $object_id, $meta_key ) {
    527     if ( ! $meta_type || ! is_numeric( $object_id ) ) {
    528         return false;
    529     }
    530 
    531     $object_id = absint( $object_id );
    532     if ( ! $object_id ) {
    533         return false;
    534     }
    535 
    536     /** This filter is documented in wp-includes/meta.php */
    537     $check = apply_filters( "get_{$meta_type}_metadata", null, $object_id, $meta_key, true );
    538     if ( null !== $check )
    539         return (bool) $check;
    540 
    541     $meta_cache = wp_cache_get( $object_id, $meta_type . '_meta' );
    542 
    543     if ( !$meta_cache ) {
    544         $meta_cache = update_meta_cache( $meta_type, array( $object_id ) );
    545         $meta_cache = $meta_cache[$object_id];
    546     }
    547 
    548     if ( isset( $meta_cache[ $meta_key ] ) )
    549         return true;
    550 
    551     return false;
    552 }
    553 
    554 /**
    555  * Get meta data by meta ID
    556  *
    557  * @since 3.3.0
    558  *
    559  * @global wpdb $wpdb
    560  *
    561  * @param string $meta_type Type of object metadata is for (e.g., comment, post, or user)
    562  * @param int    $meta_id   ID for a specific meta row
    563  * @return object|false Meta object or false.
    564  */
    565 function get_metadata_by_mid( $meta_type, $meta_id ) {
    566     global $wpdb;
    567 
    568     if ( ! $meta_type || ! is_numeric( $meta_id ) ) {
    569         return false;
    570     }
    571 
    572     $meta_id = absint( $meta_id );
    573     if ( ! $meta_id ) {
    574         return false;
    575     }
    576 
    577     $table = _get_meta_table( $meta_type );
    578     if ( ! $table ) {
    579         return false;
    580     }
    581 
    582     $id_column = ( 'user' == $meta_type ) ? 'umeta_id' : 'meta_id';
    583 
    584     $meta = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $table WHERE $id_column = %d", $meta_id ) );
    585 
    586     if ( empty( $meta ) )
    587         return false;
    588 
    589     if ( isset( $meta->meta_value ) )
    590         $meta->meta_value = maybe_unserialize( $meta->meta_value );
    591 
    592     return $meta;
    593 }
    594 
    595 /**
    596  * Update meta data by meta ID
    597  *
    598  * @since 3.3.0
    599  *
    600  * @global wpdb $wpdb
    601  *
    602  * @param string $meta_type  Type of object metadata is for (e.g., comment, post, or user)
    603  * @param int    $meta_id    ID for a specific meta row
    604  * @param string $meta_value Metadata value
    605  * @param string $meta_key   Optional, you can provide a meta key to update it
    606  * @return bool True on successful update, false on failure.
    607  */
    608 function update_metadata_by_mid( $meta_type, $meta_id, $meta_value, $meta_key = false ) {
    609     global $wpdb;
    610 
    611     // Make sure everything is valid.
    612     if ( ! $meta_type || ! is_numeric( $meta_id ) ) {
    613         return false;
    614     }
    615 
    616     $meta_id = absint( $meta_id );
    617     if ( ! $meta_id ) {
    618         return false;
    619     }
    620 
    621     $table = _get_meta_table( $meta_type );
    622     if ( ! $table ) {
    623         return false;
    624     }
    625 
    626     $column = sanitize_key($meta_type . '_id');
    627     $id_column = 'user' == $meta_type ? 'umeta_id' : 'meta_id';
    628 
    629     // Fetch the meta and go on if it's found.
    630     if ( $meta = get_metadata_by_mid( $meta_type, $meta_id ) ) {
    631         $original_key = $meta->meta_key;
    632         $object_id = $meta->{$column};
    633 
    634         // If a new meta_key (last parameter) was specified, change the meta key,
    635         // otherwise use the original key in the update statement.
    636         if ( false === $meta_key ) {
    637             $meta_key = $original_key;
    638         } elseif ( ! is_string( $meta_key ) ) {
    639             return false;
    640         }
    641 
    642         // Sanitize the meta
    643         $_meta_value = $meta_value;
    644         $meta_value = sanitize_meta( $meta_key, $meta_value, $meta_type );
    645         $meta_value = maybe_serialize( $meta_value );
    646 
    647         // Format the data query arguments.
    648         $data = array(
    649             'meta_key' => $meta_key,
    650             'meta_value' => $meta_value
    651         );
    652 
    653         // Format the where query arguments.
    654         $where = array();
    655         $where[$id_column] = $meta_id;
    656 
    657         /** This action is documented in wp-includes/meta.php */
    658         do_action( "update_{$meta_type}_meta", $meta_id, $object_id, $meta_key, $_meta_value );
    659 
    660         if ( 'post' == $meta_type ) {
    661             /** This action is documented in wp-includes/meta.php */
    662             do_action( 'update_postmeta', $meta_id, $object_id, $meta_key, $meta_value );
    663         }
    664 
    665         // Run the update query, all fields in $data are %s, $where is a %d.
    666         $result = $wpdb->update( $table, $data, $where, '%s', '%d' );
    667         if ( ! $result )
    668             return false;
    669 
    670         // Clear the caches.
    671         wp_cache_delete($object_id, $meta_type . '_meta');
    672 
    673         /** This action is documented in wp-includes/meta.php */
    674         do_action( "updated_{$meta_type}_meta", $meta_id, $object_id, $meta_key, $_meta_value );
    675 
    676         if ( 'post' == $meta_type ) {
    677             /** This action is documented in wp-includes/meta.php */
    678             do_action( 'updated_postmeta', $meta_id, $object_id, $meta_key, $meta_value );
    679         }
    680 
    681         return true;
    682     }
    683 
    684     // And if the meta was not found.
    685     return false;
    686 }
    687 
    688 /**
    689  * Delete meta data by meta ID
    690  *
    691  * @since 3.3.0
    692  *
    693  * @global wpdb $wpdb
    694  *
    695  * @param string $meta_type Type of object metadata is for (e.g., comment, post, or user)
    696  * @param int    $meta_id   ID for a specific meta row
    697  * @return bool True on successful delete, false on failure.
    698  */
    699 function delete_metadata_by_mid( $meta_type, $meta_id ) {
    700     global $wpdb;
    701 
    702     // Make sure everything is valid.
    703     if ( ! $meta_type || ! is_numeric( $meta_id ) ) {
    704         return false;
    705     }
    706 
    707     $meta_id = absint( $meta_id );
    708     if ( ! $meta_id ) {
    709         return false;
    710     }
    711 
    712     $table = _get_meta_table( $meta_type );
    713     if ( ! $table ) {
    714         return false;
    715     }
    716 
    717     // object and id columns
    718     $column = sanitize_key($meta_type . '_id');
    719     $id_column = 'user' == $meta_type ? 'umeta_id' : 'meta_id';
    720 
    721     // Fetch the meta and go on if it's found.
    722     if ( $meta = get_metadata_by_mid( $meta_type, $meta_id ) ) {
    723         $object_id = $meta->{$column};
    724 
    725         /** This action is documented in wp-includes/meta.php */
    726         do_action( "delete_{$meta_type}_meta", (array) $meta_id, $object_id, $meta->meta_key, $meta->meta_value );
    727 
    728         // Old-style action.
    729         if ( 'post' == $meta_type || 'comment' == $meta_type ) {
    730             /**
    731              * Fires immediately before deleting post or comment metadata of a specific type.
    732              *
    733              * The dynamic portion of the hook, `$meta_type`, refers to the meta
    734              * object type (post or comment).
    735              *
    736              * @since 3.4.0
    737              *
    738              * @param int $meta_id ID of the metadata entry to delete.
    739              */
    740             do_action( "delete_{$meta_type}meta", $meta_id );
    741         }
    742 
    743         // Run the query, will return true if deleted, false otherwise
    744         $result = (bool) $wpdb->delete( $table, array( $id_column => $meta_id ) );
    745 
    746         // Clear the caches.
    747         wp_cache_delete($object_id, $meta_type . '_meta');
    748 
    749         /** This action is documented in wp-includes/meta.php */
    750         do_action( "deleted_{$meta_type}_meta", (array) $meta_id, $object_id, $meta->meta_key, $meta->meta_value );
    751 
    752         // Old-style action.
    753         if ( 'post' == $meta_type || 'comment' == $meta_type ) {
    754             /**
    755              * Fires immediately after deleting post or comment metadata of a specific type.
    756              *
    757              * The dynamic portion of the hook, `$meta_type`, refers to the meta
    758              * object type (post or comment).
    759              *
    760              * @since 3.4.0
    761              *
    762              * @param int $meta_ids Deleted metadata entry ID.
    763              */
    764             do_action( "deleted_{$meta_type}meta", $meta_id );
    765         }
    766 
    767         return $result;
    768 
    769     }
    770 
    771     // Meta id was not found.
    772     return false;
    773 }
    774 
    775 /**
    776  * Update the metadata cache for the specified objects.
    777  *
    778  * @since 2.9.0
    779  *
    780  * @global wpdb $wpdb WordPress database abstraction object.
    781  *
    782  * @param string    $meta_type  Type of object metadata is for (e.g., comment, post, or user)
    783  * @param int|array $object_ids Array or comma delimited list of object IDs to update cache for
    784  * @return array|false Metadata cache for the specified objects, or false on failure.
    785  */
    786 function update_meta_cache($meta_type, $object_ids) {
    787     global $wpdb;
    788 
    789     if ( ! $meta_type || ! $object_ids ) {
    790         return false;
    791     }
    792 
    793     $table = _get_meta_table( $meta_type );
    794     if ( ! $table ) {
    795         return false;
    796     }
    797 
    798     $column = sanitize_key($meta_type . '_id');
    799 
    800     if ( !is_array($object_ids) ) {
    801         $object_ids = preg_replace('|[^0-9,]|', '', $object_ids);
    802         $object_ids = explode(',', $object_ids);
    803     }
    804 
    805     $object_ids = array_map('intval', $object_ids);
    806 
    807     $cache_key = $meta_type . '_meta';
    808     $ids = array();
    809     $cache = array();
    810     foreach ( $object_ids as $id ) {
    811         $cached_object = wp_cache_get( $id, $cache_key );
    812         if ( false === $cached_object )
    813             $ids[] = $id;
    814         else
    815             $cache[$id] = $cached_object;
    816     }
    817 
    818     if ( empty( $ids ) )
    819         return $cache;
    820 
    821     // Get meta info
    822     $id_list = join( ',', $ids );
    823     $id_column = 'user' == $meta_type ? 'umeta_id' : 'meta_id';
    824     $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 );
    825 
    826     if ( !empty($meta_list) ) {
    827         foreach ( $meta_list as $metarow) {
    828             $mpid = intval($metarow[$column]);
    829             $mkey = $metarow['meta_key'];
    830             $mval = $metarow['meta_value'];
    831 
    832             // Force subkeys to be array type:
    833             if ( !isset($cache[$mpid]) || !is_array($cache[$mpid]) )
    834                 $cache[$mpid] = array();
    835             if ( !isset($cache[$mpid][$mkey]) || !is_array($cache[$mpid][$mkey]) )
    836                 $cache[$mpid][$mkey] = array();
    837 
    838             // Add a value to the current pid/key:
    839             $cache[$mpid][$mkey][] = $mval;
    840         }
    841     }
    842 
    843     foreach ( $ids as $id ) {
    844         if ( ! isset($cache[$id]) )
    845             $cache[$id] = array();
    846         wp_cache_add( $id, $cache[$id], $cache_key );
    847     }
    848 
    849     return $cache;
    850 }
    851 
    852 /**
    853  * Given a meta query, generates SQL clauses to be appended to a main query.
    854  *
    855  * @since 3.2.0
    856  *
    857  * @see WP_Meta_Query
    858  *
    859  * @param array $meta_query         A meta query.
    860  * @param string $type              Type of meta.
    861  * @param string $primary_table     Primary database table name.
    862  * @param string $primary_id_column Primary ID column name.
    863  * @param object $context           Optional. The main query object
    864  * @return array Associative array of `JOIN` and `WHERE` SQL.
    865  */
    866 function get_meta_sql( $meta_query, $type, $primary_table, $primary_id_column, $context = null ) {
    867     $meta_query_obj = new WP_Meta_Query( $meta_query );
    868     return $meta_query_obj->get_sql( $type, $primary_table, $primary_id_column, $context );
    869 }
    870 
    8712/**
    8723 * Class for generating SQL clauses that filter a primary query according to metadata keys and values.
     
    8778 *
    8789 * @since 3.2.0
     10 * @package WordPress
     11 * @subpackage Meta
    87912 */
    88013class WP_Meta_Query {
     
    1604737    }
    1605738}
    1606 
    1607 /**
    1608  * Retrieve the name of the metadata table for the specified object type.
    1609  *
    1610  * @since 2.9.0
    1611  *
    1612  * @global wpdb $wpdb WordPress database abstraction object.
    1613  *
    1614  * @param string $type Type of object to get metadata table for (e.g., comment, post, or user)
    1615  * @return string|false Metadata table name, or false if no metadata table exists
    1616  */
    1617 function _get_meta_table($type) {
    1618     global $wpdb;
    1619 
    1620     $table_name = $type . 'meta';
    1621 
    1622     if ( empty($wpdb->$table_name) )
    1623         return false;
    1624 
    1625     return $wpdb->$table_name;
    1626 }
    1627 
    1628 /**
    1629  * Determine whether a meta key is protected.
    1630  *
    1631  * @since 3.1.3
    1632  *
    1633  * @param string      $meta_key Meta key
    1634  * @param string|null $meta_type
    1635  * @return bool True if the key is protected, false otherwise.
    1636  */
    1637 function is_protected_meta( $meta_key, $meta_type = null ) {
    1638     $protected = ( '_' == $meta_key[0] );
    1639 
    1640     /**
    1641      * Filter whether a meta key is protected.
    1642      *
    1643      * @since 3.2.0
    1644      *
    1645      * @param bool   $protected Whether the key is protected. Default false.
    1646      * @param string $meta_key  Meta key.
    1647      * @param string $meta_type Meta type.
    1648      */
    1649     return apply_filters( 'is_protected_meta', $protected, $meta_key, $meta_type );
    1650 }
    1651 
    1652 /**
    1653  * Sanitize meta value.
    1654  *
    1655  * @since 3.1.3
    1656  *
    1657  * @param string $meta_key   Meta key
    1658  * @param mixed  $meta_value Meta value to sanitize
    1659  * @param string $meta_type  Type of meta
    1660  * @return mixed Sanitized $meta_value
    1661  */
    1662 function sanitize_meta( $meta_key, $meta_value, $meta_type ) {
    1663 
    1664     /**
    1665      * Filter the sanitization of a specific meta key of a specific meta type.
    1666      *
    1667      * The dynamic portions of the hook name, `$meta_type`, and `$meta_key`,
    1668      * refer to the metadata object type (comment, post, or user) and the meta
    1669      * key value,
    1670      * respectively.
    1671      *
    1672      * @since 3.3.0
    1673      *
    1674      * @param mixed  $meta_value Meta value to sanitize.
    1675      * @param string $meta_key   Meta key.
    1676      * @param string $meta_type  Meta type.
    1677      */
    1678     return apply_filters( "sanitize_{$meta_type}_meta_{$meta_key}", $meta_value, $meta_key, $meta_type );
    1679 }
    1680 
    1681 /**
    1682  * Register meta key
    1683  *
    1684  * @since 3.3.0
    1685  *
    1686  * @param string       $meta_type         Type of meta
    1687  * @param string       $meta_key          Meta key
    1688  * @param string|array $sanitize_callback A function or method to call when sanitizing the value of $meta_key.
    1689  * @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.
    1690  */
    1691 function register_meta( $meta_type, $meta_key, $sanitize_callback, $auth_callback = null ) {
    1692     if ( is_callable( $sanitize_callback ) )
    1693         add_filter( "sanitize_{$meta_type}_meta_{$meta_key}", $sanitize_callback, 10, 3 );
    1694 
    1695     if ( empty( $auth_callback ) ) {
    1696         if ( is_protected_meta( $meta_key, $meta_type ) )
    1697             $auth_callback = '__return_false';
    1698         else
    1699             $auth_callback = '__return_true';
    1700     }
    1701 
    1702     if ( is_callable( $auth_callback ) )
    1703         add_filter( "auth_{$meta_type}_meta_{$meta_key}", $auth_callback, 10, 6 );
    1704 }
  • trunk/src/wp-includes/meta-functions.php

    r33758 r33761  
    870870
    871871/**
    872  * Class for generating SQL clauses that filter a primary query according to metadata keys and values.
    873  *
    874  * `WP_Meta_Query` is a helper that allows primary query classes, such as {@see WP_Query} and {@see WP_User_Query},
    875  * to filter their results by object metadata, by generating `JOIN` and `WHERE` subclauses to be attached
    876  * to the primary SQL query string.
    877  *
    878  * @since 3.2.0
    879  */
    880 class WP_Meta_Query {
    881     /**
    882      * Array of metadata queries.
    883      *
    884      * See {@see WP_Meta_Query::__construct()} for information on meta query arguments.
    885      *
    886      * @since 3.2.0
    887      * @access public
    888      * @var array
    889      */
    890     public $queries = array();
    891 
    892     /**
    893      * The relation between the queries. Can be one of 'AND' or 'OR'.
    894      *
    895      * @since 3.2.0
    896      * @access public
    897      * @var string
    898      */
    899     public $relation;
    900 
    901     /**
    902      * Database table to query for the metadata.
    903      *
    904      * @since 4.1.0
    905      * @access public
    906      * @var string
    907      */
    908     public $meta_table;
    909 
    910     /**
    911      * Column in meta_table that represents the ID of the object the metadata belongs to.
    912      *
    913      * @since 4.1.0
    914      * @access public
    915      * @var string
    916      */
    917     public $meta_id_column;
    918 
    919     /**
    920      * Database table that where the metadata's objects are stored (eg $wpdb->users).
    921      *
    922      * @since 4.1.0
    923      * @access public
    924      * @var string
    925      */
    926     public $primary_table;
    927 
    928     /**
    929      * Column in primary_table that represents the ID of the object.
    930      *
    931      * @since 4.1.0
    932      * @access public
    933      * @var string
    934      */
    935     public $primary_id_column;
    936 
    937     /**
    938      * A flat list of table aliases used in JOIN clauses.
    939      *
    940      * @since 4.1.0
    941      * @access protected
    942      * @var array
    943      */
    944     protected $table_aliases = array();
    945 
    946     /**
    947      * A flat list of clauses, keyed by clause 'name'.
    948      *
    949      * @since 4.2.0
    950      * @access protected
    951      * @var array
    952      */
    953     protected $clauses = array();
    954 
    955     /**
    956      * Whether the query contains any OR relations.
    957      *
    958      * @since 4.3.0
    959      * @access protected
    960      * @var bool
    961      */
    962     protected $has_or_relation = false;
    963 
    964     /**
    965      * Constructor.
    966      *
    967      * @since 3.2.0
    968      * @since 4.2.0 Introduced support for naming query clauses by associative array keys.
    969      *
    970      * @access public
    971      *
    972      * @param array $meta_query {
    973      *     Array of meta query clauses. When first-order clauses use strings as their array keys, they may be
    974      *     referenced in the 'orderby' parameter of the parent query.
    975      *
    976      *     @type string $relation Optional. The MySQL keyword used to join
    977      *                            the clauses of the query. Accepts 'AND', or 'OR'. Default 'AND'.
    978      *     @type array {
    979      *         Optional. An array of first-order clause parameters, or another fully-formed meta query.
    980      *
    981      *         @type string $key     Meta key to filter by.
    982      *         @type string $value   Meta value to filter by.
    983      *         @type string $compare MySQL operator used for comparing the $value. Accepts '=',
    984      *                               '!=', '>', '>=', '<', '<=', 'LIKE', 'NOT LIKE', 'IN', 'NOT IN',
    985      *                               'BETWEEN', 'NOT BETWEEN', 'REGEXP', 'NOT REGEXP', or 'RLIKE'.
    986      *                               Default is 'IN' when `$value` is an array, '=' otherwise.
    987      *         @type string $type    MySQL data type that the meta_value column will be CAST to for
    988      *                               comparisons. Accepts 'NUMERIC', 'BINARY', 'CHAR', 'DATE',
    989      *                               'DATETIME', 'DECIMAL', 'SIGNED', 'TIME', or 'UNSIGNED'.
    990      *                               Default is 'CHAR'.
    991      *     }
    992      * }
    993      */
    994     public function __construct( $meta_query = false ) {
    995         if ( !$meta_query )
    996             return;
    997 
    998         if ( isset( $meta_query['relation'] ) && strtoupper( $meta_query['relation'] ) == 'OR' ) {
    999             $this->relation = 'OR';
    1000         } else {
    1001             $this->relation = 'AND';
    1002         }
    1003 
    1004         $this->queries = $this->sanitize_query( $meta_query );
    1005     }
    1006 
    1007     /**
    1008      * Ensure the 'meta_query' argument passed to the class constructor is well-formed.
    1009      *
    1010      * Eliminates empty items and ensures that a 'relation' is set.
    1011      *
    1012      * @since 4.1.0
    1013      * @access public
    1014      *
    1015      * @param array $queries Array of query clauses.
    1016      * @return array Sanitized array of query clauses.
    1017      */
    1018     public function sanitize_query( $queries ) {
    1019         $clean_queries = array();
    1020 
    1021         if ( ! is_array( $queries ) ) {
    1022             return $clean_queries;
    1023         }
    1024 
    1025         foreach ( $queries as $key => $query ) {
    1026             if ( 'relation' === $key ) {
    1027                 $relation = $query;
    1028 
    1029             } elseif ( ! is_array( $query ) ) {
    1030                 continue;
    1031 
    1032             // First-order clause.
    1033             } elseif ( $this->is_first_order_clause( $query ) ) {
    1034                 if ( isset( $query['value'] ) && array() === $query['value'] ) {
    1035                     unset( $query['value'] );
    1036                 }
    1037 
    1038                 $clean_queries[ $key ] = $query;
    1039 
    1040             // Otherwise, it's a nested query, so we recurse.
    1041             } else {
    1042                 $cleaned_query = $this->sanitize_query( $query );
    1043 
    1044                 if ( ! empty( $cleaned_query ) ) {
    1045                     $clean_queries[ $key ] = $cleaned_query;
    1046                 }
    1047             }
    1048         }
    1049 
    1050         if ( empty( $clean_queries ) ) {
    1051             return $clean_queries;
    1052         }
    1053 
    1054         // Sanitize the 'relation' key provided in the query.
    1055         if ( isset( $relation ) && 'OR' === strtoupper( $relation ) ) {
    1056             $clean_queries['relation'] = 'OR';
    1057             $this->has_or_relation = true;
    1058 
    1059         /*
    1060          * If there is only a single clause, call the relation 'OR'.
    1061          * This value will not actually be used to join clauses, but it
    1062          * simplifies the logic around combining key-only queries.
    1063          */
    1064         } elseif ( 1 === count( $clean_queries ) ) {
    1065             $clean_queries['relation'] = 'OR';
    1066 
    1067         // Default to AND.
    1068         } else {
    1069             $clean_queries['relation'] = 'AND';
    1070         }
    1071 
    1072         return $clean_queries;
    1073     }
    1074 
    1075     /**
    1076      * Determine whether a query clause is first-order.
    1077      *
    1078      * A first-order meta query clause is one that has either a 'key' or
    1079      * a 'value' array key.
    1080      *
    1081      * @since 4.1.0
    1082      * @access protected
    1083      *
    1084      * @param array $query Meta query arguments.
    1085      * @return bool Whether the query clause is a first-order clause.
    1086      */
    1087     protected function is_first_order_clause( $query ) {
    1088         return isset( $query['key'] ) || isset( $query['value'] );
    1089     }
    1090 
    1091     /**
    1092      * Constructs a meta query based on 'meta_*' query vars
    1093      *
    1094      * @since 3.2.0
    1095      * @access public
    1096      *
    1097      * @param array $qv The query variables
    1098      */
    1099     public function parse_query_vars( $qv ) {
    1100         $meta_query = array();
    1101 
    1102         /*
    1103          * For orderby=meta_value to work correctly, simple query needs to be
    1104          * first (so that its table join is against an unaliased meta table) and
    1105          * needs to be its own clause (so it doesn't interfere with the logic of
    1106          * the rest of the meta_query).
    1107          */
    1108         $primary_meta_query = array();
    1109         foreach ( array( 'key', 'compare', 'type' ) as $key ) {
    1110             if ( ! empty( $qv[ "meta_$key" ] ) ) {
    1111                 $primary_meta_query[ $key ] = $qv[ "meta_$key" ];
    1112             }
    1113         }
    1114 
    1115         // WP_Query sets 'meta_value' = '' by default.
    1116         if ( isset( $qv['meta_value'] ) && '' !== $qv['meta_value'] && ( ! is_array( $qv['meta_value'] ) || $qv['meta_value'] ) ) {
    1117             $primary_meta_query['value'] = $qv['meta_value'];
    1118         }
    1119 
    1120         $existing_meta_query = isset( $qv['meta_query'] ) && is_array( $qv['meta_query'] ) ? $qv['meta_query'] : array();
    1121 
    1122         if ( ! empty( $primary_meta_query ) && ! empty( $existing_meta_query ) ) {
    1123             $meta_query = array(
    1124                 'relation' => 'AND',
    1125                 $primary_meta_query,
    1126                 $existing_meta_query,
    1127             );
    1128         } elseif ( ! empty( $primary_meta_query ) ) {
    1129             $meta_query = array(
    1130                 $primary_meta_query,
    1131             );
    1132         } elseif ( ! empty( $existing_meta_query ) ) {
    1133             $meta_query = $existing_meta_query;
    1134         }
    1135 
    1136         $this->__construct( $meta_query );
    1137     }
    1138 
    1139     /**
    1140      * Return the appropriate alias for the given meta type if applicable.
    1141      *
    1142      * @since 3.7.0
    1143      * @access public
    1144      *
    1145      * @param string $type MySQL type to cast meta_value.
    1146      * @return string MySQL type.
    1147      */
    1148     public function get_cast_for_type( $type = '' ) {
    1149         if ( empty( $type ) )
    1150             return 'CHAR';
    1151 
    1152         $meta_type = strtoupper( $type );
    1153 
    1154         if ( ! preg_match( '/^(?:BINARY|CHAR|DATE|DATETIME|SIGNED|UNSIGNED|TIME|NUMERIC(?:\(\d+(?:,\s?\d+)?\))?|DECIMAL(?:\(\d+(?:,\s?\d+)?\))?)$/', $meta_type ) )
    1155             return 'CHAR';
    1156 
    1157         if ( 'NUMERIC' == $meta_type )
    1158             $meta_type = 'SIGNED';
    1159 
    1160         return $meta_type;
    1161     }
    1162 
    1163     /**
    1164      * Generates SQL clauses to be appended to a main query.
    1165      *
    1166      * @since 3.2.0
    1167      * @access public
    1168      *
    1169      * @param string $type              Type of meta, eg 'user', 'post'.
    1170      * @param string $primary_table     Database table where the object being filtered is stored (eg wp_users).
    1171      * @param string $primary_id_column ID column for the filtered object in $primary_table.
    1172      * @param object $context           Optional. The main query object.
    1173      * @return false|array {
    1174      *     Array containing JOIN and WHERE SQL clauses to append to the main query.
    1175      *
    1176      *     @type string $join  SQL fragment to append to the main JOIN clause.
    1177      *     @type string $where SQL fragment to append to the main WHERE clause.
    1178      * }
    1179      */
    1180     public function get_sql( $type, $primary_table, $primary_id_column, $context = null ) {
    1181         if ( ! $meta_table = _get_meta_table( $type ) ) {
    1182             return false;
    1183         }
    1184 
    1185         $this->meta_table     = $meta_table;
    1186         $this->meta_id_column = sanitize_key( $type . '_id' );
    1187 
    1188         $this->primary_table     = $primary_table;
    1189         $this->primary_id_column = $primary_id_column;
    1190 
    1191         $sql = $this->get_sql_clauses();
    1192 
    1193         /*
    1194          * If any JOINs are LEFT JOINs (as in the case of NOT EXISTS), then all JOINs should
    1195          * be LEFT. Otherwise posts with no metadata will be excluded from results.
    1196          */
    1197         if ( false !== strpos( $sql['join'], 'LEFT JOIN' ) ) {
    1198             $sql['join'] = str_replace( 'INNER JOIN', 'LEFT JOIN', $sql['join'] );
    1199         }
    1200 
    1201         /**
    1202          * Filter the meta query's generated SQL.
    1203          *
    1204          * @since 3.1.0
    1205          *
    1206          * @param array $args {
    1207          *     An array of meta query SQL arguments.
    1208          *
    1209          *     @type array  $clauses           Array containing the query's JOIN and WHERE clauses.
    1210          *     @type array  $queries           Array of meta queries.
    1211          *     @type string $type              Type of meta.
    1212          *     @type string $primary_table     Primary table.
    1213          *     @type string $primary_id_column Primary column ID.
    1214          *     @type object $context           The main query object.
    1215          * }
    1216          */
    1217         return apply_filters_ref_array( 'get_meta_sql', array( $sql, $this->queries, $type, $primary_table, $primary_id_column, $context ) );
    1218     }
    1219 
    1220     /**
    1221      * Generate SQL clauses to be appended to a main query.
    1222      *
    1223      * Called by the public {@see WP_Meta_Query::get_sql()}, this method
    1224      * is abstracted out to maintain parity with the other Query classes.
    1225      *
    1226      * @since 4.1.0
    1227      * @access protected
    1228      *
    1229      * @return array {
    1230      *     Array containing JOIN and WHERE SQL clauses to append to the main query.
    1231      *
    1232      *     @type string $join  SQL fragment to append to the main JOIN clause.
    1233      *     @type string $where SQL fragment to append to the main WHERE clause.
    1234      * }
    1235      */
    1236     protected function get_sql_clauses() {
    1237         /*
    1238          * $queries are passed by reference to get_sql_for_query() for recursion.
    1239          * To keep $this->queries unaltered, pass a copy.
    1240          */
    1241         $queries = $this->queries;
    1242         $sql = $this->get_sql_for_query( $queries );
    1243 
    1244         if ( ! empty( $sql['where'] ) ) {
    1245             $sql['where'] = ' AND ' . $sql['where'];
    1246         }
    1247 
    1248         return $sql;
    1249     }
    1250 
    1251     /**
    1252      * Generate SQL clauses for a single query array.
    1253      *
    1254      * If nested subqueries are found, this method recurses the tree to
    1255      * produce the properly nested SQL.
    1256      *
    1257      * @since 4.1.0
    1258      * @access protected
    1259      *
    1260      * @param array $query Query to parse, passed by reference.
    1261      * @param int   $depth Optional. Number of tree levels deep we currently are.
    1262      *                     Used to calculate indentation. Default 0.
    1263      * @return array {
    1264      *     Array containing JOIN and WHERE SQL clauses to append to a single query array.
    1265      *
    1266      *     @type string $join  SQL fragment to append to the main JOIN clause.
    1267      *     @type string $where SQL fragment to append to the main WHERE clause.
    1268      * }
    1269      */
    1270     protected function get_sql_for_query( &$query, $depth = 0 ) {
    1271         $sql_chunks = array(
    1272             'join'  => array(),
    1273             'where' => array(),
    1274         );
    1275 
    1276         $sql = array(
    1277             'join'  => '',
    1278             'where' => '',
    1279         );
    1280 
    1281         $indent = '';
    1282         for ( $i = 0; $i < $depth; $i++ ) {
    1283             $indent .= "  ";
    1284         }
    1285 
    1286         foreach ( $query as $key => &$clause ) {
    1287             if ( 'relation' === $key ) {
    1288                 $relation = $query['relation'];
    1289             } elseif ( is_array( $clause ) ) {
    1290 
    1291                 // This is a first-order clause.
    1292                 if ( $this->is_first_order_clause( $clause ) ) {
    1293                     $clause_sql = $this->get_sql_for_clause( $clause, $query, $key );
    1294 
    1295                     $where_count = count( $clause_sql['where'] );
    1296                     if ( ! $where_count ) {
    1297                         $sql_chunks['where'][] = '';
    1298                     } elseif ( 1 === $where_count ) {
    1299                         $sql_chunks['where'][] = $clause_sql['where'][0];
    1300                     } else {
    1301                         $sql_chunks['where'][] = '( ' . implode( ' AND ', $clause_sql['where'] ) . ' )';
    1302                     }
    1303 
    1304                     $sql_chunks['join'] = array_merge( $sql_chunks['join'], $clause_sql['join'] );
    1305                 // This is a subquery, so we recurse.
    1306                 } else {
    1307                     $clause_sql = $this->get_sql_for_query( $clause, $depth + 1 );
    1308 
    1309                     $sql_chunks['where'][] = $clause_sql['where'];
    1310                     $sql_chunks['join'][]  = $clause_sql['join'];
    1311                 }
    1312             }
    1313         }
    1314 
    1315         // Filter to remove empties.
    1316         $sql_chunks['join']  = array_filter( $sql_chunks['join'] );
    1317         $sql_chunks['where'] = array_filter( $sql_chunks['where'] );
    1318 
    1319         if ( empty( $relation ) ) {
    1320             $relation = 'AND';
    1321         }
    1322 
    1323         // Filter duplicate JOIN clauses and combine into a single string.
    1324         if ( ! empty( $sql_chunks['join'] ) ) {
    1325             $sql['join'] = implode( ' ', array_unique( $sql_chunks['join'] ) );
    1326         }
    1327 
    1328         // Generate a single WHERE clause with proper brackets and indentation.
    1329         if ( ! empty( $sql_chunks['where'] ) ) {
    1330             $sql['where'] = '( ' . "\n  " . $indent . implode( ' ' . "\n  " . $indent . $relation . ' ' . "\n  " . $indent, $sql_chunks['where'] ) . "\n" . $indent . ')';
    1331         }
    1332 
    1333         return $sql;
    1334     }
    1335 
    1336     /**
    1337      * Generate SQL JOIN and WHERE clauses for a first-order query clause.
    1338      *
    1339      * "First-order" means that it's an array with a 'key' or 'value'.
    1340      *
    1341      * @since 4.1.0
    1342      * @access public
    1343      *
    1344      * @global wpdb $wpdb
    1345      *
    1346      * @param array  $clause       Query clause, passed by reference.
    1347      * @param array  $parent_query Parent query array.
    1348      * @param string $clause_key   Optional. The array key used to name the clause in the original `$meta_query`
    1349      *                             parameters. If not provided, a key will be generated automatically.
    1350      * @return array {
    1351      *     Array containing JOIN and WHERE SQL clauses to append to a first-order query.
    1352      *
    1353      *     @type string $join  SQL fragment to append to the main JOIN clause.
    1354      *     @type string $where SQL fragment to append to the main WHERE clause.
    1355      * }
    1356      */
    1357     public function get_sql_for_clause( &$clause, $parent_query, $clause_key = '' ) {
    1358         global $wpdb;
    1359 
    1360         $sql_chunks = array(
    1361             'where' => array(),
    1362             'join' => array(),
    1363         );
    1364 
    1365         if ( isset( $clause['compare'] ) ) {
    1366             $clause['compare'] = strtoupper( $clause['compare'] );
    1367         } else {
    1368             $clause['compare'] = isset( $clause['value'] ) && is_array( $clause['value'] ) ? 'IN' : '=';
    1369         }
    1370 
    1371         if ( ! in_array( $clause['compare'], array(
    1372             '=', '!=', '>', '>=', '<', '<=',
    1373             'LIKE', 'NOT LIKE',
    1374             'IN', 'NOT IN',
    1375             'BETWEEN', 'NOT BETWEEN',
    1376             'EXISTS', 'NOT EXISTS',
    1377             'REGEXP', 'NOT REGEXP', 'RLIKE'
    1378         ) ) ) {
    1379             $clause['compare'] = '=';
    1380         }
    1381 
    1382         $meta_compare = $clause['compare'];
    1383 
    1384         // First build the JOIN clause, if one is required.
    1385         $join = '';
    1386 
    1387         // We prefer to avoid joins if possible. Look for an existing join compatible with this clause.
    1388         $alias = $this->find_compatible_table_alias( $clause, $parent_query );
    1389         if ( false === $alias ) {
    1390             $i = count( $this->table_aliases );
    1391             $alias = $i ? 'mt' . $i : $this->meta_table;
    1392 
    1393             // JOIN clauses for NOT EXISTS have their own syntax.
    1394             if ( 'NOT EXISTS' === $meta_compare ) {
    1395                 $join .= " LEFT JOIN $this->meta_table";
    1396                 $join .= $i ? " AS $alias" : '';
    1397                 $join .= $wpdb->prepare( " ON ($this->primary_table.$this->primary_id_column = $alias.$this->meta_id_column AND $alias.meta_key = %s )", $clause['key'] );
    1398 
    1399             // All other JOIN clauses.
    1400             } else {
    1401                 $join .= " INNER JOIN $this->meta_table";
    1402                 $join .= $i ? " AS $alias" : '';
    1403                 $join .= " ON ( $this->primary_table.$this->primary_id_column = $alias.$this->meta_id_column )";
    1404             }
    1405 
    1406             $this->table_aliases[] = $alias;
    1407             $sql_chunks['join'][] = $join;
    1408         }
    1409 
    1410         // Save the alias to this clause, for future siblings to find.
    1411         $clause['alias'] = $alias;
    1412 
    1413         // Determine the data type.
    1414         $_meta_type = isset( $clause['type'] ) ? $clause['type'] : '';
    1415         $meta_type  = $this->get_cast_for_type( $_meta_type );
    1416         $clause['cast'] = $meta_type;
    1417 
    1418         // Fallback for clause keys is the table alias.
    1419         if ( ! $clause_key ) {
    1420             $clause_key = $clause['alias'];
    1421         }
    1422 
    1423         // Ensure unique clause keys, so none are overwritten.
    1424         $iterator = 1;
    1425         $clause_key_base = $clause_key;
    1426         while ( isset( $this->clauses[ $clause_key ] ) ) {
    1427             $clause_key = $clause_key_base . '-' . $iterator;
    1428             $iterator++;
    1429         }
    1430 
    1431         // Store the clause in our flat array.
    1432         $this->clauses[ $clause_key ] =& $clause;
    1433 
    1434         // Next, build the WHERE clause.
    1435 
    1436         // meta_key.
    1437         if ( array_key_exists( 'key', $clause ) ) {
    1438             if ( 'NOT EXISTS' === $meta_compare ) {
    1439                 $sql_chunks['where'][] = $alias . '.' . $this->meta_id_column . ' IS NULL';
    1440             } else {
    1441                 $sql_chunks['where'][] = $wpdb->prepare( "$alias.meta_key = %s", trim( $clause['key'] ) );
    1442             }
    1443         }
    1444 
    1445         // meta_value.
    1446         if ( array_key_exists( 'value', $clause ) ) {
    1447             $meta_value = $clause['value'];
    1448 
    1449             if ( in_array( $meta_compare, array( 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN' ) ) ) {
    1450                 if ( ! is_array( $meta_value ) ) {
    1451                     $meta_value = preg_split( '/[,\s]+/', $meta_value );
    1452                 }
    1453             } else {
    1454                 $meta_value = trim( $meta_value );
    1455             }
    1456 
    1457             switch ( $meta_compare ) {
    1458                 case 'IN' :
    1459                 case 'NOT IN' :
    1460                     $meta_compare_string = '(' . substr( str_repeat( ',%s', count( $meta_value ) ), 1 ) . ')';
    1461                     $where = $wpdb->prepare( $meta_compare_string, $meta_value );
    1462                     break;
    1463 
    1464                 case 'BETWEEN' :
    1465                 case 'NOT BETWEEN' :
    1466                     $meta_value = array_slice( $meta_value, 0, 2 );
    1467                     $where = $wpdb->prepare( '%s AND %s', $meta_value );
    1468                     break;
    1469 
    1470                 case 'LIKE' :
    1471                 case 'NOT LIKE' :
    1472                     $meta_value = '%' . $wpdb->esc_like( $meta_value ) . '%';
    1473                     $where = $wpdb->prepare( '%s', $meta_value );
    1474                     break;
    1475 
    1476                 // EXISTS with a value is interpreted as '='.
    1477                 case 'EXISTS' :
    1478                     $meta_compare = '=';
    1479                     $where = $wpdb->prepare( '%s', $meta_value );
    1480                     break;
    1481 
    1482                 // 'value' is ignored for NOT EXISTS.
    1483                 case 'NOT EXISTS' :
    1484                     $where = '';
    1485                     break;
    1486 
    1487                 default :
    1488                     $where = $wpdb->prepare( '%s', $meta_value );
    1489                     break;
    1490 
    1491             }
    1492 
    1493             if ( $where ) {
    1494                 $sql_chunks['where'][] = "CAST($alias.meta_value AS {$meta_type}) {$meta_compare} {$where}";
    1495             }
    1496         }
    1497 
    1498         /*
    1499          * Multiple WHERE clauses (for meta_key and meta_value) should
    1500          * be joined in parentheses.
    1501          */
    1502         if ( 1 < count( $sql_chunks['where'] ) ) {
    1503             $sql_chunks['where'] = array( '( ' . implode( ' AND ', $sql_chunks['where'] ) . ' )' );
    1504         }
    1505 
    1506         return $sql_chunks;
    1507     }
    1508 
    1509     /**
    1510      * Get a flattened list of sanitized meta clauses.
    1511      *
    1512      * This array should be used for clause lookup, as when the table alias and CAST type must be determined for
    1513      * a value of 'orderby' corresponding to a meta clause.
    1514      *
    1515      * @since 4.2.0
    1516      * @access public
    1517      *
    1518      * @return array Meta clauses.
    1519      */
    1520     public function get_clauses() {
    1521         return $this->clauses;
    1522     }
    1523 
    1524     /**
    1525      * Identify an existing table alias that is compatible with the current
    1526      * query clause.
    1527      *
    1528      * We avoid unnecessary table joins by allowing each clause to look for
    1529      * an existing table alias that is compatible with the query that it
    1530      * needs to perform.
    1531      *
    1532      * An existing alias is compatible if (a) it is a sibling of `$clause`
    1533      * (ie, it's under the scope of the same relation), and (b) the combination
    1534      * of operator and relation between the clauses allows for a shared table join.
    1535      * In the case of {@see WP_Meta_Query}, this only applies to 'IN' clauses that
    1536      * are connected by the relation 'OR'.
    1537      *
    1538      * @since 4.1.0
    1539      * @access protected
    1540      *
    1541      * @param  array       $clause       Query clause.
    1542      * @param  array       $parent_query Parent query of $clause.
    1543      * @return string|bool Table alias if found, otherwise false.
    1544      */
    1545     protected function find_compatible_table_alias( $clause, $parent_query ) {
    1546         $alias = false;
    1547 
    1548         foreach ( $parent_query as $sibling ) {
    1549             // If the sibling has no alias yet, there's nothing to check.
    1550             if ( empty( $sibling['alias'] ) ) {
    1551                 continue;
    1552             }
    1553 
    1554             // We're only interested in siblings that are first-order clauses.
    1555             if ( ! is_array( $sibling ) || ! $this->is_first_order_clause( $sibling ) ) {
    1556                 continue;
    1557             }
    1558 
    1559             $compatible_compares = array();
    1560 
    1561             // Clauses connected by OR can share joins as long as they have "positive" operators.
    1562             if ( 'OR' === $parent_query['relation'] ) {
    1563                 $compatible_compares = array( '=', 'IN', 'BETWEEN', 'LIKE', 'REGEXP', 'RLIKE', '>', '>=', '<', '<=' );
    1564 
    1565             // Clauses joined by AND with "negative" operators share a join only if they also share a key.
    1566             } elseif ( isset( $sibling['key'] ) && isset( $clause['key'] ) && $sibling['key'] === $clause['key'] ) {
    1567                 $compatible_compares = array( '!=', 'NOT IN', 'NOT LIKE' );
    1568             }
    1569 
    1570             $clause_compare  = strtoupper( $clause['compare'] );
    1571             $sibling_compare = strtoupper( $sibling['compare'] );
    1572             if ( in_array( $clause_compare, $compatible_compares ) && in_array( $sibling_compare, $compatible_compares ) ) {
    1573                 $alias = $sibling['alias'];
    1574                 break;
    1575             }
    1576         }
    1577 
    1578         /**
    1579          * Filter the table alias identified as compatible with the current clause.
    1580          *
    1581          * @since 4.1.0
    1582          *
    1583          * @param string|bool $alias        Table alias, or false if none was found.
    1584          * @param array       $clause       First-order query clause.
    1585          * @param array       $parent_query Parent of $clause.
    1586          * @param object      $this         WP_Meta_Query object.
    1587          */
    1588         return apply_filters( 'meta_query_find_compatible_table_alias', $alias, $clause, $parent_query, $this ) ;
    1589     }
    1590 
    1591     /**
    1592      * Checks whether the current query has any OR relations.
    1593      *
    1594      * In some cases, the presence of an OR relation somewhere in the query will require
    1595      * the use of a `DISTINCT` or `GROUP BY` keyword in the `SELECT` clause. The current
    1596      * method can be used in these cases to determine whether such a clause is necessary.
    1597      *
    1598      * @since 4.3.0
    1599      *
    1600      * @return bool True if the query contains any `OR` relations, otherwise false.
    1601      */
    1602     public function has_or_relation() {
    1603         return $this->has_or_relation;
    1604     }
    1605 }
    1606 
    1607 /**
    1608872 * Retrieve the name of the metadata table for the specified object type.
    1609873 *
  • trunk/src/wp-includes/meta.php

    r33665 r33761  
    1212 */
    1313
    14 /**
    15  * Add metadata for the specified object.
    16  *
    17  * @since 2.9.0
    18  *
    19  * @global wpdb $wpdb WordPress database abstraction object.
    20  *
    21  * @param string $meta_type  Type of object metadata is for (e.g., comment, post, or user)
    22  * @param int    $object_id  ID of the object metadata is for
    23  * @param string $meta_key   Metadata key
    24  * @param mixed  $meta_value Metadata value. Must be serializable if non-scalar.
    25  * @param bool   $unique     Optional, default is false.
    26  *                           Whether the specified metadata key should be unique for the object.
    27  *                           If true, and the object already has a value for the specified metadata key,
    28  *                           no change will be made.
    29  * @return int|false The meta ID on success, false on failure.
    30  */
    31 function add_metadata($meta_type, $object_id, $meta_key, $meta_value, $unique = false) {
    32     global $wpdb;
    33 
    34     if ( ! $meta_type || ! $meta_key || ! is_numeric( $object_id ) ) {
    35         return false;
    36     }
    37 
    38     $object_id = absint( $object_id );
    39     if ( ! $object_id ) {
    40         return false;
    41     }
    42 
    43     $table = _get_meta_table( $meta_type );
    44     if ( ! $table ) {
    45         return false;
    46     }
    47 
    48     $column = sanitize_key($meta_type . '_id');
    49 
    50     // expected_slashed ($meta_key)
    51     $meta_key = wp_unslash($meta_key);
    52     $meta_value = wp_unslash($meta_value);
    53     $meta_value = sanitize_meta( $meta_key, $meta_value, $meta_type );
    54 
    55     /**
    56      * Filter whether to add metadata of a specific type.
    57      *
    58      * The dynamic portion of the hook, `$meta_type`, refers to the meta
    59      * object type (comment, post, or user). Returning a non-null value
    60      * will effectively short-circuit the function.
    61      *
    62      * @since 3.1.0
    63      *
    64      * @param null|bool $check      Whether to allow adding metadata for the given type.
    65      * @param int       $object_id  Object ID.
    66      * @param string    $meta_key   Meta key.
    67      * @param mixed     $meta_value Meta value. Must be serializable if non-scalar.
    68      * @param bool      $unique     Whether the specified meta key should be unique
    69      *                              for the object. Optional. Default false.
    70      */
    71     $check = apply_filters( "add_{$meta_type}_metadata", null, $object_id, $meta_key, $meta_value, $unique );
    72     if ( null !== $check )
    73         return $check;
    74 
    75     if ( $unique && $wpdb->get_var( $wpdb->prepare(
    76         "SELECT COUNT(*) FROM $table WHERE meta_key = %s AND $column = %d",
    77         $meta_key, $object_id ) ) )
    78         return false;
    79 
    80     $_meta_value = $meta_value;
    81     $meta_value = maybe_serialize( $meta_value );
    82 
    83     /**
    84      * Fires immediately before meta of a specific type is added.
    85      *
    86      * The dynamic portion of the hook, `$meta_type`, refers to the meta
    87      * object type (comment, post, or user).
    88      *
    89      * @since 3.1.0
    90      *
    91      * @param int    $object_id  Object ID.
    92      * @param string $meta_key   Meta key.
    93      * @param mixed  $meta_value Meta value.
    94      */
    95     do_action( "add_{$meta_type}_meta", $object_id, $meta_key, $_meta_value );
    96 
    97     $result = $wpdb->insert( $table, array(
    98         $column => $object_id,
    99         'meta_key' => $meta_key,
    100         'meta_value' => $meta_value
    101     ) );
    102 
    103     if ( ! $result )
    104         return false;
    105 
    106     $mid = (int) $wpdb->insert_id;
    107 
    108     wp_cache_delete($object_id, $meta_type . '_meta');
    109 
    110     /**
    111      * Fires immediately after meta of a specific type is added.
    112      *
    113      * The dynamic portion of the hook, `$meta_type`, refers to the meta
    114      * object type (comment, post, or user).
    115      *
    116      * @since 2.9.0
    117      *
    118      * @param int    $mid        The meta ID after successful update.
    119      * @param int    $object_id  Object ID.
    120      * @param string $meta_key   Meta key.
    121      * @param mixed  $meta_value Meta value.
    122      */
    123     do_action( "added_{$meta_type}_meta", $mid, $object_id, $meta_key, $_meta_value );
    124 
    125     return $mid;
    126 }
    127 
    128 /**
    129  * Update metadata for the specified object. If no value already exists for the specified object
    130  * ID and metadata key, the metadata will be added.
    131  *
    132  * @since 2.9.0
    133  *
    134  * @global wpdb $wpdb WordPress database abstraction object.
    135  *
    136  * @param string $meta_type  Type of object metadata is for (e.g., comment, post, or user)
    137  * @param int    $object_id  ID of the object metadata is for
    138  * @param string $meta_key   Metadata key
    139  * @param mixed  $meta_value Metadata value. Must be serializable if non-scalar.
    140  * @param mixed  $prev_value Optional. If specified, only update existing metadata entries with
    141  *                           the specified value. Otherwise, update all entries.
    142  * @return int|bool Meta ID if the key didn't exist, true on successful update, false on failure.
    143  */
    144 function update_metadata($meta_type, $object_id, $meta_key, $meta_value, $prev_value = '') {
    145     global $wpdb;
    146 
    147     if ( ! $meta_type || ! $meta_key || ! is_numeric( $object_id ) ) {
    148         return false;
    149     }
    150 
    151     $object_id = absint( $object_id );
    152     if ( ! $object_id ) {
    153         return false;
    154     }
    155 
    156     $table = _get_meta_table( $meta_type );
    157     if ( ! $table ) {
    158         return false;
    159     }
    160 
    161     $column = sanitize_key($meta_type . '_id');
    162     $id_column = 'user' == $meta_type ? 'umeta_id' : 'meta_id';
    163 
    164     // expected_slashed ($meta_key)
    165     $meta_key = wp_unslash($meta_key);
    166     $passed_value = $meta_value;
    167     $meta_value = wp_unslash($meta_value);
    168     $meta_value = sanitize_meta( $meta_key, $meta_value, $meta_type );
    169 
    170     /**
    171      * Filter whether to update metadata of a specific type.
    172      *
    173      * The dynamic portion of the hook, `$meta_type`, refers to the meta
    174      * object type (comment, post, or user). Returning a non-null value
    175      * will effectively short-circuit the function.
    176      *
    177      * @since 3.1.0
    178      *
    179      * @param null|bool $check      Whether to allow updating metadata for the given type.
    180      * @param int       $object_id  Object ID.
    181      * @param string    $meta_key   Meta key.
    182      * @param mixed     $meta_value Meta value. Must be serializable if non-scalar.
    183      * @param mixed     $prev_value Optional. If specified, only update existing
    184      *                              metadata entries with the specified value.
    185      *                              Otherwise, update all entries.
    186      */
    187     $check = apply_filters( "update_{$meta_type}_metadata", null, $object_id, $meta_key, $meta_value, $prev_value );
    188     if ( null !== $check )
    189         return (bool) $check;
    190 
    191     // Compare existing value to new value if no prev value given and the key exists only once.
    192     if ( empty($prev_value) ) {
    193         $old_value = get_metadata($meta_type, $object_id, $meta_key);
    194         if ( count($old_value) == 1 ) {
    195             if ( $old_value[0] === $meta_value )
    196                 return false;
    197         }
    198     }
    199 
    200     $meta_ids = $wpdb->get_col( $wpdb->prepare( "SELECT $id_column FROM $table WHERE meta_key = %s AND $column = %d", $meta_key, $object_id ) );
    201     if ( empty( $meta_ids ) ) {
    202         return add_metadata($meta_type, $object_id, $meta_key, $passed_value);
    203     }
    204 
    205     $_meta_value = $meta_value;
    206     $meta_value = maybe_serialize( $meta_value );
    207 
    208     $data  = compact( 'meta_value' );
    209     $where = array( $column => $object_id, 'meta_key' => $meta_key );
    210 
    211     if ( !empty( $prev_value ) ) {
    212         $prev_value = maybe_serialize($prev_value);
    213         $where['meta_value'] = $prev_value;
    214     }
    215 
    216     foreach ( $meta_ids as $meta_id ) {
    217         /**
    218          * Fires immediately before updating metadata of a specific type.
    219          *
    220          * The dynamic portion of the hook, `$meta_type`, refers to the meta
    221          * object type (comment, post, or user).
    222          *
    223          * @since 2.9.0
    224          *
    225          * @param int    $meta_id    ID of the metadata entry to update.
    226          * @param int    $object_id  Object ID.
    227          * @param string $meta_key   Meta key.
    228          * @param mixed  $meta_value Meta value.
    229          */
    230         do_action( "update_{$meta_type}_meta", $meta_id, $object_id, $meta_key, $_meta_value );
    231     }
    232 
    233     if ( 'post' == $meta_type ) {
    234         foreach ( $meta_ids as $meta_id ) {
    235             /**
    236              * Fires immediately before updating a post's metadata.
    237              *
    238              * @since 2.9.0
    239              *
    240              * @param int    $meta_id    ID of metadata entry to update.
    241              * @param int    $object_id  Object ID.
    242              * @param string $meta_key   Meta key.
    243              * @param mixed  $meta_value Meta value.
    244              */
    245             do_action( 'update_postmeta', $meta_id, $object_id, $meta_key, $meta_value );
    246         }
    247     }
    248 
    249     $result = $wpdb->update( $table, $data, $where );
    250     if ( ! $result )
    251         return false;
    252 
    253     wp_cache_delete($object_id, $meta_type . '_meta');
    254 
    255     foreach ( $meta_ids as $meta_id ) {
    256         /**
    257          * Fires immediately after updating metadata of a specific type.
    258          *
    259          * The dynamic portion of the hook, `$meta_type`, refers to the meta
    260          * object type (comment, post, or user).
    261          *
    262          * @since 2.9.0
    263          *
    264          * @param int    $meta_id    ID of updated metadata entry.
    265          * @param int    $object_id  Object ID.
    266          * @param string $meta_key   Meta key.
    267          * @param mixed  $meta_value Meta value.
    268          */
    269         do_action( "updated_{$meta_type}_meta", $meta_id, $object_id, $meta_key, $_meta_value );
    270     }
    271 
    272     if ( 'post' == $meta_type ) {
    273         foreach ( $meta_ids as $meta_id ) {
    274             /**
    275              * Fires immediately after updating a post's metadata.
    276              *
    277              * @since 2.9.0
    278              *
    279              * @param int    $meta_id    ID of updated metadata entry.
    280              * @param int    $object_id  Object ID.
    281              * @param string $meta_key   Meta key.
    282              * @param mixed  $meta_value Meta value.
    283              */
    284             do_action( 'updated_postmeta', $meta_id, $object_id, $meta_key, $meta_value );
    285         }
    286     }
    287 
    288     return true;
    289 }
    290 
    291 /**
    292  * Delete metadata for the specified object.
    293  *
    294  * @since 2.9.0
    295  *
    296  * @global wpdb $wpdb WordPress database abstraction object.
    297  *
    298  * @param string $meta_type  Type of object metadata is for (e.g., comment, post, or user)
    299  * @param int    $object_id  ID of the object metadata is for
    300  * @param string $meta_key   Metadata key
    301  * @param mixed  $meta_value Optional. Metadata value. Must be serializable if non-scalar. If specified, only delete
    302  *                           metadata entries with this value. Otherwise, delete all entries with the specified meta_key.
    303  *                           Pass `null, `false`, or an empty string to skip this check. (For backward compatibility,
    304  *                           it is not possible to pass an empty string to delete those entries with an empty string
    305  *                           for a value.)
    306  * @param bool   $delete_all Optional, default is false. If true, delete matching metadata entries for all objects,
    307  *                           ignoring the specified object_id. Otherwise, only delete matching metadata entries for
    308  *                           the specified object_id.
    309  * @return bool True on successful delete, false on failure.
    310  */
    311 function delete_metadata($meta_type, $object_id, $meta_key, $meta_value = '', $delete_all = false) {
    312     global $wpdb;
    313 
    314     if ( ! $meta_type || ! $meta_key || ! is_numeric( $object_id ) && ! $delete_all ) {
    315         return false;
    316     }
    317 
    318     $object_id = absint( $object_id );
    319     if ( ! $object_id && ! $delete_all ) {
    320         return false;
    321     }
    322 
    323     $table = _get_meta_table( $meta_type );
    324     if ( ! $table ) {
    325         return false;
    326     }
    327 
    328     $type_column = sanitize_key($meta_type . '_id');
    329     $id_column = 'user' == $meta_type ? 'umeta_id' : 'meta_id';
    330     // expected_slashed ($meta_key)
    331     $meta_key = wp_unslash($meta_key);
    332     $meta_value = wp_unslash($meta_value);
    333 
    334     /**
    335      * Filter whether to delete metadata of a specific type.
    336      *
    337      * The dynamic portion of the hook, `$meta_type`, refers to the meta
    338      * object type (comment, post, or user). Returning a non-null value
    339      * will effectively short-circuit the function.
    340      *
    341      * @since 3.1.0
    342      *
    343      * @param null|bool $delete     Whether to allow metadata deletion of the given type.
    344      * @param int       $object_id  Object ID.
    345      * @param string    $meta_key   Meta key.
    346      * @param mixed     $meta_value Meta value. Must be serializable if non-scalar.
    347      * @param bool      $delete_all Whether to delete the matching metadata entries
    348      *                              for all objects, ignoring the specified $object_id.
    349      *                              Default false.
    350      */
    351     $check = apply_filters( "delete_{$meta_type}_metadata", null, $object_id, $meta_key, $meta_value, $delete_all );
    352     if ( null !== $check )
    353         return (bool) $check;
    354 
    355     $_meta_value = $meta_value;
    356     $meta_value = maybe_serialize( $meta_value );
    357 
    358     $query = $wpdb->prepare( "SELECT $id_column FROM $table WHERE meta_key = %s", $meta_key );
    359 
    360     if ( !$delete_all )
    361         $query .= $wpdb->prepare(" AND $type_column = %d", $object_id );
    362 
    363     if ( '' !== $meta_value && null !== $meta_value && false !== $meta_value )
    364         $query .= $wpdb->prepare(" AND meta_value = %s", $meta_value );
    365 
    366     $meta_ids = $wpdb->get_col( $query );
    367     if ( !count( $meta_ids ) )
    368         return false;
    369 
    370     if ( $delete_all )
    371         $object_ids = $wpdb->get_col( $wpdb->prepare( "SELECT $type_column FROM $table WHERE meta_key = %s", $meta_key ) );
    372 
    373     /**
    374      * Fires immediately before deleting metadata of a specific type.
    375      *
    376      * The dynamic portion of the hook, `$meta_type`, refers to the meta
    377      * object type (comment, post, or user).
    378      *
    379      * @since 3.1.0
    380      *
    381      * @param array  $meta_ids   An array of metadata entry IDs to delete.
    382      * @param int    $object_id  Object ID.
    383      * @param string $meta_key   Meta key.
    384      * @param mixed  $meta_value Meta value.
    385      */
    386     do_action( "delete_{$meta_type}_meta", $meta_ids, $object_id, $meta_key, $_meta_value );
    387 
    388     // Old-style action.
    389     if ( 'post' == $meta_type ) {
    390         /**
    391          * Fires immediately before deleting metadata for a post.
    392          *
    393          * @since 2.9.0
    394          *
    395          * @param array $meta_ids An array of post metadata entry IDs to delete.
    396          */
    397         do_action( 'delete_postmeta', $meta_ids );
    398     }
    399 
    400     $query = "DELETE FROM $table WHERE $id_column IN( " . implode( ',', $meta_ids ) . " )";
    401 
    402     $count = $wpdb->query($query);
    403 
    404     if ( !$count )
    405         return false;
    406 
    407     if ( $delete_all ) {
    408         foreach ( (array) $object_ids as $o_id ) {
    409             wp_cache_delete($o_id, $meta_type . '_meta');
    410         }
    411     } else {
    412         wp_cache_delete($object_id, $meta_type . '_meta');
    413     }
    414 
    415     /**
    416      * Fires immediately after deleting metadata of a specific type.
    417      *
    418      * The dynamic portion of the hook name, `$meta_type`, refers to the meta
    419      * object type (comment, post, or user).
    420      *
    421      * @since 2.9.0
    422      *
    423      * @param array  $meta_ids   An array of deleted metadata entry IDs.
    424      * @param int    $object_id  Object ID.
    425      * @param string $meta_key   Meta key.
    426      * @param mixed  $meta_value Meta value.
    427      */
    428     do_action( "deleted_{$meta_type}_meta", $meta_ids, $object_id, $meta_key, $_meta_value );
    429 
    430     // Old-style action.
    431     if ( 'post' == $meta_type ) {
    432         /**
    433          * Fires immediately after deleting metadata for a post.
    434          *
    435          * @since 2.9.0
    436          *
    437          * @param array $meta_ids An array of deleted post metadata entry IDs.
    438          */
    439         do_action( 'deleted_postmeta', $meta_ids );
    440     }
    441 
    442     return true;
    443 }
    444 
    445 /**
    446  * Retrieve metadata for the specified object.
    447  *
    448  * @since 2.9.0
    449  *
    450  * @param string $meta_type Type of object metadata is for (e.g., comment, post, or user)
    451  * @param int    $object_id ID of the object metadata is for
    452  * @param string $meta_key  Optional. Metadata key. If not specified, retrieve all metadata for
    453  *                          the specified object.
    454  * @param bool   $single    Optional, default is false.
    455  *                          If true, return only the first value of the specified meta_key.
    456  *                          This parameter has no effect if meta_key is not specified.
    457  * @return mixed Single metadata value, or array of values
    458  */
    459 function get_metadata($meta_type, $object_id, $meta_key = '', $single = false) {
    460     if ( ! $meta_type || ! is_numeric( $object_id ) ) {
    461         return false;
    462     }
    463 
    464     $object_id = absint( $object_id );
    465     if ( ! $object_id ) {
    466         return false;
    467     }
    468 
    469     /**
    470      * Filter whether to retrieve metadata of a specific type.
    471      *
    472      * The dynamic portion of the hook, `$meta_type`, refers to the meta
    473      * object type (comment, post, or user). Returning a non-null value
    474      * will effectively short-circuit the function.
    475      *
    476      * @since 3.1.0
    477      *
    478      * @param null|array|string $value     The value get_metadata() should return - a single metadata value,
    479      *                                     or an array of values.
    480      * @param int               $object_id Object ID.
    481      * @param string            $meta_key  Meta key.
    482      * @param bool              $single    Whether to return only the first value of the specified $meta_key.
    483      */
    484     $check = apply_filters( "get_{$meta_type}_metadata", null, $object_id, $meta_key, $single );
    485     if ( null !== $check ) {
    486         if ( $single && is_array( $check ) )
    487             return $check[0];
    488         else
    489             return $check;
    490     }
    491 
    492     $meta_cache = wp_cache_get($object_id, $meta_type . '_meta');
    493 
    494     if ( !$meta_cache ) {
    495         $meta_cache = update_meta_cache( $meta_type, array( $object_id ) );
    496         $meta_cache = $meta_cache[$object_id];
    497     }
    498 
    499     if ( ! $meta_key ) {
    500         return $meta_cache;
    501     }
    502 
    503     if ( isset($meta_cache[$meta_key]) ) {
    504         if ( $single )
    505             return maybe_unserialize( $meta_cache[$meta_key][0] );
    506         else
    507             return array_map('maybe_unserialize', $meta_cache[$meta_key]);
    508     }
    509 
    510     if ($single)
    511         return '';
    512     else
    513         return array();
    514 }
    515 
    516 /**
    517  * Determine if a meta key is set for a given object
    518  *
    519  * @since 3.3.0
    520  *
    521  * @param string $meta_type Type of object metadata is for (e.g., comment, post, or user)
    522  * @param int    $object_id ID of the object metadata is for
    523  * @param string $meta_key  Metadata key.
    524  * @return bool True of the key is set, false if not.
    525  */
    526 function metadata_exists( $meta_type, $object_id, $meta_key ) {
    527     if ( ! $meta_type || ! is_numeric( $object_id ) ) {
    528         return false;
    529     }
    530 
    531     $object_id = absint( $object_id );
    532     if ( ! $object_id ) {
    533         return false;
    534     }
    535 
    536     /** This filter is documented in wp-includes/meta.php */
    537     $check = apply_filters( "get_{$meta_type}_metadata", null, $object_id, $meta_key, true );
    538     if ( null !== $check )
    539         return (bool) $check;
    540 
    541     $meta_cache = wp_cache_get( $object_id, $meta_type . '_meta' );
    542 
    543     if ( !$meta_cache ) {
    544         $meta_cache = update_meta_cache( $meta_type, array( $object_id ) );
    545         $meta_cache = $meta_cache[$object_id];
    546     }
    547 
    548     if ( isset( $meta_cache[ $meta_key ] ) )
    549         return true;
    550 
    551     return false;
    552 }
    553 
    554 /**
    555  * Get meta data by meta ID
    556  *
    557  * @since 3.3.0
    558  *
    559  * @global wpdb $wpdb
    560  *
    561  * @param string $meta_type Type of object metadata is for (e.g., comment, post, or user)
    562  * @param int    $meta_id   ID for a specific meta row
    563  * @return object|false Meta object or false.
    564  */
    565 function get_metadata_by_mid( $meta_type, $meta_id ) {
    566     global $wpdb;
    567 
    568     if ( ! $meta_type || ! is_numeric( $meta_id ) ) {
    569         return false;
    570     }
    571 
    572     $meta_id = absint( $meta_id );
    573     if ( ! $meta_id ) {
    574         return false;
    575     }
    576 
    577     $table = _get_meta_table( $meta_type );
    578     if ( ! $table ) {
    579         return false;
    580     }
    581 
    582     $id_column = ( 'user' == $meta_type ) ? 'umeta_id' : 'meta_id';
    583 
    584     $meta = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $table WHERE $id_column = %d", $meta_id ) );
    585 
    586     if ( empty( $meta ) )
    587         return false;
    588 
    589     if ( isset( $meta->meta_value ) )
    590         $meta->meta_value = maybe_unserialize( $meta->meta_value );
    591 
    592     return $meta;
    593 }
    594 
    595 /**
    596  * Update meta data by meta ID
    597  *
    598  * @since 3.3.0
    599  *
    600  * @global wpdb $wpdb
    601  *
    602  * @param string $meta_type  Type of object metadata is for (e.g., comment, post, or user)
    603  * @param int    $meta_id    ID for a specific meta row
    604  * @param string $meta_value Metadata value
    605  * @param string $meta_key   Optional, you can provide a meta key to update it
    606  * @return bool True on successful update, false on failure.
    607  */
    608 function update_metadata_by_mid( $meta_type, $meta_id, $meta_value, $meta_key = false ) {
    609     global $wpdb;
    610 
    611     // Make sure everything is valid.
    612     if ( ! $meta_type || ! is_numeric( $meta_id ) ) {
    613         return false;
    614     }
    615 
    616     $meta_id = absint( $meta_id );
    617     if ( ! $meta_id ) {
    618         return false;
    619     }
    620 
    621     $table = _get_meta_table( $meta_type );
    622     if ( ! $table ) {
    623         return false;
    624     }
    625 
    626     $column = sanitize_key($meta_type . '_id');
    627     $id_column = 'user' == $meta_type ? 'umeta_id' : 'meta_id';
    628 
    629     // Fetch the meta and go on if it's found.
    630     if ( $meta = get_metadata_by_mid( $meta_type, $meta_id ) ) {
    631         $original_key = $meta->meta_key;
    632         $object_id = $meta->{$column};
    633 
    634         // If a new meta_key (last parameter) was specified, change the meta key,
    635         // otherwise use the original key in the update statement.
    636         if ( false === $meta_key ) {
    637             $meta_key = $original_key;
    638         } elseif ( ! is_string( $meta_key ) ) {
    639             return false;
    640         }
    641 
    642         // Sanitize the meta
    643         $_meta_value = $meta_value;
    644         $meta_value = sanitize_meta( $meta_key, $meta_value, $meta_type );
    645         $meta_value = maybe_serialize( $meta_value );
    646 
    647         // Format the data query arguments.
    648         $data = array(
    649             'meta_key' => $meta_key,
    650             'meta_value' => $meta_value
    651         );
    652 
    653         // Format the where query arguments.
    654         $where = array();
    655         $where[$id_column] = $meta_id;
    656 
    657         /** This action is documented in wp-includes/meta.php */
    658         do_action( "update_{$meta_type}_meta", $meta_id, $object_id, $meta_key, $_meta_value );
    659 
    660         if ( 'post' == $meta_type ) {
    661             /** This action is documented in wp-includes/meta.php */
    662             do_action( 'update_postmeta', $meta_id, $object_id, $meta_key, $meta_value );
    663         }
    664 
    665         // Run the update query, all fields in $data are %s, $where is a %d.
    666         $result = $wpdb->update( $table, $data, $where, '%s', '%d' );
    667         if ( ! $result )
    668             return false;
    669 
    670         // Clear the caches.
    671         wp_cache_delete($object_id, $meta_type . '_meta');
    672 
    673         /** This action is documented in wp-includes/meta.php */
    674         do_action( "updated_{$meta_type}_meta", $meta_id, $object_id, $meta_key, $_meta_value );
    675 
    676         if ( 'post' == $meta_type ) {
    677             /** This action is documented in wp-includes/meta.php */
    678             do_action( 'updated_postmeta', $meta_id, $object_id, $meta_key, $meta_value );
    679         }
    680 
    681         return true;
    682     }
    683 
    684     // And if the meta was not found.
    685     return false;
    686 }
    687 
    688 /**
    689  * Delete meta data by meta ID
    690  *
    691  * @since 3.3.0
    692  *
    693  * @global wpdb $wpdb
    694  *
    695  * @param string $meta_type Type of object metadata is for (e.g., comment, post, or user)
    696  * @param int    $meta_id   ID for a specific meta row
    697  * @return bool True on successful delete, false on failure.
    698  */
    699 function delete_metadata_by_mid( $meta_type, $meta_id ) {
    700     global $wpdb;
    701 
    702     // Make sure everything is valid.
    703     if ( ! $meta_type || ! is_numeric( $meta_id ) ) {
    704         return false;
    705     }
    706 
    707     $meta_id = absint( $meta_id );
    708     if ( ! $meta_id ) {
    709         return false;
    710     }
    711 
    712     $table = _get_meta_table( $meta_type );
    713     if ( ! $table ) {
    714         return false;
    715     }
    716 
    717     // object and id columns
    718     $column = sanitize_key($meta_type . '_id');
    719     $id_column = 'user' == $meta_type ? 'umeta_id' : 'meta_id';
    720 
    721     // Fetch the meta and go on if it's found.
    722     if ( $meta = get_metadata_by_mid( $meta_type, $meta_id ) ) {
    723         $object_id = $meta->{$column};
    724 
    725         /** This action is documented in wp-includes/meta.php */
    726         do_action( "delete_{$meta_type}_meta", (array) $meta_id, $object_id, $meta->meta_key, $meta->meta_value );
    727 
    728         // Old-style action.
    729         if ( 'post' == $meta_type || 'comment' == $meta_type ) {
    730             /**
    731              * Fires immediately before deleting post or comment metadata of a specific type.
    732              *
    733              * The dynamic portion of the hook, `$meta_type`, refers to the meta
    734              * object type (post or comment).
    735              *
    736              * @since 3.4.0
    737              *
    738              * @param int $meta_id ID of the metadata entry to delete.
    739              */
    740             do_action( "delete_{$meta_type}meta", $meta_id );
    741         }
    742 
    743         // Run the query, will return true if deleted, false otherwise
    744         $result = (bool) $wpdb->delete( $table, array( $id_column => $meta_id ) );
    745 
    746         // Clear the caches.
    747         wp_cache_delete($object_id, $meta_type . '_meta');
    748 
    749         /** This action is documented in wp-includes/meta.php */
    750         do_action( "deleted_{$meta_type}_meta", (array) $meta_id, $object_id, $meta->meta_key, $meta->meta_value );
    751 
    752         // Old-style action.
    753         if ( 'post' == $meta_type || 'comment' == $meta_type ) {
    754             /**
    755              * Fires immediately after deleting post or comment metadata of a specific type.
    756              *
    757              * The dynamic portion of the hook, `$meta_type`, refers to the meta
    758              * object type (post or comment).
    759              *
    760              * @since 3.4.0
    761              *
    762              * @param int $meta_ids Deleted metadata entry ID.
    763              */
    764             do_action( "deleted_{$meta_type}meta", $meta_id );
    765         }
    766 
    767         return $result;
    768 
    769     }
    770 
    771     // Meta id was not found.
    772     return false;
    773 }
    774 
    775 /**
    776  * Update the metadata cache for the specified objects.
    777  *
    778  * @since 2.9.0
    779  *
    780  * @global wpdb $wpdb WordPress database abstraction object.
    781  *
    782  * @param string    $meta_type  Type of object metadata is for (e.g., comment, post, or user)
    783  * @param int|array $object_ids Array or comma delimited list of object IDs to update cache for
    784  * @return array|false Metadata cache for the specified objects, or false on failure.
    785  */
    786 function update_meta_cache($meta_type, $object_ids) {
    787     global $wpdb;
    788 
    789     if ( ! $meta_type || ! $object_ids ) {
    790         return false;
    791     }
    792 
    793     $table = _get_meta_table( $meta_type );
    794     if ( ! $table ) {
    795         return false;
    796     }
    797 
    798     $column = sanitize_key($meta_type . '_id');
    799 
    800     if ( !is_array($object_ids) ) {
    801         $object_ids = preg_replace('|[^0-9,]|', '', $object_ids);
    802         $object_ids = explode(',', $object_ids);
    803     }
    804 
    805     $object_ids = array_map('intval', $object_ids);
    806 
    807     $cache_key = $meta_type . '_meta';
    808     $ids = array();
    809     $cache = array();
    810     foreach ( $object_ids as $id ) {
    811         $cached_object = wp_cache_get( $id, $cache_key );
    812         if ( false === $cached_object )
    813             $ids[] = $id;
    814         else
    815             $cache[$id] = $cached_object;
    816     }
    817 
    818     if ( empty( $ids ) )
    819         return $cache;
    820 
    821     // Get meta info
    822     $id_list = join( ',', $ids );
    823     $id_column = 'user' == $meta_type ? 'umeta_id' : 'meta_id';
    824     $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 );
    825 
    826     if ( !empty($meta_list) ) {
    827         foreach ( $meta_list as $metarow) {
    828             $mpid = intval($metarow[$column]);
    829             $mkey = $metarow['meta_key'];
    830             $mval = $metarow['meta_value'];
    831 
    832             // Force subkeys to be array type:
    833             if ( !isset($cache[$mpid]) || !is_array($cache[$mpid]) )
    834                 $cache[$mpid] = array();
    835             if ( !isset($cache[$mpid][$mkey]) || !is_array($cache[$mpid][$mkey]) )
    836                 $cache[$mpid][$mkey] = array();
    837 
    838             // Add a value to the current pid/key:
    839             $cache[$mpid][$mkey][] = $mval;
    840         }
    841     }
    842 
    843     foreach ( $ids as $id ) {
    844         if ( ! isset($cache[$id]) )
    845             $cache[$id] = array();
    846         wp_cache_add( $id, $cache[$id], $cache_key );
    847     }
    848 
    849     return $cache;
    850 }
    851 
    852 /**
    853  * Given a meta query, generates SQL clauses to be appended to a main query.
    854  *
    855  * @since 3.2.0
    856  *
    857  * @see WP_Meta_Query
    858  *
    859  * @param array $meta_query         A meta query.
    860  * @param string $type              Type of meta.
    861  * @param string $primary_table     Primary database table name.
    862  * @param string $primary_id_column Primary ID column name.
    863  * @param object $context           Optional. The main query object
    864  * @return array Associative array of `JOIN` and `WHERE` SQL.
    865  */
    866 function get_meta_sql( $meta_query, $type, $primary_table, $primary_id_column, $context = null ) {
    867     $meta_query_obj = new WP_Meta_Query( $meta_query );
    868     return $meta_query_obj->get_sql( $type, $primary_table, $primary_id_column, $context );
    869 }
    870 
    871 /**
    872  * Class for generating SQL clauses that filter a primary query according to metadata keys and values.
    873  *
    874  * `WP_Meta_Query` is a helper that allows primary query classes, such as {@see WP_Query} and {@see WP_User_Query},
    875  * to filter their results by object metadata, by generating `JOIN` and `WHERE` subclauses to be attached
    876  * to the primary SQL query string.
    877  *
    878  * @since 3.2.0
    879  */
    880 class WP_Meta_Query {
    881     /**
    882      * Array of metadata queries.
    883      *
    884      * See {@see WP_Meta_Query::__construct()} for information on meta query arguments.
    885      *
    886      * @since 3.2.0
    887      * @access public
    888      * @var array
    889      */
    890     public $queries = array();
    891 
    892     /**
    893      * The relation between the queries. Can be one of 'AND' or 'OR'.
    894      *
    895      * @since 3.2.0
    896      * @access public
    897      * @var string
    898      */
    899     public $relation;
    900 
    901     /**
    902      * Database table to query for the metadata.
    903      *
    904      * @since 4.1.0
    905      * @access public
    906      * @var string
    907      */
    908     public $meta_table;
    909 
    910     /**
    911      * Column in meta_table that represents the ID of the object the metadata belongs to.
    912      *
    913      * @since 4.1.0
    914      * @access public
    915      * @var string
    916      */
    917     public $meta_id_column;
    918 
    919     /**
    920      * Database table that where the metadata's objects are stored (eg $wpdb->users).
    921      *
    922      * @since 4.1.0
    923      * @access public
    924      * @var string
    925      */
    926     public $primary_table;
    927 
    928     /**
    929      * Column in primary_table that represents the ID of the object.
    930      *
    931      * @since 4.1.0
    932      * @access public
    933      * @var string
    934      */
    935     public $primary_id_column;
    936 
    937     /**
    938      * A flat list of table aliases used in JOIN clauses.
    939      *
    940      * @since 4.1.0
    941      * @access protected
    942      * @var array
    943      */
    944     protected $table_aliases = array();
    945 
    946     /**
    947      * A flat list of clauses, keyed by clause 'name'.
    948      *
    949      * @since 4.2.0
    950      * @access protected
    951      * @var array
    952      */
    953     protected $clauses = array();
    954 
    955     /**
    956      * Whether the query contains any OR relations.
    957      *
    958      * @since 4.3.0
    959      * @access protected
    960      * @var bool
    961      */
    962     protected $has_or_relation = false;
    963 
    964     /**
    965      * Constructor.
    966      *
    967      * @since 3.2.0
    968      * @since 4.2.0 Introduced support for naming query clauses by associative array keys.
    969      *
    970      * @access public
    971      *
    972      * @param array $meta_query {
    973      *     Array of meta query clauses. When first-order clauses use strings as their array keys, they may be
    974      *     referenced in the 'orderby' parameter of the parent query.
    975      *
    976      *     @type string $relation Optional. The MySQL keyword used to join
    977      *                            the clauses of the query. Accepts 'AND', or 'OR'. Default 'AND'.
    978      *     @type array {
    979      *         Optional. An array of first-order clause parameters, or another fully-formed meta query.
    980      *
    981      *         @type string $key     Meta key to filter by.
    982      *         @type string $value   Meta value to filter by.
    983      *         @type string $compare MySQL operator used for comparing the $value. Accepts '=',
    984      *                               '!=', '>', '>=', '<', '<=', 'LIKE', 'NOT LIKE', 'IN', 'NOT IN',
    985      *                               'BETWEEN', 'NOT BETWEEN', 'REGEXP', 'NOT REGEXP', or 'RLIKE'.
    986      *                               Default is 'IN' when `$value` is an array, '=' otherwise.
    987      *         @type string $type    MySQL data type that the meta_value column will be CAST to for
    988      *                               comparisons. Accepts 'NUMERIC', 'BINARY', 'CHAR', 'DATE',
    989      *                               'DATETIME', 'DECIMAL', 'SIGNED', 'TIME', or 'UNSIGNED'.
    990      *                               Default is 'CHAR'.
    991      *     }
    992      * }
    993      */
    994     public function __construct( $meta_query = false ) {
    995         if ( !$meta_query )
    996             return;
    997 
    998         if ( isset( $meta_query['relation'] ) && strtoupper( $meta_query['relation'] ) == 'OR' ) {
    999             $this->relation = 'OR';
    1000         } else {
    1001             $this->relation = 'AND';
    1002         }
    1003 
    1004         $this->queries = $this->sanitize_query( $meta_query );
    1005     }
    1006 
    1007     /**
    1008      * Ensure the 'meta_query' argument passed to the class constructor is well-formed.
    1009      *
    1010      * Eliminates empty items and ensures that a 'relation' is set.
    1011      *
    1012      * @since 4.1.0
    1013      * @access public
    1014      *
    1015      * @param array $queries Array of query clauses.
    1016      * @return array Sanitized array of query clauses.
    1017      */
    1018     public function sanitize_query( $queries ) {
    1019         $clean_queries = array();
    1020 
    1021         if ( ! is_array( $queries ) ) {
    1022             return $clean_queries;
    1023         }
    1024 
    1025         foreach ( $queries as $key => $query ) {
    1026             if ( 'relation' === $key ) {
    1027                 $relation = $query;
    1028 
    1029             } elseif ( ! is_array( $query ) ) {
    1030                 continue;
    1031 
    1032             // First-order clause.
    1033             } elseif ( $this->is_first_order_clause( $query ) ) {
    1034                 if ( isset( $query['value'] ) && array() === $query['value'] ) {
    1035                     unset( $query['value'] );
    1036                 }
    1037 
    1038                 $clean_queries[ $key ] = $query;
    1039 
    1040             // Otherwise, it's a nested query, so we recurse.
    1041             } else {
    1042                 $cleaned_query = $this->sanitize_query( $query );
    1043 
    1044                 if ( ! empty( $cleaned_query ) ) {
    1045                     $clean_queries[ $key ] = $cleaned_query;
    1046                 }
    1047             }
    1048         }
    1049 
    1050         if ( empty( $clean_queries ) ) {
    1051             return $clean_queries;
    1052         }
    1053 
    1054         // Sanitize the 'relation' key provided in the query.
    1055         if ( isset( $relation ) && 'OR' === strtoupper( $relation ) ) {
    1056             $clean_queries['relation'] = 'OR';
    1057             $this->has_or_relation = true;
    1058 
    1059         /*
    1060          * If there is only a single clause, call the relation 'OR'.
    1061          * This value will not actually be used to join clauses, but it
    1062          * simplifies the logic around combining key-only queries.
    1063          */
    1064         } elseif ( 1 === count( $clean_queries ) ) {
    1065             $clean_queries['relation'] = 'OR';
    1066 
    1067         // Default to AND.
    1068         } else {
    1069             $clean_queries['relation'] = 'AND';
    1070         }
    1071 
    1072         return $clean_queries;
    1073     }
    1074 
    1075     /**
    1076      * Determine whether a query clause is first-order.
    1077      *
    1078      * A first-order meta query clause is one that has either a 'key' or
    1079      * a 'value' array key.
    1080      *
    1081      * @since 4.1.0
    1082      * @access protected
    1083      *
    1084      * @param array $query Meta query arguments.
    1085      * @return bool Whether the query clause is a first-order clause.
    1086      */
    1087     protected function is_first_order_clause( $query ) {
    1088         return isset( $query['key'] ) || isset( $query['value'] );
    1089     }
    1090 
    1091     /**
    1092      * Constructs a meta query based on 'meta_*' query vars
    1093      *
    1094      * @since 3.2.0
    1095      * @access public
    1096      *
    1097      * @param array $qv The query variables
    1098      */
    1099     public function parse_query_vars( $qv ) {
    1100         $meta_query = array();
    1101 
    1102         /*
    1103          * For orderby=meta_value to work correctly, simple query needs to be
    1104          * first (so that its table join is against an unaliased meta table) and
    1105          * needs to be its own clause (so it doesn't interfere with the logic of
    1106          * the rest of the meta_query).
    1107          */
    1108         $primary_meta_query = array();
    1109         foreach ( array( 'key', 'compare', 'type' ) as $key ) {
    1110             if ( ! empty( $qv[ "meta_$key" ] ) ) {
    1111                 $primary_meta_query[ $key ] = $qv[ "meta_$key" ];
    1112             }
    1113         }
    1114 
    1115         // WP_Query sets 'meta_value' = '' by default.
    1116         if ( isset( $qv['meta_value'] ) && '' !== $qv['meta_value'] && ( ! is_array( $qv['meta_value'] ) || $qv['meta_value'] ) ) {
    1117             $primary_meta_query['value'] = $qv['meta_value'];
    1118         }
    1119 
    1120         $existing_meta_query = isset( $qv['meta_query'] ) && is_array( $qv['meta_query'] ) ? $qv['meta_query'] : array();
    1121 
    1122         if ( ! empty( $primary_meta_query ) && ! empty( $existing_meta_query ) ) {
    1123             $meta_query = array(
    1124                 'relation' => 'AND',
    1125                 $primary_meta_query,
    1126                 $existing_meta_query,
    1127             );
    1128         } elseif ( ! empty( $primary_meta_query ) ) {
    1129             $meta_query = array(
    1130                 $primary_meta_query,
    1131             );
    1132         } elseif ( ! empty( $existing_meta_query ) ) {
    1133             $meta_query = $existing_meta_query;
    1134         }
    1135 
    1136         $this->__construct( $meta_query );
    1137     }
    1138 
    1139     /**
    1140      * Return the appropriate alias for the given meta type if applicable.
    1141      *
    1142      * @since 3.7.0
    1143      * @access public
    1144      *
    1145      * @param string $type MySQL type to cast meta_value.
    1146      * @return string MySQL type.
    1147      */
    1148     public function get_cast_for_type( $type = '' ) {
    1149         if ( empty( $type ) )
    1150             return 'CHAR';
    1151 
    1152         $meta_type = strtoupper( $type );
    1153 
    1154         if ( ! preg_match( '/^(?:BINARY|CHAR|DATE|DATETIME|SIGNED|UNSIGNED|TIME|NUMERIC(?:\(\d+(?:,\s?\d+)?\))?|DECIMAL(?:\(\d+(?:,\s?\d+)?\))?)$/', $meta_type ) )
    1155             return 'CHAR';
    1156 
    1157         if ( 'NUMERIC' == $meta_type )
    1158             $meta_type = 'SIGNED';
    1159 
    1160         return $meta_type;
    1161     }
    1162 
    1163     /**
    1164      * Generates SQL clauses to be appended to a main query.
    1165      *
    1166      * @since 3.2.0
    1167      * @access public
    1168      *
    1169      * @param string $type              Type of meta, eg 'user', 'post'.
    1170      * @param string $primary_table     Database table where the object being filtered is stored (eg wp_users).
    1171      * @param string $primary_id_column ID column for the filtered object in $primary_table.
    1172      * @param object $context           Optional. The main query object.
    1173      * @return false|array {
    1174      *     Array containing JOIN and WHERE SQL clauses to append to the main query.
    1175      *
    1176      *     @type string $join  SQL fragment to append to the main JOIN clause.
    1177      *     @type string $where SQL fragment to append to the main WHERE clause.
    1178      * }
    1179      */
    1180     public function get_sql( $type, $primary_table, $primary_id_column, $context = null ) {
    1181         if ( ! $meta_table = _get_meta_table( $type ) ) {
    1182             return false;
    1183         }
    1184 
    1185         $this->meta_table     = $meta_table;
    1186         $this->meta_id_column = sanitize_key( $type . '_id' );
    1187 
    1188         $this->primary_table     = $primary_table;
    1189         $this->primary_id_column = $primary_id_column;
    1190 
    1191         $sql = $this->get_sql_clauses();
    1192 
    1193         /*
    1194          * If any JOINs are LEFT JOINs (as in the case of NOT EXISTS), then all JOINs should
    1195          * be LEFT. Otherwise posts with no metadata will be excluded from results.
    1196          */
    1197         if ( false !== strpos( $sql['join'], 'LEFT JOIN' ) ) {
    1198             $sql['join'] = str_replace( 'INNER JOIN', 'LEFT JOIN', $sql['join'] );
    1199         }
    1200 
    1201         /**
    1202          * Filter the meta query's generated SQL.
    1203          *
    1204          * @since 3.1.0
    1205          *
    1206          * @param array $args {
    1207          *     An array of meta query SQL arguments.
    1208          *
    1209          *     @type array  $clauses           Array containing the query's JOIN and WHERE clauses.
    1210          *     @type array  $queries           Array of meta queries.
    1211          *     @type string $type              Type of meta.
    1212          *     @type string $primary_table     Primary table.
    1213          *     @type string $primary_id_column Primary column ID.
    1214          *     @type object $context           The main query object.
    1215          * }
    1216          */
    1217         return apply_filters_ref_array( 'get_meta_sql', array( $sql, $this->queries, $type, $primary_table, $primary_id_column, $context ) );
    1218     }
    1219 
    1220     /**
    1221      * Generate SQL clauses to be appended to a main query.
    1222      *
    1223      * Called by the public {@see WP_Meta_Query::get_sql()}, this method
    1224      * is abstracted out to maintain parity with the other Query classes.
    1225      *
    1226      * @since 4.1.0
    1227      * @access protected
    1228      *
    1229      * @return array {
    1230      *     Array containing JOIN and WHERE SQL clauses to append to the main query.
    1231      *
    1232      *     @type string $join  SQL fragment to append to the main JOIN clause.
    1233      *     @type string $where SQL fragment to append to the main WHERE clause.
    1234      * }
    1235      */
    1236     protected function get_sql_clauses() {
    1237         /*
    1238          * $queries are passed by reference to get_sql_for_query() for recursion.
    1239          * To keep $this->queries unaltered, pass a copy.
    1240          */
    1241         $queries = $this->queries;
    1242         $sql = $this->get_sql_for_query( $queries );
    1243 
    1244         if ( ! empty( $sql['where'] ) ) {
    1245             $sql['where'] = ' AND ' . $sql['where'];
    1246         }
    1247 
    1248         return $sql;
    1249     }
    1250 
    1251     /**
    1252      * Generate SQL clauses for a single query array.
    1253      *
    1254      * If nested subqueries are found, this method recurses the tree to
    1255      * produce the properly nested SQL.
    1256      *
    1257      * @since 4.1.0
    1258      * @access protected
    1259      *
    1260      * @param array $query Query to parse, passed by reference.
    1261      * @param int   $depth Optional. Number of tree levels deep we currently are.
    1262      *                     Used to calculate indentation. Default 0.
    1263      * @return array {
    1264      *     Array containing JOIN and WHERE SQL clauses to append to a single query array.
    1265      *
    1266      *     @type string $join  SQL fragment to append to the main JOIN clause.
    1267      *     @type string $where SQL fragment to append to the main WHERE clause.
    1268      * }
    1269      */
    1270     protected function get_sql_for_query( &$query, $depth = 0 ) {
    1271         $sql_chunks = array(
    1272             'join'  => array(),
    1273             'where' => array(),
    1274         );
    1275 
    1276         $sql = array(
    1277             'join'  => '',
    1278             'where' => '',
    1279         );
    1280 
    1281         $indent = '';
    1282         for ( $i = 0; $i < $depth; $i++ ) {
    1283             $indent .= "  ";
    1284         }
    1285 
    1286         foreach ( $query as $key => &$clause ) {
    1287             if ( 'relation' === $key ) {
    1288                 $relation = $query['relation'];
    1289             } elseif ( is_array( $clause ) ) {
    1290 
    1291                 // This is a first-order clause.
    1292                 if ( $this->is_first_order_clause( $clause ) ) {
    1293                     $clause_sql = $this->get_sql_for_clause( $clause, $query, $key );
    1294 
    1295                     $where_count = count( $clause_sql['where'] );
    1296                     if ( ! $where_count ) {
    1297                         $sql_chunks['where'][] = '';
    1298                     } elseif ( 1 === $where_count ) {
    1299                         $sql_chunks['where'][] = $clause_sql['where'][0];
    1300                     } else {
    1301                         $sql_chunks['where'][] = '( ' . implode( ' AND ', $clause_sql['where'] ) . ' )';
    1302                     }
    1303 
    1304                     $sql_chunks['join'] = array_merge( $sql_chunks['join'], $clause_sql['join'] );
    1305                 // This is a subquery, so we recurse.
    1306                 } else {
    1307                     $clause_sql = $this->get_sql_for_query( $clause, $depth + 1 );
    1308 
    1309                     $sql_chunks['where'][] = $clause_sql['where'];
    1310                     $sql_chunks['join'][]  = $clause_sql['join'];
    1311                 }
    1312             }
    1313         }
    1314 
    1315         // Filter to remove empties.
    1316         $sql_chunks['join']  = array_filter( $sql_chunks['join'] );
    1317         $sql_chunks['where'] = array_filter( $sql_chunks['where'] );
    1318 
    1319         if ( empty( $relation ) ) {
    1320             $relation = 'AND';
    1321         }
    1322 
    1323         // Filter duplicate JOIN clauses and combine into a single string.
    1324         if ( ! empty( $sql_chunks['join'] ) ) {
    1325             $sql['join'] = implode( ' ', array_unique( $sql_chunks['join'] ) );
    1326         }
    1327 
    1328         // Generate a single WHERE clause with proper brackets and indentation.
    1329         if ( ! empty( $sql_chunks['where'] ) ) {
    1330             $sql['where'] = '( ' . "\n  " . $indent . implode( ' ' . "\n  " . $indent . $relation . ' ' . "\n  " . $indent, $sql_chunks['where'] ) . "\n" . $indent . ')';
    1331         }
    1332 
    1333         return $sql;
    1334     }
    1335 
    1336     /**
    1337      * Generate SQL JOIN and WHERE clauses for a first-order query clause.
    1338      *
    1339      * "First-order" means that it's an array with a 'key' or 'value'.
    1340      *
    1341      * @since 4.1.0
    1342      * @access public
    1343      *
    1344      * @global wpdb $wpdb
    1345      *
    1346      * @param array  $clause       Query clause, passed by reference.
    1347      * @param array  $parent_query Parent query array.
    1348      * @param string $clause_key   Optional. The array key used to name the clause in the original `$meta_query`
    1349      *                             parameters. If not provided, a key will be generated automatically.
    1350      * @return array {
    1351      *     Array containing JOIN and WHERE SQL clauses to append to a first-order query.
    1352      *
    1353      *     @type string $join  SQL fragment to append to the main JOIN clause.
    1354      *     @type string $where SQL fragment to append to the main WHERE clause.
    1355      * }
    1356      */
    1357     public function get_sql_for_clause( &$clause, $parent_query, $clause_key = '' ) {
    1358         global $wpdb;
    1359 
    1360         $sql_chunks = array(
    1361             'where' => array(),
    1362             'join' => array(),
    1363         );
    1364 
    1365         if ( isset( $clause['compare'] ) ) {
    1366             $clause['compare'] = strtoupper( $clause['compare'] );
    1367         } else {
    1368             $clause['compare'] = isset( $clause['value'] ) && is_array( $clause['value'] ) ? 'IN' : '=';
    1369         }
    1370 
    1371         if ( ! in_array( $clause['compare'], array(
    1372             '=', '!=', '>', '>=', '<', '<=',
    1373             'LIKE', 'NOT LIKE',
    1374             'IN', 'NOT IN',
    1375             'BETWEEN', 'NOT BETWEEN',
    1376             'EXISTS', 'NOT EXISTS',
    1377             'REGEXP', 'NOT REGEXP', 'RLIKE'
    1378         ) ) ) {
    1379             $clause['compare'] = '=';
    1380         }
    1381 
    1382         $meta_compare = $clause['compare'];
    1383 
    1384         // First build the JOIN clause, if one is required.
    1385         $join = '';
    1386 
    1387         // We prefer to avoid joins if possible. Look for an existing join compatible with this clause.
    1388         $alias = $this->find_compatible_table_alias( $clause, $parent_query );
    1389         if ( false === $alias ) {
    1390             $i = count( $this->table_aliases );
    1391             $alias = $i ? 'mt' . $i : $this->meta_table;
    1392 
    1393             // JOIN clauses for NOT EXISTS have their own syntax.
    1394             if ( 'NOT EXISTS' === $meta_compare ) {
    1395                 $join .= " LEFT JOIN $this->meta_table";
    1396                 $join .= $i ? " AS $alias" : '';
    1397                 $join .= $wpdb->prepare( " ON ($this->primary_table.$this->primary_id_column = $alias.$this->meta_id_column AND $alias.meta_key = %s )", $clause['key'] );
    1398 
    1399             // All other JOIN clauses.
    1400             } else {
    1401                 $join .= " INNER JOIN $this->meta_table";
    1402                 $join .= $i ? " AS $alias" : '';
    1403                 $join .= " ON ( $this->primary_table.$this->primary_id_column = $alias.$this->meta_id_column )";
    1404             }
    1405 
    1406             $this->table_aliases[] = $alias;
    1407             $sql_chunks['join'][] = $join;
    1408         }
    1409 
    1410         // Save the alias to this clause, for future siblings to find.
    1411         $clause['alias'] = $alias;
    1412 
    1413         // Determine the data type.
    1414         $_meta_type = isset( $clause['type'] ) ? $clause['type'] : '';
    1415         $meta_type  = $this->get_cast_for_type( $_meta_type );
    1416         $clause['cast'] = $meta_type;
    1417 
    1418         // Fallback for clause keys is the table alias.
    1419         if ( ! $clause_key ) {
    1420             $clause_key = $clause['alias'];
    1421         }
    1422 
    1423         // Ensure unique clause keys, so none are overwritten.
    1424         $iterator = 1;
    1425         $clause_key_base = $clause_key;
    1426         while ( isset( $this->clauses[ $clause_key ] ) ) {
    1427             $clause_key = $clause_key_base . '-' . $iterator;
    1428             $iterator++;
    1429         }
    1430 
    1431         // Store the clause in our flat array.
    1432         $this->clauses[ $clause_key ] =& $clause;
    1433 
    1434         // Next, build the WHERE clause.
    1435 
    1436         // meta_key.
    1437         if ( array_key_exists( 'key', $clause ) ) {
    1438             if ( 'NOT EXISTS' === $meta_compare ) {
    1439                 $sql_chunks['where'][] = $alias . '.' . $this->meta_id_column . ' IS NULL';
    1440             } else {
    1441                 $sql_chunks['where'][] = $wpdb->prepare( "$alias.meta_key = %s", trim( $clause['key'] ) );
    1442             }
    1443         }
    1444 
    1445         // meta_value.
    1446         if ( array_key_exists( 'value', $clause ) ) {
    1447             $meta_value = $clause['value'];
    1448 
    1449             if ( in_array( $meta_compare, array( 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN' ) ) ) {
    1450                 if ( ! is_array( $meta_value ) ) {
    1451                     $meta_value = preg_split( '/[,\s]+/', $meta_value );
    1452                 }
    1453             } else {
    1454                 $meta_value = trim( $meta_value );
    1455             }
    1456 
    1457             switch ( $meta_compare ) {
    1458                 case 'IN' :
    1459                 case 'NOT IN' :
    1460                     $meta_compare_string = '(' . substr( str_repeat( ',%s', count( $meta_value ) ), 1 ) . ')';
    1461                     $where = $wpdb->prepare( $meta_compare_string, $meta_value );
    1462                     break;
    1463 
    1464                 case 'BETWEEN' :
    1465                 case 'NOT BETWEEN' :
    1466                     $meta_value = array_slice( $meta_value, 0, 2 );
    1467                     $where = $wpdb->prepare( '%s AND %s', $meta_value );
    1468                     break;
    1469 
    1470                 case 'LIKE' :
    1471                 case 'NOT LIKE' :
    1472                     $meta_value = '%' . $wpdb->esc_like( $meta_value ) . '%';
    1473                     $where = $wpdb->prepare( '%s', $meta_value );
    1474                     break;
    1475 
    1476                 // EXISTS with a value is interpreted as '='.
    1477                 case 'EXISTS' :
    1478                     $meta_compare = '=';
    1479                     $where = $wpdb->prepare( '%s', $meta_value );
    1480                     break;
    1481 
    1482                 // 'value' is ignored for NOT EXISTS.
    1483                 case 'NOT EXISTS' :
    1484                     $where = '';
    1485                     break;
    1486 
    1487                 default :
    1488                     $where = $wpdb->prepare( '%s', $meta_value );
    1489                     break;
    1490 
    1491             }
    1492 
    1493             if ( $where ) {
    1494                 $sql_chunks['where'][] = "CAST($alias.meta_value AS {$meta_type}) {$meta_compare} {$where}";
    1495             }
    1496         }
    1497 
    1498         /*
    1499          * Multiple WHERE clauses (for meta_key and meta_value) should
    1500          * be joined in parentheses.
    1501          */
    1502         if ( 1 < count( $sql_chunks['where'] ) ) {
    1503             $sql_chunks['where'] = array( '( ' . implode( ' AND ', $sql_chunks['where'] ) . ' )' );
    1504         }
    1505 
    1506         return $sql_chunks;
    1507     }
    1508 
    1509     /**
    1510      * Get a flattened list of sanitized meta clauses.
    1511      *
    1512      * This array should be used for clause lookup, as when the table alias and CAST type must be determined for
    1513      * a value of 'orderby' corresponding to a meta clause.
    1514      *
    1515      * @since 4.2.0
    1516      * @access public
    1517      *
    1518      * @return array Meta clauses.
    1519      */
    1520     public function get_clauses() {
    1521         return $this->clauses;
    1522     }
    1523 
    1524     /**
    1525      * Identify an existing table alias that is compatible with the current
    1526      * query clause.
    1527      *
    1528      * We avoid unnecessary table joins by allowing each clause to look for
    1529      * an existing table alias that is compatible with the query that it
    1530      * needs to perform.
    1531      *
    1532      * An existing alias is compatible if (a) it is a sibling of `$clause`
    1533      * (ie, it's under the scope of the same relation), and (b) the combination
    1534      * of operator and relation between the clauses allows for a shared table join.
    1535      * In the case of {@see WP_Meta_Query}, this only applies to 'IN' clauses that
    1536      * are connected by the relation 'OR'.
    1537      *
    1538      * @since 4.1.0
    1539      * @access protected
    1540      *
    1541      * @param  array       $clause       Query clause.
    1542      * @param  array       $parent_query Parent query of $clause.
    1543      * @return string|bool Table alias if found, otherwise false.
    1544      */
    1545     protected function find_compatible_table_alias( $clause, $parent_query ) {
    1546         $alias = false;
    1547 
    1548         foreach ( $parent_query as $sibling ) {
    1549             // If the sibling has no alias yet, there's nothing to check.
    1550             if ( empty( $sibling['alias'] ) ) {
    1551                 continue;
    1552             }
    1553 
    1554             // We're only interested in siblings that are first-order clauses.
    1555             if ( ! is_array( $sibling ) || ! $this->is_first_order_clause( $sibling ) ) {
    1556                 continue;
    1557             }
    1558 
    1559             $compatible_compares = array();
    1560 
    1561             // Clauses connected by OR can share joins as long as they have "positive" operators.
    1562             if ( 'OR' === $parent_query['relation'] ) {
    1563                 $compatible_compares = array( '=', 'IN', 'BETWEEN', 'LIKE', 'REGEXP', 'RLIKE', '>', '>=', '<', '<=' );
    1564 
    1565             // Clauses joined by AND with "negative" operators share a join only if they also share a key.
    1566             } elseif ( isset( $sibling['key'] ) && isset( $clause['key'] ) && $sibling['key'] === $clause['key'] ) {
    1567                 $compatible_compares = array( '!=', 'NOT IN', 'NOT LIKE' );
    1568             }
    1569 
    1570             $clause_compare  = strtoupper( $clause['compare'] );
    1571             $sibling_compare = strtoupper( $sibling['compare'] );
    1572             if ( in_array( $clause_compare, $compatible_compares ) && in_array( $sibling_compare, $compatible_compares ) ) {
    1573                 $alias = $sibling['alias'];
    1574                 break;
    1575             }
    1576         }
    1577 
    1578         /**
    1579          * Filter the table alias identified as compatible with the current clause.
    1580          *
    1581          * @since 4.1.0
    1582          *
    1583          * @param string|bool $alias        Table alias, or false if none was found.
    1584          * @param array       $clause       First-order query clause.
    1585          * @param array       $parent_query Parent of $clause.
    1586          * @param object      $this         WP_Meta_Query object.
    1587          */
    1588         return apply_filters( 'meta_query_find_compatible_table_alias', $alias, $clause, $parent_query, $this ) ;
    1589     }
    1590 
    1591     /**
    1592      * Checks whether the current query has any OR relations.
    1593      *
    1594      * In some cases, the presence of an OR relation somewhere in the query will require
    1595      * the use of a `DISTINCT` or `GROUP BY` keyword in the `SELECT` clause. The current
    1596      * method can be used in these cases to determine whether such a clause is necessary.
    1597      *
    1598      * @since 4.3.0
    1599      *
    1600      * @return bool True if the query contains any `OR` relations, otherwise false.
    1601      */
    1602     public function has_or_relation() {
    1603         return $this->has_or_relation;
    1604     }
    1605 }
    1606 
    1607 /**
    1608  * Retrieve the name of the metadata table for the specified object type.
    1609  *
    1610  * @since 2.9.0
    1611  *
    1612  * @global wpdb $wpdb WordPress database abstraction object.
    1613  *
    1614  * @param string $type Type of object to get metadata table for (e.g., comment, post, or user)
    1615  * @return string|false Metadata table name, or false if no metadata table exists
    1616  */
    1617 function _get_meta_table($type) {
    1618     global $wpdb;
    1619 
    1620     $table_name = $type . 'meta';
    1621 
    1622     if ( empty($wpdb->$table_name) )
    1623         return false;
    1624 
    1625     return $wpdb->$table_name;
    1626 }
    1627 
    1628 /**
    1629  * Determine whether a meta key is protected.
    1630  *
    1631  * @since 3.1.3
    1632  *
    1633  * @param string      $meta_key Meta key
    1634  * @param string|null $meta_type
    1635  * @return bool True if the key is protected, false otherwise.
    1636  */
    1637 function is_protected_meta( $meta_key, $meta_type = null ) {
    1638     $protected = ( '_' == $meta_key[0] );
    1639 
    1640     /**
    1641      * Filter whether a meta key is protected.
    1642      *
    1643      * @since 3.2.0
    1644      *
    1645      * @param bool   $protected Whether the key is protected. Default false.
    1646      * @param string $meta_key  Meta key.
    1647      * @param string $meta_type Meta type.
    1648      */
    1649     return apply_filters( 'is_protected_meta', $protected, $meta_key, $meta_type );
    1650 }
    1651 
    1652 /**
    1653  * Sanitize meta value.
    1654  *
    1655  * @since 3.1.3
    1656  *
    1657  * @param string $meta_key   Meta key
    1658  * @param mixed  $meta_value Meta value to sanitize
    1659  * @param string $meta_type  Type of meta
    1660  * @return mixed Sanitized $meta_value
    1661  */
    1662 function sanitize_meta( $meta_key, $meta_value, $meta_type ) {
    1663 
    1664     /**
    1665      * Filter the sanitization of a specific meta key of a specific meta type.
    1666      *
    1667      * The dynamic portions of the hook name, `$meta_type`, and `$meta_key`,
    1668      * refer to the metadata object type (comment, post, or user) and the meta
    1669      * key value,
    1670      * respectively.
    1671      *
    1672      * @since 3.3.0
    1673      *
    1674      * @param mixed  $meta_value Meta value to sanitize.
    1675      * @param string $meta_key   Meta key.
    1676      * @param string $meta_type  Meta type.
    1677      */
    1678     return apply_filters( "sanitize_{$meta_type}_meta_{$meta_key}", $meta_value, $meta_key, $meta_type );
    1679 }
    1680 
    1681 /**
    1682  * Register meta key
    1683  *
    1684  * @since 3.3.0
    1685  *
    1686  * @param string       $meta_type         Type of meta
    1687  * @param string       $meta_key          Meta key
    1688  * @param string|array $sanitize_callback A function or method to call when sanitizing the value of $meta_key.
    1689  * @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.
    1690  */
    1691 function register_meta( $meta_type, $meta_key, $sanitize_callback, $auth_callback = null ) {
    1692     if ( is_callable( $sanitize_callback ) )
    1693         add_filter( "sanitize_{$meta_type}_meta_{$meta_key}", $sanitize_callback, 10, 3 );
    1694 
    1695     if ( empty( $auth_callback ) ) {
    1696         if ( is_protected_meta( $meta_key, $meta_type ) )
    1697             $auth_callback = '__return_false';
    1698         else
    1699             $auth_callback = '__return_true';
    1700     }
    1701 
    1702     if ( is_callable( $auth_callback ) )
    1703         add_filter( "auth_{$meta_type}_meta_{$meta_key}", $auth_callback, 10, 6 );
    1704 }
     14require_once( ABSPATH . WPINC . '/meta-functions.php' );
     15require_once( ABSPATH . WPINC . '/class-wp-meta-query.php' );
Note: See TracChangeset for help on using the changeset viewer.