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