Projet

Général

Profil

Paste
Télécharger (45 ko) Statistiques
| Branche: | Révision:

root / htmltest / includes / entity.inc @ 85ad3d82

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 in the form 'field' => $value.
32
   *
33
   * @return
34
   *   An array of entity objects indexed by their ids. When no results are
35
   *   found, an empty array is returned.
36
   */
37
  public function load($ids = array(), $conditions = array());
38
}
39

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

    
48
  /**
49
   * Static cache of entities.
50
   *
51
   * @var array
52
   */
53
  protected $entityCache;
54

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
195
    // Pass all entities loaded from the database through $this->attachLoad(),
196
    // which attaches fields (if supported by the entity type) and calls the
197
    // entity type specific load callback, for example hook_node_load().
198
    if (!empty($queried_entities)) {
199
      $this->attachLoad($queried_entities, $revision_id);
200
      $entities += $queried_entities;
201
    }
202

    
203
    if ($this->cache) {
204
      // Add entities to the cache if we are not loading a revision.
205
      if (!empty($queried_entities) && !$revision_id) {
206
        $this->cacheSet($queried_entities);
207
      }
208
    }
209

    
210
    // Ensure that the returned array is ordered the same as the original
211
    // $ids array if this was passed in and remove any invalid ids.
212
    if ($passed_ids) {
213
      // Remove any invalid ids from the array.
214
      $passed_ids = array_intersect_key($passed_ids, $entities);
215
      foreach ($entities as $entity) {
216
        $passed_ids[$entity->{$this->idKey}] = $entity;
217
      }
218
      $entities = $passed_ids;
219
    }
220

    
221
    return $entities;
222
  }
223

    
224
  /**
225
   * Builds the query to load the entity.
226
   *
227
   * This has full revision support. For entities requiring special queries,
228
   * the class can be extended, and the default query can be constructed by
229
   * calling parent::buildQuery(). This is usually necessary when the object
230
   * being loaded needs to be augmented with additional data from another
231
   * table, such as loading node type into comments or vocabulary machine name
232
   * into terms, however it can also support $conditions on different tables.
233
   * See CommentController::buildQuery() or TaxonomyTermController::buildQuery()
234
   * for examples.
235
   *
236
   * @param $ids
237
   *   An array of entity IDs, or FALSE to load all entities.
238
   * @param $conditions
239
   *   An array of conditions in the form 'field' => $value.
240
   * @param $revision_id
241
   *   The ID of the revision to load, or FALSE if this query is asking for the
242
   *   most current revision(s).
243
   *
244
   * @return SelectQuery
245
   *   A SelectQuery object for loading the entity.
246
   */
247
  protected function buildQuery($ids, $conditions = array(), $revision_id = FALSE) {
248
    $query = db_select($this->entityInfo['base table'], 'base');
249

    
250
    $query->addTag($this->entityType . '_load_multiple');
251

    
252
    if ($revision_id) {
253
      $query->join($this->revisionTable, 'revision', "revision.{$this->idKey} = base.{$this->idKey} AND revision.{$this->revisionKey} = :revisionId", array(':revisionId' => $revision_id));
254
    }
255
    elseif ($this->revisionKey) {
256
      $query->join($this->revisionTable, 'revision', "revision.{$this->revisionKey} = base.{$this->revisionKey}");
257
    }
258

    
259
    // Add fields from the {entity} table.
260
    $entity_fields = $this->entityInfo['schema_fields_sql']['base table'];
261

    
262
    if ($this->revisionKey) {
263
      // Add all fields from the {entity_revision} table.
264
      $entity_revision_fields = drupal_map_assoc($this->entityInfo['schema_fields_sql']['revision table']);
265
      // The id field is provided by entity, so remove it.
266
      unset($entity_revision_fields[$this->idKey]);
267

    
268
      // Remove all fields from the base table that are also fields by the same
269
      // name in the revision table.
270
      $entity_field_keys = array_flip($entity_fields);
271
      foreach ($entity_revision_fields as $key => $name) {
272
        if (isset($entity_field_keys[$name])) {
273
          unset($entity_fields[$entity_field_keys[$name]]);
274
        }
275
      }
276
      $query->fields('revision', $entity_revision_fields);
277
    }
278

    
279
    $query->fields('base', $entity_fields);
280

    
281
    if ($ids) {
282
      $query->condition("base.{$this->idKey}", $ids, 'IN');
283
    }
284
    if ($conditions) {
285
      foreach ($conditions as $field => $value) {
286
        $query->condition('base.' . $field, $value);
287
      }
288
    }
289
    return $query;
290
  }
291

    
292
  /**
293
   * Attaches data to entities upon loading.
294
   *
295
   * This will attach fields, if the entity is fieldable. It calls
296
   * hook_entity_load() for modules which need to add data to all entities.
297
   * It also calls hook_TYPE_load() on the loaded entities. For example
298
   * hook_node_load() or hook_user_load(). If your hook_TYPE_load()
299
   * expects special parameters apart from the queried entities, you can set
300
   * $this->hookLoadArguments prior to calling the method.
301
   * See NodeController::attachLoad() for an example.
302
   *
303
   * @param $queried_entities
304
   *   Associative array of query results, keyed on the entity ID.
305
   * @param $revision_id
306
   *   ID of the revision that was loaded, or FALSE if the most current revision
307
   *   was loaded.
308
   */
309
  protected function attachLoad(&$queried_entities, $revision_id = FALSE) {
310
    // Attach fields.
311
    if ($this->entityInfo['fieldable']) {
312
      if ($revision_id) {
313
        field_attach_load_revision($this->entityType, $queried_entities);
314
      }
315
      else {
316
        field_attach_load($this->entityType, $queried_entities);
317
      }
318
    }
319

    
320
    // Call hook_entity_load().
321
    foreach (module_implements('entity_load') as $module) {
322
      $function = $module . '_entity_load';
323
      $function($queried_entities, $this->entityType);
324
    }
325
    // Call hook_TYPE_load(). The first argument for hook_TYPE_load() are
326
    // always the queried entities, followed by additional arguments set in
327
    // $this->hookLoadArguments.
328
    $args = array_merge(array($queried_entities), $this->hookLoadArguments);
329
    foreach (module_implements($this->entityInfo['load hook']) as $module) {
330
      call_user_func_array($module . '_' . $this->entityInfo['load hook'], $args);
331
    }
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

    
359
    // Exclude any entities loaded from cache if they don't match $conditions.
360
    // This ensures the same behavior whether loading from memory or database.
361
    if ($conditions) {
362
      foreach ($entities as $entity) {
363
        $entity_values = (array) $entity;
364
        if (array_diff_assoc($conditions, $entity_values)) {
365
          unset($entities[$entity->{$this->idKey}]);
366
        }
367
      }
368
    }
369
    return $entities;
370
  }
371

    
372
  /**
373
   * Stores entities in the static entity cache.
374
   *
375
   * @param $entities
376
   *   Entities to store in the cache.
377
   */
378
  protected function cacheSet($entities) {
379
    $this->entityCache += $entities;
380
  }
381
}
382

    
383
/**
384
 * Exception thrown by EntityFieldQuery() on unsupported query syntax.
385
 *
386
 * Some storage modules might not support the full range of the syntax for
387
 * conditions, and will raise an EntityFieldQueryException when an unsupported
388
 * condition was specified.
389
 */
390
class EntityFieldQueryException extends Exception {}
391

    
392
/**
393
 * Retrieves entities matching a given set of conditions.
394
 *
395
 * This class allows finding entities based on entity properties (for example,
396
 * node->changed), field values, and generic entity meta data (bundle,
397
 * entity type, entity id, and revision ID). It is not possible to query across
398
 * multiple entity types. For example, there is no facility to find published
399
 * nodes written by users created in the last hour, as this would require
400
 * querying both node->status and user->created.
401
 *
402
 * Normally we would not want to have public properties on the object, as that
403
 * allows the object's state to become inconsistent too easily. However, this
404
 * class's standard use case involves primarily code that does need to have
405
 * direct access to the collected properties in order to handle alternate
406
 * execution routines. We therefore use public properties for simplicity. Note
407
 * that code that is simply creating and running a field query should still use
408
 * the appropriate methods to add conditions on the query.
409
 *
410
 * Storage engines are not required to support every type of query. By default,
411
 * an EntityFieldQueryException will be raised if an unsupported condition is
412
 * specified or if the query has field conditions or sorts that are stored in
413
 * different field storage engines. However, this logic can be overridden in
414
 * hook_entity_query_alter().
415
 *
416
 * Also note that this query does not automatically respect entity access
417
 * restrictions. Node access control is performed by the SQL storage engine but
418
 * other storage engines might not do this.
419
 */
420
class EntityFieldQuery {
421

    
422
  /**
423
   * Indicates that both deleted and non-deleted fields should be returned.
424
   *
425
   * @see EntityFieldQuery::deleted()
426
   */
427
  const RETURN_ALL = NULL;
428

    
429
  /**
430
   * TRUE if the query has already been altered, FALSE if it hasn't.
431
   *
432
   * Used in alter hooks to check for cloned queries that have already been
433
   * altered prior to the clone (for example, the pager count query).
434
   *
435
   * @var boolean
436
   */
437
  public $altered = FALSE;
438

    
439
  /**
440
   * Associative array of entity-generic metadata conditions.
441
   *
442
   * @var array
443
   *
444
   * @see EntityFieldQuery::entityCondition()
445
   */
446
  public $entityConditions = array();
447

    
448
  /**
449
   * List of field conditions.
450
   *
451
   * @var array
452
   *
453
   * @see EntityFieldQuery::fieldCondition()
454
   */
455
  public $fieldConditions = array();
456

    
457
  /**
458
   * List of field meta conditions (language and delta).
459
   *
460
   * Field conditions operate on columns specified by hook_field_schema(),
461
   * the meta conditions operate on columns added by the system: delta
462
   * and language. These can not be mixed with the field conditions because
463
   * field columns can have any name including delta and language.
464
   *
465
   * @var array
466
   *
467
   * @see EntityFieldQuery::fieldLanguageCondition()
468
   * @see EntityFieldQuery::fieldDeltaCondition()
469
   */
470
  public $fieldMetaConditions = array();
471

    
472
  /**
473
   * List of property conditions.
474
   *
475
   * @var array
476
   *
477
   * @see EntityFieldQuery::propertyCondition()
478
   */
479
  public $propertyConditions = array();
480

    
481
  /**
482
   * List of order clauses.
483
   *
484
   * @var array
485
   */
486
  public $order = array();
487

    
488
  /**
489
   * The query range.
490
   *
491
   * @var array
492
   *
493
   * @see EntityFieldQuery::range()
494
   */
495
  public $range = array();
496

    
497
  /**
498
   * The query pager data.
499
   *
500
   * @var array
501
   *
502
   * @see EntityFieldQuery::pager()
503
   */
504
  public $pager = array();
505

    
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
  /**
517
   * A list of field arrays used.
518
   *
519
   * Field names passed to EntityFieldQuery::fieldCondition() and
520
   * EntityFieldQuery::fieldOrderBy() are run through field_info_field() before
521
   * stored in this array. This way, the elements of this array are field
522
   * arrays.
523
   *
524
   * @var array
525
   */
526
  public $fields = array();
527

    
528
  /**
529
   * TRUE if this is a count query, FALSE if it isn't.
530
   *
531
   * @var boolean
532
   */
533
  public $count = FALSE;
534

    
535
  /**
536
   * Flag indicating whether this is querying current or all revisions.
537
   *
538
   * @var int
539
   *
540
   * @see EntityFieldQuery::age()
541
   */
542
  public $age = FIELD_LOAD_CURRENT;
543

    
544
  /**
545
   * A list of the tags added to this query.
546
   *
547
   * @var array
548
   *
549
   * @see EntityFieldQuery::addTag()
550
   */
551
  public $tags = array();
552

    
553
  /**
554
   * A list of metadata added to this query.
555
   *
556
   * @var array
557
   *
558
   * @see EntityFieldQuery::addMetaData()
559
   */
560
  public $metaData = array();
561

    
562
  /**
563
   * The ordered results.
564
   *
565
   * @var array
566
   *
567
   * @see EntityFieldQuery::execute().
568
   */
569
  public $orderedResults = array();
570

    
571
  /**
572
   * The method executing the query, if it is overriding the default.
573
   *
574
   * @var string
575
   *
576
   * @see EntityFieldQuery::execute().
577
   */
578
  public $executeCallback = '';
579

    
580
  /**
581
   * Adds a condition on entity-generic metadata.
582
   *
583
   * If the overall query contains only entity conditions or ordering, or if
584
   * there are property conditions, then specifying the entity type is
585
   * mandatory. If there are field conditions or ordering but no property
586
   * conditions or ordering, then specifying an entity type is optional. While
587
   * the field storage engine might support field conditions on more than one
588
   * entity type, there is no way to query across multiple entity base tables by
589
   * default. To specify the entity type, pass in 'entity_type' for $name,
590
   * the type as a string for $value, and no $operator (it's disregarded).
591
   *
592
   * 'bundle', 'revision_id' and 'entity_id' have no such restrictions.
593
   *
594
   * Note: The "comment" entity type does not support bundle conditions.
595
   *
596
   * @param $name
597
   *   'entity_type', 'bundle', 'revision_id' or 'entity_id'.
598
   * @param $value
599
   *   The value for $name. In most cases, this is a scalar. For more complex
600
   *   options, it is an array. The meaning of each element in the array is
601
   *   dependent on $operator.
602
   * @param $operator
603
   *   Possible values:
604
   *   - '=', '<>', '>', '>=', '<', '<=', 'STARTS_WITH', 'CONTAINS': These
605
   *     operators expect $value to be a literal of the same type as the
606
   *     column.
607
   *   - 'IN', 'NOT IN': These operators expect $value to be an array of
608
   *     literals of the same type as the column.
609
   *   - 'BETWEEN': This operator expects $value to be an array of two literals
610
   *     of the same type as the column.
611
   *   The operator can be omitted, and will default to 'IN' if the value is an
612
   *   array, or to '=' otherwise.
613
   *
614
   * @return EntityFieldQuery
615
   *   The called object.
616
   */
617
  public function entityCondition($name, $value, $operator = NULL) {
618
    // The '!=' operator is deprecated in favour of the '<>' operator since the
619
    // latter is ANSI SQL compatible.
620
    if ($operator == '!=') {
621
      $operator = '<>';
622
    }
623
    $this->entityConditions[$name] = array(
624
      'value' => $value,
625
      'operator' => $operator,
626
    );
627
    return $this;
628
  }
629

    
630
  /**
631
   * Adds a condition on field values.
632
   *
633
   * Note that entities with empty field values will be excluded from the
634
   * EntityFieldQuery results when using this method.
635
   *
636
   * @param $field
637
   *   Either a field name or a field array.
638
   * @param $column
639
   *   The column that should hold the value to be matched.
640
   * @param $value
641
   *   The value to test the column value against.
642
   * @param $operator
643
   *   The operator to be used to test the given value.
644
   * @param $delta_group
645
   *   An arbitrary identifier: conditions in the same group must have the same
646
   *   $delta_group.
647
   * @param $language_group
648
   *   An arbitrary identifier: conditions in the same group must have the same
649
   *   $language_group.
650
   *
651
   * @return EntityFieldQuery
652
   *   The called object.
653
   *
654
   * @see EntityFieldQuery::addFieldCondition
655
   * @see EntityFieldQuery::deleted
656
   */
657
  public function fieldCondition($field, $column = NULL, $value = NULL, $operator = NULL, $delta_group = NULL, $language_group = NULL) {
658
    return $this->addFieldCondition($this->fieldConditions, $field, $column, $value, $operator, $delta_group, $language_group);
659
  }
660

    
661
  /**
662
   * Adds a condition on the field language column.
663
   *
664
   * @param $field
665
   *   Either a field name or a field array.
666
   * @param $value
667
   *   The value to test the column value against.
668
   * @param $operator
669
   *   The operator to be used to test the given value.
670
   * @param $delta_group
671
   *   An arbitrary identifier: conditions in the same group must have the same
672
   *   $delta_group.
673
   * @param $language_group
674
   *   An arbitrary identifier: conditions in the same group must have the same
675
   *   $language_group.
676
   *
677
   * @return EntityFieldQuery
678
   *   The called object.
679
   *
680
   * @see EntityFieldQuery::addFieldCondition
681
   * @see EntityFieldQuery::deleted
682
   */
683
  public function fieldLanguageCondition($field, $value = NULL, $operator = NULL, $delta_group = NULL, $language_group = NULL) {
684
    return $this->addFieldCondition($this->fieldMetaConditions, $field, 'language', $value, $operator, $delta_group, $language_group);
685
  }
686

    
687
  /**
688
   * Adds a condition on the field delta column.
689
   *
690
   * @param $field
691
   *   Either a field name or a field array.
692
   * @param $value
693
   *   The value to test the column value against.
694
   * @param $operator
695
   *   The operator to be used to test the given value.
696
   * @param $delta_group
697
   *   An arbitrary identifier: conditions in the same group must have the same
698
   *   $delta_group.
699
   * @param $language_group
700
   *   An arbitrary identifier: conditions in the same group must have the same
701
   *   $language_group.
702
   *
703
   * @return EntityFieldQuery
704
   *   The called object.
705
   *
706
   * @see EntityFieldQuery::addFieldCondition
707
   * @see EntityFieldQuery::deleted
708
   */
709
  public function fieldDeltaCondition($field, $value = NULL, $operator = NULL, $delta_group = NULL, $language_group = NULL) {
710
    return $this->addFieldCondition($this->fieldMetaConditions, $field, 'delta', $value, $operator, $delta_group, $language_group);
711
  }
712

    
713
  /**
714
   * Adds the given condition to the proper condition array.
715
   *
716
   * @param $conditions
717
   *   A reference to an array of conditions.
718
   * @param $field
719
   *   Either a field name or a field array.
720
   * @param $column
721
   *   A column defined in the hook_field_schema() of this field. If this is
722
   *   omitted then the query will find only entities that have data in this
723
   *   field, using the entity and property conditions if there are any.
724
   * @param $value
725
   *   The value to test the column value against. In most cases, this is a
726
   *   scalar. For more complex options, it is an array. The meaning of each
727
   *   element in the array is dependent on $operator.
728
   * @param $operator
729
   *   Possible values:
730
   *   - '=', '<>', '>', '>=', '<', '<=', 'STARTS_WITH', 'CONTAINS': These
731
   *     operators expect $value to be a literal of the same type as the
732
   *     column.
733
   *   - 'IN', 'NOT IN': These operators expect $value to be an array of
734
   *     literals of the same type as the column.
735
   *   - 'BETWEEN': This operator expects $value to be an array of two literals
736
   *     of the same type as the column.
737
   *   The operator can be omitted, and will default to 'IN' if the value is an
738
   *   array, or to '=' otherwise.
739
   * @param $delta_group
740
   *   An arbitrary identifier: conditions in the same group must have the same
741
   *   $delta_group. For example, let's presume a multivalue field which has
742
   *   two columns, 'color' and 'shape', and for entity id 1, there are two
743
   *   values: red/square and blue/circle. Entity ID 1 does not have values
744
   *   corresponding to 'red circle', however if you pass 'red' and 'circle' as
745
   *   conditions, it will appear in the  results - by default queries will run
746
   *   against any combination of deltas. By passing the conditions with the
747
   *   same $delta_group it will ensure that only values attached to the same
748
   *   delta are matched, and entity 1 would then be excluded from the results.
749
   * @param $language_group
750
   *   An arbitrary identifier: conditions in the same group must have the same
751
   *   $language_group.
752
   *
753
   * @return EntityFieldQuery
754
   *   The called object.
755
   */
756
  protected function addFieldCondition(&$conditions, $field, $column = NULL, $value = NULL, $operator = NULL, $delta_group = NULL, $language_group = NULL) {
757
    // The '!=' operator is deprecated in favour of the '<>' operator since the
758
    // latter is ANSI SQL compatible.
759
    if ($operator == '!=') {
760
      $operator = '<>';
761
    }
762
    if (is_scalar($field)) {
763
      $field_definition = field_info_field($field);
764
      if (empty($field_definition)) {
765
        throw new EntityFieldQueryException(t('Unknown field: @field_name', array('@field_name' => $field)));
766
      }
767
      $field = $field_definition;
768
    }
769
    // Ensure the same index is used for field conditions as for fields.
770
    $index = count($this->fields);
771
    $this->fields[$index] = $field;
772
    if (isset($column)) {
773
      $conditions[$index] = array(
774
        'field' => $field,
775
        'column' => $column,
776
        'value' => $value,
777
        'operator' => $operator,
778
        'delta_group' => $delta_group,
779
        'language_group' => $language_group,
780
      );
781
    }
782
    return $this;
783
  }
784

    
785
  /**
786
   * Adds a condition on an entity-specific property.
787
   *
788
   * An $entity_type must be specified by calling
789
   * EntityFieldCondition::entityCondition('entity_type', $entity_type) before
790
   * executing the query. Also, by default only entities stored in SQL are
791
   * supported; however, EntityFieldQuery::executeCallback can be set to handle
792
   * different entity storage.
793
   *
794
   * @param $column
795
   *   A column defined in the hook_schema() of the base table of the entity.
796
   * @param $value
797
   *   The value to test the field against. In most cases, this is a scalar. For
798
   *   more complex options, it is an array. The meaning of each element in the
799
   *   array is dependent on $operator.
800
   * @param $operator
801
   *   Possible values:
802
   *   - '=', '<>', '>', '>=', '<', '<=', 'STARTS_WITH', 'CONTAINS': These
803
   *     operators expect $value to be a literal of the same type as the
804
   *     column.
805
   *   - 'IN', 'NOT IN': These operators expect $value to be an array of
806
   *     literals of the same type as the column.
807
   *   - 'BETWEEN': This operator expects $value to be an array of two literals
808
   *     of the same type as the column.
809
   *   The operator can be omitted, and will default to 'IN' if the value is an
810
   *   array, or to '=' otherwise.
811
   *
812
   * @return EntityFieldQuery
813
   *   The called object.
814
   */
815
  public function propertyCondition($column, $value, $operator = NULL) {
816
    // The '!=' operator is deprecated in favour of the '<>' operator since the
817
    // latter is ANSI SQL compatible.
818
    if ($operator == '!=') {
819
      $operator = '<>';
820
    }
821
    $this->propertyConditions[] = array(
822
      'column' => $column,
823
      'value' => $value,
824
      'operator' => $operator,
825
    );
826
    return $this;
827
  }
828

    
829
  /**
830
   * Orders the result set by entity-generic metadata.
831
   *
832
   * If called multiple times, the query will order by each specified column in
833
   * the order this method is called.
834
   *
835
   * Note: The "comment" and "taxonomy_term" entity types don't support ordering
836
   * by bundle. For "taxonomy_term", propertyOrderBy('vid') can be used instead.
837
   *
838
   * @param $name
839
   *   'entity_type', 'bundle', 'revision_id' or 'entity_id'.
840
   * @param $direction
841
   *   The direction to sort. Legal values are "ASC" and "DESC".
842
   *
843
   * @return EntityFieldQuery
844
   *   The called object.
845
   */
846
  public function entityOrderBy($name, $direction = 'ASC') {
847
    $this->order[] = array(
848
      'type' => 'entity',
849
      'specifier' => $name,
850
      'direction' => $direction,
851
    );
852
    return $this;
853
  }
854

    
855
  /**
856
   * Orders the result set by a given field column.
857
   *
858
   * If called multiple times, the query will order by each specified column in
859
   * the order this method is called. Note that entities with empty field
860
   * values will be excluded from the EntityFieldQuery results when using this
861
   * method.
862
   *
863
   * @param $field
864
   *   Either a field name or a field array.
865
   * @param $column
866
   *   A column defined in the hook_field_schema() of this field. entity_id and
867
   *   bundle can also be used.
868
   * @param $direction
869
   *   The direction to sort. Legal values are "ASC" and "DESC".
870
   *
871
   * @return EntityFieldQuery
872
   *   The called object.
873
   */
874
  public function fieldOrderBy($field, $column, $direction = 'ASC') {
875
    if (is_scalar($field)) {
876
      $field_definition = field_info_field($field);
877
      if (empty($field_definition)) {
878
        throw new EntityFieldQueryException(t('Unknown field: @field_name', array('@field_name' => $field)));
879
      }
880
      $field = $field_definition;
881
    }
882
    // Save the index used for the new field, for later use in field storage.
883
    $index = count($this->fields);
884
    $this->fields[$index] = $field;
885
    $this->order[] = array(
886
      'type' => 'field',
887
      'specifier' => array(
888
        'field' => $field,
889
        'index' => $index,
890
        'column' => $column,
891
      ),
892
      'direction' => $direction,
893
    );
894
    return $this;
895
  }
896

    
897
  /**
898
   * Orders the result set by an entity-specific property.
899
   *
900
   * An $entity_type must be specified by calling
901
   * EntityFieldCondition::entityCondition('entity_type', $entity_type) before
902
   * executing the query.
903
   *
904
   * If called multiple times, the query will order by each specified column in
905
   * the order this method is called.
906
   *
907
   * @param $column
908
   *   The column on which to order.
909
   * @param $direction
910
   *   The direction to sort. Legal values are "ASC" and "DESC".
911
   *
912
   * @return EntityFieldQuery
913
   *   The called object.
914
   */
915
  public function propertyOrderBy($column, $direction = 'ASC') {
916
    $this->order[] = array(
917
      'type' => 'property',
918
      'specifier' => $column,
919
      'direction' => $direction,
920
    );
921
    return $this;
922
  }
923

    
924
  /**
925
   * Sets the query to be a count query only.
926
   *
927
   * @return EntityFieldQuery
928
   *   The called object.
929
   */
930
  public function count() {
931
    $this->count = TRUE;
932
    return $this;
933
  }
934

    
935
  /**
936
   * Restricts a query to a given range in the result set.
937
   *
938
   * @param $start
939
   *   The first entity from the result set to return. If NULL, removes any
940
   *   range directives that are set.
941
   * @param $length
942
   *   The number of entities to return from the result set.
943
   *
944
   * @return EntityFieldQuery
945
   *   The called object.
946
   */
947
  public function range($start = NULL, $length = NULL) {
948
    $this->range = array(
949
      'start' => $start,
950
      'length' => $length,
951
    );
952
    return $this;
953
  }
954

    
955
  /**
956
   * Enables a pager for the query.
957
   *
958
   * @param $limit
959
   *   An integer specifying the number of elements per page.  If passed a false
960
   *   value (FALSE, 0, NULL), the pager is disabled.
961
   * @param $element
962
   *   An optional integer to distinguish between multiple pagers on one page.
963
   *   If not provided, one is automatically calculated.
964
   *
965
   * @return EntityFieldQuery
966
   *   The called object.
967
   */
968
  public function pager($limit = 10, $element = NULL) {
969
    if (!isset($element)) {
970
      $element = PagerDefault::$maxElement++;
971
    }
972
    elseif ($element >= PagerDefault::$maxElement) {
973
      PagerDefault::$maxElement = $element + 1;
974
    }
975

    
976
    $this->pager = array(
977
      'limit' => $limit,
978
      'element' => $element,
979
    );
980
    return $this;
981
  }
982

    
983
  /**
984
   * Enables sortable tables for this query.
985
   *
986
   * @param $headers
987
   *   An EFQ Header array based on which the order clause is added to the
988
   *   query.
989
   *
990
   * @return EntityFieldQuery
991
   *   The called object.
992
   */
993
  public function tableSort(&$headers) {
994
    // If 'field' is not initialized, the header columns aren't clickable
995
    foreach ($headers as $key =>$header) {
996
      if (is_array($header) && isset($header['specifier'])) {
997
        $headers[$key]['field'] = '';
998
      }
999
    }
1000

    
1001
    $order = tablesort_get_order($headers);
1002
    $direction = tablesort_get_sort($headers);
1003
    foreach ($headers as $header) {
1004
      if (is_array($header) && ($header['data'] == $order['name'])) {
1005
        if ($header['type'] == 'field') {
1006
          $this->fieldOrderBy($header['specifier']['field'], $header['specifier']['column'], $direction);
1007
        }
1008
        else {
1009
          $header['direction'] = $direction;
1010
          $this->order[] = $header;
1011
        }
1012
      }
1013
    }
1014

    
1015
    return $this;
1016
  }
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
  /**
1034
   * Queries the current or every revision.
1035
   *
1036
   * Note that this only affects field conditions. Property conditions always
1037
   * apply to the current revision.
1038
   * @TODO: Once revision tables have been cleaned up, revisit this.
1039
   *
1040
   * @param $age
1041
   *   - FIELD_LOAD_CURRENT (default): Query the most recent revisions for all
1042
   *     entities. The results will be keyed by entity type and entity ID.
1043
   *   - FIELD_LOAD_REVISION: Query all revisions. The results will be keyed by
1044
   *     entity type and entity revision ID.
1045
   *
1046
   * @return EntityFieldQuery
1047
   *   The called object.
1048
   */
1049
  public function age($age) {
1050
    $this->age = $age;
1051
    return $this;
1052
  }
1053

    
1054
  /**
1055
   * Adds a tag to the query.
1056
   *
1057
   * Tags are strings that mark a query so that hook_query_alter() and
1058
   * hook_query_TAG_alter() implementations may decide if they wish to alter
1059
   * the query. A query may have any number of tags, and they must be valid PHP
1060
   * identifiers (composed of letters, numbers, and underscores). For example,
1061
   * queries involving nodes that will be displayed for a user need to add the
1062
   * tag 'node_access', so that the node module can add access restrictions to
1063
   * the query.
1064
   *
1065
   * If an entity field query has tags, it must also have an entity type
1066
   * specified, because the alter hook will need the entity base table.
1067
   *
1068
   * @param string $tag
1069
   *   The tag to add.
1070
   *
1071
   * @return EntityFieldQuery
1072
   *   The called object.
1073
   */
1074
  public function addTag($tag) {
1075
    $this->tags[$tag] = $tag;
1076
    return $this;
1077
  }
1078

    
1079
  /**
1080
   * Adds additional metadata to the query.
1081
   *
1082
   * Sometimes a query may need to provide additional contextual data for the
1083
   * alter hook. The alter hook implementations may then use that information
1084
   * to decide if and how to take action.
1085
   *
1086
   * @param $key
1087
   *   The unique identifier for this piece of metadata. Must be a string that
1088
   *   follows the same rules as any other PHP identifier.
1089
   * @param $object
1090
   *   The additional data to add to the query. May be any valid PHP variable.
1091
   *
1092
   * @return EntityFieldQuery
1093
   *   The called object.
1094
   */
1095
  public function addMetaData($key, $object) {
1096
    $this->metaData[$key] = $object;
1097
    return $this;
1098
  }
1099

    
1100
  /**
1101
   * Executes the query.
1102
   *
1103
   * After executing the query, $this->orderedResults will contain a list of
1104
   * the same stub entities in the order returned by the query. This is only
1105
   * relevant if there are multiple entity types in the returned value and
1106
   * a field ordering was requested. In every other case, the returned value
1107
   * contains everything necessary for processing.
1108
   *
1109
   * @return
1110
   *   Either a number if count() was called or an array of associative arrays
1111
   *   of stub entities. The outer array keys are entity types, and the inner
1112
   *   array keys are the relevant ID. (In most cases this will be the entity
1113
   *   ID. The only exception is when age=FIELD_LOAD_REVISION is used and field
1114
   *   conditions or sorts are present -- in this case, the key will be the
1115
   *   revision ID.) The entity type will only exist in the outer array if
1116
   *   results were found. The inner array values are always stub entities, as
1117
   *   returned by entity_create_stub_entity(). To traverse the returned array:
1118
   *   @code
1119
   *     foreach ($query->execute() as $entity_type => $entities) {
1120
   *       foreach ($entities as $entity_id => $entity) {
1121
   *   @endcode
1122
   *   Note if the entity type is known, then the following snippet will load
1123
   *   the entities found:
1124
   *   @code
1125
   *     $result = $query->execute();
1126
   *     if (!empty($result[$my_type])) {
1127
   *       $entities = entity_load($my_type, array_keys($result[$my_type]));
1128
   *     }
1129
   *   @endcode
1130
   */
1131
  public function execute() {
1132
    // Give a chance to other modules to alter the query.
1133
    drupal_alter('entity_query', $this);
1134
    $this->altered = TRUE;
1135

    
1136
    // Initialize the pager.
1137
    $this->initializePager();
1138

    
1139
    // Execute the query using the correct callback.
1140
    $result = call_user_func($this->queryCallback(), $this);
1141

    
1142
    return $result;
1143
  }
1144

    
1145
  /**
1146
   * Determines the query callback to use for this entity query.
1147
   *
1148
   * @return
1149
   *   A callback that can be used with call_user_func().
1150
   */
1151
  public function queryCallback() {
1152
    // Use the override from $this->executeCallback. It can be set either
1153
    // while building the query, or using hook_entity_query_alter().
1154
    if (function_exists($this->executeCallback)) {
1155
      return $this->executeCallback;
1156
    }
1157
    // If there are no field conditions and sorts, and no execute callback
1158
    // then we default to querying entity tables in SQL.
1159
    if (empty($this->fields)) {
1160
      return array($this, 'propertyQuery');
1161
    }
1162
    // If no override, find the storage engine to be used.
1163
    foreach ($this->fields as $field) {
1164
      if (!isset($storage)) {
1165
        $storage = $field['storage']['module'];
1166
      }
1167
      elseif ($storage != $field['storage']['module']) {
1168
        throw new EntityFieldQueryException(t("Can't handle more than one field storage engine"));
1169
      }
1170
    }
1171
    if ($storage) {
1172
      // Use hook_field_storage_query() from the field storage.
1173
      return $storage . '_field_storage_query';
1174
    }
1175
    else {
1176
      throw new EntityFieldQueryException(t("Field storage engine not found."));
1177
    }
1178
  }
1179

    
1180
  /**
1181
   * Queries entity tables in SQL for property conditions and sorts.
1182
   *
1183
   * This method is only used if there are no field conditions and sorts.
1184
   *
1185
   * @return
1186
   *   See EntityFieldQuery::execute().
1187
   */
1188
  protected function propertyQuery() {
1189
    if (empty($this->entityConditions['entity_type'])) {
1190
      throw new EntityFieldQueryException(t('For this query an entity type must be specified.'));
1191
    }
1192
    $entity_type = $this->entityConditions['entity_type']['value'];
1193
    $entity_info = entity_get_info($entity_type);
1194
    if (empty($entity_info['base table'])) {
1195
      throw new EntityFieldQueryException(t('Entity %entity has no base table.', array('%entity' => $entity_type)));
1196
    }
1197
    $base_table = $entity_info['base table'];
1198
    $base_table_schema = drupal_get_schema($base_table);
1199
    $select_query = db_select($base_table);
1200
    $select_query->addExpression(':entity_type', 'entity_type', array(':entity_type' => $entity_type));
1201
    // Process the property conditions.
1202
    foreach ($this->propertyConditions as $property_condition) {
1203
      $this->addCondition($select_query, $base_table . '.' . $property_condition['column'], $property_condition);
1204
    }
1205
    // Process the four possible entity condition.
1206
    // The id field is always present in entity keys.
1207
    $sql_field = $entity_info['entity keys']['id'];
1208
    $id_map['entity_id'] = $sql_field;
1209
    $select_query->addField($base_table, $sql_field, 'entity_id');
1210
    if (isset($this->entityConditions['entity_id'])) {
1211
      $this->addCondition($select_query, $base_table . '.' . $sql_field, $this->entityConditions['entity_id']);
1212
    }
1213

    
1214
    // If there is a revision key defined, use it.
1215
    if (!empty($entity_info['entity keys']['revision'])) {
1216
      $sql_field = $entity_info['entity keys']['revision'];
1217
      $select_query->addField($base_table, $sql_field, 'revision_id');
1218
      if (isset($this->entityConditions['revision_id'])) {
1219
        $this->addCondition($select_query, $base_table . '.' . $sql_field, $this->entityConditions['revision_id']);
1220
      }
1221
    }
1222
    else {
1223
      $sql_field = 'revision_id';
1224
      $select_query->addExpression('NULL', 'revision_id');
1225
    }
1226
    $id_map['revision_id'] = $sql_field;
1227

    
1228
    // Handle bundles.
1229
    if (!empty($entity_info['entity keys']['bundle'])) {
1230
      $sql_field = $entity_info['entity keys']['bundle'];
1231
      $having = FALSE;
1232

    
1233
      if (!empty($base_table_schema['fields'][$sql_field])) {
1234
        $select_query->addField($base_table, $sql_field, 'bundle');
1235
      }
1236
    }
1237
    else {
1238
      $sql_field = 'bundle';
1239
      $select_query->addExpression(':bundle', 'bundle', array(':bundle' => $entity_type));
1240
      $having = TRUE;
1241
    }
1242
    $id_map['bundle'] = $sql_field;
1243
    if (isset($this->entityConditions['bundle'])) {
1244
      if (!empty($entity_info['entity keys']['bundle'])) {
1245
        $this->addCondition($select_query, $base_table . '.' . $sql_field, $this->entityConditions['bundle'], $having);
1246
      }
1247
      else {
1248
        // This entity has no bundle, so invalidate the query.
1249
        $select_query->where('1 = 0');
1250
      }
1251
    }
1252

    
1253
    // Order the query.
1254
    foreach ($this->order as $order) {
1255
      if ($order['type'] == 'entity') {
1256
        $key = $order['specifier'];
1257
        if (!isset($id_map[$key])) {
1258
          throw new EntityFieldQueryException(t('Do not know how to order on @key for @entity_type', array('@key' => $key, '@entity_type' => $entity_type)));
1259
        }
1260
        $select_query->orderBy($id_map[$key], $order['direction']);
1261
      }
1262
      elseif ($order['type'] == 'property') {
1263
        $select_query->orderBy($base_table . '.' . $order['specifier'], $order['direction']);
1264
      }
1265
    }
1266

    
1267
    return $this->finishQuery($select_query);
1268
  }
1269

    
1270
  /**
1271
   * Gets the total number of results and initializes a pager for the query.
1272
   *
1273
   * The pager can be disabled by either setting the pager limit to 0, or by
1274
   * setting this query to be a count query.
1275
   */
1276
  function initializePager() {
1277
    if ($this->pager && !empty($this->pager['limit']) && !$this->count) {
1278
      $page = pager_find_page($this->pager['element']);
1279
      $count_query = clone $this;
1280
      $this->pager['total'] = $count_query->count()->execute();
1281
      $this->pager['start'] = $page * $this->pager['limit'];
1282
      pager_default_initialize($this->pager['total'], $this->pager['limit'], $this->pager['element']);
1283
      $this->range($this->pager['start'], $this->pager['limit']);
1284
    }
1285
  }
1286

    
1287
  /**
1288
   * Finishes the query.
1289
   *
1290
   * Adds tags, metaData, range and returns the requested list or count.
1291
   *
1292
   * @param SelectQuery $select_query
1293
   *   A SelectQuery which has entity_type, entity_id, revision_id and bundle
1294
   *   fields added.
1295
   * @param $id_key
1296
   *   Which field's values to use as the returned array keys.
1297
   *
1298
   * @return
1299
   *   See EntityFieldQuery::execute().
1300
   */
1301
  function finishQuery($select_query, $id_key = 'entity_id') {
1302
    foreach ($this->tags as $tag) {
1303
      $select_query->addTag($tag);
1304
    }
1305
    foreach ($this->metaData as $key => $object) {
1306
      $select_query->addMetaData($key, $object);
1307
    }
1308
    $select_query->addMetaData('entity_field_query', $this);
1309
    if ($this->range) {
1310
      $select_query->range($this->range['start'], $this->range['length']);
1311
    }
1312
    if ($this->count) {
1313
      return $select_query->countQuery()->execute()->fetchField();
1314
    }
1315
    $return = array();
1316
    foreach ($select_query->execute() as $partial_entity) {
1317
      $bundle = isset($partial_entity->bundle) ? $partial_entity->bundle : NULL;
1318
      $entity = entity_create_stub_entity($partial_entity->entity_type, array($partial_entity->entity_id, $partial_entity->revision_id, $bundle));
1319
      $return[$partial_entity->entity_type][$partial_entity->$id_key] = $entity;
1320
      $this->ordered_results[] = $partial_entity;
1321
    }
1322
    return $return;
1323
  }
1324

    
1325
  /**
1326
   * Adds a condition to an already built SelectQuery (internal function).
1327
   *
1328
   * This is a helper for hook_entity_query() and hook_field_storage_query().
1329
   *
1330
   * @param SelectQuery $select_query
1331
   *   A SelectQuery object.
1332
   * @param $sql_field
1333
   *   The name of the field.
1334
   * @param $condition
1335
   *   A condition as described in EntityFieldQuery::fieldCondition() and
1336
   *   EntityFieldQuery::entityCondition().
1337
   * @param $having
1338
   *   HAVING or WHERE. This is necessary because SQL can't handle WHERE
1339
   *   conditions on aliased columns.
1340
   */
1341
  public function addCondition(SelectQuery $select_query, $sql_field, $condition, $having = FALSE) {
1342
    $method = $having ? 'havingCondition' : 'condition';
1343
    $like_prefix = '';
1344
    switch ($condition['operator']) {
1345
      case 'CONTAINS':
1346
        $like_prefix = '%';
1347
      case 'STARTS_WITH':
1348
        $select_query->$method($sql_field, $like_prefix . db_like($condition['value']) . '%', 'LIKE');
1349
        break;
1350
      default:
1351
        $select_query->$method($sql_field, $condition['value'], $condition['operator']);
1352
    }
1353
  }
1354

    
1355
}
1356

    
1357
/**
1358
 * Defines an exception thrown when a malformed entity is passed.
1359
 */
1360
class EntityMalformedException extends Exception { }