degov-8.x-2.0/modules/degov_common/degov_common.module
modules/degov_common/degov_common.module
<?php
use Drupal\Core\Entity\Display\EntityViewDisplayInterface;
use Drupal\degov_common\DegovOverride;
use Drupal\degov_common\Form\DegovMediaForm;
use Drupal\degov_common\MediaFormAlter;
use Drupal\degov_common\Plugin\views\filter\DegovBundle;
use Drupal\locale\SourceString;
use Drupal\media\MediaInterface;
/**
* Implements hook_views_plugins_filter_alter().
*/
function degov_common_views_plugins_filter_alter(array &$plugins) {
DegovOverride::pluginClass($plugins['bundle'], DegovBundle::class);
}
/**
* Implements hook_views_data_alter().
* Adds custom views fields.
*/
function degov_common_views_data_alter(array &$data) {
// Add the usage field to media.
$data['media']['usage'] = array(
'title' => t('Media Usage'),
'field' => array(
'title' => t('Usage'),
'help' => t('Shows the list of media usage.'),
'id' => 'degov_media_usage',
),
);
}
/**
* Implements hook_theme().
*/
function degov_common_theme() {
return array(
'degov_file_download_link' => array(
'variables' => array('file' => NULL, 'download_link' => NULL, 'icon' => '', 'file_size' => NULL, 'attributes' => NULL),
),
);
}
/**
* Returns a Url for a file download.
*
* @param \Drupal\file\FileInterface $file
* @param array $options
* (optional) Options for the URL object.
*
* @return \Drupal\Core\Url An Url object for the download url.
* An Url object for the download url.
*/
function degov_common_file_download_link($file, $options = []) {
$url = new \Drupal\Core\Url('degov_common.file_download', array('file' => $file->id()), $options);
return $url;
}
/**
* Get file type.
*
* @param $variables
*/
function degov_common_preprocess_degov_file_download_link(&$variables) {
/** @var \Drupal\file\FileInterface $file */
$file = $variables['file'];
$mime_type = $file->getMimeType();
$mime_type = explode('/', $mime_type);
if (!empty($mime_type[1])) {
$variables['file_type'] = $mime_type[1];
} else {
$variables['file_type'] = pathinfo($file->getFileUri(), PATHINFO_EXTENSION);
}
}
/**
* @param \Drupal\file\FileInterface $file
*
* @return array
*/
function degov_common_file_download_render_array($file) {
if ($file instanceof \Drupal\file\FileInterface) {
// Prepare the attributes for the main container of the template.
$attributes = new \Drupal\Core\Template\Attribute();
// Prepare the text and the URL of the link.
$mime_type = $file->getMimeType();
$download_url = degov_common_file_download_link($file, ['attributes' => ['type' => $mime_type . '; length=' . $file->getSize()]]);
return [
'#theme' => 'degov_file_download_link',
'#file' => $file,
'#download_link' => \Drupal\Core\Link::fromTextAndUrl(t('Download'), $download_url),
'#icon' => file_icon_class($mime_type),
'#attributes' => $attributes,
'#file_size' => format_size($file->getSize()),
];
}
}
/**
* Set degov_common module to run the last on some hooks.
* @param $implementations
* @param $hook
*/
function degov_common_module_implements_alter(&$implementations, $hook) {
if (in_array($hook, ['views_plugins_filter_alter', 'entity_type_alter', 'form_alter'])) {
// Move my_module_form_alter() to the end of the list.
// \Drupal::moduleHandler()->getImplementations()
// iterates through $implementations with a foreach loop which PHP iterates
// in the order that the items were added, so to move an item to the end of
// the array, we remove it and then add it.
$group = $implementations['degov_common'];
unset($implementations['degov_common']);
$implementations['degov_common'] = $group;
}
}
/**
* Implements hook_preprocess_node().
*/
function degov_common_preprocess_node(&$variables) {
/** @var \Drupal\node\NodeInterface $node */
$node = $variables['node'];
// Remove the right sidebar paragraph in case no content exists.
if ($node->hasField('field_sidebar_right_paragraphs') && !empty($variables['content']['field_sidebar_right_paragraphs'])) {
unset($variables['content']['field_sidebar_right_paragraphs']);
}
}
/**
* Implements hook_ENTITY_TYPE_view_alter() for media entities.
*
* @param array $build
* @param \Drupal\media\MediaInterface $entity
* @param \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display
*/
function degov_common_media_view_alter(array &$build, MediaInterface $entity, EntityViewDisplayInterface $display) {
// Skip adding contextual links if the Paragraph is in a QuickEdit form context
// to avoid causing conflicts with Quickedit JS
if (\Drupal::routeMatch()->getRouteName() == 'quickedit.field_form') {
return;
}
$build['#contextual_links']['media'] = [
'route_parameters' => [
'media' => $entity->id(),
],
'metadata' => ['changed' => $entity->getChangedTime()],
];
}
/**
* Implements hook_preprocess_HOOK() for media.html.twig.
*
* @see contextual_preprocess()
* @see template_preprocess_paragraph()
*/
function degov_common_preprocess_media(&$variables) {
// Media templates don't normally print the title_suffix, so add the
// contextual links to the content render array.
if (isset($variables['title_suffix']['contextual_links'])) {
$variables['content']['contextual_links'] = $variables['title_suffix']['contextual_links'];
$variables['content']['contextual_links']['#weight'] = -100;
}
if (isset($variables['elements']['#view_mode'])
&& isset($variables['elements']['#media'])
&& $variables['elements']['#view_mode'] === 'usage'
&& $variables['elements']['#media'] instanceof MediaInterface) {
$media = $variables['elements']['#media'];
/* @var \Drupal\entity_reference_integrity\EntityReferenceDependencyManager $dependency_manager */
$dependency_manager = \Drupal::service('entity_reference_integrity.dependency_manager');
if ($dependency_manager->hasDependents($media)) {
$referencing_entities = $dependency_manager->getDependentEntities($media);
foreach ($referencing_entities as $entity_type_id => $entities) {
$build[$entity_type_id]['list'] = [
'#title' => reset($entities)->getEntityType()->getLabel(),
'#theme' => 'item_list',
'#items' => [],
];
/* @var \Drupal\Core\Entity\EntityInterface $entity */
foreach ($entities as $entity) {
$build[$entity_type_id]['list']['#items'][] = $entity->hasLinkTemplate('canonical') ? $entity->toLink() : $entity->label();
}
}
if (!empty($build)) {
$variables['content']['usage'] = $build;
}
}
}
}
/**
* @param $modules
*/
function degov_common_modules_installed($modules) {
foreach ($modules as $module) {
\Drupal::service('degov_config.block_installer')->placeBlockConfig($module);
}
// Flush plugin caches so our facets will be shown.
\Drupal::service('plugin.cache_clearer')->clearCachedDefinitions();
}
/**
* Implements hook_form_FORM_ID_alter().
* Add styles for the ckeditor media browser.
*
* @param array $form
* @param \Drupal\Core\Form\FormStateInterface $form_state
*/
function degov_common_form_entity_browser_ckeditor_media_browser_form_alter(array &$form, \Drupal\Core\Form\FormStateInterface $form_state) {
$form['#attached']['library'][] = 'lightning_media/browser.styling';
}
/**
* Implements hook_form_FORM_ID_alter().
* Add styles for the media browser.
*
* @param array $form
* @param \Drupal\Core\Form\FormStateInterface $form_state
*/
function degov_common_form_entity_browser_media_browser_form_alter(array &$form, \Drupal\Core\Form\FormStateInterface $form_state) {
$form['#attached']['library'][] = 'degov_common/browser.styling';
if (!empty($form['selection_display'])) {
$form['#attributes']['class'][] = 'with-selection clearfix';
$form['widget_selector']['#prefix'] = '<div class="widget-area">';
$form['widget']['#suffix'] = '</div>';
$form['selection_display']['#prefix'] = '<div class="selection-area"><h3>' . t('Selected Items') . '</h3>';
$form['selection_display']['#suffix'] = '</div>';
$form['widget']['actions']['submit']['#value'] = t('Select');
}
}
/**
* Alter menu add/edit form.
* @param array $form
* @param \Drupal\Core\Form\FormStateInterface $form_state
*/
function degov_common_form_menu_link_content_menu_link_content_form_alter(array &$form, \Drupal\Core\Form\FormStateInterface $form_state) {
if (!empty($form['link']['widget'][0]['options']['attributes']['class'])) {
$form['link']['widget'][0]['options']['attributes']['class']['#description'] = t('Geben Sie hier eine <a href="http://fontawesome.io/cheatsheet" target="_blank">Font-Awesome</a> Klasse ein, z.B. "fa-archive", um das entsprechende Icon anzuzeigen (nur erste Menüebene).');
}
}
/**
* Implements hook_entity_type_alter().
*
* It is needed to change the class for media edit form to force thumbnail
* regeneration, because when you change the source image/video/etc (media item)
* the thumbnail is still referencing the old file entity.
*
*/
function degov_common_entity_type_alter(array &$entity_types) {
// Try to set the class for Media edit form from degov_common module to force thumbnail regeneration.
if (isset($entity_types['media'])) {
$entity_type = $entity_types['media'];
$replacement_class = DegovMediaForm::class;
if (get_parent_class($replacement_class) == $entity_type->getFormClass('edit')) {
$entity_type->setFormClass('edit', $replacement_class);
}
$entity_type->setLabelCallback('degov_media_label_callback');
}
}
/**
* @param \Drupal\Core\Entity\EntityInterface $entity
* @param string $entity_type
*
* @return mixed
*/
function degov_media_label_callback($entity) {
if ($entity instanceof \Drupal\media\Entity\Media) {
if ($entity->hasField('field_title') && !$entity->get('field_title')->isEmpty()) {
return $entity->get('field_title')->value;
}
return $entity->name->value;
}
}
/**
* Implements hook_form_alter().
*
* @param $form
* @param \Drupal\Core\Form\FormStateInterface $form_state
* @param $form_id
*/
function degov_common_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
/** @var \Drupal\Core\Form\FormInterface $form_object */
$form_object = $form_state->getFormObject();
if ($form_object->getFormId() === 'media_multiple_delete_confirm') {
\Drupal::service('class_resolver')
->getInstanceFromDefinition(MediaFormAlter::class)
->formAlter($form, $form_state, $form_id);
}
// Alter node forms.
if (method_exists($form_object, 'getBaseFormId') && $form_object->getBaseFormId() == 'node_form') {
// Add the novalidate attribute to node forms. Without this, it is difficult
// to find out why form validation failed (with required fields in hidden
// field groups).
$form['#attributes']['novalidate'] = TRUE;
}
// Alter the media forms.
if (method_exists($form_object, 'getBaseFormId') && $form_object->getBaseFormId() == 'media_form') {
// field_media_in_library now is deprecated, let's restrict access to it.
// @TODO the field comes from lightning, remove the code after eliminating the dependency on Lightning profile.
if (!empty($form['field_media_in_library'])) {
$form['field_media_in_library']['#access'] = FALSE;
}
// Add the novalidate attribute to media forms. Without this, it is difficult
// to find out why form validation failed (with required fields in hidden
// field groups).
$form['#attributes']['novalidate'] = TRUE;
}
}
/**
* @param $source_string
* @param $langcode
* @param $translated_string
* @throws \Drupal\locale\StringStorageException
*/
function degov_common_add_translation($source_string, $langcode, $translated_string) {
// Find existing source string.
$storage = \Drupal::service('locale.storage');
$string = $storage->findString(['source' => $source_string]);
if (is_null($string)) {
$string = new SourceString();
$string->setString($source_string);
$string->setStorage($storage);
$string->save();
}
// Create translation. If one already exists, it will be replaced.
$translation = $storage->createTranslation([
'lid' => $string->lid,
'language' => $langcode,
'translation' => $translated_string,
]);
$translation->save();
}
