This repository has been archived by the owner on Nov 16, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 105
/
FileUpload.php
362 lines (318 loc) · 11 KB
/
FileUpload.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
<?php
namespace Drupal\lightning_media\Plugin\EntityBrowser\Widget;
use Drupal\Core\Ajax\HtmlCommand;
use Drupal\Core\Ajax\InvokeCommand;
use Drupal\Core\Entity\EntityManagerInterface;
use Drupal\Core\File\FileSystemInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Utility\Token;
use Drupal\entity_browser\WidgetValidationManager;
use Drupal\file\Element\ManagedFile;
use Drupal\lightning_media\BundleResolverInterface;
use Drupal\lightning_media\SourceFieldTrait;
use Drupal\media_entity\MediaInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\HttpFoundation\Request;
/**
* An Entity Browser widget for creating media entities from uploaded files.
*
* @EntityBrowserWidget(
* id = "file_upload",
* label = @Translation("File Upload"),
* description = @Translation("Allows creation of media entities from file uploads."),
* bundle_resolver = "file_upload"
* )
*/
class FileUpload extends EntityFormProxy {
use SourceFieldTrait;
/**
* The token replacement service.
*
* @var Token
*/
protected $token;
/**
* The file system service.
*
* @var \Drupal\Core\File\FileSystemInterface
*/
protected $fileSystem;
/**
* FileUpload constructor.
*
* @param array $configuration
* Plugin configuration.
* @param string $plugin_id
* The plugin ID.
* @param mixed $plugin_definition
* The plugin definition.
* @param EventDispatcherInterface $event_dispatcher
* The event dispatcher.
* @param EntityManagerInterface $entity_manager
* The entity manager service.
* @param WidgetValidationManager $widget_validation_manager
* The widget validation manager.
* @param BundleResolverInterface $bundle_resolver
* The media bundle resolver.
* @param AccountInterface $current_user
* The currently logged in user.
* @param Token $token
* The token replacement service.
* @param FileSystemInterface $file_system
* The file system service.
*/
public function __construct(array $configuration, $plugin_id, $plugin_definition, EventDispatcherInterface $event_dispatcher, EntityManagerInterface $entity_manager, WidgetValidationManager $widget_validation_manager, BundleResolverInterface $bundle_resolver, AccountInterface $current_user, Token $token, FileSystemInterface $file_system) {
parent::__construct($configuration, $plugin_id, $plugin_definition, $event_dispatcher, $entity_manager, $widget_validation_manager, $bundle_resolver, $current_user);
$this->token = $token;
$this->fileSystem = $file_system;
$this->fieldStorage = $entity_manager->getStorage('field_config');
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
$bundle_resolver = $plugin_definition['bundle_resolver'];
return new static(
$configuration,
$plugin_id,
$plugin_definition,
$container->get('event_dispatcher'),
$container->get('entity.manager'),
$container->get('plugin.manager.entity_browser.widget_validation'),
$container->get('plugin.manager.lightning_media.bundle_resolver')->createInstance($bundle_resolver),
$container->get('current_user'),
$container->get('token'),
$container->get('file_system')
);
}
/**
* {@inheritdoc}
*/
protected function getInputValue(FormStateInterface $form_state) {
$value = $form_state->getValue('file');
if ($value) {
return $this->entityTypeManager->getStorage('file')->load($value[0]);
}
}
/**
* {@inheritdoc}
*/
protected function prepareEntities(array $form, FormStateInterface $form_state) {
$entities = parent::prepareEntities($form, $form_state);
if ($this->configuration['return_file']) {
return array_map([$this, 'getFile'], $entities);
}
else {
return $entities;
}
}
/**
* {@inheritdoc}
*/
public function getForm(array &$original_form, FormStateInterface $form_state, array $additional_widget_parameters) {
$form = parent::getForm($original_form, $form_state, $additional_widget_parameters);
$form['file'] = array(
'#type' => 'managed_file',
'#title' => $this->t('File'),
'#process' => [
[ManagedFile::class, 'processManagedFile'],
[$this, 'processInitialFileElement'],
],
'#upload_validators' => [
'file_validate_extensions' => [$this->getAllowedFileUploadExtensions()],
],
);
return $form;
}
/**
* {@inheritdoc}
*/
public function submit(array &$element, array &$form, FormStateInterface $form_state) {
/** @var \Drupal\media_entity\MediaInterface $entity */
$entity = $element['entity']['#entity'];
$file = $this->getFile($entity);
$file->setPermanent();
$file->save();
$selection = [
$this->configuration['return_file'] ? $file : $entity,
];
$this->selectEntities($selection, $form_state);
}
/**
* Returns the source file of a media entity.
*
* @param \Drupal\media_entity\MediaInterface $entity
* The media entity.
*
* @return \Drupal\file\FileInterface
* The source file.
*/
protected function getFile(MediaInterface $entity) {
$field = $this->getSourceField($entity)->getName();
return $entity->get($field)->entity;
}
/**
* Returns the expected permanent URI of the source file of a media entity.
*
* The permanent URI is computed from field configuration values and might
* change (i.e., FILE_EXISTS_RENAME) during file system operations.
*
* @param \Drupal\media_entity\MediaInterface $entity
* The media entity.
*
* @return string
* The expected permanent URI.
*/
protected function getPermanentUri(MediaInterface $entity) {
$field = $this->getSourceField($entity);
$uri = '';
$uri .= $field->getFieldStorageDefinition()->getSetting('uri_scheme');
$uri .= '://';
$uri .= $this->token->replace($field->getSetting('file_directory'));
if (substr($uri, -3) != '://') {
$uri .= '/';
}
$uri .= $this->getFile($entity)->getFilename();
return $uri;
}
/**
* {@inheritdoc}
*/
protected function generateEntity($input) {
$entity = parent::generateEntity($input);
$destination = $this->getPermanentUri($entity);
$dir = $this->fileSystem->dirname($destination);
$ready = file_prepare_directory($dir, FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS);
if ($ready) {
$file = file_move($this->getFile($entity), $destination);
if ($file) {
$file->setTemporary();
$file->save();
return $entity->set($this->getSourceField($entity)->getName(), $file);
}
}
}
/**
* Processes the file element that is NOT part of the entity form.
*
* @param array $element
* The file element.
*
* @return array
* The processed file element.
*/
public function processInitialFileElement(array $element) {
$element['upload_button']['#ajax']['callback'] = [$this, 'onUpload'];
$element['remove_button']['#value'] = $this->t('Cancel');
$element['remove_button']['#ajax']['callback'] = [$this, 'onRemove'];
return $element;
}
/**
* {@inheritdoc}
*/
public function processEntityForm(array $entity_form) {
$type_config = $entity_form['#entity']->getType()->getConfiguration();
$field = $type_config['source_field'];
if (isset($entity_form[$field])) {
$entity_form[$field]['widget'][0]['#process'][] = [$this, 'processEntityFormFileElement'];
}
return parent::processEntityForm($entity_form);
}
/**
* Processes the file element that IS part of the entity form.
*
* @param array $element
* The file element.
*
* @return array
* The processed file element.
*/
public function processEntityFormFileElement(array $element) {
$element['remove_button']['#access'] = FALSE;
if ($element['#default_value']) {
$key = 'file_' . $element['#default_value']['target_id'];
$element[$key]['#access'] = FALSE;
}
return $element;
}
/**
* AJAX callback. Responds when a file has been uploaded.
*
* @param array $form
* The complete form.
* @param \Drupal\Core\Form\FormStateInterface $form_state
* The current form state.
* @param \Symfony\Component\HttpFoundation\Request $request
* The current HTTP request.
*
* @return \Drupal\Core\Ajax\AjaxResponse
* The AJAX response.
*/
public function onUpload(array &$form, FormStateInterface $form_state, Request $request) {
$response = ManagedFile::uploadAjaxCallback($form, $form_state, $request);
$complete_form = $form_state->getCompleteForm();
$selector = '#' . $complete_form['widget']['ief_target']['#id'];
$content = $this->getEntityForm($complete_form, $form_state);
$command = new HtmlCommand($selector, $content);
$response->addCommand($command);
return $response;
}
/**
* AJAX callback. Responds when the uploaded file is removed.
*
* @param array $form
* The complete form.
* @param \Drupal\Core\Form\FormStateInterface $form_state
* The current form state.
* @param \Symfony\Component\HttpFoundation\Request $request
* The current HTTP request.
*
* @return \Drupal\Core\Ajax\AjaxResponse
* The AJAX response.
*/
public function onRemove(array &$form, FormStateInterface $form_state, Request $request) {
$response = ManagedFile::uploadAjaxCallback($form, $form_state, $request);
$complete_form = $form_state->getCompleteForm();
$selector = '#' . $complete_form['widget']['ief_target']['#id'];
$command = new InvokeCommand($selector, 'empty');
return $response->addCommand($command);
}
/**
* Returns a list of acceptable file extensions for the file upload field.
*
* @return array
* The list of acceptable file extensions.
*/
protected function getAllowedFileUploadExtensions() {
$extensions = [];
$possible_bundles = $this->bundleResolver->getPossibleBundles();
foreach ($possible_bundles as $bundle) {
$field = $this->getSourceFieldForBundle($bundle);
$extensions = array_merge($extensions, preg_split('/,?\s+/', $field->getSetting('file_extensions')));
}
return implode(' ', array_unique($extensions));
}
/**
* {@inheritdoc}
*/
public function defaultConfiguration() {
$configuration = parent::defaultConfiguration();
$configuration['return_file'] = FALSE;
return $configuration;
}
/**
* {@inheritdoc}
*/
public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
$form = parent::buildConfigurationForm($form, $form_state);
$form['return_file'] = [
'#type' => 'checkbox',
'#title' => $this->t('Return source file entity'),
'#default_value' => $this->configuration['return_file'],
'#description' => $this->t('If checked, the source file(s) of the media entity will be returned from this widget.'),
];
return $form;
}
}