View source
<?php
namespace Drupal\geofield_map\Services;
use Drupal;
use Drupal\Component\Utility\Bytes;
use Drupal\Core\File\FileSystemInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\Core\StringTranslation\TranslationInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\file\FileInterface;
use Drupal\file\Entity\File;
use Symfony\Component\Yaml\Yaml;
use Drupal\Core\Url;
use Drupal\Core\Config\Config;
use Drupal\image\Entity\ImageStyle;
use Drupal\Core\Entity\EntityStorageException;
use Symfony\Component\Yaml\Exception\ParseException;
use Drupal\Component\Utility\Unicode;
use Drupal\Core\Utility\LinkGeneratorInterface;
use Drupal\Core\Render\ElementInfoManagerInterface;
use Drupal\Core\File\Exception\NotRegularDirectoryException;
class MarkerIconService {
use StringTranslationTrait;
protected $config;
protected $translationManager;
protected $entityManager;
protected $moduleHandler;
protected $geofieldMapSettings;
protected $fileUploadValidators;
protected $defaultIconElement;
protected $link;
protected $elementInfo;
protected $markersFilesList = [];
protected $allowedExtension;
protected $fileSystem;
protected function setDefaultIconStyle() {
$image_style_path = drupal_get_path('module', 'geofield_map') . '/config/optional/image.style.geofield_map_default_icon_style.yml';
$image_style_data = Yaml::parse(file_get_contents($image_style_path));
$geofield_map_default_icon_style = $this->config
->getEditable('image.style.geofield_map_default_icon_style');
if ($geofield_map_default_icon_style instanceof Config) {
$geofield_map_default_icon_style
->setData($image_style_data)
->save(TRUE);
}
}
protected function fileIsManageableSvg(FileInterface $file) {
return $this->moduleHandler
->moduleExists('svg_image') && $file instanceof FileInterface && svg_image_is_file_svg($file);
}
protected function markersLocationUri() {
return !empty($this->geofieldMapSettings
->get('theming.markers_location.security') . $this->geofieldMapSettings
->get('theming.markers_location.rel_path')) ? $this->geofieldMapSettings
->get('theming.markers_location.security') . $this->geofieldMapSettings
->get('theming.markers_location.rel_path') : 'public://geofieldmap_markers';
}
protected function setMarkersFilesList() {
$markers_files_list = [];
$regex = '/\\.(' . preg_replace('/ +/', '|', preg_quote($this->allowedExtension)) . ')$/i';
$security = $this->geofieldMapSettings
->get('theming.markers_location.security');
$rel_path = $this->geofieldMapSettings
->get('theming.markers_location.rel_path');
try {
$files = $this->fileSystem
->scanDirectory($security . $rel_path, $regex);
$additional_markers_location = $this->geofieldMapSettings
->get('theming.additional_markers_location');
if (!empty($additional_markers_location)) {
$additional_files = $this->fileSystem
->scanDirectory($additional_markers_location, $regex);
$files = array_merge($files, $additional_files);
}
ksort($files, SORT_STRING);
foreach ($files as $k => $file) {
$markers_files_list[$k] = $file->filename;
}
} catch (NotRegularDirectoryException $e) {
watchdog_exception('geofield map set markers fiel list', $e);
}
return $markers_files_list;
}
public function __construct(ConfigFactoryInterface $config_factory, TranslationInterface $string_translation, FileSystemInterface $file_system, EntityTypeManagerInterface $entity_manager, ModuleHandlerInterface $module_handler, LinkGeneratorInterface $link_generator, ElementInfoManagerInterface $element_info) {
$this->config = $config_factory;
$this->stringTranslation = $string_translation;
$this->entityManager = $entity_manager;
$this->moduleHandler = $module_handler;
$this->link = $link_generator;
$this->elementInfo = $element_info;
$this->geofieldMapSettings = $config_factory
->get('geofield_map.settings');
$this->fileSystem = $file_system;
$this->fileUploadValidators = [
'file_validate_extensions' => !empty($this->geofieldMapSettings
->get('theming.markers_extensions')) ? [
$this->geofieldMapSettings
->get('theming.markers_extensions'),
] : [
'gif png jpg jpeg',
],
'geofield_map_file_validate_is_image' => [],
'file_validate_size' => !empty($this->geofieldMapSettings
->get('theming.markers_filesize')) ? [
Bytes::toInt($this->geofieldMapSettings
->get('theming.markers_filesize')),
] : [
Bytes::toInt('250 KB'),
],
];
$this->defaultIconElement = [
'#theme' => 'image',
'#uri' => '',
];
$this->allowedExtension = $this->geofieldMapSettings
->get('theming.markers_extensions');
$this->markersFilesList = $this
->setMarkersFilesList();
}
public function getDefaultIconElement() {
return $this->defaultIconElement;
}
public static function validateIconImageStatus(array $element, FormStateInterface $form_state) {
$clicked_button = end($form_state
->getTriggeringElement()['#parents']);
if (!empty($element['#value']['fids'][0])) {
$file = File::load($element['#value']['fids'][0]);
if (in_array($clicked_button, [
'save_settings',
'submit',
])) {
$file
->setPermanent();
self::fileSave($file);
}
if ($clicked_button == 'remove_button') {
$file
->setTemporary();
self::fileSave($file);
}
}
}
public static function fileSave(File $file) {
try {
$file
->save();
} catch (EntityStorageException $e) {
Drupal::logger('Geofield Map Themer')
->log('warning', t("The file couldn't be saved: @message", [
'@message' => $e
->getMessage(),
]));
}
}
public function getIconFileManagedElement($fid, $row_id = NULL) {
$upload_location = $this
->markersLocationUri();
$element = $this->elementInfo
->getInfo('managed_file');
$element['#row_id'] = $row_id;
$element['#geofield_map_marker_icon_upload'] = TRUE;
$element['#theme'] = 'image_widget';
$element['#preview_image_style'] = 'geofield_map_default_icon_style';
$element['#title'] = $this
->t('Choose a Marker Icon file');
$element['#title_display'] = 'invisible';
$element['#default_value'] = !empty($fid) ? [
$fid,
] : NULL;
$element['#error_no_message'] = FALSE;
$element['#upload_location'] = $upload_location;
$element['#upload_validators'] = $this->fileUploadValidators;
$element['#progress_message'] = $this
->t('Please wait...');
$element['#element_validate'] = [
[
get_class($this),
'validateIconImageStatus',
],
];
$element['#process'][] = [
get_class($this),
'processSvgManagedFile',
];
return $element;
}
public static function processSvgManagedFile(array &$element, FormStateInterface $form_state, array &$complete_form) {
$file_is_svg = FALSE;
if (isset($element['fids']) && !empty($element['fids']['#value'])) {
$fid = $element['fids']['#value'][0];
$file_is_svg = ($file = $element['#files'][$fid]) && \Drupal::service('geofield_map.marker_icon')
->fileIsManageableSvg($file);
}
$element['is_svg'] = [
'#type' => 'checkbox',
'#value' => $file_is_svg,
'#dafault_value' => $file_is_svg,
'#attributes' => [
'class' => [
'visually-hidden',
],
],
];
return $element;
}
public function getIconFileSelectElement($file_uri, $row_id = NULL) {
$options = array_merge([
'none' => '_ none _',
], $this
->getMarkersFilesList());
$element = [
'#row_id' => $row_id,
'#geofield_map_marker_icon_select' => TRUE,
'#title' => $this
->t('Marker'),
'#type' => 'select',
'#options' => $options,
'#default_value' => $file_uri,
'#description' => $this
->t('Choose among the markers files available'),
];
return $element;
}
public function getImageStyleOptions() {
$options = [
'none' => $this
->t('<- Original File ->'),
];
if ($this->moduleHandler
->moduleExists('image')) {
if (!ImageStyle::load('geofield_map_default_icon_style')) {
try {
$this
->setDefaultIconStyle();
} catch (ParseException $e) {
}
}
$image_styles = ImageStyle::loadMultiple();
foreach ($image_styles as $k => $style) {
$options[$k] = Unicode::truncate($style
->label(), 20, TRUE, TRUE);
}
}
return $options;
}
public function getFileUploadHelp() {
$element = [
'#type' => 'html_tag',
'#tag' => 'div',
'file_upload_help' => [
'#theme' => 'file_upload_help',
'#upload_validators' => $this->fileUploadValidators,
'#cardinality' => 1,
],
'geofield_map_settings_link' => [
'#type' => 'html_tag',
'#tag' => 'div',
'#value' => $this
->t('Customize this in @geofield_map_settings_page_link', [
'@geofield_map_settings_page_link' => $this->link
->generate('Geofield Map Settings Page', Url::fromRoute('geofield_map.settings')),
]),
],
'#attributes' => [
'style' => [
'style' => 'font-size:0.9em; color: gray; font-weight: normal',
],
],
];
if (!$this->moduleHandler
->moduleExists('svg_image')) {
$element['svg_support'] = [
'#type' => 'html_tag',
'#tag' => 'div',
'#value' => $this
->t('SVG Files support is disabled. Enabled it with @svg_image_link', [
'@svg_image_link' => $this->link
->generate('SVG Image Module', Url::fromUri('https://www.drupal.org/project/svg_image', [
'absolute' => TRUE,
'attributes' => [
'target' => 'blank',
],
])),
]),
];
}
else {
$element['svg_support'] = [
'#type' => 'html_tag',
'#tag' => 'div',
'#value' => $this
->t('SVG Files support enabled.'),
];
}
return $element;
}
public function getFileSelectHelp() {
$element = [
'#type' => 'html_tag',
'#tag' => 'div',
'#value' => $this
->t('Select among the files available in the Theming Markers Location:<br>@markers_location,<br>Looked extensions: @allowed_extensions<br>Customize this in: @geofield_map_settings_page_link', [
'@markers_location' => $this
->markersLocationUri(),
'@allowed_extensions' => implode(', ', explode(' ', $this->allowedExtension)),
'@geofield_map_settings_page_link' => $this->link
->generate('Geofield Map Settings Page', Url::fromRoute('geofield_map.settings')),
]),
'#attributes' => [
'style' => [
'style' => 'font-size:0.9em; color: gray; font-weight: normal',
],
],
];
return $element;
}
public function getLegendIconFromFid($fid, $image_style = 'none') {
$icon_element = [];
try {
$file = $this->entityManager
->getStorage('file')
->load($fid);
if ($file instanceof FileInterface) {
$this->defaultIconElement['#uri'] = $file
->getFileUri();
switch ($image_style) {
case 'none':
$icon_element = [
'#weight' => -10,
'#theme' => 'image',
'#uri' => $file
->getFileUri(),
];
break;
default:
$icon_element = [
'#weight' => -10,
'#theme' => 'image_style',
'#uri' => $file
->getFileUri(),
'#style_name' => '',
];
if ($this->moduleHandler
->moduleExists('image') && ImageStyle::load($image_style) && !$this
->fileIsManageableSvg($file)) {
$icon_element['#style_name'] = $image_style;
}
else {
$icon_element = $this->defaultIconElement;
}
}
}
} catch (\Exception $e) {
watchdog_exception('geofield_map', $e);
}
return $icon_element;
}
public function getLegendIconFromFileUri($file_uri, $icon_width = NULL) {
$icon_element = [
'#theme' => 'image',
'#uri' => file_create_url($file_uri),
'#attributes' => [
'width' => $icon_width,
],
];
return $icon_element;
}
public function getUriFromFid($fid = NULL) {
try {
if (isset($fid) && ($file = $this->entityManager
->getStorage('file')
->load($fid))) {
return $file
->getFileUri();
}
} catch (\Exception $e) {
watchdog_exception('geofield_map', $e);
}
return NULL;
}
public function getMarkersFilesList() {
return $this->markersFilesList;
}
public function getFileManagedUrl($fid = NULL, $image_style = 'none') {
try {
if (isset($fid) && ($file = $this->entityManager
->getStorage('file')
->load($fid))) {
$uri = $file
->getFileUri();
if ($this->moduleHandler
->moduleExists('image') && $image_style != 'none' && ImageStyle::load($image_style) && !$this
->fileIsManageableSvg($file)) {
$url = ImageStyle::load($image_style)
->buildUrl($uri);
}
else {
$url = file_create_url($uri);
}
return $url;
}
} catch (\Exception $e) {
watchdog_exception('geofield_map', $e);
}
return NULL;
}
public function getFileSelectedUrl($file_uri = NULL) {
if (isset($file_uri)) {
$url = file_create_url($file_uri);
return $url;
}
return NULL;
}
}