Project

General

Profile

Paste
Download (48.8 KB) Statistics
| Branch: | Revision:

root / drupal7 / includes / entity.inc @ 96ad5adc

1
<?php
2

    
3
/**
4
 * Interface for entity controller classes.
5
 *
6
 * All entity controller classes specified via the 'controller class' key
7
 * returned by hook_entity_info() or hook_entity_info_alter() have to implement
8
 * this interface.
9
 *
10
 * Most simple, SQL-based entity controllers will do better by extending
11
 * DrupalDefaultEntityController instead of implementing this interface
12
 * directly.
13
 */
14
interface DrupalEntityControllerInterface {
15

    
16
  /**
17
   * Resets the internal, static entity cache.
18
   *
19
   * @param $ids
20
   *   (optional) If specified, the cache is reset for the entities with the
21
   *   given ids only.
22
   */
23
  public function resetCache(array $ids = NULL);
24

    
25
  /**
26
   * Loads one or more entities.
27
   *
28
   * @param $ids
29
   *   An array of entity IDs, or FALSE to load all entities.
30
   * @param $conditions
31
   *   An array of conditions. Keys are field names on the entity's base table.
32
   *   Values will be compared for equality. All the comparisons will be ANDed
33
   *   together. This parameter is deprecated; use an EntityFieldQuery instead.
34
   *
35
   * @return
36
   *   An array of entity objects indexed by their ids. When no results are
37
   *   found, an empty array is returned.
38
   */
39
  public function load($ids = array(), $conditions = array());
40
}
41

    
42
/**
43
 * Default implementation of DrupalEntityControllerInterface.
44
 *
45
 * This class can be used as-is by most simple entity types. Entity types
46
 * requiring special handling can extend the class.
47
 */
48
class DrupalDefaultEntityController implements DrupalEntityControllerInterface {
49

    
50
  /**
51
   * Static cache of entities, keyed by entity ID.
52
   *
53
   * @var array
54
   */
55
  protected $entityCache;
56

    
57
  /**
58
   * Entity type for this controller instance.
59
   *
60
   * @var string
61
   */
62
  protected $entityType;
63

    
64
  /**
65
   * Array of information about the entity.
66
   *
67
   * @var array
68
   *
69
   * @see entity_get_info()
70
   */
71
  protected $entityInfo;
72

    
73
  /**
74
   * Additional arguments to pass to hook_TYPE_load().
75
   *
76
   * Set before calling DrupalDefaultEntityController::attachLoad().
77
   *
78
   * @var array
79
   */
80
  protected $hookLoadArguments;
81

    
82
  /**
83
   * Name of the entity's ID field in the entity database table.
84
   *
85
   * @var string
86
   */
87
  protected $idKey;
88

    
89
  /**
90
   * Name of entity's revision database table field, if it supports revisions.
91
   *
92
   * Has the value FALSE if this entity does not use revisions.
93
   *
94
   * @var string
95
   */
96
  protected $revisionKey;
97

    
98
  /**
99
   * The table that stores revisions, if the entity supports revisions.
100
   *
101
   * @var string
102
   */
103
  protected $revisionTable;
104

    
105
  /**
106
   * Whether this entity type should use the static cache.
107
   *
108
   * Set by entity info.
109
   *
110
   * @var boolean
111
   */
112
  protected $cache;
113

    
114
  /**
115
   * Constructor: sets basic variables.
116
   *
117
   * @param $entityType
118
   *   The entity type for which the instance is created.
119
   */
120
  public function __construct($entityType) {
121
    $this->entityType = $entityType;
122
    $this->entityInfo = entity_get_info($entityType);
123
    $this->entityCache = array();
124
    $this->hookLoadArguments = array();
125
    $this->idKey = $this->entityInfo['entity keys']['id'];
126

    
127
    // Check if the entity type supports revisions.
128
    if (!empty($this->entityInfo['entity keys']['revision'])) {
129
      $this->revisionKey = $this->entityInfo['entity keys']['revision'];
130
      $this->revisionTable = $this->entityInfo['revision table'];
131
    }
132
    else {
133
      $this->revisionKey = FALSE;
134
    }
135

    
136
    // Check if the entity type supports static caching of loaded entities.
137
    $this->cache = !empty($this->entityInfo['static cache']);
138
  }
139

    
140
  /**
141
   * Implements DrupalEntityControllerInterface::resetCache().
142
   */
143
  public function resetCache(array $ids = NULL) {
144
    if (isset($ids)) {
145
      foreach ($ids as $id) {
146
        unset($this->entityCache[$id]);
147
      }
148
    }
149
    else {
150
      $this->entityCache = array();
151
    }
152
  }
153

    
154
  /**
155
   * Implements DrupalEntityControllerInterface::load().
156
   */
157
  public function load($ids = array(), $conditions = array()) {
158
    $entities = array();
159

    
160
    // Revisions are not statically cached, and require a different query to
161
    // other conditions, so separate the revision id into its own variable.
162
    if ($this->revisionKey && isset($conditions[$this->revisionKey])) {
163
      $revision_id = $conditions[$this->revisionKey];
164
      unset($conditions[$this->revisionKey]);
165
    }
166
    else {
167
      $revision_id = FALSE;
168
    }
169

    
170
    // Create a new variable which is either a prepared version of the $ids
171
    // array for later comparison with the entity cache, or FALSE if no $ids
172
    // were passed. The $ids array is reduced as items are loaded from cache,
173
    // and we need to know if it's empty for this reason to avoid querying the
174
    // database when all requested entities are loaded from cache.
175
    $passed_ids = !empty($ids) ? array_flip($ids) : FALSE;
176
    // Try to load entities from the static cache, if the entity type supports
177
    // static caching.
178
    if ($this->cache && !$revision_id) {
179
      $entities += $this->cacheGet($ids, $conditions);
180
      // If any entities were loaded, remove them from the ids still to load.
181
      if ($passed_ids) {
182
        $ids = array_keys(array_diff_key($passed_ids, $entities));
183
      }
184
    }
185

    
186
    // Ensure integer entity IDs are valid.
187
    if (!empty($ids)) {
188
      $this->cleanIds($ids);
189
    }
190

    
191
    // Load any remaining entities from the database. This is the case if $ids
192
    // is set to FALSE (so we load all entities), if there are any ids left to
193
    // load, if loading a revision, or if $conditions was passed without $ids.
194
    if ($ids === FALSE || $ids || $revision_id || ($conditions && !$passed_ids)) {
195
      // Build the query.
196
      $query = $this->buildQuery($ids, $conditions, $revision_id);
197
      $queried_entities = $query
198
        ->execute()
199
        ->fetchAllAssoc($this->idKey);
200
    }
201

    
202
    // Pass all entities loaded from the database through $this->attachLoad(),
203
    // which attaches fields (if supported by the entity type) and calls the
204
    // entity type specific load callback, for example hook_node_load().
205
    if (!empty($queried_entities)) {
206
      $this->attachLoad($queried_entities, $revision_id);
207
      $entities += $queried_entities;
208
    }
209

    
210
    if ($this->cache) {
211
      // Add entities to the cache if we are not loading a revision.
212
      if (!empty($queried_entities) && !$revision_id) {
213
        $this->cacheSet($queried_entities);
214
      }
215
    }
216

    
217
    // Ensure that the returned array is ordered the same as the original
218
    // $ids array if this was passed in and remove any invalid ids.
219
    if ($passed_ids) {
220
      // Remove any invalid ids from the array.
221
      $passed_ids = array_intersect_key($passed_ids, $entities);
222
      foreach ($entities as $entity) {
223
        $passed_ids[$entity->{$this->idKey}] = $entity;
224
      }
225
      $entities = $passed_ids;
226
    }
227

    
228
    return $entities;
229
  }
230

    
231
  /**
232
   * Ensures integer entity IDs are valid.
233
   *
234
   * The identifier sanitization provided by this method has been introduced
235
   * as Drupal used to rely on the database to facilitate this, which worked
236
   * correctly with MySQL but led to errors with other DBMS such as PostgreSQL.
237
   *
238
   * @param array $ids
239
   *   The entity IDs to verify. Non-integer IDs are removed from this array if
240
   *   the entity type requires IDs to be integers.
241
   */
242
  protected function cleanIds(&$ids) {
243
    $entity_info = entity_get_info($this->entityType);
244
    if (isset($entity_info['base table field types'])) {
245
      $id_type = $entity_info['base table field types'][$this->idKey];
246
      if ($id_type == 'serial' || $id_type == 'int') {
247
        $ids = array_filter($ids, array($this, 'filterId'));
248
        $ids = array_map('intval', $ids);
249
      }
250
    }
251
  }
252

    
253
  /**
254
   * Callback for array_filter that removes non-integer IDs.
255
   */
256
  protected function filterId($id) {
257
    return is_numeric($id) && $id == (int) $id;
258
  }
259

    
260
  /**
261
   * Builds the query to load the entity.
262
   *
263
   * This has full revision support. For entities requiring special queries,
264
   * the class can be extended, and the default query can be constructed by
265
   * calling parent::buildQuery(). This is usually necessary when the object
266
   * being loaded needs to be augmented with additional data from another
267
   * table, such as loading node type into comments or vocabulary machine name
268
   * into terms, however it can also support $conditions on different tables.
269
   * See CommentController::buildQuery() or TaxonomyTermController::buildQuery()
270
   * for examples.
271
   *
272
   * @param $ids
273
   *   An array of entity IDs, or FALSE to load all entities.
274
   * @param $conditions
275
   *   An array of conditions. Keys are field names on the entity's base table.
276
   *   Values will be compared for equality. All the comparisons will be ANDed
277
   *   together. This parameter is deprecated; use an EntityFieldQuery instead.
278
   * @param $revision_id
279
   *   The ID of the revision to load, or FALSE if this query is asking for the
280
   *   most current revision(s).
281
   *
282
   * @return SelectQuery
283
   *   A SelectQuery object for loading the entity.
284
   */
285
  protected function buildQuery($ids, $conditions = array(), $revision_id = FALSE) {
286
    $query = db_select($this->entityInfo['base table'], 'base');
287

    
288
    $query->addTag($this->entityType . '_load_multiple');
289

    
290
    if ($revision_id) {
291
      $query->join($this->revisionTable, 'revision', "revision.{$this->idKey} = base.{$this->idKey} AND revision.{$this->revisionKey} = :revisionId", array(':revisionId' => $revision_id));
292
    }
293
    elseif ($this->revisionKey) {
294
      $query->join($this->revisionTable, 'revision', "revision.{$this->revisionKey} = base.{$this->revisionKey}");
295
    }
296

    
297
    // Add fields from the {entity} table.
298
    $entity_fields = $this->entityInfo['schema_fields_sql']['base table'];
299

    
300
    if ($this->revisionKey) {
301
      // Add all fields from the {entity_revision} table.
302
      $entity_revision_fields = drupal_map_assoc($this->entityInfo['schema_fields_sql']['revision table']);
303
      // The id field is provided by entity, so remove it.
304
      unset($entity_revision_fields[$this->idKey]);
305

    
306
      // Remove all fields from the base table that are also fields by the same
307
      // name in the revision table.
308
      $entity_field_keys = array_flip($entity_fields);
309
      foreach ($entity_revision_fields as $key => $name) {
310
        if (isset($entity_field_keys[$name])) {
311
          unset($entity_fields[$entity_field_keys[$name]]);
312
        }
313
      }
314
      $query->fields('revision', $entity_revision_fields);
315
    }
316

    
317
    $query->fields('base', $entity_fields);
318

    
319
    if ($ids) {
320
      $query->condition("base.{$this->idKey}", $ids, 'IN');
321
    }
322
    if ($conditions) {
323
      foreach ($conditions as $field => $value) {
324
        $query->condition('base.' . $field, $value);
325
      }
326
    }
327
    return $query;
328
  }
329

    
330
  /**
331
   * Attaches data to entities upon loading.
332
   *
333
   * This will attach fields, if the entity is fieldable. It calls
334
   * hook_entity_load() for modules which need to add data to all entities.
335
   * It also calls hook_TYPE_load() on the loaded entities. For example
336
   * hook_node_load() or hook_user_load(). If your hook_TYPE_load()
337
   * expects special parameters apart from the queried entities, you can set
338
   * $this->hookLoadArguments prior to calling the method.
339
   * See NodeController::attachLoad() for an example.
340
   *
341
   * @param $queried_entities
342
   *   Associative array of query results, keyed on the entity ID.
343
   * @param $revision_id
344
   *   ID of the revision that was loaded, or FALSE if the most current revision
345
   *   was loaded.
346
   */
347
  protected function attachLoad(&$queried_entities, $revision_id = FALSE) {
348
    // Attach fields.
349
    if ($this->entityInfo['fieldable']) {
350
      if ($revision_id) {
351
        field_attach_load_revision($this->entityType, $queried_entities);
352
      }
353
      else {
354
        field_attach_load($this->entityType, $queried_entities);
355
      }
356
    }
357

    
358
    // Call hook_entity_load().
359
    foreach (module_implements('entity_load') as $module) {
360
      $function = $module . '_entity_load';
361
      $function($queried_entities, $this->entityType);
362
    }
363
    // Call hook_TYPE_load(). The first argument for hook_TYPE_load() are
364
    // always the queried entities, followed by additional arguments set in
365
    // $this->hookLoadArguments.
366
    $args = array_merge(array($queried_entities), $this->hookLoadArguments);
367
    foreach (module_implements($this->entityInfo['load hook']) as $module) {
368
      call_user_func_array($module . '_' . $this->entityInfo['load hook'], $args);
369
    }
370
  }
371

    
372
  /**
373
   * Gets entities from the static cache.
374
   *
375
   * @param $ids
376
   *   If not empty, return entities that match these IDs.
377
   * @param $conditions
378
   *   If set, return entities that match all of these conditions.
379
   *
380
   * @return
381
   *   Array of entities from the entity cache.
382
   */
383
  protected function cacheGet($ids, $conditions = array()) {
384
    $entities = array();
385
    // Load any available entities from the internal cache.
386
    if (!empty($this->entityCache)) {
387
      if ($ids) {
388
        $entities += array_intersect_key($this->entityCache, array_flip($ids));
389
      }
390
      // If loading entities only by conditions, fetch all available entities
391
      // from the cache. Entities which don't match are removed later.
392
      elseif ($conditions) {
393
        $entities = $this->entityCache;
394
      }
395
    }
396

    
397
    // Exclude any entities loaded from cache if they don't match $conditions.
398
    // This ensures the same behavior whether loading from memory or database.
399
    if ($conditions) {
400
      foreach ($entities as $entity) {
401
        // Iterate over all conditions and compare them to the entity
402
        // properties. We cannot use array_diff_assoc() here since the
403
        // conditions can be nested arrays, too.
404
        foreach ($conditions as $property_name => $condition) {
405
          if (is_array($condition)) {
406
            // Multiple condition values for one property are treated as OR
407
            // operation: only if the value is not at all in the condition array
408
            // we remove the entity.
409
            if (!in_array($entity->{$property_name}, $condition)) {
410
              unset($entities[$entity->{$this->idKey}]);
411
              continue 2;
412
            }
413
          }
414
          elseif ($condition != $entity->{$property_name}) {
415
            unset($entities[$entity->{$this->idKey}]);
416
            continue 2;
417
          }
418
        }
419
      }
420
    }
421
    return $entities;
422
  }
423

    
424
  /**
425
   * Stores entities in the static entity cache.
426
   *
427
   * @param $entities
428
   *   Entities to store in the cache.
429
   */
430
  protected function cacheSet($entities) {
431
    $this->entityCache += $entities;
432
  }
433
}
434

    
435
/**
436
 * Exception thrown by EntityFieldQuery() on unsupported query syntax.
437
 *
438
 * Some storage modules might not support the full range of the syntax for
439
 * conditions, and will raise an EntityFieldQueryException when an unsupported
440
 * condition was specified.
441
 */
442
class EntityFieldQueryException extends Exception {}
443

    
444
/**
445
 * Retrieves entities matching a given set of conditions.
446
 *
447
 * This class allows finding entities based on entity properties (for example,
448
 * node->changed), field values, and generic entity meta data (bundle,
449
 * entity type, entity ID, and revision ID). It is not possible to query across
450
 * multiple entity types. For example, there is no facility to find published
451
 * nodes written by users created in the last hour, as this would require
452
 * querying both node->status and user->created.
453
 *
454
 * Normally we would not want to have public properties on the object, as that
455
 * allows the object's state to become inconsistent too easily. However, this
456
 * class's standard use case involves primarily code that does need to have
457
 * direct access to the collected properties in order to handle alternate
458
 * execution routines. We therefore use public properties for simplicity. Note
459
 * that code that is simply creating and running a field query should still use
460
 * the appropriate methods to add conditions on the query.
461
 *
462
 * Storage engines are not required to support every type of query. By default,
463
 * an EntityFieldQueryException will be raised if an unsupported condition is
464
 * specified or if the query has field conditions or sorts that are stored in
465
 * different field storage engines. However, this logic can be overridden in
466
 * hook_entity_query_alter().
467
 *
468
 * Also note that this query does not automatically respect entity access
469
 * restrictions. Node access control is performed by the SQL storage engine but
470
 * other storage engines might not do this.
471
 */
472
class EntityFieldQuery {
473

    
474
  /**
475
   * Indicates that both deleted and non-deleted fields should be returned.
476
   *
477
   * @see EntityFieldQuery::deleted()
478
   */
479
  const RETURN_ALL = NULL;
480

    
481
  /**
482
   * TRUE if the query has already been altered, FALSE if it hasn't.
483
   *
484
   * Used in alter hooks to check for cloned queries that have already been
485
   * altered prior to the clone (for example, the pager count query).
486
   *
487
   * @var boolean
488
   */
489
  public $altered = FALSE;
490

    
491
  /**
492
   * Associative array of entity-generic metadata conditions.
493
   *
494
   * @var array
495
   *
496
   * @see EntityFieldQuery::entityCondition()
497
   */
498
  public $entityConditions = array();
499

    
500
  /**
501
   * List of field conditions.
502
   *
503
   * @var array
504
   *
505
   * @see EntityFieldQuery::fieldCondition()
506
   */
507
  public $fieldConditions = array();
508

    
509
  /**
510
   * List of field meta conditions (language and delta).
511
   *
512
   * Field conditions operate on columns specified by hook_field_schema(),
513
   * the meta conditions operate on columns added by the system: delta
514
   * and language. These can not be mixed with the field conditions because
515
   * field columns can have any name including delta and language.
516
   *
517
   * @var array
518
   *
519
   * @see EntityFieldQuery::fieldLanguageCondition()
520
   * @see EntityFieldQuery::fieldDeltaCondition()
521
   */
522
  public $fieldMetaConditions = array();
523

    
524
  /**
525
   * List of property conditions.
526
   *
527
   * @var array
528
   *
529
   * @see EntityFieldQuery::propertyCondition()
530
   */
531
  public $propertyConditions = array();
532

    
533
  /**
534
   * List of order clauses.
535
   *
536
   * @var array
537
   */
538
  public $order = array();
539

    
540
  /**
541
   * The query range.
542
   *
543
   * @var array
544
   *
545
   * @see EntityFieldQuery::range()
546
   */
547
  public $range = array();
548

    
549
  /**
550
   * The query pager data.
551
   *
552
   * @var array
553
   *
554
   * @see EntityFieldQuery::pager()
555
   */
556
  public $pager = array();
557

    
558
  /**
559
   * Query behavior for deleted data.
560
   *
561
   * TRUE to return only deleted data, FALSE to return only non-deleted data,
562
   * EntityFieldQuery::RETURN_ALL to return everything.
563
   *
564
   * @see EntityFieldQuery::deleted()
565
   */
566
  public $deleted = FALSE;
567

    
568
  /**
569
   * A list of field arrays used.
570
   *
571
   * Field names passed to EntityFieldQuery::fieldCondition() and
572
   * EntityFieldQuery::fieldOrderBy() are run through field_info_field() before
573
   * stored in this array. This way, the elements of this array are field
574
   * arrays.
575
   *
576
   * @var array
577
   */
578
  public $fields = array();
579

    
580
  /**
581
   * TRUE if this is a count query, FALSE if it isn't.
582
   *
583
   * @var boolean
584
   */
585
  public $count = FALSE;
586

    
587
  /**
588
   * Flag indicating whether this is querying current or all revisions.
589
   *
590
   * @var int
591
   *
592
   * @see EntityFieldQuery::age()
593
   */
594
  public $age = FIELD_LOAD_CURRENT;
595

    
596
  /**
597
   * A list of the tags added to this query.
598
   *
599
   * @var array
600
   *
601
   * @see EntityFieldQuery::addTag()
602
   */
603
  public $tags = array();
604

    
605
  /**
606
   * A list of metadata added to this query.
607
   *
608
   * @var array
609
   *
610
   * @see EntityFieldQuery::addMetaData()
611
   */
612
  public $metaData = array();
613

    
614
  /**
615
   * The ordered results.
616
   *
617
   * @var array
618
   *
619
   * @see EntityFieldQuery::execute().
620
   */
621
  public $orderedResults = array();
622

    
623
  /**
624
   * The method executing the query, if it is overriding the default.
625
   *
626
   * @var string
627
   *
628
   * @see EntityFieldQuery::execute().
629
   */
630
  public $executeCallback = '';
631

    
632
  /**
633
   * Adds a condition on entity-generic metadata.
634
   *
635
   * If the overall query contains only entity conditions or ordering, or if
636
   * there are property conditions, then specifying the entity type is
637
   * mandatory. If there are field conditions or ordering but no property
638
   * conditions or ordering, then specifying an entity type is optional. While
639
   * the field storage engine might support field conditions on more than one
640
   * entity type, there is no way to query across multiple entity base tables by
641
   * default. To specify the entity type, pass in 'entity_type' for $name,
642
   * the type as a string for $value, and no $operator (it's disregarded).
643
   *
644
   * 'bundle', 'revision_id' and 'entity_id' have no such restrictions.
645
   *
646
   * Note: The "comment" entity type does not support bundle conditions.
647
   *
648
   * @param $name
649
   *   'entity_type', 'bundle', 'revision_id' or 'entity_id'.
650
   * @param $value
651
   *   The value for $name. In most cases, this is a scalar. For more complex
652
   *   options, it is an array. The meaning of each element in the array is
653
   *   dependent on $operator.
654
   * @param $operator
655
   *   Possible values:
656
   *   - '=', '<>', '>', '>=', '<', '<=', 'STARTS_WITH', 'CONTAINS': These
657
   *     operators expect $value to be a literal of the same type as the
658
   *     column.
659
   *   - 'IN', 'NOT IN': These operators expect $value to be an array of
660
   *     literals of the same type as the column.
661
   *   - 'BETWEEN': This operator expects $value to be an array of two literals
662
   *     of the same type as the column.
663
   *   The operator can be omitted, and will default to 'IN' if the value is an
664
   *   array, or to '=' otherwise.
665
   *
666
   * @return EntityFieldQuery
667
   *   The called object.
668
   */
669
  public function entityCondition($name, $value, $operator = NULL) {
670
    // The '!=' operator is deprecated in favour of the '<>' operator since the
671
    // latter is ANSI SQL compatible.
672
    if ($operator == '!=') {
673
      $operator = '<>';
674
    }
675
    $this->entityConditions[$name] = array(
676
      'value' => $value,
677
      'operator' => $operator,
678
    );
679
    return $this;
680
  }
681

    
682
  /**
683
   * Adds a condition on field values.
684
   *
685
   * Note that entities with empty field values will be excluded from the
686
   * EntityFieldQuery results when using this method.
687
   *
688
   * @param $field
689
   *   Either a field name or a field array.
690
   * @param $column
691
   *   The column that should hold the value to be matched, defined in the
692
   *   hook_field_schema() of this field. If this is omitted then all of the
693
   *   other parameters are ignored, except $field, and this call will just be
694
   *   adding a condition that says that the field has a value, rather than
695
   *   testing the value itself.
696
   * @param $value
697
   *   The value to test the column value against. In most cases, this is a
698
   *   scalar. For more complex options, it is an array. The meaning of each
699
   *   element in the array is dependent on $operator.
700
   * @param $operator
701
   *   The operator to be used to test the given value. The possible values are:
702
   *   - '=', '<>', '>', '>=', '<', '<=', 'STARTS_WITH', 'CONTAINS': These
703
   *     operators expect $value to be a literal of the same type as the
704
   *     column.
705
   *   - 'IN', 'NOT IN': These operators expect $value to be an array of
706
   *     literals of the same type as the column.
707
   *   - 'BETWEEN': This operator expects $value to be an array of two literals
708
   *     of the same type as the column.
709
   *   The operator can be omitted, and will default to 'IN' if the value is an
710
   *   array, or to '=' otherwise.
711
   * @param $delta_group
712
   *   An arbitrary identifier: conditions in the same group must have the same
713
   *   $delta_group. For example, let's presume a multivalue field which has
714
   *   two columns, 'color' and 'shape', and for entity ID 1, there are two
715
   *   values: red/square and blue/circle. Entity ID 1 does not have values
716
   *   corresponding to 'red circle'; however if you pass 'red' and 'circle' as
717
   *   conditions, it will appear in the results -- by default queries will run
718
   *   against any combination of deltas. By passing the conditions with the
719
   *   same $delta_group it will ensure that only values attached to the same
720
   *   delta are matched, and entity 1 would then be excluded from the results.
721
   * @param $language_group
722
   *   An arbitrary identifier: conditions in the same group must have the same
723
   *   $language_group.
724
   *
725
   * @return EntityFieldQuery
726
   *   The called object.
727
   *
728
   * @see EntityFieldQuery::addFieldCondition
729
   * @see EntityFieldQuery::deleted
730
   */
731
  public function fieldCondition($field, $column = NULL, $value = NULL, $operator = NULL, $delta_group = NULL, $language_group = NULL) {
732
    return $this->addFieldCondition($this->fieldConditions, $field, $column, $value, $operator, $delta_group, $language_group);
733
  }
734

    
735
  /**
736
   * Adds a condition on the field language column.
737
   *
738
   * @param $field
739
   *   Either a field name or a field array.
740
   * @param $value
741
   *   The value to test the column value against.
742
   * @param $operator
743
   *   The operator to be used to test the given value.
744
   * @param $delta_group
745
   *   An arbitrary identifier: conditions in the same group must have the same
746
   *   $delta_group.
747
   * @param $language_group
748
   *   An arbitrary identifier: conditions in the same group must have the same
749
   *   $language_group.
750
   *
751
   * @return EntityFieldQuery
752
   *   The called object.
753
   *
754
   * @see EntityFieldQuery::addFieldCondition
755
   * @see EntityFieldQuery::deleted
756
   */
757
  public function fieldLanguageCondition($field, $value = NULL, $operator = NULL, $delta_group = NULL, $language_group = NULL) {
758
    return $this->addFieldCondition($this->fieldMetaConditions, $field, 'language', $value, $operator, $delta_group, $language_group);
759
  }
760

    
761
  /**
762
   * Adds a condition on the field delta column.
763
   *
764
   * @param $field
765
   *   Either a field name or a field array.
766
   * @param $value
767
   *   The value to test the column value against.
768
   * @param $operator
769
   *   The operator to be used to test the given value.
770
   * @param $delta_group
771
   *   An arbitrary identifier: conditions in the same group must have the same
772
   *   $delta_group.
773
   * @param $language_group
774
   *   An arbitrary identifier: conditions in the same group must have the same
775
   *   $language_group.
776
   *
777
   * @return EntityFieldQuery
778
   *   The called object.
779
   *
780
   * @see EntityFieldQuery::addFieldCondition
781
   * @see EntityFieldQuery::deleted
782
   */
783
  public function fieldDeltaCondition($field, $value = NULL, $operator = NULL, $delta_group = NULL, $language_group = NULL) {
784
    return $this->addFieldCondition($this->fieldMetaConditions, $field, 'delta', $value, $operator, $delta_group, $language_group);
785
  }
786

    
787
  /**
788
   * Adds the given condition to the proper condition array.
789
   *
790
   * @param $conditions
791
   *   A reference to an array of conditions.
792
   * @param $field
793
   *   Either a field name or a field array.
794
   * @param $column
795
   *   The column that should hold the value to be matched, defined in the
796
   *   hook_field_schema() of this field. If this is omitted then all of the
797
   *   other parameters are ignored, except $field, and this call will just be
798
   *   adding a condition that says that the field has a value, rather than
799
   *   testing the value itself.
800
   * @param $value
801
   *   The value to test the column value against. In most cases, this is a
802
   *   scalar. For more complex options, it is an array. The meaning of each
803
   *   element in the array is dependent on $operator.
804
   * @param $operator
805
   *   Possible values:
806
   *   - '=', '<>', '>', '>=', '<', '<=', 'STARTS_WITH', 'CONTAINS': These
807
   *     operators expect $value to be a literal of the same type as the
808
   *     column.
809
   *   - 'IN', 'NOT IN': These operators expect $value to be an array of
810
   *     literals of the same type as the column.
811
   *   - 'BETWEEN': This operator expects $value to be an array of two literals
812
   *     of the same type as the column.
813
   *   The operator can be omitted, and will default to 'IN' if the value is an
814
   *   array, or to '=' otherwise.
815
   * @param $delta_group
816
   *   An arbitrary identifier: conditions in the same group must have the same
817
   *   $delta_group. For example, let's presume a multivalue field which has
818
   *   two columns, 'color' and 'shape', and for entity ID 1, there are two
819
   *   values: red/square and blue/circle. Entity ID 1 does not have values
820
   *   corresponding to 'red circle', however if you pass 'red' and 'circle' as
821
   *   conditions, it will appear in the results -- by default queries will run
822
   *   against any combination of deltas. By passing the conditions with the
823
   *   same $delta_group it will ensure that only values attached to the same
824
   *   delta are matched, and entity 1 would then be excluded from the results.
825
   * @param $language_group
826
   *   An arbitrary identifier: conditions in the same group must have the same
827
   *   $language_group.
828
   *
829
   * @return EntityFieldQuery
830
   *   The called object.
831
   */
832
  protected function addFieldCondition(&$conditions, $field, $column = NULL, $value = NULL, $operator = NULL, $delta_group = NULL, $language_group = NULL) {
833
    // The '!=' operator is deprecated in favour of the '<>' operator since the
834
    // latter is ANSI SQL compatible.
835
    if ($operator == '!=') {
836
      $operator = '<>';
837
    }
838
    if (is_scalar($field)) {
839
      $field_definition = field_info_field($field);
840
      if (empty($field_definition)) {
841
        throw new EntityFieldQueryException(t('Unknown field: @field_name', array('@field_name' => $field)));
842
      }
843
      $field = $field_definition;
844
    }
845
    // Ensure the same index is used for field conditions as for fields.
846
    $index = count($this->fields);
847
    $this->fields[$index] = $field;
848
    if (isset($column)) {
849
      $conditions[$index] = array(
850
        'field' => $field,
851
        'column' => $column,
852
        'value' => $value,
853
        'operator' => $operator,
854
        'delta_group' => $delta_group,
855
        'language_group' => $language_group,
856
      );
857
    }
858
    return $this;
859
  }
860

    
861
  /**
862
   * Adds a condition on an entity-specific property.
863
   *
864
   * An $entity_type must be specified by calling
865
   * EntityFieldCondition::entityCondition('entity_type', $entity_type) before
866
   * executing the query. Also, by default only entities stored in SQL are
867
   * supported; however, EntityFieldQuery::executeCallback can be set to handle
868
   * different entity storage.
869
   *
870
   * @param $column
871
   *   A column defined in the hook_schema() of the base table of the entity.
872
   * @param $value
873
   *   The value to test the field against. In most cases, this is a scalar. For
874
   *   more complex options, it is an array. The meaning of each element in the
875
   *   array is dependent on $operator.
876
   * @param $operator
877
   *   Possible values:
878
   *   - '=', '<>', '>', '>=', '<', '<=', 'STARTS_WITH', 'CONTAINS': These
879
   *     operators expect $value to be a literal of the same type as the
880
   *     column.
881
   *   - 'IN', 'NOT IN': These operators expect $value to be an array of
882
   *     literals of the same type as the column.
883
   *   - 'BETWEEN': This operator expects $value to be an array of two literals
884
   *     of the same type as the column.
885
   *   The operator can be omitted, and will default to 'IN' if the value is an
886
   *   array, or to '=' otherwise.
887
   *
888
   * @return EntityFieldQuery
889
   *   The called object.
890
   */
891
  public function propertyCondition($column, $value, $operator = NULL) {
892
    // The '!=' operator is deprecated in favour of the '<>' operator since the
893
    // latter is ANSI SQL compatible.
894
    if ($operator == '!=') {
895
      $operator = '<>';
896
    }
897
    $this->propertyConditions[] = array(
898
      'column' => $column,
899
      'value' => $value,
900
      'operator' => $operator,
901
    );
902
    return $this;
903
  }
904

    
905
  /**
906
   * Orders the result set by entity-generic metadata.
907
   *
908
   * If called multiple times, the query will order by each specified column in
909
   * the order this method is called.
910
   *
911
   * Note: The "comment" and "taxonomy_term" entity types don't support ordering
912
   * by bundle. For "taxonomy_term", propertyOrderBy('vid') can be used instead.
913
   *
914
   * @param $name
915
   *   'entity_type', 'bundle', 'revision_id' or 'entity_id'.
916
   * @param $direction
917
   *   The direction to sort. Legal values are "ASC" and "DESC".
918
   *
919
   * @return EntityFieldQuery
920
   *   The called object.
921
   */
922
  public function entityOrderBy($name, $direction = 'ASC') {
923
    $this->order[] = array(
924
      'type' => 'entity',
925
      'specifier' => $name,
926
      'direction' => $direction,
927
    );
928
    return $this;
929
  }
930

    
931
  /**
932
   * Orders the result set by a given field column.
933
   *
934
   * If called multiple times, the query will order by each specified column in
935
   * the order this method is called. Note that entities with empty field
936
   * values will be excluded from the EntityFieldQuery results when using this
937
   * method.
938
   *
939
   * @param $field
940
   *   Either a field name or a field array.
941
   * @param $column
942
   *   A column defined in the hook_field_schema() of this field. entity_id and
943
   *   bundle can also be used.
944
   * @param $direction
945
   *   The direction to sort. Legal values are "ASC" and "DESC".
946
   *
947
   * @return EntityFieldQuery
948
   *   The called object.
949
   */
950
  public function fieldOrderBy($field, $column, $direction = 'ASC') {
951
    if (is_scalar($field)) {
952
      $field_definition = field_info_field($field);
953
      if (empty($field_definition)) {
954
        throw new EntityFieldQueryException(t('Unknown field: @field_name', array('@field_name' => $field)));
955
      }
956
      $field = $field_definition;
957
    }
958
    // Save the index used for the new field, for later use in field storage.
959
    $index = count($this->fields);
960
    $this->fields[$index] = $field;
961
    $this->order[] = array(
962
      'type' => 'field',
963
      'specifier' => array(
964
        'field' => $field,
965
        'index' => $index,
966
        'column' => $column,
967
      ),
968
      'direction' => $direction,
969
    );
970
    return $this;
971
  }
972

    
973
  /**
974
   * Orders the result set by an entity-specific property.
975
   *
976
   * An $entity_type must be specified by calling
977
   * EntityFieldCondition::entityCondition('entity_type', $entity_type) before
978
   * executing the query.
979
   *
980
   * If called multiple times, the query will order by each specified column in
981
   * the order this method is called.
982
   *
983
   * @param $column
984
   *   The column on which to order.
985
   * @param $direction
986
   *   The direction to sort. Legal values are "ASC" and "DESC".
987
   *
988
   * @return EntityFieldQuery
989
   *   The called object.
990
   */
991
  public function propertyOrderBy($column, $direction = 'ASC') {
992
    $this->order[] = array(
993
      'type' => 'property',
994
      'specifier' => $column,
995
      'direction' => $direction,
996
    );
997
    return $this;
998
  }
999

    
1000
  /**
1001
   * Sets the query to be a count query only.
1002
   *
1003
   * @return EntityFieldQuery
1004
   *   The called object.
1005
   */
1006
  public function count() {
1007
    $this->count = TRUE;
1008
    return $this;
1009
  }
1010

    
1011
  /**
1012
   * Restricts a query to a given range in the result set.
1013
   *
1014
   * @param $start
1015
   *   The first entity from the result set to return. If NULL, removes any
1016
   *   range directives that are set.
1017
   * @param $length
1018
   *   The number of entities to return from the result set.
1019
   *
1020
   * @return EntityFieldQuery
1021
   *   The called object.
1022
   */
1023
  public function range($start = NULL, $length = NULL) {
1024
    $this->range = array(
1025
      'start' => $start,
1026
      'length' => $length,
1027
    );
1028
    return $this;
1029
  }
1030

    
1031
  /**
1032
   * Enables a pager for the query.
1033
   *
1034
   * @param $limit
1035
   *   An integer specifying the number of elements per page.  If passed a false
1036
   *   value (FALSE, 0, NULL), the pager is disabled.
1037
   * @param $element
1038
   *   An optional integer to distinguish between multiple pagers on one page.
1039
   *   If not provided, one is automatically calculated.
1040
   *
1041
   * @return EntityFieldQuery
1042
   *   The called object.
1043
   */
1044
  public function pager($limit = 10, $element = NULL) {
1045
    if (!isset($element)) {
1046
      $element = PagerDefault::$maxElement++;
1047
    }
1048
    elseif ($element >= PagerDefault::$maxElement) {
1049
      PagerDefault::$maxElement = $element + 1;
1050
    }
1051

    
1052
    $this->pager = array(
1053
      'limit' => $limit,
1054
      'element' => $element,
1055
    );
1056
    return $this;
1057
  }
1058

    
1059
  /**
1060
   * Enables sortable tables for this query.
1061
   *
1062
   * @param $headers
1063
   *   An EFQ Header array based on which the order clause is added to the
1064
   *   query.
1065
   *
1066
   * @return EntityFieldQuery
1067
   *   The called object.
1068
   */
1069
  public function tableSort(&$headers) {
1070
    // If 'field' is not initialized, the header columns aren't clickable
1071
    foreach ($headers as $key =>$header) {
1072
      if (is_array($header) && isset($header['specifier'])) {
1073
        $headers[$key]['field'] = '';
1074
      }
1075
    }
1076

    
1077
    $order = tablesort_get_order($headers);
1078
    $direction = tablesort_get_sort($headers);
1079
    foreach ($headers as $header) {
1080
      if (is_array($header) && ($header['data'] == $order['name'])) {
1081
        if ($header['type'] == 'field') {
1082
          $this->fieldOrderBy($header['specifier']['field'], $header['specifier']['column'], $direction);
1083
        }
1084
        else {
1085
          $header['direction'] = $direction;
1086
          $this->order[] = $header;
1087
        }
1088
      }
1089
    }
1090

    
1091
    return $this;
1092
  }
1093

    
1094
  /**
1095
   * Filters on the data being deleted.
1096
   *
1097
   * @param $deleted
1098
   *   TRUE to only return deleted data, FALSE to return non-deleted data,
1099
   *   EntityFieldQuery::RETURN_ALL to return everything. Defaults to FALSE.
1100
   *
1101
   * @return EntityFieldQuery
1102
   *   The called object.
1103
   */
1104
  public function deleted($deleted = TRUE) {
1105
    $this->deleted = $deleted;
1106
    return $this;
1107
  }
1108

    
1109
  /**
1110
   * Queries the current or every revision.
1111
   *
1112
   * Note that this only affects field conditions. Property conditions always
1113
   * apply to the current revision.
1114
   * @TODO: Once revision tables have been cleaned up, revisit this.
1115
   *
1116
   * @param $age
1117
   *   - FIELD_LOAD_CURRENT (default): Query the most recent revisions for all
1118
   *     entities. The results will be keyed by entity type and entity ID.
1119
   *   - FIELD_LOAD_REVISION: Query all revisions. The results will be keyed by
1120
   *     entity type and entity revision ID.
1121
   *
1122
   * @return EntityFieldQuery
1123
   *   The called object.
1124
   */
1125
  public function age($age) {
1126
    $this->age = $age;
1127
    return $this;
1128
  }
1129

    
1130
  /**
1131
   * Adds a tag to the query.
1132
   *
1133
   * Tags are strings that mark a query so that hook_query_alter() and
1134
   * hook_query_TAG_alter() implementations may decide if they wish to alter
1135
   * the query. A query may have any number of tags, and they must be valid PHP
1136
   * identifiers (composed of letters, numbers, and underscores). For example,
1137
   * queries involving nodes that will be displayed for a user need to add the
1138
   * tag 'node_access', so that the node module can add access restrictions to
1139
   * the query.
1140
   *
1141
   * If an entity field query has tags, it must also have an entity type
1142
   * specified, because the alter hook will need the entity base table.
1143
   *
1144
   * @param string $tag
1145
   *   The tag to add.
1146
   *
1147
   * @return EntityFieldQuery
1148
   *   The called object.
1149
   */
1150
  public function addTag($tag) {
1151
    $this->tags[$tag] = $tag;
1152
    return $this;
1153
  }
1154

    
1155
  /**
1156
   * Adds additional metadata to the query.
1157
   *
1158
   * Sometimes a query may need to provide additional contextual data for the
1159
   * alter hook. The alter hook implementations may then use that information
1160
   * to decide if and how to take action.
1161
   *
1162
   * @param $key
1163
   *   The unique identifier for this piece of metadata. Must be a string that
1164
   *   follows the same rules as any other PHP identifier.
1165
   * @param $object
1166
   *   The additional data to add to the query. May be any valid PHP variable.
1167
   *
1168
   * @return EntityFieldQuery
1169
   *   The called object.
1170
   */
1171
  public function addMetaData($key, $object) {
1172
    $this->metaData[$key] = $object;
1173
    return $this;
1174
  }
1175

    
1176
  /**
1177
   * Executes the query.
1178
   *
1179
   * After executing the query, $this->orderedResults will contain a list of
1180
   * the same stub entities in the order returned by the query. This is only
1181
   * relevant if there are multiple entity types in the returned value and
1182
   * a field ordering was requested. In every other case, the returned value
1183
   * contains everything necessary for processing.
1184
   *
1185
   * @return
1186
   *   Either a number if count() was called or an array of associative arrays
1187
   *   of stub entities. The outer array keys are entity types, and the inner
1188
   *   array keys are the relevant ID. (In most cases this will be the entity
1189
   *   ID. The only exception is when age=FIELD_LOAD_REVISION is used and field
1190
   *   conditions or sorts are present -- in this case, the key will be the
1191
   *   revision ID.) The entity type will only exist in the outer array if
1192
   *   results were found. The inner array values are always stub entities, as
1193
   *   returned by entity_create_stub_entity(). To traverse the returned array:
1194
   *   @code
1195
   *     foreach ($query->execute() as $entity_type => $entities) {
1196
   *       foreach ($entities as $entity_id => $entity) {
1197
   *   @endcode
1198
   *   Note if the entity type is known, then the following snippet will load
1199
   *   the entities found:
1200
   *   @code
1201
   *     $result = $query->execute();
1202
   *     if (!empty($result[$my_type])) {
1203
   *       $entities = entity_load($my_type, array_keys($result[$my_type]));
1204
   *     }
1205
   *   @endcode
1206
   */
1207
  public function execute() {
1208
    // Give a chance to other modules to alter the query.
1209
    drupal_alter('entity_query', $this);
1210
    $this->altered = TRUE;
1211

    
1212
    // Initialize the pager.
1213
    $this->initializePager();
1214

    
1215
    // Execute the query using the correct callback.
1216
    $result = call_user_func($this->queryCallback(), $this);
1217

    
1218
    return $result;
1219
  }
1220

    
1221
  /**
1222
   * Determines the query callback to use for this entity query.
1223
   *
1224
   * @return
1225
   *   A callback that can be used with call_user_func().
1226
   */
1227
  public function queryCallback() {
1228
    // Use the override from $this->executeCallback. It can be set either
1229
    // while building the query, or using hook_entity_query_alter().
1230
    if (function_exists($this->executeCallback)) {
1231
      return $this->executeCallback;
1232
    }
1233
    // If there are no field conditions and sorts, and no execute callback
1234
    // then we default to querying entity tables in SQL.
1235
    if (empty($this->fields)) {
1236
      return array($this, 'propertyQuery');
1237
    }
1238
    // If no override, find the storage engine to be used.
1239
    foreach ($this->fields as $field) {
1240
      if (!isset($storage)) {
1241
        $storage = $field['storage']['module'];
1242
      }
1243
      elseif ($storage != $field['storage']['module']) {
1244
        throw new EntityFieldQueryException(t("Can't handle more than one field storage engine"));
1245
      }
1246
    }
1247
    if ($storage) {
1248
      // Use hook_field_storage_query() from the field storage.
1249
      return $storage . '_field_storage_query';
1250
    }
1251
    else {
1252
      throw new EntityFieldQueryException(t("Field storage engine not found."));
1253
    }
1254
  }
1255

    
1256
  /**
1257
   * Queries entity tables in SQL for property conditions and sorts.
1258
   *
1259
   * This method is only used if there are no field conditions and sorts.
1260
   *
1261
   * @return
1262
   *   See EntityFieldQuery::execute().
1263
   */
1264
  protected function propertyQuery() {
1265
    if (empty($this->entityConditions['entity_type'])) {
1266
      throw new EntityFieldQueryException(t('For this query an entity type must be specified.'));
1267
    }
1268
    $entity_type = $this->entityConditions['entity_type']['value'];
1269
    $entity_info = entity_get_info($entity_type);
1270
    if (empty($entity_info['base table'])) {
1271
      throw new EntityFieldQueryException(t('Entity %entity has no base table.', array('%entity' => $entity_type)));
1272
    }
1273
    $base_table = $entity_info['base table'];
1274
    $base_table_schema = drupal_get_schema($base_table);
1275
    $select_query = db_select($base_table);
1276
    $select_query->addExpression(':entity_type', 'entity_type', array(':entity_type' => $entity_type));
1277
    // Process the property conditions.
1278
    foreach ($this->propertyConditions as $property_condition) {
1279
      $this->addCondition($select_query, $base_table . '.' . $property_condition['column'], $property_condition);
1280
    }
1281
    // Process the four possible entity condition.
1282
    // The id field is always present in entity keys.
1283
    $sql_field = $entity_info['entity keys']['id'];
1284
    $id_map['entity_id'] = $sql_field;
1285
    $select_query->addField($base_table, $sql_field, 'entity_id');
1286
    if (isset($this->entityConditions['entity_id'])) {
1287
      $this->addCondition($select_query, $base_table . '.' . $sql_field, $this->entityConditions['entity_id']);
1288
    }
1289

    
1290
    // If there is a revision key defined, use it.
1291
    if (!empty($entity_info['entity keys']['revision'])) {
1292
      $sql_field = $entity_info['entity keys']['revision'];
1293
      $select_query->addField($base_table, $sql_field, 'revision_id');
1294
      if (isset($this->entityConditions['revision_id'])) {
1295
        $this->addCondition($select_query, $base_table . '.' . $sql_field, $this->entityConditions['revision_id']);
1296
      }
1297
    }
1298
    else {
1299
      $sql_field = 'revision_id';
1300
      $select_query->addExpression('NULL', 'revision_id');
1301
    }
1302
    $id_map['revision_id'] = $sql_field;
1303

    
1304
    // Handle bundles.
1305
    if (!empty($entity_info['entity keys']['bundle'])) {
1306
      $sql_field = $entity_info['entity keys']['bundle'];
1307
      $having = FALSE;
1308

    
1309
      if (!empty($base_table_schema['fields'][$sql_field])) {
1310
        $select_query->addField($base_table, $sql_field, 'bundle');
1311
      }
1312
    }
1313
    else {
1314
      $sql_field = 'bundle';
1315
      $select_query->addExpression(':bundle', 'bundle', array(':bundle' => $entity_type));
1316
      $having = TRUE;
1317
    }
1318
    $id_map['bundle'] = $sql_field;
1319
    if (isset($this->entityConditions['bundle'])) {
1320
      if (!empty($entity_info['entity keys']['bundle'])) {
1321
        $this->addCondition($select_query, $base_table . '.' . $sql_field, $this->entityConditions['bundle'], $having);
1322
      }
1323
      else {
1324
        // This entity has no bundle, so invalidate the query.
1325
        $select_query->where('1 = 0');
1326
      }
1327
    }
1328

    
1329
    // Order the query.
1330
    foreach ($this->order as $order) {
1331
      if ($order['type'] == 'entity') {
1332
        $key = $order['specifier'];
1333
        if (!isset($id_map[$key])) {
1334
          throw new EntityFieldQueryException(t('Do not know how to order on @key for @entity_type', array('@key' => $key, '@entity_type' => $entity_type)));
1335
        }
1336
        $select_query->orderBy($id_map[$key], $order['direction']);
1337
      }
1338
      elseif ($order['type'] == 'property') {
1339
        $select_query->orderBy($base_table . '.' . $order['specifier'], $order['direction']);
1340
      }
1341
    }
1342

    
1343
    return $this->finishQuery($select_query);
1344
  }
1345

    
1346
  /**
1347
   * Gets the total number of results and initializes a pager for the query.
1348
   *
1349
   * The pager can be disabled by either setting the pager limit to 0, or by
1350
   * setting this query to be a count query.
1351
   */
1352
  function initializePager() {
1353
    if ($this->pager && !empty($this->pager['limit']) && !$this->count) {
1354
      $page = pager_find_page($this->pager['element']);
1355
      $count_query = clone $this;
1356
      $this->pager['total'] = $count_query->count()->execute();
1357
      $this->pager['start'] = $page * $this->pager['limit'];
1358
      pager_default_initialize($this->pager['total'], $this->pager['limit'], $this->pager['element']);
1359
      $this->range($this->pager['start'], $this->pager['limit']);
1360
    }
1361
  }
1362

    
1363
  /**
1364
   * Finishes the query.
1365
   *
1366
   * Adds tags, metaData, range and returns the requested list or count.
1367
   *
1368
   * @param SelectQuery $select_query
1369
   *   A SelectQuery which has entity_type, entity_id, revision_id and bundle
1370
   *   fields added.
1371
   * @param $id_key
1372
   *   Which field's values to use as the returned array keys.
1373
   *
1374
   * @return
1375
   *   See EntityFieldQuery::execute().
1376
   */
1377
  function finishQuery($select_query, $id_key = 'entity_id') {
1378
    foreach ($this->tags as $tag) {
1379
      $select_query->addTag($tag);
1380
    }
1381
    foreach ($this->metaData as $key => $object) {
1382
      $select_query->addMetaData($key, $object);
1383
    }
1384
    $select_query->addMetaData('entity_field_query', $this);
1385
    if ($this->range) {
1386
      $select_query->range($this->range['start'], $this->range['length']);
1387
    }
1388
    if ($this->count) {
1389
      return $select_query->countQuery()->execute()->fetchField();
1390
    }
1391
    $return = array();
1392
    foreach ($select_query->execute() as $partial_entity) {
1393
      $bundle = isset($partial_entity->bundle) ? $partial_entity->bundle : NULL;
1394
      $entity = entity_create_stub_entity($partial_entity->entity_type, array($partial_entity->entity_id, $partial_entity->revision_id, $bundle));
1395
      $return[$partial_entity->entity_type][$partial_entity->$id_key] = $entity;
1396
      $this->ordered_results[] = $partial_entity;
1397
    }
1398
    return $return;
1399
  }
1400

    
1401
  /**
1402
   * Adds a condition to an already built SelectQuery (internal function).
1403
   *
1404
   * This is a helper for hook_entity_query() and hook_field_storage_query().
1405
   *
1406
   * @param SelectQuery $select_query
1407
   *   A SelectQuery object.
1408
   * @param $sql_field
1409
   *   The name of the field.
1410
   * @param $condition
1411
   *   A condition as described in EntityFieldQuery::fieldCondition() and
1412
   *   EntityFieldQuery::entityCondition().
1413
   * @param $having
1414
   *   HAVING or WHERE. This is necessary because SQL can't handle WHERE
1415
   *   conditions on aliased columns.
1416
   */
1417
  public function addCondition(SelectQuery $select_query, $sql_field, $condition, $having = FALSE) {
1418
    $method = $having ? 'havingCondition' : 'condition';
1419
    $like_prefix = '';
1420
    switch ($condition['operator']) {
1421
      case 'CONTAINS':
1422
        $like_prefix = '%';
1423
      case 'STARTS_WITH':
1424
        $select_query->$method($sql_field, $like_prefix . db_like($condition['value']) . '%', 'LIKE');
1425
        break;
1426
      default:
1427
        $select_query->$method($sql_field, $condition['value'], $condition['operator']);
1428
    }
1429
  }
1430

    
1431
}
1432

    
1433
/**
1434
 * Defines an exception thrown when a malformed entity is passed.
1435
 */
1436
class EntityMalformedException extends Exception { }