entity.inc

File

drupal-7.x/includes/entity.inc
View source
  1. <?php
  2. /**
  3. * Interface for entity controller classes.
  4. *
  5. * All entity controller classes specified via the 'controller class' key
  6. * returned by hook_entity_info() or hook_entity_info_alter() have to implement
  7. * this interface.
  8. *
  9. * Most simple, SQL-based entity controllers will do better by extending
  10. * DrupalDefaultEntityController instead of implementing this interface
  11. * directly.
  12. */
  13. interface DrupalEntityControllerInterface {
  14. /**
  15. * Resets the internal, static entity cache.
  16. *
  17. * @param $ids
  18. * (optional) If specified, the cache is reset for the entities with the
  19. * given ids only.
  20. */
  21. public function resetCache(array $ids = NULL);
  22. /**
  23. * Loads one or more entities.
  24. *
  25. * @param $ids
  26. * An array of entity IDs, or FALSE to load all entities.
  27. * @param $conditions
  28. * An array of conditions in the form 'field' => $value.
  29. *
  30. * @return
  31. * An array of entity objects indexed by their ids. When no results are
  32. * found, an empty array is returned.
  33. */
  34. public function load($ids = array(), $conditions = array());
  35. }
  36. /**
  37. * Default implementation of DrupalEntityControllerInterface.
  38. *
  39. * This class can be used as-is by most simple entity types. Entity types
  40. * requiring special handling can extend the class.
  41. */
  42. class DrupalDefaultEntityController implements DrupalEntityControllerInterface {
  43. /**
  44. * Static cache of entities.
  45. *
  46. * @var array
  47. */
  48. protected $entityCache;
  49. /**
  50. * Entity type for this controller instance.
  51. *
  52. * @var string
  53. */
  54. protected $entityType;
  55. /**
  56. * Array of information about the entity.
  57. *
  58. * @var array
  59. *
  60. * @see entity_get_info()
  61. */
  62. protected $entityInfo;
  63. /**
  64. * Additional arguments to pass to hook_TYPE_load().
  65. *
  66. * Set before calling DrupalDefaultEntityController::attachLoad().
  67. *
  68. * @var array
  69. */
  70. protected $hookLoadArguments;
  71. /**
  72. * Name of the entity's ID field in the entity database table.
  73. *
  74. * @var string
  75. */
  76. protected $idKey;
  77. /**
  78. * Name of entity's revision database table field, if it supports revisions.
  79. *
  80. * Has the value FALSE if this entity does not use revisions.
  81. *
  82. * @var string
  83. */
  84. protected $revisionKey;
  85. /**
  86. * The table that stores revisions, if the entity supports revisions.
  87. *
  88. * @var string
  89. */
  90. protected $revisionTable;
  91. /**
  92. * Whether this entity type should use the static cache.
  93. *
  94. * Set by entity info.
  95. *
  96. * @var boolean
  97. */
  98. protected $cache;
  99. /**
  100. * Constructor: sets basic variables.
  101. *
  102. * @param $entityType
  103. * The entity type for which the instance is created.
  104. */
  105. public function __construct($entityType) {
  106. $this->entityType = $entityType;
  107. $this->entityInfo = entity_get_info($entityType);
  108. $this->entityCache = array();
  109. $this->hookLoadArguments = array();
  110. $this->idKey = $this->entityInfo['entity keys']['id'];
  111. // Check if the entity type supports revisions.
  112. if (!empty($this->entityInfo['entity keys']['revision'])) {
  113. $this->revisionKey = $this->entityInfo['entity keys']['revision'];
  114. $this->revisionTable = $this->entityInfo['revision table'];
  115. }
  116. else {
  117. $this->revisionKey = FALSE;
  118. }
  119. // Check if the entity type supports static caching of loaded entities.
  120. $this->cache = !empty($this->entityInfo['static cache']);
  121. }
  122. /**
  123. * Implements DrupalEntityControllerInterface::resetCache().
  124. */
  125. public function resetCache(array $ids = NULL) {
  126. if (isset($ids)) {
  127. foreach ($ids as $id) {
  128. unset($this->entityCache[$id]);
  129. }
  130. }
  131. else {
  132. $this->entityCache = array();
  133. }
  134. }
  135. /**
  136. * Implements DrupalEntityControllerInterface::load().
  137. */
  138. public function load($ids = array(), $conditions = array()) {
  139. $entities = array();
  140. // Revisions are not statically cached, and require a different query to
  141. // other conditions, so separate the revision id into its own variable.
  142. if ($this->revisionKey && isset($conditions[$this->revisionKey])) {
  143. $revision_id = $conditions[$this->revisionKey];
  144. unset($conditions[$this->revisionKey]);
  145. }
  146. else {
  147. $revision_id = FALSE;
  148. }
  149. // Create a new variable which is either a prepared version of the $ids
  150. // array for later comparison with the entity cache, or FALSE if no $ids
  151. // were passed. The $ids array is reduced as items are loaded from cache,
  152. // and we need to know if it's empty for this reason to avoid querying the
  153. // database when all requested entities are loaded from cache.
  154. $passed_ids = !empty($ids) ? array_flip($ids) : FALSE;
  155. // Try to load entities from the static cache, if the entity type supports
  156. // static caching.
  157. if ($this->cache && !$revision_id) {
  158. $entities += $this->cacheGet($ids, $conditions);
  159. // If any entities were loaded, remove them from the ids still to load.
  160. if ($passed_ids) {
  161. $ids = array_keys(array_diff_key($passed_ids, $entities));
  162. }
  163. }
  164. // Load any remaining entities from the database. This is the case if $ids
  165. // is set to FALSE (so we load all entities), if there are any ids left to
  166. // load, if loading a revision, or if $conditions was passed without $ids.
  167. if ($ids === FALSE || $ids || $revision_id || ($conditions && !$passed_ids)) {
  168. // Build the query.
  169. $query = $this->buildQuery($ids, $conditions, $revision_id);
  170. $queried_entities = $query
  171. ->execute()
  172. ->fetchAllAssoc($this->idKey);
  173. }
  174. // Pass all entities loaded from the database through $this->attachLoad(),
  175. // which attaches fields (if supported by the entity type) and calls the
  176. // entity type specific load callback, for example hook_node_load().
  177. if (!empty($queried_entities)) {
  178. $this->attachLoad($queried_entities, $revision_id);
  179. $entities += $queried_entities;
  180. }
  181. if ($this->cache) {
  182. // Add entities to the cache if we are not loading a revision.
  183. if (!empty($queried_entities) && !$revision_id) {
  184. $this->cacheSet($queried_entities);
  185. }
  186. }
  187. // Ensure that the returned array is ordered the same as the original
  188. // $ids array if this was passed in and remove any invalid ids.
  189. if ($passed_ids) {
  190. // Remove any invalid ids from the array.
  191. $passed_ids = array_intersect_key($passed_ids, $entities);
  192. foreach ($entities as $entity) {
  193. $passed_ids[$entity->{$this->idKey}] = $entity;
  194. }
  195. $entities = $passed_ids;
  196. }
  197. return $entities;
  198. }
  199. /**
  200. * Builds the query to load the entity.
  201. *
  202. * This has full revision support. For entities requiring special queries,
  203. * the class can be extended, and the default query can be constructed by
  204. * calling parent::buildQuery(). This is usually necessary when the object
  205. * being loaded needs to be augmented with additional data from another
  206. * table, such as loading node type into comments or vocabulary machine name
  207. * into terms, however it can also support $conditions on different tables.
  208. * See CommentController::buildQuery() or TaxonomyTermController::buildQuery()
  209. * for examples.
  210. *
  211. * @param $ids
  212. * An array of entity IDs, or FALSE to load all entities.
  213. * @param $conditions
  214. * An array of conditions in the form 'field' => $value.
  215. * @param $revision_id
  216. * The ID of the revision to load, or FALSE if this query is asking for the
  217. * most current revision(s).
  218. *
  219. * @return SelectQuery
  220. * A SelectQuery object for loading the entity.
  221. */
  222. protected function buildQuery($ids, $conditions = array(), $revision_id = FALSE) {
  223. $query = db_select($this->entityInfo['base table'], 'base');
  224. $query->addTag($this->entityType . '_load_multiple');
  225. if ($revision_id) {
  226. $query->join($this->revisionTable, 'revision', "revision.{$this->idKey} = base.{$this->idKey} AND revision.{$this->revisionKey} = :revisionId", array(':revisionId' => $revision_id));
  227. }
  228. elseif ($this->revisionKey) {
  229. $query->join($this->revisionTable, 'revision', "revision.{$this->revisionKey} = base.{$this->revisionKey}");
  230. }
  231. // Add fields from the {entity} table.
  232. $entity_fields = $this->entityInfo['schema_fields_sql']['base table'];
  233. if ($this->revisionKey) {
  234. // Add all fields from the {entity_revision} table.
  235. $entity_revision_fields = drupal_map_assoc($this->entityInfo['schema_fields_sql']['revision table']);
  236. // The id field is provided by entity, so remove it.
  237. unset($entity_revision_fields[$this->idKey]);
  238. // Remove all fields from the base table that are also fields by the same
  239. // name in the revision table.
  240. $entity_field_keys = array_flip($entity_fields);
  241. foreach ($entity_revision_fields as $key => $name) {
  242. if (isset($entity_field_keys[$name])) {
  243. unset($entity_fields[$entity_field_keys[$name]]);
  244. }
  245. }
  246. $query->fields('revision', $entity_revision_fields);
  247. }
  248. $query->fields('base', $entity_fields);
  249. if ($ids) {
  250. $query->condition("base.{$this->idKey}", $ids, 'IN');
  251. }
  252. if ($conditions) {
  253. foreach ($conditions as $field => $value) {
  254. $query->condition('base.' . $field, $value);
  255. }
  256. }
  257. return $query;
  258. }
  259. /**
  260. * Attaches data to entities upon loading.
  261. *
  262. * This will attach fields, if the entity is fieldable. It calls
  263. * hook_entity_load() for modules which need to add data to all entities.
  264. * It also calls hook_TYPE_load() on the loaded entities. For example
  265. * hook_node_load() or hook_user_load(). If your hook_TYPE_load()
  266. * expects special parameters apart from the queried entities, you can set
  267. * $this->hookLoadArguments prior to calling the method.
  268. * See NodeController::attachLoad() for an example.
  269. *
  270. * @param $queried_entities
  271. * Associative array of query results, keyed on the entity ID.
  272. * @param $revision_id
  273. * ID of the revision that was loaded, or FALSE if the most current revision
  274. * was loaded.
  275. */
  276. protected function attachLoad(&$queried_entities, $revision_id = FALSE) {
  277. // Attach fields.
  278. if ($this->entityInfo['fieldable']) {
  279. if ($revision_id) {
  280. field_attach_load_revision($this->entityType, $queried_entities);
  281. }
  282. else {
  283. field_attach_load($this->entityType, $queried_entities);
  284. }
  285. }
  286. // Call hook_entity_load().
  287. foreach (module_implements('entity_load') as $module) {
  288. $function = $module . '_entity_load';
  289. $function($queried_entities, $this->entityType);
  290. }
  291. // Call hook_TYPE_load(). The first argument for hook_TYPE_load() are
  292. // always the queried entities, followed by additional arguments set in
  293. // $this->hookLoadArguments.
  294. $args = array_merge(array($queried_entities), $this->hookLoadArguments);
  295. foreach (module_implements($this->entityInfo['load hook']) as $module) {
  296. call_user_func_array($module . '_' . $this->entityInfo['load hook'], $args);
  297. }
  298. }
  299. /**
  300. * Gets entities from the static cache.
  301. *
  302. * @param $ids
  303. * If not empty, return entities that match these IDs.
  304. * @param $conditions
  305. * If set, return entities that match all of these conditions.
  306. *
  307. * @return
  308. * Array of entities from the entity cache.
  309. */
  310. protected function cacheGet($ids, $conditions = array()) {
  311. $entities = array();
  312. // Load any available entities from the internal cache.
  313. if (!empty($this->entityCache)) {
  314. if ($ids) {
  315. $entities += array_intersect_key($this->entityCache, array_flip($ids));
  316. }
  317. // If loading entities only by conditions, fetch all available entities
  318. // from the cache. Entities which don't match are removed later.
  319. elseif ($conditions) {
  320. $entities = $this->entityCache;
  321. }
  322. }
  323. // Exclude any entities loaded from cache if they don't match $conditions.
  324. // This ensures the same behavior whether loading from memory or database.
  325. if ($conditions) {
  326. foreach ($entities as $entity) {
  327. $entity_values = (array) $entity;
  328. if (array_diff_assoc($conditions, $entity_values)) {
  329. unset($entities[$entity->{$this->idKey}]);
  330. }
  331. }
  332. }
  333. return $entities;
  334. }
  335. /**
  336. * Stores entities in the static entity cache.
  337. *
  338. * @param $entities
  339. * Entities to store in the cache.
  340. */
  341. protected function cacheSet($entities) {
  342. $this->entityCache += $entities;
  343. }
  344. }
  345. /**
  346. * Exception thrown by EntityFieldQuery() on unsupported query syntax.
  347. *
  348. * Some storage modules might not support the full range of the syntax for
  349. * conditions, and will raise an EntityFieldQueryException when an unsupported
  350. * condition was specified.
  351. */
  352. class EntityFieldQueryException extends Exception {}
  353. /**
  354. * Retrieves entities matching a given set of conditions.
  355. *
  356. * This class allows finding entities based on entity properties (for example,
  357. * node->changed), field values, and generic entity meta data (bundle,
  358. * entity type, entity id, and revision ID). It is not possible to query across
  359. * multiple entity types. For example, there is no facility to find published
  360. * nodes written by users created in the last hour, as this would require
  361. * querying both node->status and user->created.
  362. *
  363. * Normally we would not want to have public properties on the object, as that
  364. * allows the object's state to become inconsistent too easily. However, this
  365. * class's standard use case involves primarily code that does need to have
  366. * direct access to the collected properties in order to handle alternate
  367. * execution routines. We therefore use public properties for simplicity. Note
  368. * that code that is simply creating and running a field query should still use
  369. * the appropriate methods to add conditions on the query.
  370. *
  371. * Storage engines are not required to support every type of query. By default,
  372. * an EntityFieldQueryException will be raised if an unsupported condition is
  373. * specified or if the query has field conditions or sorts that are stored in
  374. * different field storage engines. However, this logic can be overridden in
  375. * hook_entity_query_alter().
  376. *
  377. * Also note that this query does not automatically respect entity access
  378. * restrictions. Node access control is performed by the SQL storage engine but
  379. * other storage engines might not do this.
  380. */
  381. class EntityFieldQuery {
  382. /**
  383. * Indicates that both deleted and non-deleted fields should be returned.
  384. *
  385. * @see EntityFieldQuery::deleted()
  386. */
  387. const RETURN_ALL = NULL;
  388. /**
  389. * TRUE if the query has already been altered, FALSE if it hasn't.
  390. *
  391. * Used in alter hooks to check for cloned queries that have already been
  392. * altered prior to the clone (for example, the pager count query).
  393. *
  394. * @var boolean
  395. */
  396. public $altered = FALSE;
  397. /**
  398. * Associative array of entity-generic metadata conditions.
  399. *
  400. * @var array
  401. *
  402. * @see EntityFieldQuery::entityCondition()
  403. */
  404. public $entityConditions = array();
  405. /**
  406. * List of field conditions.
  407. *
  408. * @var array
  409. *
  410. * @see EntityFieldQuery::fieldCondition()
  411. */
  412. public $fieldConditions = array();
  413. /**
  414. * List of field meta conditions (language and delta).
  415. *
  416. * Field conditions operate on columns specified by hook_field_schema(),
  417. * the meta conditions operate on columns added by the system: delta
  418. * and language. These can not be mixed with the field conditions because
  419. * field columns can have any name including delta and language.
  420. *
  421. * @var array
  422. *
  423. * @see EntityFieldQuery::fieldLanguageCondition()
  424. * @see EntityFieldQuery::fieldDeltaCondition()
  425. */
  426. public $fieldMetaConditions = array();
  427. /**
  428. * List of property conditions.
  429. *
  430. * @var array
  431. *
  432. * @see EntityFieldQuery::propertyCondition()
  433. */
  434. public $propertyConditions = array();
  435. /**
  436. * List of order clauses.
  437. *
  438. * @var array
  439. */
  440. public $order = array();
  441. /**
  442. * The query range.
  443. *
  444. * @var array
  445. *
  446. * @see EntityFieldQuery::range()
  447. */
  448. public $range = array();
  449. /**
  450. * The query pager data.
  451. *
  452. * @var array
  453. *
  454. * @see EntityFieldQuery::pager()
  455. */
  456. public $pager = array();
  457. /**
  458. * Query behavior for deleted data.
  459. *
  460. * TRUE to return only deleted data, FALSE to return only non-deleted data,
  461. * EntityFieldQuery::RETURN_ALL to return everything.
  462. *
  463. * @see EntityFieldQuery::deleted()
  464. */
  465. public $deleted = FALSE;
  466. /**
  467. * A list of field arrays used.
  468. *
  469. * Field names passed to EntityFieldQuery::fieldCondition() and
  470. * EntityFieldQuery::fieldOrderBy() are run through field_info_field() before
  471. * stored in this array. This way, the elements of this array are field
  472. * arrays.
  473. *
  474. * @var array
  475. */
  476. public $fields = array();
  477. /**
  478. * TRUE if this is a count query, FALSE if it isn't.
  479. *
  480. * @var boolean
  481. */
  482. public $count = FALSE;
  483. /**
  484. * Flag indicating whether this is querying current or all revisions.
  485. *
  486. * @var int
  487. *
  488. * @see EntityFieldQuery::age()
  489. */
  490. public $age = FIELD_LOAD_CURRENT;
  491. /**
  492. * A list of the tags added to this query.
  493. *
  494. * @var array
  495. *
  496. * @see EntityFieldQuery::addTag()
  497. */
  498. public $tags = array();
  499. /**
  500. * A list of metadata added to this query.
  501. *
  502. * @var array
  503. *
  504. * @see EntityFieldQuery::addMetaData()
  505. */
  506. public $metaData = array();
  507. /**
  508. * The ordered results.
  509. *
  510. * @var array
  511. *
  512. * @see EntityFieldQuery::execute().
  513. */
  514. public $orderedResults = array();
  515. /**
  516. * The method executing the query, if it is overriding the default.
  517. *
  518. * @var string
  519. *
  520. * @see EntityFieldQuery::execute().
  521. */
  522. public $executeCallback = '';
  523. /**
  524. * Adds a condition on entity-generic metadata.
  525. *
  526. * If the overall query contains only entity conditions or ordering, or if
  527. * there are property conditions, then specifying the entity type is
  528. * mandatory. If there are field conditions or ordering but no property
  529. * conditions or ordering, then specifying an entity type is optional. While
  530. * the field storage engine might support field conditions on more than one
  531. * entity type, there is no way to query across multiple entity base tables by
  532. * default. To specify the entity type, pass in 'entity_type' for $name,
  533. * the type as a string for $value, and no $operator (it's disregarded).
  534. *
  535. * 'bundle', 'revision_id' and 'entity_id' have no such restrictions.
  536. *
  537. * Note: The "comment" entity type does not support bundle conditions.
  538. *
  539. * @param $name
  540. * 'entity_type', 'bundle', 'revision_id' or 'entity_id'.
  541. * @param $value
  542. * The value for $name. In most cases, this is a scalar. For more complex
  543. * options, it is an array. The meaning of each element in the array is
  544. * dependent on $operator.
  545. * @param $operator
  546. * Possible values:
  547. * - '=', '<>', '>', '>=', '<', '<=', 'STARTS_WITH', 'CONTAINS': These
  548. * operators expect $value to be a literal of the same type as the
  549. * column.
  550. * - 'IN', 'NOT IN': These operators expect $value to be an array of
  551. * literals of the same type as the column.
  552. * - 'BETWEEN': This operator expects $value to be an array of two literals
  553. * of the same type as the column.
  554. * The operator can be omitted, and will default to 'IN' if the value is an
  555. * array, or to '=' otherwise.
  556. *
  557. * @return EntityFieldQuery
  558. * The called object.
  559. */
  560. public function entityCondition($name, $value, $operator = NULL) {
  561. // The '!=' operator is deprecated in favour of the '<>' operator since the
  562. // latter is ANSI SQL compatible.
  563. if ($operator == '!=') {
  564. $operator = '<>';
  565. }
  566. $this->entityConditions[$name] = array(
  567. 'value' => $value,
  568. 'operator' => $operator,
  569. );
  570. return $this;
  571. }
  572. /**
  573. * Adds a condition on field values.
  574. *
  575. * Note that entities with empty field values will be excluded from the
  576. * EntityFieldQuery results when using this method.
  577. *
  578. * @param $field
  579. * Either a field name or a field array.
  580. * @param $column
  581. * The column that should hold the value to be matched.
  582. * @param $value
  583. * The value to test the column value against.
  584. * @param $operator
  585. * The operator to be used to test the given value.
  586. * @param $delta_group
  587. * An arbitrary identifier: conditions in the same group must have the same
  588. * $delta_group.
  589. * @param $language_group
  590. * An arbitrary identifier: conditions in the same group must have the same
  591. * $language_group.
  592. *
  593. * @return EntityFieldQuery
  594. * The called object.
  595. *
  596. * @see EntityFieldQuery::addFieldCondition
  597. * @see EntityFieldQuery::deleted
  598. */
  599. public function fieldCondition($field, $column = NULL, $value = NULL, $operator = NULL, $delta_group = NULL, $language_group = NULL) {
  600. return $this->addFieldCondition($this->fieldConditions, $field, $column, $value, $operator, $delta_group, $language_group);
  601. }
  602. /**
  603. * Adds a condition on the field language column.
  604. *
  605. * @param $field
  606. * Either a field name or a field array.
  607. * @param $value
  608. * The value to test the column value against.
  609. * @param $operator
  610. * The operator to be used to test the given value.
  611. * @param $delta_group
  612. * An arbitrary identifier: conditions in the same group must have the same
  613. * $delta_group.
  614. * @param $language_group
  615. * An arbitrary identifier: conditions in the same group must have the same
  616. * $language_group.
  617. *
  618. * @return EntityFieldQuery
  619. * The called object.
  620. *
  621. * @see EntityFieldQuery::addFieldCondition
  622. * @see EntityFieldQuery::deleted
  623. */
  624. public function fieldLanguageCondition($field, $value = NULL, $operator = NULL, $delta_group = NULL, $language_group = NULL) {
  625. return $this->addFieldCondition($this->fieldMetaConditions, $field, 'language', $value, $operator, $delta_group, $language_group);
  626. }
  627. /**
  628. * Adds a condition on the field delta column.
  629. *
  630. * @param $field
  631. * Either a field name or a field array.
  632. * @param $value
  633. * The value to test the column value against.
  634. * @param $operator
  635. * The operator to be used to test the given value.
  636. * @param $delta_group
  637. * An arbitrary identifier: conditions in the same group must have the same
  638. * $delta_group.
  639. * @param $language_group
  640. * An arbitrary identifier: conditions in the same group must have the same
  641. * $language_group.
  642. *
  643. * @return EntityFieldQuery
  644. * The called object.
  645. *
  646. * @see EntityFieldQuery::addFieldCondition
  647. * @see EntityFieldQuery::deleted
  648. */
  649. public function fieldDeltaCondition($field, $value = NULL, $operator = NULL, $delta_group = NULL, $language_group = NULL) {
  650. return $this->addFieldCondition($this->fieldMetaConditions, $field, 'delta', $value, $operator, $delta_group, $language_group);
  651. }
  652. /**
  653. * Adds the given condition to the proper condition array.
  654. *
  655. * @param $conditions
  656. * A reference to an array of conditions.
  657. * @param $field
  658. * Either a field name or a field array.
  659. * @param $column
  660. * A column defined in the hook_field_schema() of this field. If this is
  661. * omitted then the query will find only entities that have data in this
  662. * field, using the entity and property conditions if there are any.
  663. * @param $value
  664. * The value to test the column value against. In most cases, this is a
  665. * scalar. For more complex options, it is an array. The meaning of each
  666. * element in the array is dependent on $operator.
  667. * @param $operator
  668. * Possible values:
  669. * - '=', '<>', '>', '>=', '<', '<=', 'STARTS_WITH', 'CONTAINS': These
  670. * operators expect $value to be a literal of the same type as the
  671. * column.
  672. * - 'IN', 'NOT IN': These operators expect $value to be an array of
  673. * literals of the same type as the column.
  674. * - 'BETWEEN': This operator expects $value to be an array of two literals
  675. * of the same type as the column.
  676. * The operator can be omitted, and will default to 'IN' if the value is an
  677. * array, or to '=' otherwise.
  678. * @param $delta_group
  679. * An arbitrary identifier: conditions in the same group must have the same
  680. * $delta_group. For example, let's presume a multivalue field which has
  681. * two columns, 'color' and 'shape', and for entity id 1, there are two
  682. * values: red/square and blue/circle. Entity ID 1 does not have values
  683. * corresponding to 'red circle', however if you pass 'red' and 'circle' as
  684. * conditions, it will appear in the results - by default queries will run
  685. * against any combination of deltas. By passing the conditions with the
  686. * same $delta_group it will ensure that only values attached to the same
  687. * delta are matched, and entity 1 would then be excluded from the results.
  688. * @param $language_group
  689. * An arbitrary identifier: conditions in the same group must have the same
  690. * $language_group.
  691. *
  692. * @return EntityFieldQuery
  693. * The called object.
  694. */
  695. protected function addFieldCondition(&$conditions, $field, $column = NULL, $value = NULL, $operator = NULL, $delta_group = NULL, $language_group = NULL) {
  696. // The '!=' operator is deprecated in favour of the '<>' operator since the
  697. // latter is ANSI SQL compatible.
  698. if ($operator == '!=') {
  699. $operator = '<>';
  700. }
  701. if (is_scalar($field)) {
  702. $field_definition = field_info_field($field);
  703. if (empty($field_definition)) {
  704. throw new EntityFieldQueryException(t('Unknown field: @field_name', array('@field_name' => $field)));
  705. }
  706. $field = $field_definition;
  707. }
  708. // Ensure the same index is used for field conditions as for fields.
  709. $index = count($this->fields);
  710. $this->fields[$index] = $field;
  711. if (isset($column)) {
  712. $conditions[$index] = array(
  713. 'field' => $field,
  714. 'column' => $column,
  715. 'value' => $value,
  716. 'operator' => $operator,
  717. 'delta_group' => $delta_group,
  718. 'language_group' => $language_group,
  719. );
  720. }
  721. return $this;
  722. }
  723. /**
  724. * Adds a condition on an entity-specific property.
  725. *
  726. * An $entity_type must be specified by calling
  727. * EntityFieldCondition::entityCondition('entity_type', $entity_type) before
  728. * executing the query. Also, by default only entities stored in SQL are
  729. * supported; however, EntityFieldQuery::executeCallback can be set to handle
  730. * different entity storage.
  731. *
  732. * @param $column
  733. * A column defined in the hook_schema() of the base table of the entity.
  734. * @param $value
  735. * The value to test the field against. In most cases, this is a scalar. For
  736. * more complex options, it is an array. The meaning of each element in the
  737. * array is dependent on $operator.
  738. * @param $operator
  739. * Possible values:
  740. * - '=', '<>', '>', '>=', '<', '<=', 'STARTS_WITH', 'CONTAINS': These
  741. * operators expect $value to be a literal of the same type as the
  742. * column.
  743. * - 'IN', 'NOT IN': These operators expect $value to be an array of
  744. * literals of the same type as the column.
  745. * - 'BETWEEN': This operator expects $value to be an array of two literals
  746. * of the same type as the column.
  747. * The operator can be omitted, and will default to 'IN' if the value is an
  748. * array, or to '=' otherwise.
  749. *
  750. * @return EntityFieldQuery
  751. * The called object.
  752. */
  753. public function propertyCondition($column, $value, $operator = NULL) {
  754. // The '!=' operator is deprecated in favour of the '<>' operator since the
  755. // latter is ANSI SQL compatible.
  756. if ($operator == '!=') {
  757. $operator = '<>';
  758. }
  759. $this->propertyConditions[] = array(
  760. 'column' => $column,
  761. 'value' => $value,
  762. 'operator' => $operator,
  763. );
  764. return $this;
  765. }
  766. /**
  767. * Orders the result set by entity-generic metadata.
  768. *
  769. * If called multiple times, the query will order by each specified column in
  770. * the order this method is called.
  771. *
  772. * Note: The "comment" and "taxonomy_term" entity types don't support ordering
  773. * by bundle. For "taxonomy_term", propertyOrderBy('vid') can be used instead.
  774. *
  775. * @param $name
  776. * 'entity_type', 'bundle', 'revision_id' or 'entity_id'.
  777. * @param $direction
  778. * The direction to sort. Legal values are "ASC" and "DESC".
  779. *
  780. * @return EntityFieldQuery
  781. * The called object.
  782. */
  783. public function entityOrderBy($name, $direction = 'ASC') {
  784. $this->order[] = array(
  785. 'type' => 'entity',
  786. 'specifier' => $name,
  787. 'direction' => $direction,
  788. );
  789. return $this;
  790. }
  791. /**
  792. * Orders the result set by a given field column.
  793. *
  794. * If called multiple times, the query will order by each specified column in
  795. * the order this method is called. Note that entities with empty field
  796. * values will be excluded from the EntityFieldQuery results when using this
  797. * method.
  798. *
  799. * @param $field
  800. * Either a field name or a field array.
  801. * @param $column
  802. * A column defined in the hook_field_schema() of this field. entity_id and
  803. * bundle can also be used.
  804. * @param $direction
  805. * The direction to sort. Legal values are "ASC" and "DESC".
  806. *
  807. * @return EntityFieldQuery
  808. * The called object.
  809. */
  810. public function fieldOrderBy($field, $column, $direction = 'ASC') {
  811. if (is_scalar($field)) {
  812. $field_definition = field_info_field($field);
  813. if (empty($field_definition)) {
  814. throw new EntityFieldQueryException(t('Unknown field: @field_name', array('@field_name' => $field)));
  815. }
  816. $field = $field_definition;
  817. }
  818. // Save the index used for the new field, for later use in field storage.
  819. $index = count($this->fields);
  820. $this->fields[$index] = $field;
  821. $this->order[] = array(
  822. 'type' => 'field',
  823. 'specifier' => array(
  824. 'field' => $field,
  825. 'index' => $index,
  826. 'column' => $column,
  827. ),
  828. 'direction' => $direction,
  829. );
  830. return $this;
  831. }
  832. /**
  833. * Orders the result set by an entity-specific property.
  834. *
  835. * An $entity_type must be specified by calling
  836. * EntityFieldCondition::entityCondition('entity_type', $entity_type) before
  837. * executing the query.
  838. *
  839. * If called multiple times, the query will order by each specified column in
  840. * the order this method is called.
  841. *
  842. * @param $column
  843. * The column on which to order.
  844. * @param $direction
  845. * The direction to sort. Legal values are "ASC" and "DESC".
  846. *
  847. * @return EntityFieldQuery
  848. * The called object.
  849. */
  850. public function propertyOrderBy($column, $direction = 'ASC') {
  851. $this->order[] = array(
  852. 'type' => 'property',
  853. 'specifier' => $column,
  854. 'direction' => $direction,
  855. );
  856. return $this;
  857. }
  858. /**
  859. * Sets the query to be a count query only.
  860. *
  861. * @return EntityFieldQuery
  862. * The called object.
  863. */
  864. public function count() {
  865. $this->count = TRUE;
  866. return $this;
  867. }
  868. /**
  869. * Restricts a query to a given range in the result set.
  870. *
  871. * @param $start
  872. * The first entity from the result set to return. If NULL, removes any
  873. * range directives that are set.
  874. * @param $length
  875. * The number of entities to return from the result set.
  876. *
  877. * @return EntityFieldQuery
  878. * The called object.
  879. */
  880. public function range($start = NULL, $length = NULL) {
  881. $this->range = array(
  882. 'start' => $start,
  883. 'length' => $length,
  884. );
  885. return $this;
  886. }
  887. /**
  888. * Enables a pager for the query.
  889. *
  890. * @param $limit
  891. * An integer specifying the number of elements per page. If passed a false
  892. * value (FALSE, 0, NULL), the pager is disabled.
  893. * @param $element
  894. * An optional integer to distinguish between multiple pagers on one page.
  895. * If not provided, one is automatically calculated.
  896. *
  897. * @return EntityFieldQuery
  898. * The called object.
  899. */
  900. public function pager($limit = 10, $element = NULL) {
  901. if (!isset($element)) {
  902. $element = PagerDefault::$maxElement++;
  903. }
  904. elseif ($element >= PagerDefault::$maxElement) {
  905. PagerDefault::$maxElement = $element + 1;
  906. }
  907. $this->pager = array(
  908. 'limit' => $limit,
  909. 'element' => $element,
  910. );
  911. return $this;
  912. }
  913. /**
  914. * Enables sortable tables for this query.
  915. *
  916. * @param $headers
  917. * An EFQ Header array based on which the order clause is added to the
  918. * query.
  919. *
  920. * @return EntityFieldQuery
  921. * The called object.
  922. */
  923. public function tableSort(&$headers) {
  924. // If 'field' is not initialized, the header columns aren't clickable
  925. foreach ($headers as $key =>$header) {
  926. if (is_array($header) && isset($header['specifier'])) {
  927. $headers[$key]['field'] = '';
  928. }
  929. }
  930. $order = tablesort_get_order($headers);
  931. $direction = tablesort_get_sort($headers);
  932. foreach ($headers as $header) {
  933. if (is_array($header) && ($header['data'] == $order['name'])) {
  934. if ($header['type'] == 'field') {
  935. $this->fieldOrderBy($header['specifier']['field'], $header['specifier']['column'], $direction);
  936. }
  937. else {
  938. $header['direction'] = $direction;
  939. $this->order[] = $header;
  940. }
  941. }
  942. }
  943. return $this;
  944. }
  945. /**
  946. * Filters on the data being deleted.
  947. *
  948. * @param $deleted
  949. * TRUE to only return deleted data, FALSE to return non-deleted data,
  950. * EntityFieldQuery::RETURN_ALL to return everything. Defaults to FALSE.
  951. *
  952. * @return EntityFieldQuery
  953. * The called object.
  954. */
  955. public function deleted($deleted = TRUE) {
  956. $this->deleted = $deleted;
  957. return $this;
  958. }
  959. /**
  960. * Queries the current or every revision.
  961. *
  962. * Note that this only affects field conditions. Property conditions always
  963. * apply to the current revision.
  964. * @TODO: Once revision tables have been cleaned up, revisit this.
  965. *
  966. * @param $age
  967. * - FIELD_LOAD_CURRENT (default): Query the most recent revisions for all
  968. * entities. The results will be keyed by entity type and entity ID.
  969. * - FIELD_LOAD_REVISION: Query all revisions. The results will be keyed by
  970. * entity type and entity revision ID.
  971. *
  972. * @return EntityFieldQuery
  973. * The called object.
  974. */
  975. public function age($age) {
  976. $this->age = $age;
  977. return $this;
  978. }
  979. /**
  980. * Adds a tag to the query.
  981. *
  982. * Tags are strings that mark a query so that hook_query_alter() and
  983. * hook_query_TAG_alter() implementations may decide if they wish to alter
  984. * the query. A query may have any number of tags, and they must be valid PHP
  985. * identifiers (composed of letters, numbers, and underscores). For example,
  986. * queries involving nodes that will be displayed for a user need to add the
  987. * tag 'node_access', so that the node module can add access restrictions to
  988. * the query.
  989. *
  990. * If an entity field query has tags, it must also have an entity type
  991. * specified, because the alter hook will need the entity base table.
  992. *
  993. * @param string $tag
  994. * The tag to add.
  995. *
  996. * @return EntityFieldQuery
  997. * The called object.
  998. */
  999. public function addTag($tag) {
  1000. $this->tags[$tag] = $tag;
  1001. return $this;
  1002. }
  1003. /**
  1004. * Adds additional metadata to the query.
  1005. *
  1006. * Sometimes a query may need to provide additional contextual data for the
  1007. * alter hook. The alter hook implementations may then use that information
  1008. * to decide if and how to take action.
  1009. *
  1010. * @param $key
  1011. * The unique identifier for this piece of metadata. Must be a string that
  1012. * follows the same rules as any other PHP identifier.
  1013. * @param $object
  1014. * The additional data to add to the query. May be any valid PHP variable.
  1015. *
  1016. * @return EntityFieldQuery
  1017. * The called object.
  1018. */
  1019. public function addMetaData($key, $object) {
  1020. $this->metaData[$key] = $object;
  1021. return $this;
  1022. }
  1023. /**
  1024. * Executes the query.
  1025. *
  1026. * After executing the query, $this->orderedResults will contain a list of
  1027. * the same stub entities in the order returned by the query. This is only
  1028. * relevant if there are multiple entity types in the returned value and
  1029. * a field ordering was requested. In every other case, the returned value
  1030. * contains everything necessary for processing.
  1031. *
  1032. * @return
  1033. * Either a number if count() was called or an array of associative arrays
  1034. * of stub entities. The outer array keys are entity types, and the inner
  1035. * array keys are the relevant ID. (In most cases this will be the entity
  1036. * ID. The only exception is when age=FIELD_LOAD_REVISION is used and field
  1037. * conditions or sorts are present -- in this case, the key will be the
  1038. * revision ID.) The entity type will only exist in the outer array if
  1039. * results were found. The inner array values are always stub entities, as
  1040. * returned by entity_create_stub_entity(). To traverse the returned array:
  1041. * @code
  1042. * foreach ($query->execute() as $entity_type => $entities) {
  1043. * foreach ($entities as $entity_id => $entity) {
  1044. * @endcode
  1045. * Note if the entity type is known, then the following snippet will load
  1046. * the entities found:
  1047. * @code
  1048. * $result = $query->execute();
  1049. * if (!empty($result[$my_type])) {
  1050. * $entities = entity_load($my_type, array_keys($result[$my_type]));
  1051. * }
  1052. * @endcode
  1053. */
  1054. public function execute() {
  1055. // Give a chance to other modules to alter the query.
  1056. drupal_alter('entity_query', $this);
  1057. $this->altered = TRUE;
  1058. // Initialize the pager.
  1059. $this->initializePager();
  1060. // Execute the query using the correct callback.
  1061. $result = call_user_func($this->queryCallback(), $this);
  1062. return $result;
  1063. }
  1064. /**
  1065. * Determines the query callback to use for this entity query.
  1066. *
  1067. * @return
  1068. * A callback that can be used with call_user_func().
  1069. */
  1070. public function queryCallback() {
  1071. // Use the override from $this->executeCallback. It can be set either
  1072. // while building the query, or using hook_entity_query_alter().
  1073. if (function_exists($this->executeCallback)) {
  1074. return $this->executeCallback;
  1075. }
  1076. // If there are no field conditions and sorts, and no execute callback
  1077. // then we default to querying entity tables in SQL.
  1078. if (empty($this->fields)) {
  1079. return array($this, 'propertyQuery');
  1080. }
  1081. // If no override, find the storage engine to be used.
  1082. foreach ($this->fields as $field) {
  1083. if (!isset($storage)) {
  1084. $storage = $field['storage']['module'];
  1085. }
  1086. elseif ($storage != $field['storage']['module']) {
  1087. throw new EntityFieldQueryException(t("Can't handle more than one field storage engine"));
  1088. }
  1089. }
  1090. if ($storage) {
  1091. // Use hook_field_storage_query() from the field storage.
  1092. return $storage . '_field_storage_query';
  1093. }
  1094. else {
  1095. throw new EntityFieldQueryException(t("Field storage engine not found."));
  1096. }
  1097. }
  1098. /**
  1099. * Queries entity tables in SQL for property conditions and sorts.
  1100. *
  1101. * This method is only used if there are no field conditions and sorts.
  1102. *
  1103. * @return
  1104. * See EntityFieldQuery::execute().
  1105. */
  1106. protected function propertyQuery() {
  1107. if (empty($this->entityConditions['entity_type'])) {
  1108. throw new EntityFieldQueryException(t('For this query an entity type must be specified.'));
  1109. }
  1110. $entity_type = $this->entityConditions['entity_type']['value'];
  1111. $entity_info = entity_get_info($entity_type);
  1112. if (empty($entity_info['base table'])) {
  1113. throw new EntityFieldQueryException(t('Entity %entity has no base table.', array('%entity' => $entity_type)));
  1114. }
  1115. $base_table = $entity_info['base table'];
  1116. $base_table_schema = drupal_get_schema($base_table);
  1117. $select_query = db_select($base_table);
  1118. $select_query->addExpression(':entity_type', 'entity_type', array(':entity_type' => $entity_type));
  1119. // Process the property conditions.
  1120. foreach ($this->propertyConditions as $property_condition) {
  1121. $this->addCondition($select_query, $base_table . '.' . $property_condition['column'], $property_condition);
  1122. }
  1123. // Process the four possible entity condition.
  1124. // The id field is always present in entity keys.
  1125. $sql_field = $entity_info['entity keys']['id'];
  1126. $id_map['entity_id'] = $sql_field;
  1127. $select_query->addField($base_table, $sql_field, 'entity_id');
  1128. if (isset($this->entityConditions['entity_id'])) {
  1129. $this->addCondition($select_query, $base_table . '.' . $sql_field, $this->entityConditions['entity_id']);
  1130. }
  1131. // If there is a revision key defined, use it.
  1132. if (!empty($entity_info['entity keys']['revision'])) {
  1133. $sql_field = $entity_info['entity keys']['revision'];
  1134. $select_query->addField($base_table, $sql_field, 'revision_id');
  1135. if (isset($this->entityConditions['revision_id'])) {
  1136. $this->addCondition($select_query, $base_table . '.' . $sql_field, $this->entityConditions['revision_id']);
  1137. }
  1138. }
  1139. else {
  1140. $sql_field = 'revision_id';
  1141. $select_query->addExpression('NULL', 'revision_id');
  1142. }
  1143. $id_map['revision_id'] = $sql_field;
  1144. // Handle bundles.
  1145. if (!empty($entity_info['entity keys']['bundle'])) {
  1146. $sql_field = $entity_info['entity keys']['bundle'];
  1147. $having = FALSE;
  1148. if (!empty($base_table_schema['fields'][$sql_field])) {
  1149. $select_query->addField($base_table, $sql_field, 'bundle');
  1150. }
  1151. }
  1152. else {
  1153. $sql_field = 'bundle';
  1154. $select_query->addExpression(':bundle', 'bundle', array(':bundle' => $entity_type));
  1155. $having = TRUE;
  1156. }
  1157. $id_map['bundle'] = $sql_field;
  1158. if (isset($this->entityConditions['bundle'])) {
  1159. if (!empty($entity_info['entity keys']['bundle'])) {
  1160. $this->addCondition($select_query, $base_table . '.' . $sql_field, $this->entityConditions['bundle'], $having);
  1161. }
  1162. else {
  1163. // This entity has no bundle, so invalidate the query.
  1164. $select_query->where('1 = 0');
  1165. }
  1166. }
  1167. // Order the query.
  1168. foreach ($this->order as $order) {
  1169. if ($order['type'] == 'entity') {
  1170. $key = $order['specifier'];
  1171. if (!isset($id_map[$key])) {
  1172. throw new EntityFieldQueryException(t('Do not know how to order on @key for @entity_type', array('@key' => $key, '@entity_type' => $entity_type)));
  1173. }
  1174. $select_query->orderBy($id_map[$key], $order['direction']);
  1175. }
  1176. elseif ($order['type'] == 'property') {
  1177. $select_query->orderBy($base_table . '.' . $order['specifier'], $order['direction']);
  1178. }
  1179. }
  1180. return $this->finishQuery($select_query);
  1181. }
  1182. /**
  1183. * Gets the total number of results and initializes a pager for the query.
  1184. *
  1185. * The pager can be disabled by either setting the pager limit to 0, or by
  1186. * setting this query to be a count query.
  1187. */
  1188. function initializePager() {
  1189. if ($this->pager && !empty($this->pager['limit']) && !$this->count) {
  1190. $page = pager_find_page($this->pager['element']);
  1191. $count_query = clone $this;
  1192. $this->pager['total'] = $count_query->count()->execute();
  1193. $this->pager['start'] = $page * $this->pager['limit'];
  1194. pager_default_initialize($this->pager['total'], $this->pager['limit'], $this->pager['element']);
  1195. $this->range($this->pager['start'], $this->pager['limit']);
  1196. }
  1197. }
  1198. /**
  1199. * Finishes the query.
  1200. *
  1201. * Adds tags, metaData, range and returns the requested list or count.
  1202. *
  1203. * @param SelectQuery $select_query
  1204. * A SelectQuery which has entity_type, entity_id, revision_id and bundle
  1205. * fields added.
  1206. * @param $id_key
  1207. * Which field's values to use as the returned array keys.
  1208. *
  1209. * @return
  1210. * See EntityFieldQuery::execute().
  1211. */
  1212. function finishQuery($select_query, $id_key = 'entity_id') {
  1213. foreach ($this->tags as $tag) {
  1214. $select_query->addTag($tag);
  1215. }
  1216. foreach ($this->metaData as $key => $object) {
  1217. $select_query->addMetaData($key, $object);
  1218. }
  1219. $select_query->addMetaData('entity_field_query', $this);
  1220. if ($this->range) {
  1221. $select_query->range($this->range['start'], $this->range['length']);
  1222. }
  1223. if ($this->count) {
  1224. return $select_query->countQuery()->execute()->fetchField();
  1225. }
  1226. $return = array();
  1227. foreach ($select_query->execute() as $partial_entity) {
  1228. $bundle = isset($partial_entity->bundle) ? $partial_entity->bundle : NULL;
  1229. $entity = entity_create_stub_entity($partial_entity->entity_type, array($partial_entity->entity_id, $partial_entity->revision_id, $bundle));
  1230. $return[$partial_entity->entity_type][$partial_entity->$id_key] = $entity;
  1231. $this->ordered_results[] = $partial_entity;
  1232. }
  1233. return $return;
  1234. }
  1235. /**
  1236. * Adds a condition to an already built SelectQuery (internal function).
  1237. *
  1238. * This is a helper for hook_entity_query() and hook_field_storage_query().
  1239. *
  1240. * @param SelectQuery $select_query
  1241. * A SelectQuery object.
  1242. * @param $sql_field
  1243. * The name of the field.
  1244. * @param $condition
  1245. * A condition as described in EntityFieldQuery::fieldCondition() and
  1246. * EntityFieldQuery::entityCondition().
  1247. * @param $having
  1248. * HAVING or WHERE. This is necessary because SQL can't handle WHERE
  1249. * conditions on aliased columns.
  1250. */
  1251. public function addCondition(SelectQuery $select_query, $sql_field, $condition, $having = FALSE) {
  1252. $method = $having ? 'havingCondition' : 'condition';
  1253. $like_prefix = '';
  1254. switch ($condition['operator']) {
  1255. case 'CONTAINS':
  1256. $like_prefix = '%';
  1257. case 'STARTS_WITH':
  1258. $select_query->$method($sql_field, $like_prefix . db_like($condition['value']) . '%', 'LIKE');
  1259. break;
  1260. default:
  1261. $select_query->$method($sql_field, $condition['value'], $condition['operator']);
  1262. }
  1263. }
  1264. }
  1265. /**
  1266. * Defines an exception thrown when a malformed entity is passed.
  1267. */
  1268. class EntityMalformedException extends Exception { }