Updated to Drupal 8.5. Core Media not yet in use.
[yaffs-website] / web / core / modules / link / src / Plugin / Field / FieldWidget / LinkWidget.php
1 <?php
2
3 namespace Drupal\link\Plugin\Field\FieldWidget;
4
5 use Drupal\Core\Entity\Element\EntityAutocomplete;
6 use Drupal\Core\Field\FieldItemListInterface;
7 use Drupal\Core\Field\WidgetBase;
8 use Drupal\Core\Form\FormStateInterface;
9 use Drupal\link\LinkItemInterface;
10 use Symfony\Component\Validator\ConstraintViolation;
11 use Symfony\Component\Validator\ConstraintViolationListInterface;
12
13 /**
14  * Plugin implementation of the 'link' widget.
15  *
16  * @FieldWidget(
17  *   id = "link_default",
18  *   label = @Translation("Link"),
19  *   field_types = {
20  *     "link"
21  *   }
22  * )
23  */
24 class LinkWidget extends WidgetBase {
25
26   /**
27    * {@inheritdoc}
28    */
29   public static function defaultSettings() {
30     return [
31       'placeholder_url' => '',
32       'placeholder_title' => '',
33     ] + parent::defaultSettings();
34   }
35
36   /**
37    * Gets the URI without the 'internal:' or 'entity:' scheme.
38    *
39    * The following two forms of URIs are transformed:
40    * - 'entity:' URIs: to entity autocomplete ("label (entity id)") strings;
41    * - 'internal:' URIs: the scheme is stripped.
42    *
43    * This method is the inverse of ::getUserEnteredStringAsUri().
44    *
45    * @param string $uri
46    *   The URI to get the displayable string for.
47    *
48    * @return string
49    *
50    * @see static::getUserEnteredStringAsUri()
51    */
52   protected static function getUriAsDisplayableString($uri) {
53     $scheme = parse_url($uri, PHP_URL_SCHEME);
54
55     // By default, the displayable string is the URI.
56     $displayable_string = $uri;
57
58     // A different displayable string may be chosen in case of the 'internal:'
59     // or 'entity:' built-in schemes.
60     if ($scheme === 'internal') {
61       $uri_reference = explode(':', $uri, 2)[1];
62
63       // @todo '<front>' is valid input for BC reasons, may be removed by
64       //   https://www.drupal.org/node/2421941
65       $path = parse_url($uri, PHP_URL_PATH);
66       if ($path === '/') {
67         $uri_reference = '<front>' . substr($uri_reference, 1);
68       }
69
70       $displayable_string = $uri_reference;
71     }
72     elseif ($scheme === 'entity') {
73       list($entity_type, $entity_id) = explode('/', substr($uri, 7), 2);
74       // Show the 'entity:' URI as the entity autocomplete would.
75       // @todo Support entity types other than 'node'. Will be fixed in
76       //    https://www.drupal.org/node/2423093.
77       if ($entity_type == 'node' && $entity = \Drupal::entityTypeManager()->getStorage($entity_type)->load($entity_id)) {
78         $displayable_string = EntityAutocomplete::getEntityLabels([$entity]);
79       }
80     }
81
82     return $displayable_string;
83   }
84
85   /**
86    * Gets the user-entered string as a URI.
87    *
88    * The following two forms of input are mapped to URIs:
89    * - entity autocomplete ("label (entity id)") strings: to 'entity:' URIs;
90    * - strings without a detectable scheme: to 'internal:' URIs.
91    *
92    * This method is the inverse of ::getUriAsDisplayableString().
93    *
94    * @param string $string
95    *   The user-entered string.
96    *
97    * @return string
98    *   The URI, if a non-empty $uri was passed.
99    *
100    * @see static::getUriAsDisplayableString()
101    */
102   protected static function getUserEnteredStringAsUri($string) {
103     // By default, assume the entered string is an URI.
104     $uri = $string;
105
106     // Detect entity autocomplete string, map to 'entity:' URI.
107     $entity_id = EntityAutocomplete::extractEntityIdFromAutocompleteInput($string);
108     if ($entity_id !== NULL) {
109       // @todo Support entity types other than 'node'. Will be fixed in
110       //    https://www.drupal.org/node/2423093.
111       $uri = 'entity:node/' . $entity_id;
112     }
113     // Detect a schemeless string, map to 'internal:' URI.
114     elseif (!empty($string) && parse_url($string, PHP_URL_SCHEME) === NULL) {
115       // @todo '<front>' is valid input for BC reasons, may be removed by
116       //   https://www.drupal.org/node/2421941
117       // - '<front>' -> '/'
118       // - '<front>#foo' -> '/#foo'
119       if (strpos($string, '<front>') === 0) {
120         $string = '/' . substr($string, strlen('<front>'));
121       }
122       $uri = 'internal:' . $string;
123     }
124
125     return $uri;
126   }
127
128   /**
129    * Form element validation handler for the 'uri' element.
130    *
131    * Disallows saving inaccessible or untrusted URLs.
132    */
133   public static function validateUriElement($element, FormStateInterface $form_state, $form) {
134     $uri = static::getUserEnteredStringAsUri($element['#value']);
135     $form_state->setValueForElement($element, $uri);
136
137     // If getUserEnteredStringAsUri() mapped the entered value to a 'internal:'
138     // URI , ensure the raw value begins with '/', '?' or '#'.
139     // @todo '<front>' is valid input for BC reasons, may be removed by
140     //   https://www.drupal.org/node/2421941
141     if (parse_url($uri, PHP_URL_SCHEME) === 'internal' && !in_array($element['#value'][0], ['/', '?', '#'], TRUE) && substr($element['#value'], 0, 7) !== '<front>') {
142       $form_state->setError($element, t('Manually entered paths should start with /, ? or #.'));
143       return;
144     }
145   }
146
147   /**
148    * Form element validation handler for the 'title' element.
149    *
150    * Conditionally requires the link title if a URL value was filled in.
151    */
152   public static function validateTitleElement(&$element, FormStateInterface $form_state, $form) {
153     if ($element['uri']['#value'] !== '' && $element['title']['#value'] === '') {
154       // We expect the field name placeholder value to be wrapped in t() here,
155       // so it won't be escaped again as it's already marked safe.
156       $form_state->setError($element['title'], t('@title field is required if there is @uri input.', ['@title' => $element['title']['#title'], '@uri' => $element['uri']['#title']]));
157     }
158   }
159
160   /**
161    * {@inheritdoc}
162    */
163   public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
164     /** @var \Drupal\link\LinkItemInterface $item */
165     $item = $items[$delta];
166
167     $element['uri'] = [
168       '#type' => 'url',
169       '#title' => $this->t('URL'),
170       '#placeholder' => $this->getSetting('placeholder_url'),
171       // The current field value could have been entered by a different user.
172       // However, if it is inaccessible to the current user, do not display it
173       // to them.
174       '#default_value' => (!$item->isEmpty() && (\Drupal::currentUser()->hasPermission('link to any page') || $item->getUrl()->access())) ? static::getUriAsDisplayableString($item->uri) : NULL,
175       '#element_validate' => [[get_called_class(), 'validateUriElement']],
176       '#maxlength' => 2048,
177       '#required' => $element['#required'],
178       '#link_type' => $this->getFieldSetting('link_type'),
179     ];
180
181     // If the field is configured to support internal links, it cannot use the
182     // 'url' form element and we have to do the validation ourselves.
183     if ($this->supportsInternalLinks()) {
184       $element['uri']['#type'] = 'entity_autocomplete';
185       // @todo The user should be able to select an entity type. Will be fixed
186       //    in https://www.drupal.org/node/2423093.
187       $element['uri']['#target_type'] = 'node';
188       // Disable autocompletion when the first character is '/', '#' or '?'.
189       $element['uri']['#attributes']['data-autocomplete-first-character-blacklist'] = '/#?';
190
191       // The link widget is doing its own processing in
192       // static::getUriAsDisplayableString().
193       $element['uri']['#process_default_value'] = FALSE;
194     }
195
196     // If the field is configured to allow only internal links, add a useful
197     // element prefix and description.
198     if (!$this->supportsExternalLinks()) {
199       $element['uri']['#field_prefix'] = rtrim(\Drupal::url('<front>', [], ['absolute' => TRUE]), '/');
200       $element['uri']['#description'] = $this->t('This must be an internal path such as %add-node. You can also start typing the title of a piece of content to select it. Enter %front to link to the front page.', ['%add-node' => '/node/add', '%front' => '<front>']);
201     }
202     // If the field is configured to allow both internal and external links,
203     // show a useful description.
204     elseif ($this->supportsExternalLinks() && $this->supportsInternalLinks()) {
205       $element['uri']['#description'] = $this->t('Start typing the title of a piece of content to select it. You can also enter an internal path such as %add-node or an external URL such as %url. Enter %front to link to the front page.', ['%front' => '<front>', '%add-node' => '/node/add', '%url' => 'http://example.com']);
206     }
207     // If the field is configured to allow only external links, show a useful
208     // description.
209     elseif ($this->supportsExternalLinks() && !$this->supportsInternalLinks()) {
210       $element['uri']['#description'] = $this->t('This must be an external URL such as %url.', ['%url' => 'http://example.com']);
211     }
212
213     $element['title'] = [
214       '#type' => 'textfield',
215       '#title' => $this->t('Link text'),
216       '#placeholder' => $this->getSetting('placeholder_title'),
217       '#default_value' => isset($items[$delta]->title) ? $items[$delta]->title : NULL,
218       '#maxlength' => 255,
219       '#access' => $this->getFieldSetting('title') != DRUPAL_DISABLED,
220       '#required' => $this->getFieldSetting('title') === DRUPAL_REQUIRED && $element['#required'],
221     ];
222     // Post-process the title field to make it conditionally required if URL is
223     // non-empty. Omit the validation on the field edit form, since the field
224     // settings cannot be saved otherwise.
225     if (!$this->isDefaultValueWidget($form_state) && $this->getFieldSetting('title') === DRUPAL_REQUIRED) {
226       $element['#element_validate'][] = [get_called_class(), 'validateTitleElement'];
227
228       if (!$element['title']['#required']) {
229         // Make title required on the front-end when URI filled-in.
230         $field_name = $this->fieldDefinition->getName();
231
232         $parents = $element['#field_parents'];
233         $parents[] = $field_name;
234         $selector = $root = array_shift($parents);
235         if ($parents) {
236           $selector = $root . '[' . implode('][', $parents) . ']';
237         }
238
239         $element['title']['#states']['required'] = [
240           ':input[name="' . $selector . '[' . $delta . '][uri]"]' => ['filled' => TRUE]
241         ];
242       }
243     }
244
245     // Exposing the attributes array in the widget is left for alternate and more
246     // advanced field widgets.
247     $element['attributes'] = [
248       '#type' => 'value',
249       '#tree' => TRUE,
250       '#value' => !empty($items[$delta]->options['attributes']) ? $items[$delta]->options['attributes'] : [],
251       '#attributes' => ['class' => ['link-field-widget-attributes']],
252     ];
253
254     // If cardinality is 1, ensure a proper label is output for the field.
255     if ($this->fieldDefinition->getFieldStorageDefinition()->getCardinality() == 1) {
256       // If the link title is disabled, use the field definition label as the
257       // title of the 'uri' element.
258       if ($this->getFieldSetting('title') == DRUPAL_DISABLED) {
259         $element['uri']['#title'] = $element['#title'];
260         // By default the field description is added to the title field. Since
261         // the title field is disabled, we add the description, if given, to the
262         // uri element instead.
263         if (!empty($element['#description'])) {
264           if (empty($element['uri']['#description'])) {
265             $element['uri']['#description'] = $element['#description'];
266           }
267           else {
268             // If we have the description of the type of field together with
269             // the user provided description, we want to make a distinction
270             // between "core help text" and "user entered help text". To make
271             // this distinction more clear, we put them in an unordered list.
272             $element['uri']['#description'] = [
273               '#theme' => 'item_list',
274               '#items' => [
275                 // Assume the user-specified description has the most relevance,
276                 // so place it first.
277                 $element['#description'],
278                 $element['uri']['#description'],
279               ],
280             ];
281           }
282         }
283       }
284       // Otherwise wrap everything in a details element.
285       else {
286         $element += [
287           '#type' => 'fieldset',
288         ];
289       }
290     }
291
292     return $element;
293   }
294
295   /**
296    * Indicates enabled support for link to routes.
297    *
298    * @return bool
299    *   Returns TRUE if the LinkItem field is configured to support links to
300    *   routes, otherwise FALSE.
301    */
302   protected function supportsInternalLinks() {
303     $link_type = $this->getFieldSetting('link_type');
304     return (bool) ($link_type & LinkItemInterface::LINK_INTERNAL);
305   }
306
307   /**
308    * Indicates enabled support for link to external URLs.
309    *
310    * @return bool
311    *   Returns TRUE if the LinkItem field is configured to support links to
312    *   external URLs, otherwise FALSE.
313    */
314   protected function supportsExternalLinks() {
315     $link_type = $this->getFieldSetting('link_type');
316     return (bool) ($link_type & LinkItemInterface::LINK_EXTERNAL);
317   }
318
319   /**
320    * {@inheritdoc}
321    */
322   public function settingsForm(array $form, FormStateInterface $form_state) {
323     $elements = parent::settingsForm($form, $form_state);
324
325     $elements['placeholder_url'] = [
326       '#type' => 'textfield',
327       '#title' => $this->t('Placeholder for URL'),
328       '#default_value' => $this->getSetting('placeholder_url'),
329       '#description' => $this->t('Text that will be shown inside the field until a value is entered. This hint is usually a sample value or a brief description of the expected format.'),
330     ];
331     $elements['placeholder_title'] = [
332       '#type' => 'textfield',
333       '#title' => $this->t('Placeholder for link text'),
334       '#default_value' => $this->getSetting('placeholder_title'),
335       '#description' => $this->t('Text that will be shown inside the field until a value is entered. This hint is usually a sample value or a brief description of the expected format.'),
336       '#states' => [
337         'invisible' => [
338           ':input[name="instance[settings][title]"]' => ['value' => DRUPAL_DISABLED],
339         ],
340       ],
341     ];
342
343     return $elements;
344   }
345
346   /**
347    * {@inheritdoc}
348    */
349   public function settingsSummary() {
350     $summary = [];
351
352     $placeholder_title = $this->getSetting('placeholder_title');
353     $placeholder_url = $this->getSetting('placeholder_url');
354     if (empty($placeholder_title) && empty($placeholder_url)) {
355       $summary[] = $this->t('No placeholders');
356     }
357     else {
358       if (!empty($placeholder_title)) {
359         $summary[] = $this->t('Title placeholder: @placeholder_title', ['@placeholder_title' => $placeholder_title]);
360       }
361       if (!empty($placeholder_url)) {
362         $summary[] = $this->t('URL placeholder: @placeholder_url', ['@placeholder_url' => $placeholder_url]);
363       }
364     }
365
366     return $summary;
367   }
368
369   /**
370    * {@inheritdoc}
371    */
372   public function massageFormValues(array $values, array $form, FormStateInterface $form_state) {
373     foreach ($values as &$value) {
374       $value['uri'] = static::getUserEnteredStringAsUri($value['uri']);
375       $value += ['options' => []];
376     }
377     return $values;
378   }
379
380
381   /**
382    * {@inheritdoc}
383    *
384    * Override the '%uri' message parameter, to ensure that 'internal:' URIs
385    * show a validation error message that doesn't mention that scheme.
386    */
387   public function flagErrors(FieldItemListInterface $items, ConstraintViolationListInterface $violations, array $form, FormStateInterface $form_state) {
388     /** @var \Symfony\Component\Validator\ConstraintViolationInterface $violation */
389     foreach ($violations as $offset => $violation) {
390       $parameters = $violation->getParameters();
391       if (isset($parameters['@uri'])) {
392         $parameters['@uri'] = static::getUriAsDisplayableString($parameters['@uri']);
393         $violations->set($offset, new ConstraintViolation(
394           $this->t($violation->getMessageTemplate(), $parameters),
395           $violation->getMessageTemplate(),
396           $parameters,
397           $violation->getRoot(),
398           $violation->getPropertyPath(),
399           $violation->getInvalidValue(),
400           $violation->getPlural(),
401           $violation->getCode()
402         ));
403       }
404     }
405     parent::flagErrors($items, $violations, $form, $form_state);
406   }
407
408 }