123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528 |
- <?php
- use Drupal\Component\Plugin\DerivativeInspectionInterface;
- use Drupal\Core\Access\AccessResult;
- use Drupal\Core\Entity\EntityInterface;
- use Drupal\Core\Form\FormStateInterface;
- use Drupal\Core\Render\Element;
- use Drupal\Core\Render\Element\RenderElement;
- use Drupal\Core\Routing\RouteMatchInterface;
- use Drupal\Core\Session\AccountInterface;
- use Drupal\Core\Template\Attribute;
- use Drupal\Core\Url;
- use Drupal\field\FieldConfigInterface;
- use Drupal\media\Plugin\media\Source\OEmbedInterface;
- use Drupal\views\ViewExecutable;
- function media_help($route_name, RouteMatchInterface $route_match) {
- switch ($route_name) {
- case 'help.page.media':
- $output = '<h3>' . t('About') . '</h3>';
- $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>';
- $output .= '<h3>' . t('Uses') . '</h3>';
- $output .= '<dl>';
- $output .= '<dt>' . t('Creating media items') . '</dt>';
- $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>';
- $output .= '<dt>' . t('Listing media items') . '</dt>';
- $output .= '<dd>' . t('Media items are listed at the <a href=":media-collection">media administration page</a>.', [
- ':media-collection' => Url::fromRoute('entity.media.collection')->toString(),
- ]) . '</dd>';
- $output .= '<dt>' . t('Creating custom media types') . '</dt>';
- $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.', [
- ':media-new' => Url::fromRoute('entity.media_type.add_form')->toString(),
- ':field' => Url::fromRoute('help.page', ['name' => 'field'])->toString(),
- ]) . '</dd>';
- $output .= '<dt>' . t('Creating revisions') . '</dt>';
- $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>';
- $output .= '<dt>' . t('User permissions') . '</dt>';
- $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>.', [
- ':permissions' => Url::fromRoute('user.admin_permissions', [], ['fragment' => 'module-media'])->toString(),
- ]) . '</dd>';
- $output .= '<dt>' . t('Adding media to other content') . '</dt>';
- $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>';
- $output .= '</dl>';
- $output .= '<h3>' . t('Differences between Media, File, and Image reference fields') . '</h3>';
- $output .= '<p>' . t('<em>Media</em> reference fields offer several advantages over basic <em>File</em> and <em>Image</em> references:') . '</p>';
- $output .= '<ul>';
- $output .= '<li>' . t('Media reference fields can reference multiple media types in the same field.') . '</li>';
- $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>';
- $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>';
- $output .= '<li>' . t('Contributed or custom projects can provide additional media sources (such as third-party websites, Twitter, etc.).') . '</li>';
- $output .= '<li>' . t('Existing media items can be reused on any other content items with a media reference field.') . '</li>';
- $output .= '</ul>';
- $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>';
- return $output;
- }
- }
- function media_theme() {
- return [
- 'media' => [
- 'render element' => 'elements',
- ],
- 'media_reference_help' => [
- 'render element' => 'element',
- 'base hook' => 'field_multiple_value_form',
- ],
- 'media_oembed_iframe' => [
- 'variables' => [
- 'media' => NULL,
- 'placeholder_token' => '',
- ],
- ],
- 'media_embed_error' => [
- 'variables' => [
- 'message' => NULL,
- 'attributes' => [],
- ],
- ],
- ];
- }
- function media_entity_access(EntityInterface $entity, $operation, AccountInterface $account) {
- if ($operation === 'delete' && $entity instanceof FieldConfigInterface && $entity->getTargetEntityTypeId() === 'media') {
-
- $media_type = \Drupal::entityTypeManager()->getStorage('media_type')->load($entity->getTargetBundle());
- return AccessResult::forbiddenIf($entity->id() === 'media.' . $media_type->id() . '.' . $media_type->getSource()->getConfiguration()['source_field']);
- }
- return AccessResult::neutral();
- }
- function media_theme_suggestions_media(array $variables) {
- $suggestions = [];
-
- $media = $variables['elements']['#media'];
- $sanitized_view_mode = strtr($variables['elements']['#view_mode'], '.', '_');
- $suggestions[] = 'media__' . $sanitized_view_mode;
- $suggestions[] = 'media__' . $media->bundle();
- $suggestions[] = 'media__' . $media->bundle() . '__' . $sanitized_view_mode;
-
- $source = $media->getSource();
- if ($source instanceof DerivativeInspectionInterface) {
- $source_id = $source->getBaseId();
- $derivative_id = $source->getDerivativeId();
- if ($derivative_id) {
- $source_id .= '__derivative_' . $derivative_id;
- }
- }
- else {
- $source_id = $source->getPluginId();
- }
- $suggestions[] = "media__source_$source_id";
-
-
- if ($source instanceof OEmbedInterface) {
- $provider_id = $source->getMetadata($media, 'provider_name');
- if ($provider_id) {
- $provider_id = \Drupal::transliteration()->transliterate($provider_id);
- $provider_id = preg_replace('/[^a-z0-9_]+/', '_', mb_strtolower($provider_id));
- $suggestions[] = end($suggestions) . "__provider_$provider_id";
- }
- }
- return $suggestions;
- }
- function template_preprocess_media(array &$variables) {
- $variables['media'] = $variables['elements']['#media'];
- $variables['view_mode'] = $variables['elements']['#view_mode'];
- $variables['name'] = $variables['media']->label();
-
- foreach (Element::children($variables['elements']) as $key) {
- $variables['content'][$key] = $variables['elements'][$key];
- }
- }
- function media_field_ui_preconfigured_options_alter(array &$options, $field_type) {
-
-
- $field_type_manager = \Drupal::service('plugin.manager.field.field_type');
- $class = $field_type_manager->getPluginClass($field_type);
- if (!is_a($class, 'Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem', TRUE)) {
- return;
- }
-
-
- if (!empty($options['media'])) {
- $options['media']['entity_view_display']['type'] = 'entity_reference_entity_view';
- }
- }
- function media_form_field_ui_field_storage_add_form_alter(&$form, FormStateInterface $form_state, $form_id) {
-
-
- $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.');
- if (\Drupal::moduleHandler()->moduleExists('help')) {
- $description_text .= ' ' . t('For more information, see the <a href="@help_url">Media help page</a>.', [
- '@help_url' => Url::fromRoute('help.page', ['name' => 'media'])->toString(),
- ]);
- }
- $form['add']['description_wrapper'] = [
- '#type' => 'container',
- ];
- $field_types = [
- 'file',
- 'image',
- 'field_ui:entity_reference:media',
- ];
- foreach ($field_types as $field_name) {
- $form['add']['description_wrapper']["description_{$field_name}"] = [
- '#type' => 'item',
- '#markup' => $description_text,
- '#states' => [
- 'visible' => [
- ':input[name="new_storage_type"]' => ['value' => $field_name],
- ],
- ],
- ];
- }
- $form['add']['new_storage_type']['#weight'] = 0;
- $form['add']['description_wrapper']['#weight'] = 1;
- }
- function media_field_widget_multivalue_form_alter(array &$elements, FormStateInterface $form_state, array $context) {
-
- if ($context['default']) {
- return;
- }
-
- $field_type = $context['items']->getFieldDefinition()->getType();
- $target_type = $context['items']->getFieldDefinition()->getFieldStorageDefinition()->getSetting('target_type');
- if ($field_type !== 'entity_reference' || $target_type !== 'media') {
- return;
- }
-
- $widget_plugin_id = $context['widget']->getPluginId();
- if (in_array($widget_plugin_id, ['entity_reference_autocomplete', 'entity_reference_autocomplete_tags'])) {
- $is_autocomplete = TRUE;
- }
- else {
-
-
- return;
- }
- $elements['#media_help'] = [];
-
-
- $settings = $context['items']->getFieldDefinition()->getSetting('handler_settings');
- $allowed_bundles = !empty($settings['target_bundles']) ? $settings['target_bundles'] : [];
- $add_url = _media_get_add_url($allowed_bundles);
- if ($add_url) {
- $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]);
- }
- $elements['#theme'] = 'media_reference_help';
-
-
-
-
-
- if (empty($elements['#cardinality_multiple'])) {
- $elements['#cardinality_multiple'] = NULL;
- }
-
-
- $elements['#media_help']['#original_label'] = isset($elements['#title']) ? $elements['#title'] : $context['items']->getFieldDefinition()->getLabel();
-
-
- $use_existing_label = t('Use existing media');
- if (!empty($elements[0]['target_id']['#title'])) {
- $elements[0]['target_id']['#title'] = $use_existing_label;
- }
- if (!empty($elements['#title'])) {
- $elements['#title'] = $use_existing_label;
- }
- if (!empty($elements['target_id']['#title'])) {
- $elements['target_id']['#title'] = $use_existing_label;
- }
-
-
-
- if ($is_autocomplete) {
- $elements['#media_help']['#media_list_help'] = t('Type part of the media name.');
- $overview_url = Url::fromRoute('entity.media.collection');
- if ($overview_url->access()) {
- $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()]);
- }
- $all_bundles = \Drupal::service('entity_type.bundle.info')->getBundleInfo('media');
- $bundle_labels = array_map(function ($bundle) use ($all_bundles) {
- return $all_bundles[$bundle]['label'];
- }, $allowed_bundles);
- $elements['#media_help']['#allowed_types_help'] = t('Allowed media types: %types', ['%types' => implode(", ", $bundle_labels)]);
- }
- }
- function media_preprocess_media_reference_help(&$variables) {
-
-
-
-
-
- $element = $variables['element'];
- Element::setAttributes($element, ['id']);
- RenderElement::setAttributes($element);
- $variables['attributes'] = isset($element['#attributes']) ? $element['#attributes'] : [];
- $variables['legend_attributes'] = new Attribute();
- $variables['header_attributes'] = new Attribute();
- $variables['description']['attributes'] = new Attribute();
- $variables['legend_span_attributes'] = new Attribute();
- if (!empty($element['#media_help'])) {
- foreach ($element['#media_help'] as $key => $text) {
- $variables[substr($key, 1)] = $text;
- }
- }
- }
- function _media_get_add_url($allowed_bundles) {
- $access_handler = \Drupal::entityTypeManager()->getAccessControlHandler('media');
- $create_bundles = array_filter($allowed_bundles, [$access_handler, 'createAccess']);
-
- if (count($create_bundles) === 1) {
- return Url::fromRoute('entity.media.add_form', ['media_type' => reset($create_bundles)])->toString();
- }
- elseif (count($create_bundles) > 1) {
- return Url::fromRoute('entity.media.add_page')->toString();
- }
- return FALSE;
- }
- function media_entity_type_alter(array &$entity_types) {
- if (\Drupal::config('media.settings')->get('standalone_url')) {
-
- $entity_type = $entity_types['media'];
- $entity_type->setLinkTemplate('canonical', '/media/{media}');
- }
- }
- function media_form_filter_format_edit_form_alter(array &$form, FormStateInterface $form_state, $form_id) {
-
-
- $form['#validate'][] = 'media_filter_format_edit_form_validate';
- }
- function media_form_filter_format_add_form_alter(array &$form, FormStateInterface $form_state, $form_id) {
-
-
- $form['#validate'][] = 'media_filter_format_edit_form_validate';
- }
- function media_filter_format_edit_form_validate($form, FormStateInterface $form_state) {
- if ($form_state->getTriggeringElement()['#name'] !== 'op') {
- return;
- }
- $allowed_html_path = [
- 'filters',
- 'filter_html',
- 'settings',
- 'allowed_html',
- ];
- $filter_html_settings_path = [
- 'filters',
- 'filter_html',
- 'settings',
- ];
- $filter_html_enabled = $form_state->getValue([
- 'filters',
- 'filter_html',
- 'status',
- ]);
- $media_embed_enabled = $form_state->getValue([
- 'filters',
- 'media_embed',
- 'status',
- ]);
- if (!$media_embed_enabled) {
- return;
- }
- $get_filter_label = function ($filter_plugin_id) use ($form) {
- return (string) $form['filters']['order'][$filter_plugin_id]['filter']['#markup'];
- };
- if ($filter_html_enabled && $form_state->getValue($allowed_html_path)) {
-
- $filter_format = $form_state->getFormObject()->getEntity();
- $filter_html = clone $filter_format->filters()->get('filter_html');
- $filter_html->setConfiguration(['settings' => $form_state->getValue($filter_html_settings_path)]);
- $restrictions = $filter_html->getHTMLRestrictions();
- $allowed = $restrictions['allowed'];
-
- if (!isset($allowed['drupal-media'])) {
- $form_state->setError($form['filters']['settings']['filter_html']['allowed_html'], t('The %media-embed-filter-label filter requires <code><drupal-media></code> among the allowed HTML tags.', [
- '%media-embed-filter-label' => $get_filter_label('media_embed'),
- ]));
- }
- else {
- $required_attributes = [
- 'data-entity-type',
- 'data-entity-uuid',
- ];
-
-
- if ($allowed['drupal-media'] === FALSE) {
- $missing_attributes = $required_attributes;
- }
- else {
- $missing_attributes = array_diff($required_attributes, array_keys($allowed['drupal-media']));
- }
- if ($missing_attributes) {
- $form_state->setError($form['filters']['settings']['filter_html']['allowed_html'], t('The <code><drupal-media></code> tag in the allowed HTML tags is missing the following attributes: <code>%list</code>.', [
- '%list' => implode(', ', $missing_attributes),
- ]));
- }
- }
- }
- $filters = $form_state->getValue('filters');
-
-
- $precedents = [
- 'filter_align',
- 'filter_caption',
- 'filter_html_image_secure',
- ];
- $error_filters = [];
- foreach ($precedents as $filter_name) {
-
- $precedent = $filters[$filter_name];
- if (empty($precedent['status']) || !isset($precedent['weight'])) {
- continue;
- }
- if ($precedent['weight'] >= $filters['media_embed']['weight']) {
- $error_filters[$filter_name] = $get_filter_label($filter_name);
- }
- }
- if (!empty($error_filters)) {
- $error_message = \Drupal::translation()->formatPlural(
- count($error_filters),
- 'The %media-embed-filter-label filter needs to be placed after the %filter filter.',
- 'The %media-embed-filter-label filter needs to be placed after the following filters: %filters.',
- [
- '%media-embed-filter-label' => $get_filter_label('media_embed'),
- '%filter' => reset($error_filters),
- '%filters' => implode(', ', $error_filters),
- ]
- );
- $form_state->setErrorByName('filters', $error_message);
- }
- }
- function media_field_widget_form_alter(&$element, FormStateInterface $form_state, $context) {
-
-
-
- if (!empty($element['#type']) && $element['#type'] == 'text_format') {
- $element['#attributes']['data-media-embed-host-entity-langcode'] = $context['items']->getLangcode();
- }
- }
- function media_views_query_substitutions(ViewExecutable $view) {
- $account = \Drupal::currentUser();
- return [
- '***VIEW_OWN_UNPUBLISHED_MEDIA***' => (int) $account->hasPermission('view own unpublished media'),
- '***ADMINISTER_MEDIA***' => (int) $account->hasPermission('administer media'),
- ];
- }
|