comparison sites/all/modules/entityreference/plugins/selection/EntityReference_SelectionHandler_Generic.class.php @ 4:ce11bbd8f642

added modules
author danieleb <danielebarchiesi@me.com>
date Thu, 19 Sep 2013 10:38:44 +0100
parents
children
comparison
equal deleted inserted replaced
3:b28be78d8160 4:ce11bbd8f642
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 return entity_label($this->field['settings']['target_type'], $entity);
308 }
309
310 /**
311 * Ensure a base table exists for the query.
312 *
313 * If we have a field-only query, we want to assure we have a base-table
314 * so we can later alter the query in entityFieldQueryAlter().
315 *
316 * @param $query
317 * The Select query.
318 *
319 * @return
320 * The alias of the base-table.
321 */
322 public function ensureBaseTable(SelectQueryInterface $query) {
323 $tables = $query->getTables();
324
325 // Check the current base table.
326 foreach ($tables as $table) {
327 if (empty($table['join'])) {
328 $alias = $table['alias'];
329 break;
330 }
331 }
332
333 if (strpos($alias, 'field_data_') !== 0) {
334 // The existing base-table is the correct one.
335 return $alias;
336 }
337
338 // Join the known base-table.
339 $target_type = $this->field['settings']['target_type'];
340 $entity_info = entity_get_info($target_type);
341 $id = $entity_info['entity keys']['id'];
342 // Return the alias of the table.
343 return $query->innerJoin($target_type, NULL, "$target_type.$id = $alias.entity_id");
344 }
345 }
346
347 /**
348 * Override for the Node type.
349 *
350 * This only exists to workaround core bugs.
351 */
352 class EntityReference_SelectionHandler_Generic_node extends EntityReference_SelectionHandler_Generic {
353 public function entityFieldQueryAlter(SelectQueryInterface $query) {
354 // Adding the 'node_access' tag is sadly insufficient for nodes: core
355 // requires us to also know about the concept of 'published' and
356 // 'unpublished'. We need to do that as long as there are no access control
357 // modules in use on the site. As long as one access control module is there,
358 // it is supposed to handle this check.
359 if (!user_access('bypass node access') && !count(module_implements('node_grants'))) {
360 $base_table = $this->ensureBaseTable($query);
361 $query->condition("$base_table.status", NODE_PUBLISHED);
362 }
363 }
364 }
365
366 /**
367 * Override for the User type.
368 *
369 * This only exists to workaround core bugs.
370 */
371 class EntityReference_SelectionHandler_Generic_user extends EntityReference_SelectionHandler_Generic {
372 public function buildEntityFieldQuery($match = NULL, $match_operator = 'CONTAINS') {
373 $query = parent::buildEntityFieldQuery($match, $match_operator);
374
375 // The user entity doesn't have a label column.
376 if (isset($match)) {
377 $query->propertyCondition('name', $match, $match_operator);
378 }
379
380 // Adding the 'user_access' tag is sadly insufficient for users: core
381 // requires us to also know about the concept of 'blocked' and
382 // 'active'.
383 if (!user_access('administer users')) {
384 $query->propertyCondition('status', 1);
385 }
386 return $query;
387 }
388
389 public function entityFieldQueryAlter(SelectQueryInterface $query) {
390 if (user_access('administer users')) {
391 // In addition, if the user is administrator, we need to make sure to
392 // match the anonymous user, that doesn't actually have a name in the
393 // database.
394 $conditions = &$query->conditions();
395 foreach ($conditions as $key => $condition) {
396 if ($key !== '#conjunction' && is_string($condition['field']) && $condition['field'] === 'users.name') {
397 // Remove the condition.
398 unset($conditions[$key]);
399
400 // Re-add the condition and a condition on uid = 0 so that we end up
401 // with a query in the form:
402 // WHERE (name LIKE :name) OR (:anonymous_name LIKE :name AND uid = 0)
403 $or = db_or();
404 $or->condition($condition['field'], $condition['value'], $condition['operator']);
405 // Sadly, the Database layer doesn't allow us to build a condition
406 // in the form ':placeholder = :placeholder2', because the 'field'
407 // part of a condition is always escaped.
408 // As a (cheap) workaround, we separately build a condition with no
409 // field, and concatenate the field and the condition separately.
410 $value_part = db_and();
411 $value_part->condition('anonymous_name', $condition['value'], $condition['operator']);
412 $value_part->compile(Database::getConnection(), $query);
413 $or->condition(db_and()
414 ->where(str_replace('anonymous_name', ':anonymous_name', (string) $value_part), $value_part->arguments() + array(':anonymous_name' => format_username(user_load(0))))
415 ->condition('users.uid', 0)
416 );
417 $query->condition($or);
418 }
419 }
420 }
421 }
422 }
423
424 /**
425 * Override for the Comment type.
426 *
427 * This only exists to workaround core bugs.
428 */
429 class EntityReference_SelectionHandler_Generic_comment extends EntityReference_SelectionHandler_Generic {
430 public function entityFieldQueryAlter(SelectQueryInterface $query) {
431 // Adding the 'comment_access' tag is sadly insufficient for comments: core
432 // requires us to also know about the concept of 'published' and
433 // 'unpublished'.
434 if (!user_access('administer comments')) {
435 $base_table = $this->ensureBaseTable($query);
436 $query->condition("$base_table.status", COMMENT_PUBLISHED);
437 }
438
439 // The Comment module doesn't implement any proper comment access,
440 // and as a consequence doesn't make sure that comments cannot be viewed
441 // when the user doesn't have access to the node.
442 $tables = $query->getTables();
443 $base_table = key($tables);
444 $node_alias = $query->innerJoin('node', 'n', '%alias.nid = ' . $base_table . '.nid');
445 // Pass the query to the node access control.
446 $this->reAlterQuery($query, 'node_access', $node_alias);
447
448 // Alas, the comment entity exposes a bundle, but doesn't have a bundle column
449 // in the database. We have to alter the query ourself to go fetch the
450 // bundle.
451 $conditions = &$query->conditions();
452 foreach ($conditions as $key => &$condition) {
453 if ($key !== '#conjunction' && is_string($condition['field']) && $condition['field'] === 'node_type') {
454 $condition['field'] = $node_alias . '.type';
455 foreach ($condition['value'] as &$value) {
456 if (substr($value, 0, 13) == 'comment_node_') {
457 $value = substr($value, 13);
458 }
459 }
460 break;
461 }
462 }
463
464 // Passing the query to node_query_node_access_alter() is sadly
465 // insufficient for nodes.
466 // @see EntityReferenceHandler_node::entityFieldQueryAlter()
467 if (!user_access('bypass node access') && !count(module_implements('node_grants'))) {
468 $query->condition($node_alias . '.status', 1);
469 }
470 }
471 }
472
473 /**
474 * Override for the File type.
475 *
476 * This only exists to workaround core bugs.
477 */
478 class EntityReference_SelectionHandler_Generic_file extends EntityReference_SelectionHandler_Generic {
479 public function entityFieldQueryAlter(SelectQueryInterface $query) {
480 // Core forces us to know about 'permanent' vs. 'temporary' files.
481 $tables = $query->getTables();
482 $base_table = key($tables);
483 $query->condition('status', FILE_STATUS_PERMANENT);
484
485 // Access control to files is a very difficult business. For now, we are not
486 // going to give it a shot.
487 // @todo: fix this when core access control is less insane.
488 return $query;
489 }
490
491 public function getLabel($entity) {
492 // The file entity doesn't have a label. More over, the filename is
493 // sometimes empty, so use the basename in that case.
494 return $entity->filename !== '' ? $entity->filename : basename($entity->uri);
495 }
496 }
497
498 /**
499 * Override for the Taxonomy term type.
500 *
501 * This only exists to workaround core bugs.
502 */
503 class EntityReference_SelectionHandler_Generic_taxonomy_term extends EntityReference_SelectionHandler_Generic {
504 public function entityFieldQueryAlter(SelectQueryInterface $query) {
505 // The Taxonomy module doesn't implement any proper taxonomy term access,
506 // and as a consequence doesn't make sure that taxonomy terms cannot be viewed
507 // when the user doesn't have access to the vocabulary.
508 $base_table = $this->ensureBaseTable($query);
509 $vocabulary_alias = $query->innerJoin('taxonomy_vocabulary', 'n', '%alias.vid = ' . $base_table . '.vid');
510 $query->addMetadata('base_table', $vocabulary_alias);
511 // Pass the query to the taxonomy access control.
512 $this->reAlterQuery($query, 'taxonomy_vocabulary_access', $vocabulary_alias);
513
514 // Also, the taxonomy term entity exposes a bundle, but doesn't have a bundle
515 // column in the database. We have to alter the query ourself to go fetch
516 // the bundle.
517 $conditions = &$query->conditions();
518 foreach ($conditions as $key => &$condition) {
519 if ($key !== '#conjunction' && is_string($condition['field']) && $condition['field'] === 'vocabulary_machine_name') {
520 $condition['field'] = $vocabulary_alias . '.machine_name';
521 break;
522 }
523 }
524 }
525
526 /**
527 * Implements EntityReferenceHandler::getReferencableEntities().
528 */
529 public function getReferencableEntities($match = NULL, $match_operator = 'CONTAINS', $limit = 0) {
530 if ($match || $limit) {
531 return parent::getReferencableEntities($match , $match_operator, $limit);
532 }
533
534 $options = array();
535 $entity_type = $this->field['settings']['target_type'];
536
537 // We imitate core by calling taxonomy_get_tree().
538 $entity_info = entity_get_info('taxonomy_term');
539 $bundles = !empty($this->field['settings']['handler_settings']['target_bundles']) ? $this->field['settings']['handler_settings']['target_bundles'] : array_keys($entity_info['bundles']);
540
541 foreach ($bundles as $bundle) {
542 if ($vocabulary = taxonomy_vocabulary_machine_name_load($bundle)) {
543 if ($terms = taxonomy_get_tree($vocabulary->vid, 0)) {
544 foreach ($terms as $term) {
545 $options[$vocabulary->machine_name][$term->tid] = str_repeat('-', $term->depth) . check_plain($term->name);
546 }
547 }
548 }
549 }
550
551 return $options;
552 }
553 }