Upgraded drupal core with security updates
[yaffs-website] / web / core / modules / contact / src / MessageForm.php
1 <?php
2
3 namespace Drupal\contact;
4
5 use Drupal\Component\Datetime\TimeInterface;
6 use Drupal\Core\Datetime\DateFormatterInterface;
7 use Drupal\Core\Entity\ContentEntityForm;
8 use Drupal\Core\Entity\EntityManagerInterface;
9 use Drupal\Core\Entity\EntityTypeBundleInfoInterface;
10 use Drupal\Core\Flood\FloodInterface;
11 use Drupal\Core\Form\FormStateInterface;
12 use Drupal\Core\Language\LanguageManagerInterface;
13 use Symfony\Component\DependencyInjection\ContainerInterface;
14
15 /**
16  * Form controller for contact message forms.
17  */
18 class MessageForm extends ContentEntityForm {
19
20   /**
21    * The message being used by this form.
22    *
23    * @var \Drupal\contact\MessageInterface
24    */
25   protected $entity;
26
27   /**
28    * The flood control mechanism.
29    *
30    * @var \Drupal\Core\Flood\FloodInterface
31    */
32   protected $flood;
33
34   /**
35    * The language manager service.
36    *
37    * @var \Drupal\Core\Language\LanguageManagerInterface
38    */
39   protected $languageManager;
40
41   /**
42    * The contact mail handler service.
43    *
44    * @var \Drupal\contact\MailHandlerInterface
45    */
46   protected $mailHandler;
47
48   /**
49    * The date formatter service.
50    *
51    * @var \Drupal\Core\Datetime\DateFormatterInterface
52    */
53   protected $dateFormatter;
54
55   /**
56    * Constructs a MessageForm object.
57    *
58    * @param \Drupal\Core\Entity\EntityManagerInterface $entity_manager
59    *   The entity manager.
60    * @param \Drupal\Core\Flood\FloodInterface $flood
61    *   The flood control mechanism.
62    * @param \Drupal\Core\Language\LanguageManagerInterface $language_manager
63    *   The language manager service.
64    * @param \Drupal\contact\MailHandlerInterface $mail_handler
65    *   The contact mail handler service.
66    * @param \Drupal\Core\Datetime\DateFormatterInterface $date_formatter
67    *   The date service.
68    * @param \Drupal\Core\Entity\EntityTypeBundleInfoInterface $entity_type_bundle_info
69    *   The entity type bundle service.
70    * @param \Drupal\Component\Datetime\TimeInterface $time
71    *   The time service.
72    */
73   public function __construct(EntityManagerInterface $entity_manager, FloodInterface $flood, LanguageManagerInterface $language_manager, MailHandlerInterface $mail_handler, DateFormatterInterface $date_formatter, EntityTypeBundleInfoInterface $entity_type_bundle_info = NULL, TimeInterface $time = NULL) {
74     parent::__construct($entity_manager, $entity_type_bundle_info, $time);
75     $this->flood = $flood;
76     $this->languageManager = $language_manager;
77     $this->mailHandler = $mail_handler;
78     $this->dateFormatter = $date_formatter;
79   }
80
81   /**
82    * {@inheritdoc}
83    */
84   public static function create(ContainerInterface $container) {
85     return new static(
86       $container->get('entity.manager'),
87       $container->get('flood'),
88       $container->get('language_manager'),
89       $container->get('contact.mail_handler'),
90       $container->get('date.formatter'),
91       $container->get('entity_type.bundle.info'),
92       $container->get('datetime.time')
93     );
94   }
95
96   /**
97    * {@inheritdoc}
98    */
99   public function form(array $form, FormStateInterface $form_state) {
100     $user = $this->currentUser();
101     $message = $this->entity;
102     $form = parent::form($form, $form_state, $message);
103     $form['#attributes']['class'][] = 'contact-form';
104
105     if (!empty($message->preview)) {
106       $form['preview'] = [
107         '#theme_wrappers' => ['container__preview'],
108         '#attributes' => ['class' => ['preview']],
109       ];
110       $form['preview']['message'] = $this->entityManager->getViewBuilder('contact_message')->view($message, 'full');
111     }
112
113     $form['name'] = [
114       '#type' => 'textfield',
115       '#title' => $this->t('Your name'),
116       '#maxlength' => 255,
117       '#required' => TRUE,
118     ];
119     $form['mail'] = [
120       '#type' => 'email',
121       '#title' => $this->t('Your email address'),
122       '#required' => TRUE,
123     ];
124     if ($user->isAnonymous()) {
125       $form['#attached']['library'][] = 'core/drupal.form';
126       $form['#attributes']['data-user-info-from-browser'] = TRUE;
127     }
128     // Do not allow authenticated users to alter the name or email values to
129     // prevent the impersonation of other users.
130     else {
131       $form['name']['#type'] = 'item';
132       $form['name']['#value'] = $user->getDisplayName();
133       $form['name']['#required'] = FALSE;
134       $form['name']['#plain_text'] = $user->getDisplayName();
135
136       $form['mail']['#type'] = 'item';
137       $form['mail']['#value'] = $user->getEmail();
138       $form['mail']['#required'] = FALSE;
139       $form['mail']['#plain_text'] = $user->getEmail();
140     }
141
142     // The user contact form has a preset recipient.
143     if ($message->isPersonal()) {
144       $form['recipient'] = [
145         '#type' => 'item',
146         '#title' => $this->t('To'),
147         '#value' => $message->getPersonalRecipient()->id(),
148         'name' => [
149           '#theme' => 'username',
150           '#account' => $message->getPersonalRecipient(),
151         ],
152       ];
153     }
154
155     $form['copy'] = [
156       '#type' => 'checkbox',
157       '#title' => $this->t('Send yourself a copy'),
158       // Do not allow anonymous users to send themselves a copy, because it can
159       // be abused to spam people.
160       '#access' => $user->isAuthenticated(),
161     ];
162     return $form;
163   }
164
165   /**
166    * {@inheritdoc}
167    */
168   public function actions(array $form, FormStateInterface $form_state) {
169     $elements = parent::actions($form, $form_state);
170     $elements['submit']['#value'] = $this->t('Send message');
171     $elements['preview'] = [
172       '#type' => 'submit',
173       '#value' => $this->t('Preview'),
174       '#submit' => ['::submitForm', '::preview'],
175     ];
176     return $elements;
177   }
178
179   /**
180    * Form submission handler for the 'preview' action.
181    */
182   public function preview(array $form, FormStateInterface $form_state) {
183     $message = $this->entity;
184     $message->preview = TRUE;
185     $form_state->setRebuild();
186   }
187
188   /**
189    * {@inheritdoc}
190    */
191   public function validateForm(array &$form, FormStateInterface $form_state) {
192     $message = parent::validateForm($form, $form_state);
193
194     // Check if flood control has been activated for sending emails.
195     if (!$this->currentUser()->hasPermission('administer contact forms') && (!$message->isPersonal() || !$this->currentUser()->hasPermission('administer users'))) {
196       $limit = $this->config('contact.settings')->get('flood.limit');
197       $interval = $this->config('contact.settings')->get('flood.interval');
198
199       if (!$this->flood->isAllowed('contact', $limit, $interval)) {
200         $form_state->setErrorByName('', $this->t('You cannot send more than %limit messages in @interval. Try again later.', [
201           '%limit' => $limit,
202           '@interval' => $this->dateFormatter->formatInterval($interval),
203         ]));
204       }
205     }
206
207     return $message;
208   }
209
210   /**
211    * {@inheritdoc}
212    */
213   public function save(array $form, FormStateInterface $form_state) {
214     $message = $this->entity;
215     $user = $this->currentUser();
216     // Save the message. In core this is a no-op but should contrib wish to
217     // implement message storage, this will make the task of swapping in a real
218     // storage controller straight-forward.
219     $message->save();
220     $this->mailHandler->sendMailMessages($message, $user);
221     $contact_form = $message->getContactForm();
222
223     $this->flood->register('contact', $this->config('contact.settings')->get('flood.interval'));
224     if ($submission_message = $contact_form->getMessage()) {
225       drupal_set_message($submission_message);
226     }
227
228     // To avoid false error messages caused by flood control, redirect away from
229     // the contact form; either to the contacted user account or the front page.
230     if ($message->isPersonal() && $user->hasPermission('access user profiles')) {
231       $form_state->setRedirectUrl($message->getPersonalRecipient()->urlInfo());
232     }
233     else {
234       $form_state->setRedirectUrl($contact_form->getRedirectUrl());
235     }
236   }
237
238 }