updated core from 8.4 to 8.5 : bug with login_destination

This commit is contained in:
Bachir Soussi Chiadmi
2018-03-13 14:01:21 +01:00
parent 0d78da249b
commit e668535a4e
3486 changed files with 89604 additions and 33283 deletions
@@ -70,16 +70,55 @@ field.field_settings.file:
type: boolean
label: 'Enable Description field'
file.formatter.media:
type: mapping
label: 'Media display format settings'
mapping:
controls:
type: boolean
label: 'Show playback controls'
autoplay:
type: boolean
label: 'Autoplay'
loop:
type: boolean
label: 'Loop'
multiple_file_display_type:
type: string
label: 'Display of multiple files'
field.formatter.settings.file_audio:
type: file.formatter.media
label: 'Audio file display format settings'
field.formatter.settings.file_video:
type: file.formatter.media
label: 'Video file display format settings'
mapping:
muted:
type: boolean
label: 'Muted'
width:
type: integer
label: 'Width'
height:
type: integer
label: 'Height'
field.formatter.settings.file_default:
type: mapping
label: 'Generic file format settings'
mapping:
use_description_as_link_text:
type: boolean
label: 'Replace the file name by its description when available'
field.formatter.settings.file_rss_enclosure:
type: mapping
label: 'RSS enclosure format settings'
field.formatter.settings.file_table:
type: mapping
type: field.formatter.settings.file_default
label: 'Table of files format settings'
field.formatter.settings.file_url_plain:
+3 -3
View File
@@ -7,8 +7,8 @@ package: Field types
dependencies:
- field
# Information added by Drupal.org packaging script on 2018-01-03
version: '8.4.4'
# Information added by Drupal.org packaging script on 2018-03-07
version: '8.5.0'
core: '8.x'
project: 'drupal'
datestamp: 1515021228
datestamp: 1520457825
+36
View File
@@ -5,6 +5,8 @@
* Install, update and uninstall functions for File module.
*/
use Drupal\Core\Entity\Entity\EntityViewDisplay;
/**
* Implements hook_schema().
*/
@@ -128,3 +130,37 @@ function file_update_8300() {
return t('Files that have no remaining usages are no longer deleted by default.');
}
/**
* Add 'use_description_as_link_text' setting to file field formatters.
*/
function file_update_8001() {
$displays = EntityViewDisplay::loadMultiple();
foreach ($displays as $display) {
/** @var \Drupal\Core\Entity\Entity\EntityViewDisplay $display */
$fields_settings = $display->get('content');
$changed = FALSE;
foreach ($fields_settings as $field_name => $settings) {
if (!empty($settings['type'])) {
switch ($settings['type']) {
// The file_table formatter never displayed available descriptions
// before, so we disable this option to ensure backward compatibility.
case 'file_table':
$fields_settings[$field_name]['settings']['use_description_as_link_text'] = FALSE;
$changed = TRUE;
break;
// The file_default formatter always displayed available descriptions
// before, so we enable this option to ensure backward compatibility.
case 'file_default':
$fields_settings[$field_name]['settings']['use_description_as_link_text'] = TRUE;
$changed = TRUE;
break;
}
}
}
if ($changed === TRUE) {
$display->set('content', $fields_settings)->save();
}
}
}
+150 -9
View File
@@ -48,6 +48,16 @@ function file_help($route_name, RouteMatchInterface $route_match) {
}
}
/**
* Implements hook_field_widget_info_alter().
*/
function file_field_widget_info_alter(array &$info) {
// Allows using the 'uri' widget for the 'file_uri' field type, which uses it
// as the default widget.
// @see \Drupal\file\Plugin\Field\FieldType\FileUriItem
$info['uri']['field_types'][] = 'file_uri';
}
/**
* Loads file entities from the database.
*
@@ -140,7 +150,7 @@ function file_load($fid, $reset = FALSE) {
*/
function file_copy(FileInterface $source, $destination = NULL, $replace = FILE_EXISTS_RENAME) {
if (!file_valid_uri($destination)) {
if (($realpath = drupal_realpath($source->getFileUri())) !== FALSE) {
if (($realpath = \Drupal::service('file_system')->realpath($source->getFileUri())) !== FALSE) {
\Drupal::logger('file')->notice('File %file (%realpath) could not be copied because the destination %destination is invalid. This is often caused by improper use of file_copy() or a missing stream wrapper.', ['%file' => $source->getFileUri(), '%realpath' => $realpath, '%destination' => $destination]);
}
else {
@@ -215,7 +225,7 @@ function file_copy(FileInterface $source, $destination = NULL, $replace = FILE_E
*/
function file_move(FileInterface $source, $destination = NULL, $replace = FILE_EXISTS_RENAME) {
if (!file_valid_uri($destination)) {
if (($realpath = drupal_realpath($source->getFileUri())) !== FALSE) {
if (($realpath = \Drupal::service('file_system')->realpath($source->getFileUri())) !== FALSE) {
\Drupal::logger('file')->notice('File %file (%realpath) could not be moved because the destination %destination is invalid. This may be caused by improper use of file_move() or a missing stream wrapper.', ['%file' => $source->getFileUri(), '%realpath' => $realpath, '%destination' => $destination]);
}
else {
@@ -396,7 +406,7 @@ function file_validate_is_image(FileInterface $file) {
$image = $image_factory->get($file->getFileUri());
if (!$image->isValid()) {
$supported_extensions = $image_factory->getSupportedExtensions();
$errors[] = t('Image type not supported. Allowed types: %types', ['%types' => implode(' ', $supported_extensions)]);
$errors[] = t('The image file is invalid or the image type is not allowed. Allowed types: %types', ['%types' => implode(', ', $supported_extensions)]);
}
return $errors;
@@ -434,22 +444,40 @@ function file_validate_image_resolution(FileInterface $file, $maximum_dimensions
// Check first that the file is an image.
$image_factory = \Drupal::service('image.factory');
$image = $image_factory->get($file->getFileUri());
if ($image->isValid()) {
$scaling = FALSE;
if ($maximum_dimensions) {
// Check that it is smaller than the given dimensions.
list($width, $height) = explode('x', $maximum_dimensions);
if ($image->getWidth() > $width || $image->getHeight() > $height) {
// Try to resize the image to fit the dimensions.
if ($image->scale($width, $height)) {
$scaling = TRUE;
$image->save();
if (!empty($width) && !empty($height)) {
$message = t('The image was resized to fit within the maximum allowed dimensions of %dimensions pixels.', ['%dimensions' => $maximum_dimensions]);
$message = t('The image was resized to fit within the maximum allowed dimensions of %dimensions pixels. The new dimensions of the resized image are %new_widthx%new_height pixels.',
[
'%dimensions' => $maximum_dimensions,
'%new_width' => $image->getWidth(),
'%new_height' => $image->getHeight(),
]);
}
elseif (empty($width)) {
$message = t('The image was resized to fit within the maximum allowed height of %height pixels.', ['%height' => $height]);
$message = t('The image was resized to fit within the maximum allowed height of %height pixels. The new dimensions of the resized image are %new_widthx%new_height pixels.',
[
'%height' => $height,
'%new_width' => $image->getWidth(),
'%new_height' => $image->getHeight(),
]);
}
elseif (empty($height)) {
$message = t('The image was resized to fit within the maximum allowed width of %width pixels.', ['%width' => $width]);
$message = t('The image was resized to fit within the maximum allowed width of %width pixels. The new dimensions of the resized image are %new_widthx%new_height pixels.',
[
'%width' => $width,
'%new_width' => $image->getWidth(),
'%new_height' => $image->getHeight(),
]);
}
drupal_set_message($message);
}
@@ -463,7 +491,22 @@ function file_validate_image_resolution(FileInterface $file, $maximum_dimensions
// Check that it is larger than the given dimensions.
list($width, $height) = explode('x', $minimum_dimensions);
if ($image->getWidth() < $width || $image->getHeight() < $height) {
$errors[] = t('The image is too small; the minimum dimensions are %dimensions pixels.', ['%dimensions' => $minimum_dimensions]);
if ($scaling) {
$errors[] = t('The resized image is too small. The minimum dimensions are %dimensions pixels and after resizing, the image size will be %widthx%height pixels.',
[
'%dimensions' => $minimum_dimensions,
'%width' => $image->getWidth(),
'%height' => $image->getHeight(),
]);
}
else {
$errors[] = t('The image is too small. The minimum dimensions are %dimensions pixels and the image size is %widthx%height pixels.',
[
'%dimensions' => $minimum_dimensions,
'%width' => $image->getWidth(),
'%height' => $image->getHeight(),
]);
}
}
}
}
@@ -571,6 +614,12 @@ function file_theme() {
'file_managed_file' => [
'render element' => 'element',
],
'file_audio' => [
'variables' => ['files' => [], 'attributes' => NULL],
],
'file_video' => [
'variables' => ['files' => [], 'attributes' => NULL],
],
// From file.field.inc.
'file_widget_multiple' => [
@@ -673,6 +722,91 @@ function file_cron() {
}
}
/**
* Saves form file uploads.
*
* The files will be added to the {file_managed} table as temporary files.
* Temporary files are periodically cleaned. Use the 'file.usage' service to
* register the usage of the file which will automatically mark it as permanent.
*
* @param array $element
* The FAPI element whose values are being saved.
* @param \Drupal\Core\Form\FormStateInterface $form_state
* The current state of the form.
* @param null|int $delta
* (optional) The delta of the file to return the file entity.
* Defaults to NULL.
* @param int $replace
* (optional) The replace behavior when the destination file already exists.
* Possible values include:
* - FILE_EXISTS_REPLACE: Replace the existing file.
* - FILE_EXISTS_RENAME: (default) Append _{incrementing number} until the
* filename is unique.
* - FILE_EXISTS_ERROR: Do nothing and return FALSE.
*
* @return array|\Drupal\file\FileInterface|null|false
* An array of file entities or a single file entity if $delta != NULL. Each
* array element contains the file entity if the upload succeeded or FALSE if
* there was an error. Function returns NULL if no file was uploaded.
*
* @deprecated in Drupal 8.4.x, will be removed before Drupal 9.0.0.
* For backwards compatibility use core file upload widgets in forms.
*
* @internal
* This function wraps file_save_upload() to allow correct error handling in
* forms.
*
* @todo Revisit after https://www.drupal.org/node/2244513.
*/
function _file_save_upload_from_form(array $element, FormStateInterface $form_state, $delta = NULL, $replace = FILE_EXISTS_RENAME) {
// Get all errors set before calling this method. This will also clear them
// from $_SESSION.
$errors_before = drupal_get_messages('error');
$upload_location = isset($element['#upload_location']) ? $element['#upload_location'] : FALSE;
$upload_name = implode('_', $element['#parents']);
$upload_validators = isset($element['#upload_validators']) ? $element['#upload_validators'] : [];
$result = file_save_upload($upload_name, $upload_validators, $upload_location, $delta, $replace);
// Get new errors that are generated while trying to save the upload. This
// will also clear them from $_SESSION.
$errors_new = drupal_get_messages('error');
if (!empty($errors_new['error'])) {
$errors_new = $errors_new['error'];
if (count($errors_new) > 1) {
// Render multiple errors into a single message.
// This is needed because only one error per element is supported.
$render_array = [
'error' => [
'#markup' => t('One or more files could not be uploaded.'),
],
'item_list' => [
'#theme' => 'item_list',
'#items' => $errors_new,
],
];
$error_message = \Drupal::service('renderer')->renderPlain($render_array);
}
else {
$error_message = reset($errors_new);
}
$form_state->setError($element, $error_message);
}
// Ensure that errors set prior to calling this method are still shown to the
// user.
if (!empty($errors_before['error'])) {
foreach ($errors_before['error'] as $error) {
drupal_set_message($error, 'error');
}
}
return $result;
}
/**
* Saves file uploads to a new location.
*
@@ -680,6 +814,10 @@ function file_cron() {
* Temporary files are periodically cleaned. Use the 'file.usage' service to
* register the usage of the file which will automatically mark it as permanent.
*
* Note that this function does not support correct form error handling. The
* file upload widgets in core do support this. It is advised to use these in
* any custom form, instead of calling this function.
*
* @param string $form_field_name
* A string that is the associative array key of the upload form element in
* the form array.
@@ -710,6 +848,10 @@ function file_cron() {
* An array of file entities or a single file entity if $delta != NULL. Each
* array element contains the file entity if the upload succeeded or FALSE if
* there was an error. Function returns NULL if no file was uploaded.
*
* @see _file_save_upload_from_form()
*
* @todo: move this logic to a service in https://www.drupal.org/node/2244513.
*/
function file_save_upload($form_field_name, $validators = [], $destination = FALSE, $delta = NULL, $replace = FILE_EXISTS_RENAME) {
$user = \Drupal::currentUser();
@@ -1200,9 +1342,8 @@ function file_managed_file_save_upload($element, FormStateInterface $form_state)
$files_uploaded = $element['#multiple'] && count(array_filter($file_upload)) > 0;
$files_uploaded |= !$element['#multiple'] && !empty($file_upload);
if ($files_uploaded) {
if (!$files = file_save_upload($upload_name, $element['#upload_validators'], $destination)) {
if (!$files = _file_save_upload_from_form($element, $form_state)) {
\Drupal::logger('file')->notice('The file upload failed. %upload', ['%upload' => $upload_name]);
$form_state->setError($element, t('Files in the @name field were unable to be uploaded.', ['@name' => $element['#title']]));
return [];
}
@@ -2,8 +2,10 @@
# migration as an optional dependency.
id: d6_file
label: Public files
audit: true
migration_tags:
- Drupal 6
- Content
source:
plugin: d6_file
constants:
@@ -2,11 +2,16 @@ id: d6_upload
label: File uploads
migration_tags:
- Drupal 6
- Content
source:
plugin: d6_upload
process:
nid: nid
vid: vid
langcode:
plugin: user_langcode
source: language
fallback_to_site_default: true
type: type
upload:
plugin: sub_process
@@ -2,6 +2,7 @@ id: d6_upload_entity_display
label: Upload display configuration
migration_tags:
- Drupal 6
- Configuration
source:
plugin: d6_upload_instance
constants:
@@ -2,6 +2,7 @@ id: d6_upload_entity_form_display
label: Upload form display configuration
migration_tags:
- Drupal 6
- Configuration
source:
plugin: d6_upload_instance
constants:
@@ -2,6 +2,7 @@ id: d6_upload_field
label: Upload field configuration
migration_tags:
- Drupal 6
- Configuration
source:
# We do an empty source and a proper destination to have an idmap for
# migration_dependencies.
@@ -2,6 +2,7 @@ id: d6_upload_field_instance
label: Upload field instance configuration
migration_tags:
- Drupal 6
- Configuration
source:
plugin: d6_upload_instance
constants:
@@ -2,8 +2,10 @@
# migration as an optional dependency.
id: d7_file
label: Public files
audit: true
migration_tags:
- Drupal 7
- Content
source:
plugin: d7_file
scheme: public
@@ -1,7 +1,9 @@
id: d7_file_private
label: Private files
audit: true
migration_tags:
- Drupal 7
- Content
source:
plugin: d7_file
scheme: private
@@ -3,6 +3,7 @@ label: File configuration
migration_tags:
- Drupal 6
- Drupal 7
- Configuration
source:
plugin: variable
variables:
+47
View File
@@ -0,0 +1,47 @@
<?php
namespace Drupal\file;
use Drupal\Core\TypedData\TypedData;
/**
* Computed file URL property class.
*/
class ComputedFileUrl extends TypedData {
/**
* Computed root-relative file URL.
*
* @var string
*/
protected $url = NULL;
/**
* {@inheritdoc}
*/
public function getValue() {
if ($this->url !== NULL) {
return $this->url;
}
assert($this->getParent()->getEntity() instanceof FileInterface);
$uri = $this->getParent()->getEntity()->getFileUri();
$this->url = file_url_transform_relative(file_create_url($uri));
return $this->url;
}
/**
* {@inheritdoc}
*/
public function setValue($value, $notify = TRUE) {
$this->url = $value;
// Notify the parent of any changes.
if ($notify && isset($this->parent)) {
$this->parent->onChange($this->name);
}
}
}
+1 -1
View File
@@ -243,7 +243,7 @@ class File extends ContentEntityBase implements FileInterface {
->setLabel(t('Filename'))
->setDescription(t('Name of the file with no path components.'));
$fields['uri'] = BaseFieldDefinition::create('uri')
$fields['uri'] = BaseFieldDefinition::create('file_uri')
->setLabel(t('URI'))
->setDescription(t('The URI to access the file (either local or remote).'))
->setSetting('max_length', 255)
@@ -22,8 +22,12 @@ class FileAccessControlHandler extends EntityAccessControlHandler {
/** @var \Drupal\file\FileInterface $entity */
if ($operation == 'download' || $operation == 'view') {
if (\Drupal::service('file_system')->uriScheme($entity->getFileUri()) === 'public') {
// Always allow access to file in public file system.
return AccessResult::allowed();
if ($operation === 'download') {
return AccessResult::allowed();
}
else {
return AccessResult::allowedIfHasPermission($account, 'access content');
}
}
elseif ($references = $this->getFileReferences($entity)) {
foreach ($references as $field_name => $entity_map) {
@@ -0,0 +1,52 @@
<?php
namespace Drupal\file\Plugin\Field\FieldFormatter;
use Drupal\Core\Form\FormStateInterface;
/**
* Base class for file formatters that have to deal with file descriptions.
*/
abstract class DescriptionAwareFileFormatterBase extends FileFormatterBase {
/**
* {@inheritdoc}
*/
public static function defaultSettings() {
$settings = parent::defaultSettings();
$settings['use_description_as_link_text'] = TRUE;
return $settings;
}
/**
* {@inheritdoc}
*/
public function settingsForm(array $form, FormStateInterface $form_state) {
$form = parent::settingsForm($form, $form_state);
$form['use_description_as_link_text'] = [
'#title' => $this->t('Use description as link text'),
'#description' => $this->t('Replace the file name by its description when available'),
'#type' => 'checkbox',
'#default_value' => $this->getSetting('use_description_as_link_text'),
];
return $form;
}
/**
* {@inheritdoc}
*/
public function settingsSummary() {
$summary = parent::settingsSummary();
if ($this->getSetting('use_description_as_link_text')) {
$summary[] = $this->t('Use description as link text');
}
return $summary;
}
}
@@ -0,0 +1,26 @@
<?php
namespace Drupal\file\Plugin\Field\FieldFormatter;
/**
* Plugin implementation of the 'file_audio' formatter.
*
* @FieldFormatter(
* id = "file_audio",
* label = @Translation("Audio"),
* description = @Translation("Display the file using an HTML5 audio tag."),
* field_types = {
* "file"
* }
* )
*/
class FileAudioFormatter extends FileMediaFormatterBase {
/**
* {@inheritdoc}
*/
public static function getMediaType() {
return 'audio';
}
}
@@ -0,0 +1,220 @@
<?php
namespace Drupal\file\Plugin\Field\FieldFormatter;
use Drupal\Core\Cache\Cache;
use Drupal\Core\Field\EntityReferenceFieldItemListInterface;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Template\Attribute;
/**
* Base class for media file formatter.
*/
abstract class FileMediaFormatterBase extends FileFormatterBase implements FileMediaFormatterInterface {
/**
* Gets the HTML tag for the formatter.
*
* @return string
* The HTML tag of this formatter.
*/
protected function getHtmlTag() {
return static::getMediaType();
}
/**
* {@inheritdoc}
*/
public static function defaultSettings() {
return [
'controls' => TRUE,
'autoplay' => FALSE,
'loop' => FALSE,
'multiple_file_display_type' => 'tags',
] + parent::defaultSettings();
}
/**
* {@inheritdoc}
*/
public function settingsForm(array $form, FormStateInterface $form_state) {
return [
'controls' => [
'#title' => $this->t('Show playback controls'),
'#type' => 'checkbox',
'#default_value' => $this->getSetting('controls'),
],
'autoplay' => [
'#title' => $this->t('Autoplay'),
'#type' => 'checkbox',
'#default_value' => $this->getSetting('autoplay'),
],
'loop' => [
'#title' => $this->t('Loop'),
'#type' => 'checkbox',
'#default_value' => $this->getSetting('loop'),
],
'multiple_file_display_type' => [
'#title' => $this->t('Display of multiple files'),
'#type' => 'radios',
'#options' => [
'tags' => $this->t('Use multiple @tag tags, each with a single source.', ['@tag' => '<' . $this->getHtmlTag() . '>']),
'sources' => $this->t('Use multiple sources within a single @tag tag.', ['@tag' => '<' . $this->getHtmlTag() . '>']),
],
'#default_value' => $this->getSetting('multiple_file_display_type'),
],
];
}
/**
* {@inheritdoc}
*/
public static function isApplicable(FieldDefinitionInterface $field_definition) {
if (!parent::isApplicable($field_definition)) {
return FALSE;
}
/** @var \Symfony\Component\HttpFoundation\File\MimeType\MimeTypeGuesserInterface $extension_mime_type_guesser */
$extension_mime_type_guesser = \Drupal::service('file.mime_type.guesser.extension');
$extension_list = array_filter(preg_split('/\s+/', $field_definition->getSetting('file_extensions')));
foreach ($extension_list as $extension) {
$mime_type = $extension_mime_type_guesser->guess('fakedFile.' . $extension);
if (static::mimeTypeApplies($mime_type)) {
return TRUE;
}
}
return FALSE;
}
/**
* {@inheritdoc}
*/
public function settingsSummary() {
$summary = [];
$summary[] = $this->t('Playback controls: %controls', ['%controls' => $this->getSetting('controls') ? $this->t('visible') : $this->t('hidden')]);
$summary[] = $this->t('Autoplay: %autoplay', ['%autoplay' => $this->getSetting('autoplay') ? $this->t('yes') : $this->t('no')]);
$summary[] = $this->t('Loop: %loop', ['%loop' => $this->getSetting('loop') ? $this->t('yes') : $this->t('no')]);
switch ($this->getSetting('multiple_file_display_type')) {
case 'tags':
$summary[] = $this->t('Multiple file display: Multiple HTML tags');
break;
case 'sources':
$summary[] = $this->t('Multiple file display: One HTML tag with multiple sources');
break;
}
return $summary;
}
/**
* {@inheritdoc}
*/
public function viewElements(FieldItemListInterface $items, $langcode) {
$elements = [];
$source_files = $this->getSourceFiles($items, $langcode);
if (empty($source_files)) {
return $elements;
}
$attributes = $this->prepareAttributes();
foreach ($source_files as $delta => $files) {
$elements[$delta] = [
'#theme' => $this->getPluginId(),
'#attributes' => $attributes,
'#files' => $files,
'#cache' => ['tags' => []],
];
$cache_tags = [];
foreach ($files as $file) {
$cache_tags = Cache::mergeTags($cache_tags, $file['file']->getCacheTags());
}
$elements[$delta]['#cache']['tags'] = $cache_tags;
}
return $elements;
}
/**
* Prepare the attributes according to the settings.
*
* @param string[] $additional_attributes
* Additional attributes to be applied to the HTML element. Attribute names
* will be used as key and value in the HTML element.
*
* @return \Drupal\Core\Template\Attribute
* Container with all the attributes for the HTML tag.
*/
protected function prepareAttributes(array $additional_attributes = []) {
$attributes = new Attribute();
foreach (['controls', 'autoplay', 'loop'] + $additional_attributes as $attribute) {
if ($this->getSetting($attribute)) {
$attributes->setAttribute($attribute, $attribute);
}
}
return $attributes;
}
/**
* Check if given MIME type applies to the media type of the formatter.
*
* @param string $mime_type
* The complete MIME type.
*
* @return bool
* TRUE if the MIME type applies, FALSE otherwise.
*/
protected static function mimeTypeApplies($mime_type) {
list($type) = explode('/', $mime_type, 2);
return $type === static::getMediaType();
}
/**
* Gets source files with attributes.
*
* @param \Drupal\Core\Field\EntityReferenceFieldItemListInterface $items
* The item list.
* @param string $langcode
* The language code of the referenced entities to display.
*
* @return array
* Numerically indexed array, which again contains an associative array with
* the following key/values:
* - file => \Drupal\file\Entity\File
* - source_attributes => \Drupal\Core\Template\Attribute
*/
protected function getSourceFiles(EntityReferenceFieldItemListInterface $items, $langcode) {
$source_files = [];
// Because we can have the files grouped in a single media tag, we do a
// grouping in case the multiple file behavior is not 'tags'.
/** @var \Drupal\file\Entity\File $file */
foreach ($this->getEntitiesToView($items, $langcode) as $file) {
if (static::mimeTypeApplies($file->getMimeType())) {
$source_attributes = new Attribute();
$source_attributes
->setAttribute('src', file_url_transform_relative(file_create_url($file->getFileUri())))
->setAttribute('type', $file->getMimeType());
if ($this->getSetting('multiple_file_display_type') === 'tags') {
$source_files[] = [
[
'file' => $file,
'source_attributes' => $source_attributes,
],
];
}
else {
$source_files[0][] = [
'file' => $file,
'source_attributes' => $source_attributes,
];
}
}
}
return $source_files;
}
}
@@ -0,0 +1,26 @@
<?php
namespace Drupal\file\Plugin\Field\FieldFormatter;
/**
* Defines getter methods for FileMediaFormatterBase.
*
* This interface is used on the FileMediaFormatterBase class to ensure that
* each file media formatter will be based on a media type.
*
* Abstract classes are not able to implement abstract static methods,
* this interface will work around that.
*
* @see \Drupal\file\Plugin\Field\FieldFormatter\FileMediaFormatterBase
*/
interface FileMediaFormatterInterface {
/**
* Gets the applicable media type for a formatter.
*
* @return string
* The media type of this formatter.
*/
public static function getMediaType();
}
@@ -13,7 +13,8 @@ use Drupal\Core\Form\FormStateInterface;
* id = "file_uri",
* label = @Translation("File URI"),
* field_types = {
* "uri"
* "uri",
* "file_uri",
* }
* )
*/
@@ -0,0 +1,94 @@
<?php
namespace Drupal\file\Plugin\Field\FieldFormatter;
use Drupal\Core\Form\FormStateInterface;
/**
* Plugin implementation of the 'file_video' formatter.
*
* @FieldFormatter(
* id = "file_video",
* label = @Translation("Video"),
* description = @Translation("Display the file using an HTML5 video tag."),
* field_types = {
* "file"
* }
* )
*/
class FileVideoFormatter extends FileMediaFormatterBase {
/**
* {@inheritdoc}
*/
public static function getMediaType() {
return 'video';
}
/**
* {@inheritdoc}
*/
public static function defaultSettings() {
return [
'muted' => FALSE,
'width' => 640,
'height' => 480,
] + parent::defaultSettings();
}
/**
* {@inheritdoc}
*/
public function settingsForm(array $form, FormStateInterface $form_state) {
return parent::settingsForm($form, $form_state) + [
'muted' => [
'#title' => $this->t('Muted'),
'#type' => 'checkbox',
'#default_value' => $this->getSetting('muted'),
],
'width' => [
'#type' => 'number',
'#title' => $this->t('Width'),
'#default_value' => $this->getSetting('width'),
'#size' => 5,
'#maxlength' => 5,
'#field_suffix' => $this->t('pixels'),
'#min' => 0,
'#required' => TRUE,
],
'height' => [
'#type' => 'number',
'#title' => $this->t('Height'),
'#default_value' => $this->getSetting('height'),
'#size' => 5,
'#maxlength' => 5,
'#field_suffix' => $this->t('pixels'),
'#min' => 0,
'#required' => TRUE,
],
];
}
/**
* {@inheritdoc}
*/
public function settingsSummary() {
$summary = parent::settingsSummary();
$summary[] = $this->t('Muted: %muted', ['%muted' => $this->getSetting('muted') ? $this->t('yes') : $this->t('no')]);
$summary[] = $this->t('Size: %width x %height pixels', [
'%width' => $this->getSetting('width'),
'%height' => $this->getSetting('height'),
]);
return $summary;
}
/**
* {@inheritdoc}
*/
protected function prepareAttributes(array $additional_attributes = []) {
return parent::prepareAttributes(['muted'])
->setAttribute('width', $this->getSetting('width'))
->setAttribute('height', $this->getSetting('height'));
}
}
@@ -15,7 +15,7 @@ use Drupal\Core\Field\FieldItemListInterface;
* }
* )
*/
class GenericFileFormatter extends FileFormatterBase {
class GenericFileFormatter extends DescriptionAwareFileFormatterBase {
/**
* {@inheritdoc}
@@ -28,7 +28,7 @@ class GenericFileFormatter extends FileFormatterBase {
$elements[$delta] = [
'#theme' => 'file_link',
'#file' => $file,
'#description' => $item->description,
'#description' => $this->getSetting('use_description_as_link_text') ? $item->description : NULL,
'#cache' => [
'tags' => $file->getCacheTags(),
],
@@ -15,7 +15,7 @@ use Drupal\Core\Field\FieldItemListInterface;
* }
* )
*/
class TableFormatter extends FileFormatterBase {
class TableFormatter extends DescriptionAwareFileFormatterBase {
/**
* {@inheritdoc}
@@ -27,11 +27,13 @@ class TableFormatter extends FileFormatterBase {
$header = [t('Attachment'), t('Size')];
$rows = [];
foreach ($files as $delta => $file) {
$item = $file->_referringItem;
$rows[] = [
[
'data' => [
'#theme' => 'file_link',
'#file' => $file,
'#description' => $this->getSetting('use_description_as_link_text') ? $item->description : NULL,
'#cache' => [
'tags' => $file->getCacheTags(),
],
@@ -0,0 +1,39 @@
<?php
namespace Drupal\file\Plugin\Field\FieldType;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\Core\Field\Plugin\Field\FieldType\UriItem;
use Drupal\Core\TypedData\DataDefinition;
use Drupal\file\ComputedFileUrl;
/**
* File-specific plugin implementation of a URI item to provide a full URL.
*
* @FieldType(
* id = "file_uri",
* label = @Translation("File URI"),
* description = @Translation("An entity field containing a file URI, and a computed root-relative file URL."),
* no_ui = TRUE,
* default_formatter = "file_uri",
* default_widget = "uri",
* )
*/
class FileUriItem extends UriItem {
/**
* {@inheritdoc}
*/
public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition) {
$properties = parent::propertyDefinitions($field_definition);
$properties['url'] = DataDefinition::create('string')
->setLabel(t('Root-relative file URL'))
->setComputed(TRUE)
->setInternal(FALSE)
->setClass(ComputedFileUrl::class);
return $properties;
}
}
@@ -11,7 +11,9 @@ use Drupal\migrate_drupal\Plugin\migrate\cckfield\CckFieldPluginBase;
/**
* @MigrateCckField(
* id = "filefield",
* core = {6}
* core = {6},
* source_module = "filefield",
* destination_module = "file"
* )
*
* @deprecated in Drupal 8.3.x, to be removed before Drupal 9.0.x. Use
@@ -11,7 +11,9 @@ use Drupal\migrate_drupal\Plugin\migrate\cckfield\CckFieldPluginBase;
/**
* @MigrateCckField(
* id = "file",
* core = {7}
* core = {7},
* source_module = "file",
* destination_module = "file"
* )
*
* @deprecated in Drupal 8.3.x, to be removed before Drupal 9.0.x. Use
@@ -2,40 +2,16 @@
namespace Drupal\file\Plugin\migrate\cckfield\d7;
@trigger_error('ImageField is deprecated in Drupal 8.3.x and will be removed before Drupal 9.0.x. Use \Drupal\file\Plugin\migrate\field\d7\ImageField instead.', E_USER_DEPRECATED);
@trigger_error('ImageField is deprecated in Drupal 8.3.x and will be removed before Drupal 9.0.x. Use \Drupal\image\Plugin\migrate\field\d7\ImageField instead. See https://www.drupal.org/node/2936061.', E_USER_DEPRECATED);
use Drupal\migrate\Plugin\MigrationInterface;
use Drupal\migrate_drupal\Plugin\migrate\cckfield\CckFieldPluginBase;
use Drupal\image\Plugin\migrate\cckfield\d7\ImageField as LegacyImageField;
/**
* @MigrateCckField(
* id = "image",
* core = {7}
* )
* CCK plugin for image fields.
*
* @deprecated in Drupal 8.3.x, to be removed before Drupal 9.0.x. Use
* \Drupal\file\Plugin\migrate\field\d7\ImageField instead.
* \Drupal\image\Plugin\migrate\field\d7\ImageField instead.
*
* @see https://www.drupal.org/node/2751897
* @see https://www.drupal.org/node/2936061
*/
class ImageField extends CckFieldPluginBase {
/**
* {@inheritdoc}
*/
public function processCckFieldValues(MigrationInterface $migration, $field_name, $data) {
$process = [
'plugin' => 'sub_process',
'source' => $field_name,
'process' => [
'target_id' => 'fid',
'alt' => 'alt',
'title' => 'title',
'width' => 'width',
'height' => 'height',
],
];
$migration->mergeProcessOfProperty($field_name, $process);
}
}
class ImageField extends LegacyImageField {}
@@ -9,7 +9,9 @@ use Drupal\migrate_drupal\Plugin\migrate\field\FieldPluginBase;
/**
* @MigrateField(
* id = "filefield",
* core = {6}
* core = {6},
* source_module = "filefield",
* destination_module = "file"
* )
*/
class FileField extends FieldPluginBase {
@@ -0,0 +1,17 @@
<?php
namespace Drupal\file\Plugin\migrate\field\d6;
@trigger_error('ImageField is deprecated in Drupal 8.5.x and will be removed before Drupal 9.0.x. Use \Drupal\image\Plugin\migrate\field\d6\ImageField instead. See https://www.drupal.org/node/2936061.', E_USER_DEPRECATED);
use Drupal\image\Plugin\migrate\field\d6\ImageField as NonLegacyImageField;
/**
* Field plugin for image fields.
*
* @deprecated in Drupal 8.5.x, to be removed before Drupal 9.0.x. Use
* \Drupal\image\Plugin\migrate\field\d6\ImageField instead.
*
* @see https://www.drupal.org/node/2936061
*/
class ImageField extends NonLegacyImageField {}
@@ -8,7 +8,9 @@ use Drupal\migrate\Plugin\MigrationInterface;
/**
* @MigrateField(
* id = "file",
* core = {7}
* core = {7},
* source_module = "file",
* destination_module = "file"
* )
*/
class FileField extends D6FileField {
@@ -2,33 +2,16 @@
namespace Drupal\file\Plugin\migrate\field\d7;
use Drupal\migrate\Plugin\MigrationInterface;
use Drupal\migrate_drupal\Plugin\migrate\field\FieldPluginBase;
@trigger_error('ImageField is deprecated in Drupal 8.5.x and will be removed before Drupal 9.0.x. Use \Drupal\image\Plugin\migrate\field\d7\ImageField instead. See https://www.drupal.org/node/2936061.', E_USER_DEPRECATED);
use Drupal\image\Plugin\migrate\field\d7\ImageField as NonLegacyImageField;
/**
* @MigrateField(
* id = "image",
* core = {7}
* )
* Field plugin for image fields.
*
* @deprecated in Drupal 8.5.x, to be removed before Drupal 9.0.x. Use
* \Drupal\image\Plugin\migrate\field\d7\ImageField instead.
*
* @see https://www.drupal.org/node/2936061
*/
class ImageField extends FieldPluginBase {
/**
* {@inheritdoc}
*/
public function processFieldValues(MigrationInterface $migration, $field_name, $data) {
$process = [
'plugin' => 'sub_process',
'source' => $field_name,
'process' => [
'target_id' => 'fid',
'alt' => 'alt',
'title' => 'title',
'width' => 'width',
'height' => 'height',
],
];
$migration->mergeProcessOfProperty($field_name, $process);
}
}
class ImageField extends NonLegacyImageField {}
@@ -29,6 +29,7 @@ class Upload extends DrupalSqlBase {
->fields('u', ['nid', 'vid']);
$query->innerJoin('node', 'n', static::JOIN);
$query->addField('n', 'type');
$query->addField('n', 'language');
return $query;
}
@@ -54,6 +55,7 @@ class Upload extends DrupalSqlBase {
'nid' => $this->t('The node Id.'),
'vid' => $this->t('The version Id.'),
'type' => $this->t('The node type'),
'language' => $this->t('The node language.'),
'description' => $this->t('The file description.'),
'list' => $this->t('Whether the list should be visible on the node page.'),
'weight' => $this->t('The file weight.'),
@@ -4,6 +4,7 @@ namespace Drupal\file\Tests;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\file\Entity\File;
use Drupal\node\Entity\Node;
/**
* Tests the display of file fields in node and views.
@@ -96,7 +97,7 @@ class FileFieldDisplayTest extends FileFieldTestBase {
// Test that fields appear as expected after during the preview.
// Add a second file.
$name = 'files[' . $field_name . '_1][]';
$edit[$name] = drupal_realpath($test_file->getFileUri());
$edit[$name] = \Drupal::service('file_system')->realpath($test_file->getFileUri());
// Uncheck the display checkboxes and go to the preview.
$edit[$field_name . '[0][display]'] = FALSE;
@@ -165,7 +166,7 @@ class FileFieldDisplayTest extends FileFieldTestBase {
$title = $this->randomString();
$edit = [
'title[0][value]' => $title,
'files[field_' . $field_name . '_0]' => drupal_realpath($file->uri),
'files[field_' . $field_name . '_0]' => \Drupal::service('file_system')->realpath($file->uri),
];
$this->drupalPostForm('node/add/' . $type_name, $edit, t('Save'));
$node = $this->drupalGetNodeByTitle($title);
@@ -173,4 +174,49 @@ class FileFieldDisplayTest extends FileFieldTestBase {
$this->assertText(t('The description may be used as the label of the link to the file.'));
}
/**
* Tests description display of File Field.
*/
public function testDescriptionDefaultFileFieldDisplay() {
$field_name = strtolower($this->randomMachineName());
$type_name = 'article';
$field_storage_settings = [
'display_field' => '1',
'display_default' => '1',
'cardinality' => FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED,
];
$field_settings = [
'description_field' => '1',
];
$widget_settings = [];
$this->createFileField($field_name, 'node', $type_name, $field_storage_settings, $field_settings, $widget_settings);
$test_file = $this->getTestFile('text');
// Create a new node with the uploaded file.
$nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
// Add file description.
$description = 'This is the test file description';
$this->drupalPostForm("node/$nid/edit", [$field_name . '[0][description]' => $description], t('Save'));
// Load uncached node.
\Drupal::entityTypeManager()->getStorage('node')->resetCache([$nid]);
$node = Node::load($nid);
// Test default formatter.
$this->drupalGet('node/' . $nid);
$this->assertFieldByXPath('//a[@href="' . $node->{$field_name}->entity->url() . '"]', $description);
// Change formatter to "Table of files".
$display = \Drupal::entityTypeManager()->getStorage('entity_view_display')->load('node.' . $type_name . '.default');
$display->setComponent($field_name, [
'label' => 'hidden',
'type' => 'file_table',
])->save();
$this->drupalGet('node/' . $nid);
$this->assertFieldByXPath('//a[@href="' . $node->{$field_name}->entity->url() . '"]', $description);
}
}
@@ -251,7 +251,7 @@ abstract class FileFieldTestBase extends WebTestBase {
*/
public function replaceNodeFile($file, $field_name, $nid, $new_revision = TRUE) {
$edit = [
'files[' . $field_name . '_0]' => drupal_realpath($file->getFileUri()),
'files[' . $field_name . '_0]' => \Drupal::service('file_system')->realpath($file->getFileUri()),
'revision' => (string) (int) $new_revision,
];
@@ -160,7 +160,7 @@ class FileFieldWidgetTest extends FileFieldTestBase {
$this->drupalGet("node/add/$type_name");
foreach ([$field_name2, $field_name] as $each_field_name) {
for ($delta = 0; $delta < 3; $delta++) {
$edit = ['files[' . $each_field_name . '_' . $delta . '][]' => drupal_realpath($test_file->getFileUri())];
$edit = ['files[' . $each_field_name . '_' . $delta . '][]' => \Drupal::service('file_system')->realpath($test_file->getFileUri())];
// If the Upload button doesn't exist, drupalPostForm() will automatically
// fail with an assertion message.
$this->drupalPostForm(NULL, $edit, t('Upload'));
@@ -373,7 +373,7 @@ class FileFieldWidgetTest extends FileFieldTestBase {
// Add a comment with a file.
$text_file = $this->getTestFile('text');
$edit = [
'files[field_' . $name . '_' . 0 . ']' => drupal_realpath($text_file->getFileUri()),
'files[field_' . $name . '_' . 0 . ']' => \Drupal::service('file_system')->realpath($text_file->getFileUri()),
'comment_body[0][value]' => $comment_body = $this->randomMachineName(),
];
$this->drupalPostForm('node/' . $node->id(), $edit, t('Save'));
@@ -429,7 +429,7 @@ class FileFieldWidgetTest extends FileFieldTestBase {
$name = 'files[' . $field_name . '_0]';
// Upload file with incorrect extension, check for validation error.
$edit[$name] = drupal_realpath($test_file_image->getFileUri());
$edit[$name] = \Drupal::service('file_system')->realpath($test_file_image->getFileUri());
switch ($type) {
case 'nojs':
$this->drupalPostForm(NULL, $edit, t('Upload'));
@@ -443,7 +443,7 @@ class FileFieldWidgetTest extends FileFieldTestBase {
$this->assertRaw($error_message, t('Validation error when file with wrong extension uploaded (JSMode=%type).', ['%type' => $type]));
// Upload file with correct extension, check that error message is removed.
$edit[$name] = drupal_realpath($test_file_text->getFileUri());
$edit[$name] = \Drupal::service('file_system')->realpath($test_file_text->getFileUri());
switch ($type) {
case 'nojs':
$this->drupalPostForm(NULL, $edit, t('Upload'));
@@ -96,7 +96,7 @@ class FileListingTest extends FileFieldTestBase {
$file = $this->getTestFile('image');
$edit = [
'files[file_0]' => drupal_realpath($file->getFileUri()),
'files[file_0]' => \Drupal::service('file_system')->realpath($file->getFileUri()),
];
$this->drupalPostForm(NULL, $edit, t('Save'));
$node = Node::load($node->id());
@@ -36,7 +36,7 @@ class FileManagedFileElementTest extends FileFieldTestBase {
// was not saved.
$last_fid_prior = $this->getLastFileId();
$edit = [
$file_field_name => drupal_realpath($test_file->getFileUri()),
$file_field_name => \Drupal::service('file_system')->realpath($test_file->getFileUri()),
'form_token' => 'invalid token',
];
$this->drupalPostForm($path, $edit, t('Save'));
@@ -46,7 +46,7 @@ class FileManagedFileElementTest extends FileFieldTestBase {
// Submit a new file, without using the Upload button.
$last_fid_prior = $this->getLastFileId();
$edit = [$file_field_name => drupal_realpath($test_file->getFileUri())];
$edit = [$file_field_name => \Drupal::service('file_system')->realpath($test_file->getFileUri())];
$this->drupalPostForm($path, $edit, t('Save'));
$last_fid = $this->getLastFileId();
$this->assertTrue($last_fid > $last_fid_prior, 'New file got saved.');
@@ -61,7 +61,7 @@ class FileManagedFileElementTest extends FileFieldTestBase {
// Upload, then Submit.
$last_fid_prior = $this->getLastFileId();
$this->drupalGet($path);
$edit = [$file_field_name => drupal_realpath($test_file->getFileUri())];
$edit = [$file_field_name => \Drupal::service('file_system')->realpath($test_file->getFileUri())];
if ($ajax) {
$this->drupalPostAjaxForm(NULL, $edit, $input_base_name . '_upload_button');
}
@@ -92,7 +92,7 @@ class FileManagedFileElementTest extends FileFieldTestBase {
// Upload, then Remove, then Submit.
$this->drupalGet($path);
$edit = [$file_field_name => drupal_realpath($test_file->getFileUri())];
$edit = [$file_field_name => \Drupal::service('file_system')->realpath($test_file->getFileUri())];
if ($ajax) {
$this->drupalPostAjaxForm(NULL, $edit, $input_base_name . '_upload_button');
}
@@ -120,7 +120,7 @@ class FileManagedFileElementTest extends FileFieldTestBase {
// The multiple file upload has additional conditions that need checking.
$path = 'file/test/1/1/1';
$edit = ['files[nested_file][]' => drupal_realpath($test_file->getFileUri())];
$edit = ['files[nested_file][]' => \Drupal::service('file_system')->realpath($test_file->getFileUri())];
$fid_list = [];
$this->drupalGet($path);
@@ -158,7 +158,7 @@ class FileManagedFileElementTest extends FileFieldTestBase {
$test_file = $this->getTestFile('text');
$file_field_name = 'files[nested_file][]';
$edit = [$file_field_name => drupal_realpath($test_file->getFileUri())];
$edit = [$file_field_name => \Drupal::service('file_system')->realpath($test_file->getFileUri())];
$this->drupalPostForm(NULL, $edit, t('Upload'));
$fid = $this->getLastFileId();
@@ -179,7 +179,7 @@ class FileManagedFileElementTest extends FileFieldTestBase {
$test_file = $this->getTestFile('text');
$file_field_name = 'files[nested_file][]';
$edit = [$file_field_name => drupal_realpath($test_file->getFileUri())];
$edit = [$file_field_name => \Drupal::service('file_system')->realpath($test_file->getFileUri())];
$this->drupalPostForm(NULL, $edit, t('Upload'));
$this->drupalPostForm(NULL, [], t('Save'));
@@ -91,7 +91,7 @@ class FileOnTranslatedEntityTest extends FileFieldTestBase {
// Edit the node to upload a file.
$edit = [];
$name = 'files[' . $this->fieldName . '_0]';
$edit[$name] = drupal_realpath($this->drupalGetTestFiles('text')[0]->uri);
$edit[$name] = \Drupal::service('file_system')->realpath($this->drupalGetTestFiles('text')[0]->uri);
$this->drupalPostForm('node/' . $default_language_node->id() . '/edit', $edit, t('Save'));
$first_fid = $this->getLastFileId();
@@ -102,7 +102,7 @@ class FileOnTranslatedEntityTest extends FileFieldTestBase {
$edit = [];
$edit['title[0][value]'] = 'Bill Murray';
$name = 'files[' . $this->fieldName . '_0]';
$edit[$name] = drupal_realpath($this->drupalGetTestFiles('text')[1]->uri);
$edit[$name] = \Drupal::service('file_system')->realpath($this->drupalGetTestFiles('text')[1]->uri);
$this->drupalPostForm(NULL, $edit, t('Save (this translation)'));
// This inspects the HTML after the post of the translation, the file
// should be displayed on the original node.
@@ -128,7 +128,7 @@ class FileOnTranslatedEntityTest extends FileFieldTestBase {
$edit = [];
$edit['title[0][value]'] = 'Scarlett Johansson';
$name = 'files[' . $this->fieldName . '_0]';
$edit[$name] = drupal_realpath($this->drupalGetTestFiles('text')[2]->uri);
$edit[$name] = \Drupal::service('file_system')->realpath($this->drupalGetTestFiles('text')[2]->uri);
$this->drupalPostForm(NULL, $edit, t('Save (this translation)'));
$third_fid = $this->getLastFileId();
@@ -156,7 +156,7 @@ class FileOnTranslatedEntityTest extends FileFieldTestBase {
$edit = [];
$edit['title[0][value]'] = 'David Bowie';
$name = 'files[' . $this->fieldName . '_0]';
$edit[$name] = drupal_realpath($this->drupalGetTestFiles('text')[3]->uri);
$edit[$name] = \Drupal::service('file_system')->realpath($this->drupalGetTestFiles('text')[3]->uri);
$this->drupalPostForm(NULL, $edit, t('Save (this translation)'));
$replaced_second_fid = $this->getLastFileId();
@@ -38,6 +38,8 @@ class FilePrivateTest extends FileFieldTestBase {
*/
public function testPrivateFile() {
$node_storage = $this->container->get('entity.manager')->getStorage('node');
/** @var \Drupal\Core\File\FileSystemInterface $file_system */
$file_system = \Drupal::service('file_system');
$type_name = 'article';
$field_name = strtolower($this->randomMachineName());
$this->createFileField($field_name, 'node', $type_name, ['uri_scheme' => 'private']);
@@ -128,7 +130,7 @@ class FilePrivateTest extends FileFieldTestBase {
);
$test_file = $this->getTestFile('text');
$this->drupalGet('node/add/' . $type_name);
$edit = ['files[' . $field_name . '_0]' => drupal_realpath($test_file->getFileUri())];
$edit = ['files[' . $field_name . '_0]' => $file_system->realpath($test_file->getFileUri())];
$this->drupalPostForm(NULL, $edit, t('Upload'));
/** @var \Drupal\file\FileStorageInterface $file_storage */
$file_storage = $this->container->get('entity.manager')->getStorage('file');
@@ -155,7 +157,7 @@ class FilePrivateTest extends FileFieldTestBase {
$this->drupalGet('node/add/' . $type_name);
$edit = [];
$edit['title[0][value]'] = $this->randomMachineName();
$edit['files[' . $field_name . '_0]'] = drupal_realpath($test_file->getFileUri());
$edit['files[' . $field_name . '_0]'] = $file_system->realpath($test_file->getFileUri());
$this->drupalPostForm(NULL, $edit, t('Save'));
$new_node = $this->drupalGetNodeByTitle($edit['title[0][value]']);
$file_id = $new_node->{$field_name}->target_id;
@@ -184,7 +186,7 @@ class FilePrivateTest extends FileFieldTestBase {
$this->drupalGet('node/add/' . $type_name);
$edit = [];
$edit['title[0][value]'] = $this->randomMachineName();
$edit['files[' . $field_name . '_0]'] = drupal_realpath($test_file->getFileUri());
$edit['files[' . $field_name . '_0]'] = $file_system->realpath($test_file->getFileUri());
$this->drupalPostForm(NULL, $edit, t('Save'));
$new_node = $this->drupalGetNodeByTitle($edit['title[0][value]']);
$file = File::load($new_node->{$field_name}->target_id);
@@ -209,7 +211,7 @@ class FilePrivateTest extends FileFieldTestBase {
$this->drupalGet('node/add/' . $type_name);
$edit = [];
$edit['title[0][value]'] = $this->randomMachineName();
$edit['files[' . $field_name . '_0]'] = drupal_realpath($test_file->getFileUri());
$edit['files[' . $field_name . '_0]'] = $file_system->realpath($test_file->getFileUri());
$this->drupalPostForm(NULL, $edit, t('Save'));
$new_node = $this->drupalGetNodeByTitle($edit['title[0][value]']);
$new_node->setPublished(FALSE);
@@ -80,7 +80,7 @@ class PrivateFileOnTranslatedEntityTest extends FileFieldTestBase {
// Edit the node to upload a file.
$edit = [];
$name = 'files[' . $this->fieldName . '_0]';
$edit[$name] = drupal_realpath($this->drupalGetTestFiles('text')[0]->uri);
$edit[$name] = \Drupal::service('file_system')->realpath($this->drupalGetTestFiles('text')[0]->uri);
$this->drupalPostForm('node/' . $default_language_node->id() . '/edit', $edit, t('Save'));
$last_fid_prior = $this->getLastFileId();
@@ -105,7 +105,7 @@ class PrivateFileOnTranslatedEntityTest extends FileFieldTestBase {
$edit = [];
$edit['title[0][value]'] = $this->randomMachineName();
$name = 'files[' . $this->fieldName . '_0]';
$edit[$name] = drupal_realpath($this->drupalGetTestFiles('text')[1]->uri);
$edit[$name] = \Drupal::service('file_system')->realpath($this->drupalGetTestFiles('text')[1]->uri);
$this->drupalPostForm(NULL, $edit, t('Save (this translation)'));
$last_fid = $this->getLastFileId();
@@ -0,0 +1,484 @@
<?php
namespace Drupal\file\Tests;
use Drupal\file\Entity\File;
/**
* Tests the _file_save_upload_from_form() function.
*
* @group file
*
* @see _file_save_upload_from_form()
*/
class SaveUploadFormTest extends FileManagedTestBase {
/**
* Modules to enable.
*
* @var array
*/
public static $modules = ['dblog'];
/**
* An image file path for uploading.
*
* @var \Drupal\file\FileInterface
*/
protected $image;
/**
* A PHP file path for upload security testing.
*/
protected $phpfile;
/**
* The largest file id when the test starts.
*/
protected $maxFidBefore;
/**
* Extension of the image filename.
*
* @var string
*/
protected $imageExtension;
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
$account = $this->drupalCreateUser(['access site reports']);
$this->drupalLogin($account);
$image_files = $this->drupalGetTestFiles('image');
$this->image = File::create((array) current($image_files));
list(, $this->imageExtension) = explode('.', $this->image->getFilename());
$this->assertTrue(is_file($this->image->getFileUri()), "The image file we're going to upload exists.");
$this->phpfile = current($this->drupalGetTestFiles('php'));
$this->assertTrue(is_file($this->phpfile->uri), 'The PHP file we are going to upload exists.');
$this->maxFidBefore = db_query('SELECT MAX(fid) AS fid FROM {file_managed}')->fetchField();
/** @var \Drupal\Core\File\FileSystemInterface $file_system */
$file_system = \Drupal::service('file_system');
// Upload with replace to guarantee there's something there.
$edit = [
'file_test_replace' => FILE_EXISTS_REPLACE,
'files[file_test_upload][]' => $file_system->realpath($this->image->getFileUri()),
];
$this->drupalPostForm('file-test/save_upload_from_form_test', $edit, t('Submit'));
$this->assertResponse(200, 'Received a 200 response for posted test file.');
$this->assertRaw(t('You WIN!'), 'Found the success message.');
// Check that the correct hooks were called then clean out the hook
// counters.
$this->assertFileHooksCalled(['validate', 'insert']);
file_test_reset();
}
/**
* Tests the _file_save_upload_from_form() function.
*/
public function testNormal() {
$max_fid_after = db_query('SELECT MAX(fid) AS fid FROM {file_managed}')->fetchField();
$this->assertTrue($max_fid_after > $this->maxFidBefore, 'A new file was created.');
$file1 = File::load($max_fid_after);
$this->assertTrue($file1, 'Loaded the file.');
// MIME type of the uploaded image may be either image/jpeg or image/png.
$this->assertEqual(substr($file1->getMimeType(), 0, 5), 'image', 'A MIME type was set.');
// Reset the hook counters to get rid of the 'load' we just called.
file_test_reset();
// Upload a second file.
$image2 = current($this->drupalGetTestFiles('image'));
/** @var \Drupal\Core\File\FileSystemInterface $file_system */
$file_system = \Drupal::service('file_system');
$edit = ['files[file_test_upload][]' => $file_system->realpath($image2->uri)];
$this->drupalPostForm('file-test/save_upload_from_form_test', $edit, t('Submit'));
$this->assertResponse(200, 'Received a 200 response for posted test file.');
$this->assertRaw(t('You WIN!'));
$max_fid_after = db_query('SELECT MAX(fid) AS fid FROM {file_managed}')->fetchField();
// Check that the correct hooks were called.
$this->assertFileHooksCalled(['validate', 'insert']);
$file2 = File::load($max_fid_after);
$this->assertTrue($file2, 'Loaded the file');
// MIME type of the uploaded image may be either image/jpeg or image/png.
$this->assertEqual(substr($file2->getMimeType(), 0, 5), 'image', 'A MIME type was set.');
// Load both files using File::loadMultiple().
$files = File::loadMultiple([$file1->id(), $file2->id()]);
$this->assertTrue(isset($files[$file1->id()]), 'File was loaded successfully');
$this->assertTrue(isset($files[$file2->id()]), 'File was loaded successfully');
// Upload a third file to a subdirectory.
$image3 = current($this->drupalGetTestFiles('image'));
$image3_realpath = $file_system->realpath($image3->uri);
$dir = $this->randomMachineName();
$edit = [
'files[file_test_upload][]' => $image3_realpath,
'file_subdir' => $dir,
];
$this->drupalPostForm('file-test/save_upload_from_form_test', $edit, t('Submit'));
$this->assertResponse(200, 'Received a 200 response for posted test file.');
$this->assertRaw(t('You WIN!'));
$this->assertTrue(is_file('temporary://' . $dir . '/' . trim(drupal_basename($image3_realpath))));
}
/**
* Tests extension handling.
*/
public function testHandleExtension() {
/** @var \Drupal\Core\File\FileSystemInterface $file_system */
$file_system = \Drupal::service('file_system');
// The file being tested is a .gif which is in the default safe list
// of extensions to allow when the extension validator isn't used. This is
// implicitly tested at the testNormal() test. Here we tell
// _file_save_upload_from_form() to only allow ".foo".
$extensions = 'foo';
$edit = [
'file_test_replace' => FILE_EXISTS_REPLACE,
'files[file_test_upload][]' => $file_system->realpath($this->image->getFileUri()),
'extensions' => $extensions,
];
$this->drupalPostForm('file-test/save_upload_from_form_test', $edit, t('Submit'));
$this->assertResponse(200, 'Received a 200 response for posted test file.');
$message = t('Only files with the following extensions are allowed:') . ' <em class="placeholder">' . $extensions . '</em>';
$this->assertRaw($message, 'Cannot upload a disallowed extension');
$this->assertRaw(t('Epic upload FAIL!'), 'Found the failure message.');
// Check that the correct hooks were called.
$this->assertFileHooksCalled(['validate']);
// Reset the hook counters.
file_test_reset();
$extensions = 'foo ' . $this->imageExtension;
// Now tell _file_save_upload_from_form() to allow the extension of our test image.
$edit = [
'file_test_replace' => FILE_EXISTS_REPLACE,
'files[file_test_upload][]' => $file_system->realpath($this->image->getFileUri()),
'extensions' => $extensions,
];
$this->drupalPostForm('file-test/save_upload_from_form_test', $edit, t('Submit'));
$this->assertResponse(200, 'Received a 200 response for posted test file.');
$this->assertNoRaw(t('Only files with the following extensions are allowed:'), 'Can upload an allowed extension.');
$this->assertRaw(t('You WIN!'), 'Found the success message.');
// Check that the correct hooks were called.
$this->assertFileHooksCalled(['validate', 'load', 'update']);
// Reset the hook counters.
file_test_reset();
// Now tell _file_save_upload_from_form() to allow any extension.
$edit = [
'file_test_replace' => FILE_EXISTS_REPLACE,
'files[file_test_upload][]' => $file_system->realpath($this->image->getFileUri()),
'allow_all_extensions' => TRUE,
];
$this->drupalPostForm('file-test/save_upload_from_form_test', $edit, t('Submit'));
$this->assertResponse(200, 'Received a 200 response for posted test file.');
$this->assertNoRaw(t('Only files with the following extensions are allowed:'), 'Can upload any extension.');
$this->assertRaw(t('You WIN!'), 'Found the success message.');
// Check that the correct hooks were called.
$this->assertFileHooksCalled(['validate', 'load', 'update']);
}
/**
* Tests dangerous file handling.
*/
public function testHandleDangerousFile() {
$config = $this->config('system.file');
/** @var \Drupal\Core\File\FileSystemInterface $file_system */
$file_system = \Drupal::service('file_system');
// Allow the .php extension and make sure it gets renamed to .txt for
// safety. Also check to make sure its MIME type was changed.
$edit = [
'file_test_replace' => FILE_EXISTS_REPLACE,
'files[file_test_upload][]' => $file_system->realpath($this->phpfile->uri),
'is_image_file' => FALSE,
'extensions' => 'php',
];
$this->drupalPostForm('file-test/save_upload_from_form_test', $edit, t('Submit'));
$this->assertResponse(200, 'Received a 200 response for posted test file.');
$message = t('For security reasons, your upload has been renamed to') . ' <em class="placeholder">' . $this->phpfile->filename . '.txt' . '</em>';
$this->assertRaw($message, 'Dangerous file was renamed.');
$this->assertRaw(t('File MIME type is text/plain.'), "Dangerous file's MIME type was changed.");
$this->assertRaw(t('You WIN!'), 'Found the success message.');
// Check that the correct hooks were called.
$this->assertFileHooksCalled(['validate', 'insert']);
// Ensure dangerous files are not renamed when insecure uploads is TRUE.
// Turn on insecure uploads.
$config->set('allow_insecure_uploads', 1)->save();
// Reset the hook counters.
file_test_reset();
$this->drupalPostForm('file-test/save_upload_from_form_test', $edit, t('Submit'));
$this->assertResponse(200, 'Received a 200 response for posted test file.');
$this->assertNoRaw(t('For security reasons, your upload has been renamed'), 'Found no security message.');
$this->assertRaw(t('File name is @filename', ['@filename' => $this->phpfile->filename]), 'Dangerous file was not renamed when insecure uploads is TRUE.');
$this->assertRaw(t('You WIN!'), 'Found the success message.');
// Check that the correct hooks were called.
$this->assertFileHooksCalled(['validate', 'insert']);
// Turn off insecure uploads.
$config->set('allow_insecure_uploads', 0)->save();
}
/**
* Tests file munge handling.
*/
public function testHandleFileMunge() {
/** @var \Drupal\Core\File\FileSystemInterface $file_system */
$file_system = \Drupal::service('file_system');
// Ensure insecure uploads are disabled for this test.
$this->config('system.file')->set('allow_insecure_uploads', 0)->save();
$this->image = file_move($this->image, $this->image->getFileUri() . '.foo.' . $this->imageExtension);
// Reset the hook counters to get rid of the 'move' we just called.
file_test_reset();
$extensions = $this->imageExtension;
$edit = [
'files[file_test_upload][]' => $file_system->realpath($this->image->getFileUri()),
'extensions' => $extensions,
];
$munged_filename = $this->image->getFilename();
$munged_filename = substr($munged_filename, 0, strrpos($munged_filename, '.'));
$munged_filename .= '_.' . $this->imageExtension;
$this->drupalPostForm('file-test/save_upload_from_form_test', $edit, t('Submit'));
$this->assertResponse(200, 'Received a 200 response for posted test file.');
$this->assertRaw(t('For security reasons, your upload has been renamed'), 'Found security message.');
$this->assertRaw(t('File name is @filename', ['@filename' => $munged_filename]), 'File was successfully munged.');
$this->assertRaw(t('You WIN!'), 'Found the success message.');
// Check that the correct hooks were called.
$this->assertFileHooksCalled(['validate', 'insert']);
// Ensure we don't munge files if we're allowing any extension.
// Reset the hook counters.
file_test_reset();
$edit = [
'files[file_test_upload][]' => $file_system->realpath($this->image->getFileUri()),
'allow_all_extensions' => TRUE,
];
$this->drupalPostForm('file-test/save_upload_from_form_test', $edit, t('Submit'));
$this->assertResponse(200, 'Received a 200 response for posted test file.');
$this->assertNoRaw(t('For security reasons, your upload has been renamed'), 'Found no security message.');
$this->assertRaw(t('File name is @filename', ['@filename' => $this->image->getFilename()]), 'File was not munged when allowing any extension.');
$this->assertRaw(t('You WIN!'), 'Found the success message.');
// Check that the correct hooks were called.
$this->assertFileHooksCalled(['validate', 'insert']);
}
/**
* Tests renaming when uploading over a file that already exists.
*/
public function testExistingRename() {
/** @var \Drupal\Core\File\FileSystemInterface $file_system */
$file_system = \Drupal::service('file_system');
$edit = [
'file_test_replace' => FILE_EXISTS_RENAME,
'files[file_test_upload][]' => $file_system->realpath($this->image->getFileUri())
];
$this->drupalPostForm('file-test/save_upload_from_form_test', $edit, t('Submit'));
$this->assertResponse(200, 'Received a 200 response for posted test file.');
$this->assertRaw(t('You WIN!'), 'Found the success message.');
// Check that the correct hooks were called.
$this->assertFileHooksCalled(['validate', 'insert']);
}
/**
* Tests replacement when uploading over a file that already exists.
*/
public function testExistingReplace() {
/** @var \Drupal\Core\File\FileSystemInterface $file_system */
$file_system = \Drupal::service('file_system');
$edit = [
'file_test_replace' => FILE_EXISTS_REPLACE,
'files[file_test_upload][]' => $file_system->realpath($this->image->getFileUri())
];
$this->drupalPostForm('file-test/save_upload_from_form_test', $edit, t('Submit'));
$this->assertResponse(200, 'Received a 200 response for posted test file.');
$this->assertRaw(t('You WIN!'), 'Found the success message.');
// Check that the correct hooks were called.
$this->assertFileHooksCalled(['validate', 'load', 'update']);
}
/**
* Tests for failure when uploading over a file that already exists.
*/
public function testExistingError() {
/** @var \Drupal\Core\File\FileSystemInterface $file_system */
$file_system = \Drupal::service('file_system');
$edit = [
'file_test_replace' => FILE_EXISTS_ERROR,
'files[file_test_upload][]' => $file_system->realpath($this->image->getFileUri())
];
$this->drupalPostForm('file-test/save_upload_from_form_test', $edit, t('Submit'));
$this->assertResponse(200, 'Received a 200 response for posted test file.');
$this->assertRaw(t('Epic upload FAIL!'), 'Found the failure message.');
// Check that the no hooks were called while failing.
$this->assertFileHooksCalled([]);
}
/**
* Tests for no failures when not uploading a file.
*/
public function testNoUpload() {
$this->drupalPostForm('file-test/save_upload_from_form_test', [], t('Submit'));
$this->assertNoRaw(t('Epic upload FAIL!'), 'Failure message not found.');
}
/**
* Tests for log entry on failing destination.
*/
public function testDrupalMovingUploadedFileError() {
// Create a directory and make it not writable.
$test_directory = 'test_drupal_move_uploaded_file_fail';
drupal_mkdir('temporary://' . $test_directory, 0000);
$this->assertTrue(is_dir('temporary://' . $test_directory));
/** @var \Drupal\Core\File\FileSystemInterface $file_system */
$file_system = \Drupal::service('file_system');
$edit = [
'file_subdir' => $test_directory,
'files[file_test_upload][]' => $file_system->realpath($this->image->getFileUri())
];
\Drupal::state()->set('file_test.disable_error_collection', TRUE);
$this->drupalPostForm('file-test/save_upload_from_form_test', $edit, t('Submit'));
$this->assertResponse(200, 'Received a 200 response for posted test file.');
$this->assertRaw(t('File upload error. Could not move uploaded file.'), 'Found the failure message.');
$this->assertRaw(t('Epic upload FAIL!'), 'Found the failure message.');
// Uploading failed. Now check the log.
$this->drupalGet('admin/reports/dblog');
$this->assertResponse(200);
$this->assertRaw(t('Upload error. Could not move uploaded file @file to destination @destination.', [
'@file' => $this->image->getFilename(),
'@destination' => 'temporary://' . $test_directory . '/' . $this->image->getFilename()
]), 'Found upload error log entry.');
}
/**
* Tests that form validation does not change error messages.
*/
public function testErrorMessagesAreNotChanged() {
$error = 'An error message set before _file_save_upload_from_form()';
/** @var \Drupal\Core\File\FileSystemInterface $file_system */
$file_system = \Drupal::service('file_system');
$edit = [
'files[file_test_upload][]' => $file_system->realpath($this->image->getFileUri()),
'error_message' => $error,
];
$this->drupalPostForm('file-test/save_upload_from_form_test', $edit, t('Submit'));
$this->assertResponse(200, 'Received a 200 response for posted test file.');
$this->assertRaw(t('You WIN!'), 'Found the success message.');
// Ensure the expected error message is present and the counts before and
// after calling _file_save_upload_from_form() are correct.
$this->assertText($error);
$this->assertRaw('Number of error messages before _file_save_upload_from_form(): 1');
$this->assertRaw('Number of error messages after _file_save_upload_from_form(): 1');
// Test that error messages are preserved when an error occurs.
$edit = [
'files[file_test_upload][]' => $file_system->realpath($this->image->getFileUri()),
'error_message' => $error,
'extensions' => 'foo'
];
$this->drupalPostForm('file-test/save_upload_from_form_test', $edit, t('Submit'));
$this->assertResponse(200, 'Received a 200 response for posted test file.');
$this->assertRaw(t('Epic upload FAIL!'), 'Found the failure message.');
// Ensure the expected error message is present and the counts before and
// after calling _file_save_upload_from_form() are correct.
$this->assertText($error);
$this->assertRaw('Number of error messages before _file_save_upload_from_form(): 1');
$this->assertRaw('Number of error messages after _file_save_upload_from_form(): 2');
// Test a successful upload with no messages.
$edit = [
'files[file_test_upload][]' => $file_system->realpath($this->image->getFileUri()),
];
$this->drupalPostForm('file-test/save_upload_from_form_test', $edit, t('Submit'));
$this->assertResponse(200, 'Received a 200 response for posted test file.');
$this->assertRaw(t('You WIN!'), 'Found the success message.');
// Ensure the error message is not present and the counts before and after
// calling _file_save_upload_from_form() are correct.
$this->assertNoText($error);
$this->assertRaw('Number of error messages before _file_save_upload_from_form(): 0');
$this->assertRaw('Number of error messages after _file_save_upload_from_form(): 0');
}
/**
* Tests that multiple validation errors are combined in one message.
*/
public function testCombinedErrorMessages() {
$textfile = current($this->drupalGetTestFiles('text'));
$this->assertTrue(is_file($textfile->uri), 'The text file we are going to upload exists.');
/** @var \Drupal\Core\File\FileSystemInterface $file_system */
$file_system = \Drupal::service('file_system');
$edit = [
'files[file_test_upload][]' => [
$file_system->realpath($this->phpfile->uri),
$file_system->realpath($textfile->uri),
],
'allow_all_extensions' => FALSE,
'is_image_file' => TRUE,
'extensions' => 'jpeg',
];
$this->drupalPostForm('file-test/save_upload_from_form_test', $edit, t('Submit'));
$this->assertResponse(200, 'Received a 200 response for posted test file.');
$this->assertRaw(t('Epic upload FAIL!'), 'Found the failure message.');
// Search for combined error message followed by a formatted list of messages.
$this->assertRaw(t('One or more files could not be uploaded.') . '<div class="item-list">', 'Error message contains combined list of validation errors.');
}
/**
* Tests highlighting of file upload field when it has an error.
*/
public function testUploadFieldIsHighlighted() {
$this->assertEqual(0, count($this->cssSelect('input[name="files[file_test_upload][]"].error')), 'Successful file upload has no error.');
/** @var \Drupal\Core\File\FileSystemInterface $file_system */
$file_system = \Drupal::service('file_system');
$edit = [
'files[file_test_upload][]' => $file_system->realpath($this->image->getFileUri()),
'extensions' => 'foo'
];
$this->drupalPostForm('file-test/save_upload_from_form_test', $edit, t('Submit'));
$this->assertResponse(200, 'Received a 200 response for posted test file.');
$this->assertRaw(t('Epic upload FAIL!'), 'Found the failure message.');
$this->assertEqual(1, count($this->cssSelect('input[name="files[file_test_upload][]"].error')), 'File upload field has error.');
}
}
+13 -13
View File
@@ -60,7 +60,7 @@ class SaveUploadTest extends FileManagedTestBase {
// Upload with replace to guarantee there's something there.
$edit = [
'file_test_replace' => FILE_EXISTS_REPLACE,
'files[file_test_upload]' => drupal_realpath($this->image->getFileUri()),
'files[file_test_upload]' => \Drupal::service('file_system')->realpath($this->image->getFileUri()),
];
$this->drupalPostForm('file-test/upload', $edit, t('Submit'));
$this->assertResponse(200, 'Received a 200 response for posted test file.');
@@ -88,7 +88,7 @@ class SaveUploadTest extends FileManagedTestBase {
// Upload a second file.
$image2 = current($this->drupalGetTestFiles('image'));
$edit = ['files[file_test_upload]' => drupal_realpath($image2->uri)];
$edit = ['files[file_test_upload]' => \Drupal::service('file_system')->realpath($image2->uri)];
$this->drupalPostForm('file-test/upload', $edit, t('Submit'));
$this->assertResponse(200, 'Received a 200 response for posted test file.');
$this->assertRaw(t('You WIN!'));
@@ -109,7 +109,7 @@ class SaveUploadTest extends FileManagedTestBase {
// Upload a third file to a subdirectory.
$image3 = current($this->drupalGetTestFiles('image'));
$image3_realpath = drupal_realpath($image3->uri);
$image3_realpath = \Drupal::service('file_system')->realpath($image3->uri);
$dir = $this->randomMachineName();
$edit = [
'files[file_test_upload]' => $image3_realpath,
@@ -132,7 +132,7 @@ class SaveUploadTest extends FileManagedTestBase {
$extensions = 'foo';
$edit = [
'file_test_replace' => FILE_EXISTS_REPLACE,
'files[file_test_upload]' => drupal_realpath($this->image->getFileUri()),
'files[file_test_upload]' => \Drupal::service('file_system')->realpath($this->image->getFileUri()),
'extensions' => $extensions,
];
@@ -152,7 +152,7 @@ class SaveUploadTest extends FileManagedTestBase {
// Now tell file_save_upload() to allow the extension of our test image.
$edit = [
'file_test_replace' => FILE_EXISTS_REPLACE,
'files[file_test_upload]' => drupal_realpath($this->image->getFileUri()),
'files[file_test_upload]' => \Drupal::service('file_system')->realpath($this->image->getFileUri()),
'extensions' => $extensions,
];
@@ -170,7 +170,7 @@ class SaveUploadTest extends FileManagedTestBase {
// Now tell file_save_upload() to allow any extension.
$edit = [
'file_test_replace' => FILE_EXISTS_REPLACE,
'files[file_test_upload]' => drupal_realpath($this->image->getFileUri()),
'files[file_test_upload]' => \Drupal::service('file_system')->realpath($this->image->getFileUri()),
'allow_all_extensions' => TRUE,
];
$this->drupalPostForm('file-test/upload', $edit, t('Submit'));
@@ -191,7 +191,7 @@ class SaveUploadTest extends FileManagedTestBase {
// safety. Also check to make sure its MIME type was changed.
$edit = [
'file_test_replace' => FILE_EXISTS_REPLACE,
'files[file_test_upload]' => drupal_realpath($this->phpfile->uri),
'files[file_test_upload]' => \Drupal::service('file_system')->realpath($this->phpfile->uri),
'is_image_file' => FALSE,
'extensions' => 'php',
];
@@ -238,7 +238,7 @@ class SaveUploadTest extends FileManagedTestBase {
$extensions = $this->imageExtension;
$edit = [
'files[file_test_upload]' => drupal_realpath($this->image->getFileUri()),
'files[file_test_upload]' => \Drupal::service('file_system')->realpath($this->image->getFileUri()),
'extensions' => $extensions,
];
@@ -260,7 +260,7 @@ class SaveUploadTest extends FileManagedTestBase {
file_test_reset();
$edit = [
'files[file_test_upload]' => drupal_realpath($this->image->getFileUri()),
'files[file_test_upload]' => \Drupal::service('file_system')->realpath($this->image->getFileUri()),
'allow_all_extensions' => TRUE,
];
@@ -280,7 +280,7 @@ class SaveUploadTest extends FileManagedTestBase {
public function testExistingRename() {
$edit = [
'file_test_replace' => FILE_EXISTS_RENAME,
'files[file_test_upload]' => drupal_realpath($this->image->getFileUri())
'files[file_test_upload]' => \Drupal::service('file_system')->realpath($this->image->getFileUri())
];
$this->drupalPostForm('file-test/upload', $edit, t('Submit'));
$this->assertResponse(200, 'Received a 200 response for posted test file.');
@@ -296,7 +296,7 @@ class SaveUploadTest extends FileManagedTestBase {
public function testExistingReplace() {
$edit = [
'file_test_replace' => FILE_EXISTS_REPLACE,
'files[file_test_upload]' => drupal_realpath($this->image->getFileUri())
'files[file_test_upload]' => \Drupal::service('file_system')->realpath($this->image->getFileUri())
];
$this->drupalPostForm('file-test/upload', $edit, t('Submit'));
$this->assertResponse(200, 'Received a 200 response for posted test file.');
@@ -312,7 +312,7 @@ class SaveUploadTest extends FileManagedTestBase {
public function testExistingError() {
$edit = [
'file_test_replace' => FILE_EXISTS_ERROR,
'files[file_test_upload]' => drupal_realpath($this->image->getFileUri())
'files[file_test_upload]' => \Drupal::service('file_system')->realpath($this->image->getFileUri())
];
$this->drupalPostForm('file-test/upload', $edit, t('Submit'));
$this->assertResponse(200, 'Received a 200 response for posted test file.');
@@ -341,7 +341,7 @@ class SaveUploadTest extends FileManagedTestBase {
$edit = [
'file_subdir' => $test_directory,
'files[file_test_upload]' => drupal_realpath($this->image->getFileUri())
'files[file_test_upload]' => \Drupal::service('file_system')->realpath($this->image->getFileUri())
];
\Drupal::state()->set('file_test.disable_error_collection', TRUE);
@@ -0,0 +1,59 @@
<?php
namespace Drupal\file\Tests\Update;
use Drupal\system\Tests\Update\UpdatePathTestBase;
/**
* Tests File update path.
*
* @group file
*/
class FileUpdateTest extends UpdatePathTestBase {
/**
* Modules to enable after the database is loaded.
*/
protected static $modules = ['file'];
/**
* {@inheritdoc}
*/
protected function setDatabaseDumpFiles() {
$this->databaseDumpFiles = [
__DIR__ . '/../../../../system/tests/fixtures/update/drupal-8.bare.standard.php.gz',
__DIR__ . '/../../../tests/fixtures/update/drupal-8.file_formatters_update_2677990.php',
];
}
/**
* Tests file_update_8001().
*/
public function testPostUpdate8001() {
$view = 'core.entity_view_display.node.article.default';
// Check that field_file_generic formatter has no
// use_description_as_link_text setting.
$formatter_settings = $this->config($view)->get('content.field_file_generic_2677990.settings');
$this->assertTrue(!isset($formatter_settings['use_description_as_link_text']));
// Check that field_file_table formatter has no use_description_as_link_text
// setting.
$formatter_settings = $this->config($view)->get('content.field_file_table_2677990.settings');
$this->assertTrue(!isset($formatter_settings['use_description_as_link_text']));
// Run updates.
$this->runUpdates();
// Check that field_file_generic formatter has a
// use_description_as_link_text setting which value is TRUE.
$formatter_settings = $this->config($view)->get('content.field_file_generic_2677990.settings');
$this->assertEqual($formatter_settings, ['use_description_as_link_text' => TRUE]);
// Check that field_file_table formatter has a use_description_as_link_text
// setting which value is FALSE.
$formatter_settings = $this->config($view)->get('content.field_file_table_2677990.settings');
$this->assertEqual($formatter_settings, ['use_description_as_link_text' => FALSE]);
}
}
@@ -30,8 +30,8 @@ class RelationshipUserFileDataTest extends ViewTestBase {
*/
public static $testViews = ['test_file_user_file_data'];
protected function setUp() {
parent::setUp();
protected function setUp($import_test_views = TRUE) {
parent::setUp($import_test_views);
// Create the user profile field and instance.
FieldStorageConfig::create([
@@ -0,0 +1,22 @@
{#
/**
* @file
* Default theme implementation to display the file entity as an audio tag.
*
* Available variables:
* - attributes: An array of HTML attributes, intended to be added to the
* audio tag.
* - files: And array of files to be added as sources for the audio tag. Each
* element is an array with the following elements:
* - file: The full file object.
* - source_attributes: An array of HTML attributes for to be added to the
* source tag.
*
* @ingroup themeable
*/
#}
<audio {{ attributes }}>
{% for file in files %}
<source {{ file.source_attributes }} />
{% endfor %}
</audio>
@@ -0,0 +1,22 @@
{#
/**
* @file
* Default theme implementation to display the file entity as a video tag.
*
* Available variables:
* - attributes: An array of HTML attributes, intended to be added to the
* video tag.
* - files: And array of files to be added as sources for the video tag. Each
* element is an array with the following elements:
* - file: The full file object.
* - source_attributes: An array of HTML attributes for to be added to the
* source tag.
*
* @ingroup themeable
*/
#}
<video {{ attributes }}>
{% for file in files %}
<source {{ file.source_attributes }} />
{% endfor %}
</video>
@@ -5,8 +5,8 @@ package: Testing
# version: VERSION
# core: 8.x
# Information added by Drupal.org packaging script on 2018-01-03
version: '8.4.4'
# Information added by Drupal.org packaging script on 2018-03-07
version: '8.5.0'
core: '8.x'
project: 'drupal'
datestamp: 1515021228
datestamp: 1520457825
@@ -7,6 +7,8 @@ use Drupal\Core\Form\FormStateInterface;
/**
* Form controller for file_module_test module.
*
* @internal
*/
class FileModuleTestForm extends FormBase {
@@ -5,8 +5,8 @@ package: Testing
# version: VERSION
# core: 8.x
# Information added by Drupal.org packaging script on 2018-01-03
version: '8.4.4'
# Information added by Drupal.org packaging script on 2018-03-07
version: '8.5.0'
core: '8.x'
project: 'drupal'
datestamp: 1515021228
datestamp: 1520457825
@@ -4,3 +4,9 @@ file.test:
_form: 'Drupal\file_test\Form\FileTestForm'
requirements:
_access: 'TRUE'
file.save_upload_from_form_test:
path: '/file-test/save_upload_from_form_test'
defaults:
_form: 'Drupal\file_test\Form\FileTestSaveUploadFromForm'
requirements:
_access: 'TRUE'
@@ -0,0 +1,179 @@
<?php
namespace Drupal\file_test\Form;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Messenger\MessengerInterface;
use Drupal\Core\State\StateInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* File test form class.
*/
class FileTestSaveUploadFromForm extends FormBase {
/**
* Stores the state storage service.
*
* @var \Drupal\Core\State\StateInterface
*/
protected $state;
/**
* The messenger.
*
* @var \Drupal\Core\Messenger\MessengerInterface
*/
protected $messenger;
/**
* Constructs a FileTestSaveUploadFromForm object.
*
* @param \Drupal\Core\State\StateInterface $state
* The state key value store.
* @param \Drupal\Core\Messenger\MessengerInterface $messenger
* The messenger.
*/
public function __construct(StateInterface $state, MessengerInterface $messenger) {
$this->state = $state;
$this->messenger = $messenger;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('state'),
$container->get('messenger')
);
}
/**
* {@inheritdoc}
*/
public function getFormId() {
return '_file_test_save_upload_from_form';
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state) {
$form['file_test_upload'] = [
'#type' => 'file',
'#multiple' => TRUE,
'#title' => $this->t('Upload a file'),
];
$form['file_test_replace'] = [
'#type' => 'select',
'#title' => $this->t('Replace existing image'),
'#options' => [
FILE_EXISTS_RENAME => $this->t('Appends number until name is unique'),
FILE_EXISTS_REPLACE => $this->t('Replace the existing file'),
FILE_EXISTS_ERROR => $this->t('Fail with an error'),
],
'#default_value' => FILE_EXISTS_RENAME,
];
$form['file_subdir'] = [
'#type' => 'textfield',
'#title' => $this->t('Subdirectory for test file'),
'#default_value' => '',
];
$form['extensions'] = [
'#type' => 'textfield',
'#title' => $this->t('Allowed extensions.'),
'#default_value' => '',
];
$form['allow_all_extensions'] = [
'#type' => 'checkbox',
'#title' => $this->t('Allow all extensions?'),
'#default_value' => FALSE,
];
$form['is_image_file'] = [
'#type' => 'checkbox',
'#title' => $this->t('Is this an image file?'),
'#default_value' => TRUE,
];
$form['error_message'] = [
'#type' => 'textfield',
'#title' => $this->t('Custom error message.'),
'#default_value' => '',
];
$form['submit'] = [
'#type' => 'submit',
'#value' => $this->t('Submit'),
];
return $form;
}
/**
* {@inheritdoc}
*/
public function validateForm(array &$form, FormStateInterface $form_state) {
// Process the upload and perform validation. Note: we're using the
// form value for the $replace parameter.
if (!$form_state->isValueEmpty('file_subdir')) {
$destination = 'temporary://' . $form_state->getValue('file_subdir');
file_prepare_directory($destination, FILE_CREATE_DIRECTORY);
}
else {
$destination = FALSE;
}
// Preset custom error message if requested.
if ($form_state->getValue('error_message')) {
$this->messenger->addError($form_state->getValue('error_message'));
}
// Setup validators.
$validators = [];
if ($form_state->getValue('is_image_file')) {
$validators['file_validate_is_image'] = [];
}
if ($form_state->getValue('allow_all_extensions')) {
$validators['file_validate_extensions'] = [];
}
elseif (!$form_state->isValueEmpty('extensions')) {
$validators['file_validate_extensions'] = [$form_state->getValue('extensions')];
}
// The test for drupal_move_uploaded_file() triggering a warning is
// unavoidable. We're interested in what happens afterwards in
// _file_save_upload_from_form().
if ($this->state->get('file_test.disable_error_collection')) {
define('SIMPLETEST_COLLECT_ERRORS', FALSE);
}
$form['file_test_upload']['#upload_validators'] = $validators;
$form['file_test_upload']['#upload_location'] = $destination;
$this->messenger->addStatus($this->t('Number of error messages before _file_save_upload_from_form(): @count.', ['@count' => count($this->messenger->messagesByType(MessengerInterface::TYPE_ERROR))]));
$file = _file_save_upload_from_form($form['file_test_upload'], $form_state, 0, $form_state->getValue('file_test_replace'));
$this->messenger->addStatus($this->t('Number of error messages after _file_save_upload_from_form(): @count.', ['@count' => count($this->messenger->messagesByType(MessengerInterface::TYPE_ERROR))]));
if ($file) {
$form_state->setValue('file_test_upload', $file);
$this->messenger->addStatus($this->t('File @filepath was uploaded.', ['@filepath' => $file->getFileUri()]));
$this->messenger->addStatus($this->t('File name is @filename.', ['@filename' => $file->getFilename()]));
$this->messenger->addStatus($this->t('File MIME type is @mimetype.', ['@mimetype' => $file->getMimeType()]));
$this->messenger->addStatus($this->t('You WIN!'));
}
elseif ($file === FALSE) {
$this->messenger->addError($this->t('Epic upload FAIL!'));
}
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {}
}
@@ -0,0 +1,71 @@
uuid: 9ca49b35-b49d-4014-9337-965cdf15b61e
langcode: en
status: true
dependencies:
config:
- field.field.node.article.body
- field.field.node.article.comment
- field.field.node.article.field_file_generic_2677990
- field.field.node.article.field_file_table_2677990
- field.field.node.article.field_image
- field.field.node.article.field_tags
- image.style.large
- node.type.article
module:
- comment
- file
- image
- text
- user
_core:
default_config_hash: JtAg_-waIt1quMtdDtHIaXJMxvTuSmxW7bWyO6Zd68E
id: node.article.default
targetEntityType: node
bundle: article
mode: default
content:
body:
type: text_default
weight: 0
settings: { }
third_party_settings: { }
label: hidden
comment:
label: above
type: comment_default
weight: 20
settings:
pager_id: 0
third_party_settings: { }
field_file_generic_2677990:
weight: 101
label: above
settings: { }
third_party_settings: { }
type: file_default
field_file_table_2677990:
weight: 102
label: above
settings: { }
third_party_settings: { }
type: file_table
field_image:
type: image
weight: -1
settings:
image_style: large
image_link: ''
third_party_settings: { }
label: hidden
field_tags:
type: entity_reference_label
weight: 10
label: above
settings:
link: true
third_party_settings: { }
links:
weight: 100
settings: { }
third_party_settings: { }
hidden: { }
@@ -0,0 +1,88 @@
<?php
/**
* @file
* Contains database additions to drupal-8.bare.standard.php.gz for testing the
* upgrade path of https://www.drupal.org/node/2677990.
*/
use Drupal\Core\Database\Database;
use Drupal\Component\Serialization\Yaml;
use Drupal\field\Entity\FieldStorageConfig;
$connection = Database::getConnection();
// Configuration for a file field storage for generic display.
$field_file_generic_2677990 = Yaml::decode(file_get_contents(__DIR__ . '/field.storage.node.field_file_generic_2677990.yml'));
// Configuration for a file field storage for table display.
$field_file_table_2677990 = Yaml::decode(file_get_contents(__DIR__ . '/field.storage.node.field_file_table_2677990.yml'));
$connection->insert('config')
->fields([
'collection',
'name',
'data',
])
->values([
'collection' => '',
'name' => 'field.storage.' . $field_file_generic_2677990['id'],
'data' => serialize($field_file_generic_2677990),
])
->values([
'collection' => '',
'name' => 'field.storage.' . $field_file_table_2677990['id'],
'data' => serialize($field_file_table_2677990),
])
->execute();
// We need to Update the registry of "last installed" field definitions.
$installed = $connection->select('key_value')
->fields('key_value', ['value'])
->condition('collection', 'entity.definitions.installed')
->condition('name', 'node.field_storage_definitions')
->execute()
->fetchField();
$installed = unserialize($installed);
$installed['field_file_generic_2677990'] = new FieldStorageConfig($field_file_generic_2677990);
$installed['field_file_table_2677990'] = new FieldStorageConfig($field_file_table_2677990);
$connection->update('key_value')
->condition('collection', 'entity.definitions.installed')
->condition('name', 'node.field_storage_definitions')
->fields([
'value' => serialize($installed)
])
->execute();
// Configuration for a file field storage for generic display.
$field_file_generic_2677990 = Yaml::decode(file_get_contents(__DIR__ . '/field.field.node.article.field_file_generic_2677990.yml'));
// Configuration for a file field storage for table display.
$field_file_table_2677990 = Yaml::decode(file_get_contents(__DIR__ . '/field.field.node.article.field_file_table_2677990.yml'));
$connection->insert('config')
->fields([
'collection',
'name',
'data',
])
->values([
'collection' => '',
'name' => 'field.field.' . $field_file_generic_2677990['id'],
'data' => serialize($field_file_generic_2677990),
])
->values([
'collection' => '',
'name' => 'field.field.' . $field_file_table_2677990['id'],
'data' => serialize($field_file_table_2677990),
])
->execute();
// Configuration of the view mode to set the proper formatters.
$view_mode_2677990 = Yaml::decode(file_get_contents(__DIR__ . '/core.entity_view_display.node.article.default_2677990.yml'));
$connection->update('config')
->fields([
'data' => serialize($view_mode_2677990),
])
->condition('name', 'core.entity_view_display.' . $view_mode_2677990['id'])
->execute();
@@ -0,0 +1,27 @@
uuid: d352a831-c267-4ecc-9b4e-7ae1896b2241
langcode: en
status: true
dependencies:
config:
- field.storage.node.field_file_generic_2677990
- node.type.article
module:
- file
id: node.article.field_file_generic_2677990
field_name: field_file_generic_2677990
entity_type: node
bundle: article
label: 'File generic'
description: ''
required: false
translatable: false
default_value: { }
default_value_callback: ''
settings:
file_directory: '[date:custom:Y]-[date:custom:m]'
file_extensions: txt
max_filesize: ''
description_field: true
handler: 'default:file'
handler_settings: { }
field_type: file
@@ -0,0 +1,27 @@
uuid: 44c7a590-ffcc-4534-b01c-b17b8d57ed48
langcode: en
status: true
dependencies:
config:
- field.storage.node.field_file_table_2677990
- node.type.article
module:
- file
id: node.article.field_file_table_2677990
field_name: field_file_table_2677990
entity_type: node
bundle: article
label: 'File table'
description: ''
required: false
translatable: false
default_value: { }
default_value_callback: ''
settings:
file_directory: '[date:custom:Y]-[date:custom:m]'
file_extensions: txt
max_filesize: ''
description_field: true
handler: 'default:file'
handler_settings: { }
field_type: file
@@ -0,0 +1,23 @@
uuid: a7eb470d-e538-4221-a8ac-57f989d92d8e
langcode: en
status: true
dependencies:
module:
- file
- node
id: node.field_file_generic_2677990
field_name: field_file_generic_2677990
entity_type: node
type: file
settings:
display_field: false
display_default: false
uri_scheme: public
target_type: file
module: file
locked: false
cardinality: 1
translatable: true
indexes: { }
persist_with_no_fields: false
custom_storage: false
@@ -0,0 +1,23 @@
uuid: 43113a5e-3e07-4234-b045-4aa4cd217dca
langcode: en
status: true
dependencies:
module:
- file
- node
id: node.field_file_table_2677990
field_name: field_file_table_2677990
entity_type: node
type: file
settings:
display_field: false
display_default: false
uri_scheme: public
target_type: file
module: file
locked: false
cardinality: 1
translatable: true
indexes: { }
persist_with_no_fields: false
custom_storage: false
@@ -8,8 +8,8 @@ dependencies:
- file
- views
# Information added by Drupal.org packaging script on 2018-01-03
version: '8.4.4'
# Information added by Drupal.org packaging script on 2018-03-07
version: '8.5.0'
core: '8.x'
project: 'drupal'
datestamp: 1515021228
datestamp: 1520457825
@@ -180,7 +180,7 @@ abstract class FileFieldTestBase extends BrowserTestBase {
*/
public function replaceNodeFile($file, $field_name, $nid, $new_revision = TRUE) {
$edit = [
'files[' . $field_name . '_0]' => drupal_realpath($file->getFileUri()),
'files[' . $field_name . '_0]' => \Drupal::service('file_system')->realpath($file->getFileUri()),
'revision' => (string) (int) $new_revision,
];
@@ -3,6 +3,7 @@
namespace Drupal\Tests\file\Functional;
use Drupal\file\Entity\File;
use Drupal\user\Entity\Role;
/**
* Tests access to managed files.
@@ -11,6 +12,19 @@ use Drupal\file\Entity\File;
*/
class FileManagedAccessTest extends FileManagedTestBase {
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
// Give anonymous users permission to access content, so they can view and
// download public files.
$anonymous_role = Role::load(Role::ANONYMOUS_ID);
$anonymous_role->grantPermission('access content');
$anonymous_role->save();
}
/**
* Tests if public file is always accessible.
*/
@@ -29,7 +43,7 @@ class FileManagedAccessTest extends FileManagedTestBase {
$file->save();
// Create authenticated user to check file access.
$account = $this->createUser(['access site reports']);
$account = $this->createUser(['access site reports', 'access content']);
$this->assertTrue($file->access('view', $account), 'Public file is viewable to authenticated user');
$this->assertTrue($file->access('download', $account), 'Public file is downloadable to authenticated user');
@@ -54,7 +68,7 @@ class FileManagedAccessTest extends FileManagedTestBase {
$file->save();
// Create authenticated user to check file access.
$account = $this->createUser(['access site reports']);
$account = $this->createUser(['access site reports', 'access content']);
$this->assertFalse($file->access('view', $account), 'Private file is not viewable to authenticated user');
$this->assertFalse($file->access('download', $account), 'Private file is not downloadable to authenticated user');
@@ -0,0 +1,58 @@
<?php
namespace Drupal\Tests\file\Functional\Formatter;
use Drupal\entity_test\Entity\EntityTest;
use Drupal\file\Entity\File;
/**
* @coversDefaultClass \Drupal\file\Plugin\Field\FieldFormatter\FileAudioFormatter
* @group file
*/
class FileAudioFormatterTest extends FileMediaFormatterTestBase {
/**
* @covers ::viewElements
*
* @dataProvider dataProvider
*/
public function testRender($tag_count, $formatter_settings) {
$field_config = $this->createMediaField('file_audio', 'mp3', $formatter_settings);
file_put_contents('public://file.mp3', str_repeat('t', 10));
$file1 = File::create([
'uri' => 'public://file.mp3',
'filename' => 'file.mp3',
]);
$file1->save();
$file2 = File::create([
'uri' => 'public://file.mp3',
'filename' => 'file.mp3',
]);
$file2->save();
$entity = EntityTest::create([
$field_config->getName() => [
[
'target_id' => $file1->id(),
],
[
'target_id' => $file2->id(),
],
],
]);
$entity->save();
$this->drupalGet($entity->toUrl());
$file1_url = file_url_transform_relative(file_create_url($file1->getFileUri()));
$file2_url = file_url_transform_relative(file_create_url($file2->getFileUri()));
$assert_session = $this->assertSession();
$assert_session->elementsCount('css', 'audio[controls="controls"]', $tag_count);
$assert_session->elementExists('css', "audio > source[src='$file1_url'][type='audio/mpeg']");
$assert_session->elementExists('css', "audio > source[src='$file2_url'][type='audio/mpeg']");
}
}
@@ -0,0 +1,93 @@
<?php
namespace Drupal\Tests\file\Functional\Formatter;
use Drupal\Component\Utility\Unicode;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\field\Entity\FieldConfig;
use Drupal\field\Entity\FieldStorageConfig;
use Drupal\Tests\BrowserTestBase;
/**
* Provides methods specifically for testing File module's media formatter's.
*/
abstract class FileMediaFormatterTestBase extends BrowserTestBase {
/**
* {@inheritdoc}
*/
protected static $modules = [
'entity_test',
'field',
'file',
'user',
'system',
];
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
$this->drupalLogin($this->drupalCreateUser(['view test entity']));
}
/**
* Creates a file field and set's the correct formatter.
*
* @param string $formatter
* The formatter ID.
* @param string $file_extensions
* The file extensions of the new field.
* @param array $formatter_settings
* Settings for the formatter.
*
* @return \Drupal\field\Entity\FieldConfig
* Newly created file field.
*/
protected function createMediaField($formatter, $file_extensions, array $formatter_settings = []) {
$entity_type = $bundle = 'entity_test';
$field_name = Unicode::strtolower($this->randomMachineName());
FieldStorageConfig::create([
'entity_type' => $entity_type,
'field_name' => $field_name,
'type' => 'file',
'cardinality' => FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED,
])->save();
$field_config = FieldConfig::create([
'entity_type' => $entity_type,
'field_name' => $field_name,
'bundle' => $bundle,
'settings' => [
'file_extensions' => trim($file_extensions),
],
]);
$field_config->save();
$display = entity_get_display('entity_test', 'entity_test', 'full');
$display->setComponent($field_name, [
'type' => $formatter,
'settings' => $formatter_settings,
])->save();
return $field_config;
}
/**
* Data provider for testRender.
*
* @return array
* An array of data arrays.
* The data array contains:
* - The number of expected HTML tags.
* - An array of settings for the field formatter.
*/
public function dataProvider() {
return [
[2, []],
[1, ['multiple_file_display_type' => 'sources']],
];
}
}
@@ -0,0 +1,58 @@
<?php
namespace Drupal\Tests\file\Functional\Formatter;
use Drupal\entity_test\Entity\EntityTest;
use Drupal\file\Entity\File;
/**
* @coversDefaultClass \Drupal\file\Plugin\Field\FieldFormatter\FileVideoFormatter
* @group file
*/
class FileVideoFormatterTest extends FileMediaFormatterTestBase {
/**
* @covers ::viewElements
*
* @dataProvider dataProvider
*/
public function testRender($tag_count, $formatter_settings) {
$field_config = $this->createMediaField('file_video', 'mp4', $formatter_settings);
file_put_contents('public://file.mp4', str_repeat('t', 10));
$file1 = File::create([
'uri' => 'public://file.mp4',
'filename' => 'file.mp4',
]);
$file1->save();
$file2 = File::create([
'uri' => 'public://file.mp4',
'filename' => 'file.mp4',
]);
$file2->save();
$entity = EntityTest::create([
$field_config->getName() => [
[
'target_id' => $file1->id(),
],
[
'target_id' => $file2->id(),
],
],
]);
$entity->save();
$this->drupalGet($entity->toUrl());
$file1_url = file_url_transform_relative(file_create_url($file1->getFileUri()));
$file2_url = file_url_transform_relative(file_create_url($file2->getFileUri()));
$assert_session = $this->assertSession();
$assert_session->elementsCount('css', 'video[controls="controls"]', $tag_count);
$assert_session->elementExists('css', "video > source[src='$file1_url'][type='video/mp4']");
$assert_session->elementExists('css', "video > source[src='$file2_url'][type='video/mp4']");
}
}
@@ -0,0 +1,91 @@
<?php
namespace Drupal\Tests\file\Kernel;
use Drupal\Core\Field\FieldItemInterface;
use Drupal\Core\TypedData\DataDefinitionInterface;
use Drupal\file\FileInterface;
use Drupal\file\ComputedFileUrl;
use Drupal\KernelTests\KernelTestBase;
/**
* @coversDefaultClass \Drupal\file\ComputedFileUrl
*
* @group file
*/
class ComputedFileUrlTest extends KernelTestBase {
/**
* The test URL to use.
*
* @var string
*/
protected $testUrl = 'public://druplicon.txt';
/**
* @covers ::getValue
*/
public function testGetValue() {
$entity = $this->prophesize(FileInterface::class);
$entity->getFileUri()
->willReturn($this->testUrl);
$parent = $this->prophesize(FieldItemInterface::class);
$parent->getEntity()
->shouldBeCalledTimes(2)
->willReturn($entity->reveal());
$definition = $this->prophesize(DataDefinitionInterface::class);
$typed_data = new ComputedFileUrl($definition->reveal(), $this->randomMachineName(), $parent->reveal());
$expected = base_path() . $this->siteDirectory . '/files/druplicon.txt';
$this->assertSame($expected, $typed_data->getValue());
// Do this a second time to confirm the same value is returned but the value
// isn't retrieved from the parent entity again.
$this->assertSame($expected, $typed_data->getValue());
}
/**
* @covers ::setValue
*/
public function testSetValue() {
$name = $this->randomMachineName();
$parent = $this->prophesize(FieldItemInterface::class);
$parent->onChange($name)
->shouldBeCalled();
$definition = $this->prophesize(DataDefinitionInterface::class);
$typed_data = new ComputedFileUrl($definition->reveal(), $name, $parent->reveal());
// Setting the value explicitly should mean the parent entity is never
// called into.
$typed_data->setValue($this->testUrl);
$this->assertSame($this->testUrl, $typed_data->getValue());
// Do this a second time to confirm the same value is returned but the value
// isn't retrieved from the parent entity again.
$this->assertSame($this->testUrl, $typed_data->getValue());
}
/**
* @covers ::setValue
*/
public function testSetValueNoNotify() {
$name = $this->randomMachineName();
$parent = $this->prophesize(FieldItemInterface::class);
$parent->onChange($name)
->shouldNotBeCalled();
$definition = $this->prophesize(DataDefinitionInterface::class);
$typed_data = new ComputedFileUrl($definition->reveal(), $name, $parent->reveal());
// Setting the value should explicitly should mean the parent entity is
// never called into.
$typed_data->setValue($this->testUrl, FALSE);
$this->assertSame($this->testUrl, $typed_data->getValue());
}
}
@@ -10,6 +10,7 @@ use Drupal\field\Entity\FieldConfig;
use Drupal\Tests\field\Kernel\FieldKernelTestBase;
use Drupal\field\Entity\FieldStorageConfig;
use Drupal\file\Entity\File;
use Drupal\user\Entity\Role;
/**
* Tests using entity fields of the file field type.
@@ -42,6 +43,14 @@ class FileItemTest extends FieldKernelTestBase {
protected function setUp() {
parent::setUp();
$this->installEntitySchema('user');
$this->installConfig(['user']);
// Give anonymous users permission to access content, so they can view and
// download public files.
$anonymous_role = Role::load(Role::ANONYMOUS_ID);
$anonymous_role->grantPermission('access content');
$anonymous_role->save();
$this->installEntitySchema('file');
$this->installSchema('file', ['file_usage']);
@@ -0,0 +1,40 @@
<?php
namespace Drupal\Tests\file\Kernel;
use Drupal\file\Entity\File;
/**
* File URI field item test.
*
* @group file
*
* @see \Drupal\file\Plugin\Field\FieldType\FileUriItem
* @see \Drupal\file\FileUrl
*/
class FileUriItemTest extends FileManagedUnitTestBase {
/**
* Tests the file entity override of the URI field.
*/
public function testCustomFileUriField() {
$uri = 'public://druplicon.txt';
// Create a new file entity.
$file = File::create([
'uid' => 1,
'filename' => 'druplicon.txt',
'uri' => $uri,
'filemime' => 'text/plain',
'status' => FILE_STATUS_PERMANENT,
]);
file_put_contents($file->getFileUri(), 'hello world');
$file->save();
$this->assertSame($uri, $file->uri->value);
$expected_url = base_path() . $this->siteDirectory . '/files/druplicon.txt';
$this->assertSame($expected_url, $file->uri->url);
}
}
@@ -16,7 +16,7 @@ class MigrateUploadTest extends MigrateDrupal6TestBase {
/**
* {@inheritdoc}
*/
public static $modules = ['menu_ui'];
public static $modules = ['language', 'menu_ui'];
/**
* {@inheritdoc}
@@ -51,7 +51,7 @@ class MigrateUploadTest extends MigrateDrupal6TestBase {
}
$this->prepareMigrations($id_mappings);
$this->migrateContent();
$this->migrateContent(['translations']);
// Since we are only testing a subset of the file migration, do not check
// that the full file migration has been run.
$migration = $this->getMigration('d6_upload');
@@ -65,16 +65,18 @@ class MigrateUploadTest extends MigrateDrupal6TestBase {
public function testUpload() {
$this->container->get('entity.manager')
->getStorage('node')
->resetCache([1, 2]);
->resetCache([1, 2, 12]);
$nodes = Node::loadMultiple([1, 2]);
$nodes = Node::loadMultiple([1, 2, 12]);
$node = $nodes[1];
$this->assertEquals('en', $node->langcode->value);
$this->assertIdentical(1, count($node->upload));
$this->assertIdentical('1', $node->upload[0]->target_id);
$this->assertIdentical('file 1-1-1', $node->upload[0]->description);
$this->assertIdentical(FALSE, $node->upload[0]->isDisplayed());
$node = $nodes[2];
$this->assertEquals('en', $node->langcode->value);
$this->assertIdentical(2, count($node->upload));
$this->assertIdentical('3', $node->upload[0]->target_id);
$this->assertIdentical('file 2-3-3', $node->upload[0]->description);
@@ -82,6 +84,13 @@ class MigrateUploadTest extends MigrateDrupal6TestBase {
$this->assertIdentical('2', $node->upload[1]->target_id);
$this->assertIdentical(TRUE, $node->upload[1]->isDisplayed());
$this->assertIdentical('file 2-3-2', $node->upload[1]->description);
$node = $nodes[12];
$this->assertEquals('zu', $node->langcode->value);
$this->assertEquals(1, count($node->upload));
$this->assertEquals('3', $node->upload[0]->target_id);
$this->assertEquals('file 12-15-3', $node->upload[0]->description);
$this->assertEquals(FALSE, $node->upload[0]->isDisplayed());
}
}
@@ -20,6 +20,7 @@ class CckFileTest extends MigrateDrupalTestBase {
* Tests configurability of file migration name.
*
* @covers ::__construct
* @expectedDeprecation CckFile is deprecated in Drupal 8.3.x and will be be removed before Drupal 9.0.x. Use \Drupal\file\Plugin\migrate\process\d6\FieldFile instead.
*/
public function testConfigurableFileMigration() {
$migration = Migration::create($this->container, [], 'custom_migration', []);
@@ -34,6 +34,14 @@ class UploadTest extends MigrateSqlSourceTestBase {
'list' => '0',
'weight' => '-1',
],
[
'fid' => '3',
'nid' => '12',
'vid' => '15',
'description' => 'file 12-15-3',
'list' => '0',
'weight' => '0',
],
];
$tests[0]['source_data']['node'] = [
@@ -54,6 +62,23 @@ class UploadTest extends MigrateSqlSourceTestBase {
'tnid' => '0',
'translate' => '0',
],
[
'nid' => '12',
'vid' => '15',
'type' => 'page',
'language' => 'zu',
'title' => 'Abantu zulu',
'uid' => '1',
'status' => '1',
'created' => '1444238800',
'changed' => '1444238808',
'comment' => '0',
'promote' => '0',
'moderate' => '0',
'sticky' => '0',
'tnid' => '12',
'translate' => '0',
],
];
// The expected results.
@@ -66,10 +91,24 @@ class UploadTest extends MigrateSqlSourceTestBase {
'list' => '0',
],
],
'language' => '',
'nid' => '1',
'vid' => '1',
'type' => 'story',
],
[
'upload' => [
[
'fid' => '3',
'description' => 'file 12-15-3',
'list' => '0',
],
],
'language' => 'zu',
'nid' => '12',
'vid' => '15',
'type' => 'page',
],
];
return $tests;
@@ -0,0 +1,60 @@
<?php
namespace Drupal\Tests\file\Unit\Plugin\migrate\field\d6;
use Drupal\migrate\Plugin\MigrationInterface;
use Drupal\Tests\UnitTestCase;
use Drupal\file\Plugin\migrate\field\d6\ImageField;
use Prophecy\Argument;
/**
* @coversDefaultClass \Drupal\file\Plugin\migrate\field\d6\ImageField
* @group file
* @group legacy
*/
class ImageFieldTest extends UnitTestCase {
/**
* @var \Drupal\migrate_drupal\Plugin\MigrateFieldInterface
*/
protected $plugin;
/**
* @var \Drupal\migrate\Plugin\MigrationInterface
*/
protected $migration;
/**
* {@inheritdoc}
*/
protected function setUp() {
$this->plugin = new ImageField([], 'image', []);
$migration = $this->prophesize(MigrationInterface::class);
// The plugin's processFieldValues() method will call
// mergeProcessOfProperty() and return nothing. So, in order to examine the
// process pipeline created by the plugin, we need to ensure that
// getProcess() always returns the last input to mergeProcessOfProperty().
$migration->mergeProcessOfProperty(Argument::type('string'), Argument::type('array'))
->will(function ($arguments) use ($migration) {
$migration->getProcess()->willReturn($arguments[1]);
});
$this->migration = $migration->reveal();
}
/**
* @covers ::processFieldValues
* @expectedDeprecation ImageField is deprecated in Drupal 8.5.x and will be removed before Drupal 9.0.x. Use \Drupal\image\Plugin\migrate\field\d6\ImageField instead. See https://www.drupal.org/node/2936061.
*/
public function testProcessFieldValues() {
$this->plugin->processFieldValues($this->migration, 'somefieldname', []);
$expected = [
'plugin' => 'd6_field_file',
'source' => 'somefieldname',
];
$this->assertSame($expected, $this->migration->getProcess());
}
}
@@ -10,6 +10,7 @@ use Prophecy\Argument;
/**
* @coversDefaultClass \Drupal\file\Plugin\migrate\field\d7\ImageField
* @group file
* @group legacy
*/
class ImageFieldTest extends UnitTestCase {
@@ -44,6 +45,7 @@ class ImageFieldTest extends UnitTestCase {
/**
* @covers ::processFieldValues
* @expectedDeprecation ImageField is deprecated in Drupal 8.5.x and will be removed before Drupal 9.0.x. Use \Drupal\image\Plugin\migrate\field\d7\ImageField instead. See https://www.drupal.org/node/2936061.
*/
public function testProcessFieldValues() {
$this->plugin->processFieldValues($this->migration, 'somefieldname', []);
@@ -17,6 +17,8 @@ class CckFileTest extends UnitTestCase {
/**
* Tests that alt and title attributes are included in transformed values.
*
* @expectedDeprecation CckFile is deprecated in Drupal 8.3.x and will be be removed before Drupal 9.0.x. Use \Drupal\file\Plugin\migrate\process\d6\FieldFile instead.
*/
public function testTransformAltTitle() {
$executable = $this->prophesize(MigrateExecutableInterface::class)->reveal();
@@ -4,7 +4,6 @@ namespace Drupal\Tests\file\Unit\Plugin\migrate\process\d6;
use Drupal\file\Plugin\migrate\process\d6\FileUri;
use Drupal\migrate\MigrateExecutable;
use Drupal\migrate\MigrateMessage;
use Drupal\migrate\Row;
use Drupal\Tests\migrate\Unit\MigrateTestCase;
@@ -69,7 +68,7 @@ class FileUriTest extends MigrateTestCase {
}
protected function doTransform(array $value) {
$executable = new MigrateExecutable($this->getMigration(), new MigrateMessage());
$executable = new MigrateExecutable($this->getMigration());
$row = new Row();
return (new FileUri([], 'file_uri', []))