Update to drupal 8.0.0-rc1. For more information, see https://www.drupal.org/node/2582663

This commit is contained in:
Greg Anderson 2015-10-08 11:40:12 -07:00
parent eb34d130a8
commit f32e58e4b1
8476 changed files with 211648 additions and 170042 deletions

View file

@ -52,8 +52,8 @@ display:
id: 0
total_pages: 0
tags:
previous: ' previous'
next: 'next '
previous: ' Previous'
next: 'Next '
expose:
items_per_page: false
items_per_page_label: 'Items per page'
@ -395,8 +395,8 @@ display:
type: boolean
settings:
format: custom
format_custom_false: 'Temporary'
format_custom_true: 'Permanent'
format_custom_false: Temporary
format_custom_true: Permanent
plugin_id: field
entity_type: file
entity_field: status
@ -718,9 +718,13 @@ display:
display_extenders: { }
cache_metadata:
contexts:
- languages
- 'languages:language_content'
- 'languages:language_interface'
- url
cacheable: false
- url.query_args
- user.permissions
max-age: 0
tags: { }
page_1:
display_plugin: page
id: page_1
@ -751,9 +755,13 @@ display:
display_extenders: { }
cache_metadata:
contexts:
- languages
- 'languages:language_content'
- 'languages:language_interface'
- url
cacheable: false
- url.query_args
- user.permissions
max-age: 0
tags: { }
page_2:
display_plugin: page
id: page_2
@ -783,8 +791,8 @@ display:
id: 0
total_pages: 0
tags:
previous: ' previous'
next: 'next '
previous: ' Previous'
next: 'Next '
expose:
items_per_page: false
items_per_page_label: 'Items per page'
@ -1019,7 +1027,7 @@ display:
title_enable: false
title: All
title_enable: true
title: 'File usage information for %1'
title: 'File usage information for {{ arguments.fid }}'
default_argument_type: fixed
default_argument_options:
argument: ''
@ -1105,6 +1113,9 @@ display:
display_extenders: { }
cache_metadata:
contexts:
- languages
- 'languages:language_interface'
- url
cacheable: false
- url.query_args
- user.permissions
max-age: 0
tags: { }

View file

@ -1,62 +0,0 @@
/**
* @file
* Default style for file module.
*/
/* File icons.*/
.file {
padding-left: 20px; /* LTR */
display: inline-block;
min-height: 16px;
background-repeat: no-repeat;
background-position: left center; /* LTR */
}
[dir="rtl"] .file {
padding-left: inherit;
padding-right: 20px;
background-position: right center;
}
.file--general,
.file--application-octet-stream {
background-image: url(../icons/application-octet-stream.png);
}
.file--package-x-generic {
background-image: url(../icons/package-x-generic.png);
}
.file--x-office-spreadsheet {
background-image: url(../icons/x-office-spreadsheet.png);
}
.file--x-office-document {
background-image: url(../icons/x-office-document.png);
}
.file--x-office-presentation {
background-image: url(../icons/x-office-presentation.png);
}
.file--text-x-script {
background-image: url(../icons/text-x-script.png);
}
.file--text-html {
background-image: url(../icons/text-html.png);
}
.file--text-plain {
background-image: url(../icons/text-plain.png);
}
.file--application-pdf {
background-image: url(../icons/application-pdf.png);
}
.file--application-x-executable {
background-image: url(../icons/application-x-executable.png);
}
.file--audio {
background-image: url(../icons/audio-x-generic.png);
}
.file--video {
background-image: url(../icons/video-x-generic.png);
}
.file--text {
background-image: url(../icons/text-x-generic.png);
}
.file--image {
background-image: url(../icons/image-x-generic.png);
}

View file

@ -7,7 +7,7 @@
use Drupal\Component\Utility\Html;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\FieldFilteredString;
use Drupal\Core\Field\FieldFilteredMarkup;
use Drupal\Core\Render\Element;
/**
@ -169,7 +169,7 @@ function template_preprocess_file_upload_help(&$variables) {
$descriptions = array();
if (!empty($description)) {
$descriptions[] = FieldFilteredString::create($description);
$descriptions[] = FieldFilteredMarkup::create($description);
}
if (isset($cardinality)) {
if ($cardinality == -1) {
@ -180,7 +180,7 @@ function template_preprocess_file_upload_help(&$variables) {
}
}
if (isset($upload_validators['file_validate_size'])) {
$descriptions[] = t('!size limit.', array('!size' => format_size($upload_validators['file_validate_size'][0])));
$descriptions[] = t('@size limit.', array('@size' => format_size($upload_validators['file_validate_size'][0])));
}
if (isset($upload_validators['file_validate_extensions'])) {
$descriptions[] = t('Allowed types: @extensions.', array('@extensions' => $upload_validators['file_validate_extensions'][0]));

View file

@ -98,18 +98,18 @@ function file_requirements($phase) {
}
elseif (!$implementation && extension_loaded('apc')) {
$value = t('Not enabled');
$description = t('Your server is capable of displaying file upload progress through APC, but it is not enabled. Add <code>apc.rfc1867 = 1</code> to your php.ini configuration. Alternatively, it is recommended to use <a href="@url">PECL uploadprogress</a>, which supports more than one simultaneous upload.', array('@url' => 'http://pecl.php.net/package/uploadprogress'));
$description = t('Your server is capable of displaying file upload progress through APC, but it is not enabled. Add <code>apc.rfc1867 = 1</code> to your php.ini configuration. Alternatively, it is recommended to use <a href=":url">PECL uploadprogress</a>, which supports more than one simultaneous upload.', array(':url' => 'http://pecl.php.net/package/uploadprogress'));
}
elseif (!$implementation) {
$value = t('Not enabled');
$description = t('Your server is capable of displaying file upload progress, but does not have the required libraries. It is recommended to install the <a href="@uploadprogress_url">PECL uploadprogress library</a> (preferred) or to install <a href="@apc_url">APC</a>.', array('@uploadprogress_url' => 'http://pecl.php.net/package/uploadprogress', '@apc_url' => 'http://php.net/apc'));
$description = t('Your server is capable of displaying file upload progress, but does not have the required libraries. It is recommended to install the <a href=":uploadprogress_url">PECL uploadprogress library</a> (preferred) or to install <a href=":apc_url">APC</a>.', array(':uploadprogress_url' => 'http://pecl.php.net/package/uploadprogress', ':apc_url' => 'http://php.net/apc'));
}
elseif ($implementation == 'apc') {
$value = t('Enabled (<a href="@url">APC RFC1867</a>)', array('@url' => 'http://php.net/manual/apc.configuration.php#ini.apc.rfc1867'));
$description = t('Your server is capable of displaying file upload progress using APC RFC1867. Note that only one upload at a time is supported. It is recommended to use the <a href="@url">PECL uploadprogress library</a> if possible.', array('@url' => 'http://pecl.php.net/package/uploadprogress'));
$value = t('Enabled (<a href=":url">APC RFC1867</a>)', array(':url' => 'http://php.net/manual/apc.configuration.php#ini.apc.rfc1867'));
$description = t('Your server is capable of displaying file upload progress using APC RFC1867. Note that only one upload at a time is supported. It is recommended to use the <a href=":url">PECL uploadprogress library</a> if possible.', array(':url' => 'http://pecl.php.net/package/uploadprogress'));
}
elseif ($implementation == 'uploadprogress') {
$value = t('Enabled (<a href="@url">PECL uploadprogress</a>)', array('@url' => 'http://pecl.php.net/package/uploadprogress'));
$value = t('Enabled (<a href=":url">PECL uploadprogress</a>)', array(':url' => 'http://pecl.php.net/package/uploadprogress'));
}
$requirements['file_progress'] = array(
'title' => t('Upload progress'),

View file

@ -12,10 +12,3 @@ drupal.file:
- core/jquery.once
- core/drupal
- core/drupalSettings
drupal.file.formatter.generic:
version: VERSION
css:
theme:
css/file.theme.css: {}

View file

@ -5,7 +5,6 @@
* Defines a "managed_file" Form API field and a "file" field for Field module.
*/
use Drupal\Component\Utility\Html;
use Drupal\Core\Datetime\Entity\DateFormat;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Form\FormStateInterface;
@ -32,15 +31,15 @@ function file_help($route_name, RouteMatchInterface $route_match) {
case 'help.page.file':
$output = '';
$output .= '<h3>' . t('About') . '</h3>';
$output .= '<p>' . t('The File module allows you to create fields that contain files. See the <a href="!field">Field module help</a> and the <a href="!field_ui">Field UI help</a> pages for general information on fields and how to create and manage them. For more information, see the <a href="!file_documentation">online documentation for the File module</a>.', array('!field' => \Drupal::url('help.page', array('name' => 'field')), '!field_ui' => (\Drupal::moduleHandler()->moduleExists('field_ui')) ? \Drupal::url('help.page', array('name' => 'field_ui')) :'#', '!file_documentation' => 'https://www.drupal.org/documentation/modules/file')) . '</p>';
$output .= '<p>' . t('The File module allows you to create fields that contain files. See the <a href=":field">Field module help</a> and the <a href=":field_ui">Field UI help</a> pages for general information on fields and how to create and manage them. For more information, see the <a href=":file_documentation">online documentation for the File module</a>.', array(':field' => \Drupal::url('help.page', array('name' => 'field')), ':field_ui' => (\Drupal::moduleHandler()->moduleExists('field_ui')) ? \Drupal::url('help.page', array('name' => 'field_ui')) :'#', ':file_documentation' => 'https://www.drupal.org/documentation/modules/file')) . '</p>';
$output .= '<h3>' . t('Uses') . '</h3>';
$output .= '<dl>';
$output .= '<dt>' . t('Managing and displaying file fields') . '</dt>';
$output .= '<dd>' . t('The <em>settings</em> and the <em>display</em> of the file field can be configured separately. See the <a href="!field_ui">Field UI help</a> for more information on how to manage fields and their display.', array('!field_ui' => (\Drupal::moduleHandler()->moduleExists('field_ui')) ? \Drupal::url('help.page', array('name' => 'field_ui')) : '#')) . '</dd>';
$output .= '<dd>' . t('The <em>settings</em> and the <em>display</em> of the file field can be configured separately. See the <a href=":field_ui">Field UI help</a> for more information on how to manage fields and their display.', array(':field_ui' => (\Drupal::moduleHandler()->moduleExists('field_ui')) ? \Drupal::url('help.page', array('name' => 'field_ui')) : '#')) . '</dd>';
$output .= '<dt>' . t('Allowing file extensions') . '</dt>';
$output .= '<dd>' . t('In the field settings, you can define the allowed file extensions (for example <em>pdf docx psd</em>) for the files that will be uploaded with the file field.') . '</dd>';
$output .= '<dt>' . t('Storing files ') . '</dt>';
$output .= '<dd>' . t('Uploaded files can either be stored as <em>public</em> or <em>private</em>, depending on the <a href="!file-system">File system settings</a>. For more information, see the <a href="!system-help">System module help page</a>.', array('!file-system' => \Drupal::url('system.file_system_settings'), '!system-help' => \Drupal::url('help.page', array('name' => 'system')))) . '</dd>';
$output .= '<dd>' . t('Uploaded files can either be stored as <em>public</em> or <em>private</em>, depending on the <a href=":file-system">File system settings</a>. For more information, see the <a href=":system-help">System module help page</a>.', array(':file-system' => \Drupal::url('system.file_system_settings'), ':system-help' => \Drupal::url('help.page', array('name' => 'system')))) . '</dd>';
$output .= '<dt>' . t('Restricting the maximum file size') . '</dt>';
$output .= '<dd>' . t('The maximum file size that users can upload is limited by PHP settings of the server, but you can restrict by entering the desired value as the <em>Maximum upload size</em> setting. The maximum file size is automatically displayed to users in the help text of the file field.') . '</dd>';
$output .= '<dt>' . t('Displaying files and descriptions') . '<dt>';
@ -402,7 +401,7 @@ function file_validate_is_image(FileInterface $file) {
/**
* Verifies that image dimensions are within the specified maximum and minimum.
*
* Non-image files will be ignored. If a image toolkit is available the image
* Non-image files will be ignored. If an image toolkit is available the image
* will be scaled to fit within the desired maximum dimensions.
*
* @param \Drupal\file\FileInterface $file
@ -951,7 +950,6 @@ function file_tokens($type, $tokens, array $data, array $options, BubbleableMeta
else {
$langcode = NULL;
}
$sanitize = !empty($options['sanitize']);
$replacements = array();
@ -968,15 +966,15 @@ function file_tokens($type, $tokens, array $data, array $options, BubbleableMeta
// Essential file data
case 'name':
$replacements[$original] = $sanitize ? Html::escape($file->getFilename()) : $file->getFilename();
$replacements[$original] = $file->getFilename();
break;
case 'path':
$replacements[$original] = $sanitize ? Html::escape($file->getFileUri()) : $file->getFileUri();
$replacements[$original] = $file->getFileUri();
break;
case 'mime':
$replacements[$original] = $sanitize ? Html::escape($file->getMimeType()) : $file->getMimeType();
$replacements[$original] = $file->getMimeType();
break;
case 'size':
@ -984,7 +982,7 @@ function file_tokens($type, $tokens, array $data, array $options, BubbleableMeta
break;
case 'url':
$replacements[$original] = $sanitize ? Html::escape(file_create_url($file->getFileUri())) : file_create_url($file->getFileUri());
$replacements[$original] = file_create_url($file->getFileUri());
break;
// These tokens are default variations on the chained tokens handled below.
@ -1004,7 +1002,7 @@ function file_tokens($type, $tokens, array $data, array $options, BubbleableMeta
$owner = $file->getOwner();
$bubbleable_metadata->addCacheableDependency($owner);
$name = $owner->label();
$replacements[$original] = $sanitize ? Html::escape($name) : $name;
$replacements[$original] = $name;
break;
}
}
@ -1182,7 +1180,7 @@ function file_managed_file_save_upload($element, FormStateInterface $form_state)
if ($files_uploaded) {
if (!$files = file_save_upload($upload_name, $element['#upload_validators'], $destination)) {
\Drupal::logger('file')->notice('The file upload failed. %upload', array('%upload' => $upload_name));
$form_state->setError($element, t('Files in the !name field were unable to be uploaded.', array('!name' => $element['#title'])));
$form_state->setError($element, t('Files in the @name field were unable to be uploaded.', array('@name' => $element['#title'])));
return array();
}

View file

@ -24,7 +24,7 @@ function file_field_views_data(FieldStorageConfigInterface $field_storage) {
'base' => 'file_managed',
'entity type' => 'file',
'base field' => 'fid',
'label' => t('file from !field_name', array('!field_name' => $field_storage->getName())),
'label' => t('file from @field_name', array('@field_name' => $field_storage->getName())),
);
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 189 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 346 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 189 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 314 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 385 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 260 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 265 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 220 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 220 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 276 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 214 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 196 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 181 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 183 B

View file

@ -1,7 +1,7 @@
# Every migration that saves into {file_managed} must have the d6_file
# migration as an optional dependency to ensure d6_file runs first.
id: d6_file
label: Drupal 6 files
label: Files
migration_tags:
- Drupal 6
source:

View file

@ -1,5 +1,5 @@
id: d6_file_settings
label: Drupal 6 file configuration
label: File configuration
migration_tags:
- Drupal 6
source:

View file

@ -1,5 +1,5 @@
id: d6_upload
label: Drupal 6 file uploads
label: File uploads
migration_tags:
- Drupal 6
source:

View file

@ -1,5 +1,5 @@
id: d6_upload_entity_display
label: Drupal 6 upload display configuration
label: Upload display configuration
migration_tags:
- Drupal 6
source:
@ -19,7 +19,7 @@ process:
field_name: 'constants/name'
type: 'constants/type'
options: 'constants/options'
'options/type': @type
'options/type': '@type'
destination:
plugin: component_entity_display
migration_dependencies:

View file

@ -1,5 +1,5 @@
id: d6_upload_entity_form_display
label: Drupal 6 upload form display configuration
label: Upload form display configuration
migration_tags:
- Drupal 6
source:
@ -20,7 +20,7 @@ process:
form_mode: 'constants/form_mode'
type: 'constants/type'
options: 'constants/options'
'options/type': @type
'options/type': '@type'
destination:
plugin: component_entity_form_display
migration_dependencies:

View file

@ -1,5 +1,5 @@
id: d6_upload_field
label: Drupal 6 upload field configuration
label: Upload field configuration
migration_tags:
- Drupal 6
source:

View file

@ -1,5 +1,5 @@
id: d6_upload_field_instance
label: Drupal 6 upload field instance configuration
label: Upload field instance configuration
migration_tags:
- Drupal 6
source:

View file

@ -1,7 +1,7 @@
# Every migration that references a file by fid should specify this migration
# as an optional dependency.
id: d7_file
label: Drupal 7 files
label: Files
migration_tags:
- Drupal 7
source:

View file

@ -372,19 +372,25 @@ class ManagedFile extends FormElement {
if ($file->isPermanent()) {
$references = static::fileUsage()->listUsage($file);
if (empty($references)) {
$form_state->setError($element, t('The file used in the !name field may not be referenced.', ['!name' => $element['#title']]));
// We expect the field name placeholder value to be wrapped in t()
// here, so it won't be escaped again as it's already marked safe.
$form_state->setError($element, t('The file used in the @name field may not be referenced.', ['@name' => $element['#title']]));
}
}
}
else {
$form_state->setError($element, t('The file referenced by the !name field does not exist.', ['!name' => $element['#title']]));
// We expect the field name placeholder value to be wrapped in t()
// here, so it won't be escaped again as it's already marked safe.
$form_state->setError($element, t('The file referenced by the @name field does not exist.', ['@name' => $element['#title']]));
}
}
}
// Check required property based on the FID.
if ($element['#required'] && empty($element['fids']['#value']) && !in_array($clicked_button, ['upload_button', 'remove_button'])) {
$form_state->setError($element, t('!name is required.', ['!name' => $element['#title']]));
// We expect the field name placeholder value to be wrapped in t()
// here, so it won't be escaped again as it's already marked safe.
$form_state->setError($element, t('@name field is required.', ['@name' => $element['#title']]));
}
// Consolidate the array value of this field to array of FIDs.

View file

@ -110,13 +110,6 @@ class File extends ContentEntityBase implements FileInterface {
return $this->get('created')->value;
}
/**
* {@inheritdoc}
*/
public function getChangedTime() {
return $this->get('changed')->value;
}
/**
* {@inheritdoc}
*/

View file

@ -21,7 +21,7 @@ class FileAccessControlHandler extends EntityAccessControlHandler {
/**
* {@inheritdoc}
*/
protected function checkAccess(EntityInterface $entity, $operation, $langcode, AccountInterface $account) {
protected function checkAccess(EntityInterface $entity, $operation, AccountInterface $account) {
/** @var \Drupal\file\FileInterface $entity */
if ($operation == 'download' || $operation == 'view') {
if (\Drupal::service('file_system')->uriScheme($entity->getFileUri()) === 'public') {

View file

@ -7,7 +7,7 @@
namespace Drupal\file\Plugin\EntityReferenceSelection;
use Drupal\Core\Entity\Plugin\EntityReferenceSelection\SelectionBase;
use Drupal\Core\Entity\Plugin\EntityReferenceSelection\DefaultSelection;
/**
* Provides specific access control for the file entity type.
@ -20,7 +20,7 @@ use Drupal\Core\Entity\Plugin\EntityReferenceSelection\SelectionBase;
* weight = 1
* )
*/
class FileSelection extends SelectionBase {
class FileSelection extends DefaultSelection {
/**
* {@inheritdoc}

View file

@ -46,7 +46,7 @@ abstract class BaseFieldFileFormatterBase extends FormatterBase {
/**
* {@inheritdoc}
*/
public function viewElements(FieldItemListInterface $items) {
public function viewElements(FieldItemListInterface $items, $langcode) {
$elements = [];
$url = NULL;

View file

@ -34,7 +34,7 @@ class FileSize extends FormatterBase {
/**
* {@inheritdoc}
*/
public function viewElements(FieldItemListInterface $items) {
public function viewElements(FieldItemListInterface $items, $langcode) {
$elements = [];
foreach ($items as $delta => $item) {

View file

@ -25,10 +25,10 @@ class GenericFileFormatter extends FileFormatterBase {
/**
* {@inheritdoc}
*/
public function viewElements(FieldItemListInterface $items) {
public function viewElements(FieldItemListInterface $items, $langcode) {
$elements = array();
foreach ($this->getEntitiesToView($items) as $delta => $file) {
foreach ($this->getEntitiesToView($items, $langcode) as $delta => $file) {
$item = $file->_referringItem;
$elements[$delta] = array(
'#theme' => 'file_link',
@ -47,11 +47,6 @@ class GenericFileFormatter extends FileFormatterBase {
unset($item->_attributes);
}
}
if (!empty($elements)) {
$elements['#attached'] = array(
'library' => array('file/drupal.file.formatter.generic'),
);
}
return $elements;
}

View file

@ -25,11 +25,11 @@ class RSSEnclosureFormatter extends FileFormatterBase {
/**
* {@inheritdoc}
*/
public function viewElements(FieldItemListInterface $items) {
public function viewElements(FieldItemListInterface $items, $langcode) {
$entity = $items->getEntity();
// Add the first file as an enclosure to the RSS item. RSS allows only one
// enclosure per item. See: http://en.wikipedia.org/wiki/RSS_enclosure
foreach ($this->getEntitiesToView($items) as $delta => $file) {
foreach ($this->getEntitiesToView($items, $langcode) as $delta => $file) {
$entity->rss_elements[] = array(
'key' => 'enclosure',
'attributes' => array(

View file

@ -25,10 +25,10 @@ class TableFormatter extends FileFormatterBase {
/**
* {@inheritdoc}
*/
public function viewElements(FieldItemListInterface $items) {
public function viewElements(FieldItemListInterface $items, $langcode) {
$elements = array();
if ($files = $this->getEntitiesToView($items)) {
if ($files = $this->getEntitiesToView($items, $langcode)) {
$header = array(t('Attachment'), t('Size'));
$rows = array();
foreach ($files as $delta => $file) {

View file

@ -25,10 +25,10 @@ class UrlPlainFormatter extends FileFormatterBase {
/**
* {@inheritdoc}
*/
public function viewElements(FieldItemListInterface $items) {
public function viewElements(FieldItemListInterface $items, $langcode) {
$elements = array();
foreach ($this->getEntitiesToView($items) as $delta => $file) {
foreach ($this->getEntitiesToView($items, $langcode) as $delta => $file) {
$elements[$delta] = array(
'#markup' => file_create_url($file->getFileUri()),
'#cache' => array(

View file

@ -54,7 +54,9 @@ class FileFieldItemList extends EntityReferenceFieldItemList {
// Get the file IDs attached to the field before this update.
$field_name = $this->getFieldDefinition()->getName();
$original_ids = array();
$original_items = $entity->original->getTranslation($this->getLangcode())->$field_name;
$langcode = $this->getLangcode();
$original = $entity->original;
$original_items = $original->hasTranslation($langcode) ? $original->getTranslation($langcode)->{$field_name} : $original->{$field_name};
foreach ($original_items as $item) {
$original_ids[] = $item->target_id;
}

View file

@ -8,6 +8,7 @@
namespace Drupal\file\Plugin\Field\FieldType;
use Drupal\Component\Utility\Bytes;
use Drupal\Component\Render\PlainTextOutput;
use Drupal\Component\Utility\Random;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
@ -249,7 +250,7 @@ class FileItem extends EntityReferenceItem {
*/
public static function validateMaxFilesize($element, FormStateInterface $form_state) {
if (!empty($element['#value']) && !is_numeric(Bytes::toInt($element['#value']))) {
$form_state->setError($element, t('The "!name" option must contain a valid value. You may either leave the text field empty or enter a string like "512" (bytes), "80 KB" (kilobytes) or "50 MB" (megabytes).', array('!name' => t($element['title']))));
$form_state->setError($element, t('The "@name" option must contain a valid value. You may either leave the text field empty or enter a string like "512" (bytes), "80 KB" (kilobytes) or "50 MB" (megabytes).', array('@name' => $element['title'])));
}
}
@ -260,7 +261,8 @@ class FileItem extends EntityReferenceItem {
* An array of token objects to pass to token_replace().
*
* @return string
* A file directory URI with tokens replaced.
* An unsanitized file directory URI with tokens replaced. The result of
* the token replacement is then converted to plain text and returned.
*
* @see token_replace()
*/
@ -268,9 +270,9 @@ class FileItem extends EntityReferenceItem {
$settings = $this->getSettings();
$destination = trim($settings['file_directory'], '/');
// Replace tokens.
$destination = \Drupal::token()->replace($destination, $data);
// Replace tokens. As the tokens might contain HTML we convert it to plain
// text.
$destination = PlainTextOutput::renderFromHtml(\Drupal::token()->replace($destination, $data));
return $settings['uri_scheme'] . '://' . $destination;
}
@ -309,8 +311,12 @@ class FileItem extends EntityReferenceItem {
$random = new Random();
$settings = $field_definition->getSettings();
// Prepare destination.
$dirname = $settings['uri_scheme'] . '://' . $settings['file_directory'];
file_prepare_directory($dirname, FILE_CREATE_DIRECTORY);
// Generate a file entity.
$destination = $settings['uri_scheme'] . '://' . $settings['file_directory'] . $random->name(10, TRUE) . '.txt';
$destination = $dirname . '/' . $random->name(10, TRUE) . '.txt';
$data = $random->paragraphs(3);
$file = file_save_data($data, $destination, FILE_EXISTS_ERROR);
$values = array(
@ -334,4 +340,11 @@ class FileItem extends EntityReferenceItem {
return TRUE;
}
/**
* {@inheritdoc}
*/
public static function getPreconfiguredOptions() {
return [];
}
}

View file

@ -9,7 +9,7 @@ namespace Drupal\file\Plugin\Field\FieldWidget;
use Drupal\Component\Utility\NestedArray;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\FieldFilteredString;
use Drupal\Core\Field\FieldFilteredMarkup;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\Core\Field\WidgetBase;
@ -119,7 +119,7 @@ class FileWidget extends WidgetBase implements ContainerFactoryPluginInterface {
}
$title = $this->fieldDefinition->getLabel();
$description = FieldFilteredString::create($this->fieldDefinition->getDescription());
$description = FieldFilteredMarkup::create($this->fieldDefinition->getDescription());
$elements = array();
@ -370,7 +370,10 @@ class FileWidget extends WidgetBase implements ContainerFactoryPluginInterface {
$item = $element['#value'];
$item['fids'] = $element['fids']['#value'];
$element['#theme'] = 'file_widget';
// Prevent the file widget from overriding the image widget.
if (!isset($element['#theme'])) {
$element['#theme'] = 'file_widget';
}
// Add the display field if enabled.
if ($element['#display_field']) {

View file

@ -73,6 +73,20 @@ class EntityFile extends EntityContentBase {
);
}
/**
* {@inheritdoc}
*/
protected function getEntity(Row $row, array $old_destination_id_values) {
$destination = $row->getDestinationProperty($this->configuration['destination_path_property']);
$entity = $this->storage->loadByProperties(['uri' => $destination]);
if ($entity) {
return reset($entity);
}
else {
return parent::getEntity($row, $old_destination_id_values);
}
}
/**
* {@inheritdoc}
*/

View file

@ -24,20 +24,19 @@ class FileUri extends ProcessPluginBase {
* {@inheritdoc}
*/
public function transform($value, MigrateExecutableInterface $migrate_executable, Row $row, $destination_property) {
list($filepath, $file_directory_path, $temp_directory_path, $is_public) = $value;
// Specific handling using $temp_directory_path for temporary files.
if (substr($filepath, 0, strlen($temp_directory_path)) === $temp_directory_path) {
$uri = preg_replace('/^' . preg_quote($temp_directory_path, '/') . '/', '', $filepath);
return "temporary://$uri";
return 'temporary://' . ltrim($uri, '/');
}
// Strip the files path from the uri instead of using basename
// so any additional folders in the path are preserved.
$uri = preg_replace('/^' . preg_quote($file_directory_path, '/') . '/', '', $filepath);
return $is_public ? "public://$uri" : "private://$uri";
return ($is_public ? 'public' : 'private') . '://' . ltrim($uri, '/');
}
}

View file

@ -44,18 +44,13 @@ class File extends DrupalSqlBase {
* {@inheritdoc}
*/
public function query() {
$query = $this->select('files', 'f')->fields('f', array(
'fid',
'uid',
'filename',
'filepath',
'filemime',
'filesize',
'status',
'timestamp',
));
$query->orderBy('timestamp');
return $query;
return $this->select('files', 'f')
->fields('f')
->orderBy('timestamp')
// If two or more files have the same timestamp, they'll end up in a
// non-deterministic order. Ordering by fid (or any other unique field)
// will prevent this.
->orderBy('fid');
}
/**

View file

@ -26,19 +26,23 @@ class UploadInstance extends DrupalSqlBase {
* {@inheritdoc}
*/
protected function initializeIterator() {
$prefix = 'upload';
$node_types = $this->getDatabase()->query('SELECT type FROM {node_type}')->fetchCol();
foreach ($node_types as $node_type) {
$variables[] = $prefix . '_' . $node_type;
}
$node_types = $this->select('node_type', 'nt')
->fields('nt', ['type'])
->execute()
->fetchCol();
$variables = array_map(function($type) { return 'upload_' . $type; }, $node_types);
$max_filesize = $this->variableGet('upload_uploadsize_default', 1);
$max_filesize = $max_filesize ? $max_filesize . 'MB' : '';
$file_extensions = $this->variableGet('upload_extensions_default', 'jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp');
$return = array();
$values = $this->getDatabase()->query('SELECT name, value FROM {variable} WHERE name IN ( :name[] )', array(':name[]' => $variables))->fetchAllKeyed();
$values = $this->select('variable', 'v')
->fields('v', ['name', 'value'])
->condition('name', $variables, 'IN')
->execute()
->fetchAllKeyed();
foreach ($node_types as $node_type) {
$name = $prefix . '_' . $node_type;
$name = 'upload_' . $node_type;
if (isset($values[$name])) {
$enabled = unserialize($values[$name]);
if ($enabled) {

View file

@ -7,6 +7,7 @@
namespace Drupal\file\Plugin\migrate\source\d7;
use Drupal\Core\Database\Query\Condition;
use Drupal\migrate\Row;
use Drupal\migrate_drupal\Plugin\migrate\source\DrupalSqlBase;
@ -44,9 +45,28 @@ class File extends DrupalSqlBase {
* {@inheritdoc}
*/
public function query() {
return $this->select('file_managed', 'f')
$query = $this->select('file_managed', 'f')
->fields('f')
->orderBy('timestamp');
// Filter by scheme(s), if configured.
if (isset($this->configuration['scheme'])) {
$schemes = array();
// Accept either a single scheme, or a list.
foreach ((array) $this->configuration['scheme'] as $scheme) {
$schemes[] = rtrim($scheme) . '://';
}
$schemes = array_map([$this->getDatabase(), 'escapeLike'], $schemes);
// uri LIKE 'public://%' OR uri LIKE 'private://%'
$conditions = new Condition('OR');
foreach ($schemes as $scheme) {
$conditions->condition('uri', $scheme . '%', 'LIKE');
}
$query->condition($conditions);
}
return $query;
}
/**
@ -69,7 +89,9 @@ class File extends DrupalSqlBase {
// At this point, $path could be an absolute path or a relative path,
// depending on how the scheme's variable was set. So we need to shear out
// the source_base_path in order to make them all relative.
$path = str_replace($this->migration->get('destination.source_base_path'), NULL, $path);
// @todo Don't depend on destination configuration.
// @see https://www.drupal.org/node/2577871
$path = str_replace($this->migration->get('destination')['source_base_path'], NULL, $path);
$row->setSourceProperty('filepath', $path);
return parent::prepareRow($row);
}

View file

@ -113,14 +113,25 @@ class DownloadTest extends FileManagedTestBase {
'clean' => '',
'unclean' => 'index.php/',
);
$public_directory_path = \Drupal::service('stream_wrapper_manager')->getViaScheme('public')->getDirectoryPath();
foreach ($clean_url_settings as $clean_url_setting => $script_path) {
$clean_urls = $clean_url_setting == 'clean';
$request = $this->prepareRequestForGenerator($clean_urls);
$base_path = $request->getSchemeAndHttpHost() . $request->getBasePath();
$this->checkUrl('public', '', $basename, $base_path . '/' . \Drupal::service('stream_wrapper_manager')->getViaScheme('public')->getDirectoryPath() . '/' . $basename_encoded);
$this->checkUrl('public', '', $basename, $base_path . '/' . $public_directory_path . '/' . $basename_encoded);
$this->checkUrl('private', '', $basename, $base_path . '/' . $script_path . 'system/files/' . $basename_encoded);
}
$this->assertEqual(file_create_url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=='), 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==', t('Generated URL matches expected URL.'));
// Test public files with a different host name from settings.
$test_base_url = 'http://www.example.com/cdn';
$this->settingsSet('file_public_base_url', $test_base_url);
$filepath = file_create_filename('test.txt', '');
$directory_uri = 'public://' . dirname($filepath);
file_prepare_directory($directory_uri, FILE_CREATE_DIRECTORY);
$file = $this->createFile($filepath, NULL, 'public');
$url = file_create_url($file->getFileUri());
$expected_url = $test_base_url . '/' . basename($filepath);
$this->assertEqual($url, $expected_url);
}
/**

View file

@ -35,8 +35,7 @@ class FileFieldValidateTest extends FileFieldTestBase {
$edit = array();
$edit['title[0][value]'] = $this->randomMachineName();
$this->drupalPostForm('node/add/' . $type_name, $edit, t('Save and publish'));
$this->assertText('1 error has been found: ' . $field->label(), 'Node save failed when required file field was empty.');
$this->assertIdentical(1, count($this->xpath('//div[contains(concat(" ", normalize-space(@class), " "), :class)]//a', [':class' => ' messages--error '])), 'There is one link in the error message.');
$this->assertRaw(t('@title field is required.', array('@title' => $field->getLabel())), 'Node save failed when required file field was empty.');
// Create a new node with the uploaded file.
$nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
@ -57,8 +56,7 @@ class FileFieldValidateTest extends FileFieldTestBase {
$edit = array();
$edit['title[0][value]'] = $this->randomMachineName();
$this->drupalPostForm('node/add/' . $type_name, $edit, t('Save and publish'));
$this->assertText('1 error has been found: ' . $field->label(), 'Node save failed when required multiple value file field was empty.');
$this->assertIdentical(1, count($this->xpath('//div[contains(concat(" ", normalize-space(@class), " "), :class)]//a', [':class' => ' messages--error '])), 'There is one link in the error message.');
$this->assertRaw(t('@title field is required.', array('@title' => $field->getLabel())), 'Node save failed when required multiple value file field was empty.');
// Create a new node with the uploaded file into the multivalue field.
$nid = $this->uploadNodeFile($test_file, $field_name, $type_name);

View file

@ -10,6 +10,7 @@ namespace Drupal\file\Tests;
use Drupal\Core\Field\FieldItemInterface;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\field\Entity\FieldConfig;
use Drupal\field\Tests\FieldUnitTestBase;
/**
@ -33,6 +34,13 @@ class FileItemTest extends FieldUnitTestBase {
*/
protected $file;
/**
* Directory where the sample files are stored.
*
* @var string
*/
protected $directory;
protected function setUp() {
parent::setUp();
@ -45,10 +53,12 @@ class FileItemTest extends FieldUnitTestBase {
'type' => 'file',
'cardinality' => FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED,
))->save();
$this->directory = $this->getRandomGenerator()->name(8);
entity_create('field_config', array(
'entity_type' => 'entity_test',
'field_name' => 'file_test',
'bundle' => 'entity_test',
'settings' => array('file_directory' => $this->directory),
))->save();
file_put_contents('public://example.txt', $this->randomMachineName());
$this->file = entity_create('file', array(
@ -61,6 +71,12 @@ class FileItemTest extends FieldUnitTestBase {
* Tests using entity fields of the file field type.
*/
public function testFileItem() {
// Check that the selection handler was automatically assigned to
// 'default:file'.
$field_definition = FieldConfig::load('entity_test.entity_test.file_test');
$handler_id = $field_definition->getSetting('handler');
$this->assertEqual($handler_id, 'default:file');
// Create a test entity with the
$entity = entity_create('entity_test');
$entity->file_test->target_id = $this->file->id();
@ -100,6 +116,9 @@ class FileItemTest extends FieldUnitTestBase {
$entity = entity_create('entity_test');
$entity->file_test->generateSampleItems();
$this->entityValidateAndSave($entity);
// Verify that the sample file was stored in the correct directory.
$uri = $entity->file_test->entity->getFileUri();
$this->assertEqual($this->directory, dirname(file_uri_target($uri)));
// Make sure the computed files reflects updates to the file.
file_put_contents('public://example-3.txt', $this->randomMachineName());

View file

@ -154,4 +154,26 @@ class FileManagedFileElementTest extends FileFieldTestBase {
$this->assertNoFieldByXpath('//input[@name="nested[file][file_' . $fid_list[0] . '][selected]"]', NULL, 'An individual file can be deleted from a multiple file element.');
$this->assertFieldByXpath('//input[@name="nested[file][file_' . $fid_list[1] . '][selected]"]', NULL, 'Second individual file not deleted when the first file is deleted from a multiple file element.');
}
/**
* Ensure that warning is shown if file on the field has been removed.
*/
public function testManagedFileRemoved() {
$this->drupalGet('file/test/1/0/1');
$test_file = $this->getTestFile('text');
$file_field_name = 'files[nested_file][]';
$edit = [$file_field_name => drupal_realpath($test_file->getFileUri())];
$this->drupalPostForm(NULL, $edit, t('Upload'));
$fid = $this->getLastFileId();
$file = \Drupal::entityManager()->getStorage('file')->load($fid);
$file->delete();
$this->drupalPostForm(NULL, $edit, t('Upload'));
// We expect the title 'Managed <em>file & butter</em>' which got escaped
// via a t() call before.
$this->assertRaw('The file referenced by the Managed <em>file &amp; butter</em> field does not exist.');
}
}

View file

@ -56,7 +56,7 @@ class FileTokenReplaceTest extends FileFieldTestBase {
$tests['[file:created:short]'] = format_date($file->getCreatedTime(), 'short', '', NULL, $language_interface->getId());
$tests['[file:changed]'] = format_date($file->getChangedTime(), 'medium', '', NULL, $language_interface->getId());
$tests['[file:changed:short]'] = format_date($file->getChangedTime(), 'short', '', NULL, $language_interface->getId());
$tests['[file:owner]'] = Html::escape(user_format_name($this->adminUser));
$tests['[file:owner]'] = Html::escape($this->adminUser->getDisplayName());
$tests['[file:owner:uid]'] = $file->getOwnerId();
$base_bubbleable_metadata = BubbleableMetadata::createFromObject($file);

View file

@ -19,13 +19,6 @@ class MigrateFileConfigsTest extends MigrateDrupal6TestBase {
use SchemaCheckTestTrait;
/**
* Modules to enable.
*
* @var array
*/
public static $modules = array('file');
/**
* {@inheritdoc}
*/

View file

@ -8,11 +8,13 @@
namespace Drupal\file\Tests\Migrate\d6;
use Drupal\Component\Utility\Random;
use Drupal\file\Entity\File;
use Drupal\file\FileInterface;
use Drupal\migrate\Entity\Migration;
use Drupal\migrate\Tests\MigrateDumpAlterInterface;
use Drupal\Core\Database\Database;
use Drupal\migrate_drupal\Tests\d6\MigrateDrupal6TestBase;
use Drupal\simpletest\TestBase;
use Drupal\file\Entity\File;
/**
* file migration.
@ -28,13 +30,6 @@ class MigrateFileTest extends MigrateDrupal6TestBase implements MigrateDumpAlter
*/
protected static $tempFilename;
/**
* Modules to enable.
*
* @var array
*/
public static $modules = array('file');
/**
* {@inheritdoc}
*/
@ -45,33 +40,53 @@ class MigrateFileTest extends MigrateDrupal6TestBase implements MigrateDumpAlter
$this->installConfig(['file']);
/** @var \Drupal\migrate\Entity\MigrationInterface $migration */
$migration = entity_load('migration', 'd6_file');
$migration = Migration::load('d6_file');
$source = $migration->get('source');
$source['site_path'] = 'core/modules/simpletest';
$migration->set('source', $source);
$this->executeMigration($migration);
$this->standalone = TRUE;
}
/**
* Asserts a file entity.
*
* @param integer $fid
* The file ID.
* @param string $name
* The expected file name.
* @param integer $size
* The expected file size.
* @param string $uri
* The expected file URI.
* @param string $type
* The expected MIME type.
* @param integer $uid
* The expected file owner ID.
*/
protected function assertEntity($fid, $name, $size, $uri, $type, $uid) {
/** @var \Drupal\file\FileInterface $file */
$file = File::load($fid);
$this->assertTrue($file instanceof FileInterface);
$this->assertIdentical($name, $file->getFilename());
$this->assertIdentical($size, $file->getSize());
$this->assertIdentical($uri, $file->getFileUri());
$this->assertIdentical($type, $file->getMimeType());
$this->assertIdentical($uid, $file->getOwnerId());
}
/**
* Tests the Drupal 6 files to Drupal 8 migration.
*/
public function testFiles() {
/** @var \Drupal\file\FileInterface $file */
$file = File::load(1);
$this->assertIdentical('Image1.png', $file->getFilename());
$this->assertIdentical('39325', $file->getSize());
$this->assertIdentical('public://image-1.png', $file->getFileUri());
$this->assertIdentical('image/png', $file->getMimeType());
$this->assertIdentical("1", $file->getOwnerId());
// It is pointless to run the second half from MigrateDrupal6Test.
if (empty($this->standalone)) {
return;
}
$this->assertEntity(1, 'Image1.png', '39325', 'public://image-1.png', 'image/png', '1');
$this->assertEntity(2, 'Image2.jpg', '1831', 'public://image-2.jpg', 'image/jpeg', '1');
$this->assertEntity(3, 'Image-test.gif', '183', 'public://image-test.gif', 'image/jpeg', '1');
$this->assertEntity(5, 'html-1.txt', '24', 'public://html-1.txt', 'text/plain', '1');
// Test that we can re-import and also test with file_directory_path set.
db_truncate(entity_load('migration', 'd6_file')->getIdMap()->mapTableName())->execute();
\Drupal::database()
->truncate(Migration::load('d6_file')->getIdMap()->mapTableName())
->execute();
// Update the file_directory_path.
Database::getConnection('default', 'migrate')
@ -85,7 +100,7 @@ class MigrateFileTest extends MigrateDrupal6TestBase implements MigrateDumpAlter
->condition('name', 'file_directory_temp')
->execute();
$migration = entity_load_unchanged('migration', 'd6_file');
$migration = \Drupal::entityManager()->getStorage('migration')->loadUnchanged('d6_file');
$this->executeMigration($migration);
$file = File::load(2);
@ -94,6 +109,10 @@ class MigrateFileTest extends MigrateDrupal6TestBase implements MigrateDumpAlter
// Ensure that a temporary file has been migrated.
$file = File::load(6);
$this->assertIdentical('temporary://' . static::getUniqueFilename(), $file->getFileUri());
// File 7, created in static::migrateDumpAlter(), shares a path with
// file 5, which means it should be skipped entirely.
$this->assertNull(File::load(7));
}
/**
@ -115,8 +134,10 @@ class MigrateFileTest extends MigrateDrupal6TestBase implements MigrateDumpAlter
static::$tempFilename = $test->getDatabasePrefix() . $random->name() . '.jpg';
$file_path = $temp_directory . '/' . static::$tempFilename;
file_put_contents($file_path, '');
Database::getConnection('default', 'migrate')
->update('files')
$db = Database::getConnection('default', 'migrate');
$db->update('files')
->condition('fid', 6)
->fields(array(
'filename' => static::$tempFilename,
@ -124,6 +145,14 @@ class MigrateFileTest extends MigrateDrupal6TestBase implements MigrateDumpAlter
))
->execute();
$file = (array) $db->select('files')
->fields('files')
->condition('fid', 5)
->execute()
->fetchObject();
unset($file['fid']);
$db->insert('files')->fields($file)->execute();
return static::$tempFilename;
}

View file

@ -1,100 +0,0 @@
<?php
/**
* @file
* Contains \Drupal\file\Tests\Migrate\d6\MigrateUploadBase.
*/
namespace Drupal\file\Tests\Migrate\d6;
use Drupal\migrate_drupal\Tests\d6\MigrateDrupal6TestBase;
/**
* Base class for file/upload migration tests.
*/
abstract class MigrateUploadBase extends MigrateDrupal6TestBase {
/**
* {@inheritdoc}
*/
static $modules = array('file', 'node');
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
$this->installEntitySchema('file');
$this->installEntitySchema('node');
$this->installSchema('file', ['file_usage']);
$this->installSchema('node', ['node_access']);
// Create new file entities.
for ($i = 1; $i <= 3; $i++) {
$file = entity_create('file', array(
'fid' => $i,
'uid' => 1,
'filename' => 'druplicon.txt',
'uri' => "public://druplicon-$i.txt",
'filemime' => 'text/plain',
'created' => 1,
'changed' => 1,
'status' => FILE_STATUS_PERMANENT,
));
$file->enforceIsNew();
file_put_contents($file->getFileUri(), 'hello world');
// Save it, inserting a new record.
$file->save();
$id_mappings['d6_file'][] = array(array($i), array($i));
}
// Add a node type.
$node_type = entity_create('node_type', array('type' => 'story'));
$node_type->save();
// Add a file field.
entity_create('field_storage_config', array(
'field_name' => 'upload',
'entity_type' => 'node',
'type' => 'file',
'cardinality' => -1,
'settings' => array(
'display_field' => TRUE,
),
))->save();
entity_create('field_config', array(
'field_name' => 'upload',
'entity_type' => 'node',
'bundle' => 'story',
))->save();
$id_mappings['d6_node'] = array(
array(array(1), array(1)),
array(array(2), array(2)),
);
$id_mappings['d6_upload_field_instance'] = [
[['story'], ['node', 'story', 'upload']],
];
$this->prepareMigrations($id_mappings);
$vids = array(1, 2, 3);
for ($i = 1; $i <= 2; $i++) {
$node = entity_create('node', array(
'type' => 'story',
'nid' => $i,
'vid' => array_shift($vids),
'title' => $this->randomString(),
));
$node->enforceIsNew();
$node->save();
if ($i == 1) {
$node->vid->value = array_shift($vids);
$node->enforceIsNew(FALSE);
$node->isDefaultRevision(FALSE);
$node->save();
}
}
}
}

View file

@ -7,6 +7,8 @@
namespace Drupal\file\Tests\Migrate\d6;
use Drupal\Core\Entity\Entity\EntityViewDisplay;
use Drupal\migrate\Entity\Migration;
use Drupal\migrate_drupal\Tests\d6\MigrateDrupal6TestBase;
/**
@ -16,29 +18,12 @@ use Drupal\migrate_drupal\Tests\d6\MigrateDrupal6TestBase;
*/
class MigrateUploadEntityDisplayTest extends MigrateDrupal6TestBase {
/**
* The modules to be enabled during the test.
*
* @var array
*/
static $modules = array('node', 'file');
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
entity_create('node_type', array('type' => 'article'))->save();
entity_create('node_type', array('type' => 'story'))->save();
entity_create('node_type', array('type' => 'page'))->save();
$id_mappings = array(
'd6_upload_field_instance' => array(
array(array(1), array('node', 'page', 'upload')),
),
);
$this->prepareMigrations($id_mappings);
$this->migrateFields();
$this->executeMigration('d6_upload_entity_display');
}
@ -46,20 +31,20 @@ class MigrateUploadEntityDisplayTest extends MigrateDrupal6TestBase {
* Tests the Drupal 6 upload settings to Drupal 8 entity display migration.
*/
public function testUploadEntityDisplay() {
$display = entity_get_display('node', 'page', 'default');
$display = EntityViewDisplay::load('node.page.default');
$component = $display->getComponent('upload');
$this->assertIdentical('file_default', $component['type']);
$display = entity_get_display('node', 'story', 'default');
$display = EntityViewDisplay::load('node.story.default');
$component = $display->getComponent('upload');
$this->assertIdentical('file_default', $component['type']);
// Assure this doesn't exist.
$display = entity_get_display('node', 'article', 'default');
$display = EntityViewDisplay::load('node.article.default');
$component = $display->getComponent('upload');
$this->assertTrue(is_null($component));
$this->assertIdentical(array('node', 'page', 'default', 'upload'), entity_load('migration', 'd6_upload_entity_display')->getIdMap()->lookupDestinationID(array('page')));
$this->assertIdentical(array('node', 'page', 'default', 'upload'), Migration::load('d6_upload_entity_display')->getIdMap()->lookupDestinationID(array('page')));
}
}

View file

@ -7,6 +7,8 @@
namespace Drupal\file\Tests\Migrate\d6;
use Drupal\Core\Entity\Entity\EntityFormDisplay;
use Drupal\migrate\Entity\Migration;
use Drupal\migrate_drupal\Tests\d6\MigrateDrupal6TestBase;
/**
@ -16,29 +18,12 @@ use Drupal\migrate_drupal\Tests\d6\MigrateDrupal6TestBase;
*/
class MigrateUploadEntityFormDisplayTest extends MigrateDrupal6TestBase {
/**
* The modules to be enabled during the test.
*
* @var array
*/
static $modules = array('file', 'node');
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
entity_create('node_type', array('type' => 'article'))->save();
entity_create('node_type', array('type' => 'story'))->save();
entity_create('node_type', array('type' => 'page'))->save();
$id_mappings = array(
'd6_upload_field_instance' => array(
array(array(1), array('node', 'page', 'upload')),
),
);
$this->prepareMigrations($id_mappings);
$this->migrateFields();
$this->executeMigration('d6_upload_entity_form_display');
}
@ -46,20 +31,20 @@ class MigrateUploadEntityFormDisplayTest extends MigrateDrupal6TestBase {
* Tests the Drupal 6 upload settings to Drupal 8 entity form display migration.
*/
public function testUploadEntityFormDisplay() {
$display = entity_get_form_display('node', 'page', 'default');
$display = EntityFormDisplay::load('node.page.default');
$component = $display->getComponent('upload');
$this->assertIdentical('file_generic', $component['type']);
$display = entity_get_form_display('node', 'story', 'default');
$display = EntityFormDisplay::load('node.story.default');
$component = $display->getComponent('upload');
$this->assertIdentical('file_generic', $component['type']);
// Assure this doesn't exist.
$display = entity_get_form_display('node', 'article', 'default');
$display = EntityFormDisplay::load('node.article.default');
$component = $display->getComponent('upload');
$this->assertTrue(is_null($component));
$this->assertIdentical(array('node', 'page', 'default', 'upload'), entity_load('migration', 'd6_upload_entity_form_display')->getIdMap()->lookupDestinationID(array('page')));
$this->assertIdentical(array('node', 'page', 'default', 'upload'), Migration::load('d6_upload_entity_form_display')->getIdMap()->lookupDestinationID(array('page')));
}
}

View file

@ -8,6 +8,7 @@
namespace Drupal\file\Tests\Migrate\d6;
use Drupal\field\Entity\FieldStorageConfig;
use Drupal\migrate\Entity\Migration;
use Drupal\migrate_drupal\Tests\d6\MigrateDrupal6TestBase;
/**
@ -17,19 +18,12 @@ use Drupal\migrate_drupal\Tests\d6\MigrateDrupal6TestBase;
*/
class MigrateUploadFieldTest extends MigrateDrupal6TestBase {
/**
* The modules to be enabled during the test.
*
* @var array
*/
static $modules = array('file', 'node');
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
$this->executeMigration('d6_upload_field');
$this->migrateFields();
}
/**
@ -38,7 +32,7 @@ class MigrateUploadFieldTest extends MigrateDrupal6TestBase {
public function testUpload() {
$field_storage = FieldStorageConfig::load('node.upload');
$this->assertIdentical('node.upload', $field_storage->id());
$this->assertIdentical(array('node', 'upload'), entity_load('migration', 'd6_upload_field')->getIdMap()->lookupDestinationID(array('')));
$this->assertIdentical(array('node', 'upload'), Migration::load('d6_upload_field')->getIdMap()->lookupDestinationID(array('')));
}
}

View file

@ -8,6 +8,7 @@
namespace Drupal\file\Tests\Migrate\d6;
use Drupal\field\Entity\FieldConfig;
use Drupal\migrate\Entity\Migration;
use Drupal\migrate_drupal\Tests\d6\MigrateDrupal6TestBase;
/**
@ -17,41 +18,12 @@ use Drupal\migrate_drupal\Tests\d6\MigrateDrupal6TestBase;
*/
class MigrateUploadInstanceTest extends MigrateDrupal6TestBase {
/**
* The modules to be enabled during the test.
*
* @var array
*/
static $modules = array('file', 'node');
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
// Add some node mappings to get past checkRequirements().
$id_mappings = array(
'd6_upload_field' => array(
array(array(1), array('node', 'upload')),
),
'd6_node_type' => array(
array(array('page'), array('page')),
array(array('story'), array('story')),
),
);
$this->prepareMigrations($id_mappings);
foreach (array('page', 'story') as $type) {
entity_create('node_type', array('type' => $type))->save();
}
entity_create('field_storage_config', array(
'entity_type' => 'node',
'field_name' => 'upload',
'type' => 'file',
'translatable' => '0',
))->save();
$this->executeMigration('d6_upload_field_instance');
$this->migrateFields();
}
/**
@ -72,7 +44,7 @@ class MigrateUploadInstanceTest extends MigrateDrupal6TestBase {
$field = FieldConfig::load('node.article.upload');
$this->assertTrue(is_null($field));
$this->assertIdentical(array('node', 'page', 'upload'), entity_load('migration', 'd6_upload_field_instance')->getIdMap()->lookupDestinationID(array('page')));
$this->assertIdentical(array('node', 'page', 'upload'), Migration::load('d6_upload_field_instance')->getIdMap()->lookupDestinationID(array('page')));
}
}

View file

@ -7,6 +7,9 @@
namespace Drupal\file\Tests\Migrate\d6;
use Drupal\file\Entity\File;
use Drupal\migrate\Entity\Migration;
use Drupal\migrate_drupal\Tests\d6\MigrateDrupal6TestBase;
use Drupal\node\Entity\Node;
/**
@ -14,32 +17,58 @@ use Drupal\node\Entity\Node;
*
* @group migrate_drupal_6
*/
class MigrateUploadTest extends MigrateUploadBase {
class MigrateUploadTest extends MigrateDrupal6TestBase {
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
$id_mappings = array(
'd6_node:*' => array(
array(
array(0),
array(0),
),
),
);
$this->installEntitySchema('file');
$this->installEntitySchema('node');
$this->installSchema('file', ['file_usage']);
$this->installSchema('node', ['node_access']);
$id_mappings = array('d6_file' => array());
// Create new file entities.
for ($i = 1; $i <= 3; $i++) {
$file = File::create(array(
'fid' => $i,
'uid' => 1,
'filename' => 'druplicon.txt',
'uri' => "public://druplicon-$i.txt",
'filemime' => 'text/plain',
'created' => 1,
'changed' => 1,
'status' => FILE_STATUS_PERMANENT,
));
$file->enforceIsNew();
file_put_contents($file->getFileUri(), 'hello world');
// Save it, inserting a new record.
$file->save();
$id_mappings['d6_file'][] = array(array($i), array($i));
}
$this->prepareMigrations($id_mappings);
$this->executeMigration('d6_upload');
$this->migrateContent();
// Since we are only testing a subset of the file migration, do not check
// that the full file migration has been run.
$migration = Migration::load('d6_upload');
$migration->set('requirements', []);
$this->executeMigration($migration);
}
/**
* Test upload migration from Drupal 6 to Drupal 8.
*/
function testUpload() {
$node_storage = $this->container->get('entity.manager')->getStorage('node');
$node_storage->resetCache(array(1, 2));
$nodes = Node::loadMultiple(array(1, 2));
$this->container->get('entity.manager')
->getStorage('node')
->resetCache([1, 2]);
$nodes = Node::loadMultiple([1, 2]);
$node = $nodes[1];
$this->assertIdentical(1, count($node->upload));
$this->assertIdentical('1', $node->upload[0]->target_id);

View file

@ -220,7 +220,7 @@ class SaveUploadTest extends FileManagedTestBase {
$this->drupalPostForm('file-test/upload', $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', array('!filename' => $this->phpfile->filename)), 'Dangerous file was not renamed when insecure uploads is TRUE.');
$this->assertRaw(t('File name is @filename', array('@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.
@ -254,7 +254,7 @@ class SaveUploadTest extends FileManagedTestBase {
$this->drupalPostForm('file-test/upload', $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', array('!filename' => $munged_filename)), 'File was successfully munged.');
$this->assertRaw(t('File name is @filename', array('@filename' => $munged_filename)), 'File was successfully munged.');
$this->assertRaw(t('You WIN!'), 'Found the success message.');
// Check that the correct hooks were called.
@ -272,7 +272,7 @@ class SaveUploadTest extends FileManagedTestBase {
$this->drupalPostForm('file-test/upload', $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', array('!filename' => $this->image->getFilename())), 'File was not munged when allowing any extension.');
$this->assertRaw(t('File name is @filename', array('@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.

View file

@ -84,7 +84,7 @@ class RelationshipUserFileDataTest extends ViewTestBase {
'user',
],
];
$this->assertIdentical($expected, $view->calculateDependencies());
$this->assertIdentical($expected, $view->getDependencies());
$this->executeView($view);
$expected_result = array(
array(

View file

@ -43,7 +43,7 @@ class FileModuleTestForm extends FormBase {
$form['nested']['file'] = array(
'#type' => 'managed_file',
'#title' => $this->t('Managed file'),
'#title' => $this->t('Managed <em>@type</em>', ['@type' => 'file & butter']),
'#upload_location' => 'public://test',
'#progress_message' => $this->t('Please wait...'),
'#extended' => (bool) $extended,

View file

@ -19,9 +19,9 @@ class FileTestAccessControlHandler extends FileAccessControlHandler implements F
/**
* {@inheritdoc}
*/
protected function checkAccess(EntityInterface $entity, $operation, $langcode, AccountInterface $account) {
protected function checkAccess(EntityInterface $entity, $operation, AccountInterface $account) {
\Drupal::state()->set('file_access_formatter_check', TRUE);
return parent::checkAccess($entity, $operation, $langcode, $account);
return parent::checkAccess($entity, $operation, $account);
}
}

View file

@ -0,0 +1,84 @@
<?php
/**
* @file
* Contains \Drupal\Tests\file\Unit\Plugin\migrate\process\d6\FileUriTest.
*/
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;
/**
* @coversDefaultClass \Drupal\file\Plugin\migrate\process\d6\FileUri
* @group file
*/
class FileUriTest extends MigrateTestCase {
protected $migrationConfiguration = [
'id' => 'test',
];
public function testPublic() {
$value = [
'sites/default/files/foo.jpg',
'sites/default/files',
'/tmp',
TRUE,
];
$this->assertEquals('public://foo.jpg', $this->doTransform($value));
}
public function testPublicUnknownBasePath() {
$value = [
'/path/to/public/files/foo.jpg',
'sites/default/files',
'/tmp',
TRUE,
];
$this->assertEquals('public://path/to/public/files/foo.jpg', $this->doTransform($value));
}
public function testPrivate() {
$value = [
'sites/default/files/baz.gif',
'sites/default/files',
'/tmp',
FALSE,
];
$this->assertEquals('private://baz.gif', $this->doTransform($value));
}
public function testPrivateUnknownBasePath() {
$value = [
'/path/to/private/files/baz.gif',
'sites/default/files',
'/tmp',
FALSE,
];
$this->assertEquals('private://path/to/private/files/baz.gif', $this->doTransform($value));
}
public function testTemporary() {
$value = [
'/tmp/bar.png',
'sites/default/files',
'/tmp',
TRUE,
];
$this->assertEquals('temporary://bar.png', $this->doTransform($value));
}
protected function doTransform(array $value) {
$executable = new MigrateExecutable($this->getMigration(), new MigrateMessage());
$row = new Row([], []);
return (new FileUri([], 'file_uri', []))
->transform($value, $executable, $row, 'foobaz');
}
}

View file

@ -18,9 +18,7 @@ class FileTest extends MigrateSqlSourceTestCase {
const PLUGIN_CLASS = 'Drupal\file\Plugin\migrate\source\d6\File';
// The fake Migration configuration entity.
protected $migrationConfiguration = array(
// The ID of the entity, can be any string.
'id' => 'test',
'source' => array(
'plugin' => 'd6_file',

View file

@ -0,0 +1,70 @@
<?php
/**
* @file
* Contains \Drupal\Tests\file\Unit\Plugin\migrate\source\d6\UploadInstanceTest.
*/
namespace Drupal\Tests\file\Unit\Plugin\migrate\source\d6;
use Drupal\file\Plugin\migrate\source\d6\UploadInstance;
use Drupal\Tests\migrate\Unit\MigrateSqlSourceTestCase;
/**
* Tests d6_upload_instance source plugin.
*
* @group file
*/
class UploadInstanceTest extends MigrateSqlSourceTestCase {
const PLUGIN_CLASS = UploadInstance::class;
protected $migrationConfiguration = array(
'id' => 'test',
'source' => array(
'plugin' => 'd6_upload_instance',
),
);
protected $expectedResults = array(
array(
'node_type' => 'article',
'max_filesize' => '16MB',
'file_extensions' => 'txt pdf',
),
);
/**
* {@inheritdoc}
*/
protected function setUp() {
$this->databaseContents['node_type'] = array(
array(
'type' => 'article',
),
array(
'type' => 'company',
),
);
$this->databaseContents['variable'] = array(
array(
'name' => 'upload_article',
'value' => serialize(TRUE),
),
array(
'name' => 'upload_company',
'value' => serialize(FALSE),
),
array(
'name' => 'upload_uploadsize_default',
'value' => serialize(16),
),
array(
'name' => 'upload_extensions_default',
'value' => serialize('txt pdf'),
),
);
parent::setUp();
}
}

View file

@ -0,0 +1,80 @@
<?php
/**
* @file
* Contains \Drupal\Tests\file\Unit\Plugin\migrate\source\d6\UploadTest.
*/
namespace Drupal\Tests\file\Unit\Plugin\migrate\source\d6;
use Drupal\file\Plugin\migrate\source\d6\Upload;
use Drupal\Tests\migrate\Unit\MigrateSqlSourceTestCase;
/**
* Tests d6_upload source plugin.
*
* @group file
*/
class UploadTest extends MigrateSqlSourceTestCase {
const PLUGIN_CLASS = Upload::class;
protected $migrationConfiguration = array(
'id' => 'test',
'source' => array(
'plugin' => 'd6_upload',
),
);
protected $expectedResults = array(
array(
'upload' => array(
array(
'fid' => '1',
'description' => 'file 1-1-1',
'list' => '0',
),
),
'nid' => '1',
'vid' => '1',
'type' => 'story',
),
);
/**
* {@inheritdoc}
*/
protected function setUp() {
$this->databaseContents['upload'] = array(
array(
'fid' => '1',
'nid' => '1',
'vid' => '1',
'description' => 'file 1-1-1',
'list' => '0',
'weight' => '-1',
),
);
$this->databaseContents['node'] = array(
array(
'nid' => '1',
'vid' => '1',
'type' => 'story',
'language' => '',
'title' => 'Test title',
'uid' => '1',
'status' => '1',
'created' => '1388271197',
'changed' => '1420861423',
'comment' => '0',
'promote' => '0',
'moderate' => '0',
'sticky' => '0',
'tnid' => '0',
'translate' => '0',
),
);
parent::setUp();
}
}

View file

@ -7,6 +7,7 @@
namespace Drupal\Tests\file\Unit\Plugin\migrate\source\d7;
use Drupal\Core\Database\Query\ConditionInterface;
use Drupal\file\Plugin\migrate\source\d7\File;
use Drupal\migrate\Row;
use Drupal\Tests\migrate\Unit\MigrateSqlSourceTestCase;
@ -20,12 +21,19 @@ class FileTest extends MigrateSqlSourceTestCase {
const PLUGIN_CLASS = 'Drupal\Tests\file\Unit\Plugin\migrate\source\d7\TestFile';
// The fake Migration configuration entity.
protected $migrationConfiguration = array(
// The ID of the entity, can be any string.
'id' => 'test',
'source' => array(
'plugin' => 'd7_file',
// Used by testFilteringByScheme().
'scheme' => array(
'public',
'private',
),
),
'destination' => array(
'plugin' => 'entity:file',
'source_base_path' => '/path/to/files',
),
);
@ -84,6 +92,25 @@ class FileTest extends MigrateSqlSourceTestCase {
$row->getSourceProperty('filepath'));
}
/**
* Tests that it's possible to filter files by scheme.
*/
public function testFilteringByScheme() {
$query_conditions = $this->source->query()->conditions();
$scheme_condition = end($query_conditions);
$this->assertInstanceOf(ConditionInterface::class, $scheme_condition['field']);
$conditions = $scheme_condition['field']->conditions();
$this->assertSame('uri', $conditions[0]['field']);
$this->assertSame('LIKE', $conditions[0]['operator']);
$this->assertSame('public://%', $conditions[0]['value']);
$this->assertSame('uri', $conditions[1]['field']);
$this->assertSame('LIKE', $conditions[1]['operator']);
$this->assertSame('private://%', $conditions[1]['value']);
}
}
/**