5 * Provides media items.
8 use Drupal\Component\Plugin\DerivativeInspectionInterface;
9 use Drupal\Core\Access\AccessResult;
10 use Drupal\Core\Entity\EntityInterface;
11 use Drupal\Core\Form\FormStateInterface;
12 use Drupal\Core\Render\Element;
13 use Drupal\Core\Render\Element\RenderElement;
14 use Drupal\Core\Routing\RouteMatchInterface;
15 use Drupal\Core\Session\AccountInterface;
16 use Drupal\Core\Template\Attribute;
18 use Drupal\field\FieldConfigInterface;
19 use Drupal\media\Plugin\media\Source\OEmbedInterface;
22 * Implements hook_help().
24 function media_help($route_name, RouteMatchInterface $route_match) {
25 switch ($route_name) {
26 case 'help.page.media':
27 $output = '<h3>' . t('About') . '</h3>';
28 $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>';
29 $output .= '<h3>' . t('Uses') . '</h3>';
31 $output .= '<dt>' . t('Creating media items') . '</dt>';
32 $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>';
33 $output .= '<dt>' . t('Listing media items') . '</dt>';
34 $output .= '<dd>' . t('Media items are listed at the <a href=":media-collection">media administration page</a>.', [
35 ':media-collection' => Url::fromRoute('entity.media.collection')->toString(),
37 $output .= '<dt>' . t('Creating custom media types') . '</dt>';
38 $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.', [
39 ':media-new' => Url::fromRoute('entity.media_type.add_form')->toString(),
40 ':field' => Url::fromRoute('help.page', ['name' => 'field'])->toString(),
42 $output .= '<dt>' . t('Creating revisions') . '</dt>';
43 $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>';
44 $output .= '<dt>' . t('User permissions') . '</dt>';
45 $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>.', [
46 ':permissions' => Url::fromRoute('user.admin_permissions', [], ['fragment' => 'module-media'])->toString(),
48 $output .= '<dt>' . t('Adding media to other content') . '</dt>';
49 $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>';
51 $output .= '<h3>' . t('Differences between Media, File, and Image reference fields') . '</h3>';
52 $output .= '<p>' . t('<em>Media</em> reference fields offer several advantages over basic <em>File</em> and <em>Image</em> references:') . '</p>';
54 $output .= '<li>' . t('Media reference fields can reference multiple media types in the same field.') . '</li>';
55 $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>';
56 $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>';
57 $output .= '<li>' . t('Contributed or custom projects can provide additional media sources (such as third-party websites, Twitter, etc.).') . '</li>';
58 $output .= '<li>' . t('Existing media items can be reused on any other content items with a media reference field.') . '</li>';
60 $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>';
66 * Implements hook_theme().
68 function media_theme() {
71 'render element' => 'elements',
73 'media_reference_help' => [
74 'render element' => 'element',
75 'base hook' => 'field_multiple_value_form',
77 'media_oembed_iframe' => [
86 * Implements hook_entity_access().
88 function media_entity_access(EntityInterface $entity, $operation, AccountInterface $account) {
89 if ($operation === 'delete' && $entity instanceof FieldConfigInterface && $entity->getTargetEntityTypeId() === 'media') {
90 /** @var \Drupal\media\MediaTypeInterface $media_type */
91 $media_type = \Drupal::entityTypeManager()->getStorage('media_type')->load($entity->getTargetBundle());
92 return AccessResult::forbiddenIf($entity->id() === 'media.' . $media_type->id() . '.' . $media_type->getSource()->getConfiguration()['source_field']);
94 return AccessResult::neutral();
98 * Implements hook_theme_suggestions_HOOK().
100 function media_theme_suggestions_media(array $variables) {
102 /** @var \Drupal\media\MediaInterface $media */
103 $media = $variables['elements']['#media'];
104 $sanitized_view_mode = strtr($variables['elements']['#view_mode'], '.', '_');
106 $suggestions[] = 'media__' . $sanitized_view_mode;
107 $suggestions[] = 'media__' . $media->bundle();
108 $suggestions[] = 'media__' . $media->bundle() . '__' . $sanitized_view_mode;
110 // Add suggestions based on the source plugin ID.
111 $source = $media->getSource();
112 if ($source instanceof DerivativeInspectionInterface) {
113 $source_id = $source->getBaseId();
114 $derivative_id = $source->getDerivativeId();
115 if ($derivative_id) {
116 $source_id .= '__derivative_' . $derivative_id;
120 $source_id = $source->getPluginId();
122 $suggestions[] = "media__source_$source_id";
124 // If the source plugin uses oEmbed, add a suggestion based on the provider
125 // name, if available.
126 if ($source instanceof OEmbedInterface) {
127 $provider_id = $source->getMetadata($media, 'provider_name');
129 $provider_id = \Drupal::transliteration()->transliterate($provider_id);
130 $provider_id = preg_replace('/[^a-z0-9_]+/', '_', mb_strtolower($provider_id));
131 $suggestions[] = end($suggestions) . "__provider_$provider_id";
139 * Prepares variables for media templates.
141 * Default template: media.html.twig.
143 * @param array $variables
144 * An associative array containing:
145 * - elements: An array of elements to display in view mode.
146 * - media: The media item.
147 * - name: The label for the media item.
148 * - view_mode: View mode; e.g., 'full', 'teaser', etc.
150 function template_preprocess_media(array &$variables) {
151 $variables['media'] = $variables['elements']['#media'];
152 $variables['view_mode'] = $variables['elements']['#view_mode'];
153 $variables['name'] = $variables['media']->label();
155 // Helpful $content variable for templates.
156 foreach (Element::children($variables['elements']) as $key) {
157 $variables['content'][$key] = $variables['elements'][$key];
162 * Implements hook_field_ui_preconfigured_options_alter().
164 function media_field_ui_preconfigured_options_alter(array &$options, $field_type) {
165 // If the field is not an "entity_reference"-based field, bail out.
166 /** @var \Drupal\Core\Field\FieldTypePluginManager $field_type_manager */
167 $field_type_manager = \Drupal::service('plugin.manager.field.field_type');
168 $class = $field_type_manager->getPluginClass($field_type);
169 if (!is_a($class, 'Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem', TRUE)) {
173 // Set the default formatter for media in entity reference fields to be the
174 // "Rendered entity" formatter.
175 if (!empty($options['media'])) {
176 $options['media']['entity_view_display']['type'] = 'entity_reference_entity_view';
181 * Implements hook_form_FORM_ID_alter().
183 function media_form_field_ui_field_storage_add_form_alter(&$form, FormStateInterface $form_state, $form_id) {
184 // Provide some help text to aid users decide whether they need a Media,
185 // File, or Image reference field.
186 $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.');
187 if (\Drupal::moduleHandler()->moduleExists('help')) {
188 $description_text .= ' ' . t('For more information, see the <a href="@help_url">Media help page</a>.', [
189 '@help_url' => Url::fromRoute('help.page', ['name' => 'media'])->toString(),
192 $form['add']['description_wrapper'] = [
193 '#type' => 'container',
198 'field_ui:entity_reference:media',
200 foreach ($field_types as $field_name) {
201 $form['add']['description_wrapper']["description_{$field_name}"] = [
203 '#markup' => $description_text,
206 ':input[name="new_storage_type"]' => ['value' => $field_name],
211 $form['add']['new_storage_type']['#weight'] = 0;
212 $form['add']['description_wrapper']['#weight'] = 1;
216 * Implements hook_field_widget_multivalue_form_alter().
218 function media_field_widget_multivalue_form_alter(array &$elements, FormStateInterface $form_state, array $context) {
219 // Do not alter the default settings form.
220 if ($context['default']) {
224 // Only act on entity reference fields that reference media.
225 $field_type = $context['items']->getFieldDefinition()->getType();
226 $target_type = $context['items']->getFieldDefinition()->getFieldStorageDefinition()->getSetting('target_type');
227 if ($field_type !== 'entity_reference' || $target_type !== 'media') {
231 // Autocomplete widgets need different help text than options widgets.
232 $widget_plugin_id = $context['widget']->getPluginId();
233 if (in_array($widget_plugin_id, ['entity_reference_autocomplete', 'entity_reference_autocomplete_tags'])) {
234 $is_autocomplete = TRUE;
237 // @todo We can't yet properly alter non-autocomplete fields. Resolve this
238 // in https://www.drupal.org/node/2943020 and remove this condition.
241 $elements['#media_help'] = [];
243 // Retrieve the media bundle list and add information for the user based on
244 // which bundles are available to be created or referenced.
245 $settings = $context['items']->getFieldDefinition()->getSetting('handler_settings');
246 $allowed_bundles = !empty($settings['target_bundles']) ? $settings['target_bundles'] : [];
247 $add_url = _media_get_add_url($allowed_bundles);
249 $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]);
252 $elements['#theme'] = 'media_reference_help';
253 // @todo template_preprocess_field_multiple_value_form() assumes this key
254 // exists, but it does not exist in the case of a single widget that
255 // accepts multiple values. This is for some reason necessary to use
256 // our template for the entity_autocomplete_tags widget.
257 // Research and resolve this in https://www.drupal.org/node/2943020.
258 if (empty($elements['#cardinality_multiple'])) {
259 $elements['#cardinality_multiple'] = NULL;
262 // Use the title set on the element if it exists, otherwise fall back to the
264 $elements['#media_help']['#original_label'] = isset($elements['#title']) ? $elements['#title'] : $context['items']->getFieldDefinition()->getLabel();
266 // Customize the label for the field widget.
267 // @todo Research a better approach https://www.drupal.org/node/2943024.
268 $use_existing_label = t('Use existing media');
269 if (!empty($elements[0]['target_id']['#title'])) {
270 $elements[0]['target_id']['#title'] = $use_existing_label;
272 if (!empty($elements['#title'])) {
273 $elements['#title'] = $use_existing_label;
275 if (!empty($elements['target_id']['#title'])) {
276 $elements['target_id']['#title'] = $use_existing_label;
279 // This help text is only relevant for autocomplete widgets. When the user
280 // is presented with options, they don't need to type anything or know what
281 // types of media are allowed.
282 if ($is_autocomplete) {
283 $elements['#media_help']['#media_list_help'] = t('Type part of the media name.');
285 $overview_url = Url::fromRoute('entity.media.collection');
286 if ($overview_url->access()) {
287 $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()]);
289 $all_bundles = \Drupal::service('entity_type.bundle.info')->getBundleInfo('media');
290 $bundle_labels = array_map(function ($bundle) use ($all_bundles) {
291 return $all_bundles[$bundle]['label'];
292 }, $allowed_bundles);
293 $elements['#media_help']['#allowed_types_help'] = t('Allowed media types: %types', ['%types' => implode(", ", $bundle_labels)]);
298 * Implements hook_preprocess_HOOK() for media reference widgets.
300 function media_preprocess_media_reference_help(&$variables) {
301 // Most of these attribute checks are copied from
302 // template_preprocess_fieldset(). Our template extends
303 // field-multiple-value-form.html.twig to provide our help text, but also
304 // groups the information within a semantic fieldset with a legend. So, we
305 // incorporate parity for both.
306 $element = $variables['element'];
307 Element::setAttributes($element, ['id']);
308 RenderElement::setAttributes($element);
309 $variables['attributes'] = isset($element['#attributes']) ? $element['#attributes'] : [];
310 $variables['legend_attributes'] = new Attribute();
311 $variables['header_attributes'] = new Attribute();
312 $variables['description']['attributes'] = new Attribute();
313 $variables['legend_span_attributes'] = new Attribute();
315 if (!empty($element['#media_help'])) {
316 foreach ($element['#media_help'] as $key => $text) {
317 $variables[substr($key, 1)] = $text;
323 * Returns the appropriate URL to add media for the current user.
325 * @todo Remove in https://www.drupal.org/project/drupal/issues/2938116
327 * @param string[] $allowed_bundles
328 * An array of bundles that should be checked for create access.
330 * @return bool|\Drupal\Core\Url
331 * The URL to add media, or FALSE if the user cannot create any media.
334 * This function is internal and may be removed in a minor release.
336 function _media_get_add_url($allowed_bundles) {
337 $access_handler = \Drupal::entityTypeManager()->getAccessControlHandler('media');
338 $create_bundles = array_filter($allowed_bundles, [$access_handler, 'createAccess']);
340 // Add a section about how to create media if the user has access to do so.
341 if (count($create_bundles) === 1) {
342 return Url::fromRoute('entity.media.add_form', ['media_type' => reset($create_bundles)])->toString();
344 elseif (count($create_bundles) > 1) {
345 return Url::fromRoute('entity.media.add_page')->toString();