entity.inc 49 KB

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