PageRenderTime 27ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/wp-includes/meta.php

https://github.com/muskmelon/Greemo
PHP | 610 lines | 304 code | 112 blank | 194 comment | 90 complexity | 6c348770e604335a30969613b09090f3 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 True 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 (bool) $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. $wpdb->insert( $table, array(
  54. $column => $object_id,
  55. 'meta_key' => $meta_key,
  56. 'meta_value' => $meta_value
  57. ) );
  58. wp_cache_delete($object_id, $meta_type . '_meta');
  59. // users cache stores usermeta that must be cleared.
  60. if ( 'user' == $meta_type )
  61. clean_user_cache($object_id);
  62. do_action( "added_{$meta_type}_meta", $wpdb->insert_id, $object_id, $meta_key, $_meta_value );
  63. return true;
  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. $wpdb->update( $table, $data, $where );
  121. wp_cache_delete($object_id, $meta_type . '_meta');
  122. // users cache stores usermeta that must be cleared.
  123. if ( 'user' == $meta_type )
  124. clean_user_cache($object_id);
  125. do_action( "updated_{$meta_type}_meta", $meta_id, $object_id, $meta_key, $_meta_value );
  126. return true;
  127. }
  128. /**
  129. * Delete metadata for the specified object.
  130. *
  131. * @since 2.9.0
  132. * @uses $wpdb WordPress database object for queries.
  133. * @uses do_action() Calls 'deleted_{$meta_type}_meta' after deleting with meta_id of
  134. * deleted metadata entries, object ID, meta key, and meta value
  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 string $meta_value Optional. Metadata value. If specified, only delete metadata entries
  140. * with this value. Otherwise, delete all entries with the specified meta_key.
  141. * @param bool $delete_all Optional, default is false. If true, delete matching metadata entries
  142. * for all objects, ignoring the specified object_id. Otherwise, only delete matching
  143. * metadata entries for the specified object_id.
  144. * @return bool True on successful delete, false on failure.
  145. */
  146. function delete_metadata($meta_type, $object_id, $meta_key, $meta_value = '', $delete_all = false) {
  147. if ( !$meta_type || !$meta_key )
  148. return false;
  149. if ( (!$object_id = absint($object_id)) && !$delete_all )
  150. return false;
  151. if ( ! $table = _get_meta_table($meta_type) )
  152. return false;
  153. global $wpdb;
  154. $type_column = esc_sql($meta_type . '_id');
  155. $id_column = 'user' == $meta_type ? 'umeta_id' : 'meta_id';
  156. // expected_slashed ($meta_key)
  157. $meta_key = stripslashes($meta_key);
  158. $meta_value = stripslashes_deep($meta_value);
  159. $check = apply_filters( "delete_{$meta_type}_metadata", null, $object_id, $meta_key, $meta_value, $delete_all );
  160. if ( null !== $check )
  161. return (bool) $check;
  162. $_meta_value = $meta_value;
  163. $meta_value = maybe_serialize( $meta_value );
  164. $query = $wpdb->prepare( "SELECT $id_column FROM $table WHERE meta_key = %s", $meta_key );
  165. if ( !$delete_all )
  166. $query .= $wpdb->prepare(" AND $type_column = %d", $object_id );
  167. if ( $meta_value )
  168. $query .= $wpdb->prepare(" AND meta_value = %s", $meta_value );
  169. $meta_ids = $wpdb->get_col( $query );
  170. if ( !count( $meta_ids ) )
  171. return false;
  172. do_action( "delete_{$meta_type}_meta", $meta_ids, $object_id, $meta_key, $_meta_value );
  173. $query = "DELETE FROM $table WHERE $id_column IN( " . implode( ',', $meta_ids ) . " )";
  174. $count = $wpdb->query($query);
  175. if ( !$count )
  176. return false;
  177. wp_cache_delete($object_id, $meta_type . '_meta');
  178. // users cache stores usermeta that must be cleared.
  179. if ( 'user' == $meta_type )
  180. clean_user_cache($object_id);
  181. do_action( "deleted_{$meta_type}_meta", $meta_ids, $object_id, $meta_key, $_meta_value );
  182. return true;
  183. }
  184. /**
  185. * Retrieve metadata for the specified object.
  186. *
  187. * @since 2.9.0
  188. *
  189. * @param string $meta_type Type of object metadata is for (e.g., comment, post, or user)
  190. * @param int $object_id ID of the object metadata is for
  191. * @param string $meta_key Optional. Metadata key. If not specified, retrieve all metadata for
  192. * the specified object.
  193. * @param bool $single Optional, default is false. If true, return only the first value of the
  194. * specified meta_key. This parameter has no effect if meta_key is not specified.
  195. * @return string|array Single metadata value, or array of values
  196. */
  197. function get_metadata($meta_type, $object_id, $meta_key = '', $single = false) {
  198. if ( !$meta_type )
  199. return false;
  200. if ( !$object_id = absint($object_id) )
  201. return false;
  202. $check = apply_filters( "get_{$meta_type}_metadata", null, $object_id, $meta_key, $single );
  203. if ( null !== $check ) {
  204. if ( $single && is_array( $check ) )
  205. return $check[0];
  206. else
  207. return $check;
  208. }
  209. $meta_cache = wp_cache_get($object_id, $meta_type . '_meta');
  210. if ( !$meta_cache ) {
  211. $meta_cache = update_meta_cache( $meta_type, array( $object_id ) );
  212. $meta_cache = $meta_cache[$object_id];
  213. }
  214. if ( !$meta_key )
  215. return $meta_cache;
  216. if ( isset($meta_cache[$meta_key]) ) {
  217. if ( $single )
  218. return maybe_unserialize( $meta_cache[$meta_key][0] );
  219. else
  220. return array_map('maybe_unserialize', $meta_cache[$meta_key]);
  221. }
  222. if ($single)
  223. return '';
  224. else
  225. return array();
  226. }
  227. /**
  228. * Update the metadata cache for the specified objects.
  229. *
  230. * @since 2.9.0
  231. * @uses $wpdb WordPress database object for queries.
  232. *
  233. * @param string $meta_type Type of object metadata is for (e.g., comment, post, or user)
  234. * @param int|array $object_ids array or comma delimited list of object IDs to update cache for
  235. * @return mixed Metadata cache for the specified objects, or false on failure.
  236. */
  237. function update_meta_cache($meta_type, $object_ids) {
  238. if ( empty( $meta_type ) || empty( $object_ids ) )
  239. return false;
  240. if ( ! $table = _get_meta_table($meta_type) )
  241. return false;
  242. $column = esc_sql($meta_type . '_id');
  243. global $wpdb;
  244. if ( !is_array($object_ids) ) {
  245. $object_ids = preg_replace('|[^0-9,]|', '', $object_ids);
  246. $object_ids = explode(',', $object_ids);
  247. }
  248. $object_ids = array_map('intval', $object_ids);
  249. $cache_key = $meta_type . '_meta';
  250. $ids = array();
  251. $cache = array();
  252. foreach ( $object_ids as $id ) {
  253. $cached_object = wp_cache_get( $id, $cache_key );
  254. if ( false === $cached_object )
  255. $ids[] = $id;
  256. else
  257. $cache[$id] = $cached_object;
  258. }
  259. if ( empty( $ids ) )
  260. return $cache;
  261. // Get meta info
  262. $id_list = join(',', $ids);
  263. $meta_list = $wpdb->get_results( $wpdb->prepare("SELECT $column, meta_key, meta_value FROM $table WHERE $column IN ($id_list)",
  264. $meta_type), ARRAY_A );
  265. if ( !empty($meta_list) ) {
  266. foreach ( $meta_list as $metarow) {
  267. $mpid = intval($metarow[$column]);
  268. $mkey = $metarow['meta_key'];
  269. $mval = $metarow['meta_value'];
  270. // Force subkeys to be array type:
  271. if ( !isset($cache[$mpid]) || !is_array($cache[$mpid]) )
  272. $cache[$mpid] = array();
  273. if ( !isset($cache[$mpid][$mkey]) || !is_array($cache[$mpid][$mkey]) )
  274. $cache[$mpid][$mkey] = array();
  275. // Add a value to the current pid/key:
  276. $cache[$mpid][$mkey][] = $mval;
  277. }
  278. }
  279. foreach ( $ids as $id ) {
  280. if ( ! isset($cache[$id]) )
  281. $cache[$id] = array();
  282. wp_cache_add( $id, $cache[$id], $cache_key );
  283. }
  284. return $cache;
  285. }
  286. /**
  287. * Given a meta query, generates SQL clauses to be appended to a main query
  288. *
  289. * @since 3.2.0
  290. *
  291. * @see WP_Meta_Query
  292. *
  293. * @param array (optional) $meta_query A meta query
  294. * @param string $type Type of meta
  295. * @param string $primary_table
  296. * @param string $primary_id_column
  297. * @param object $context (optional) The main query object
  298. * @return array( 'join' => $join_sql, 'where' => $where_sql )
  299. */
  300. function get_meta_sql( $meta_query = false, $type, $primary_table, $primary_id_column, $context = null ) {
  301. $meta_query_obj = new WP_Meta_Query( $meta_query );
  302. return $meta_query_obj->get_sql( $type, $primary_table, $primary_id_column, $context );
  303. }
  304. /**
  305. * Container class for a multiple metadata query
  306. *
  307. * @since 3.2.0
  308. */
  309. class WP_Meta_Query {
  310. /**
  311. * List of metadata queries. A single query is an associative array:
  312. * - 'key' string The meta key
  313. * - 'value' string|array The meta value
  314. * - 'compare' (optional) string How to compare the key to the value.
  315. * Possible values: '=', '!=', '>', '>=', '<', '<=', 'LIKE', 'NOT LIKE', 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN'.
  316. * Default: '='
  317. * - 'type' string (optional) The type of the value.
  318. * Possible values: 'NUMERIC', 'BINARY', 'CHAR', 'DATE', 'DATETIME', 'DECIMAL', 'SIGNED', 'TIME', 'UNSIGNED'.
  319. * Default: 'CHAR'
  320. *
  321. * @since 3.2.0
  322. * @access public
  323. * @var array
  324. */
  325. public $queries = array();
  326. /**
  327. * The relation between the queries. Can be one of 'AND' or 'OR'.
  328. *
  329. * @since 3.2.0
  330. * @access public
  331. * @var string
  332. */
  333. public $relation;
  334. /**
  335. * Constructor
  336. *
  337. * @param array (optional) $meta_query A meta query
  338. */
  339. function __construct( $meta_query = false ) {
  340. if ( !$meta_query )
  341. return;
  342. if ( isset( $meta_query['relation'] ) && strtoupper( $meta_query['relation'] ) == 'OR' ) {
  343. $this->relation = 'OR';
  344. } else {
  345. $this->relation = 'AND';
  346. }
  347. $this->queries = array();
  348. foreach ( $meta_query as $key => $query ) {
  349. if ( ! is_array( $query ) )
  350. continue;
  351. $this->queries[] = $query;
  352. }
  353. }
  354. /**
  355. * Constructs a meta query based on 'meta_*' query vars
  356. *
  357. * @since 3.2.0
  358. * @access public
  359. *
  360. * @param array $qv The query variables
  361. */
  362. function parse_query_vars( $qv ) {
  363. $meta_query = array();
  364. // Simple query needs to be first for orderby=meta_value to work correctly
  365. foreach ( array( 'key', 'compare', 'type' ) as $key ) {
  366. if ( !empty( $qv[ "meta_$key" ] ) )
  367. $meta_query[0][ $key ] = $qv[ "meta_$key" ];
  368. }
  369. // WP_Query sets 'meta_value' = '' by default
  370. if ( isset( $qv[ 'meta_value' ] ) && '' !== $qv[ 'meta_value' ] )
  371. $meta_query[0]['value'] = $qv[ 'meta_value' ];
  372. if ( !empty( $qv['meta_query'] ) && is_array( $qv['meta_query'] ) ) {
  373. $meta_query = array_merge( $meta_query, $qv['meta_query'] );
  374. }
  375. $this->__construct( $meta_query );
  376. }
  377. /**
  378. * Generates SQL clauses to be appended to a main query.
  379. *
  380. * @since 3.2.0
  381. * @access public
  382. *
  383. * @param string $type Type of meta
  384. * @param string $primary_table
  385. * @param string $primary_id_column
  386. * @param object $context (optional) The main query object
  387. * @return array( 'join' => $join_sql, 'where' => $where_sql )
  388. */
  389. function get_sql( $type, $primary_table, $primary_id_column, $context = null ) {
  390. global $wpdb;
  391. if ( ! $meta_table = _get_meta_table( $type ) )
  392. return false;
  393. $meta_id_column = esc_sql( $type . '_id' );
  394. $join = array();
  395. $where = array();
  396. foreach ( $this->queries as $k => $q ) {
  397. $meta_key = isset( $q['key'] ) ? trim( $q['key'] ) : '';
  398. $meta_compare = isset( $q['compare'] ) ? strtoupper( $q['compare'] ) : '=';
  399. $meta_type = isset( $q['type'] ) ? strtoupper( $q['type'] ) : 'CHAR';
  400. if ( ! in_array( $meta_compare, array( '=', '!=', '>', '>=', '<', '<=', 'LIKE', 'NOT LIKE', 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN' ) ) )
  401. $meta_compare = '=';
  402. if ( 'NUMERIC' == $meta_type )
  403. $meta_type = 'SIGNED';
  404. elseif ( ! in_array( $meta_type, array( 'BINARY', 'CHAR', 'DATE', 'DATETIME', 'DECIMAL', 'SIGNED', 'TIME', 'UNSIGNED' ) ) )
  405. $meta_type = 'CHAR';
  406. $i = count( $join );
  407. $alias = $i ? 'mt' . $i : $meta_table;
  408. // Set JOIN
  409. $join[$i] = "INNER JOIN $meta_table";
  410. $join[$i] .= $i ? " AS $alias" : '';
  411. $join[$i] .= " ON ($primary_table.$primary_id_column = $alias.$meta_id_column)";
  412. $where[$k] = '';
  413. if ( !empty( $meta_key ) )
  414. $where[$k] = $wpdb->prepare( "$alias.meta_key = %s", $meta_key );
  415. if ( !isset( $q['value'] ) ) {
  416. if ( empty( $where[$k] ) )
  417. unset( $join[$i] );
  418. continue;
  419. }
  420. $meta_value = $q['value'];
  421. if ( in_array( $meta_compare, array( 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN' ) ) ) {
  422. if ( ! is_array( $meta_value ) )
  423. $meta_value = preg_split( '/[,\s]+/', $meta_value );
  424. if ( empty( $meta_value ) ) {
  425. unset( $join[$i] );
  426. continue;
  427. }
  428. } else {
  429. $meta_value = trim( $meta_value );
  430. }
  431. if ( 'IN' == substr( $meta_compare, -2) ) {
  432. $meta_compare_string = '(' . substr( str_repeat( ',%s', count( $meta_value ) ), 1 ) . ')';
  433. } elseif ( 'BETWEEN' == substr( $meta_compare, -7) ) {
  434. $meta_value = array_slice( $meta_value, 0, 2 );
  435. $meta_compare_string = '%s AND %s';
  436. } elseif ( 'LIKE' == substr( $meta_compare, -4 ) ) {
  437. $meta_value = '%' . like_escape( $meta_value ) . '%';
  438. $meta_compare_string = '%s';
  439. } else {
  440. $meta_compare_string = '%s';
  441. }
  442. if ( ! empty( $where[$k] ) )
  443. $where[$k] .= ' AND ';
  444. $where[$k] = ' (' . $where[$k] . $wpdb->prepare( "CAST($alias.meta_value AS {$meta_type}) {$meta_compare} {$meta_compare_string})", $meta_value );
  445. }
  446. $where = array_filter( $where );
  447. if ( empty( $where ) )
  448. $where = '';
  449. else
  450. $where = ' AND (' . implode( "\n{$this->relation} ", $where ) . ' )';
  451. $join = implode( "\n", $join );
  452. if ( ! empty( $join ) )
  453. $join = ' ' . $join;
  454. return apply_filters_ref_array( 'get_meta_sql', array( compact( 'join', 'where' ), $this->queries, $type, $primary_table, $primary_id_column, $context ) );
  455. }
  456. }
  457. /**
  458. * Retrieve the name of the metadata table for the specified object type.
  459. *
  460. * @since 2.9.0
  461. * @uses $wpdb WordPress database object for queries.
  462. *
  463. * @param string $type Type of object to get metadata table for (e.g., comment, post, or user)
  464. * @return mixed Metadata table name, or false if no metadata table exists
  465. */
  466. function _get_meta_table($type) {
  467. global $wpdb;
  468. $table_name = $type . 'meta';
  469. if ( empty($wpdb->$table_name) )
  470. return false;
  471. return $wpdb->$table_name;
  472. }
  473. /**
  474. * Determine whether a meta key is protected
  475. *
  476. * @since 3.1.3
  477. *
  478. * @param string $meta_key Meta key
  479. * @return bool True if the key is protected, false otherwise.
  480. */
  481. function is_protected_meta( $meta_key, $meta_type = null ) {
  482. $protected = ( '_' == $meta_key[0] );
  483. return apply_filters( 'is_protected_meta', $protected, $meta_key, $meta_type );
  484. }
  485. /**
  486. * Sanitize meta value
  487. *
  488. * @since 3.1.3
  489. *
  490. * @param string $meta_key Meta key
  491. * @param mixed $meta_value Meta value to sanitize
  492. * @param string $meta_type Type of meta
  493. * @return mixed Sanitized $meta_value
  494. */
  495. function sanitize_meta( $meta_key, $meta_value, $meta_type = null ) {
  496. return apply_filters( 'sanitize_meta', $meta_value, $meta_key, $meta_type );
  497. }
  498. ?>