Projet

Général

Profil

Paste
Télécharger (20,6 ko) Statistiques
| Branche: | Révision:

root / drupal7 / sites / all / modules / entityreference / plugins / selection / EntityReference_SelectionHandler_Generic.class.php @ 3acd948f

1
<?php
2

    
3
/**
4
 * A generic Entity handler.
5
 *
6
 * The generic base implementation has a variety of overrides to workaround
7
 * core's largely deficient entity handling.
8
 */
9
class EntityReference_SelectionHandler_Generic implements EntityReference_SelectionHandler {
10

    
11
  /**
12
   * Implements EntityReferenceHandler::getInstance().
13
   */
14
  public static function getInstance($field, $instance = NULL, $entity_type = NULL, $entity = NULL) {
15
    $target_entity_type = $field['settings']['target_type'];
16

    
17
    // Check if the entity type does exist and has a base table.
18
    $entity_info = entity_get_info($target_entity_type);
19
    if (empty($entity_info['base table'])) {
20
      return EntityReference_SelectionHandler_Broken::getInstance($field, $instance);
21
    }
22

    
23
    if (class_exists($class_name = 'EntityReference_SelectionHandler_Generic_' . $target_entity_type)) {
24
      return new $class_name($field, $instance, $entity_type, $entity);
25
    }
26
    else {
27
      return new EntityReference_SelectionHandler_Generic($field, $instance, $entity_type, $entity);
28
    }
29
  }
30

    
31
  protected function __construct($field, $instance = NULL, $entity_type = NULL, $entity = NULL) {
32
    $this->field = $field;
33
    $this->instance = $instance;
34
    $this->entity_type = $entity_type;
35
    $this->entity = $entity;
36
  }
37

    
38
  /**
39
   * Implements EntityReferenceHandler::settingsForm().
40
   */
41
  public static function settingsForm($field, $instance) {
42
    $entity_info = entity_get_info($field['settings']['target_type']);
43

    
44
    // Merge-in default values.
45
    $field['settings']['handler_settings'] += array(
46
      'target_bundles' => array(),
47
      'sort' => array(
48
        'type' => 'none',
49
      )
50
    );
51

    
52
    if (!empty($entity_info['entity keys']['bundle'])) {
53
      $bundles = array();
54
      foreach ($entity_info['bundles'] as $bundle_name => $bundle_info) {
55
        $bundles[$bundle_name] = $bundle_info['label'];
56
      }
57

    
58
      $form['target_bundles'] = array(
59
        '#type' => 'checkboxes',
60
        '#title' => t('Target bundles'),
61
        '#options' => $bundles,
62
        '#default_value' => $field['settings']['handler_settings']['target_bundles'],
63
        '#size' => 6,
64
        '#multiple' => TRUE,
65
        '#description' => t('The bundles of the entity type that can be referenced. Optional, leave empty for all bundles.'),
66
        '#element_validate' => array('_entityreference_element_validate_filter'),
67
      );
68
    }
69
    else {
70
      $form['target_bundles'] = array(
71
        '#type' => 'value',
72
        '#value' => array(),
73
      );
74
    }
75

    
76
    $form['sort']['type'] = array(
77
      '#type' => 'select',
78
      '#title' => t('Sort by'),
79
      '#options' => array(
80
        'none' => t("Don't sort"),
81
        'property' => t('A property of the base table of the entity'),
82
        'field' => t('A field attached to this entity'),
83
      ),
84
      '#ajax' => TRUE,
85
      '#limit_validation_errors' => array(),
86
      '#default_value' => $field['settings']['handler_settings']['sort']['type'],
87
    );
88

    
89
    $form['sort']['settings'] = array(
90
      '#type' => 'container',
91
      '#attributes' => array('class' => array('entityreference-settings')),
92
      '#process' => array('_entityreference_form_process_merge_parent'),
93
    );
94

    
95
    if ($field['settings']['handler_settings']['sort']['type'] == 'property') {
96
      // Merge-in default values.
97
      $field['settings']['handler_settings']['sort'] += array(
98
        'property' => NULL,
99
      );
100

    
101
      $form['sort']['settings']['property'] = array(
102
        '#type' => 'select',
103
        '#title' => t('Sort property'),
104
        '#required' => TRUE,
105
        '#options' => drupal_map_assoc($entity_info['schema_fields_sql']['base table']),
106
        '#default_value' => $field['settings']['handler_settings']['sort']['property'],
107
      );
108
    }
109
    elseif ($field['settings']['handler_settings']['sort']['type'] == 'field') {
110
      // Merge-in default values.
111
      $field['settings']['handler_settings']['sort'] += array(
112
        'field' => NULL,
113
      );
114

    
115
      $fields = array();
116
      foreach (field_info_instances($field['settings']['target_type']) as $bundle_name => $bundle_instances) {
117
        foreach ($bundle_instances as $instance_name => $instance_info) {
118
          $field_info = field_info_field($instance_name);
119
          foreach ($field_info['columns'] as $column_name => $column_info) {
120
            $fields[$instance_name . ':' . $column_name] = t('@label (column @column)', array('@label' => $instance_info['label'], '@column' => $column_name));
121
          }
122
        }
123
      }
124

    
125
      $form['sort']['settings']['field'] = array(
126
        '#type' => 'select',
127
        '#title' => t('Sort field'),
128
        '#required' => TRUE,
129
        '#options' => $fields,
130
        '#default_value' => $field['settings']['handler_settings']['sort']['field'],
131
      );
132
    }
133

    
134
    if ($field['settings']['handler_settings']['sort']['type'] != 'none') {
135
      // Merge-in default values.
136
      $field['settings']['handler_settings']['sort'] += array(
137
        'direction' => 'ASC',
138
      );
139

    
140
      $form['sort']['settings']['direction'] = array(
141
        '#type' => 'select',
142
        '#title' => t('Sort direction'),
143
        '#required' => TRUE,
144
        '#options' => array(
145
          'ASC' => t('Ascending'),
146
          'DESC' => t('Descending'),
147
        ),
148
        '#default_value' => $field['settings']['handler_settings']['sort']['direction'],
149
      );
150
    }
151

    
152
    return $form;
153
  }
154

    
155
  /**
156
   * Implements EntityReferenceHandler::getReferencableEntities().
157
   */
158
  public function getReferencableEntities($match = NULL, $match_operator = 'CONTAINS', $limit = 0) {
159
    $options = array();
160
    $entity_type = $this->field['settings']['target_type'];
161

    
162
    $query = $this->buildEntityFieldQuery($match, $match_operator);
163
    if ($limit > 0) {
164
      $query->range(0, $limit);
165
    }
166

    
167
    $results = $query->execute();
168

    
169
    if (!empty($results[$entity_type])) {
170
      $entities = entity_load($entity_type, array_keys($results[$entity_type]));
171
      foreach ($entities as $entity_id => $entity) {
172
        list(,, $bundle) = entity_extract_ids($entity_type, $entity);
173
        $options[$bundle][$entity_id] = check_plain($this->getLabel($entity));
174
      }
175
    }
176

    
177
    return $options;
178
  }
179

    
180
  /**
181
   * Implements EntityReferenceHandler::countReferencableEntities().
182
   */
183
  public function countReferencableEntities($match = NULL, $match_operator = 'CONTAINS') {
184
    $query = $this->buildEntityFieldQuery($match, $match_operator);
185
    return $query
186
      ->count()
187
      ->execute();
188
  }
189

    
190
  /**
191
   * Implements EntityReferenceHandler::validateReferencableEntities().
192
   */
193
  public function validateReferencableEntities(array $ids) {
194
    if ($ids) {
195
      $entity_type = $this->field['settings']['target_type'];
196
      $query = $this->buildEntityFieldQuery();
197
      $query->entityCondition('entity_id', $ids, 'IN');
198
      $result = $query->execute();
199
      if (!empty($result[$entity_type])) {
200
        return array_keys($result[$entity_type]);
201
      }
202
    }
203

    
204
    return array();
205
  }
206

    
207
  /**
208
   * Implements EntityReferenceHandler::validateAutocompleteInput().
209
   */
210
  public function validateAutocompleteInput($input, &$element, &$form_state, $form) {
211
      $bundled_entities = $this->getReferencableEntities($input, '=', 6);
212
      $entities = array();
213
      foreach($bundled_entities as $entities_list) {
214
        $entities += $entities_list;
215
      }
216
      if (empty($entities)) {
217
        // Error if there are no entities available for a required field.
218
        form_error($element, t('There are no entities matching "%value"', array('%value' => $input)));
219
      }
220
      elseif (count($entities) > 5) {
221
        // Error if there are more than 5 matching entities.
222
        form_error($element, t('Many entities are called %value. Specify the one you want by appending the id in parentheses, like "@value (@id)"', array(
223
          '%value' => $input,
224
          '@value' => $input,
225
          '@id' => key($entities),
226
        )));
227
      }
228
      elseif (count($entities) > 1) {
229
        // More helpful error if there are only a few matching entities.
230
        $multiples = array();
231
        foreach ($entities as $id => $name) {
232
          $multiples[] = $name . ' (' . $id . ')';
233
        }
234
        form_error($element, t('Multiple entities match this reference; "%multiple"', array('%multiple' => implode('", "', $multiples))));
235
      }
236
      else {
237
        // Take the one and only matching entity.
238
        return key($entities);
239
      }
240
  }
241

    
242
  /**
243
   * Build an EntityFieldQuery to get referencable entities.
244
   */
245
  protected function buildEntityFieldQuery($match = NULL, $match_operator = 'CONTAINS') {
246
    $query = new EntityFieldQuery();
247
    $query->entityCondition('entity_type', $this->field['settings']['target_type']);
248
    if (!empty($this->field['settings']['handler_settings']['target_bundles'])) {
249
      $query->entityCondition('bundle', $this->field['settings']['handler_settings']['target_bundles'], 'IN');
250
    }
251
    if (isset($match)) {
252
      $entity_info = entity_get_info($this->field['settings']['target_type']);
253
      if (isset($entity_info['entity keys']['label'])) {
254
        $query->propertyCondition($entity_info['entity keys']['label'], $match, $match_operator);
255
      }
256
    }
257

    
258
    // Add a generic entity access tag to the query.
259
    $query->addTag($this->field['settings']['target_type'] . '_access');
260
    $query->addTag('entityreference');
261
    $query->addMetaData('field', $this->field);
262
    $query->addMetaData('entityreference_selection_handler', $this);
263

    
264
    // Add the sort option.
265
    if (!empty($this->field['settings']['handler_settings']['sort'])) {
266
      $sort_settings = $this->field['settings']['handler_settings']['sort'];
267
      if ($sort_settings['type'] == 'property') {
268
        $query->propertyOrderBy($sort_settings['property'], $sort_settings['direction']);
269
      }
270
      elseif ($sort_settings['type'] == 'field') {
271
        list($field, $column) = explode(':', $sort_settings['field'], 2);
272
        $query->fieldOrderBy($field, $column, $sort_settings['direction']);
273
      }
274
    }
275

    
276
    return $query;
277
  }
278

    
279
  /**
280
   * Implements EntityReferenceHandler::entityFieldQueryAlter().
281
   */
282
  public function entityFieldQueryAlter(SelectQueryInterface $query) {
283

    
284
  }
285

    
286
  /**
287
   * Helper method: pass a query to the alteration system again.
288
   *
289
   * This allow Entity Reference to add a tag to an existing query, to ask
290
   * access control mechanisms to alter it again.
291
   */
292
  protected function reAlterQuery(SelectQueryInterface $query, $tag, $base_table) {
293
    // Save the old tags and metadata.
294
    // For some reason, those are public.
295
    $old_tags = $query->alterTags;
296
    $old_metadata = $query->alterMetaData;
297

    
298
    $query->alterTags = array($tag => TRUE);
299
    $query->alterMetaData['base_table'] = $base_table;
300
    drupal_alter(array('query', 'query_' . $tag), $query);
301

    
302
    // Restore the tags and metadata.
303
    $query->alterTags = $old_tags;
304
    $query->alterMetaData = $old_metadata;
305
  }
306

    
307
  /**
308
   * Implements EntityReferenceHandler::getLabel().
309
   */
310
  public function getLabel($entity) {
311
    $target_type = $this->field['settings']['target_type'];
312
    return entity_access('view', $target_type, $entity) ? entity_label($target_type, $entity) : t(ENTITYREFERENCE_DENIED);
313
  }
314

    
315
  /**
316
   * Ensure a base table exists for the query.
317
   *
318
   * If we have a field-only query, we want to assure we have a base-table
319
   * so we can later alter the query in entityFieldQueryAlter().
320
   *
321
   * @param $query
322
   *   The Select query.
323
   *
324
   * @return
325
   *   The alias of the base-table.
326
   */
327
  public function ensureBaseTable(SelectQueryInterface $query) {
328
    $tables = $query->getTables();
329

    
330
    // Check the current base table.
331
    foreach ($tables as $table) {
332
      if (empty($table['join'])) {
333
        $alias = $table['alias'];
334
        break;
335
      }
336
    }
337

    
338
    if (strpos($alias, 'field_data_') !== 0) {
339
      // The existing base-table is the correct one.
340
      return $alias;
341
    }
342

    
343
    // Join the known base-table.
344
    $target_type = $this->field['settings']['target_type'];
345
    $entity_info = entity_get_info($target_type);
346
    $target_type_base_table = $entity_info['base table'];
347
    $id = $entity_info['entity keys']['id'];
348

    
349
    // Return the alias of the table.
350
    return $query->innerJoin($target_type_base_table, NULL, "%alias.$id = $alias.entity_id");
351
  }
352
}
353

    
354
/**
355
 * Override for the Node type.
356
 *
357
 * This only exists to workaround core bugs.
358
 */
359
class EntityReference_SelectionHandler_Generic_node extends EntityReference_SelectionHandler_Generic {
360
  public function entityFieldQueryAlter(SelectQueryInterface $query) {
361
    // Adding the 'node_access' tag is sadly insufficient for nodes: core
362
    // requires us to also know about the concept of 'published' and
363
    // 'unpublished'. We need to do that as long as there are no access control
364
    // modules in use on the site. As long as one access control module is there,
365
    // it is supposed to handle this check.
366
    if (!user_access('bypass node access') && !count(module_implements('node_grants'))) {
367
      $base_table = $this->ensureBaseTable($query);
368
      $query->condition("$base_table.status", NODE_PUBLISHED);
369
    }
370
  }
371
}
372

    
373
/**
374
 * Override for the User type.
375
 *
376
 * This only exists to workaround core bugs.
377
 */
378
class EntityReference_SelectionHandler_Generic_user extends EntityReference_SelectionHandler_Generic {
379
  public function buildEntityFieldQuery($match = NULL, $match_operator = 'CONTAINS') {
380
    $query = parent::buildEntityFieldQuery($match, $match_operator);
381

    
382
    // The user entity doesn't have a label column.
383
    if (isset($match)) {
384
      $query->propertyCondition('name', $match, $match_operator);
385
    }
386

    
387
    // Adding the 'user_access' tag is sadly insufficient for users: core
388
    // requires us to also know about the concept of 'blocked' and
389
    // 'active'.
390
    if (!user_access('administer users')) {
391
      $query->propertyCondition('status', 1);
392
    }
393
    return $query;
394
  }
395

    
396
  public function entityFieldQueryAlter(SelectQueryInterface $query) {
397
    if (user_access('administer users')) {
398
      // In addition, if the user is administrator, we need to make sure to
399
      // match the anonymous user, that doesn't actually have a name in the
400
      // database.
401
      $conditions = &$query->conditions();
402
      foreach ($conditions as $key => $condition) {
403
        if ($key !== '#conjunction' && is_string($condition['field']) && $condition['field'] === 'users.name') {
404
          // Remove the condition.
405
          unset($conditions[$key]);
406

    
407
          // Re-add the condition and a condition on uid = 0 so that we end up
408
          // with a query in the form:
409
          //    WHERE (name LIKE :name) OR (:anonymous_name LIKE :name AND uid = 0)
410
          $or = db_or();
411
          $or->condition($condition['field'], $condition['value'], $condition['operator']);
412
          // Sadly, the Database layer doesn't allow us to build a condition
413
          // in the form ':placeholder = :placeholder2', because the 'field'
414
          // part of a condition is always escaped.
415
          // As a (cheap) workaround, we separately build a condition with no
416
          // field, and concatenate the field and the condition separately.
417
          $value_part = db_and();
418
          $value_part->condition('anonymous_name', $condition['value'], $condition['operator']);
419
          $value_part->compile(Database::getConnection(), $query);
420
          $or->condition(db_and()
421
            ->where(str_replace('anonymous_name', ':anonymous_name', (string) $value_part), $value_part->arguments() + array(':anonymous_name' => format_username(user_load(0))))
422
            ->condition('users.uid', 0)
423
          );
424
          $query->condition($or);
425
        }
426
      }
427
    }
428
  }
429
}
430

    
431
/**
432
 * Override for the Comment type.
433
 *
434
 * This only exists to workaround core bugs.
435
 */
436
class EntityReference_SelectionHandler_Generic_comment extends EntityReference_SelectionHandler_Generic {
437
  public function entityFieldQueryAlter(SelectQueryInterface $query) {
438
    // Adding the 'comment_access' tag is sadly insufficient for comments: core
439
    // requires us to also know about the concept of 'published' and
440
    // 'unpublished'.
441
    if (!user_access('administer comments')) {
442
      $base_table = $this->ensureBaseTable($query);
443
      $query->condition("$base_table.status", COMMENT_PUBLISHED);
444
    }
445

    
446
    // The Comment module doesn't implement any proper comment access,
447
    // and as a consequence doesn't make sure that comments cannot be viewed
448
    // when the user doesn't have access to the node.
449
    $tables = $query->getTables();
450
    $base_table = key($tables);
451
    $node_alias = $query->innerJoin('node', 'n', '%alias.nid = ' . $base_table . '.nid');
452
    // Pass the query to the node access control.
453
    $this->reAlterQuery($query, 'node_access', $node_alias);
454

    
455
    // Alas, the comment entity exposes a bundle, but doesn't have a bundle column
456
    // in the database. We have to alter the query ourself to go fetch the
457
    // bundle.
458
    $conditions = &$query->conditions();
459
    foreach ($conditions as $key => &$condition) {
460
      if ($key !== '#conjunction' && is_string($condition['field']) && $condition['field'] === 'node_type') {
461
        $condition['field'] = $node_alias . '.type';
462
        foreach ($condition['value'] as &$value) {
463
          if (substr($value, 0, 13) == 'comment_node_') {
464
            $value = substr($value, 13);
465
          }
466
        }
467
        break;
468
      }
469
    }
470

    
471
    // Passing the query to node_query_node_access_alter() is sadly
472
    // insufficient for nodes.
473
    // @see EntityReferenceHandler_node::entityFieldQueryAlter()
474
    if (!user_access('bypass node access') && !count(module_implements('node_grants'))) {
475
      $query->condition($node_alias . '.status', 1);
476
    }
477
  }
478
}
479

    
480
/**
481
 * Override for the File type.
482
 *
483
 * This only exists to workaround core bugs.
484
 */
485
class EntityReference_SelectionHandler_Generic_file extends EntityReference_SelectionHandler_Generic {
486
  public function entityFieldQueryAlter(SelectQueryInterface $query) {
487
    // Core forces us to know about 'permanent' vs. 'temporary' files.
488
    $tables = $query->getTables();
489
    $base_table = key($tables);
490
    $query->condition('status', FILE_STATUS_PERMANENT);
491

    
492
    // Access control to files is a very difficult business. For now, we are not
493
    // going to give it a shot.
494
    // @todo: fix this when core access control is less insane.
495
    return $query;
496
  }
497

    
498
  public function getLabel($entity) {
499
    // The file entity doesn't have a label. More over, the filename is
500
    // sometimes empty, so use the basename in that case.
501
    return $entity->filename !== '' ? $entity->filename : basename($entity->uri);
502
  }
503
}
504

    
505
/**
506
 * Override for the Taxonomy term type.
507
 *
508
 * This only exists to workaround core bugs.
509
 */
510
class EntityReference_SelectionHandler_Generic_taxonomy_term extends EntityReference_SelectionHandler_Generic {
511
  public function entityFieldQueryAlter(SelectQueryInterface $query) {
512
    // The Taxonomy module doesn't implement any proper taxonomy term access,
513
    // and as a consequence doesn't make sure that taxonomy terms cannot be viewed
514
    // when the user doesn't have access to the vocabulary.
515
    $base_table = $this->ensureBaseTable($query);
516
    $vocabulary_alias = $query->innerJoin('taxonomy_vocabulary', 'n', '%alias.vid = ' . $base_table . '.vid');
517
    $query->addMetadata('base_table', $vocabulary_alias);
518
    // Pass the query to the taxonomy access control.
519
    $this->reAlterQuery($query, 'taxonomy_vocabulary_access', $vocabulary_alias);
520

    
521
    // Also, the taxonomy term entity exposes a bundle, but doesn't have a bundle
522
    // column in the database. We have to alter the query ourself to go fetch
523
    // the bundle.
524
    $conditions = &$query->conditions();
525
    foreach ($conditions as $key => &$condition) {
526
      if ($key !== '#conjunction' && is_string($condition['field']) && $condition['field'] === 'vocabulary_machine_name') {
527
        $condition['field'] = $vocabulary_alias . '.machine_name';
528
        break;
529
      }
530
    }
531
  }
532

    
533
  /**
534
   * Implements EntityReferenceHandler::getReferencableEntities().
535
   */
536
  public function getReferencableEntities($match = NULL, $match_operator = 'CONTAINS', $limit = 0) {
537
    if ($match || $limit) {
538
      return parent::getReferencableEntities($match , $match_operator, $limit);
539
    }
540

    
541
    $options = array();
542
    $entity_type = $this->field['settings']['target_type'];
543

    
544
    // We imitate core by calling taxonomy_get_tree().
545
    $entity_info = entity_get_info('taxonomy_term');
546
    $bundles = !empty($this->field['settings']['handler_settings']['target_bundles']) ? $this->field['settings']['handler_settings']['target_bundles'] : array_keys($entity_info['bundles']);
547

    
548
    foreach ($bundles as $bundle) {
549
      if ($vocabulary = taxonomy_vocabulary_machine_name_load($bundle)) {
550
        if ($terms = taxonomy_get_tree($vocabulary->vid, 0, NULL, TRUE)) {
551
          foreach ($terms as $term) {
552
            $options[$vocabulary->machine_name][$term->tid] = str_repeat('-', $term->depth) . check_plain(entity_label('taxonomy_term', $term));
553
          }
554
        }
555
      }
556
    }
557

    
558
    return $options;
559
  }
560
}