Commit b8016410 authored by catch's avatar catch
Browse files

Issue #2015697 by claudiu.cristea, yched, Berdir, splatio: Convert field type...

Issue #2015697 by claudiu.cristea, yched, Berdir, splatio: Convert field type to typed data plugin for file and image modules.
parent ef874408
...@@ -470,10 +470,10 @@ function content_translation_translatable_batch($translatable, $field_name, &$co ...@@ -470,10 +470,10 @@ function content_translation_translatable_batch($translatable, $field_name, &$co
// We need a two-step approach while updating field translations: given // We need a two-step approach while updating field translations: given
// that field-specific update functions might rely on the stored values to // that field-specific update functions might rely on the stored values to
// perform their processing, see for instance file_field_update(), first // perform their processing first we need to store the new translations
// we need to store the new translations and only after we can remove the // and only after we can remove the old ones. Otherwise we might have data
// old ones. Otherwise we might have data loss, since the removal of the // loss, since the removal of the old translations might occur before the
// old translations might occur before the new ones are stored. // new ones are stored.
if ($translatable && isset($entity->{$field_name}[Language::LANGCODE_NOT_SPECIFIED])) { if ($translatable && isset($entity->{$field_name}[Language::LANGCODE_NOT_SPECIFIED])) {
// If the field is being switched to translatable and has data for // If the field is being switched to translatable and has data for
// Language::LANGCODE_NOT_SPECIFIED then we need to move the data to the right // Language::LANGCODE_NOT_SPECIFIED then we need to move the data to the right
......
...@@ -6,314 +6,15 @@ ...@@ -6,314 +6,15 @@
*/ */
use Drupal\Component\Utility\NestedArray; use Drupal\Component\Utility\NestedArray;
use Drupal\Core\Entity\EntityInterface;
/** /**
* Implements hook_field_info(). * Implements hook_field_info_alter().
*/
function file_field_info() {
return array(
'file' => array(
'label' => t('File'),
'description' => t('This field stores the ID of a file as an integer value.'),
'settings' => array(
'display_field' => 0,
'display_default' => 0,
'uri_scheme' => file_default_scheme(),
),
'instance_settings' => array(
'file_extensions' => 'txt',
'file_directory' => '',
'max_filesize' => '',
'description_field' => 0,
),
'default_widget' => 'file_generic',
'default_formatter' => 'file_default',
'class' => '\Drupal\file\Type\FileItem',
'list_class' => '\Drupal\file\Type\FileField',
),
);
}
/**
* Implements hook_field_settings_form().
*/
function file_field_settings_form($field, $instance) {
$defaults = \Drupal::service('plugin.manager.entity.field.field_type')->getDefaultSettings($field['type']);
$settings = array_merge($defaults, $field['settings']);
$form['#attached']['library'][] = array('file', 'drupal.file');
$form['display_field'] = array(
'#type' => 'checkbox',
'#title' => t('Enable <em>Display</em> field'),
'#default_value' => $settings['display_field'],
'#description' => t('The display option allows users to choose if a file should be shown when viewing the content.'),
);
$form['display_default'] = array(
'#type' => 'checkbox',
'#title' => t('Files displayed by default'),
'#default_value' => $settings['display_default'],
'#description' => t('This setting only has an effect if the display option is enabled.'),
'#states' => array(
'visible' => array(
':input[name="field[settings][display_field]"]' => array('checked' => TRUE),
),
),
);
$scheme_options = array();
foreach (file_get_stream_wrappers(STREAM_WRAPPERS_WRITE_VISIBLE) as $scheme => $stream_wrapper) {
$scheme_options[$scheme] = $stream_wrapper['name'];
}
$form['uri_scheme'] = array(
'#type' => 'radios',
'#title' => t('Upload destination'),
'#options' => $scheme_options,
'#default_value' => $settings['uri_scheme'],
'#description' => t('Select where the final files should be stored. Private file storage has significantly more overhead than public files, but allows restricted access to files within this field.'),
'#disabled' => $field->hasData(),
);
return $form;
}
/**
* Implements hook_field_instance_settings_form().
*/
function file_field_instance_settings_form($field, $instance) {
$settings = $instance['settings'];
$form['file_directory'] = array(
'#type' => 'textfield',
'#title' => t('File directory'),
'#default_value' => $settings['file_directory'],
'#description' => t('Optional subdirectory within the upload destination where files will be stored. Do not include preceding or trailing slashes.'),
'#element_validate' => array('_file_generic_settings_file_directory_validate'),
'#weight' => 3,
);
// Make the extension list a little more human-friendly by comma-separation.
$extensions = str_replace(' ', ', ', $settings['file_extensions']);
$form['file_extensions'] = array(
'#type' => 'textfield',
'#title' => t('Allowed file extensions'),
'#default_value' => $extensions,
'#description' => t('Separate extensions with a space or comma and do not include the leading dot.'),
'#element_validate' => array('_file_generic_settings_extensions'),
'#weight' => 1,
// By making this field required, we prevent a potential security issue
// that would allow files of any type to be uploaded.
'#required' => TRUE,
);
$form['max_filesize'] = array(
'#type' => 'textfield',
'#title' => t('Maximum upload size'),
'#default_value' => $settings['max_filesize'],
'#description' => t('Enter a value like "512" (bytes), "80 KB" (kilobytes) or "50 MB" (megabytes) in order to restrict the allowed file size. If left empty the file sizes will be limited only by PHP\'s maximum post and file upload sizes (current limit <strong>%limit</strong>).', array('%limit' => format_size(file_upload_max_size()))),
'#size' => 10,
'#element_validate' => array('_file_generic_settings_max_filesize'),
'#weight' => 5,
);
$form['description_field'] = array(
'#type' => 'checkbox',
'#title' => t('Enable <em>Description</em> field'),
'#default_value' => isset($settings['description_field']) ? $settings['description_field'] : '',
'#description' => t('The description field allows users to enter a description about the uploaded file.'),
'#parents' => array('instance', 'settings', 'description_field'),
'#weight' => 11,
);
return $form;
}
/**
* Render API callback: Validates the maximum upload size field.
*
* Ensures that a size has been entered and that it can be parsed by
* parse_size().
*
* This function is assigned as an #element_validate callback in
* file_field_instance_settings_form().
*/
function _file_generic_settings_max_filesize($element, &$form_state) {
if (!empty($element['#value']) && !is_numeric(parse_size($element['#value']))) {
form_error($element, t('The "!name" option must contain a valid value. You may either leave the text field empty or enter a string like "512" (bytes), "80 KB" (kilobytes) or "50 MB" (megabytes).', array('!name' => t($element['title']))));
}
}
/**
* Render API callback: Validates the allowed file extensions field.
*
* This function is assigned as an #element_validate callback in
* file_field_instance_settings_form().
*
* This doubles as a convenience clean-up function and a validation routine.
* Commas are allowed by the end-user, but ultimately the value will be stored
* as a space-separated list for compatibility with file_validate_extensions().
*/
function _file_generic_settings_extensions($element, &$form_state) {
if (!empty($element['#value'])) {
$extensions = preg_replace('/([, ]+\.?)/', ' ', trim(strtolower($element['#value'])));
$extensions = array_filter(explode(' ', $extensions));
$extensions = implode(' ', array_unique($extensions));
if (!preg_match('/^([a-z0-9]+([.][a-z0-9])* ?)+$/', $extensions)) {
form_error($element, t('The list of allowed extensions is not valid, be sure to exclude leading dots and to separate extensions with a comma or space.'));
}
else {
form_set_value($element, $extensions, $form_state);
}
}
}
/**
* Render API callback: Validates the file destination field.
*
* Removes slashes from the beginning and end of the destination value and
* ensures that the file directory path is not included at the beginning of the
* value.
*
* This function is assigned as an #element_validate callback in
* file_field_instance_settings_form().
*/
function _file_generic_settings_file_directory_validate($element, &$form_state) {
// Strip slashes from the beginning and end of $widget['file_directory'].
$value = trim($element['#value'], '\\/');
form_set_value($element, $value, $form_state);
}
/**
* Implements hook_field_insert().
*/
function file_field_insert(EntityInterface $entity, $field, $instance, $langcode, &$items) {
// Add a new usage of each uploaded file.
foreach ($items as $item) {
file_usage()->add(file_load($item['target_id']), 'file', $entity->entityType(), $entity->id());
}
}
/**
* Implements hook_field_update().
* *
* Checks for files that have been removed from the object. * Cannot annotate in FieldItem plugin the settings.uri_scheme meta data key
*/ * with a dynamic value. We need to alter the value here.
function file_field_update(EntityInterface $entity, $field, $instance, $langcode, &$items) {
// On new revisions, all files are considered to be a new usage and no
// deletion of previous file usages are necessary.
if (!empty($entity->original) && $entity->getRevisionId() != $entity->original->getRevisionId()) {
foreach ($items as $item) {
file_usage()->add(file_load($item['target_id']), 'file', $entity->entityType(), $entity->id());
}
return;
}
// Build a display of the current FIDs.
$current_fids = array();
foreach ($items as $item) {
$current_fids[] = $item['target_id'];
}
// Compare the original field values with the ones that are being saved.
$original = $entity->original->getBCEntity();
$original_fids = array();
if (!empty($original->{$field['field_name']}[$langcode])) {
foreach ($original->{$field['field_name']}[$langcode] as $original_item) {
$original_fids[] = $original_item['target_id'];
if (isset($original_item['target_id']) && !in_array($original_item['target_id'], $current_fids)) {
// Decrement the file usage count by 1.
file_usage()->delete(file_load($original_item['target_id']), 'file', $entity->entityType(), $entity->id());
}
}
}
// Add new usage entries for newly added files.
foreach ($items as $item) {
if (!in_array($item['target_id'], $original_fids)) {
file_usage()->add(file_load($item['target_id']), 'file', $entity->entityType(), $entity->id());
}
}
}
/**
* Implements hook_field_delete().
*/ */
function file_field_delete(EntityInterface $entity, $field, $instance, $langcode, &$items) { function file_field_info_alter(&$info) {
// Delete all file usages within this entity. $info['file']['settings']['uri_scheme'] = file_default_scheme();
foreach ($items as $delta => $item) {
file_usage()->delete(file_load($item['target_id']), 'file', $entity->entityType(), $entity->id(), 0);
}
}
/**
* Implements hook_field_delete_revision().
*/
function file_field_delete_revision(EntityInterface $entity, $field, $instance, $langcode, &$items) {
foreach ($items as $delta => $item) {
// Decrement the file usage count by 1.
file_usage()->delete(file_load($item['target_id']), 'file', $entity->entityType(), $entity->id());
}
}
/**
* Implements hook_field_is_empty().
*/
function file_field_is_empty($item, $field_type) {
return empty($item['target_id']);
}
/**
* Retrieves the upload validators for a file field.
*
* @param array $field_settings
* The field settings.
*
* @return
* An array suitable for passing to file_save_upload() or the file field
* element's '#upload_validators' property.
*/
function file_field_widget_upload_validators(array $field_settings) {
// Cap the upload size according to the PHP limit.
$max_filesize = parse_size(file_upload_max_size());
if (!empty($field_settings['max_filesize']) && parse_size($field_settings['max_filesize']) < $max_filesize) {
$max_filesize = parse_size($field_settings['max_filesize']);
}
$validators = array();
// There is always a file size limit due to the PHP server limit.
$validators['file_validate_size'] = array($max_filesize);
// Add the extension check if necessary.
if (!empty($field_settings['file_extensions'])) {
$validators['file_validate_extensions'] = array($field_settings['file_extensions']);
}
return $validators;
}
/**
* Determines the URI for a file field.
*
* @param array $field_settings
* The field settings.
* @param $data
* An array of token objects to pass to
* \Drupal\Core\Utility\Token::replace().
*
* @return
* A file directory URI with tokens replaced.
*
* @see \Drupal\Core\Utility\Token::replace()
*/
function file_field_widget_uri(array $field_settings, $data = array()) {
$destination = trim($field_settings['file_directory'], '/');
// Replace tokens.
$destination = Drupal::token()->replace($destination, $data);
return $field_settings['uri_scheme'] . '://' . $destination;
} }
/** /**
......
...@@ -152,44 +152,6 @@ function file_schema() { ...@@ -152,44 +152,6 @@ function file_schema() {
return $schema; return $schema;
} }
/**
* Implements hook_field_schema().
*/
function file_field_schema($field) {
return array(
'columns' => array(
'target_id' => array(
'description' => 'The ID of the target entity.',
'type' => 'int',
'not null' => TRUE,
'unsigned' => TRUE,
),
'display' => array(
'description' => 'Flag to control whether this file should be displayed when viewing content.',
'type' => 'int',
'size' => 'tiny',
'unsigned' => TRUE,
'not null' => TRUE,
'default' => 1,
),
'description' => array(
'description' => 'A description of the file.',
'type' => 'text',
'not null' => FALSE,
),
),
'indexes' => array(
'target_id' => array('target_id'),
),
'foreign keys' => array(
'target_id' => array(
'table' => 'file_managed',
'columns' => array('target_id' => 'fid'),
),
),
);
}
/** /**
* Implements hook_requirements(). * Implements hook_requirements().
* *
......
<?php
/**
* @file
* Contains \Drupal\file\Plugin\field\field_type\FileField.
*/
namespace Drupal\file\Plugin\field\field_type;
use Drupal\field\Plugin\Type\FieldType\ConfigField;
/**
* Represents a configurable entity file field.
*/
class FileField extends ConfigField {
/**
* {@inheritdoc}
*/
public function defaultValuesForm(array &$form, array &$form_state) { }
/**
* {@inheritdoc}
*/
public function update() {
parent::update();
$this->updateFileUsage();
}
/**
* Updates the file usage.
*/
protected function updateFileUsage() {
$entity = $this->getRoot();
// On new revisions, all files are considered to be a new usage and no
// deletion of previous file usages are necessary.
if (!empty($entity->original) && $entity->getRevisionId() != $entity->original->getRevisionId()) {
foreach ($this->list as $item) {
file_usage()->add($item->entity, 'file', $entity->entityType(), $entity->id());
}
return;
}
// Build a list of the current target IDs.
$fids = array();
foreach ($this->list as $item) {
$fids[] = $item->target_id;
}
// Compare the original field values with the ones that are being saved.
$field_name = $this->getFieldDefinition()->getFieldName();
$original_fids = array();
$original_items = $entity->original->getTranslation($this->getLangcode())->$field_name;
foreach ($original_items as $item) {
$original_fids[] = $item->target_id;
if ($item->target_id && !in_array($item->target_id, $fids)) {
// Decrement the file usage count by 1.
file_usage()->delete($item->entity, 'file', $entity->entityType(), $entity->id());
}
}
// Add new usage entries for newly added files.
foreach ($this->list as $item) {
if ($item->target_id && !in_array($item->target_id, $original_fids)) {
file_usage()->add($item->entity, 'file', $entity->entityType(), $entity->id());
}
}
}
}
<?php
/**
* @file
* Contains \Drupal\file\Plugin\field\field_type\FileItem.
*/
namespace Drupal\file\Plugin\field\field_type;
use Drupal\Core\Annotation\Translation;
use Drupal\Core\Entity\Annotation\FieldType;
use Drupal\Core\Entity\Plugin\DataType\EntityReferenceItem;
use Drupal\field\FieldInterface;
use Drupal\field\Plugin\Type\FieldType\ConfigFieldItemInterface;
/**
* Plugin implementation of the 'file' field type.
*
* @FieldType(
* id = "file",
* label = @Translation("File"),
* description = @Translation("This field stores the ID of a file as an integer value."),
* settings = {
* "display_field" = "0",
* "display_default" = "0",
* "uri_scheme" = ""
* },
* instance_settings = {
* "file_extensions" = "txt",
* "file_directory" = "",
* "max_filesize" = "",
* "description_field" = "0"
* },
* default_widget = "file_generic",
* default_formatter = "file_default",
* list_class = "\Drupal\file\Plugin\field\field_type\FileField"
* )
*/
class FileItem extends EntityReferenceItem implements ConfigFieldItemInterface {
/**
* Property definitions of the contained properties.
*
* @see FileItem::getPropertyDefinitions()
*
* @var array
*/
static $propertyDefinitions;
/**
* {@inheritdoc}
*/
public function getInstance() {
if (!isset($this->instance) && $parent = $this->getParent()) {
$this->instance = $parent->getInstance();
}
return $this->instance;
}
/**
* {@inheritdoc}
*/
public static function schema(FieldInterface $field) {
return array(
'columns' => array(
'target_id' => array(
'description' => 'The ID of the file entity.',
'type' => 'int',
'not null' => TRUE,
'unsigned' => TRUE,
),
'display' => array(
'description' => 'Flag to control whether this file should be displayed when viewing content.',
'type' => 'int',
'size' => 'tiny',
'unsigned' => TRUE,
'not null' => TRUE,
'default' => 1,
),
'description' => array(
'description' => 'A description of the file.',
'type' => 'text',
'not null' => FALSE,
),
),
'indexes' => array(
'target_id' => array('target_id'),
),
'foreign keys' => array(
'target_id' => array(
'table' => 'file_managed',
'columns' => array('target_id' => 'fid'),
),
),
);
}
/**
* {@inheritdoc}
*/
public function getPropertyDefinitions() {
$this->definition['settings']['target_type'] = 'file';
if (!isset(static::$propertyDefinitions)) {
static::$propertyDefinitions = parent::getPropertyDefinitions();
static::$propertyDefinitions['display'] = array(
'type' => 'boolean',
'label' => t('Flag to control whether this file should be displayed when viewing content.'),
);
static::$propertyDefinitions['description'] = array(
'type' => 'string',
'label' => t('A description of the file.'),
);
}
return static::$propertyDefinitions;
}
/**
* {@inheritdoc}
*/
public function settingsForm(array $form, array &$form_state, $has_data) {
$element = array();
$element['#attached']['library'][] = array('file', 'drupal.file');
$element['display_field'] = array(
'#type' => 'checkbox',
'#title' => t('Enable <em>Display</em> field'),
'#default_value' => $this->getFieldSetting('display_field'),
'#description' => t('The display option allows users to choose if a file should be shown when viewing the content.'),
);
$element['display_default'] = array(
'#type' => 'checkbox',
'#title' => t('Files displayed by default'),
'#default_value' => $this->getFieldSetting('display_default'),
'#description' => t('This setting only has an effect if the display option is enabled.'),
'#states' => array(
'visible' => array(