forked from SU-SWS/stanford_media
-
Notifications
You must be signed in to change notification settings - Fork 0
/
stanford_media.module
384 lines (339 loc) · 12.3 KB
/
stanford_media.module
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
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
<?php
/**
* @file
* stanford_media.module
*/
use Drupal\Component\Utility\UrlHelper;
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Entity\Display\EntityViewDisplayInterface;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\file\FileInterface;
use Drupal\media\Entity\MediaType;
use Drupal\media\MediaInterface;
use Drupal\stanford_media\Form\MediaLibraryEmbeddableForm;
use Drupal\stanford_media\Form\MediaLibraryFileUploadForm;
use Drupal\stanford_media\Form\MediaLibraryGoogleFormForm;
/**
* Implements hook_preprocess_HOOK().
*/
function stanford_media_preprocess_field(&$variables) {
if ($variables['entity_type'] != 'media') {
return;
}
/** @var \Drupal\Core\Field\FieldItemListInterface $field_items */
$field_items = $variables['element']['#items'];
/** @var \Drupal\media\MediaInterface $media */
$media = $field_items->getEntity();
if ($media->getSource()->getPluginId() != 'oembed:video') {
return;
}
/** @var \Drupal\media\OEmbed\UrlResolverInterface $url_resolver */
$url_resolver = \Drupal::service('media.oembed.url_resolver');
foreach ($variables['items'] as $delta => &$item) {
if (
isset($item['content']['#attributes']['title']) ||
isset($item['content']['#iframe']['#attributes']['title'])
) {
// Title attribute is already provided.
continue;
}
$url = $media->get($variables['field_name'])->get($delta)->getString();
if ($url && UrlHelper::isValid($url)) {
$oembed_url = $url_resolver->getResourceUrl($url);
if (isset($item['content']['#iframe'])) {
// Support oembed lazyload module.
$item['content']['#iframe']['#attributes']['data-oembed-resource'] = $oembed_url;
}
$item['content']['#attributes']['data-oembed-resource'] = $oembed_url;
$variables['#attached']['library'][] = 'stanford_media/display';
}
}
}
/**
* Implements hook_entity_type_alter().
*/
function stanford_media_entity_type_alter(array &$entity_types) {
// Add route for media entity type to view the usage details.
$entity_types['media']->setLinkTemplate('usage', '/media/{media}/usage');
}
/**
* Implements hook_entity_operation_alter().
*/
/**
* Implements hook_entity_operation().
*/
function stanford_media_entity_operation(EntityInterface $entity) {
$operations = [];
if ($entity->getEntityTypeId() == 'media' && $entity->access('update')) {
$operations['usage'] = [
'title' => t('Usage'),
'weight' => 100,
'url' => $entity->toUrl('usage'),
];
}
return $operations;
}
/**
* Implements hook_ENTITY_TYPE_delete().
*/
function stanford_media_media_delete(MediaInterface $media) {
\Drupal::service('stanford_media')->deleteMediaFiles($media);
}
/**
* Implements hook_entity_bundle_field_info_alter().
*/
function stanford_media_entity_bundle_field_info_alter(&$fields, EntityTypeInterface $entity_type, $bundle) {
if ($entity_type->id() == 'media') {
/** @var \Drupal\media\MediaTypeInterface $media_type */
$media_type = MediaType::load($bundle);
if (!$media_type) {
return;
}
$source = $media_type->getSource();
// If the media type is using the embeddable plugin, add a constraint on the
// unstructured code field.
if ($source->getPluginId() == 'embeddable') {
$unstructured_field = $source->getConfiguration()['unstructured_field_name'] ?? '';
if (isset($fields[$unstructured_field])) {
$fields[$unstructured_field]->addConstraint('embeddable');
}
}
}
}
/**
* Implements hook_ENTITY_TYPE_presave().
*/
function stanford_media_media_presave(MediaInterface $entity) {
$source = MediaType::load($entity->bundle())->getSource();
// When the media entity has raw embed code, modify it using the validation
// plugin before the entity is saved.
if (
$source->getPluginId() == 'embeddable' &&
!\Drupal::currentUser()->hasPermission('bypass embed field validation')
) {
/** @var \Drupal\stanford_media\Plugin\media\Source\Embeddable $source */
if ($source->hasUnstructured($entity)) {
$unstructured_field = $source->getConfiguration()['unstructured_field_name'] ?? '';
$code = $source->getSourceFieldValue($entity);
$code = $source->prepareEmbedCode($code);
$entity->set($unstructured_field, $code);
}
}
}
/**
* Implements hook_field_widget_single_element_form_alter().
*/
function stanford_media_field_widget_single_element_form_alter(array &$element, FormStateInterface $form_state, array $context) {
/** @var \Drupal\Core\Field\FieldItemListInterface $items */
$items = $context['items'];
if ($items->getFieldDefinition()->getType() == 'image') {
$element['#process'][] = [
'\Drupal\stanford_media\StanfordMedia',
'imageWidgetProcess',
];
}
}
/**
* Implements hook_field_widget_WIDGET_TYPE_form_alter().
*/
function stanford_media_field_widget_text_textarea_form_alter(&$element, FormStateInterface $form_state, $context) {
// Adds the library outside ckeditor iframe.
$element['#attached']['library'][] = 'stanford_media/admin';
}
/**
* Implements hook_theme_registry_alter().
*/
function stanford_media_theme_registry_alter(&$theme_registry) {
// Register the path to the template files.
$path = \Drupal::service('extension.list.module')->getPath('stanford_media') . '/templates';
$theme_registry['dropzonejs']['path'] = $path;
}
/**
* Implements hook_ENTITY_TYPE_view_alter().
*/
function stanford_media_media_view_alter(array &$build, EntityInterface $entity, EntityViewDisplayInterface $display) {
if (empty($build['#embed'])) {
return;
}
foreach (_stanford_media_get_dialog_plugins($entity) as $plugin) {
$plugin->embedAlter($build, $entity);
}
$build['#attached']['library'][] = 'stanford_media/display';
}
/**
* Get a list of all plugins applicable for the entity.
*
* @param \Drupal\Core\Entity\EntityInterface $entity
* The media entity to check for plugins.
*
* @return \Drupal\stanford_media\Plugin\MediaEmbedDialogInterface[]
* Array of applicable plugins.
*
* @throws \Drupal\Component\Plugin\Exception\PluginException
*/
function _stanford_media_get_dialog_plugins(EntityInterface $entity) {
$plugins = [];
/** @var \Drupal\stanford_media\Plugin\MediaEmbedDialogManager $dialog_manager */
$dialog_manager = \Drupal::service('plugin.manager.media_embed_dialog_manager');
foreach (array_keys($dialog_manager->getDefinitions()) as $plugin_id) {
/** @var \Drupal\stanford_media\Plugin\MediaEmbedDialogInterface $plugin */
$plugin = $dialog_manager->createInstance($plugin_id, ['entity' => $entity]);
if ($plugin->isApplicable()) {
$plugins[$plugin_id] = $plugin;
}
}
return $plugins;
}
/**
* Implements hook_media_source_info_alter().
*/
function stanford_media_media_source_info_alter(array &$sources) {
$sources['audio_file']['forms']['media_library_add'] = MediaLibraryFileUploadForm::class;
$sources['file']['forms']['media_library_add'] = MediaLibraryFileUploadForm::class;
$sources['image']['forms']['media_library_add'] = MediaLibraryFileUploadForm::class;
$sources['video_file']['forms']['media_library_add'] = MediaLibraryFileUploadForm::class;
$sources['google_form']['forms']['media_library_add'] = MediaLibraryGoogleFormForm::class;
$sources['embeddable']['forms']['media_library_add'] = MediaLibraryEmbeddableForm::class;
}
/**
* Implements hook_preprocess_HOOK().
*/
function stanford_media_preprocess_dropzonejs(&$variables) {
// Adds additional things to the template for the dropzone js widget.
$variables['allowed_files'] = str_replace(' ', ', ', $variables['element']['#extensions']);
}
/**
* Implements hook_preprocess_HOOK().
*/
function stanford_media_preprocess_media(&$variables) {
/** @var \Drupal\media\MediaInterface $media */
$media = $variables['media'];
if ($media->getSource()->getPluginId() != 'file') {
return;
}
$media_type = \Drupal::entityTypeManager()
->getStorage('media_type')
->load($media->bundle());
$source_field = $media->getSource()
->getSourceFieldDefinition($media_type)
->getName();
if (empty($variables['content'][$source_field][0]['#description'])) {
$variables['content'][$source_field][0]['#description'] = $variables['name'];
}
}
/**
* Implements hook_preprocess_HOOK().
*/
function stanford_media_preprocess_filter_caption(&$variables) {
if (!isset($variables['classes'])) {
$variables['classes'] = '';
}
$variables['classes'] = trim($variables['classes'] . ' caption');
}
/**
* Implements hook_ENTITY_TYPE_prepare_form().
*/
function stanford_media_media_prepare_form(MediaInterface $media, $operation, FormStateInterface $form_state) {
/** @var \Drupal\entity_usage\EntityUsageInterface $entity_usage_service */
$entity_usage_service = \Drupal::service('entity_usage.usage');
$sources = $entity_usage_service->listSources($media);
$count = 0;
foreach ($sources as $source) {
$count += count($source);
}
// Display a message to the user to alert them than editing will affect
// multiple pieces of content.
if ($count) {
$message = \Drupal::translation()->formatPlural(
$count,
'Changing this media item will affect %count piece of content.',
'Changing this media item will affect %count pieces of content.',
['%count' => $count]
);
\Drupal::messenger()->addWarning($message);
}
}
/**
* Implements hook_entity_access().
*
* Restrict access to media entities that are used as field default values.
*/
function stanford_media_entity_access(EntityInterface $entity, $operation, AccountInterface $account) {
// Only lock down the media entities since they are the default field values
// that we care about.
if (
$entity->getEntityTypeId() != 'media' ||
!in_array($operation, ['update', 'delete'])
) {
return AccessResult::neutral();
}
$configs = \Drupal::configFactory()->listAll('field.field.');
foreach ($configs as $config_name) {
$config = \Drupal::config($config_name);
// Check for the fields we are interested in by checking their type and
// handler settings.
if (
$config->get('field_type') == 'entity_reference' &&
$config->get('settings.handler') == 'default:media' &&
!empty($config->get('default_value'))
) {
$default_value = $config->get('default_value');
// The field default value matches the current media entity, so we want to
// forbid editing/deleting if the user doesn't have the proper permission.
if (!empty($default_value[0]['target_uuid']) && $entity->uuid() == $default_value[0]['target_uuid']) {
return AccessResult::forbiddenIf(!$account->hasPermission('edit field default media'), 'The entity is set as a default field value.');
}
}
}
return AccessResult::neutral();
}
/**
* Implements hook_ENTITY_TYPE_insert().
*/
function stanford_media_file_insert(FileInterface $file) {
$extension = pathinfo($file->getFileUri(), PATHINFO_EXTENSION);
$file_path = \Drupal::service('file_system')->realpath($file->getFileUri());
if (
!in_array($extension, ['jpg', 'jpeg', 'png']) ||
!file_exists($file_path) ||
!class_exists('Imagick')
) {
return;
}
try {
$image = new Imagick($file_path);
switch ($image->getImageOrientation()) {
case imagick::ORIENTATION_BOTTOMRIGHT:
// Rotate 180 degrees.
$image->rotateimage("#000", 180);
break;
case imagick::ORIENTATION_RIGHTTOP:
// Rotate 90 degrees CW.
$image->rotateimage("#000", 90);
break;
case imagick::ORIENTATION_LEFTBOTTOM:
// Rotate 90 degrees CCW.
$image->rotateimage("#000", -90);
break;
}
// Now that it's rotated, set the orientation, before stripping all other
// tags.
$image->setImageOrientation(imagick::ORIENTATION_TOPLEFT);
// 1. Extract the ICC profile
// 2. Strip EXIF data and image profile
// 3. Add the ICC profile back
$profiles = $image->getImageProfiles('icc');
$image->stripImage();
if (isset($profiles['icc'])) {
$image->profileImage('icc', $profiles['icc']);
}
$image->writeImage($file_path);
}
catch (\Exception $e) {
\Drupal::logger('stanford_media')
->error('Unable to strip metadata & fix orientation from image: %path', ['%path' => $file_path]);
}
}