You are here

svg_image_field.module in SVG Image Field 2.0.x

Same filename and directory in other branches
  1. 8 svg_image_field.module
  2. 2.1.x svg_image_field.module

File

svg_image_field.module
View source
<?php

/**
 * @file
 * Contains svg_image_field.module.
 */
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Url;
use Drupal\file\FileInterface;
use Drupal\media_library\Form\FileUploadForm;

/**
 * Implements hook_help().
 */
function svg_image_field_help($route_name, RouteMatchInterface $route_match) {
  switch ($route_name) {

    // Main module help for the svg_formatter module.
    case 'help.page.svg_image_field':
      $field_ui_url = \Drupal::moduleHandler()
        ->moduleExists('field_ui') ? Url::fromRoute('help.page', [
        'name' => 'field_ui',
      ])
        ->toString() : '#';
      $output = '';
      $output .= '<h3>' . t('About') . '</h3>';
      $output .= '<p>' . t('The SVG image field module allows you to create fields that contain
 svg image files and to configure svg output. See the <a href=":field">Field module help</a> and
  the <a href=":field_ui">Field UI help</a> pages for terminology and general information on
  entities, fields, and how to create and manage fields.', [
        ':field' => Url::fromRoute('help.page', [
          'name' => 'field',
        ])
          ->toString(),
        ':field_ui' => $field_ui_url,
      ]) . '</p>';
      $output .= '<h3>' . t('Uses') . '</h3>';
      $output .= '<dt>' . t('Configuring svg image fields') . '</dt>';
      $output .= '<dd>' . t('A few of the settings for svg image fields are defined once when you create the field and
      cannot be changed later; these include the choice of public or private file storage and the number of images that can be stored in the field.
       The rest of the settings can be edited later; these settings include the field label, help text, and the subdirectory in the public or private file storage
       where the images will be stored. The editable settings can also have different values for different entity sub-types; for instance,
       if your image field is used on both Page and Article content types, you can store the files in a
        different subdirectory for the two content types.') . '</dd>';
      $output .= '<dd>' . t('For accessibility and search engine optimization, all images that convey meaning on web sites should have alternate text.
       Drupal also allows entry of title text for images, but it can lead to confusion for screen reader users and its use is not recommended.
       SVG image fields can be configured so that alternate and title text fields are enabled or disabled; if enabled, the fields can be set to be required.
        The recommended setting is to enable and require alternate text and disable title text.') . '</dd>';
      $output .= '<dd>' . t('When you create an svg image field, you will need to choose whether the uploaded images will be stored in the public or
 private file directory defined in your settings.php file and shown on the <a href=":file-system">File system page</a>. This choice cannot be changed later.
  You can also configure your field to store files in a subdirectory of the public or private directory; this setting can be changed later and
  can be different for each entity sub-type using the field. For more information on file storage,
  see the <a href=":system-help">System module help page</a>.', [
        ':file-system' => Url::fromRoute('system.file_system_settings')
          ->toString(),
        ':system-help' => Url::fromRoute('help.page', [
          'name' => 'system',
        ])
          ->toString(),
      ]) . '</dd>';
      $output .= '<dd>' . t('The maximum file size that can be uploaded is limited by PHP settings of the server,
 but you can restrict it further by configuring a <em>Maximum upload size</em> in the field settings (this setting can be changed later).
 The maximum file size, either from PHP server settings or field configuration, is automatically displayed to users in the help text of the image field.') . '</dd>';
      $output .= '<dd>' . t('You can also configure a default image that will be used if no image is uploaded in an image field.
       This default can be defined for all instances of the field in the field storage settings when you create a field, and the setting can be overridden
        for each entity sub-type that uses the field.') . '</dd>';
      $output .= '<dt>' . t('Configuring displays and form displays') . '</dt>';
      $output .= '<dd>' . t('On the <em>Manage display</em> page, you can choose the image formatter,
 which determines the image width and height used to display the image in each display mode and whether or not to display the image alt and title.
  On the <em>Manage form display</em> page, you can configure the image upload widget, including setting the preview image max-width and max-height
   shown on the entity edit form.') . '</dd>';
      $output .= '</dl>';
      return $output;
    default:
  }
}

/**
 * Implements hook_theme().
 */
function svg_image_field_theme() {
  return [
    'svg_image_field_formatter' => [
      'variables' => [
        'inline' => FALSE,
        'attributes' => NULL,
        'uri' => NULL,
        'svg_data' => NULL,
        'link_url' => NULL,
      ],
    ],
  ];
}

/**
 * Checks that the file has valid mime type.
 *
 * @param \Drupal\file\FileInterface $file
 *   A file entity.
 *
 * @return array
 *   An empty array if the mime_type is allowed or an array containing an
 *   error message if it's not.
 *
 * @see hook_file_validate()
 */
function svg_image_field_validate_mime_type(FileInterface $file) {
  $errors = [];
  $file_system = \Drupal::service('file_system');
  $file_path = $file_system
    ->realpath($file
    ->getFileUri());
  $mime_type = $file
    ->getMimeType();
  $allowed_mime_types = [
    'image/svg+xml',
    'image/svg',
  ];
  if (in_array($mime_type, $allowed_mime_types) === FALSE) {
    $errors[] = t('Only files with mime type %mime-types-allowed are allowed. Mime type detected %mime-type-detected', [
      '%mime-types-allowed' => implode(',', $allowed_mime_types),
      '%mime-type-detected' => $mime_type,
    ]);
  }
  else {
    $xml = new DOMDocument();
    if (@$xml
      ->load($file_path) === FALSE || $xml
      ->getElementsByTagName('svg')->length === 0) {
      $errors[] = t('File %file-name is not valid svg', [
        '%file-name' => $file
          ->getFilename(),
      ]);
    }
  }
  return $errors;
}

/**
 * Implements hook_media_source_info_alter().
 */
function svg_image_field_media_source_info_alter(array &$sources) {
  $sources['svg']['forms']['media_library_add'] = FileUploadForm::class;
}

/**
 * Prepares variables for `media--media-library.html.twig`
 */
function svg_image_field_preprocess_media__media_library(&$variables) {
  $variables['#attached']['library'][] = 'svg_image_field/media_library';
}

/**
 * Prepares variables for image style templates.
 *
 * @see template_preprocess_image_style()
 */
function svg_image_field_preprocess_image_style(array &$variables) {
  if (isset($variables['image']['#access']) && !$variables['image']['#access']) {
    $extension = pathinfo($variables['uri'], PATHINFO_EXTENSION);
    $extension = mb_strtolower($extension);
    if ($extension === 'svg') {
      $variables['image']['#access'] = TRUE;
      $variables['image']['#attributes']['class'] = 'no-image-style';
    }
  }
}

Functions

Namesort descending Description
svg_image_field_help Implements hook_help().
svg_image_field_media_source_info_alter Implements hook_media_source_info_alter().
svg_image_field_preprocess_image_style Prepares variables for image style templates.
svg_image_field_preprocess_media__media_library Prepares variables for `media--media-library.html.twig`
svg_image_field_theme Implements hook_theme().
svg_image_field_validate_mime_type Checks that the file has valid mime type.