/wp-includes/meta.php

https://github.com/netconstructor/WordPress · PHP · 861 lines · 426 code · 172 blank · 263 comment · 130 complexity · 740147efbbcbeec0101a042930cccebf MD5 · raw file

  1. <?php
  2. /**
  3. * Metadata API
  4. *
  5. * Functions for retrieving and manipulating metadata of various WordPress object types. Metadata
  6. * for an object is a represented by a simple key-value pair. Objects may contain multiple
  7. * metadata entries that share the same key and differ only in their value.
  8. *
  9. * @package WordPress
  10. * @subpackage Meta
  11. * @since 2.9.0
  12. */
  13. /**
  14. * Add metadata for the specified object.
  15. *
  16. * @since 2.9.0
  17. * @uses $wpdb WordPress database object for queries.
  18. * @uses do_action() Calls 'added_{$meta_type}_meta' with meta_id of added metadata entry,
  19. * object ID, meta key, and meta value
  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 string $meta_value Metadata value
  25. * @param bool $unique Optional, default is false. Whether the specified metadata key should be
  26. * unique for the object. If true, and the object already has a value for the specified
  27. * metadata key, no change will be made
  28. * @return bool The meta ID on successful update, false on failure.
  29. */
  30. function add_metadata($meta_type, $object_id, $meta_key, $meta_value, $unique = false) {
  31. if ( !$meta_type || !$meta_key )
  32. return false;
  33. if ( !$object_id = absint($object_id) )
  34. return false;
  35. if ( ! $table = _get_meta_table($meta_type) )
  36. return false;
  37. global $wpdb;
  38. $column = esc_sql($meta_type . '_id');
  39. // expected_slashed ($meta_key)
  40. $meta_key = stripslashes($meta_key);
  41. $meta_value = stripslashes_deep($meta_value);
  42. $meta_value = sanitize_meta( $meta_key, $meta_value, $meta_type );
  43. $check = apply_filters( "add_{$meta_type}_metadata", null, $object_id, $meta_key, $meta_value, $unique );
  44. if ( null !== $check )
  45. return $check;
  46. if ( $unique && $wpdb->get_var( $wpdb->prepare(
  47. "SELECT COUNT(*) FROM $table WHERE meta_key = %s AND $column = %d",
  48. $meta_key, $object_id ) ) )
  49. return false;
  50. $_meta_value = $meta_value;
  51. $meta_value = maybe_serialize( $meta_value );
  52. do_action( "add_{$meta_type}_meta", $object_id, $meta_key, $_meta_value );
  53. $result = $wpdb->insert( $table, array(
  54. $column => $object_id,
  55. 'meta_key' => $meta_key,
  56. 'meta_value' => $meta_value
  57. ) );
  58. if ( ! $result )
  59. return false;
  60. $mid = (int) $wpdb->insert_id;
  61. wp_cache_delete($object_id, $meta_type . '_meta');
  62. do_action( "added_{$meta_type}_meta", $mid, $object_id, $meta_key, $_meta_value );
  63. return $mid;
  64. }
  65. /**
  66. * Update metadata for the specified object. If no value already exists for the specified object
  67. * ID and metadata key, the metadata will be added.
  68. *
  69. * @since 2.9.0
  70. * @uses $wpdb WordPress database object for queries.
  71. * @uses do_action() Calls 'update_{$meta_type}_meta' before updating metadata with meta_id of
  72. * metadata entry to update, object ID, meta key, and meta value
  73. * @uses do_action() Calls 'updated_{$meta_type}_meta' after updating metadata with meta_id of
  74. * updated metadata entry, object ID, meta key, and meta value
  75. *
  76. * @param string $meta_type Type of object metadata is for (e.g., comment, post, or user)
  77. * @param int $object_id ID of the object metadata is for
  78. * @param string $meta_key Metadata key
  79. * @param string $meta_value Metadata value
  80. * @param string $prev_value Optional. If specified, only update existing metadata entries with
  81. * the specified value. Otherwise, update all entries.
  82. * @return bool True on successful update, false on failure.
  83. */
  84. function update_metadata($meta_type, $object_id, $meta_key, $meta_value, $prev_value = '') {
  85. if ( !$meta_type || !$meta_key )
  86. return false;
  87. if ( !$object_id = absint($object_id) )
  88. return false;
  89. if ( ! $table = _get_meta_table($meta_type) )
  90. return false;
  91. global $wpdb;
  92. $column = esc_sql($meta_type . '_id');
  93. $id_column = 'user' == $meta_type ? 'umeta_id' : 'meta_id';
  94. // expected_slashed ($meta_key)
  95. $meta_key = stripslashes($meta_key);
  96. $meta_value = stripslashes_deep($meta_value);
  97. $meta_value = sanitize_meta( $meta_key, $meta_value, $meta_type );
  98. $check = apply_filters( "update_{$meta_type}_metadata", null, $object_id, $meta_key, $meta_value, $prev_value );
  99. if ( null !== $check )
  100. return (bool) $check;
  101. if ( ! $meta_id = $wpdb->get_var( $wpdb->prepare( "SELECT $id_column FROM $table WHERE meta_key = %s AND $column = %d", $meta_key, $object_id ) ) )
  102. return add_metadata($meta_type, $object_id, $meta_key, $meta_value);
  103. // Compare existing value to new value if no prev value given and the key exists only once.
  104. if ( empty($prev_value) ) {
  105. $old_value = get_metadata($meta_type, $object_id, $meta_key);
  106. if ( count($old_value) == 1 ) {
  107. if ( $old_value[0] === $meta_value )
  108. return false;
  109. }
  110. }
  111. $_meta_value = $meta_value;
  112. $meta_value = maybe_serialize( $meta_value );
  113. $data = compact( 'meta_value' );
  114. $where = array( $column => $object_id, 'meta_key' => $meta_key );
  115. if ( !empty( $prev_value ) ) {
  116. $prev_value = maybe_serialize($prev_value);
  117. $where['meta_value'] = $prev_value;
  118. }
  119. do_action( "update_{$meta_type}_meta", $meta_id, $object_id, $meta_key, $_meta_value );
  120. if ( 'post' == $meta_type )
  121. do_action( 'update_postmeta', $meta_id, $object_id, $meta_key, $meta_value );
  122. $wpdb->update( $table, $data, $where );
  123. wp_cache_delete($object_id, $meta_type . '_meta');
  124. do_action( "updated_{$meta_type}_meta", $meta_id, $object_id, $meta_key, $_meta_value );
  125. if ( 'post' == $meta_type )
  126. do_action( 'updated_postmeta', $meta_id, $object_id, $meta_key, $meta_value );
  127. return true;
  128. }
  129. /**
  130. * Delete metadata for the specified object.
  131. *
  132. * @since 2.9.0
  133. * @uses $wpdb WordPress database object for queries.
  134. * @uses do_action() Calls 'deleted_{$meta_type}_meta' after deleting with meta_id of
  135. * deleted metadata entries, object ID, meta key, and meta value
  136. *
  137. * @param string $meta_type Type of object metadata is for (e.g., comment, post, or user)
  138. * @param int $object_id ID of the object metadata is for
  139. * @param string $meta_key Metadata key
  140. * @param string $meta_value Optional. Metadata value. If specified, only delete metadata entries
  141. * with this value. Otherwise, delete all entries with the specified meta_key.
  142. * @param bool $delete_all Optional, default is false. If true, delete matching metadata entries
  143. * for all objects, ignoring the specified object_id. Otherwise, only delete matching
  144. * metadata entries for the specified object_id.
  145. * @return bool True on successful delete, false on failure.
  146. */
  147. function delete_metadata($meta_type, $object_id, $meta_key, $meta_value = '', $delete_all = false) {
  148. if ( !$meta_type || !$meta_key )
  149. return false;
  150. if ( (!$object_id = absint($object_id)) && !$delete_all )
  151. return false;
  152. if ( ! $table = _get_meta_table($meta_type) )
  153. return false;
  154. global $wpdb;
  155. $type_column = esc_sql($meta_type . '_id');
  156. $id_column = 'user' == $meta_type ? 'umeta_id' : 'meta_id';
  157. // expected_slashed ($meta_key)
  158. $meta_key = stripslashes($meta_key);
  159. $meta_value = stripslashes_deep($meta_value);
  160. $check = apply_filters( "delete_{$meta_type}_metadata", null, $object_id, $meta_key, $meta_value, $delete_all );
  161. if ( null !== $check )
  162. return (bool) $check;
  163. $_meta_value = $meta_value;
  164. $meta_value = maybe_serialize( $meta_value );
  165. $query = $wpdb->prepare( "SELECT $id_column FROM $table WHERE meta_key = %s", $meta_key );
  166. if ( !$delete_all )
  167. $query .= $wpdb->prepare(" AND $type_column = %d", $object_id );
  168. if ( $meta_value )
  169. $query .= $wpdb->prepare(" AND meta_value = %s", $meta_value );
  170. $meta_ids = $wpdb->get_col( $query );
  171. if ( !count( $meta_ids ) )
  172. return false;
  173. if ( $delete_all )
  174. $object_ids = $wpdb->get_col( $wpdb->prepare( "SELECT $type_column FROM $table WHERE meta_key = %s", $meta_key ) );
  175. do_action( "delete_{$meta_type}_meta", $meta_ids, $object_id, $meta_key, $_meta_value );
  176. if ( 'post' == $meta_type )
  177. do_action( 'delete_postmeta', $meta_ids );
  178. $query = "DELETE FROM $table WHERE $id_column IN( " . implode( ',', $meta_ids ) . " )";
  179. $count = $wpdb->query($query);
  180. if ( !$count )
  181. return false;
  182. if ( $delete_all ) {
  183. foreach ( (array) $object_ids as $o_id ) {
  184. wp_cache_delete($o_id, $meta_type . '_meta');
  185. }
  186. } else {
  187. wp_cache_delete($object_id, $meta_type . '_meta');
  188. }
  189. do_action( "deleted_{$meta_type}_meta", $meta_ids, $object_id, $meta_key, $_meta_value );
  190. if ( 'post' == $meta_type )
  191. do_action( 'deleted_postmeta', $meta_ids );
  192. return true;
  193. }
  194. /**
  195. * Retrieve metadata for the specified object.
  196. *
  197. * @since 2.9.0
  198. *
  199. * @param string $meta_type Type of object metadata is for (e.g., comment, post, or user)
  200. * @param int $object_id ID of the object metadata is for
  201. * @param string $meta_key Optional. Metadata key. If not specified, retrieve all metadata for
  202. * the specified object.
  203. * @param bool $single Optional, default is false. If true, return only the first value of the
  204. * specified meta_key. This parameter has no effect if meta_key is not specified.
  205. * @return string|array Single metadata value, or array of values
  206. */
  207. function get_metadata($meta_type, $object_id, $meta_key = '', $single = false) {
  208. if ( !$meta_type )
  209. return false;
  210. if ( !$object_id = absint($object_id) )
  211. return false;
  212. $check = apply_filters( "get_{$meta_type}_metadata", null, $object_id, $meta_key, $single );
  213. if ( null !== $check ) {
  214. if ( $single && is_array( $check ) )
  215. return $check[0];
  216. else
  217. return $check;
  218. }
  219. $meta_cache = wp_cache_get($object_id, $meta_type . '_meta');
  220. if ( !$meta_cache ) {
  221. $meta_cache = update_meta_cache( $meta_type, array( $object_id ) );
  222. $meta_cache = $meta_cache[$object_id];
  223. }
  224. if ( !$meta_key )
  225. return $meta_cache;
  226. if ( isset($meta_cache[$meta_key]) ) {
  227. if ( $single )
  228. return maybe_unserialize( $meta_cache[$meta_key][0] );
  229. else
  230. return array_map('maybe_unserialize', $meta_cache[$meta_key]);
  231. }
  232. if ($single)
  233. return '';
  234. else
  235. return array();
  236. }
  237. /**
  238. * Determine if a meta key is set for a given object
  239. *
  240. * @since 3.3.0
  241. *
  242. * @param string $meta_type Type of object metadata is for (e.g., comment, post, or user)
  243. * @param int $object_id ID of the object metadata is for
  244. * @param string $meta_key Metadata key.
  245. * @return boolean true of the key is set, false if not.
  246. */
  247. function metadata_exists( $meta_type, $object_id, $meta_key ) {
  248. if ( ! $meta_type )
  249. return false;
  250. if ( ! $object_id = absint( $object_id ) )
  251. return false;
  252. $check = apply_filters( "get_{$meta_type}_metadata", null, $object_id, $meta_key, true );
  253. if ( null !== $check )
  254. return true;
  255. $meta_cache = wp_cache_get( $object_id, $meta_type . '_meta' );
  256. if ( !$meta_cache ) {
  257. $meta_cache = update_meta_cache( $meta_type, array( $object_id ) );
  258. $meta_cache = $meta_cache[$object_id];
  259. }
  260. if ( isset( $meta_cache[ $meta_key ] ) )
  261. return true;
  262. return false;
  263. }
  264. /**
  265. * Get meta data by meta ID
  266. *
  267. * @since 3.3.0
  268. *
  269. * @param string $meta_type Type of object metadata is for (e.g., comment, post, or user)
  270. * @param int $meta_id ID for a specific meta row
  271. * @return object Meta object or false.
  272. */
  273. function get_metadata_by_mid( $meta_type, $meta_id ) {
  274. global $wpdb;
  275. if ( ! $meta_type )
  276. return false;
  277. if ( !$meta_id = absint( $meta_id ) )
  278. return false;
  279. if ( ! $table = _get_meta_table($meta_type) )
  280. return false;
  281. $id_column = ( 'user' == $meta_type ) ? 'umeta_id' : 'meta_id';
  282. $meta = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $table WHERE $id_column = %d", $meta_id ) );
  283. if ( empty( $meta ) )
  284. return false;
  285. if ( isset( $meta->meta_value ) )
  286. $meta->meta_value = maybe_unserialize( $meta->meta_value );
  287. return $meta;
  288. }
  289. /**
  290. * Update meta data by meta ID
  291. *
  292. * @since 3.3.0
  293. *
  294. * @uses get_metadata_by_mid() Calls get_metadata_by_mid() to fetch the meta key, value
  295. * and object_id of the given meta_id.
  296. *
  297. * @param string $meta_type Type of object metadata is for (e.g., comment, post, or user)
  298. * @param int $meta_id ID for a specific meta row
  299. * @param string $meta_value Metadata value
  300. * @param string $meta_key Optional, you can provide a meta key to update it
  301. * @return bool True on successful update, false on failure.
  302. */
  303. function update_metadata_by_mid( $meta_type, $meta_id, $meta_value, $meta_key = false ) {
  304. global $wpdb;
  305. // Make sure everything is valid.
  306. if ( ! $meta_type )
  307. return false;
  308. if ( ! $meta_id = absint( $meta_id ) )
  309. return false;
  310. if ( ! $table = _get_meta_table( $meta_type ) )
  311. return false;
  312. $column = esc_sql($meta_type . '_id');
  313. $id_column = 'user' == $meta_type ? 'umeta_id' : 'meta_id';
  314. // Fetch the meta and go on if it's found.
  315. if ( $meta = get_metadata_by_mid( $meta_type, $meta_id ) ) {
  316. $original_key = $meta->meta_key;
  317. $original_value = $meta->meta_value;
  318. $object_id = $meta->{$column};
  319. // If a new meta_key (last parameter) was specified, change the meta key,
  320. // otherwise use the original key in the update statement.
  321. if ( false === $meta_key ) {
  322. $meta_key = $original_key;
  323. } elseif ( ! is_string( $meta_key ) ) {
  324. return false;
  325. }
  326. // Sanitize the meta
  327. $_meta_value = $meta_value;
  328. $meta_value = sanitize_meta( $meta_key, $meta_value, $meta_type );
  329. $meta_value = maybe_serialize( $meta_value );
  330. // Format the data query arguments.
  331. $data = array(
  332. 'meta_key' => $meta_key,
  333. 'meta_value' => $meta_value
  334. );
  335. // Format the where query arguments.
  336. $where = array();
  337. $where[$id_column] = $meta_id;
  338. do_action( "update_{$meta_type}_meta", $meta_id, $object_id, $meta_key, $_meta_value );
  339. if ( 'post' == $meta_type )
  340. do_action( 'update_postmeta', $meta_id, $object_id, $meta_key, $meta_value );
  341. // Run the update query, all fields in $data are %s, $where is a %d.
  342. $result = (bool) $wpdb->update( $table, $data, $where, '%s', '%d' );
  343. // Clear the caches.
  344. wp_cache_delete($object_id, $meta_type . '_meta');
  345. do_action( "updated_{$meta_type}_meta", $meta_id, $object_id, $meta_key, $_meta_value );
  346. if ( 'post' == $meta_type )
  347. do_action( 'updated_postmeta', $meta_id, $object_id, $meta_key, $meta_value );
  348. return $result;
  349. }
  350. // And if the meta was not found.
  351. return false;
  352. }
  353. /**
  354. * Delete meta data by meta ID
  355. *
  356. * @since 3.3.0
  357. *
  358. * @uses get_metadata_by_mid() Calls get_metadata_by_mid() to fetch the meta key, value
  359. * and object_id of the given meta_id.
  360. *
  361. * @param string $meta_type Type of object metadata is for (e.g., comment, post, or user)
  362. * @param int $meta_id ID for a specific meta row
  363. * @return bool True on successful delete, false on failure.
  364. */
  365. function delete_metadata_by_mid( $meta_type, $meta_id ) {
  366. global $wpdb;
  367. // Make sure everything is valid.
  368. if ( ! $meta_type )
  369. return false;
  370. if ( ! $meta_id = absint( $meta_id ) )
  371. return false;
  372. if ( ! $table = _get_meta_table( $meta_type ) )
  373. return false;
  374. // object and id columns
  375. $column = esc_sql($meta_type . '_id');
  376. $id_column = 'user' == $meta_type ? 'umeta_id' : 'meta_id';
  377. // Fetch the meta and go on if it's found.
  378. if ( $meta = get_metadata_by_mid( $meta_type, $meta_id ) ) {
  379. $object_id = $meta->{$column};
  380. do_action( "delete_{$meta_type}_meta", (array) $meta_id, $object_id, $meta->meta_key, $meta->meta_value );
  381. if ( 'post' == $meta_type )
  382. do_action( 'delete_postmeta', $object_id );
  383. // Run the query, will return true if deleted, false otherwise
  384. $result = (bool) $wpdb->query( $wpdb->prepare( "DELETE FROM $table WHERE $id_column = %d LIMIT 1;", $meta_id ) );
  385. // Clear the caches.
  386. wp_cache_delete($object_id, $meta_type . '_meta');
  387. do_action( "deleted_{$meta_type}_meta", (array) $meta_id, $object_id, $meta->meta_key, $meta->meta_value );
  388. if ( 'post' == $meta_type )
  389. do_action( 'delete_postmeta', $object_id );
  390. return $result;
  391. }
  392. // Meta id was not found.
  393. return false;
  394. }
  395. /**
  396. * Update the metadata cache for the specified objects.
  397. *
  398. * @since 2.9.0
  399. * @uses $wpdb WordPress database object for queries.
  400. *
  401. * @param string $meta_type Type of object metadata is for (e.g., comment, post, or user)
  402. * @param int|array $object_ids array or comma delimited list of object IDs to update cache for
  403. * @return mixed Metadata cache for the specified objects, or false on failure.
  404. */
  405. function update_meta_cache($meta_type, $object_ids) {
  406. if ( empty( $meta_type ) || empty( $object_ids ) )
  407. return false;
  408. if ( ! $table = _get_meta_table($meta_type) )
  409. return false;
  410. $column = esc_sql($meta_type . '_id');
  411. global $wpdb;
  412. if ( !is_array($object_ids) ) {
  413. $object_ids = preg_replace('|[^0-9,]|', '', $object_ids);
  414. $object_ids = explode(',', $object_ids);
  415. }
  416. $object_ids = array_map('intval', $object_ids);
  417. $cache_key = $meta_type . '_meta';
  418. $ids = array();
  419. $cache = array();
  420. foreach ( $object_ids as $id ) {
  421. $cached_object = wp_cache_get( $id, $cache_key );
  422. if ( false === $cached_object )
  423. $ids[] = $id;
  424. else
  425. $cache[$id] = $cached_object;
  426. }
  427. if ( empty( $ids ) )
  428. return $cache;
  429. // Get meta info
  430. $id_list = join(',', $ids);
  431. $meta_list = $wpdb->get_results( $wpdb->prepare("SELECT $column, meta_key, meta_value FROM $table WHERE $column IN ($id_list)",
  432. $meta_type), ARRAY_A );
  433. if ( !empty($meta_list) ) {
  434. foreach ( $meta_list as $metarow) {
  435. $mpid = intval($metarow[$column]);
  436. $mkey = $metarow['meta_key'];
  437. $mval = $metarow['meta_value'];
  438. // Force subkeys to be array type:
  439. if ( !isset($cache[$mpid]) || !is_array($cache[$mpid]) )
  440. $cache[$mpid] = array();
  441. if ( !isset($cache[$mpid][$mkey]) || !is_array($cache[$mpid][$mkey]) )
  442. $cache[$mpid][$mkey] = array();
  443. // Add a value to the current pid/key:
  444. $cache[$mpid][$mkey][] = $mval;
  445. }
  446. }
  447. foreach ( $ids as $id ) {
  448. if ( ! isset($cache[$id]) )
  449. $cache[$id] = array();
  450. wp_cache_add( $id, $cache[$id], $cache_key );
  451. }
  452. return $cache;
  453. }
  454. /**
  455. * Given a meta query, generates SQL clauses to be appended to a main query
  456. *
  457. * @since 3.2.0
  458. *
  459. * @see WP_Meta_Query
  460. *
  461. * @param array (optional) $meta_query A meta query
  462. * @param string $type Type of meta
  463. * @param string $primary_table
  464. * @param string $primary_id_column
  465. * @param object $context (optional) The main query object
  466. * @return array( 'join' => $join_sql, 'where' => $where_sql )
  467. */
  468. function get_meta_sql( $meta_query = false, $type, $primary_table, $primary_id_column, $context = null ) {
  469. $meta_query_obj = new WP_Meta_Query( $meta_query );
  470. return $meta_query_obj->get_sql( $type, $primary_table, $primary_id_column, $context );
  471. }
  472. /**
  473. * Container class for a multiple metadata query
  474. *
  475. * @since 3.2.0
  476. */
  477. class WP_Meta_Query {
  478. /**
  479. * List of metadata queries. A single query is an associative array:
  480. * - 'key' string The meta key
  481. * - 'value' string|array The meta value
  482. * - 'compare' (optional) string How to compare the key to the value.
  483. * Possible values: '=', '!=', '>', '>=', '<', '<=', 'LIKE', 'NOT LIKE', 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN'.
  484. * Default: '='
  485. * - 'type' string (optional) The type of the value.
  486. * Possible values: 'NUMERIC', 'BINARY', 'CHAR', 'DATE', 'DATETIME', 'DECIMAL', 'SIGNED', 'TIME', 'UNSIGNED'.
  487. * Default: 'CHAR'
  488. *
  489. * @since 3.2.0
  490. * @access public
  491. * @var array
  492. */
  493. public $queries = array();
  494. /**
  495. * The relation between the queries. Can be one of 'AND' or 'OR'.
  496. *
  497. * @since 3.2.0
  498. * @access public
  499. * @var string
  500. */
  501. public $relation;
  502. /**
  503. * Constructor
  504. *
  505. * @param array (optional) $meta_query A meta query
  506. */
  507. function __construct( $meta_query = false ) {
  508. if ( !$meta_query )
  509. return;
  510. if ( isset( $meta_query['relation'] ) && strtoupper( $meta_query['relation'] ) == 'OR' ) {
  511. $this->relation = 'OR';
  512. } else {
  513. $this->relation = 'AND';
  514. }
  515. $this->queries = array();
  516. foreach ( $meta_query as $key => $query ) {
  517. if ( ! is_array( $query ) )
  518. continue;
  519. $this->queries[] = $query;
  520. }
  521. }
  522. /**
  523. * Constructs a meta query based on 'meta_*' query vars
  524. *
  525. * @since 3.2.0
  526. * @access public
  527. *
  528. * @param array $qv The query variables
  529. */
  530. function parse_query_vars( $qv ) {
  531. $meta_query = array();
  532. // Simple query needs to be first for orderby=meta_value to work correctly
  533. foreach ( array( 'key', 'compare', 'type' ) as $key ) {
  534. if ( !empty( $qv[ "meta_$key" ] ) )
  535. $meta_query[0][ $key ] = $qv[ "meta_$key" ];
  536. }
  537. // WP_Query sets 'meta_value' = '' by default
  538. if ( isset( $qv[ 'meta_value' ] ) && '' !== $qv[ 'meta_value' ] )
  539. $meta_query[0]['value'] = $qv[ 'meta_value' ];
  540. if ( !empty( $qv['meta_query'] ) && is_array( $qv['meta_query'] ) ) {
  541. $meta_query = array_merge( $meta_query, $qv['meta_query'] );
  542. }
  543. $this->__construct( $meta_query );
  544. }
  545. /**
  546. * Generates SQL clauses to be appended to a main query.
  547. *
  548. * @since 3.2.0
  549. * @access public
  550. *
  551. * @param string $type Type of meta
  552. * @param string $primary_table
  553. * @param string $primary_id_column
  554. * @param object $context (optional) The main query object
  555. * @return array( 'join' => $join_sql, 'where' => $where_sql )
  556. */
  557. function get_sql( $type, $primary_table, $primary_id_column, $context = null ) {
  558. global $wpdb;
  559. if ( ! $meta_table = _get_meta_table( $type ) )
  560. return false;
  561. $meta_id_column = esc_sql( $type . '_id' );
  562. $join = array();
  563. $where = array();
  564. foreach ( $this->queries as $k => $q ) {
  565. $meta_key = isset( $q['key'] ) ? trim( $q['key'] ) : '';
  566. $meta_compare = isset( $q['compare'] ) ? strtoupper( $q['compare'] ) : '=';
  567. $meta_type = isset( $q['type'] ) ? strtoupper( $q['type'] ) : 'CHAR';
  568. if ( ! in_array( $meta_compare, array( '=', '!=', '>', '>=', '<', '<=', 'LIKE', 'NOT LIKE', 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN' ) ) )
  569. $meta_compare = '=';
  570. if ( 'NUMERIC' == $meta_type )
  571. $meta_type = 'SIGNED';
  572. elseif ( ! in_array( $meta_type, array( 'BINARY', 'CHAR', 'DATE', 'DATETIME', 'DECIMAL', 'SIGNED', 'TIME', 'UNSIGNED' ) ) )
  573. $meta_type = 'CHAR';
  574. $i = count( $join );
  575. $alias = $i ? 'mt' . $i : $meta_table;
  576. // Set JOIN
  577. $join[$i] = "INNER JOIN $meta_table";
  578. $join[$i] .= $i ? " AS $alias" : '';
  579. $join[$i] .= " ON ($primary_table.$primary_id_column = $alias.$meta_id_column)";
  580. $where[$k] = '';
  581. if ( !empty( $meta_key ) )
  582. $where[$k] = $wpdb->prepare( "$alias.meta_key = %s", $meta_key );
  583. if ( !isset( $q['value'] ) ) {
  584. if ( empty( $where[$k] ) )
  585. unset( $join[$i] );
  586. continue;
  587. }
  588. $meta_value = $q['value'];
  589. if ( in_array( $meta_compare, array( 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN' ) ) ) {
  590. if ( ! is_array( $meta_value ) )
  591. $meta_value = preg_split( '/[,\s]+/', $meta_value );
  592. if ( empty( $meta_value ) ) {
  593. unset( $join[$i] );
  594. continue;
  595. }
  596. } else {
  597. $meta_value = trim( $meta_value );
  598. }
  599. if ( 'IN' == substr( $meta_compare, -2) ) {
  600. $meta_compare_string = '(' . substr( str_repeat( ',%s', count( $meta_value ) ), 1 ) . ')';
  601. } elseif ( 'BETWEEN' == substr( $meta_compare, -7) ) {
  602. $meta_value = array_slice( $meta_value, 0, 2 );
  603. $meta_compare_string = '%s AND %s';
  604. } elseif ( 'LIKE' == substr( $meta_compare, -4 ) ) {
  605. $meta_value = '%' . like_escape( $meta_value ) . '%';
  606. $meta_compare_string = '%s';
  607. } else {
  608. $meta_compare_string = '%s';
  609. }
  610. if ( ! empty( $where[$k] ) )
  611. $where[$k] .= ' AND ';
  612. $where[$k] = ' (' . $where[$k] . $wpdb->prepare( "CAST($alias.meta_value AS {$meta_type}) {$meta_compare} {$meta_compare_string})", $meta_value );
  613. }
  614. $where = array_filter( $where );
  615. if ( empty( $where ) )
  616. $where = '';
  617. else
  618. $where = ' AND (' . implode( "\n{$this->relation} ", $where ) . ' )';
  619. $join = implode( "\n", $join );
  620. if ( ! empty( $join ) )
  621. $join = ' ' . $join;
  622. return apply_filters_ref_array( 'get_meta_sql', array( compact( 'join', 'where' ), $this->queries, $type, $primary_table, $primary_id_column, $context ) );
  623. }
  624. }
  625. /**
  626. * Retrieve the name of the metadata table for the specified object type.
  627. *
  628. * @since 2.9.0
  629. * @uses $wpdb WordPress database object for queries.
  630. *
  631. * @param string $type Type of object to get metadata table for (e.g., comment, post, or user)
  632. * @return mixed Metadata table name, or false if no metadata table exists
  633. */
  634. function _get_meta_table($type) {
  635. global $wpdb;
  636. $table_name = $type . 'meta';
  637. if ( empty($wpdb->$table_name) )
  638. return false;
  639. return $wpdb->$table_name;
  640. }
  641. /**
  642. * Determine whether a meta key is protected
  643. *
  644. * @since 3.1.3
  645. *
  646. * @param string $meta_key Meta key
  647. * @return bool True if the key is protected, false otherwise.
  648. */
  649. function is_protected_meta( $meta_key, $meta_type = null ) {
  650. $protected = ( '_' == $meta_key[0] );
  651. return apply_filters( 'is_protected_meta', $protected, $meta_key, $meta_type );
  652. }
  653. /**
  654. * Sanitize meta value
  655. *
  656. * @since 3.1.3
  657. *
  658. * @param string $meta_key Meta key
  659. * @param mixed $meta_value Meta value to sanitize
  660. * @param string $meta_type Type of meta
  661. * @return mixed Sanitized $meta_value
  662. */
  663. function sanitize_meta( $meta_key, $meta_value, $meta_type ) {
  664. return apply_filters( "sanitize_{$meta_type}_meta_{$meta_key}", $meta_value, $meta_key, $meta_type );
  665. }
  666. /**
  667. * Register meta key
  668. *
  669. * @since 3.3.0
  670. *
  671. * @param string $meta_type Type of meta
  672. * @param string $meta_key Meta key
  673. * @param string|array $sanitize_callback A function or method to call when sanitizing the value of $meta_key.
  674. * @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.
  675. * @param array $args Arguments
  676. */
  677. function register_meta( $meta_type, $meta_key, $sanitize_callback, $auth_callback = null ) {
  678. if ( is_callable( $sanitize_callback ) )
  679. add_filter( "sanitize_{$meta_type}_meta_{$meta_key}", $sanitize_callback, 10, 3 );
  680. if ( empty( $auth_callback ) ) {
  681. if ( is_protected_meta( $meta_key, $meta_type ) )
  682. $auth_callback = '__return_false';
  683. else
  684. $auth_callback = '__return_true';
  685. }
  686. if ( is_callable( $auth_callback ) )
  687. add_filter( "auth_{$meta_type}_meta_{$meta_key}", $auth_callback, 10, 6 );
  688. }
  689. ?>