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
+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([