Projet

Général

Profil

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

root / drupal7 / sites / all / modules / entityreference / plugins / selection / EntityReference_SelectionHandler_Generic.class.php @ 56aebcb7

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
      $entities = $this->getReferencableEntities($input, '=', 6);
212
      if (empty($entities)) {
213
        // Error if there are no entities available for a required field.
214
        form_error($element, t('There are no entities matching "%value"', array('%value' => $input)));
215
      }
216
      elseif (count($entities) > 5) {
217
        // Error if there are more than 5 matching entities.
218
        form_error($element, t('Many entities are called %value. Specify the one you want by appending the id in parentheses, like "@value (@id)"', array(
219
          '%value' => $input,
220
          '@value' => $input,
221
          '@id' => key($entities),
222
        )));
223
      }
224
      elseif (count($entities) > 1) {
225
        // More helpful error if there are only a few matching entities.
226
        $multiples = array();
227
        foreach ($entities as $id => $name) {
228
          $multiples[] = $name . ' (' . $id . ')';
229
        }
230
        form_error($element, t('Multiple entities match this reference; "%multiple"', array('%multiple' => implode('", "', $multiples))));
231
      }
232
      else {
233
        // Take the one and only matching entity.
234
        return key($entities);
235
      }
236
  }
237

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

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

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

    
272
    return $query;
273
  }
274

    
275
  /**
276
   * Implements EntityReferenceHandler::entityFieldQueryAlter().
277
   */
278
  public function entityFieldQueryAlter(SelectQueryInterface $query) {
279

    
280
  }
281

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

    
294
    $query->alterTags = array($tag => TRUE);
295
    $query->alterMetaData['base_table'] = $base_table;
296
    drupal_alter(array('query', 'query_' . $tag), $query);
297

    
298
    // Restore the tags and metadata.
299
    $query->alterTags = $old_tags;
300
    $query->alterMetaData = $old_metadata;
301
  }
302

    
303
  /**
304
   * Implements EntityReferenceHandler::getLabel().
305
   */
306
  public function getLabel($entity) {
307
    $target_type = $this->field['settings']['target_type'];
308
    return entity_access('view', $target_type, $entity) ? entity_label($target_type, $entity) : t('- Restricted access -');
309
  }
310

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

    
326
    // Check the current base table.
327
    foreach ($tables as $table) {
328
      if (empty($table['join'])) {
329
        $alias = $table['alias'];
330
        break;
331
      }
332
    }
333

    
334
    if (strpos($alias, 'field_data_') !== 0) {
335
      // The existing base-table is the correct one.
336
      return $alias;
337
    }
338

    
339
    // Join the known base-table.
340
    $target_type = $this->field['settings']['target_type'];
341
    $entity_info = entity_get_info($target_type);
342
    $target_type_base_table = $entity_info['base table'];
343
    $id = $entity_info['entity keys']['id'];
344

    
345
    // Return the alias of the table.
346
    return $query->innerJoin($target_type_base_table, NULL, "%alias.$id = $alias.entity_id");
347
  }
348
}
349

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

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

    
378
    // The user entity doesn't have a label column.
379
    if (isset($match)) {
380
      $query->propertyCondition('name', $match, $match_operator);
381
    }
382

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

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

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

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

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

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

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

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

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

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

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

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

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

    
537
    $options = array();
538
    $entity_type = $this->field['settings']['target_type'];
539

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

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

    
554
    return $options;
555
  }
556
}