merged entityreference submodule

This commit is contained in:
Bachir Soussi Chiadmi
2015-04-19 15:18:46 +02:00
37 changed files with 5394 additions and 0 deletions

View File

@@ -0,0 +1,189 @@
<?php
/**
* @file
* CTools plugin class for the taxonomy-index behavior.
*/
/**
* Extends an entityreference field to maintain its references to taxonomy terms
* in the {taxonomy_index} table.
*
* Note, unlike entityPostInsert() and entityPostUpdate(), entityDelete()
* is not needed as cleanup is performed by taxonomy module in
* taxonomy_delete_node_index().
*/
class EntityReferenceBehavior_TaxonomyIndex extends EntityReference_BehaviorHandler_Abstract {
/**
* Overrides EntityReference_BehaviorHandler_Abstract::access().
*
* Ensure that it is only enabled for ER instances on nodes targeting
* terms, and the core variable to maintain index is enabled.
*/
public function access($field, $instance) {
if ($instance['entity_type'] != 'node' || $field['settings']['target_type'] != 'taxonomy_term') {
return;
}
if ($field['storage']['type'] !== 'field_sql_storage') {
// Field doesn't use SQL storage.
return;
}
return variable_get('taxonomy_maintain_index_table', TRUE);
}
/**
* Overrides EntityReference_BehaviorHandler_Abstract::entityPostInsert().
*
* Runs after hook_node_insert() used by taxonomy module.
*/
public function entityPostInsert($entity_type, $entity, $field, $instance) {
if ($entity_type != 'node') {
return;
}
$this->buildNodeIndex($entity);
}
/**
* Overrides EntityReference_BehaviorHandler_Abstract::entityPostUpdate().
*
* Runs after hook_node_update() used by taxonomy module.
*/
public function entityPostUpdate($entity_type, $entity, $field, $instance) {
if ($entity_type != 'node') {
return;
}
$this->buildNodeIndex($entity);
}
/**
* Builds and inserts taxonomy index entries for a given node.
*
* The index lists all terms that are related to a given node entity, and is
* therefore maintained at the entity level.
*
* @param $node
* The node object.
*
* @see taxonomy_build_node_index()
*/
protected function buildNodeIndex($node) {
// We maintain a denormalized table of term/node relationships, containing
// only data for current, published nodes.
$status = NULL;
if (variable_get('taxonomy_maintain_index_table', TRUE)) {
// If a node property is not set in the node object when node_save() is
// called, the old value from $node->original is used.
if (!empty($node->original)) {
$status = (int)(!empty($node->status) || (!isset($node->status) && !empty($node->original->status)));
$sticky = (int)(!empty($node->sticky) || (!isset($node->sticky) && !empty($node->original->sticky)));
}
else {
$status = (int)(!empty($node->status));
$sticky = (int)(!empty($node->sticky));
}
}
// We only maintain the taxonomy index for published nodes.
if ($status) {
// Collect a unique list of all the term IDs from all node fields.
$tid_all = array();
foreach (field_info_instances('node', $node->type) as $instance) {
$field_name = $instance['field_name'];
$field = field_info_field($field_name);
if (!empty($field['settings']['target_type']) && $field['settings']['target_type'] == 'taxonomy_term' && $field['storage']['type'] == 'field_sql_storage') {
// If a field value is not set in the node object when node_save() is
// called, the old value from $node->original is used.
if (isset($node->{$field_name})) {
$items = $node->{$field_name};
}
elseif (isset($node->original->{$field_name})) {
$items = $node->original->{$field_name};
}
else {
continue;
}
foreach (field_available_languages('node', $field) as $langcode) {
if (!empty($items[$langcode])) {
foreach ($items[$langcode] as $item) {
$tid_all[$item['target_id']] = $item['target_id'];
}
}
}
}
// Re-calculate the terms added in taxonomy_build_node_index() so
// we can optimize database queries.
$original_tid_all = array();
if ($field['module'] == 'taxonomy' && $field['storage']['type'] == 'field_sql_storage') {
// If a field value is not set in the node object when node_save() is
// called, the old value from $node->original is used.
if (isset($node->{$field_name})) {
$items = $node->{$field_name};
}
elseif (isset($node->original->{$field_name})) {
$items = $node->original->{$field_name};
}
else {
continue;
}
foreach (field_available_languages('node', $field) as $langcode) {
if (!empty($items[$langcode])) {
foreach ($items[$langcode] as $item) {
$original_tid_all[$item['tid']] = $item['tid'];
}
}
}
}
}
// Insert index entries for all the node's terms, that were not
// already inserted in taxonomy_build_node_index().
$tid_all = array_diff($tid_all, $original_tid_all);
// Insert index entries for all the node's terms.
if (!empty($tid_all)) {
$query = db_insert('taxonomy_index')->fields(array('nid', 'tid', 'sticky', 'created'));
foreach ($tid_all as $tid) {
$query->values(array(
'nid' => $node->nid,
'tid' => $tid,
'sticky' => $sticky,
'created' => $node->created,
));
}
$query->execute();
}
}
}
/**
* Overrides EntityReference_BehaviorHandler_Abstract::settingsForm().
*/
public function settingsForm($field, $instance) {
$form = array();
$target = $field['settings']['target_type'];
if ($target != 'taxonomy_term') {
$form['ti-on-terms'] = array(
'#markup' => t('This behavior can only be set when the target type is taxonomy_term, but the target of this field is %target.', array('%target' => $target)),
);
}
$entity_type = $instance['entity_type'];
if ($entity_type != 'node') {
$form['ti-on-nodes'] = array(
'#markup' => t('This behavior can only be set when the entity type is node, but the entity type of this instance is %type.', array('%type' => $entity_type)),
);
}
if (!variable_get('taxonomy_maintain_index_table', TRUE)) {
$form['ti-disabled'] = array(
'#markup' => t('This core variable "taxonomy_maintain_index_table" is disabled.'),
);
}
return $form;
}
}

View File

@@ -0,0 +1,18 @@
<?php
class EntityReferenceBehavior_ViewsFilterSelect extends EntityReference_BehaviorHandler_Abstract {
public function views_data_alter(&$data, $field) {
$entity_info = entity_get_info($field['settings']['target_type']);
$field_name = $field['field_name'] . '_target_id';
foreach ($data as $table_name => &$table_data) {
if (isset($table_data[$field_name])) {
// Set the entity id filter to use the in_operator handler with our
// own callback to return the values.
$table_data[$field_name]['filter']['handler'] = 'views_handler_filter_in_operator';
$table_data[$field_name]['filter']['options callback'] = 'entityreference_views_handler_options_list';
$table_data[$field_name]['filter']['options arguments'] = array($field['field_name']);
}
}
}
}

View File

@@ -0,0 +1,214 @@
<?php
/**
* Additional behaviors for a Entity Reference field.
*
* Implementations that wish to provide an implementation of this should
* register it using CTools' plugin system.
*/
interface EntityReference_BehaviorHandler {
/**
* Constructor for the behavior.
*
* @param $behavior
* The name of the behavior plugin.
*/
public function __construct($behavior);
/**
* Alter the field schema.
*
* @see hook_field_schema()
*/
public function schema_alter(&$schema, $field);
/**
* Alter the properties information of a field instance.
*
* @see entity_hook_field_info()
*/
public function property_info_alter(&$info, $entity_type, $field, $instance, $field_type);
/**
* Alter the views data of a field.
*
* @see entityreference_field_views_data()
*/
public function views_data_alter(&$data, $field);
/**
* Act on loading entity reference fields of entities.
*
* @see hook_field_load()
*/
public function load($entity_type, $entities, $field, $instances, $langcode, &$items);
/**
* Alter the empty status of a field item.
*
* @see hook_field_is_empty()
*/
public function is_empty_alter(&$empty, $item, $field);
/**
* Act on validating an entity reference field.
*
* @see hook_field_validate()
*/
public function validate($entity_type, $entity, $field, $instance, $langcode, $items, &$errors);
/**
* Act on presaving an entity reference field.
*
* @see hook_field_presave()
*/
public function presave($entity_type, $entity, $field, $instance, $langcode, &$items);
/**
* Act before inserting an entity reference field.
*
* @see hook_field_insert()
*/
public function insert($entity_type, $entity, $field, $instance, $langcode, &$items);
/**
* Act after inserting an entity reference field.
*
* @see hook_field_attach_insert()
*/
public function postInsert($entity_type, $entity, $field, $instance);
/**
* Act before updating an entity reference field.
*
* @see hook_field_update()
*/
public function update($entity_type, $entity, $field, $instance, $langcode, &$items);
/**
* Act after updating an entity reference field.
*
* @see hook_field_attach_update()
*/
public function postUpdate($entity_type, $entity, $field, $instance);
/**
* Act before deleting an entity with an entity reference field.
*
* @see hook_field_delete()
*/
public function delete($entity_type, $entity, $field, $instance, $langcode, &$items);
/**
* Act after deleting an entity with an entity reference field.
*
* @see hook_field_attach_delete()
*/
public function postDelete($entity_type, $entity, $field, $instance);
/**
* Act after inserting an entity.
*
* @see hook_entity_insert()
*/
public function entityPostInsert($entity_type, $entity, $field, $instance);
/**
* Act after updating an entity.
*
* @see hook_entity_update()
*/
public function entityPostUpdate($entity_type, $entity, $field, $instance);
/**
* Act after deleting an entity.
*
* @see hook_entity_delete()
*/
public function entityPostDelete($entity_type, $entity, $field, $instance);
/**
* Generate a settings form for this handler.
*/
public function settingsForm($field, $instance);
/**
* Determine if handler should appear.
*/
public function access($field, $instance);
}
/**
* An abstract implementation of EntityReference_BehaviorHandler.
*/
abstract class EntityReference_BehaviorHandler_Abstract implements EntityReference_BehaviorHandler {
/**
* The name of the behavior plugin.
*/
protected $behavior;
/**
* The plugin definition.
*/
protected $plugin;
public function __construct($behavior) {
$this->behavior = $behavior;
ctools_include('plugins');
$plugin = ctools_get_plugins('entityreference', 'behavior', $behavior);
$this->plugin = $plugin;
}
public function schema_alter(&$schema, $field) {}
public function property_info_alter(&$info, $entity_type, $field, $instance, $field_type) {}
public function views_data_alter(&$data, $field) {}
public function load($entity_type, $entities, $field, $instances, $langcode, &$items) {}
public function is_empty_alter(&$empty, $item, $field) {}
public function validate($entity_type, $entity, $field, $instance, $langcode, $items, &$errors) {}
public function presave($entity_type, $entity, $field, $instance, $langcode, &$items) {}
public function insert($entity_type, $entity, $field, $instance, $langcode, &$items) {}
public function postInsert($entity_type, $entity, $field, $instance) {}
public function update($entity_type, $entity, $field, $instance, $langcode, &$items) {}
public function postUpdate($entity_type, $entity, $field, $instance) {}
public function delete($entity_type, $entity, $field, $instance, $langcode, &$items) {}
public function postDelete($entity_type, $entity, $field, $instance) {}
public function entityPostInsert($entity_type, $entity, $field, $instance) {}
public function entityPostUpdate($entity_type, $entity, $field, $instance) {}
public function entityPostDelete($entity_type, $entity, $field, $instance) {}
public function settingsForm($field, $instance) {}
public function access($field, $instance) {
return TRUE;
}
}
/**
* A broken implementation of EntityReference_BehaviorHandler.
*/
class EntityReference_BehaviorHandler_Broken extends EntityReference_BehaviorHandler_Abstract {
public function settingsForm($field, $instance) {
$form['behavior_handler'] = array(
'#markup' => t('The selected behavior handler is broken.'),
);
return $form;
}
}

View File

@@ -0,0 +1,16 @@
<?php
/**
* @file
* CTools plugin declaration for taxonomy-index behavior.
*/
if (module_exists('taxonomy')) {
$plugin = array(
'title' => t('Taxonomy index'),
'description' => t('Include the term references created by instances of this field carried by node entities in the core {taxonomy_index} table. This will allow various modules to handle them like core term_reference fields.'),
'class' => 'EntityReferenceBehavior_TaxonomyIndex',
'behavior type' => 'instance',
'force enabled' => TRUE,
);
}

View File

@@ -0,0 +1,10 @@
<?php
if (module_exists('views')) {
$plugin = array(
'title' => t('Render Views filters as select list'),
'description' => t('Provides a select list for Views filters on this field. This should not be used when there are over 100 entities, as it might cause an out of memory error.'),
'class' => 'EntityReferenceBehavior_ViewsFilterSelect',
'behavior type' => 'field',
);
}

View File

@@ -0,0 +1,599 @@
<?php
/**
* A generic Entity handler.
*
* The generic base implementation has a variety of overrides to workaround
* core's largely deficient entity handling.
*/
class EntityReference_SelectionHandler_Generic implements EntityReference_SelectionHandler {
/**
* Implements EntityReferenceHandler::getInstance().
*/
public static function getInstance($field, $instance = NULL, $entity_type = NULL, $entity = NULL) {
$target_entity_type = $field['settings']['target_type'];
// Check if the entity type does exist and has a base table.
$entity_info = entity_get_info($target_entity_type);
if (empty($entity_info['base table'])) {
return EntityReference_SelectionHandler_Broken::getInstance($field, $instance);
}
if (class_exists($class_name = 'EntityReference_SelectionHandler_Generic_' . $target_entity_type)) {
return new $class_name($field, $instance, $entity_type, $entity);
}
else {
return new EntityReference_SelectionHandler_Generic($field, $instance, $entity_type, $entity);
}
}
protected function __construct($field, $instance = NULL, $entity_type = NULL, $entity = NULL) {
$this->field = $field;
$this->instance = $instance;
$this->entity_type = $entity_type;
$this->entity = $entity;
}
/**
* Implements EntityReferenceHandler::settingsForm().
*/
public static function settingsForm($field, $instance) {
$entity_info = entity_get_info($field['settings']['target_type']);
// Merge-in default values.
$field['settings']['handler_settings'] += array(
'target_bundles' => array(),
'sort' => array(
'type' => 'none',
)
);
if (!empty($entity_info['entity keys']['bundle'])) {
$bundles = array();
foreach ($entity_info['bundles'] as $bundle_name => $bundle_info) {
$bundles[$bundle_name] = $bundle_info['label'];
}
$form['target_bundles'] = array(
'#type' => 'checkboxes',
'#title' => t('Target bundles'),
'#options' => $bundles,
'#default_value' => $field['settings']['handler_settings']['target_bundles'],
'#size' => 6,
'#multiple' => TRUE,
'#description' => t('The bundles of the entity type that can be referenced. Optional, leave empty for all bundles.'),
'#element_validate' => array('_entityreference_element_validate_filter'),
);
}
else {
$form['target_bundles'] = array(
'#type' => 'value',
'#value' => array(),
);
}
$form['sort']['type'] = array(
'#type' => 'select',
'#title' => t('Sort by'),
'#options' => array(
'none' => t("Don't sort"),
'property' => t('A property of the base table of the entity'),
'field' => t('A field attached to this entity'),
),
'#ajax' => TRUE,
'#limit_validation_errors' => array(),
'#default_value' => $field['settings']['handler_settings']['sort']['type'],
);
$form['sort']['settings'] = array(
'#type' => 'container',
'#attributes' => array('class' => array('entityreference-settings')),
'#process' => array('_entityreference_form_process_merge_parent'),
);
if ($field['settings']['handler_settings']['sort']['type'] == 'property') {
// Merge-in default values.
$field['settings']['handler_settings']['sort'] += array(
'property' => NULL,
);
$form['sort']['settings']['property'] = array(
'#type' => 'select',
'#title' => t('Sort property'),
'#required' => TRUE,
'#options' => drupal_map_assoc($entity_info['schema_fields_sql']['base table']),
'#default_value' => $field['settings']['handler_settings']['sort']['property'],
);
}
elseif ($field['settings']['handler_settings']['sort']['type'] == 'field') {
// Merge-in default values.
$field['settings']['handler_settings']['sort'] += array(
'field' => NULL,
);
$fields = array();
foreach (field_info_instances($field['settings']['target_type']) as $bundle_name => $bundle_instances) {
foreach ($bundle_instances as $instance_name => $instance_info) {
$field_info = field_info_field($instance_name);
foreach ($field_info['columns'] as $column_name => $column_info) {
$fields[$instance_name . ':' . $column_name] = t('@label (column @column)', array('@label' => $instance_info['label'], '@column' => $column_name));
}
}
}
$form['sort']['settings']['field'] = array(
'#type' => 'select',
'#title' => t('Sort field'),
'#required' => TRUE,
'#options' => $fields,
'#default_value' => $field['settings']['handler_settings']['sort']['field'],
);
}
if ($field['settings']['handler_settings']['sort']['type'] != 'none') {
// Merge-in default values.
$field['settings']['handler_settings']['sort'] += array(
'direction' => 'ASC',
);
$form['sort']['settings']['direction'] = array(
'#type' => 'select',
'#title' => t('Sort direction'),
'#required' => TRUE,
'#options' => array(
'ASC' => t('Ascending'),
'DESC' => t('Descending'),
),
'#default_value' => $field['settings']['handler_settings']['sort']['direction'],
);
}
return $form;
}
/**
* Implements EntityReferenceHandler::getReferencableEntities().
*/
public function getReferencableEntities($match = NULL, $match_operator = 'CONTAINS', $limit = 0) {
$options = array();
$entity_type = $this->field['settings']['target_type'];
$query = $this->buildEntityFieldQuery($match, $match_operator);
if ($limit > 0) {
$query->range(0, $limit);
}
$results = $query->execute();
if (!empty($results[$entity_type])) {
$entities = entity_load($entity_type, array_keys($results[$entity_type]));
foreach ($entities as $entity_id => $entity) {
list(,, $bundle) = entity_extract_ids($entity_type, $entity);
$options[$bundle][$entity_id] = check_plain($this->getLabel($entity));
}
}
return $options;
}
/**
* Implements EntityReferenceHandler::countReferencableEntities().
*/
public function countReferencableEntities($match = NULL, $match_operator = 'CONTAINS') {
$query = $this->buildEntityFieldQuery($match, $match_operator);
return $query
->count()
->execute();
}
/**
* Implements EntityReferenceHandler::validateReferencableEntities().
*/
public function validateReferencableEntities(array $ids) {
if ($ids) {
$entity_type = $this->field['settings']['target_type'];
$query = $this->buildEntityFieldQuery();
$query->entityCondition('entity_id', $ids, 'IN');
$result = $query->execute();
if (!empty($result[$entity_type])) {
return array_keys($result[$entity_type]);
}
}
return array();
}
/**
* Implements EntityReferenceHandler::validateAutocompleteInput().
*/
public function validateAutocompleteInput($input, &$element, &$form_state, $form) {
$entities = $this->getReferencableEntities($input, '=', 6);
if (empty($entities)) {
// Error if there are no entities available for a required field.
form_error($element, t('There are no entities matching "%value"', array('%value' => $input)));
}
elseif (count($entities) > 5) {
// Error if there are more than 5 matching entities.
form_error($element, t('Many entities are called %value. Specify the one you want by appending the id in parentheses, like "@value (@id)"', array(
'%value' => $input,
'@value' => $input,
'@id' => key($entities),
)));
}
elseif (count($entities) > 1) {
// More helpful error if there are only a few matching entities.
$multiples = array();
foreach ($entities as $id => $name) {
$multiples[] = $name . ' (' . $id . ')';
}
form_error($element, t('Multiple entities match this reference; "%multiple"', array('%multiple' => implode('", "', $multiples))));
}
else {
// Take the one and only matching entity.
return key($entities);
}
}
/**
* Build an EntityFieldQuery to get referencable entities.
*/
protected function buildEntityFieldQuery($match = NULL, $match_operator = 'CONTAINS') {
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', $this->field['settings']['target_type']);
if (!empty($this->field['settings']['handler_settings']['target_bundles'])) {
$query->entityCondition('bundle', $this->field['settings']['handler_settings']['target_bundles'], 'IN');
}
if (isset($match)) {
$entity_info = entity_get_info($this->field['settings']['target_type']);
if (isset($entity_info['entity keys']['label'])) {
$query->propertyCondition($entity_info['entity keys']['label'], $match, $match_operator);
}
}
// Add a generic entity access tag to the query.
$query->addTag($this->field['settings']['target_type'] . '_access');
$query->addTag('entityreference');
$query->addMetaData('field', $this->field);
$query->addMetaData('entityreference_selection_handler', $this);
// Add the sort option.
if (!empty($this->field['settings']['handler_settings']['sort'])) {
$sort_settings = $this->field['settings']['handler_settings']['sort'];
if ($sort_settings['type'] == 'property') {
$query->propertyOrderBy($sort_settings['property'], $sort_settings['direction']);
}
elseif ($sort_settings['type'] == 'field') {
list($field, $column) = explode(':', $sort_settings['field'], 2);
$query->fieldOrderBy($field, $column, $sort_settings['direction']);
}
}
return $query;
}
/**
* Implements EntityReferenceHandler::entityFieldQueryAlter().
*/
public function entityFieldQueryAlter(SelectQueryInterface $query) {
}
/**
* Helper method: pass a query to the alteration system again.
*
* This allow Entity Reference to add a tag to an existing query, to ask
* access control mechanisms to alter it again.
*/
protected function reAlterQuery(SelectQueryInterface $query, $tag, $base_table) {
// Save the old tags and metadata.
// For some reason, those are public.
$old_tags = $query->alterTags;
$old_metadata = $query->alterMetaData;
$query->alterTags = array($tag => TRUE);
$query->alterMetaData['base_table'] = $base_table;
drupal_alter(array('query', 'query_' . $tag), $query);
// Restore the tags and metadata.
$query->alterTags = $old_tags;
$query->alterMetaData = $old_metadata;
}
/**
* Implements EntityReferenceHandler::getLabel().
*/
public function getLabel($entity) {
return entity_label($this->field['settings']['target_type'], $entity);
}
/**
* Ensure a base table exists for the query.
*
* If we have a field-only query, we want to assure we have a base-table
* so we can later alter the query in entityFieldQueryAlter().
*
* @param $query
* The Select query.
*
* @return
* The alias of the base-table.
*/
public function ensureBaseTable(SelectQueryInterface $query) {
$tables = $query->getTables();
// Check the current base table.
foreach ($tables as $table) {
if (empty($table['join'])) {
$alias = $table['alias'];
break;
}
}
if (strpos($alias, 'field_data_') !== 0) {
// The existing base-table is the correct one.
return $alias;
}
// Join the known base-table.
$target_type = $this->field['settings']['target_type'];
$entity_info = entity_get_info($target_type);
$id = $entity_info['entity keys']['id'];
// Return the alias of the table.
return $query->innerJoin($target_type, NULL, "$target_type.$id = $alias.entity_id");
}
}
/**
* Override for the Node type.
*
* This only exists to workaround core bugs.
*/
class EntityReference_SelectionHandler_Generic_node extends EntityReference_SelectionHandler_Generic {
public function entityFieldQueryAlter(SelectQueryInterface $query) {
// Adding the 'node_access' tag is sadly insufficient for nodes: core
// requires us to also know about the concept of 'published' and
// 'unpublished'. We need to do that as long as there are no access control
// modules in use on the site. As long as one access control module is there,
// it is supposed to handle this check.
if (!user_access('bypass node access') && !count(module_implements('node_grants'))) {
$base_table = $this->ensureBaseTable($query);
$query->condition("$base_table.status", NODE_PUBLISHED);
}
}
}
/**
* Override for the User type.
*
* This only exists to workaround core bugs.
*/
class EntityReference_SelectionHandler_Generic_user extends EntityReference_SelectionHandler_Generic {
/**
* Implements EntityReferenceHandler::settingsForm().
*/
public static function settingsForm($field, $instance) {
$settings = $field['settings']['handler_settings'];
$form = parent::settingsForm($field, $instance);
$form['referenceable_roles'] = array(
'#type' => 'checkboxes',
'#title' => t('User roles that can be referenced'),
'#default_value' => isset($settings['referenceable_roles']) ? array_filter($settings['referenceable_roles']) : array(),
'#options' => user_roles(TRUE),
);
$form['referenceable_status'] = array(
'#type' => 'checkboxes',
'#title' => t('User status that can be referenced'),
'#default_value' => isset($settings['referenceable_status']) ? array_filter($settings['referenceable_status']) : array('active' => 'active'),
'#options' => array('active' => t('Active'), 'blocked' => t('Blocked')),
);
return $form;
}
public function buildEntityFieldQuery($match = NULL, $match_operator = 'CONTAINS') {
$query = parent::buildEntityFieldQuery($match, $match_operator);
// The user entity doesn't have a label column.
if (isset($match)) {
$query->propertyCondition('name', $match, $match_operator);
}
$field = $this->field;
$settings = $field['settings']['handler_settings'];
$referenceable_roles = isset($settings['referenceable_roles']) ? array_filter($settings['referenceable_roles']) : array();
$referenceable_status = isset($settings['referenceable_status']) ? array_filter($settings['referenceable_status']) : array('active' => 'active');
// If this filter is not filled, use the users access permissions.
if (empty($referenceable_status)) {
// Adding the 'user_access' tag is sadly insufficient for users: core
// requires us to also know about the concept of 'blocked' and 'active'.
if (!user_access('administer users')) {
$query->propertyCondition('status', 1);
}
}
elseif (count($referenceable_status) == 1) {
$values = array('active' => 1, 'blocked' => 0);
$query->propertyCondition('status', $values[key($referenceable_status)]);
}
return $query;
}
public function entityFieldQueryAlter(SelectQueryInterface $query) {
$conditions = &$query->conditions();
if (user_access('administer users')) {
// If the user is administrator, we need to make sure to
// match the anonymous user, that doesn't actually have a name in the
// database.
foreach ($conditions as $key => $condition) {
if ($key !== '#conjunction' && is_string($condition['field']) && $condition['field'] === 'users.name') {
// Remove the condition.
unset($conditions[$key]);
// Re-add the condition and a condition on uid = 0 so that we end up
// with a query in the form:
// WHERE (name LIKE :name) OR (:anonymous_name LIKE :name AND uid = 0)
$or = db_or();
$or->condition($condition['field'], $condition['value'], $condition['operator']);
// Sadly, the Database layer doesn't allow us to build a condition
// in the form ':placeholder = :placeholder2', because the 'field'
// part of a condition is always escaped.
// As a (cheap) workaround, we separately build a condition with no
// field, and concatenate the field and the condition separately.
$value_part = db_and();
$value_part->condition('anonymous_name', $condition['value'], $condition['operator']);
$value_part->compile(Database::getConnection(), $query);
$or->condition(db_and()
->where(str_replace('anonymous_name', ':anonymous_name', (string) $value_part), $value_part->arguments() + array(':anonymous_name' => format_username(user_load(0))))
->condition('users.uid', 0)
);
$query->condition($or);
}
}
}
$field = $this->field;
$settings = $field['settings']['handler_settings'];
$referenceable_roles = isset($settings['referenceable_roles']) ? array_filter($settings['referenceable_roles']) : array();
if (!$referenceable_roles || !empty($referenceable_roles[DRUPAL_AUTHENTICATED_RID])) {
// Return early if "authenticated user" choosen.
return;
}
if (!isset($referenceable_roles[DRUPAL_AUTHENTICATED_RID])) {
$query->join('users_roles', 'users_roles', 'users.uid = users_roles.uid');
$query->condition('users_roles.rid', array_keys($referenceable_roles), 'IN');
}
}
}
/**
* Override for the Comment type.
*
* This only exists to workaround core bugs.
*/
class EntityReference_SelectionHandler_Generic_comment extends EntityReference_SelectionHandler_Generic {
public function entityFieldQueryAlter(SelectQueryInterface $query) {
// Adding the 'comment_access' tag is sadly insufficient for comments: core
// requires us to also know about the concept of 'published' and
// 'unpublished'.
if (!user_access('administer comments')) {
$base_table = $this->ensureBaseTable($query);
$query->condition("$base_table.status", COMMENT_PUBLISHED);
}
// The Comment module doesn't implement any proper comment access,
// and as a consequence doesn't make sure that comments cannot be viewed
// when the user doesn't have access to the node.
$tables = $query->getTables();
$base_table = key($tables);
$node_alias = $query->innerJoin('node', 'n', '%alias.nid = ' . $base_table . '.nid');
// Pass the query to the node access control.
$this->reAlterQuery($query, 'node_access', $node_alias);
// Alas, the comment entity exposes a bundle, but doesn't have a bundle column
// in the database. We have to alter the query ourself to go fetch the
// bundle.
$conditions = &$query->conditions();
foreach ($conditions as $key => &$condition) {
if ($key !== '#conjunction' && is_string($condition['field']) && $condition['field'] === 'node_type') {
$condition['field'] = $node_alias . '.type';
foreach ($condition['value'] as &$value) {
if (substr($value, 0, 13) == 'comment_node_') {
$value = substr($value, 13);
}
}
break;
}
}
// Passing the query to node_query_node_access_alter() is sadly
// insufficient for nodes.
// @see EntityReferenceHandler_node::entityFieldQueryAlter()
if (!user_access('bypass node access') && !count(module_implements('node_grants'))) {
$query->condition($node_alias . '.status', 1);
}
}
}
/**
* Override for the File type.
*
* This only exists to workaround core bugs.
*/
class EntityReference_SelectionHandler_Generic_file extends EntityReference_SelectionHandler_Generic {
public function entityFieldQueryAlter(SelectQueryInterface $query) {
// Core forces us to know about 'permanent' vs. 'temporary' files.
$tables = $query->getTables();
$base_table = key($tables);
$query->condition('status', FILE_STATUS_PERMANENT);
// Access control to files is a very difficult business. For now, we are not
// going to give it a shot.
// @todo: fix this when core access control is less insane.
return $query;
}
public function getLabel($entity) {
// The file entity doesn't have a label. More over, the filename is
// sometimes empty, so use the basename in that case.
return $entity->filename !== '' ? $entity->filename : basename($entity->uri);
}
}
/**
* Override for the Taxonomy term type.
*
* This only exists to workaround core bugs.
*/
class EntityReference_SelectionHandler_Generic_taxonomy_term extends EntityReference_SelectionHandler_Generic {
public function entityFieldQueryAlter(SelectQueryInterface $query) {
// The Taxonomy module doesn't implement any proper taxonomy term access,
// and as a consequence doesn't make sure that taxonomy terms cannot be viewed
// when the user doesn't have access to the vocabulary.
$base_table = $this->ensureBaseTable($query);
$vocabulary_alias = $query->innerJoin('taxonomy_vocabulary', 'n', '%alias.vid = ' . $base_table . '.vid');
$query->addMetadata('base_table', $vocabulary_alias);
// Pass the query to the taxonomy access control.
$this->reAlterQuery($query, 'taxonomy_vocabulary_access', $vocabulary_alias);
// Also, the taxonomy term entity exposes a bundle, but doesn't have a bundle
// column in the database. We have to alter the query ourself to go fetch
// the bundle.
$conditions = &$query->conditions();
foreach ($conditions as $key => &$condition) {
if ($key !== '#conjunction' && is_string($condition['field']) && $condition['field'] === 'vocabulary_machine_name') {
$condition['field'] = $vocabulary_alias . '.machine_name';
break;
}
}
}
/**
* Implements EntityReferenceHandler::getReferencableEntities().
*/
public function getReferencableEntities($match = NULL, $match_operator = 'CONTAINS', $limit = 0) {
if ($match || $limit) {
return parent::getReferencableEntities($match , $match_operator, $limit);
}
$options = array();
$entity_type = $this->field['settings']['target_type'];
// We imitate core by calling taxonomy_get_tree().
$entity_info = entity_get_info('taxonomy_term');
$bundles = !empty($this->field['settings']['handler_settings']['target_bundles']) ? $this->field['settings']['handler_settings']['target_bundles'] : array_keys($entity_info['bundles']);
foreach ($bundles as $bundle) {
if ($vocabulary = taxonomy_vocabulary_machine_name_load($bundle)) {
if ($terms = taxonomy_get_tree($vocabulary->vid, 0)) {
foreach ($terms as $term) {
$options[$vocabulary->machine_name][$term->tid] = str_repeat('-', $term->depth) . check_plain($term->name);
}
}
}
}
return $options;
}
}

View File

@@ -0,0 +1,553 @@
<?php
/**
* A generic Entity handler.
*
* The generic base implementation has a variety of overrides to workaround
* core's largely deficient entity handling.
*/
class EntityReference_SelectionHandler_Generic implements EntityReference_SelectionHandler {
/**
* Implements EntityReferenceHandler::getInstance().
*/
public static function getInstance($field, $instance = NULL, $entity_type = NULL, $entity = NULL) {
$target_entity_type = $field['settings']['target_type'];
// Check if the entity type does exist and has a base table.
$entity_info = entity_get_info($target_entity_type);
if (empty($entity_info['base table'])) {
return EntityReference_SelectionHandler_Broken::getInstance($field, $instance);
}
if (class_exists($class_name = 'EntityReference_SelectionHandler_Generic_' . $target_entity_type)) {
return new $class_name($field, $instance, $entity_type, $entity);
}
else {
return new EntityReference_SelectionHandler_Generic($field, $instance, $entity_type, $entity);
}
}
protected function __construct($field, $instance = NULL, $entity_type = NULL, $entity = NULL) {
$this->field = $field;
$this->instance = $instance;
$this->entity_type = $entity_type;
$this->entity = $entity;
}
/**
* Implements EntityReferenceHandler::settingsForm().
*/
public static function settingsForm($field, $instance) {
$entity_info = entity_get_info($field['settings']['target_type']);
// Merge-in default values.
$field['settings']['handler_settings'] += array(
'target_bundles' => array(),
'sort' => array(
'type' => 'none',
)
);
if (!empty($entity_info['entity keys']['bundle'])) {
$bundles = array();
foreach ($entity_info['bundles'] as $bundle_name => $bundle_info) {
$bundles[$bundle_name] = $bundle_info['label'];
}
$form['target_bundles'] = array(
'#type' => 'checkboxes',
'#title' => t('Target bundles'),
'#options' => $bundles,
'#default_value' => $field['settings']['handler_settings']['target_bundles'],
'#size' => 6,
'#multiple' => TRUE,
'#description' => t('The bundles of the entity type that can be referenced. Optional, leave empty for all bundles.'),
'#element_validate' => array('_entityreference_element_validate_filter'),
);
}
else {
$form['target_bundles'] = array(
'#type' => 'value',
'#value' => array(),
);
}
$form['sort']['type'] = array(
'#type' => 'select',
'#title' => t('Sort by'),
'#options' => array(
'none' => t("Don't sort"),
'property' => t('A property of the base table of the entity'),
'field' => t('A field attached to this entity'),
),
'#ajax' => TRUE,
'#limit_validation_errors' => array(),
'#default_value' => $field['settings']['handler_settings']['sort']['type'],
);
$form['sort']['settings'] = array(
'#type' => 'container',
'#attributes' => array('class' => array('entityreference-settings')),
'#process' => array('_entityreference_form_process_merge_parent'),
);
if ($field['settings']['handler_settings']['sort']['type'] == 'property') {
// Merge-in default values.
$field['settings']['handler_settings']['sort'] += array(
'property' => NULL,
);
$form['sort']['settings']['property'] = array(
'#type' => 'select',
'#title' => t('Sort property'),
'#required' => TRUE,
'#options' => drupal_map_assoc($entity_info['schema_fields_sql']['base table']),
'#default_value' => $field['settings']['handler_settings']['sort']['property'],
);
}
elseif ($field['settings']['handler_settings']['sort']['type'] == 'field') {
// Merge-in default values.
$field['settings']['handler_settings']['sort'] += array(
'field' => NULL,
);
$fields = array();
foreach (field_info_instances($field['settings']['target_type']) as $bundle_name => $bundle_instances) {
foreach ($bundle_instances as $instance_name => $instance_info) {
$field_info = field_info_field($instance_name);
foreach ($field_info['columns'] as $column_name => $column_info) {
$fields[$instance_name . ':' . $column_name] = t('@label (column @column)', array('@label' => $instance_info['label'], '@column' => $column_name));
}
}
}
$form['sort']['settings']['field'] = array(
'#type' => 'select',
'#title' => t('Sort field'),
'#required' => TRUE,
'#options' => $fields,
'#default_value' => $field['settings']['handler_settings']['sort']['field'],
);
}
if ($field['settings']['handler_settings']['sort']['type'] != 'none') {
// Merge-in default values.
$field['settings']['handler_settings']['sort'] += array(
'direction' => 'ASC',
);
$form['sort']['settings']['direction'] = array(
'#type' => 'select',
'#title' => t('Sort direction'),
'#required' => TRUE,
'#options' => array(
'ASC' => t('Ascending'),
'DESC' => t('Descending'),
),
'#default_value' => $field['settings']['handler_settings']['sort']['direction'],
);
}
return $form;
}
/**
* Implements EntityReferenceHandler::getReferencableEntities().
*/
public function getReferencableEntities($match = NULL, $match_operator = 'CONTAINS', $limit = 0) {
$options = array();
$entity_type = $this->field['settings']['target_type'];
$query = $this->buildEntityFieldQuery($match, $match_operator);
if ($limit > 0) {
$query->range(0, $limit);
}
$results = $query->execute();
if (!empty($results[$entity_type])) {
$entities = entity_load($entity_type, array_keys($results[$entity_type]));
foreach ($entities as $entity_id => $entity) {
list(,, $bundle) = entity_extract_ids($entity_type, $entity);
$options[$bundle][$entity_id] = check_plain($this->getLabel($entity));
}
}
return $options;
}
/**
* Implements EntityReferenceHandler::countReferencableEntities().
*/
public function countReferencableEntities($match = NULL, $match_operator = 'CONTAINS') {
$query = $this->buildEntityFieldQuery($match, $match_operator);
return $query
->count()
->execute();
}
/**
* Implements EntityReferenceHandler::validateReferencableEntities().
*/
public function validateReferencableEntities(array $ids) {
if ($ids) {
$entity_type = $this->field['settings']['target_type'];
$query = $this->buildEntityFieldQuery();
$query->entityCondition('entity_id', $ids, 'IN');
$result = $query->execute();
if (!empty($result[$entity_type])) {
return array_keys($result[$entity_type]);
}
}
return array();
}
/**
* Implements EntityReferenceHandler::validateAutocompleteInput().
*/
public function validateAutocompleteInput($input, &$element, &$form_state, $form) {
$entities = $this->getReferencableEntities($input, '=', 6);
if (empty($entities)) {
// Error if there are no entities available for a required field.
form_error($element, t('There are no entities matching "%value"', array('%value' => $input)));
}
elseif (count($entities) > 5) {
// Error if there are more than 5 matching entities.
form_error($element, t('Many entities are called %value. Specify the one you want by appending the id in parentheses, like "@value (@id)"', array(
'%value' => $input,
'@value' => $input,
'@id' => key($entities),
)));
}
elseif (count($entities) > 1) {
// More helpful error if there are only a few matching entities.
$multiples = array();
foreach ($entities as $id => $name) {
$multiples[] = $name . ' (' . $id . ')';
}
form_error($element, t('Multiple entities match this reference; "%multiple"', array('%multiple' => implode('", "', $multiples))));
}
else {
// Take the one and only matching entity.
return key($entities);
}
}
/**
* Build an EntityFieldQuery to get referencable entities.
*/
protected function buildEntityFieldQuery($match = NULL, $match_operator = 'CONTAINS') {
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', $this->field['settings']['target_type']);
if (!empty($this->field['settings']['handler_settings']['target_bundles'])) {
$query->entityCondition('bundle', $this->field['settings']['handler_settings']['target_bundles'], 'IN');
}
if (isset($match)) {
$entity_info = entity_get_info($this->field['settings']['target_type']);
if (isset($entity_info['entity keys']['label'])) {
$query->propertyCondition($entity_info['entity keys']['label'], $match, $match_operator);
}
}
// Add a generic entity access tag to the query.
$query->addTag($this->field['settings']['target_type'] . '_access');
$query->addTag('entityreference');
$query->addMetaData('field', $this->field);
$query->addMetaData('entityreference_selection_handler', $this);
// Add the sort option.
if (!empty($this->field['settings']['handler_settings']['sort'])) {
$sort_settings = $this->field['settings']['handler_settings']['sort'];
if ($sort_settings['type'] == 'property') {
$query->propertyOrderBy($sort_settings['property'], $sort_settings['direction']);
}
elseif ($sort_settings['type'] == 'field') {
list($field, $column) = explode(':', $sort_settings['field'], 2);
$query->fieldOrderBy($field, $column, $sort_settings['direction']);
}
}
return $query;
}
/**
* Implements EntityReferenceHandler::entityFieldQueryAlter().
*/
public function entityFieldQueryAlter(SelectQueryInterface $query) {
}
/**
* Helper method: pass a query to the alteration system again.
*
* This allow Entity Reference to add a tag to an existing query, to ask
* access control mechanisms to alter it again.
*/
protected function reAlterQuery(SelectQueryInterface $query, $tag, $base_table) {
// Save the old tags and metadata.
// For some reason, those are public.
$old_tags = $query->alterTags;
$old_metadata = $query->alterMetaData;
$query->alterTags = array($tag => TRUE);
$query->alterMetaData['base_table'] = $base_table;
drupal_alter(array('query', 'query_' . $tag), $query);
// Restore the tags and metadata.
$query->alterTags = $old_tags;
$query->alterMetaData = $old_metadata;
}
/**
* Implements EntityReferenceHandler::getLabel().
*/
public function getLabel($entity) {
return entity_label($this->field['settings']['target_type'], $entity);
}
/**
* Ensure a base table exists for the query.
*
* If we have a field-only query, we want to assure we have a base-table
* so we can later alter the query in entityFieldQueryAlter().
*
* @param $query
* The Select query.
*
* @return
* The alias of the base-table.
*/
public function ensureBaseTable(SelectQueryInterface $query) {
$tables = $query->getTables();
// Check the current base table.
foreach ($tables as $table) {
if (empty($table['join'])) {
$alias = $table['alias'];
break;
}
}
if (strpos($alias, 'field_data_') !== 0) {
// The existing base-table is the correct one.
return $alias;
}
// Join the known base-table.
$target_type = $this->field['settings']['target_type'];
$entity_info = entity_get_info($target_type);
$id = $entity_info['entity keys']['id'];
// Return the alias of the table.
return $query->innerJoin($target_type, NULL, "$target_type.$id = $alias.entity_id");
}
}
/**
* Override for the Node type.
*
* This only exists to workaround core bugs.
*/
class EntityReference_SelectionHandler_Generic_node extends EntityReference_SelectionHandler_Generic {
public function entityFieldQueryAlter(SelectQueryInterface $query) {
// Adding the 'node_access' tag is sadly insufficient for nodes: core
// requires us to also know about the concept of 'published' and
// 'unpublished'. We need to do that as long as there are no access control
// modules in use on the site. As long as one access control module is there,
// it is supposed to handle this check.
if (!user_access('bypass node access') && !count(module_implements('node_grants'))) {
$base_table = $this->ensureBaseTable($query);
$query->condition("$base_table.status", NODE_PUBLISHED);
}
}
}
/**
* Override for the User type.
*
* This only exists to workaround core bugs.
*/
class EntityReference_SelectionHandler_Generic_user extends EntityReference_SelectionHandler_Generic {
public function buildEntityFieldQuery($match = NULL, $match_operator = 'CONTAINS') {
$query = parent::buildEntityFieldQuery($match, $match_operator);
// The user entity doesn't have a label column.
if (isset($match)) {
$query->propertyCondition('name', $match, $match_operator);
}
// Adding the 'user_access' tag is sadly insufficient for users: core
// requires us to also know about the concept of 'blocked' and
// 'active'.
if (!user_access('administer users')) {
$query->propertyCondition('status', 1);
}
return $query;
}
public function entityFieldQueryAlter(SelectQueryInterface $query) {
if (user_access('administer users')) {
// In addition, if the user is administrator, we need to make sure to
// match the anonymous user, that doesn't actually have a name in the
// database.
$conditions = &$query->conditions();
foreach ($conditions as $key => $condition) {
if ($key !== '#conjunction' && is_string($condition['field']) && $condition['field'] === 'users.name') {
// Remove the condition.
unset($conditions[$key]);
// Re-add the condition and a condition on uid = 0 so that we end up
// with a query in the form:
// WHERE (name LIKE :name) OR (:anonymous_name LIKE :name AND uid = 0)
$or = db_or();
$or->condition($condition['field'], $condition['value'], $condition['operator']);
// Sadly, the Database layer doesn't allow us to build a condition
// in the form ':placeholder = :placeholder2', because the 'field'
// part of a condition is always escaped.
// As a (cheap) workaround, we separately build a condition with no
// field, and concatenate the field and the condition separately.
$value_part = db_and();
$value_part->condition('anonymous_name', $condition['value'], $condition['operator']);
$value_part->compile(Database::getConnection(), $query);
$or->condition(db_and()
->where(str_replace('anonymous_name', ':anonymous_name', (string) $value_part), $value_part->arguments() + array(':anonymous_name' => format_username(user_load(0))))
->condition('users.uid', 0)
);
$query->condition($or);
}
}
}
}
}
/**
* Override for the Comment type.
*
* This only exists to workaround core bugs.
*/
class EntityReference_SelectionHandler_Generic_comment extends EntityReference_SelectionHandler_Generic {
public function entityFieldQueryAlter(SelectQueryInterface $query) {
// Adding the 'comment_access' tag is sadly insufficient for comments: core
// requires us to also know about the concept of 'published' and
// 'unpublished'.
if (!user_access('administer comments')) {
$base_table = $this->ensureBaseTable($query);
$query->condition("$base_table.status", COMMENT_PUBLISHED);
}
// The Comment module doesn't implement any proper comment access,
// and as a consequence doesn't make sure that comments cannot be viewed
// when the user doesn't have access to the node.
$tables = $query->getTables();
$base_table = key($tables);
$node_alias = $query->innerJoin('node', 'n', '%alias.nid = ' . $base_table . '.nid');
// Pass the query to the node access control.
$this->reAlterQuery($query, 'node_access', $node_alias);
// Alas, the comment entity exposes a bundle, but doesn't have a bundle column
// in the database. We have to alter the query ourself to go fetch the
// bundle.
$conditions = &$query->conditions();
foreach ($conditions as $key => &$condition) {
if ($key !== '#conjunction' && is_string($condition['field']) && $condition['field'] === 'node_type') {
$condition['field'] = $node_alias . '.type';
foreach ($condition['value'] as &$value) {
if (substr($value, 0, 13) == 'comment_node_') {
$value = substr($value, 13);
}
}
break;
}
}
// Passing the query to node_query_node_access_alter() is sadly
// insufficient for nodes.
// @see EntityReferenceHandler_node::entityFieldQueryAlter()
if (!user_access('bypass node access') && !count(module_implements('node_grants'))) {
$query->condition($node_alias . '.status', 1);
}
}
}
/**
* Override for the File type.
*
* This only exists to workaround core bugs.
*/
class EntityReference_SelectionHandler_Generic_file extends EntityReference_SelectionHandler_Generic {
public function entityFieldQueryAlter(SelectQueryInterface $query) {
// Core forces us to know about 'permanent' vs. 'temporary' files.
$tables = $query->getTables();
$base_table = key($tables);
$query->condition('status', FILE_STATUS_PERMANENT);
// Access control to files is a very difficult business. For now, we are not
// going to give it a shot.
// @todo: fix this when core access control is less insane.
return $query;
}
public function getLabel($entity) {
// The file entity doesn't have a label. More over, the filename is
// sometimes empty, so use the basename in that case.
return $entity->filename !== '' ? $entity->filename : basename($entity->uri);
}
}
/**
* Override for the Taxonomy term type.
*
* This only exists to workaround core bugs.
*/
class EntityReference_SelectionHandler_Generic_taxonomy_term extends EntityReference_SelectionHandler_Generic {
public function entityFieldQueryAlter(SelectQueryInterface $query) {
// The Taxonomy module doesn't implement any proper taxonomy term access,
// and as a consequence doesn't make sure that taxonomy terms cannot be viewed
// when the user doesn't have access to the vocabulary.
$base_table = $this->ensureBaseTable($query);
$vocabulary_alias = $query->innerJoin('taxonomy_vocabulary', 'n', '%alias.vid = ' . $base_table . '.vid');
$query->addMetadata('base_table', $vocabulary_alias);
// Pass the query to the taxonomy access control.
$this->reAlterQuery($query, 'taxonomy_vocabulary_access', $vocabulary_alias);
// Also, the taxonomy term entity exposes a bundle, but doesn't have a bundle
// column in the database. We have to alter the query ourself to go fetch
// the bundle.
$conditions = &$query->conditions();
foreach ($conditions as $key => &$condition) {
if ($key !== '#conjunction' && is_string($condition['field']) && $condition['field'] === 'vocabulary_machine_name') {
$condition['field'] = $vocabulary_alias . '.machine_name';
break;
}
}
}
/**
* Implements EntityReferenceHandler::getReferencableEntities().
*/
public function getReferencableEntities($match = NULL, $match_operator = 'CONTAINS', $limit = 0) {
if ($match || $limit) {
return parent::getReferencableEntities($match , $match_operator, $limit);
}
$options = array();
$entity_type = $this->field['settings']['target_type'];
// We imitate core by calling taxonomy_get_tree().
$entity_info = entity_get_info('taxonomy_term');
$bundles = !empty($this->field['settings']['handler_settings']['target_bundles']) ? $this->field['settings']['handler_settings']['target_bundles'] : array_keys($entity_info['bundles']);
foreach ($bundles as $bundle) {
if ($vocabulary = taxonomy_vocabulary_machine_name_load($bundle)) {
if ($terms = taxonomy_get_tree($vocabulary->vid, 0)) {
foreach ($terms as $term) {
$options[$vocabulary->machine_name][$term->tid] = str_repeat('-', $term->depth) . check_plain($term->name);
}
}
}
}
return $options;
}
}

View File

@@ -0,0 +1,193 @@
<?php
/**
* Entity handler for Views.
*/
class EntityReference_SelectionHandler_Views implements EntityReference_SelectionHandler {
/**
* Implements EntityReferenceHandler::getInstance().
*/
public static function getInstance($field, $instance = NULL, $entity_type = NULL, $entity = NULL) {
return new EntityReference_SelectionHandler_Views($field, $instance);
}
protected function __construct($field, $instance) {
$this->field = $field;
$this->instance = $instance;
}
/**
* Implements EntityReferenceHandler::settingsForm().
*/
public static function settingsForm($field, $instance) {
$view_settings = empty($field['settings']['handler_settings']['view']) ? '' : $field['settings']['handler_settings']['view'];
$displays = views_get_applicable_views('entityreference display');
// Filter views that list the entity type we want, and group the separate
// displays by view.
$entity_info = entity_get_info($field['settings']['target_type']);
$options = array();
foreach ($displays as $data) {
list($view, $display_id) = $data;
if ($view->base_table == $entity_info['base table']) {
$options[$view->name . ':' . $display_id] = $view->name . ' - ' . $view->display[$display_id]->display_title;
}
}
// The value of the 'view_and_display' select below will need to be split
// into 'view_name' and 'view_display' in the final submitted values, so
// we massage the data at validate time on the wrapping element (not
// ideal).
$form['view']['#element_validate'] = array('entityreference_view_settings_validate');
if ($options) {
$default = !empty($view_settings['view_name']) ? $view_settings['view_name'] . ':' . $view_settings['display_name'] : NULL;
$form['view']['view_and_display'] = array(
'#type' => 'select',
'#title' => t('View used to select the entities'),
'#required' => TRUE,
'#options' => $options,
'#default_value' => $default,
'#description' => '<p>' . t('Choose the view and display that select the entities that can be referenced.<br />Only views with a display of type "Entity Reference" are eligible.') . '</p>',
);
$default = !empty($view_settings['args']) ? implode(', ', $view_settings['args']) : '';
$form['view']['args'] = array(
'#type' => 'textfield',
'#title' => t('View arguments'),
'#default_value' => $default,
'#required' => FALSE,
'#description' => t('Provide a comma separated list of arguments to pass to the view.'),
);
}
else {
$form['view']['no_view_help'] = array(
'#markup' => '<p>' . t('No eligible views were found. <a href="@create">Create a view</a> with an <em>Entity Reference</em> display, or add such a display to an <a href="@existing">existing view</a>.', array(
'@create' => url('admin/structure/views/add'),
'@existing' => url('admin/structure/views'),
)) . '</p>',
);
}
return $form;
}
protected function initializeView($match = NULL, $match_operator = 'CONTAINS', $limit = 0, $ids = NULL) {
$view_name = $this->field['settings']['handler_settings']['view']['view_name'];
$display_name = $this->field['settings']['handler_settings']['view']['display_name'];
$args = $this->field['settings']['handler_settings']['view']['args'];
$entity_type = $this->field['settings']['target_type'];
// Check that the view is valid and the display still exists.
$this->view = views_get_view($view_name);
if (!$this->view || !isset($this->view->display[$display_name]) || !$this->view->access($display_name)) {
watchdog('entityreference', 'The view %view_name is no longer eligible for the %field_name field.', array('%view_name' => $view_name, '%field_name' => $this->instance['label']), WATCHDOG_WARNING);
return FALSE;
}
$this->view->set_display($display_name);
// Make sure the query is not cached.
$this->view->is_cacheable = FALSE;
// Pass options to the display handler to make them available later.
$entityreference_options = array(
'match' => $match,
'match_operator' => $match_operator,
'limit' => $limit,
'ids' => $ids,
);
$this->view->display_handler->set_option('entityreference_options', $entityreference_options);
return TRUE;
}
/**
* Implements EntityReferenceHandler::getReferencableEntities().
*/
public function getReferencableEntities($match = NULL, $match_operator = 'CONTAINS', $limit = 0) {
$display_name = $this->field['settings']['handler_settings']['view']['display_name'];
$args = $this->field['settings']['handler_settings']['view']['args'];
$result = array();
if ($this->initializeView($match, $match_operator, $limit)) {
// Get the results.
$result = $this->view->execute_display($display_name, $args);
}
$return = array();
if ($result) {
$target_type = $this->field['settings']['target_type'];
$entities = entity_load($target_type, array_keys($result));
foreach($entities as $entity) {
list($id,, $bundle) = entity_extract_ids($target_type, $entity);
$return[$bundle][$id] = $result[$id];
}
}
return $return;
}
/**
* Implements EntityReferenceHandler::countReferencableEntities().
*/
function countReferencableEntities($match = NULL, $match_operator = 'CONTAINS') {
$this->getReferencableEntities($match, $match_operator);
return $this->view->total_items;
}
function validateReferencableEntities(array $ids) {
$display_name = $this->field['settings']['handler_settings']['view']['display_name'];
$args = $this->field['settings']['handler_settings']['view']['args'];
$result = array();
if ($this->initializeView(NULL, 'CONTAINS', 0, $ids)) {
// Get the results.
$entities = $this->view->execute_display($display_name, $args);
$result = array_keys($entities);
}
return $result;
}
/**
* Implements EntityReferenceHandler::validateAutocompleteInput().
*/
public function validateAutocompleteInput($input, &$element, &$form_state, $form) {
return NULL;
}
/**
* Implements EntityReferenceHandler::getLabel().
*/
public function getLabel($entity) {
return entity_label($this->field['settings']['target_type'], $entity);
}
/**
* Implements EntityReferenceHandler::entityFieldQueryAlter().
*/
public function entityFieldQueryAlter(SelectQueryInterface $query) {
}
}
function entityreference_view_settings_validate($element, &$form_state, $form) {
// Split view name and display name from the 'view_and_display' value.
if (!empty($element['view_and_display']['#value'])) {
list($view, $display) = explode(':', $element['view_and_display']['#value']);
}
else {
form_error($element, t('The views entity selection mode requires a view.'));
return;
}
// Explode the 'args' string into an actual array. Beware, explode() turns an
// empty string into an array with one empty string. We'll need an empty array
// instead.
$args_string = trim($element['args']['#value']);
if ($args_string === '') {
$args = array();
}
else {
// array_map is called to trim whitespaces from the arguments.
$args = array_map('trim', explode(',', $args_string));
}
$value = array('view_name' => $view, 'display_name' => $display, 'args' => $args);
form_set_value($element, $value, $form_state);
}

View File

@@ -0,0 +1,113 @@
<?php
/**
* @file
* Abstraction of the selection logic of an entity reference field.
*
* Implementations that wish to provide an implementation of this should
* register it using CTools' plugin system.
*/
interface EntityReference_SelectionHandler {
/**
* Factory function: create a new instance of this handler for a given field.
*
* @param $field
* A field datastructure.
* @return EntityReferenceHandler
*/
public static function getInstance($field, $instance = NULL, $entity_type = NULL, $entity = NULL);
/**
* Return a list of referencable entities.
*
* @return
* An array of referencable entities, which keys are entity ids and
* values (safe HTML) labels to be displayed to the user.
*/
public function getReferencableEntities($match = NULL, $match_operator = 'CONTAINS', $limit = 0);
/**
* Count entities that are referencable by a given field.
*/
public function countReferencableEntities($match = NULL, $match_operator = 'CONTAINS');
/**
* Validate that entities can be referenced by this field.
*
* @return
* An array of entity ids that are valid.
*/
public function validateReferencableEntities(array $ids);
/**
* Validate Input from autocomplete widget that has no Id.
*
* @see _entityreference_autocomplete_validate()
*
* @param $input
* Single string from autocomplete widget.
* @param $element
* The form element to set a form error.
* @return
* Value of a matching entity id, or NULL if none.
*/
public function validateAutocompleteInput($input, &$element, &$form_state, $form);
/**
* Give the handler a chance to alter the SelectQuery generated by EntityFieldQuery.
*/
public function entityFieldQueryAlter(SelectQueryInterface $query);
/**
* Return the label of a given entity.
*/
public function getLabel($entity);
/**
* Generate a settings form for this handler.
*/
public static function settingsForm($field, $instance);
}
/**
* A null implementation of EntityReference_SelectionHandler.
*/
class EntityReference_SelectionHandler_Broken implements EntityReference_SelectionHandler {
public static function getInstance($field, $instance = NULL, $entity_type = NULL, $entity = NULL) {
return new EntityReference_SelectionHandler_Broken($field, $instance, $entity_type, $entity);
}
protected function __construct($field, $instance) {
$this->field = $field;
$this->instance = $instance;
}
public static function settingsForm($field, $instance) {
$form['selection_handler'] = array(
'#markup' => t('The selected selection handler is broken.'),
);
return $form;
}
public function getReferencableEntities($match = NULL, $match_operator = 'CONTAINS', $limit = 0) {
return array();
}
public function countReferencableEntities($match = NULL, $match_operator = 'CONTAINS') {
return 0;
}
public function validateReferencableEntities(array $ids) {
return array();
}
public function validateAutocompleteInput($input, &$element, &$form_state, $form) {
return NULL;
}
public function entityFieldQueryAlter(SelectQueryInterface $query) {}
public function getLabel($entity) {
return '';
}
}

View File

@@ -0,0 +1,7 @@
<?php
$plugin = array(
'title' => t('Simple (with optional filter by bundle)'),
'class' => 'EntityReference_SelectionHandler_Generic',
'weight' => -100,
);

View File

@@ -0,0 +1,9 @@
<?php
if (module_exists('views')) {
$plugin = array(
'title' => t('Views: Filter by an entity reference view'),
'class' => 'EntityReference_SelectionHandler_Views',
'weight' => 0,
);
}