Updated to Drupal 8.5. Core Media not yet in use.
[yaffs-website] / web / core / modules / media / media.module
1 <?php
2
3 /**
4  * @file
5  * Provides media items.
6  */
7
8 use Drupal\Core\Access\AccessResult;
9 use Drupal\Core\Entity\EntityInterface;
10 use Drupal\Core\Form\FormStateInterface;
11 use Drupal\Core\Render\Element;
12 use Drupal\Core\Render\Element\RenderElement;
13 use Drupal\Core\Routing\RouteMatchInterface;
14 use Drupal\Core\Session\AccountInterface;
15 use Drupal\Core\Template\Attribute;
16 use Drupal\Core\Url;
17 use Drupal\field\FieldConfigInterface;
18
19 /**
20  * Implements hook_help().
21  */
22 function media_help($route_name, RouteMatchInterface $route_match) {
23   switch ($route_name) {
24     case 'help.page.media':
25       $output = '<h3>' . t('About') . '</h3>';
26       $output .= '<p>' . t('The Media module manages the creation, editing, deletion, settings, and display of media. Items are typically images, documents, slideshows, YouTube videos, tweets, Instagram photos, etc. You can reference media items from any other content on your site. For more information, see the <a href=":media">online documentation for the Media module</a>.', [':media' => 'https://www.drupal.org/docs/8/core/modules/media']) . '</p>';
27       $output .= '<h3>' . t('Uses') . '</h3>';
28       $output .= '<dl>';
29       $output .= '<dt>' . t('Creating media items') . '</dt>';
30       $output .= '<dd>' . t('When a new media item is created, the Media module records basic information about it, including the author, date of creation, and the <a href=":media-type">media type</a>. It also manages the <em>publishing options</em>, which define whether or not the item is published. Default settings can be configured for each type of media on your site.', [':media-type' => Url::fromRoute('entity.media_type.collection')->toString()]) . '</dd>';
31       $output .= '<dt>' . t('Listing media items') . '</dt>';
32       $output .= '<dd>' . t('Media items are listed at the <a href=":media-collection">media administration page</a>.', [
33         ':media-collection' => Url::fromRoute('entity.media.collection')->toString(),
34       ]) . '</dd>';
35       $output .= '<dt>' . t('Creating custom media types') . '</dt>';
36       $output .= '<dd>' . t('The Media module gives users with the <em>Administer media types</em> permission the ability to <a href=":media-new">create new media types</a> in addition to the default ones already configured. Each media type has an associated media source (such as the image source) which support thumbnail generation and metadata extraction. Fields managed by the <a href=":field">Field module</a> may be added for storing that metadata, such as width and height, as well as any other associated values.', [
37         ':media-new' => Url::fromRoute('entity.media_type.add_form')->toString(),
38         ':field' => Url::fromRoute('help.page', ['name' => 'field'])->toString(),
39       ]) . '</dd>';
40       $output .= '<dt>' . t('Creating revisions') . '</dt>';
41       $output .= '<dd>' . t('The Media module also enables you to create multiple versions of any media item, and revert to older versions using the <em>Revision information</em> settings.') . '</dd>';
42       $output .= '<dt>' . t('User permissions') . '</dt>';
43       $output .= '<dd>' . t('The Media module makes a number of permissions available, which can be set by role on the <a href=":permissions">permissions page</a>.', [
44         ':permissions' => Url::fromRoute('user.admin_permissions', [], ['fragment' => 'module-media'])->toString(),
45       ]) . '</dd>';
46       $output .= '<dt>' . t('Adding media to other content') . '</dt>';
47       $output .= '<dd>' . t('Users with permission to administer content types can add media support by adding a media reference field to the content type on the content type administration page. (The same is true of block types, taxonomy terms, user profiles, and other content that supports fields.) A media reference field can refer to any configured media type. It is possible to allow multiple media types in the same field.') . '</dd>';
48       $output .= '</dl>';
49       $output .= '<h3>' . t('Differences between Media, File, and Image reference fields') . '</h3>';
50       $output .= '<p>' . t('<em>Media</em> reference fields offer several advantages over basic <em>File</em> and <em>Image</em> references:') . '</p>';
51       $output .= '<ul>';
52       $output .= '<li>' . t('Media reference fields can reference multiple media types in the same field.') . '</li>';
53       $output .= '<li>' . t('Fields can also be added to media types themselves, which means that custom metadata like descriptions and taxonomy tags can be added for the referenced media. (Basic file and image fields do not support this.)') . '</li>';
54       $output .= '<li>' . t('Media types for audio and video files are provided by default, so there is no need for additional configuration to upload these media.') . '</li>';
55       $output .= '<li>' . t('Contributed or custom projects can provide additional media sources (such as third-party websites, Twitter, etc.).') . '</li>';
56       $output .= '<li>' . t('Existing media items can be reused on any other content items with a media reference field.') . '</li>';
57       $output .= '</ul>';
58       $output .= '<p>' . t('Use <em>Media</em> reference fields for most files, images, audio, videos, and remote media. Use <em>File</em> or <em>Image</em> reference fields when creating your own media types, or for legacy files and images created before enabling the Media module.') . '</p>';
59       return $output;
60   }
61 }
62
63 /**
64  * Implements hook_theme().
65  */
66 function media_theme() {
67   return [
68     'media' => [
69       'render element' => 'elements',
70     ],
71     'media_reference_help' => [
72       'render element' => 'element',
73       'base hook' => 'field_multiple_value_form',
74     ],
75   ];
76 }
77
78 /**
79  * Implements hook_entity_access().
80  */
81 function media_entity_access(EntityInterface $entity, $operation, AccountInterface $account) {
82   if ($operation === 'delete' && $entity instanceof FieldConfigInterface && $entity->getTargetEntityTypeId() === 'media') {
83     /** @var \Drupal\media\MediaTypeInterface $media_type */
84     $media_type = \Drupal::entityTypeManager()->getStorage('media_type')->load($entity->getTargetBundle());
85     return AccessResult::forbiddenIf($entity->id() === 'media.' . $media_type->id() . '.' . $media_type->getSource()->getConfiguration()['source_field']);
86   }
87   return AccessResult::neutral();
88 }
89
90 /**
91  * Implements hook_theme_suggestions_HOOK().
92  */
93 function media_theme_suggestions_media(array $variables) {
94   $suggestions = [];
95   $media = $variables['elements']['#media'];
96   $sanitized_view_mode = strtr($variables['elements']['#view_mode'], '.', '_');
97
98   $suggestions[] = 'media__' . $sanitized_view_mode;
99   $suggestions[] = 'media__' . $media->bundle();
100   $suggestions[] = 'media__' . $media->bundle() . '__' . $sanitized_view_mode;
101
102   return $suggestions;
103 }
104
105 /**
106  * Prepares variables for media templates.
107  *
108  * Default template: media.html.twig.
109  *
110  * @param array $variables
111  *   An associative array containing:
112  *   - elements: An array of elements to display in view mode.
113  *   - media: The media item.
114  *   - name: The label for the media item.
115  *   - view_mode: View mode; e.g., 'full', 'teaser', etc.
116  */
117 function template_preprocess_media(array &$variables) {
118   $variables['media'] = $variables['elements']['#media'];
119   $variables['view_mode'] = $variables['elements']['#view_mode'];
120   $variables['name'] = $variables['media']->label();
121
122   // Helpful $content variable for templates.
123   foreach (Element::children($variables['elements']) as $key) {
124     $variables['content'][$key] = $variables['elements'][$key];
125   }
126 }
127
128 /**
129  * Implements hook_field_ui_preconfigured_options_alter().
130  */
131 function media_field_ui_preconfigured_options_alter(array &$options, $field_type) {
132   // If the field is not an "entity_reference"-based field, bail out.
133   /** @var \Drupal\Core\Field\FieldTypePluginManager $field_type_manager */
134   $field_type_manager = \Drupal::service('plugin.manager.field.field_type');
135   $class = $field_type_manager->getPluginClass($field_type);
136   if (!is_a($class, 'Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem', TRUE)) {
137     return;
138   }
139
140   // Set the default formatter for media in entity reference fields to be the
141   // "Rendered entity" formatter.
142   if (!empty($options['media'])) {
143     $options['media']['entity_view_display']['type'] = 'entity_reference_entity_view';
144   }
145 }
146
147 /**
148  * Implements hook_form_FORM_ID_alter().
149  */
150 function media_form_field_ui_field_storage_add_form_alter(&$form, FormStateInterface $form_state, $form_id) {
151   // Provide some help text to aid users decide whether they need a Media,
152   // File, or Image reference field.
153   $description_text = t('Use <em>Media</em> reference fields for most files, images, audio, videos, and remote media. Use <em>File</em> or <em>Image</em> reference fields when creating your own media types, or for legacy files and images created before enabling the Media module.');
154   if (\Drupal::moduleHandler()->moduleExists('help')) {
155     $description_text .= ' ' . t('For more information, see the <a href="@help_url">Media help page</a>.', [
156       '@help_url' => Url::fromRoute('help.page', ['name' => 'media'])->toString(),
157     ]);
158   }
159   $form['add']['description_wrapper'] = [
160     '#type' => 'container',
161   ];
162   $field_types = [
163     'file',
164     'image',
165     'field_ui:entity_reference:media',
166   ];
167   foreach ($field_types as $field_name) {
168     $form['add']['description_wrapper']["description_{$field_name}"] = [
169       '#type' => 'item',
170       '#markup' => $description_text,
171       '#states' => [
172         'visible' => [
173           ':input[name="new_storage_type"]' => ['value' => $field_name],
174         ],
175       ],
176     ];
177   }
178   $form['add']['new_storage_type']['#weight'] = 0;
179   $form['add']['description_wrapper']['#weight'] = 1;
180 }
181
182 /**
183  * Implements hook_field_widget_multivalue_form_alter().
184  */
185 function media_field_widget_multivalue_form_alter(array &$elements, FormStateInterface $form_state, array $context) {
186   // Do not alter the default settings form.
187   if ($context['default']) {
188     return;
189   }
190
191   // Only act on entity reference fields that reference media.
192   $field_type = $context['items']->getFieldDefinition()->getType();
193   $target_type = $context['items']->getFieldDefinition()->getFieldStorageDefinition()->getSetting('target_type');
194   if ($field_type !== 'entity_reference' ||  $target_type !== 'media') {
195     return;
196   }
197
198   // Autocomplete widgets need different help text than options widgets.
199   $widget_plugin_id = $context['widget']->getPluginId();
200   if (in_array($widget_plugin_id, ['entity_reference_autocomplete', 'entity_reference_autocomplete_tags'])) {
201     $is_autocomplete = TRUE;
202   }
203   else {
204     // @todo We can't yet properly alter non-autocomplete fields. Resolve this
205     //   in https://www.drupal.org/node/2943020 and remove this condition.
206     return;
207   }
208   $elements['#media_help'] = [];
209
210   // Retrieve the media bundle list and add information for the user based on
211   // which bundles are available to be created or referenced.
212   $settings = $context['items']->getFieldDefinition()->getSetting('handler_settings');
213   $allowed_bundles = isset($settings['target_bundles']) ? $settings['target_bundles'] : [];
214   $access_handler = \Drupal::entityTypeManager()->getAccessControlHandler('media');
215   $all_bundles = \Drupal::service('entity_type.bundle.info')->getBundleInfo('media');
216   $bundle_labels = [];
217   $create_bundles = [];
218   foreach ($allowed_bundles as $bundle) {
219     $bundle_labels[] = $all_bundles[$bundle]['label'];
220     if ($access_handler->createAccess($bundle)) {
221       $create_bundles[] = $bundle;
222       if (count($create_bundles) > 1) {
223         // If the user has access to create more than 1 bundle then the
224         // individual media type form can not be used.
225         break;
226       }
227     }
228   }
229
230   // Add a section about how to create media if the user has access to do so.
231   if (!empty($create_bundles)) {
232     if (count($create_bundles) === 1) {
233       $add_url = Url::fromRoute('entity.media.add_form', ['media_type' => $create_bundles[0]])->toString();
234     }
235     elseif (count($create_bundles) > 1) {
236       $add_url = Url::fromRoute('entity.media.add_page')->toString();
237     }
238     $elements['#media_help']['#media_add_help'] = t('Create your media on the <a href=":add_page" target="_blank">media add page</a> (opens a new window), then add it by name to the field below.', [':add_page' => $add_url]);
239   }
240
241   $elements['#theme'] = 'media_reference_help';
242   // @todo template_preprocess_field_multiple_value_form() assumes this key
243   //   exists, but it does not exist in the case of a single widget that
244   //   accepts multiple values. This is for some reason necessary to use
245   //   our template for the entity_autocomplete_tags widget.
246   //   Research and resolve this in https://www.drupal.org/node/2943020.
247   if (empty($elements['#cardinality_multiple'])) {
248     $elements['#cardinality_multiple'] = NULL;
249   }
250
251   // Use the title set on the element if it exists, otherwise fall back to the
252   // field label.
253   $elements['#media_help']['#original_label'] = isset($elements['#title']) ? $elements['#title'] : $context['items']->getFieldDefinition()->getLabel();
254
255   // Customize the label for the field widget.
256   // @todo Research a better approach https://www.drupal.org/node/2943024.
257   $use_existing_label = t('Use existing media');
258   if (!empty($elements[0]['target_id']['#title'])) {
259     $elements[0]['target_id']['#title'] = $use_existing_label;
260   }
261   if (!empty($elements['#title'])) {
262     $elements['#title'] = $use_existing_label;
263   }
264   if (!empty($elements['target_id']['#title'])) {
265     $elements['target_id']['#title'] = $use_existing_label;
266   }
267
268   // This help text is only relevant for autocomplete widgets. When the user
269   // is presented with options, they don't need to type anything or know what
270   // types of media are allowed.
271   if ($is_autocomplete) {
272     $elements['#media_help']['#media_list_help'] = t('Type part of the media name.');
273
274     $overview_url = Url::fromRoute('entity.media.collection');
275     if ($overview_url->access()) {
276       $elements['#media_help']['#media_list_link'] = t('See the <a href=":list_url" target="_blank">media list</a> (opens a new window) to help locate media.', [':list_url' => $overview_url->toString()]);
277     }
278     $elements['#media_help']['#allowed_types_help'] = t('Allowed media types: %types', ['%types' => implode(", ", $bundle_labels)]);
279   }
280 }
281
282 /**
283  * Implements hook_preprocess_HOOK() for media reference widgets.
284  */
285 function media_preprocess_media_reference_help(&$variables) {
286   // Most of these attribute checks are copied from
287   // template_preprocess_fieldset(). Our template extends
288   // field-multiple-value-form.html.twig to provide our help text, but also
289   // groups the information within a semantic fieldset with a legend. So, we
290   // incorporate parity for both.
291   $element = $variables['element'];
292   Element::setAttributes($element, ['id']);
293   RenderElement::setAttributes($element);
294   $variables['attributes'] = isset($element['#attributes']) ? $element['#attributes'] : [];
295   $variables['legend_attributes'] = new Attribute();
296   $variables['header_attributes'] = new Attribute();
297   $variables['description']['attributes'] = new Attribute();
298   $variables['legend_span_attributes'] = new Attribute();
299
300   if (!empty($element['#media_help'])) {
301     foreach ($element['#media_help'] as $key => $text) {
302       $variables[substr($key, 1)] = $text;
303     }
304   }
305 }