Version 1
[yaffs-website] / web / core / modules / editor / src / Form / EditorImageDialog.php
1 <?php
2
3 namespace Drupal\editor\Form;
4
5 use Drupal\Component\Utility\Bytes;
6 use Drupal\Core\Form\FormBase;
7 use Drupal\Core\Form\FormStateInterface;
8 use Drupal\editor\Entity\Editor;
9 use Drupal\Core\Ajax\AjaxResponse;
10 use Drupal\Core\Ajax\HtmlCommand;
11 use Drupal\editor\Ajax\EditorDialogSave;
12 use Drupal\Core\Ajax\CloseModalDialogCommand;
13 use Symfony\Component\DependencyInjection\ContainerInterface;
14 use Drupal\Core\Entity\EntityStorageInterface;
15
16 /**
17  * Provides an image dialog for text editors.
18  */
19 class EditorImageDialog extends FormBase {
20
21   /**
22    * The file storage service.
23    *
24    * @var \Drupal\Core\Entity\EntityStorageInterface
25    */
26   protected $fileStorage;
27
28   /**
29    * Constructs a form object for image dialog.
30    *
31    * @param \Drupal\Core\Entity\EntityStorageInterface $file_storage
32    *   The file storage service.
33    */
34   public function __construct(EntityStorageInterface $file_storage) {
35     $this->fileStorage = $file_storage;
36   }
37
38   /**
39    * {@inheritdoc}
40    */
41   public static function create(ContainerInterface $container) {
42     return new static(
43       $container->get('entity.manager')->getStorage('file')
44     );
45   }
46
47   /**
48    * {@inheritdoc}
49    */
50   public function getFormId() {
51     return 'editor_image_dialog';
52   }
53
54   /**
55    * {@inheritdoc}
56    *
57    * @param \Drupal\editor\Entity\Editor $editor
58    *   The text editor to which this dialog corresponds.
59    */
60   public function buildForm(array $form, FormStateInterface $form_state, Editor $editor = NULL) {
61     // This form is special, in that the default values do not come from the
62     // server side, but from the client side, from a text editor. We must cache
63     // this data in form state, because when the form is rebuilt, we will be
64     // receiving values from the form, instead of the values from the text
65     // editor. If we don't cache it, this data will be lost.
66     if (isset($form_state->getUserInput()['editor_object'])) {
67       // By convention, the data that the text editor sends to any dialog is in
68       // the 'editor_object' key. And the image dialog for text editors expects
69       // that data to be the attributes for an <img> element.
70       $image_element = $form_state->getUserInput()['editor_object'];
71       $form_state->set('image_element', $image_element);
72       $form_state->setCached(TRUE);
73     }
74     else {
75       // Retrieve the image element's attributes from form state.
76       $image_element = $form_state->get('image_element') ?: [];
77     }
78
79     $form['#tree'] = TRUE;
80     $form['#attached']['library'][] = 'editor/drupal.editor.dialog';
81     $form['#prefix'] = '<div id="editor-image-dialog-form">';
82     $form['#suffix'] = '</div>';
83
84     // Construct strings to use in the upload validators.
85     $image_upload = $editor->getImageUploadSettings();
86     if (!empty($image_upload['max_dimensions']['width']) || !empty($image_upload['max_dimensions']['height'])) {
87       $max_dimensions = $image_upload['max_dimensions']['width'] . 'x' . $image_upload['max_dimensions']['height'];
88     }
89     else {
90       $max_dimensions = 0;
91     }
92     $max_filesize = min(Bytes::toInt($image_upload['max_size']), file_upload_max_size());
93
94     $existing_file = isset($image_element['data-entity-uuid']) ? \Drupal::entityManager()->loadEntityByUuid('file', $image_element['data-entity-uuid']) : NULL;
95     $fid = $existing_file ? $existing_file->id() : NULL;
96
97     $form['fid'] = [
98       '#title' => $this->t('Image'),
99       '#type' => 'managed_file',
100       '#upload_location' => $image_upload['scheme'] . '://' . $image_upload['directory'],
101       '#default_value' => $fid ? [$fid] : NULL,
102       '#upload_validators' => [
103         'file_validate_extensions' => ['gif png jpg jpeg'],
104         'file_validate_size' => [$max_filesize],
105         'file_validate_image_resolution' => [$max_dimensions],
106       ],
107       '#required' => TRUE,
108     ];
109
110     $form['attributes']['src'] = [
111       '#title' => $this->t('URL'),
112       '#type' => 'textfield',
113       '#default_value' => isset($image_element['src']) ? $image_element['src'] : '',
114       '#maxlength' => 2048,
115       '#required' => TRUE,
116     ];
117
118     // If the editor has image uploads enabled, show a managed_file form item,
119     // otherwise show a (file URL) text form item.
120     if ($image_upload['status']) {
121       $form['attributes']['src']['#access'] = FALSE;
122       $form['attributes']['src']['#required'] = FALSE;
123     }
124     else {
125       $form['fid']['#access'] = FALSE;
126       $form['fid']['#required'] = FALSE;
127     }
128
129     // The alt attribute is *required*, but we allow users to opt-in to empty
130     // alt attributes for the very rare edge cases where that is valid by
131     // specifying two double quotes as the alternative text in the dialog.
132     // However, that *is* stored as an empty alt attribute, so if we're editing
133     // an existing image (which means the src attribute is set) and its alt
134     // attribute is empty, then we show that as two double quotes in the dialog.
135     // @see https://www.drupal.org/node/2307647
136     $alt = isset($image_element['alt']) ? $image_element['alt'] : '';
137     if ($alt === '' && !empty($image_element['src'])) {
138       $alt = '""';
139     }
140     $form['attributes']['alt'] = [
141       '#title' => $this->t('Alternative text'),
142       '#placeholder' => $this->t('Short description for the visually impaired'),
143       '#type' => 'textfield',
144       '#required' => TRUE,
145       '#required_error' => $this->t('Alternative text is required.<br />(Only in rare cases should this be left empty. To create empty alternative text, enter <code>""</code> — two double quotes without any content).'),
146       '#default_value' => $alt,
147       '#maxlength' => 2048,
148     ];
149
150     // When Drupal core's filter_align is being used, the text editor may
151     // offer the ability to change the alignment.
152     if (isset($image_element['data-align']) && $editor->getFilterFormat()->filters('filter_align')->status) {
153       $form['align'] = [
154         '#title' => $this->t('Align'),
155         '#type' => 'radios',
156         '#options' => [
157           'none' => $this->t('None'),
158           'left' => $this->t('Left'),
159           'center' => $this->t('Center'),
160           'right' => $this->t('Right'),
161         ],
162         '#default_value' => $image_element['data-align'] === '' ? 'none' : $image_element['data-align'],
163         '#wrapper_attributes' => ['class' => ['container-inline']],
164         '#attributes' => ['class' => ['container-inline']],
165         '#parents' => ['attributes', 'data-align'],
166       ];
167     }
168
169     // When Drupal core's filter_caption is being used, the text editor may
170     // offer the ability to in-place edit the image's caption: show a toggle.
171     if (isset($image_element['hasCaption']) && $editor->getFilterFormat()->filters('filter_caption')->status) {
172       $form['caption'] = [
173         '#title' => $this->t('Caption'),
174         '#type' => 'checkbox',
175         '#default_value' => $image_element['hasCaption'] === 'true',
176         '#parents' => ['attributes', 'hasCaption'],
177       ];
178     }
179
180     $form['actions'] = [
181       '#type' => 'actions',
182     ];
183     $form['actions']['save_modal'] = [
184       '#type' => 'submit',
185       '#value' => $this->t('Save'),
186       // No regular submit-handler. This form only works via JavaScript.
187       '#submit' => [],
188       '#ajax' => [
189         'callback' => '::submitForm',
190         'event' => 'click',
191       ],
192     ];
193
194     return $form;
195   }
196
197   /**
198    * {@inheritdoc}
199    */
200   public function submitForm(array &$form, FormStateInterface $form_state) {
201     $response = new AjaxResponse();
202
203     // Convert any uploaded files from the FID values to data-entity-uuid
204     // attributes and set data-entity-type to 'file'.
205     $fid = $form_state->getValue(['fid', 0]);
206     if (!empty($fid)) {
207       $file = $this->fileStorage->load($fid);
208       $file_url = file_create_url($file->getFileUri());
209       // Transform absolute image URLs to relative image URLs: prevent problems
210       // on multisite set-ups and prevent mixed content errors.
211       $file_url = file_url_transform_relative($file_url);
212       $form_state->setValue(['attributes', 'src'], $file_url);
213       $form_state->setValue(['attributes', 'data-entity-uuid'], $file->uuid());
214       $form_state->setValue(['attributes', 'data-entity-type'], 'file');
215     }
216
217     // When the alt attribute is set to two double quotes, transform it to the
218     // empty string: two double quotes signify "empty alt attribute". See above.
219     if (trim($form_state->getValue(['attributes', 'alt'])) === '""') {
220       $form_state->setValue(['attributes', 'alt'], '');
221     }
222
223     if ($form_state->getErrors()) {
224       unset($form['#prefix'], $form['#suffix']);
225       $form['status_messages'] = [
226         '#type' => 'status_messages',
227         '#weight' => -10,
228       ];
229       $response->addCommand(new HtmlCommand('#editor-image-dialog-form', $form));
230     }
231     else {
232       $response->addCommand(new EditorDialogSave($form_state->getValues()));
233       $response->addCommand(new CloseModalDialogCommand());
234     }
235
236     return $response;
237   }
238
239 }