FINAL suepr merge step : added all modules to this super repos

This commit is contained in:
Bachir Soussi Chiadmi
2015-04-19 16:46:59 +02:00
7585 changed files with 1723356 additions and 18 deletions

View File

@@ -0,0 +1,976 @@
<?php
/**
* @file
* Provides a controller building upon the core controller but providing more
* features like full CRUD functionality.
*/
/**
* Interface for EntityControllers compatible with the entity API.
*/
interface EntityAPIControllerInterface extends DrupalEntityControllerInterface {
/**
* Delete permanently saved entities.
*
* In case of failures, an exception is thrown.
*
* @param $ids
* An array of entity IDs.
*/
public function delete($ids);
/**
* Invokes a hook on behalf of the entity. For hooks that have a respective
* field API attacher like insert/update/.. the attacher is called too.
*/
public function invoke($hook, $entity);
/**
* Permanently saves the given entity.
*
* In case of failures, an exception is thrown.
*
* @param $entity
* The entity to save.
*
* @return
* SAVED_NEW or SAVED_UPDATED is returned depending on the operation
* performed.
*/
public function save($entity);
/**
* Create a new entity.
*
* @param array $values
* An array of values to set, keyed by property name.
* @return
* A new instance of the entity type.
*/
public function create(array $values = array());
/**
* Exports an entity as serialized string.
*
* @param $entity
* The entity to export.
* @param $prefix
* An optional prefix for each line.
*
* @return
* The exported entity as serialized string. The format is determined by
* the controller and has to be compatible with the format that is accepted
* by the import() method.
*/
public function export($entity, $prefix = '');
/**
* Imports an entity from a string.
*
* @param string $export
* An exported entity as serialized string.
*
* @return
* An entity object not yet saved.
*/
public function import($export);
/**
* Builds a structured array representing the entity's content.
*
* The content built for the entity will vary depending on the $view_mode
* parameter.
*
* @param $entity
* An entity object.
* @param $view_mode
* View mode, e.g. 'full', 'teaser'...
* @param $langcode
* (optional) A language code to use for rendering. Defaults to the global
* content language of the current request.
* @return
* The renderable array.
*/
public function buildContent($entity, $view_mode = 'full', $langcode = NULL);
/**
* Generate an array for rendering the given entities.
*
* @param $entities
* An array of entities to render.
* @param $view_mode
* View mode, e.g. 'full', 'teaser'...
* @param $langcode
* (optional) A language code to use for rendering. Defaults to the global
* content language of the current request.
* @param $page
* (optional) If set will control if the entity is rendered: if TRUE
* the entity will be rendered without its title, so that it can be embeded
* in another context. If FALSE the entity will be displayed with its title
* in a mode suitable for lists.
* If unset, the page mode will be enabled if the current path is the URI
* of the entity, as returned by entity_uri().
* This parameter is only supported for entities which controller is a
* EntityAPIControllerInterface.
* @return
* The renderable array, keyed by entity name or numeric id.
*/
public function view($entities, $view_mode = 'full', $langcode = NULL, $page = NULL);
}
/**
* Interface for EntityControllers of entities that support revisions.
*/
interface EntityAPIControllerRevisionableInterface extends EntityAPIControllerInterface {
/**
* Delete an entity revision.
*
* Note that the default revision of an entity cannot be deleted.
*
* @param $revision_id
* The ID of the revision to delete.
*
* @return boolean
* TRUE if the entity revision could be deleted, FALSE otherwise.
*/
public function deleteRevision($revision_id);
}
/**
* A controller implementing EntityAPIControllerInterface for the database.
*/
class EntityAPIController extends DrupalDefaultEntityController implements EntityAPIControllerRevisionableInterface {
protected $cacheComplete = FALSE;
protected $bundleKey;
protected $defaultRevisionKey;
/**
* Overridden.
* @see DrupalDefaultEntityController#__construct()
*/
public function __construct($entityType) {
parent::__construct($entityType);
// If this is the bundle of another entity, set the bundle key.
if (isset($this->entityInfo['bundle of'])) {
$info = entity_get_info($this->entityInfo['bundle of']);
$this->bundleKey = $info['bundle keys']['bundle'];
}
$this->defaultRevisionKey = !empty($this->entityInfo['entity keys']['default revision']) ? $this->entityInfo['entity keys']['default revision'] : 'default_revision';
}
/**
* Overrides DrupalDefaultEntityController::buildQuery().
*/
protected function buildQuery($ids, $conditions = array(), $revision_id = FALSE) {
$query = parent::buildQuery($ids, $conditions, $revision_id);
if ($this->revisionKey) {
// Compare revision id of the base and revision table, if equal then this
// is the default revision.
$query->addExpression('base.' . $this->revisionKey . ' = revision.' . $this->revisionKey, $this->defaultRevisionKey);
}
return $query;
}
/**
* Builds and executes the query for loading.
*
* @return The results in a Traversable object.
*/
public function query($ids, $conditions, $revision_id = FALSE) {
// Build the query.
$query = $this->buildQuery($ids, $conditions, $revision_id);
$result = $query->execute();
if (!empty($this->entityInfo['entity class'])) {
$result->setFetchMode(PDO::FETCH_CLASS, $this->entityInfo['entity class'], array(array(), $this->entityType));
}
return $result;
}
/**
* Overridden.
* @see DrupalDefaultEntityController#load($ids, $conditions)
*
* In contrast to the parent implementation we factor out query execution, so
* fetching can be further customized easily.
*/
public function load($ids = array(), $conditions = array()) {
$entities = array();
// Revisions are not statically cached, and require a different query to
// other conditions, so separate the revision id into its own variable.
if ($this->revisionKey && isset($conditions[$this->revisionKey])) {
$revision_id = $conditions[$this->revisionKey];
unset($conditions[$this->revisionKey]);
}
else {
$revision_id = FALSE;
}
// Create a new variable which is either a prepared version of the $ids
// array for later comparison with the entity cache, or FALSE if no $ids
// were passed. The $ids array is reduced as items are loaded from cache,
// and we need to know if it's empty for this reason to avoid querying the
// database when all requested entities are loaded from cache.
$passed_ids = !empty($ids) ? array_flip($ids) : FALSE;
// Try to load entities from the static cache.
if ($this->cache && !$revision_id) {
$entities = $this->cacheGet($ids, $conditions);
// If any entities were loaded, remove them from the ids still to load.
if ($passed_ids) {
$ids = array_keys(array_diff_key($passed_ids, $entities));
}
}
// Support the entitycache module if activated.
if (!empty($this->entityInfo['entity cache']) && !$revision_id && $ids && !$conditions) {
$cached_entities = EntityCacheControllerHelper::entityCacheGet($this, $ids, $conditions);
// If any entities were loaded, remove them from the ids still to load.
$ids = array_diff($ids, array_keys($cached_entities));
$entities += $cached_entities;
// Add loaded entities to the static cache if we are not loading a
// revision.
if ($this->cache && !empty($cached_entities) && !$revision_id) {
$this->cacheSet($cached_entities);
}
}
// Load any remaining entities from the database. This is the case if $ids
// is set to FALSE (so we load all entities), if there are any ids left to
// load or if loading a revision.
if (!($this->cacheComplete && $ids === FALSE && !$conditions) && ($ids === FALSE || $ids || $revision_id)) {
$queried_entities = array();
foreach ($this->query($ids, $conditions, $revision_id) as $record) {
// Skip entities already retrieved from cache.
if (isset($entities[$record->{$this->idKey}])) {
continue;
}
// For DB-based entities take care of serialized columns.
if (!empty($this->entityInfo['base table'])) {
$schema = drupal_get_schema($this->entityInfo['base table']);
foreach ($schema['fields'] as $field => $info) {
if (!empty($info['serialize']) && isset($record->$field)) {
$record->$field = unserialize($record->$field);
// Support automatic merging of 'data' fields into the entity.
if (!empty($info['merge']) && is_array($record->$field)) {
foreach ($record->$field as $key => $value) {
$record->$key = $value;
}
unset($record->$field);
}
}
}
}
$queried_entities[$record->{$this->idKey}] = $record;
}
}
// Pass all entities loaded from the database through $this->attachLoad(),
// which attaches fields (if supported by the entity type) and calls the
// entity type specific load callback, for example hook_node_load().
if (!empty($queried_entities)) {
$this->attachLoad($queried_entities, $revision_id);
$entities += $queried_entities;
}
// Entitycache module support: Add entities to the entity cache if we are
// not loading a revision.
if (!empty($this->entityInfo['entity cache']) && !empty($queried_entities) && !$revision_id) {
EntityCacheControllerHelper::entityCacheSet($this, $queried_entities);
}
if ($this->cache) {
// Add entities to the cache if we are not loading a revision.
if (!empty($queried_entities) && !$revision_id) {
$this->cacheSet($queried_entities);
// Remember if we have cached all entities now.
if (!$conditions && $ids === FALSE) {
$this->cacheComplete = TRUE;
}
}
}
// Ensure that the returned array is ordered the same as the original
// $ids array if this was passed in and remove any invalid ids.
if ($passed_ids && $passed_ids = array_intersect_key($passed_ids, $entities)) {
foreach ($passed_ids as $id => $value) {
$passed_ids[$id] = $entities[$id];
}
$entities = $passed_ids;
}
return $entities;
}
/**
* Overrides DrupalDefaultEntityController::resetCache().
*/
public function resetCache(array $ids = NULL) {
$this->cacheComplete = FALSE;
parent::resetCache($ids);
// Support the entitycache module.
if (!empty($this->entityInfo['entity cache'])) {
EntityCacheControllerHelper::resetEntityCache($this, $ids);
}
}
/**
* Implements EntityAPIControllerInterface.
*/
public function invoke($hook, $entity) {
// entity_revision_delete() invokes hook_entity_revision_delete() and
// hook_field_attach_delete_revision() just as node module does. So we need
// to adjust the name of our revision deletion field attach hook in order to
// stick to this pattern.
$field_attach_hook = ($hook == 'revision_delete' ? 'delete_revision' : $hook);
if (!empty($this->entityInfo['fieldable']) && function_exists($function = 'field_attach_' . $field_attach_hook)) {
$function($this->entityType, $entity);
}
if (!empty($this->entityInfo['bundle of']) && entity_type_is_fieldable($this->entityInfo['bundle of'])) {
$type = $this->entityInfo['bundle of'];
// Call field API bundle attachers for the entity we are a bundle of.
if ($hook == 'insert') {
field_attach_create_bundle($type, $entity->{$this->bundleKey});
}
elseif ($hook == 'delete') {
field_attach_delete_bundle($type, $entity->{$this->bundleKey});
}
elseif ($hook == 'update' && $entity->original->{$this->bundleKey} != $entity->{$this->bundleKey}) {
field_attach_rename_bundle($type, $entity->original->{$this->bundleKey}, $entity->{$this->bundleKey});
}
}
// Invoke the hook.
module_invoke_all($this->entityType . '_' . $hook, $entity);
// Invoke the respective entity level hook.
if ($hook == 'presave' || $hook == 'insert' || $hook == 'update' || $hook == 'delete') {
module_invoke_all('entity_' . $hook, $entity, $this->entityType);
}
// Invoke rules.
if (module_exists('rules')) {
rules_invoke_event($this->entityType . '_' . $hook, $entity);
}
}
/**
* Implements EntityAPIControllerInterface.
*
* @param $transaction
* Optionally a DatabaseTransaction object to use. Allows overrides to pass
* in their transaction object.
*/
public function delete($ids, DatabaseTransaction $transaction = NULL) {
$entities = $ids ? $this->load($ids) : FALSE;
if (!$entities) {
// Do nothing, in case invalid or no ids have been passed.
return;
}
// This transaction causes troubles on MySQL, see
// http://drupal.org/node/1007830. So we deactivate this by default until
// is shipped in a point release.
// $transaction = isset($transaction) ? $transaction : db_transaction();
try {
$ids = array_keys($entities);
db_delete($this->entityInfo['base table'])
->condition($this->idKey, $ids, 'IN')
->execute();
if (isset($this->revisionTable)) {
db_delete($this->revisionTable)
->condition($this->idKey, $ids, 'IN')
->execute();
}
// Reset the cache as soon as the changes have been applied.
$this->resetCache($ids);
foreach ($entities as $id => $entity) {
$this->invoke('delete', $entity);
}
// Ignore slave server temporarily.
db_ignore_slave();
}
catch (Exception $e) {
if (isset($transaction)) {
$transaction->rollback();
}
watchdog_exception($this->entityType, $e);
throw $e;
}
}
/**
* Implements EntityAPIControllerRevisionableInterface::deleteRevision().
*/
public function deleteRevision($revision_id) {
if ($entity_revision = entity_revision_load($this->entityType, $revision_id)) {
// Prevent deleting the default revision.
if (entity_revision_is_default($this->entityType, $entity_revision)) {
return FALSE;
}
db_delete($this->revisionTable)
->condition($this->revisionKey, $revision_id)
->execute();
$this->invoke('revision_delete', $entity_revision);
return TRUE;
}
return FALSE;
}
/**
* Implements EntityAPIControllerInterface.
*
* @param $transaction
* Optionally a DatabaseTransaction object to use. Allows overrides to pass
* in their transaction object.
*/
public function save($entity, DatabaseTransaction $transaction = NULL) {
$transaction = isset($transaction) ? $transaction : db_transaction();
try {
// Load the stored entity, if any.
if (!empty($entity->{$this->idKey}) && !isset($entity->original)) {
// In order to properly work in case of name changes, load the original
// entity using the id key if it is available.
$entity->original = entity_load_unchanged($this->entityType, $entity->{$this->idKey});
}
$entity->is_new = !empty($entity->is_new) || empty($entity->{$this->idKey});
$this->invoke('presave', $entity);
if ($entity->is_new) {
$return = drupal_write_record($this->entityInfo['base table'], $entity);
if ($this->revisionKey) {
$this->saveRevision($entity);
}
$this->invoke('insert', $entity);
}
else {
// Update the base table if the entity doesn't have revisions or
// we are updating the default revision.
if (!$this->revisionKey || !empty($entity->{$this->defaultRevisionKey})) {
$return = drupal_write_record($this->entityInfo['base table'], $entity, $this->idKey);
}
if ($this->revisionKey) {
$return = $this->saveRevision($entity);
}
$this->resetCache(array($entity->{$this->idKey}));
$this->invoke('update', $entity);
// Field API always saves as default revision, so if the revision saved
// is not default we have to restore the field values of the default
// revision now by invoking field_attach_update() once again.
if ($this->revisionKey && !$entity->{$this->defaultRevisionKey} && !empty($this->entityInfo['fieldable'])) {
field_attach_update($this->entityType, $entity->original);
}
}
// Ignore slave server temporarily.
db_ignore_slave();
unset($entity->is_new);
unset($entity->is_new_revision);
unset($entity->original);
return $return;
}
catch (Exception $e) {
$transaction->rollback();
watchdog_exception($this->entityType, $e);
throw $e;
}
}
/**
* Saves an entity revision.
*
* @param Entity $entity
* Entity revision to save.
*/
protected function saveRevision($entity) {
// Convert the entity into an array as it might not have the same properties
// as the entity, it is just a raw structure.
$record = (array) $entity;
// File fields assumes we are using $entity->revision instead of
// $entity->is_new_revision, so we also support it and make sure it's set to
// the same value.
$entity->is_new_revision = !empty($entity->is_new_revision) || !empty($entity->revision) || $entity->is_new;
$entity->revision = &$entity->is_new_revision;
$entity->{$this->defaultRevisionKey} = !empty($entity->{$this->defaultRevisionKey}) || $entity->is_new;
// When saving a new revision, set any existing revision ID to NULL so as to
// ensure that a new revision will actually be created.
if ($entity->is_new_revision && isset($record[$this->revisionKey])) {
$record[$this->revisionKey] = NULL;
}
if ($entity->is_new_revision) {
drupal_write_record($this->revisionTable, $record);
$update_default_revision = $entity->{$this->defaultRevisionKey};
}
else {
drupal_write_record($this->revisionTable, $record, $this->revisionKey);
// @todo: Fix original entity to be of the same revision and check whether
// the default revision key has been set.
$update_default_revision = $entity->{$this->defaultRevisionKey} && $entity->{$this->revisionKey} != $entity->original->{$this->revisionKey};
}
// Make sure to update the new revision key for the entity.
$entity->{$this->revisionKey} = $record[$this->revisionKey];
// Mark this revision as the default one.
if ($update_default_revision) {
db_update($this->entityInfo['base table'])
->fields(array($this->revisionKey => $record[$this->revisionKey]))
->condition($this->idKey, $entity->{$this->idKey})
->execute();
}
return $entity->is_new_revision ? SAVED_NEW : SAVED_UPDATED;
}
/**
* Implements EntityAPIControllerInterface.
*/
public function create(array $values = array()) {
// Add is_new property if it is not set.
$values += array('is_new' => TRUE);
if (isset($this->entityInfo['entity class']) && $class = $this->entityInfo['entity class']) {
return new $class($values, $this->entityType);
}
return (object) $values;
}
/**
* Implements EntityAPIControllerInterface.
*
* @return
* A serialized string in JSON format suitable for the import() method.
*/
public function export($entity, $prefix = '') {
$vars = get_object_vars($entity);
unset($vars['is_new']);
return entity_var_json_export($vars, $prefix);
}
/**
* Implements EntityAPIControllerInterface.
*
* @param $export
* A serialized string in JSON format as produced by the export() method.
*/
public function import($export) {
$vars = drupal_json_decode($export);
if (is_array($vars)) {
return $this->create($vars);
}
return FALSE;
}
/**
* Implements EntityAPIControllerInterface.
*
* @param $content
* Optionally. Allows pre-populating the built content to ease overridding
* this method.
*/
public function buildContent($entity, $view_mode = 'full', $langcode = NULL, $content = array()) {
// Remove previously built content, if exists.
$entity->content = $content;
$langcode = isset($langcode) ? $langcode : $GLOBALS['language_content']->language;
// By default add in properties for all defined extra fields.
if ($extra_field_controller = entity_get_extra_fields_controller($this->entityType)) {
$wrapper = entity_metadata_wrapper($this->entityType, $entity);
$extra = $extra_field_controller->fieldExtraFields();
$type_extra = &$extra[$this->entityType][$this->entityType]['display'];
$bundle_extra = &$extra[$this->entityType][$wrapper->getBundle()]['display'];
foreach ($wrapper as $name => $property) {
if (isset($type_extra[$name]) || isset($bundle_extra[$name])) {
$this->renderEntityProperty($wrapper, $name, $property, $view_mode, $langcode, $entity->content);
}
}
}
// Add in fields.
if (!empty($this->entityInfo['fieldable'])) {
// Perform the preparation tasks if they have not been performed yet.
// An internal flag prevents the operation from running twice.
$key = isset($entity->{$this->idKey}) ? $entity->{$this->idKey} : NULL;
field_attach_prepare_view($this->entityType, array($key => $entity), $view_mode);
$entity->content += field_attach_view($this->entityType, $entity, $view_mode, $langcode);
}
// Invoke hook_ENTITY_view() to allow modules to add their additions.
if (module_exists('rules')) {
rules_invoke_all($this->entityType . '_view', $entity, $view_mode, $langcode);
}
else {
module_invoke_all($this->entityType . '_view', $entity, $view_mode, $langcode);
}
module_invoke_all('entity_view', $entity, $this->entityType, $view_mode, $langcode);
$build = $entity->content;
unset($entity->content);
return $build;
}
/**
* Renders a single entity property.
*/
protected function renderEntityProperty($wrapper, $name, $property, $view_mode, $langcode, &$content) {
$info = $property->info();
$content[$name] = array(
'#label_hidden' => FALSE,
'#label' => $info['label'],
'#entity_wrapped' => $wrapper,
'#theme' => 'entity_property',
'#property_name' => $name,
'#access' => $property->access('view'),
'#entity_type' => $this->entityType,
);
$content['#attached']['css']['entity.theme'] = drupal_get_path('module', 'entity') . '/theme/entity.theme.css';
}
/**
* Implements EntityAPIControllerInterface.
*/
public function view($entities, $view_mode = 'full', $langcode = NULL, $page = NULL) {
// For Field API and entity_prepare_view, the entities have to be keyed by
// (numeric) id.
$entities = entity_key_array_by_property($entities, $this->idKey);
if (!empty($this->entityInfo['fieldable'])) {
field_attach_prepare_view($this->entityType, $entities, $view_mode);
}
entity_prepare_view($this->entityType, $entities);
$langcode = isset($langcode) ? $langcode : $GLOBALS['language_content']->language;
$view = array();
foreach ($entities as $entity) {
$build = entity_build_content($this->entityType, $entity, $view_mode, $langcode);
$build += array(
// If the entity type provides an implementation, use this instead the
// generic one.
// @see template_preprocess_entity()
'#theme' => 'entity',
'#entity_type' => $this->entityType,
'#entity' => $entity,
'#view_mode' => $view_mode,
'#language' => $langcode,
'#page' => $page,
);
// Allow modules to modify the structured entity.
drupal_alter(array($this->entityType . '_view', 'entity_view'), $build, $this->entityType);
$key = isset($entity->{$this->idKey}) ? $entity->{$this->idKey} : NULL;
$view[$this->entityType][$key] = $build;
}
return $view;
}
}
/**
* A controller implementing exportables stored in the database.
*/
class EntityAPIControllerExportable extends EntityAPIController {
protected $entityCacheByName = array();
protected $nameKey, $statusKey, $moduleKey;
/**
* Overridden.
*
* Allows specifying a name key serving as uniform identifier for this entity
* type while still internally we are using numeric identifieres.
*/
public function __construct($entityType) {
parent::__construct($entityType);
// Use the name key as primary identifier.
$this->nameKey = isset($this->entityInfo['entity keys']['name']) ? $this->entityInfo['entity keys']['name'] : $this->idKey;
if (!empty($this->entityInfo['exportable'])) {
$this->statusKey = isset($this->entityInfo['entity keys']['status']) ? $this->entityInfo['entity keys']['status'] : 'status';
$this->moduleKey = isset($this->entityInfo['entity keys']['module']) ? $this->entityInfo['entity keys']['module'] : 'module';
}
}
/**
* Support loading by name key.
*/
protected function buildQuery($ids, $conditions = array(), $revision_id = FALSE) {
// Add the id condition ourself, as we might have a separate name key.
$query = parent::buildQuery(array(), $conditions, $revision_id);
if ($ids) {
// Support loading by numeric ids as well as by machine names.
$key = is_numeric(reset($ids)) ? $this->idKey : $this->nameKey;
$query->condition("base.$key", $ids, 'IN');
}
return $query;
}
/**
* Overridden to support passing numeric ids as well as names as $ids.
*/
public function load($ids = array(), $conditions = array()) {
$entities = array();
// Only do something if loaded by names.
if (!$ids || $this->nameKey == $this->idKey || is_numeric(reset($ids))) {
return parent::load($ids, $conditions);
}
// Revisions are not statically cached, and require a different query to
// other conditions, so separate the revision id into its own variable.
if ($this->revisionKey && isset($conditions[$this->revisionKey])) {
$revision_id = $conditions[$this->revisionKey];
unset($conditions[$this->revisionKey]);
}
else {
$revision_id = FALSE;
}
$passed_ids = !empty($ids) ? array_flip($ids) : FALSE;
// Care about the static cache.
if ($this->cache && !$revision_id) {
$entities = $this->cacheGetByName($ids, $conditions);
}
// If any entities were loaded, remove them from the ids still to load.
if ($entities) {
$ids = array_keys(array_diff_key($passed_ids, $entities));
}
$entities_by_id = parent::load($ids, $conditions);
$entities += entity_key_array_by_property($entities_by_id, $this->nameKey);
// Ensure that the returned array is keyed by numeric id and ordered the
// same as the original $ids array and remove any invalid ids.
$return = array();
foreach ($passed_ids as $name => $value) {
if (isset($entities[$name])) {
$return[$entities[$name]->{$this->idKey}] = $entities[$name];
}
}
return $return;
}
/**
* Overridden.
* @see DrupalDefaultEntityController::cacheGet()
*/
protected function cacheGet($ids, $conditions = array()) {
if (!empty($this->entityCache) && $ids !== array()) {
$entities = $ids ? array_intersect_key($this->entityCache, array_flip($ids)) : $this->entityCache;
return $this->applyConditions($entities, $conditions);
}
return array();
}
/**
* Like cacheGet() but keyed by name.
*/
protected function cacheGetByName($names, $conditions = array()) {
if (!empty($this->entityCacheByName) && $names !== array() && $names) {
// First get the entities by ids, then apply the conditions.
// Generally, we make use of $this->entityCache, but if we are loading by
// name, we have to use $this->entityCacheByName.
$entities = array_intersect_key($this->entityCacheByName, array_flip($names));
return $this->applyConditions($entities, $conditions);
}
return array();
}
protected function applyConditions($entities, $conditions = array()) {
if ($conditions) {
foreach ($entities as $key => $entity) {
$entity_values = (array) $entity;
// We cannot use array_diff_assoc() here because condition values can
// also be arrays, e.g. '$conditions = array('status' => array(1, 2))'
foreach ($conditions as $condition_key => $condition_value) {
if (is_array($condition_value)) {
if (!isset($entity_values[$condition_key]) || !in_array($entity_values[$condition_key], $condition_value)) {
unset($entities[$key]);
}
}
elseif (!isset($entity_values[$condition_key]) || $entity_values[$condition_key] != $condition_value) {
unset($entities[$key]);
}
}
}
}
return $entities;
}
/**
* Overridden.
* @see DrupalDefaultEntityController::cacheSet()
*/
protected function cacheSet($entities) {
$this->entityCache += $entities;
// If we have a name key, also support static caching when loading by name.
if ($this->nameKey != $this->idKey) {
$this->entityCacheByName += entity_key_array_by_property($entities, $this->nameKey);
}
}
/**
* Overridden.
* @see DrupalDefaultEntityController::attachLoad()
*
* Changed to call type-specific hook with the entities keyed by name if they
* have one.
*/
protected function attachLoad(&$queried_entities, $revision_id = FALSE) {
// Attach fields.
if ($this->entityInfo['fieldable']) {
if ($revision_id) {
field_attach_load_revision($this->entityType, $queried_entities);
}
else {
field_attach_load($this->entityType, $queried_entities);
}
}
// Call hook_entity_load().
foreach (module_implements('entity_load') as $module) {
$function = $module . '_entity_load';
$function($queried_entities, $this->entityType);
}
// Call hook_TYPE_load(). The first argument for hook_TYPE_load() are
// always the queried entities, followed by additional arguments set in
// $this->hookLoadArguments.
// For entities with a name key, pass the entities keyed by name to the
// specific load hook.
if ($this->nameKey != $this->idKey) {
$entities_by_name = entity_key_array_by_property($queried_entities, $this->nameKey);
}
else {
$entities_by_name = $queried_entities;
}
$args = array_merge(array($entities_by_name), $this->hookLoadArguments);
foreach (module_implements($this->entityInfo['load hook']) as $module) {
call_user_func_array($module . '_' . $this->entityInfo['load hook'], $args);
}
}
public function resetCache(array $ids = NULL) {
$this->cacheComplete = FALSE;
if (isset($ids)) {
foreach (array_intersect_key($this->entityCache, array_flip($ids)) as $id => $entity) {
unset($this->entityCacheByName[$this->entityCache[$id]->{$this->nameKey}]);
unset($this->entityCache[$id]);
}
}
else {
$this->entityCache = array();
$this->entityCacheByName = array();
}
}
/**
* Overridden to care about reverted entities.
*/
public function delete($ids, DatabaseTransaction $transaction = NULL) {
$entities = $ids ? $this->load($ids) : FALSE;
if ($entities) {
parent::delete($ids, $transaction);
foreach ($entities as $id => $entity) {
if (entity_has_status($this->entityType, $entity, ENTITY_IN_CODE)) {
entity_defaults_rebuild(array($this->entityType));
break;
}
}
}
}
/**
* Overridden to care about reverted bundle entities and to skip Rules.
*/
public function invoke($hook, $entity) {
if ($hook == 'delete') {
// To ease figuring out whether this is a revert, make sure that the
// entity status is updated in case the providing module has been
// disabled.
if (entity_has_status($this->entityType, $entity, ENTITY_IN_CODE) && !module_exists($entity->{$this->moduleKey})) {
$entity->{$this->statusKey} = ENTITY_CUSTOM;
}
$is_revert = entity_has_status($this->entityType, $entity, ENTITY_IN_CODE);
}
if (!empty($this->entityInfo['fieldable']) && function_exists($function = 'field_attach_' . $hook)) {
$function($this->entityType, $entity);
}
if (isset($this->entityInfo['bundle of']) && $type = $this->entityInfo['bundle of']) {
// Call field API bundle attachers for the entity we are a bundle of.
if ($hook == 'insert') {
field_attach_create_bundle($type, $entity->{$this->bundleKey});
}
elseif ($hook == 'delete' && !$is_revert) {
field_attach_delete_bundle($type, $entity->{$this->bundleKey});
}
elseif ($hook == 'update' && $id = $entity->{$this->nameKey}) {
if ($entity->original->{$this->bundleKey} != $entity->{$this->bundleKey}) {
field_attach_rename_bundle($type, $entity->original->{$this->bundleKey}, $entity->{$this->bundleKey});
}
}
}
// Invoke the hook.
module_invoke_all($this->entityType . '_' . $hook, $entity);
// Invoke the respective entity level hook.
if ($hook == 'presave' || $hook == 'insert' || $hook == 'update' || $hook == 'delete') {
module_invoke_all('entity_' . $hook, $entity, $this->entityType);
}
}
/**
* Overridden to care exportables that are overridden.
*/
public function save($entity, DatabaseTransaction $transaction = NULL) {
// Preload $entity->original by name key if necessary.
if (!empty($entity->{$this->nameKey}) && empty($entity->{$this->idKey}) && !isset($entity->original)) {
$entity->original = entity_load_unchanged($this->entityType, $entity->{$this->nameKey});
}
// Update the status for entities getting overridden.
if (entity_has_status($this->entityType, $entity, ENTITY_IN_CODE) && empty($entity->is_rebuild)) {
$entity->{$this->statusKey} |= ENTITY_CUSTOM;
}
return parent::save($entity, $transaction);
}
/**
* Overridden.
*/
public function export($entity, $prefix = '') {
$vars = get_object_vars($entity);
unset($vars[$this->statusKey], $vars[$this->moduleKey], $vars['is_new']);
if ($this->nameKey != $this->idKey) {
unset($vars[$this->idKey]);
}
return entity_var_json_export($vars, $prefix);
}
/**
* Implements EntityAPIControllerInterface.
*/
public function view($entities, $view_mode = 'full', $langcode = NULL, $page = NULL) {
$view = parent::view($entities, $view_mode, $langcode, $page);
if ($this->nameKey != $this->idKey) {
// Re-key the view array to be keyed by name.
$return = array();
foreach ($view[$this->entityType] as $id => $content) {
$key = isset($content['#entity']->{$this->nameKey}) ? $content['#entity']->{$this->nameKey} : NULL;
$return[$this->entityType][$key] = $content;
}
$view = $return;
}
return $view;
}
}

View File

@@ -0,0 +1,320 @@
<?php
/**
* @file
* Provides a base class for entities.
*/
/**
* A common class for entities.
*
* It's suggested, but not required, to extend this class and to override
* __construct() in order to specify a fixed entity type.
*
* For providing an entity label and URI it is suggested to override the
* defaultLabel() and defaultUri() methods, and to specify the
* entity_class_label() and entity_class_uri() as respective callbacks in
* hook_entity_info(). That way modules are able to override your defaults
* by altering the hook_entity_info() callbacks, while $entity->label() and
* $entity->uri() reflect this changes as well.
*
* Defaults for entity properties can be easily defined by adding class
* properties, e.g.:
* @code
* public $name = '';
* public $count = 0;
* @endcode
*/
class Entity {
protected $entityType;
protected $entityInfo;
protected $idKey, $nameKey, $statusKey;
protected $defaultLabel = FALSE;
/**
* Creates a new entity.
*
* @see entity_create()
*/
public function __construct(array $values = array(), $entityType = NULL) {
if (empty($entityType)) {
throw new Exception('Cannot create an instance of Entity without a specified entity type.');
}
$this->entityType = $entityType;
$this->setUp();
// Set initial values.
foreach ($values as $key => $value) {
$this->$key = $value;
}
}
/**
* Set up the object instance on construction or unserializiation.
*/
protected function setUp() {
$this->entityInfo = entity_get_info($this->entityType);
$this->idKey = $this->entityInfo['entity keys']['id'];
$this->nameKey = isset($this->entityInfo['entity keys']['name']) ? $this->entityInfo['entity keys']['name'] : $this->idKey;
$this->statusKey = empty($info['entity keys']['status']) ? 'status' : $info['entity keys']['status'];
}
/**
* Returns the internal, numeric identifier.
*
* Returns the numeric identifier, even if the entity type has specified a
* name key. In the latter case, the numeric identifier is supposed to be used
* when dealing generically with entities or internally to refer to an entity,
* i.e. in a relational database. If unsure, use Entity:identifier().
*/
public function internalIdentifier() {
return isset($this->{$this->idKey}) ? $this->{$this->idKey} : NULL;
}
/**
* Returns the entity identifier, i.e. the entities name or numeric id.
*
* @return
* The identifier of the entity. If the entity type makes use of a name key,
* the name is returned, else the numeric id.
*
* @see entity_id()
*/
public function identifier() {
return isset($this->{$this->nameKey}) ? $this->{$this->nameKey} : NULL;
}
/**
* Returns the info of the type of the entity.
*
* @see entity_get_info()
*/
public function entityInfo() {
return $this->entityInfo;
}
/**
* Returns the type of the entity.
*/
public function entityType() {
return $this->entityType;
}
/**
* Returns the bundle of the entity.
*
* @return
* The bundle of the entity. Defaults to the entity type if the entity type
* does not make use of different bundles.
*/
public function bundle() {
return !empty($this->entityInfo['entity keys']['bundle']) ? $this->{$this->entityInfo['entity keys']['bundle']} : $this->entityType;
}
/**
* Returns the label of the entity.
*
* Modules may alter the label by specifying another 'label callback' using
* hook_entity_info_alter().
*
* @see entity_label()
*/
public function label() {
// If the default label flag is enabled, this is being invoked recursively.
// In this case we need to use our default label callback directly. This may
// happen if a module provides a label callback implementation different
// from ours, but then invokes Entity::label() or entity_class_label() from
// there.
if ($this->defaultLabel || (isset($this->entityInfo['label callback']) && $this->entityInfo['label callback'] == 'entity_class_label')) {
return $this->defaultLabel();
}
$this->defaultLabel = TRUE;
$label = entity_label($this->entityType, $this);
$this->defaultLabel = FALSE;
return $label;
}
/**
* Defines the entity label if the 'entity_class_label' callback is used.
*
* Specify 'entity_class_label' as 'label callback' in hook_entity_info() to
* let the entity label point to this method. Override this in order to
* implement a custom default label.
*/
protected function defaultLabel() {
// Add in the translated specified label property.
return $this->getTranslation($this->entityInfo['entity keys']['label']);
}
/**
* Returns the uri of the entity just as entity_uri().
*
* Modules may alter the uri by specifying another 'uri callback' using
* hook_entity_info_alter().
*
* @see entity_uri()
*/
public function uri() {
if (isset($this->entityInfo['uri callback']) && $this->entityInfo['uri callback'] == 'entity_class_uri') {
return $this->defaultUri();
}
return entity_uri($this->entityType, $this);
}
/**
* Override this in order to implement a custom default URI and specify
* 'entity_class_uri' as 'uri callback' hook_entity_info().
*/
protected function defaultUri() {
return array('path' => 'default/' . $this->identifier());
}
/**
* Checks if the entity has a certain exportable status.
*
* @param $status
* A status constant, i.e. one of ENTITY_CUSTOM, ENTITY_IN_CODE,
* ENTITY_OVERRIDDEN or ENTITY_FIXED.
*
* @return
* For exportable entities TRUE if the entity has the status, else FALSE.
* In case the entity is not exportable, NULL is returned.
*
* @see entity_has_status()
*/
public function hasStatus($status) {
if (!empty($this->entityInfo['exportable'])) {
return isset($this->{$this->statusKey}) && ($this->{$this->statusKey} & $status) == $status;
}
}
/**
* Permanently saves the entity.
*
* @see entity_save()
*/
public function save() {
return entity_get_controller($this->entityType)->save($this);
}
/**
* Permanently deletes the entity.
*
* @see entity_delete()
*/
public function delete() {
$id = $this->identifier();
if (isset($id)) {
entity_get_controller($this->entityType)->delete(array($id));
}
}
/**
* Exports the entity.
*
* @see entity_export()
*/
public function export($prefix = '') {
return entity_get_controller($this->entityType)->export($this, $prefix);
}
/**
* Generate an array for rendering the entity.
*
* @see entity_view()
*/
public function view($view_mode = 'full', $langcode = NULL, $page = NULL) {
return entity_get_controller($this->entityType)->view(array($this), $view_mode, $langcode, $page);
}
/**
* Builds a structured array representing the entity's content.
*
* @see entity_build_content()
*/
public function buildContent($view_mode = 'full', $langcode = NULL) {
return entity_get_controller($this->entityType)->buildContent($this, $view_mode, $langcode);
}
/**
* Gets the raw, translated value of a property or field.
*
* Supports retrieving field translations as well as i18n string translations.
*
* Note that this returns raw data values, which might not reflect what
* has been declared for hook_entity_property_info() as no 'getter callbacks'
* are invoked or no referenced entities are loaded. For retrieving values
* reflecting the property info make use of entity metadata wrappers, see
* entity_metadata_wrapper().
*
* @param $property_name
* The name of the property to return; e.g., 'title'.
* @param $langcode
* (optional) The language code of the language to which the value should
* be translated. If set to NULL, the default display language is being
* used.
*
* @return
* The raw, translated property value; or the raw, un-translated value if no
* translation is available.
*
* @todo Implement an analogous setTranslation() method for updating.
*/
public function getTranslation($property, $langcode = NULL) {
$all_info = entity_get_all_property_info($this->entityType);
// Assign by reference to avoid triggering notices if metadata is missing.
$property_info = &$all_info[$property];
if (!empty($property_info['translatable'])) {
if (!empty($property_info['field'])) {
return field_get_items($this->entityType, $this, $property, $langcode);
}
elseif (!empty($property_info['i18n string'])) {
$name = $this->entityInfo['module'] . ':' . $this->entityType . ':' . $this->identifier() . ':' . $property;
return entity_i18n_string($name, $this->$property, $langcode);
}
}
return $this->$property;
}
/**
* Checks whether the entity is the default revision.
*
* @return Boolean
*
* @see entity_revision_is_default()
*/
public function isDefaultRevision() {
if (!empty($this->entityInfo['entity keys']['revision'])) {
$key = !empty($this->entityInfo['entity keys']['default revision']) ? $this->entityInfo['entity keys']['default revision'] : 'default_revision';
return !empty($this->$key);
}
return TRUE;
}
/**
* Magic method to only serialize what's necessary.
*/
public function __sleep() {
$vars = get_object_vars($this);
unset($vars['entityInfo'], $vars['idKey'], $vars['nameKey'], $vars['statusKey']);
// Also key the returned array with the variable names so the method may
// be easily overridden and customized.
return drupal_map_assoc(array_keys($vars));
}
/**
* Magic method to invoke setUp() on unserialization.
*/
public function __wakeup() {
$this->setUp();
}
}
/**
* These classes are deprecated by "Entity" and are only here for backward
* compatibility reasons.
*/
class EntityDB extends Entity {}
class EntityExtendable extends Entity {}
class EntityDBExtendable extends Entity {}

View File

@@ -0,0 +1,650 @@
<?php
/**
* @file
* Provides API functions around hook_entity_property_info(). Also see
* entity.info.inc, which cares for providing entity property info for all core
* entity types.
*/
/**
* Get the entity property info array of an entity type.
*
* @param $entity_type
* The entity type, e.g. node, for which the info shall be returned, or NULL
* to return an array with info about all types.
*
* @see hook_entity_property_info()
* @see hook_entity_property_info_alter()
*/
function entity_get_property_info($entity_type = NULL) {
// Use the advanced drupal_static() pattern, since this is called very often.
static $drupal_static_fast;
if (!isset($drupal_static_fast)) {
$drupal_static_fast['info'] = &drupal_static(__FUNCTION__);
}
$info = &$drupal_static_fast['info'];
// hook_entity_property_info() includes translated strings, so each language
// is cached separately.
$langcode = $GLOBALS['language']->language;
if (empty($info)) {
if ($cache = cache_get("entity_property_info:$langcode")) {
$info = $cache->data;
}
else {
$info = module_invoke_all('entity_property_info');
// Let other modules alter the entity info.
drupal_alter('entity_property_info', $info);
cache_set("entity_property_info:$langcode", $info);
}
}
return empty($entity_type) ? $info : (isset($info[$entity_type]) ? $info[$entity_type] : array());
}
/**
* Returns the default information for an entity property.
*
* @return
* An array of optional property information keys mapped to their defaults.
*
* @see hook_entity_property_info()
*/
function entity_property_info_defaults() {
return array(
'type' => 'text',
'getter callback' => 'entity_property_verbatim_get',
);
}
/**
* Gets an array of info about all properties of a given entity type.
*
* In contrast to entity_get_property_info(), this function returns info about
* all properties the entity might have, thus it adds an all properties assigned
* to entity bundles.
*
* @param $entity_type
* (optiona) The entity type to return properties for.
*
* @return
* An array of info about properties. If the type is ommitted, all known
* properties are returned.
*/
function entity_get_all_property_info($entity_type = NULL) {
if (!isset($entity_type)) {
// Retrieve all known properties.
$properties = array();
foreach (entity_get_info() as $entity_type => $info) {
$properties += entity_get_all_property_info($entity_type);
}
return $properties;
}
// Else retrieve the properties of the given entity type only.
$info = entity_get_property_info($entity_type);
$info += array('properties' => array(), 'bundles' => array());
// Add all bundle properties.
foreach ($info['bundles'] as $bundle => $bundle_info) {
$bundle_info += array('properties' => array());
$info['properties'] += $bundle_info['properties'];
}
return $info['properties'];
}
/**
* Queries for entities having the given property value.
*
* @param $entity_type
* The type of the entity.
* @param $property
* The name of the property to query for.
* @param $value
* A single property value or an array of possible values to query for.
* @param $limit
* Limit the numer of results. Defaults to 30.
*
* @return
* An array of entity ids or NULL if there is no information how to query for
* the given property.
*/
function entity_property_query($entity_type, $property, $value, $limit = 30) {
$properties = entity_get_all_property_info($entity_type);
$info = $properties[$property] + array('type' => 'text', 'queryable' => !empty($properties[$property]['schema field']));
// We still support the deprecated query callback, so just add in EFQ-based
// callbacks in case 'queryable' is set to TRUE and make use of the callback.
if ($info['queryable'] && empty($info['query callback'])) {
$info['query callback'] = !empty($info['field']) ? 'entity_metadata_field_query' : 'entity_metadata_table_query';
}
$type = $info['type'];
// Make sure an entity or a list of entities are passed on as identifiers
// with the help of the wrappers. For that ensure the data type matches the
// passed on value(s).
if (is_array($value) && !entity_property_list_extract_type($type)) {
$type = 'list<' . $type . '>';
}
elseif (!is_array($value) && entity_property_list_extract_type($type)) {
$type = entity_property_list_extract_type($type);
}
$wrapper = entity_metadata_wrapper($type, $value);
$value = $wrapper->value(array('identifier' => TRUE));
if (!empty($info['query callback'])) {
return $info['query callback']($entity_type, $property, $value, $limit);
}
}
/**
* Resets the cached information of hook_entity_property_info().
*/
function entity_property_info_cache_clear() {
drupal_static_reset('entity_get_property_info');
// Clear all languages.
cache_clear_all('entity_property_info:', 'cache', TRUE);
}
/**
* Implements hook_hook_info().
*/
function entity_hook_info() {
$hook_info['entity_property_info'] = array(
'group' => 'info',
);
$hook_info['entity_property_info_alter'] = array(
'group' => 'info',
);
return $hook_info;
}
/**
* Implements hook_field_info_alter().
* Defines default property types for core field types.
*/
function entity_field_info_alter(&$field_info) {
if (module_exists('number')) {
$field_info['number_integer']['property_type'] = 'integer';
$field_info['number_decimal']['property_type'] = 'decimal';
$field_info['number_float']['property_type'] = 'decimal';
}
if (module_exists('text')) {
$field_info['text']['property_type'] = 'text';
$field_info['text']['property_callbacks'][] = 'entity_metadata_field_text_property_callback';
$field_info['text_long']['property_type'] = 'text';
$field_info['text_long']['property_callbacks'][] = 'entity_metadata_field_text_property_callback';
$field_info['text_with_summary']['property_type'] = 'field_item_textsummary';
$field_info['text_with_summary']['property_callbacks'][] = 'entity_metadata_field_text_property_callback';
}
if (module_exists('list')) {
$field_info['list_integer']['property_type'] = 'integer';
$field_info['list_boolean']['property_type'] = 'boolean';
$field_info['list_float']['property_type'] = 'decimal';
$field_info['list_text']['property_type'] = 'text';
}
if (module_exists('taxonomy')) {
$field_info['taxonomy_term_reference']['property_type'] = 'taxonomy_term';
$field_info['taxonomy_term_reference']['property_callbacks'][] = 'entity_metadata_field_term_reference_callback';
}
if (module_exists('file')) {
// The callback specifies a custom data structure matching the file field
// items. We introduce a custom type name for this data structure.
$field_info['file']['property_type'] = 'field_item_file';
$field_info['file']['property_callbacks'][] = 'entity_metadata_field_file_callback';
}
if (module_exists('image')) {
// The callback specifies a custom data structure matching the image field
// items. We introduce a custom type name for this data structure.
$field_info['image']['property_type'] = 'field_item_image';
$field_info['image']['property_callbacks'][] = 'entity_metadata_field_file_callback';
$field_info['image']['property_callbacks'][] = 'entity_metadata_field_image_callback';
}
}
/**
* Implements hook_field_create_instance().
* Clear the cache when a field instance changed.
*/
function entity_field_create_instance() {
entity_property_info_cache_clear();
}
/**
* Implements hook_field_delete_instance().
* Clear the cache when a field instance changed.
*/
function entity_field_delete_instance() {
entity_property_info_cache_clear();
}
/**
* Implements hook_field_update_instance().
* Clear the cache when a field instance changed.
*/
function entity_field_update_instance() {
entity_property_info_cache_clear();
}
/**
* Verifies that the given data can be safely used as the given type regardless
* of the PHP variable type of $data. Example: the string "15" is a valid
* integer, but "15nodes" is not.
*
* @return
* Whether the data is valid for the given type.
*/
function entity_property_verify_data_type($data, $type) {
// As this may be called very often statically cache the entity info using
// the fast pattern.
static $drupal_static_fast;
if (!isset($drupal_static_fast)) {
// Make use of the same static as entity info.
entity_get_info();
$drupal_static_fast['entity_info'] = &drupal_static('entity_get_info');
}
$info = &$drupal_static_fast['entity_info'];
// First off check for entities, which may be represented by their ids too.
if (isset($info[$type])) {
if (is_object($data)) {
return TRUE;
}
elseif (isset($info[$type]['entity keys']['name'])) {
// Read the data type of the name key from the metadata if available.
$key = $info[$type]['entity keys']['name'];
$property_info = entity_get_property_info($type);
$property_type = isset($property_info['properties'][$key]['type']) ? $property_info['properties'][$key]['type'] : 'token';
return entity_property_verify_data_type($data, $property_type);
}
return entity_property_verify_data_type($data, empty($info[$type]['fieldable']) ? 'text' : 'integer');
}
switch ($type) {
case 'site':
case 'unknown':
return TRUE;
case 'date':
case 'duration':
case 'integer':
return is_numeric($data) && strpos($data, '.') === FALSE;
case 'decimal':
return is_numeric($data);
case 'text':
return is_scalar($data);
case 'token':
return is_scalar($data) && preg_match('!^[a-z][a-z0-9_]*$!', $data);
case 'boolean':
return is_scalar($data) && (is_bool($data) || $data == 0 || $data == 1);
case 'uri':
return valid_url($data, TRUE);
case 'list':
return (is_array($data) && array_values($data) == $data) || (is_object($data) && $data instanceof EntityMetadataArrayObject);
case 'entity':
return is_object($data) && $data instanceof EntityDrupalWrapper;
default:
case 'struct':
return is_object($data) || is_array($data);
}
}
/**
* Creates the entity object for an array of given property values.
*
* @param $entity_type
* The entity type to create an entity for.
* @param $values
* An array of values as described by the entity's property info. All entity
* properties of the given entity type that are marked as required, must be
* present.
* If the passed values have no matching property, their value will be
* assigned to the entity directly, without the use of the metadata-wrapper
* property.
*
* @return EntityDrupalWrapper
* An EntityDrupalWrapper wrapping the newly created entity or FALSE, if
* there were no information how to create the entity.
*/
function entity_property_values_create_entity($entity_type, $values = array()) {
if (entity_type_supports($entity_type, 'create')) {
$info = entity_get_info($entity_type);
// Create the initial entity by passing the values for all 'entity keys'
// to entity_create().
$entity_keys = array_filter($info['entity keys']);
$creation_values = array_intersect_key($values, array_flip($entity_keys));
// In case the bundle key does not match the property that sets it, ensure
// the bundle key is initialized somehow, so entity_extract_ids()
// does not bail out during wrapper creation.
if (!empty($info['entity keys']['bundle'])) {
$creation_values += array($info['entity keys']['bundle'] => FALSE);
}
$entity = entity_create($entity_type, $creation_values);
// Now set the remaining values using the wrapper.
$wrapper = entity_metadata_wrapper($entity_type, $entity);
foreach ($values as $key => $value) {
if (!in_array($key, $info['entity keys'])) {
if (isset($wrapper->$key)) {
$wrapper->$key->set($value);
}
else {
$entity->$key = $value;
}
}
}
// @todo: Once we require Drupal 7.7 or later, verify the entity has
// now a valid bundle and throw the EntityMalformedException if not.
return $wrapper;
}
return FALSE;
}
/**
* Extracts the contained type for a list type string like list<date>.
*
* @return
* The contained type or FALSE, if the given type string is no list.
*/
function entity_property_list_extract_type($type) {
if (strpos($type, 'list<') === 0 && $type[strlen($type)-1] == '>') {
return substr($type, 5, -1);
}
return FALSE;
}
/**
* Extracts the innermost type for a type string like list<list<date>>.
*
* @param $type
* The type to examine.
*
* @return
* For list types, the innermost type. The type itself otherwise.
*/
function entity_property_extract_innermost_type($type) {
while (strpos($type, 'list<') === 0 && $type[strlen($type)-1] == '>') {
$type = substr($type, 5, -1);
}
return $type;
}
/**
* Gets the property just as it is set in the data.
*/
function entity_property_verbatim_get($data, array $options, $name, $type, $info) {
$name = isset($info['schema field']) ? $info['schema field'] : $name;
if ((is_array($data) || (is_object($data) && $data instanceof ArrayAccess)) && isset($data[$name])) {
return $data[$name];
}
elseif (is_object($data) && isset($data->$name)) {
// Incorporate i18n_string translations. We may rely on the entity class
// here as its usage is required by the i18n integration.
if (isset($options['language']) && !empty($info['i18n string'])) {
return $data->getTranslation($name, $options['language']->language);
}
else {
return $data->$name;
}
}
return NULL;
}
/**
* Date values are converted from ISO strings to timestamp if needed.
*/
function entity_property_verbatim_date_get($data, array $options, $name, $type, $info) {
$name = isset($info['schema field']) ? $info['schema field'] : $name;
return is_numeric($data[$name]) ? $data[$name] : strtotime($data[$name], REQUEST_TIME);
}
/**
* Sets the property to the given value. May be used as 'setter callback'.
*/
function entity_property_verbatim_set(&$data, $name, $value, $langcode, $type, $info) {
$name = isset($info['schema field']) ? $info['schema field'] : $name;
if (is_array($data) || (is_object($data) && $data instanceof ArrayAccess)) {
$data[$name] = $value;
}
elseif (is_object($data)) {
$data->$name = $value;
}
}
/**
* Gets the property using the getter method (named just like the property).
*/
function entity_property_getter_method($object, array $options, $name) {
// Remove any underscores as classes are expected to use CamelCase.
$method = strtr($name, array('_' => ''));
return $object->$method();
}
/**
* Sets the property to the given value using the setter method. May be used as
* 'setter callback'.
*/
function entity_property_setter_method($object, $name, $value) {
// Remove any underscores as classes are expected to use CamelCase.
$method = 'set' . strtr($name, array('_' => ''));
// Invoke the setProperty() method where 'Property' is the property name.
$object->$method($value);
}
/**
* Getter callback for getting an array. Makes sure it's numerically indexed.
*/
function entity_property_get_list($data, array $options, $name) {
return isset($data->$name) ? array_values($data->$name) : array();
}
/**
* A validation callback ensuring the passed integer is positive.
*/
function entity_property_validate_integer_positive($value) {
return $value > 0;
}
/**
* A validation callback ensuring the passed integer is non-negative.
*/
function entity_property_validate_integer_non_negative($value) {
return $value >= 0;
}
/**
* A simple auto-creation callback for array based data structures.
*/
function entity_property_create_array($property_name, $context) {
return array();
}
/**
* Flattens the given options in single dimensional array.
* We don't depend on options module, so we cannot use options_array_flatten().
*
* @see options_array_flatten()
*/
function entity_property_options_flatten($options) {
$result = array();
foreach ($options as $key => $value) {
if (is_array($value)) {
$result += $value;
}
else {
$result[$key] = $value;
}
}
return $result;
}
/**
* Defines info for the properties of the text_formatted data structure.
*/
function entity_property_text_formatted_info() {
return array(
'value' => array(
'type' => 'text',
'label' => t('Text'),
'sanitized' => TRUE,
'getter callback' => 'entity_metadata_field_text_get',
'setter callback' => 'entity_property_verbatim_set',
'setter permission' => 'administer nodes',
'raw getter callback' => 'entity_property_verbatim_get',
),
'summary' => array(
'type' => 'text',
'label' => t('Summary'),
'sanitized' => TRUE,
'getter callback' => 'entity_metadata_field_text_get',
'setter callback' => 'entity_property_verbatim_set',
'setter permission' => 'administer nodes',
'raw getter callback' => 'entity_property_verbatim_get',
),
'format' => array(
'type' => 'token',
'label' => t('Text format'),
'options list' => 'entity_metadata_field_text_formats',
'getter callback' => 'entity_property_verbatim_get',
),
);
}
/**
* Defines info for the properties of the field_item_textsummary data structure.
*/
function entity_property_field_item_textsummary_info() {
return array(
'value' => array(
'type' => 'text',
'label' => t('Text'),
'setter callback' => 'entity_property_verbatim_set',
),
'summary' => array(
'type' => 'text',
'label' => t('Summary'),
'setter callback' => 'entity_property_verbatim_set',
),
);
}
/**
* Defines info for the properties of the file-field item data structure.
*/
function entity_property_field_item_file_info() {
$properties['file'] = array(
'type' => 'file',
'label' => t('The file.'),
'getter callback' => 'entity_metadata_field_file_get',
'setter callback' => 'entity_metadata_field_file_set',
'required' => TRUE,
);
$properties['description'] = array(
'type' => 'text',
'label' => t('The file description'),
'setter callback' => 'entity_property_verbatim_set',
);
$properties['display'] = array(
'type' => 'boolean',
'label' => t('Whether the file is being displayed.'),
'setter callback' => 'entity_property_verbatim_set',
);
return $properties;
}
/**
* Defines info for the properties of the image-field item data structure.
*/
function entity_property_field_item_image_info() {
$properties['file'] = array(
'type' => 'file',
'label' => t('The image file.'),
'getter callback' => 'entity_metadata_field_file_get',
'setter callback' => 'entity_metadata_field_file_set',
'required' => TRUE,
);
$properties['alt'] = array(
'type' => 'text',
'label' => t('The "Alt" attribute text'),
'setter callback' => 'entity_property_verbatim_set',
);
$properties['title'] = array(
'type' => 'text',
'label' => t('The "Title" attribute text'),
'setter callback' => 'entity_property_verbatim_set',
);
return $properties;
}
/**
* Previously, hook_entity_property_info() has been provided by the removed
* entity metadata module. To provide backward compatibility for provided
* helpers that may be specified in hook_entity_property_info(), the following
* (deprecated) functions are provided.
*/
/**
* Deprecated.
* Do not make use of this function, instead use the new one.
*/
function entity_metadata_verbatim_get($data, array $options, $name) {
return entity_property_verbatim_get($data, $options, $name);
}
/**
* Deprecated.
* Do not make use of this function, instead use the new one.
*/
function entity_metadata_verbatim_set($data, $name, $value) {
return entity_property_verbatim_set($data, $name, $value);
}
/**
* Deprecated.
* Do not make use of this function, instead use the new one.
*/
function entity_metadata_getter_method($object, array $options, $name) {
return entity_property_getter_method($object, $options, $name);
}
/**
* Deprecated.
* Do not make use of this function, instead use the new one.
*/
function entity_metadata_setter_method($object, $name, $value) {
entity_property_setter_method($object, $name, $value);
}
/**
* Deprecated.
* Do not make use of this function, instead use the new one.
*/
function entity_metadata_get_list($data, array $options, $name) {
return entity_property_get_list($data, $options, $name);
}
/**
* Deprecated.
* Do not make use of this function, instead use the new one.
*/
function entity_metadata_validate_integer_positive($value) {
return entity_property_validate_integer_positive($value);
}
/**
* Deprecated.
* Do not make use of this function, instead use the new one.
*/
function entity_metadata_validate_integer_non_negative($value) {
return entity_property_validate_integer_non_negative($value);
}
/**
* Deprecated.
* Do not make use of this function, instead use the new one.
*/
function entity_metadata_text_formatted_properties() {
return entity_property_text_formatted_info();
}

View File

@@ -0,0 +1,834 @@
<?php
/**
* @file
* Provides a controller for building an entity overview form.
*/
/**
* Default UI controller providing admin UI.
*
* This controller suites best for managing configuration entities.
* For a controller suiting content entities, see EntityContentUIController.
*/
class EntityDefaultUIController {
protected $entityType;
protected $entityInfo, $path;
protected $id_count;
/**
* Defines the number of entries to show per page in overview table.
*/
public $overviewPagerLimit = 25;
public function __construct($entity_type, $entity_info) {
$this->entityType = $entity_type;
$this->entityInfo = $entity_info;
$this->path = $this->entityInfo['admin ui']['path'];
$this->statusKey = empty($this->entityInfo['entity keys']['status']) ? 'status' : $this->entityInfo['entity keys']['status'];
}
/**
* Provides definitions for implementing hook_menu().
*/
public function hook_menu() {
$items = array();
// Set this on the object so classes that extend hook_menu() can use it.
$this->id_count = count(explode('/', $this->path));
$wildcard = isset($this->entityInfo['admin ui']['menu wildcard']) ? $this->entityInfo['admin ui']['menu wildcard'] : '%entity_object';
$plural_label = isset($this->entityInfo['plural label']) ? $this->entityInfo['plural label'] : $this->entityInfo['label'] . 's';
$items[$this->path] = array(
'title' => $plural_label,
'page callback' => 'drupal_get_form',
'page arguments' => array($this->entityType . '_overview_form', $this->entityType),
'description' => 'Manage ' . $plural_label . '.',
'access callback' => 'entity_access',
'access arguments' => array('view', $this->entityType),
'file' => 'includes/entity.ui.inc',
);
$items[$this->path . '/list'] = array(
'title' => 'List',
'type' => MENU_DEFAULT_LOCAL_TASK,
'weight' => -10,
);
$items[$this->path . '/add'] = array(
'title callback' => 'entity_ui_get_action_title',
'title arguments' => array('add', $this->entityType),
'page callback' => 'entity_ui_get_form',
'page arguments' => array($this->entityType, NULL, 'add'),
'access callback' => 'entity_access',
'access arguments' => array('create', $this->entityType),
'type' => MENU_LOCAL_ACTION,
);
$items[$this->path . '/manage/' . $wildcard] = array(
'title' => 'Edit',
'title callback' => 'entity_label',
'title arguments' => array($this->entityType, $this->id_count + 1),
'page callback' => 'entity_ui_get_form',
'page arguments' => array($this->entityType, $this->id_count + 1),
'load arguments' => array($this->entityType),
'access callback' => 'entity_access',
'access arguments' => array('update', $this->entityType, $this->id_count + 1),
);
$items[$this->path . '/manage/' . $wildcard . '/edit'] = array(
'title' => 'Edit',
'load arguments' => array($this->entityType),
'type' => MENU_DEFAULT_LOCAL_TASK,
);
// Clone form, a special case for the edit form.
$items[$this->path . '/manage/' . $wildcard . '/clone'] = array(
'title' => 'Clone',
'page callback' => 'entity_ui_get_form',
'page arguments' => array($this->entityType, $this->id_count + 1, 'clone'),
'load arguments' => array($this->entityType),
'access callback' => 'entity_access',
'access arguments' => array('create', $this->entityType),
);
// Menu item for operations like revert and delete.
$items[$this->path . '/manage/' . $wildcard . '/%'] = array(
'page callback' => 'drupal_get_form',
'page arguments' => array($this->entityType . '_operation_form', $this->entityType, $this->id_count + 1, $this->id_count + 2),
'load arguments' => array($this->entityType),
'access callback' => 'entity_access',
'access arguments' => array('delete', $this->entityType, $this->id_count + 1),
'file' => 'includes/entity.ui.inc',
);
if (!empty($this->entityInfo['exportable'])) {
// Menu item for importing an entity.
$items[$this->path . '/import'] = array(
'title callback' => 'entity_ui_get_action_title',
'title arguments' => array('import', $this->entityType),
'page callback' => 'drupal_get_form',
'page arguments' => array($this->entityType . '_operation_form', $this->entityType, NULL, 'import'),
'access callback' => 'entity_access',
'access arguments' => array('create', $this->entityType),
'file' => 'includes/entity.ui.inc',
'type' => MENU_LOCAL_ACTION,
);
}
if (!empty($this->entityInfo['admin ui']['file'])) {
// Add in the include file for the entity form.
foreach (array("/manage/$wildcard", "/manage/$wildcard/clone", '/add') as $path_end) {
$items[$this->path . $path_end]['file'] = $this->entityInfo['admin ui']['file'];
$items[$this->path . $path_end]['file path'] = isset($this->entityInfo['admin ui']['file path']) ? $this->entityInfo['admin ui']['file path'] : drupal_get_path('module', $this->entityInfo['module']);
}
}
return $items;
}
/**
* Provides definitions for implementing hook_forms().
*
* Use per bundle form ids if possible, such that easy per bundle alterations
* are supported too.
*
* Note that for performance reasons, this method is only invoked for forms,
* which receive the entity_type as first argument. Thus any forms added, must
* follow that pattern.
*
* @see entity_forms()
*/
public function hook_forms() {
// The overview and the operation form are implemented by the controller,
// the callback and validation + submit handlers just invoke the controller.
$forms[$this->entityType . '_overview_form'] = array(
'callback' => 'entity_ui_overview_form',
'wrapper_callback' => 'entity_ui_form_defaults',
);
$forms[$this->entityType . '_operation_form'] = array(
'callback' => 'entity_ui_operation_form',
'wrapper_callback' => 'entity_ui_form_defaults',
);
// The entity form (ENTITY_TYPE_form) handles editing, adding and cloning.
// For that form, the wrapper callback entity_ui_main_form_defaults() gets
// directly invoked via entity_ui_get_form().
// If there are bundles though, we use form ids that include the bundle name
// (ENTITY_TYPE_edit_BUNDLE_NAME_form) to enable per bundle alterations
// as well as alterations based upon the base form id (ENTITY_TYPE_form).
if (!(count($this->entityInfo['bundles']) == 1 && isset($this->entityInfo['bundles'][$this->entityType]))) {
foreach ($this->entityInfo['bundles'] as $bundle => $bundle_info) {
$forms[$this->entityType . '_edit_' . $bundle . '_form']['callback'] = $this->entityType . '_form';
// Again the wrapper callback is invoked by entity_ui_get_form() anyway.
}
}
return $forms;
}
/**
* Builds the entity overview form.
*/
public function overviewForm($form, &$form_state) {
// By default just show a simple overview for all entities.
$form['table'] = $this->overviewTable();
$form['pager'] = array('#theme' => 'pager');
return $form;
}
/**
* Overview form validation callback.
*
* @param $form
* The form array of the overview form.
* @param $form_state
* The overview form state which will be used for validating.
*/
public function overviewFormValidate($form, &$form_state) {}
/**
* Overview form submit callback.
*
* @param $form
* The form array of the overview form.
* @param $form_state
* The overview form state which will be used for submitting.
*/
public function overviewFormSubmit($form, &$form_state) {}
/**
* Generates the render array for a overview table for arbitrary entities
* matching the given conditions.
*
* @param $conditions
* An array of conditions as needed by entity_load().
* @return Array
* A renderable array.
*/
public function overviewTable($conditions = array()) {
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', $this->entityType);
// Add all conditions to query.
foreach ($conditions as $key => $value) {
$query->propertyCondition($key, $value);
}
if ($this->overviewPagerLimit) {
$query->pager($this->overviewPagerLimit);
}
$results = $query->execute();
$ids = isset($results[$this->entityType]) ? array_keys($results[$this->entityType]) : array();
$entities = $ids ? entity_load($this->entityType, $ids) : array();
ksort($entities);
$rows = array();
foreach ($entities as $entity) {
$rows[] = $this->overviewTableRow($conditions, entity_id($this->entityType, $entity), $entity);
}
$render = array(
'#theme' => 'table',
'#header' => $this->overviewTableHeaders($conditions, $rows),
'#rows' => $rows,
'#empty' => t('None.'),
);
return $render;
}
/**
* Generates the table headers for the overview table.
*/
protected function overviewTableHeaders($conditions, $rows, $additional_header = array()) {
$header = $additional_header;
array_unshift($header, t('Label'));
if (!empty($this->entityInfo['exportable'])) {
$header[] = t('Status');
}
// Add operations with the right colspan.
$header[] = array('data' => t('Operations'), 'colspan' => $this->operationCount());
return $header;
}
/**
* Returns the operation count for calculating colspans.
*/
protected function operationCount() {
$count = 3;
$count += !empty($this->entityInfo['bundle of']) && entity_type_is_fieldable($this->entityInfo['bundle of']) && module_exists('field_ui') ? 2 : 0;
$count += !empty($this->entityInfo['exportable']) ? 1 : 0;
$count += !empty($this->entityInfo['i18n controller class']) ? 1 : 0;
return $count;
}
/**
* Generates the row for the passed entity and may be overridden in order to
* customize the rows.
*
* @param $additional_cols
* Additional columns to be added after the entity label column.
*/
protected function overviewTableRow($conditions, $id, $entity, $additional_cols = array()) {
$entity_uri = entity_uri($this->entityType, $entity);
$row[] = array('data' => array(
'#theme' => 'entity_ui_overview_item',
'#label' => entity_label($this->entityType, $entity),
'#name' => !empty($this->entityInfo['exportable']) ? entity_id($this->entityType, $entity) : FALSE,
'#url' => $entity_uri ? $entity_uri : FALSE,
'#entity_type' => $this->entityType),
);
// Add in any passed additional cols.
foreach ($additional_cols as $col) {
$row[] = $col;
}
// Add a row for the exportable status.
if (!empty($this->entityInfo['exportable'])) {
$row[] = array('data' => array(
'#theme' => 'entity_status',
'#status' => $entity->{$this->statusKey},
));
}
// In case this is a bundle, we add links to the field ui tabs.
$field_ui = !empty($this->entityInfo['bundle of']) && entity_type_is_fieldable($this->entityInfo['bundle of']) && module_exists('field_ui');
// For exportable entities we add an export link.
$exportable = !empty($this->entityInfo['exportable']);
// If i18n integration is enabled, add a link to the translate tab.
$i18n = !empty($this->entityInfo['i18n controller class']);
// Add operations depending on the status.
if (entity_has_status($this->entityType, $entity, ENTITY_FIXED)) {
$row[] = array('data' => l(t('clone'), $this->path . '/manage/' . $id . '/clone'), 'colspan' => $this->operationCount());
}
else {
$row[] = l(t('edit'), $this->path . '/manage/' . $id);
if ($field_ui) {
$row[] = l(t('manage fields'), $this->path . '/manage/' . $id . '/fields');
$row[] = l(t('manage display'), $this->path . '/manage/' . $id . '/display');
}
if ($i18n) {
$row[] = l(t('translate'), $this->path . '/manage/' . $id . '/translate');
}
if ($exportable) {
$row[] = l(t('clone'), $this->path . '/manage/' . $id . '/clone');
}
if (empty($this->entityInfo['exportable']) || !entity_has_status($this->entityType, $entity, ENTITY_IN_CODE)) {
$row[] = l(t('delete'), $this->path . '/manage/' . $id . '/delete', array('query' => drupal_get_destination()));
}
elseif (entity_has_status($this->entityType, $entity, ENTITY_OVERRIDDEN)) {
$row[] = l(t('revert'), $this->path . '/manage/' . $id . '/revert', array('query' => drupal_get_destination()));
}
else {
$row[] = '';
}
}
if ($exportable) {
$row[] = l(t('export'), $this->path . '/manage/' . $id . '/export');
}
return $row;
}
/**
* Builds the operation form.
*
* For the export operation a serialized string of the entity is directly
* shown in the form (no submit function needed).
*/
public function operationForm($form, &$form_state, $entity, $op) {
switch ($op) {
case 'revert':
$label = entity_label($this->entityType, $entity);
$confirm_question = t('Are you sure you want to revert the %entity %label?', array('%entity' => $this->entityInfo['label'], '%label' => $label));
return confirm_form($form, $confirm_question, $this->path);
case 'delete':
$label = entity_label($this->entityType, $entity);
$confirm_question = t('Are you sure you want to delete the %entity %label?', array('%entity' => $this->entityInfo['label'], '%label' => $label));
return confirm_form($form, $confirm_question, $this->path);
case 'export':
if (!empty($this->entityInfo['exportable'])) {
$export = entity_export($this->entityType, $entity);
$form['export'] = array(
'#type' => 'textarea',
'#title' => t('Export'),
'#description' => t('For importing copy the content of the text area and paste it into the import page.'),
'#rows' => 25,
'#default_value' => $export,
);
return $form;
}
case 'import':
$form['import'] = array(
'#type' => 'textarea',
'#title' => t('Import'),
'#description' => t('Paste an exported %entity_type here.', array('%entity_type' => $this->entityInfo['label'])),
'#rows' => 20,
);
$form['overwrite'] = array(
'#title' => t('Overwrite'),
'#type' => 'checkbox',
'#description' => t('If checked, any existing %entity with the same identifier will be replaced by the import.', array('%entity' => $this->entityInfo['label'])),
'#default_value' => FALSE,
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Import'),
);
return $form;
}
drupal_not_found();
exit;
}
/**
* Operation form validation callback.
*/
public function operationFormValidate($form, &$form_state) {
if ($form_state['op'] == 'import') {
if ($entity = entity_import($this->entityType, $form_state['values']['import'])) {
// Store the successfully imported entity in $form_state.
$form_state[$this->entityType] = $entity;
if (!$form_state['values']['overwrite']) {
// Check for existing entities with the same identifier.
$id = entity_id($this->entityType, $entity);
$entities = entity_load($this->entityType, array($id));
if (!empty($entities)) {
$label = entity_label($this->entityType, $entity);
$vars = array('%entity' => $this->entityInfo['label'], '%label' => $label);
form_set_error('import', t('Import of %entity %label failed, a %entity with the same machine name already exists. Check the overwrite option to replace it.', $vars));
}
}
}
else {
form_set_error('import', t('Import failed.'));
}
}
}
/**
* Operation form submit callback.
*/
public function operationFormSubmit($form, &$form_state) {
$msg = $this->applyOperation($form_state['op'], $form_state[$this->entityType]);
drupal_set_message($msg);
$form_state['redirect'] = $this->path;
}
/**
* Applies an operation to the given entity.
*
* Note: the export operation is directly carried out by the operationForm()
* method.
*
* @param string $op
* The operation (revert, delete or import).
* @param $entity
* The entity to manipulate.
*
* @return
* The status message of what has been applied.
*/
public function applyOperation($op, $entity) {
$label = entity_label($this->entityType, $entity);
$vars = array('%entity' => $this->entityInfo['label'], '%label' => $label);
$id = entity_id($this->entityType, $entity);
$edit_link = l(t('edit'), $this->path . '/manage/' . $id . '/edit');
switch ($op) {
case 'revert':
entity_delete($this->entityType, $id);
watchdog($this->entityType, 'Reverted %entity %label to the defaults.', $vars, WATCHDOG_NOTICE, $edit_link);
return t('Reverted %entity %label to the defaults.', $vars);
case 'delete':
entity_delete($this->entityType, $id);
watchdog($this->entityType, 'Deleted %entity %label.', $vars);
return t('Deleted %entity %label.', $vars);
case 'import':
// First check if there is any existing entity with the same ID.
$id = entity_id($this->entityType, $entity);
$entities = entity_load($this->entityType, array($id));
if ($existing_entity = reset($entities)) {
// Copy DB id and remove the new indicator to overwrite the DB record.
$idkey = $this->entityInfo['entity keys']['id'];
$entity->{$idkey} = $existing_entity->{$idkey};
unset($entity->is_new);
}
entity_save($this->entityType, $entity);
watchdog($this->entityType, 'Imported %entity %label.', $vars);
return t('Imported %entity %label.', $vars);
default:
return FALSE;
}
}
/**
* Entity submit builder invoked via entity_ui_form_submit_build_entity().
*
* Extracts the form values and updates the entity.
*
* The provided implementation makes use of the helper function
* entity_form_submit_build_entity() provided by core, which already invokes
* the field API attacher for fieldable entities.
*
* @return
* The updated entity.
*
* @see entity_ui_form_submit_build_entity()
*/
public function entityFormSubmitBuildEntity($form, &$form_state) {
// Add the bundle property to the entity if the entity type supports bundles
// and the form provides a value for the bundle key. Especially new entities
// need to have their bundle property pre-populated before we invoke
// entity_form_submit_build_entity().
if (!empty($this->entityInfo['entity keys']['bundle']) && isset($form_state['values'][$this->entityInfo['entity keys']['bundle']])) {
$form_state[$this->entityType]->{$this->entityInfo['entity keys']['bundle']} = $form_state['values'][$this->entityInfo['entity keys']['bundle']];
}
entity_form_submit_build_entity($this->entityType, $form_state[$this->entityType], $form, $form_state);
return $form_state[$this->entityType];
}
}
/**
* UI controller providing UI for content entities.
*
* For a controller providing UI for bundleable content entities, see
* EntityBundleableUIController.
* For a controller providing admin UI for configuration entities, see
* EntityDefaultUIController.
*/
class EntityContentUIController extends EntityDefaultUIController {
/**
* Provides definitions for implementing hook_menu().
*/
public function hook_menu() {
$items = parent::hook_menu();
$wildcard = isset($this->entityInfo['admin ui']['menu wildcard']) ? $this->entityInfo['admin ui']['menu wildcard'] : '%entity_object';
// Unset the manage entity path, as the provided UI is for admin entities.
unset($items[$this->path]);
$defaults = array(
'file' => $this->entityInfo['admin ui']['file'],
'file path' => isset($this->entityInfo['admin ui']['file path']) ? $this->entityInfo['admin ui']['file path'] : drupal_get_path('module', $this->entityInfo['module']),
);
// Add view, edit and delete menu items for content entities.
$items[$this->path . '/' . $wildcard] = array(
'title callback' => 'entity_ui_get_page_title',
'title arguments' => array('view', $this->entityType, $this->id_count),
'page callback' => 'entity_ui_entity_page_view',
'page arguments' => array($this->id_count),
'load arguments' => array($this->entityType),
'access callback' => 'entity_access',
'access arguments' => array('view', $this->entityType, $this->id_count),
) + $defaults;
$items[$this->path . '/' . $wildcard . '/view'] = array(
'title' => 'View',
'type' => MENU_DEFAULT_LOCAL_TASK,
'load arguments' => array($this->entityType),
'weight' => -10,
) + $defaults;
$items[$this->path . '/' . $wildcard . '/edit'] = array(
'page callback' => 'entity_ui_get_form',
'page arguments' => array($this->entityType, $this->id_count),
'load arguments' => array($this->entityType),
'access callback' => 'entity_access',
'access arguments' => array('edit', $this->entityType, $this->id_count),
'title' => 'Edit',
'type' => MENU_LOCAL_TASK,
'context' => MENU_CONTEXT_PAGE | MENU_CONTEXT_INLINE,
) + $defaults;
$items[$this->path . '/' . $wildcard . '/delete'] = array(
'page callback' => 'drupal_get_form',
'page arguments' => array($this->entityType . '_operation_form', $this->entityType, $this->id_count, 'delete'),
'load arguments' => array($this->entityType),
'access callback' => 'entity_access',
'access arguments' => array('delete', $this->entityType, $this->id_count),
'title' => 'Delete',
'type' => MENU_LOCAL_TASK,
'context' => MENU_CONTEXT_INLINE,
'file' => $this->entityInfo['admin ui']['file'],
'file path' => isset($this->entityInfo['admin ui']['file path']) ? $this->entityInfo['admin ui']['file path'] : drupal_get_path('module', $this->entityInfo['module']),
) + $defaults;
return $items;
}
/**
* Operation form submit callback.
*/
public function operationFormSubmit($form, &$form_state) {
parent::operationFormSubmit($form, $form_state);
// The manage entity path is unset for the content entity UI.
$form_state['redirect'] = '<front>';
}
}
/**
* UI controller providing UI for bundleable content entities.
*
* Adds a bundle selection page to the entity/add path, analogously to the
* node/add path.
*/
class EntityBundleableUIController extends EntityContentUIController {
/**
* Provides definitions for implementing hook_menu().
*/
public function hook_menu() {
$items = parent::hook_menu();
// Extend the 'add' path.
$items[$this->path . '/add'] = array(
'title callback' => 'entity_ui_get_action_title',
'title arguments' => array('add', $this->entityType),
'page callback' => 'entity_ui_bundle_add_page',
'page arguments' => array($this->entityType),
'access callback' => 'entity_access',
'access arguments' => array('create', $this->entityType),
'type' => MENU_LOCAL_ACTION,
);
$items[$this->path . '/add/%'] = array(
'title callback' => 'entity_ui_get_action_title',
'title arguments' => array('add', $this->entityType, $this->id_count + 1),
'page callback' => 'entity_ui_get_bundle_add_form',
'page arguments' => array($this->entityType, $this->id_count + 1),
'access callback' => 'entity_access',
'access arguments' => array('create', $this->entityType),
);
if (!empty($this->entityInfo['admin ui']['file'])) {
// Add in the include file for the entity form.
foreach (array('/add', '/add/%') as $path_end) {
$items[$this->path . $path_end]['file'] = $this->entityInfo['admin ui']['file'];
$items[$this->path . $path_end]['file path'] = isset($this->entityInfo['admin ui']['file path']) ? $this->entityInfo['admin ui']['file path'] : drupal_get_path('module', $this->entityInfo['module']);
}
}
return $items;
}
}
/**
* Form builder function for the overview form.
*
* @see EntityDefaultUIController::overviewForm()
*/
function entity_ui_overview_form($form, &$form_state, $entity_type) {
return entity_ui_controller($entity_type)->overviewForm($form, $form_state);
}
/**
* Form builder for the entity operation form.
*
* @see EntityDefaultUIController::operationForm()
*/
function entity_ui_operation_form($form, &$form_state, $entity_type, $entity, $op) {
$form_state['op'] = $op;
return entity_ui_controller($entity_type)->operationForm($form, $form_state, $entity, $op);
}
/**
* Form wrapper the main entity form.
*
* @see entity_ui_form_defaults()
*/
function entity_ui_main_form_defaults($form, &$form_state, $entity = NULL, $op = NULL) {
// Now equals entity_ui_form_defaults() but is still here to keep backward
// compatability.
return entity_ui_form_defaults($form, $form_state, $form_state['entity_type'], $entity, $op);
}
/**
* Clones the entity object and makes sure it will get saved as new entity.
*
* @return
* The cloned entity object.
*/
function entity_ui_clone_entity($entity_type, $entity) {
// Clone the entity and make sure it will get saved as a new entity.
$entity = clone $entity;
$entity_info = entity_get_info($entity_type);
$entity->{$entity_info['entity keys']['id']} = FALSE;
if (!empty($entity_info['entity keys']['name'])) {
$entity->{$entity_info['entity keys']['name']} = FALSE;
}
$entity->is_new = TRUE;
// Make sure the status of a cloned exportable is custom.
if (!empty($entity_info['exportable'])) {
$status_key = isset($entity_info['entity keys']['status']) ? $entity_info['entity keys']['status'] : 'status';
$entity->$status_key = ENTITY_CUSTOM;
}
return $entity;
}
/**
* Form wrapper callback for all entity ui forms.
*
* This callback makes sure the form state is properly initialized and sets
* some useful default titles.
*
* @see EntityDefaultUIController::hook_forms()
*/
function entity_ui_form_defaults($form, &$form_state, $entity_type, $entity = NULL, $op = NULL) {
$defaults = array(
'entity_type' => $entity_type,
);
if (isset($entity)) {
$defaults[$entity_type] = $entity;
}
if (isset($op)) {
$defaults['op'] = $op;
}
$form_state += $defaults;
if (isset($op)) {
drupal_set_title(entity_ui_get_page_title($op, $entity_type, $entity), PASS_THROUGH);
}
// Add in handlers pointing to the controller for the forms implemented by it.
if (isset($form_state['build_info']['base_form_id']) && $form_state['build_info']['base_form_id'] != $entity_type . '_form') {
$form['#validate'][] = 'entity_ui_controller_form_validate';
$form['#submit'][] = 'entity_ui_controller_form_submit';
}
return $form;
}
/**
* Validation callback for forms implemented by the UI controller.
*/
function entity_ui_controller_form_validate($form, &$form_state) {
// Remove 'entity_ui_' prefix and the '_form' suffix.
$base = substr($form_state['build_info']['base_form_id'], 10, -5);
$method = $base . 'FormValidate';
entity_ui_controller($form_state['entity_type'])->$method($form, $form_state);
}
/**
* Submit callback for forms implemented by the UI controller.
*/
function entity_ui_controller_form_submit($form, &$form_state) {
// Remove 'entity_ui_' prefix and the '_form' suffix.
$base = substr($form_state['build_info']['base_form_id'], 10, -5);
$method = $base . 'FormSubmit';
entity_ui_controller($form_state['entity_type'])->$method($form, $form_state);
}
/**
* Gets the page title for the passed operation.
*/
function entity_ui_get_page_title($op, $entity_type, $entity = NULL) {
$label = entity_label($entity_type, $entity);
switch ($op) {
case 'view':
return $label;
case 'edit':
return t('Edit @label', array('@label' => $label));
case 'clone':
return t('Clone @label', array('@label' => $label));
case 'revert':
return t('Revert @label', array('@label' => $label));
case 'delete':
return t('Delete @label', array('@label' => $label));
case 'export':
return t('Export @label', array('@label' => $label));
}
if (isset($entity)) {
list(, , $bundle) = entity_extract_ids($entity_type, $entity);
}
return entity_ui_get_action_title($op, $entity_type, $bundle);
}
/**
* Gets the page/menu title for local action operations.
*
* @param $op
* The current operation. One of 'add' or 'import'.
* @param $entity_type
* The entity type.
* @param $bundle_name
* (Optional) The name of the bundle. May be NULL if the bundle name is not
* relevant to the current page. If the entity type has only one bundle, or no
* bundles, this will be the same as the entity type.
*/
function entity_ui_get_action_title($op, $entity_type, $bundle_name = NULL) {
$info = entity_get_info($entity_type);
switch ($op) {
case 'add':
if (isset($bundle_name) && $bundle_name != $entity_type) {
return t('Add @bundle_name @entity_type', array(
'@bundle_name' => drupal_strtolower($info['bundles'][$bundle_name]['label']),
'@entity_type' => drupal_strtolower($info['label']),
));
}
else {
return t('Add @entity_type', array('@entity_type' => drupal_strtolower($info['label'])));
}
case 'import':
return t('Import @entity_type', array('@entity_type' => drupal_strtolower($info['label'])));
}
}
/**
* Submit builder for the main entity form, which extracts the form values and updates the entity.
*
* This is a helper function for entities making use of the entity UI
* controller.
*
* @return
* The updated entity.
*
* @see EntityDefaultUIController::hook_forms()
* @see EntityDefaultUIController::entityFormSubmitBuildEntity()
*/
function entity_ui_form_submit_build_entity($form, &$form_state) {
return entity_ui_controller($form_state['entity_type'])->entityFormSubmitBuildEntity($form, $form_state);
}
/**
* Validation callback for machine names of exportables.
*
* We don't allow numeric machine names, as entity_load() treats them as the
* numeric identifier and they are easily confused with ids in general.
*/
function entity_ui_validate_machine_name($element, &$form_state) {
if (is_numeric($element['#value'])) {
form_error($element, t('Machine-readable names must not consist of numbers only.'));
}
}
/**
* Returns HTML for an entity on the entity overview listing.
*
* @ingroup themeable
*/
function theme_entity_ui_overview_item($variables) {
$output = $variables['url'] ? l($variables['label'], $variables['url']['path'], $variables['url']['options']) : check_plain($variables['label']);
if ($variables['name']) {
$output .= ' <small> (' . t('Machine name') . ': ' . check_plain($variables['name']) . ')</small>';
}
return $output;
}
/**
* Page callback for viewing an entity.
*
* @param Entity $entity
* The entity to be rendered.
*
* @return array
* A renderable array of the entity in full view mode.
*/
function entity_ui_entity_page_view($entity) {
return $entity->view('full', NULL, TRUE);
}

File diff suppressed because it is too large Load Diff