media.module 16 KB

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