View source
<?php
namespace Drupal\juicebox;
use Drupal\Core\Messenger\MessengerInterface;
use Symfony\Component\HttpFoundation\RequestStack;
use Drupal\Core\Path\CurrentPathStack;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Routing\UrlGeneratorInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Component\Render\FormattableMarkup;
use Drupal\Component\Utility\Html;
use Drupal\file\FileInterface;
use Drupal\Core\StringTranslation\TranslationInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Security\TrustedCallbackInterface;
use Drupal\Core\Render\Element;
class JuiceboxFormatter implements JuiceboxFormatterInterface, TrustedCallbackInterface {
use StringTranslationTrait;
protected $configFactory;
protected $urlGenerator;
protected $moduleManager;
protected $currentPathStack;
protected $request;
protected static $library = [];
protected $messenger;
protected $entityTypeManager;
public function __construct(ConfigFactoryInterface $config_factory, TranslationInterface $string_translation, UrlGeneratorInterface $url_generator, ModuleHandlerInterface $module_manager, CurrentPathStack $currentPathStack, RequestStack $request_stack, MessengerInterface $messenger_interface, EntityTypeManagerInterface $entity_type_manager) {
$this->configFactory = $config_factory;
$this->stringTranslation = $string_translation;
$this->urlGenerator = $url_generator;
$this->moduleManager = $module_manager;
$this->currentPathStack = $currentPathStack;
$this->request = $request_stack
->getCurrentRequest();
$this->messenger = $messenger_interface;
$this->entityTypeManager = $entity_type_manager;
}
public static function trustedCallbacks() {
return [
'preRenderFieldsets',
];
}
public static function preRenderFieldsets($form) {
foreach (Element::children($form) as $key) {
$element = $form[$key];
if (isset($element['#jb_fieldset']) && isset($form[$element['#jb_fieldset']])) {
$form[$element['#jb_fieldset']][$key] = $element;
unset($form[$key]);
}
}
return $form;
}
public function newGallery(array $id_args) {
$id = '';
foreach ($id_args as $arg) {
$arg = preg_replace('/[^0-9a-zA-Z-]/', '-', $arg);
$id .= $arg . '--';
}
$id = trim($id, '- ');
$library = $this
->getLibrary();
$class = 'Drupal\\juicebox\\JuiceboxGallery';
$this->moduleManager
->alter('juicebox_gallery_class', $class, $library);
$object_settings = [
'filter_markup' => $this->configFactory
->get('juicebox.settings')
->get('apply_markup_filter'),
'process_attributes' => FALSE,
];
$gallery = new $class($id, $object_settings);
if ($gallery instanceof JuiceboxGalleryInterface) {
return $gallery;
}
throw new \Exception('Could not instantiate Juicebox gallery.');
}
public function getGlobalSettings() {
return $this->configFactory
->get('juicebox.settings')
->get();
}
public function getLibrary($force_local = FALSE, $reset = FALSE) {
if (file_exists(DRUPAL_ROOT . '/' . 'sites/all/libraries/juicebox/juicebox.js')) {
$librarypath = '/sites/all/libraries/juicebox/juicebox.js';
}
elseif (file_exists(DRUPAL_ROOT . '/' . 'libraries/juicebox/juicebox.js')) {
$librarypath = '/libraries/juicebox/juicebox.js';
}
if (isset($librarypath)) {
juicebox_build_library_array($librarypath, $library);
}
else {
$notification_top = $this
->t('The Juicebox Javascript library does not appear to be installed. Please download and install the most recent version of the Juicebox library.');
$this->messenger
->addError($notification_top);
}
return $library;
}
public function runCommonBuild(JuiceboxGalleryInterface $gallery, array $settings, $data = NULL) {
$global_settings = $this
->getGlobalSettings();
$this
->setGalleryOptions($gallery, $settings);
if ($global_settings['translate_interface']) {
$base_string = $global_settings['base_languagelist'];
if (!empty($base_string)) {
$base_string = Html::escape($base_string);
$gallery
->addOption('languagelist', $base_string, FALSE);
}
}
$this->moduleManager
->alter('juicebox_gallery', $gallery, $data);
}
public function buildEmbed(JuiceboxGalleryInterface $gallery, array $settings, array $xml_route_info, $add_js = TRUE, $add_xml = FALSE, array $contextual = []) {
$settings = $settings + $this
->getGlobalSettings();
$xml_route_info += [
'route_name' => '',
'route_parameters' => [],
'options' => [],
];
$embed_id = $gallery
->getId();
$embed_xml_id = 'xml--' . $embed_id;
$output = [
'#gallery' => $gallery,
'#theme' => 'juicebox_embed_markup',
'#settings' => $settings,
'#attached' => [],
'#contextual_links' => $contextual + [
'juicebox_conf_global' => [
'route_parameters' => [],
],
],
'#cache' => [
'tags' => [
'juicebox_gallery',
],
],
'#suffix' => '',
];
if ($add_js) {
$embed_query_additions = [];
if ($add_xml) {
$embed_query_additions['xml-source-path'] = trim($this->currentPathStack
->getPath(), '/');
$embed_query_additions['xml-source-id'] = $embed_xml_id;
}
$xml_query_additions = array_merge([
'checksum' => $gallery
->getChecksum(),
], $embed_query_additions);
$xml_options = array_merge_recursive([
'query' => $xml_query_additions,
], $xml_route_info['options']);
$xml_url = $this->urlGenerator
->generateFromRoute($xml_route_info['route_name'], $xml_route_info['route_parameters'], $xml_options);
if (file_exists(DRUPAL_ROOT . '/' . 'sites/all/libraries/juicebox/juicebox.js')) {
$output['#attached']['library'][] = 'juicebox/juicebox.sites';
}
elseif (file_exists(DRUPAL_ROOT . '/' . 'libraries/juicebox/juicebox.js')) {
$output['#attached']['library'][] = 'juicebox/juicebox';
}
else {
$notification_top = $this
->t('The Juicebox Javascript library does not appear to be installed. Please download and install the most recent version of the Juicebox library.');
$this->messenger
->addError($notification_top);
}
$output['#attached']['drupalSettings']['juicebox'] = [
$embed_id => $gallery
->getJavascriptVars($xml_url),
];
$output['#attached']['library'][] = 'juicebox/juicebox.local';
}
if ($add_xml) {
$output['#suffix'] .= $gallery
->renderXml($embed_xml_id);
}
$output['#suffix'] = new FormattableMarkup($output['#suffix'], []);
return $output;
}
public function styleImageSrcData(FileInterface $image_file, $image_style, FileInterface $thumb_file, $thumb_style, array $settings) {
$check_incompatible = !empty($settings['incompatible_file_action']);
$src_data = [];
$src_data = $this
->styleImage($image_file, $image_style, $check_incompatible);
$src_data['thumbURL'] = '';
if (!$src_data['juicebox_compatible'] && $image_file
->id() == $thumb_file
->id()) {
$src_data['thumbURL'] = $src_data['imageURL'];
}
else {
$thumb_image_data = $this
->styleImage($thumb_file, $thumb_style, $check_incompatible);
$src_data['thumbURL'] = $thumb_image_data['imageURL'];
}
$src_data['linkURL'] = $src_data['unstyled_src'];
if ($src_data['juicebox_compatible'] && !empty($settings['linkurl_source']) && $settings['linkurl_source'] == 'image_styled') {
$src_data['linkURL'] = $src_data['imageURL'];
}
$src_data['linkTarget'] = !empty($settings['linkurl_target']) ? $settings['linkurl_target'] : '_blank';
return $src_data;
}
protected function styleImage(FileInterface $file, $style, $check_compatible = TRUE) {
$global_settings = $this
->getGlobalSettings();
$library = $this
->getLibrary();
$mimetype = $file
->getMimeType();
$image_data = [];
$image_data['juicebox_compatible'] = TRUE;
$image_data['unstyled_src'] = file_create_url($file
->getFileUri());
if ($check_compatible && !empty($library['compatible_mimetypes']) && !in_array($mimetype, $library['compatible_mimetypes'])) {
$image_data['juicebox_compatible'] = FALSE;
$icon_dir = drupal_get_path('module', 'juicebox') . '/images/mimetypes';
$type_parts = explode('/', $mimetype);
$icon_path = $icon_dir . '/' . reset($type_parts) . '.png';
if (file_exists($icon_path)) {
$image_data['imageURL'] = file_create_url($icon_path);
}
else {
$image_data['imageURL'] = file_create_url($icon_dir . '/general.png');
}
}
else {
$sizes = [
'imageURL' => $style,
];
if ($style == 'juicebox_multisize') {
$sizes = [
'smallImageURL' => $global_settings['juicebox_multisize_small'],
'imageURL' => $global_settings['juicebox_multisize_medium'],
'largeImageURL' => $global_settings['juicebox_multisize_large'],
];
}
foreach ($sizes as $size => $style_each) {
if (!empty($style_each)) {
$style_obj = $this->entityTypeManager
->getStorage('image_style')
->load($style_each);
if ($style_obj) {
$image_data[$size] = $style_obj
->buildUrl($file
->getFileUri());
}
}
else {
$image_data[$size] = $image_data['unstyled_src'];
}
}
}
return $image_data;
}
protected function setGalleryOptions(JuiceboxGalleryInterface $gallery, array $settings) {
foreach ([
'jlib_galleryWidth',
'jlib_galleryHeight',
'jlib_backgroundColor',
'jlib_textColor',
'jlib_thumbFrameColor',
] as $name) {
if (isset($settings[$name])) {
$name_real = str_replace('jlib_', '', $name);
$gallery
->addOption(mb_strtolower($name_real), trim(Html::escape($settings[$name])));
}
}
foreach ([
'jlib_showOpenButton',
'jlib_showExpandButton',
'jlib_showThumbsButton',
'jlib_useThumbDots',
'jlib_useFullscreenExpand',
] as $name) {
if (isset($settings[$name])) {
$name_real = str_replace('jlib_', '', $name);
$gallery
->addOption(mb_strtolower($name_real), !empty($settings[$name]) ? 'TRUE' : 'FALSE');
}
}
if (!empty($settings['manual_config'])) {
$manual_options = explode("\n", $settings['manual_config']);
foreach ($manual_options as $option) {
$option = trim($option);
if (!empty($option)) {
$matches = [];
preg_match('/^([A-Za-z0-9]+?)="([^"]+?)"$/u', $option, $matches);
list(, $name, $value) = $matches;
$gallery
->addOption(mb_strtolower($name), Html::escape($value));
}
}
}
}
public function confBaseOptions() {
return [
'jlib_galleryWidth' => '100%',
'jlib_galleryHeight' => '100%',
'jlib_backgroundColor' => '#222222',
'jlib_textColor' => 'rgba(255,255,255,1)',
'jlib_thumbFrameColor' => 'rgba(255,255,255,.5)',
'jlib_showOpenButton' => 1,
'jlib_showExpandButton' => 1,
'jlib_showThumbsButton' => 1,
'jlib_useThumbDots' => 0,
'jlib_useFullscreenExpand' => 0,
'manual_config' => '',
'custom_parent_classes' => '',
'apply_markup_filter' => 1,
'linkurl_source' => '',
'linkurl_target' => '_blank',
'incompatible_file_action' => 'show_icon_and_link',
];
}
public function confBaseForm(array $form, array $settings) {
$library = $this
->getLibrary();
$disallowed_conf = [];
if (!empty($library) && empty($library['error'])) {
if (empty($library['version'])) {
$notification_top = $this
->t('<strong>Notice:</strong> Your Juicebox Library version could not be detected. Some options below may not function correctly.');
}
elseif (!empty($library['disallowed_conf'])) {
$disallowed_conf = $library['disallowed_conf'];
$notification_top = $this
->t('<strong>Notice:</strong> You are currently using Juicebox library version <strong>@version</strong> which is not compatible with some of the options listed below. These options will appear disabled until you upgrade to the most recent Juicebox library version.', [
'@version' => $library['version'],
]);
$notification_label = $this
->t(' (not available in @version)', [
'@version' => $library['version'],
]);
}
}
else {
$notification_top = $this
->t('The Juicebox Javascript library does not appear to be installed. Please download and install the most recent version of the Juicebox library.');
$this->messenger
->addError($notification_top);
$form['#pre_render'] = [
static::class . '::preRenderFieldsets',
];
return $form;
}
$form['juicebox_config'] = [
'#type' => 'details',
'#title' => $this
->t('Juicebox Library - Lite Config'),
'#open' => FALSE,
'#description' => !empty($notification_top) ? '<p>' . $notification_top . '</p>' : '',
'#weight' => 10,
];
$form['jlib_galleryWidth'] = [
'#jb_fieldset' => 'juicebox_config',
'#type' => 'textfield',
'#title' => $this
->t('Gallery Width'),
'#description' => $this
->t('Set the gallery width in a standard numeric format (such as 100% or 300px).'),
'#element_validate' => [
'juicebox_element_validate_dimension',
],
];
$form['jlib_galleryHeight'] = [
'#jb_fieldset' => 'juicebox_config',
'#type' => 'textfield',
'#title' => $this
->t('Gallery Height'),
'#description' => $this
->t('Set the gallery height in a standard numeric format (such as 100% or 300px).'),
'#element_validate' => [
'juicebox_element_validate_dimension',
],
];
$form['jlib_backgroundColor'] = [
'#jb_fieldset' => 'juicebox_config',
'#type' => 'textfield',
'#title' => $this
->t('Background Color'),
'#description' => $this
->t('Set the gallery background color as a CSS3 color value (such as rgba(10,50,100,0.7) or #FF00FF).'),
];
$form['jlib_textColor'] = [
'#jb_fieldset' => 'juicebox_config',
'#type' => 'textfield',
'#title' => $this
->t('Text Color'),
'#description' => $this
->t('Set the color of all gallery text as a CSS3 color value (such as rgba(255,255,255,1) or #FF00FF).'),
];
$form['jlib_thumbFrameColor'] = [
'#jb_fieldset' => 'juicebox_config',
'#type' => 'textfield',
'#title' => $this
->t('Thumbnail Frame Color'),
'#description' => $this
->t('Set the color of the thumbnail frame as a CSS3 color value (such as rgba(255,255,255,.5) or #FF00FF).'),
];
$form['jlib_showOpenButton'] = [
'#jb_fieldset' => 'juicebox_config',
'#type' => 'checkbox',
'#title' => $this
->t('Show Open Image Button'),
'#description' => $this
->t('Whether to show the "Open Image" button. This will link to the full size version of the image within a new tab to facilitate downloading.'),
];
$form['jlib_showExpandButton'] = [
'#jb_fieldset' => 'juicebox_config',
'#type' => 'checkbox',
'#title' => $this
->t('Show Expand Button'),
'#description' => $this
->t('Whether to show the "Expand" button. Clicking this button expands the gallery to fill the browser window.'),
];
$form['jlib_useFullscreenExpand'] = [
'#jb_fieldset' => 'juicebox_config',
'#type' => 'checkbox',
'#title' => $this
->t('Use Fullscreen Expand'),
'#description' => $this
->t('Whether to trigger fullscreen mode when clicking the expand button (for supported browsers).'),
];
$form['jlib_showThumbsButton'] = [
'#jb_fieldset' => 'juicebox_config',
'#type' => 'checkbox',
'#title' => $this
->t('Show Thumbs Button'),
'#description' => $this
->t('Whether to show the "Toggle Thumbnails" button.'),
];
$form['jlib_useThumbDots'] = [
'#jb_fieldset' => 'juicebox_config',
'#type' => 'checkbox',
'#title' => $this
->t('Show Thumbs Dots'),
'#description' => $this
->t('Whether to replace the thumbnail images with small dots.'),
];
$form['juicebox_manual_config'] = [
'#type' => 'details',
'#title' => $this
->t('Juicebox Library - Pro / Manual Config'),
'#open' => FALSE,
'#description' => $this
->t('Specify any additional Juicebox library configuration options (such as "Pro" options) here.<br/>Options set here always take precedence over those set in the "Lite" options above if there is a conflict.'),
'#weight' => 20,
];
$form['manual_config'] = [
'#jb_fieldset' => 'juicebox_manual_config',
'#type' => 'textarea',
'#title' => $this
->t('Pro / Manual Configuraton Options'),
'#description' => $this
->t('Add one option per line in the format <strong>optionName="optionValue"</strong><br/>See also: http://www.juicebox.net/support/config_options'),
'#element_validate' => [
'juicebox_element_validate_config',
],
];
$form['advanced'] = [
'#type' => 'details',
'#title' => $this
->t('Juicebox - Advanced Options'),
'#open' => FALSE,
'#weight' => 30,
];
$form['incompatible_file_action'] = [
'#jb_fieldset' => 'advanced',
'#type' => 'select',
'#title' => $this
->t('Incompatible File Type Handling'),
'#options' => [
'skip' => $this
->t('Bypass incompatible files'),
'show_icon' => $this
->t('Show mimetype icon placehoder'),
'show_icon_and_link' => $this
->t('Show mimetype icon placholder and link to file'),
],
'#empty_option' => $this
->t('Do nothing'),
'#description' => $this
->t('Specify any special handling that should be applied to files that Juicebox cannot display (non-images).'),
];
$form['linkurl_source'] = [
'#jb_fieldset' => 'advanced',
'#type' => 'select',
'#title' => $this
->t("LinkURL Source"),
'#description' => $this
->t('The linkURL is an image-specific path for accessing each image outside the gallery. This is used by features such as the "Open Image Button".'),
'#options' => [
'image_styled' => 'Main Image - Styled (use this gallery\'s main image style setting)',
],
'#empty_option' => $this
->t('Main Image - Unstyled (original image)'),
];
$form['linkurl_target'] = [
'#jb_fieldset' => 'advanced',
'#type' => 'select',
'#title' => $this
->t('LinkURL Target'),
'#options' => [
'_blank' => $this
->t('_blank'),
'_self' => $this
->t('_self'),
'_parent' => $this
->t('_parent'),
'_top' => $this
->t('_top'),
],
'#description' => $this
->t('Specify a target for any links that make user of the image linkURL.'),
];
$form['custom_parent_classes'] = [
'#jb_fieldset' => 'advanced',
'#type' => 'textfield',
'#title' => $this
->t('Custom Classes for Parent Container'),
'#description' => $this
->t('Define any custom classes that should be added to the parent container within the Juicebox embed markup.<br/>This can be handy if you want to apply more advanced styling or dimensioning rules to this gallery via CSS. Enter as space-separated values.'),
];
foreach ($form as $conf_key => &$conf_value) {
if (!empty($conf_value['#type']) && $conf_value['#type'] != 'details') {
$conf_value['#default_value'] = $settings[$conf_key];
if (in_array($conf_key, $disallowed_conf)) {
$conf_value['#title'] .= $notification_label;
$conf_value['#disabled'] = TRUE;
}
}
}
$form['#pre_render'] = [
static::class . '::preRenderFieldsets',
];
return $form;
}
public function confBaseStylePresets($allow_multisize = TRUE) {
$library = $this
->getLibrary();
$presets = image_style_options(FALSE);
if ($allow_multisize && !in_array('juicebox_multisize_image_style', $library['disallowed_conf'])) {
$presets = [
'juicebox_multisize' => $this
->t('Juicebox PRO multi-size (adaptive)'),
] + $presets;
}
return $presets;
}
}