Security update to Drupal 8.4.6
[yaffs-website] / web / core / modules / language / src / Form / NegotiationUrlForm.php
1 <?php
2
3 namespace Drupal\language\Form;
4
5 use Drupal\Core\Form\ConfigFormBase;
6 use Drupal\Core\Form\FormStateInterface;
7 use Drupal\Core\Language\LanguageInterface;
8 use Drupal\Core\Language\LanguageManagerInterface;
9 use Drupal\Core\Config\ConfigFactoryInterface;
10 use Symfony\Component\DependencyInjection\ContainerInterface;
11 use Drupal\language\Plugin\LanguageNegotiation\LanguageNegotiationUrl;
12
13 /**
14  * Configure the URL language negotiation method for this site.
15  */
16 class NegotiationUrlForm extends ConfigFormBase {
17
18   /**
19    * The language manager.
20    *
21    * @var \Drupal\Core\Language\LanguageManagerInterface
22    */
23   protected $languageManager;
24
25   /**
26    * Constructs a new NegotiationUrlForm object.
27    *
28    * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
29    *   The factory for configuration objects.
30    * @param \Drupal\Core\Language\LanguageManagerInterface $language_manager
31    *   The language manager.
32    */
33   public function __construct(ConfigFactoryInterface $config_factory, LanguageManagerInterface $language_manager) {
34     parent::__construct($config_factory);
35     $this->languageManager = $language_manager;
36   }
37
38   /**
39    * {@inheritdoc}
40    */
41   public static function create(ContainerInterface $container) {
42     return new static(
43       $container->get('config.factory'),
44       $container->get('language_manager')
45     );
46   }
47
48   /**
49    * {@inheritdoc}
50    */
51   public function getFormId() {
52     return 'language_negotiation_configure_url_form';
53   }
54
55   /**
56    * {@inheritdoc}
57    */
58   protected function getEditableConfigNames() {
59     return ['language.negotiation'];
60   }
61
62   /**
63    * {@inheritdoc}
64    */
65   public function buildForm(array $form, FormStateInterface $form_state) {
66     global $base_url;
67     $config = $this->config('language.negotiation');
68
69     $form['language_negotiation_url_part'] = [
70       '#title' => $this->t('Part of the URL that determines language'),
71       '#type' => 'radios',
72       '#options' => [
73         LanguageNegotiationUrl::CONFIG_PATH_PREFIX => $this->t('Path prefix'),
74         LanguageNegotiationUrl::CONFIG_DOMAIN => $this->t('Domain'),
75       ],
76       '#default_value' => $config->get('url.source'),
77     ];
78
79     $form['prefix'] = [
80       '#type' => 'details',
81       '#tree' => TRUE,
82       '#title' => $this->t('Path prefix configuration'),
83       '#open' => TRUE,
84       '#description' => $this->t('Language codes or other custom text to use as a path prefix for URL language detection. For the selected fallback language, this value may be left blank. <strong>Modifying this value may break existing URLs. Use with caution in a production environment.</strong> Example: Specifying "deutsch" as the path prefix code for German results in URLs like "example.com/deutsch/contact".'),
85       '#states' => [
86         'visible' => [
87           ':input[name="language_negotiation_url_part"]' => [
88             'value' => (string) LanguageNegotiationUrl::CONFIG_PATH_PREFIX,
89           ],
90         ],
91       ],
92     ];
93     $form['domain'] = [
94       '#type' => 'details',
95       '#tree' => TRUE,
96       '#title' => $this->t('Domain configuration'),
97       '#open' => TRUE,
98       '#description' => $this->t('The domain names to use for these languages. <strong>Modifying this value may break existing URLs. Use with caution in a production environment.</strong> Example: Specifying "de.example.com" as language domain for German will result in a URL like "http://de.example.com/contact".'),
99       '#states' => [
100         'visible' => [
101           ':input[name="language_negotiation_url_part"]' => [
102             'value' => (string) LanguageNegotiationUrl::CONFIG_DOMAIN,
103           ],
104         ],
105       ],
106     ];
107
108     $languages = $this->languageManager->getLanguages();
109     $prefixes = $config->get('url.prefixes');
110     $domains = $config->get('url.domains');
111     foreach ($languages as $langcode => $language) {
112       $t_args = ['%language' => $language->getName(), '%langcode' => $language->getId()];
113       $form['prefix'][$langcode] = [
114         '#type' => 'textfield',
115         '#title' => $language->isDefault() ? $this->t('%language (%langcode) path prefix (Default language)', $t_args) : $this->t('%language (%langcode) path prefix', $t_args),
116         '#maxlength' => 64,
117         '#default_value' => isset($prefixes[$langcode]) ? $prefixes[$langcode] : '',
118         '#field_prefix' => $base_url . '/',
119       ];
120       $form['domain'][$langcode] = [
121         '#type' => 'textfield',
122         '#title' => $this->t('%language (%langcode) domain', ['%language' => $language->getName(), '%langcode' => $language->getId()]),
123         '#maxlength' => 128,
124         '#default_value' => isset($domains[$langcode]) ? $domains[$langcode] : '',
125       ];
126     }
127
128     $form_state->setRedirect('language.negotiation');
129
130     return parent::buildForm($form, $form_state);
131   }
132
133   /**
134    * {@inheritdoc}
135    */
136   public function validateForm(array &$form, FormStateInterface $form_state) {
137     $languages = $this->languageManager->getLanguages();
138
139     // Count repeated values for uniqueness check.
140     $count = array_count_values($form_state->getValue('prefix'));
141     $default_langcode = $this->config('language.negotiation')->get('selected_langcode');
142     if ($default_langcode == LanguageInterface::LANGCODE_SITE_DEFAULT) {
143       $default_langcode = $this->languageManager->getDefaultLanguage()->getId();
144     }
145     foreach ($languages as $langcode => $language) {
146       $value = $form_state->getValue(['prefix', $langcode]);
147       if ($value === '') {
148         if (!($default_langcode == $langcode) && $form_state->getValue('language_negotiation_url_part') == LanguageNegotiationUrl::CONFIG_PATH_PREFIX) {
149           // Throw a form error if the prefix is blank for a non-default language,
150           // although it is required for selected negotiation type.
151           $form_state->setErrorByName("prefix][$langcode", $this->t('The prefix may only be left blank for the <a href=":url">selected detection fallback language.</a>', [
152             ':url' => $this->getUrlGenerator()->generate('language.negotiation_selected'),
153           ]));
154         }
155       }
156       elseif (strpos($value, '/') !== FALSE) {
157         // Throw a form error if the string contains a slash,
158         // which would not work.
159         $form_state->setErrorByName("prefix][$langcode", $this->t('The prefix may not contain a slash.'));
160       }
161       elseif (isset($count[$value]) && $count[$value] > 1) {
162         // Throw a form error if there are two languages with the same
163         // domain/prefix.
164         $form_state->setErrorByName("prefix][$langcode", $this->t('The prefix for %language, %value, is not unique.', ['%language' => $language->getName(), '%value' => $value]));
165       }
166     }
167
168     // Count repeated values for uniqueness check.
169     $count = array_count_values($form_state->getValue('domain'));
170     foreach ($languages as $langcode => $language) {
171       $value = $form_state->getValue(['domain', $langcode]);
172
173       if ($value === '') {
174         if ($form_state->getValue('language_negotiation_url_part') == LanguageNegotiationUrl::CONFIG_DOMAIN) {
175           // Throw a form error if the domain is blank for a non-default language,
176           // although it is required for selected negotiation type.
177           $form_state->setErrorByName("domain][$langcode", $this->t('The domain may not be left blank for %language.', ['%language' => $language->getName()]));
178         }
179       }
180       elseif (isset($count[$value]) && $count[$value] > 1) {
181         // Throw a form error if there are two languages with the same
182         // domain/domain.
183         $form_state->setErrorByName("domain][$langcode", $this->t('The domain for %language, %value, is not unique.', ['%language' => $language->getName(), '%value' => $value]));
184       }
185     }
186
187     // Domain names should not contain protocol and/or ports.
188     foreach ($languages as $langcode => $language) {
189       $value = $form_state->getValue(['domain', $langcode]);
190       if (!empty($value)) {
191         // Ensure we have exactly one protocol when checking the hostname.
192         $host = 'http://' . str_replace(['http://', 'https://'], '', $value);
193         if (parse_url($host, PHP_URL_HOST) != $value) {
194           $form_state->setErrorByName("domain][$langcode", $this->t('The domain for %language may only contain the domain name, not a trailing slash, protocol and/or port.', ['%language' => $language->getName()]));
195         }
196       }
197     }
198
199     parent::validateForm($form, $form_state);
200   }
201
202   /**
203    * {@inheritdoc}
204    */
205   public function submitForm(array &$form, FormStateInterface $form_state) {
206     // Save selected format (prefix or domain).
207     $this->config('language.negotiation')
208       ->set('url.source', $form_state->getValue('language_negotiation_url_part'))
209       // Save new domain and prefix values.
210       ->set('url.prefixes', $form_state->getValue('prefix'))
211       ->set('url.domains', $form_state->getValue('domain'))
212       ->save();
213
214     parent::submitForm($form, $form_state);
215   }
216
217 }