You are here

public function ForwardForm::submitForm in Forward 4.0.x

Same name and namespace in other branches
  1. 8.3 src/Form/ForwardForm.php \Drupal\forward\Form\ForwardForm::submitForm()
  2. 8 src/Form/ForwardForm.php \Drupal\forward\Form\ForwardForm::submitForm()
  3. 8.2 src/Form/ForwardForm.php \Drupal\forward\Form\ForwardForm::submitForm()
  4. 4.x src/Form/ForwardForm.php \Drupal\forward\Form\ForwardForm::submitForm()

Form submission handler.

Parameters

array $form: An associative array containing the structure of the form.

\Drupal\Core\Form\FormStateInterface $form_state: The current state of the form.

Overrides FormInterface::submitForm

File

src/Form/ForwardForm.php, line 438

Class

ForwardForm
Forward a page to a friend.

Namespace

Drupal\forward\Form

Code

public function submitForm(array &$form, FormStateInterface $form_state) {
  $entity = $this->entity;

  // Get form values.
  $recipients = $this
    ->splitEmailAddresses($form_state
    ->getValue('recipient'));

  // Decide if we're sending HTML or plain text. Default to HTML.
  $email_format = 'html';
  if ($form_state
    ->getValue('email_format') == 'plain_text') {
    $email_format = 'plain_text';
  }

  // Use the entity language to drive translation.
  $langcode = $entity
    ->language()
    ->getId();

  // Switch to anonymous user session if logged in,
  // unless bypassing access control.
  $switched = FALSE;
  if ($this
    ->currentUser()
    ->isAuthenticated() && empty($this->settings['forward_bypass_access_control'])) {
    $this->accountSwitcher
      ->switchTo(new AnonymousUserSession());
    $switched = TRUE;
  }
  try {

    // Build the message subject line.
    $token = $this
      ->getToken($form_state);
    $params['subject'] = $this->tokenService
      ->replace($this->settings['forward_email_subject'], $token, [
      'langcode' => $langcode,
    ]);

    // Build the entity content.
    $view_mode = '';
    $elements = [];
    if ($entity
      ->access('view')) {
      $view_builder = $this->entityTypeManager
        ->getViewBuilder($entity
        ->getEntityTypeId());
      foreach ([
        'forward',
        'teaser',
        'full',
      ] as $view_mode) {
        if ($this
          ->isValidDisplay($entity, $view_mode)) {
          $elements = $view_builder
            ->view($entity, $view_mode, $langcode);
        }
        if (!empty($elements)) {
          break;
        }
      }
    }

    // Render the page content.
    $content = $this->renderer
      ->render($elements);

    // Build the header line.
    $markup = $this->tokenService
      ->replace($this->settings['forward_email_message'], $token, [
      'langcode' => $langcode,
    ]);
    $header = [
      '#markup' => $markup,
    ];

    // Build the footer line.
    $markup = $this->tokenService
      ->replace($this->settings['forward_email_footer'], $token, [
      'langcode' => $langcode,
    ]);
    $footer = [
      '#markup' => $markup,
    ];

    // Build the personal message if present.
    $message = '';
    if ($this->settings['forward_personal_message']) {
      if ($this->settings['forward_personal_message_filter']) {

        // HTML allowed in personal message, so filter
        // out anything but the allowed tags.
        $raw_values = $form_state
          ->getUserInput();
        $allowed_tags = explode(',', $this->settings['forward_personal_message_tags']);
        $message = !empty($raw_values['message']) ? Xss::filter($raw_values['message'], $allowed_tags) : '';
        $message = [
          '#markup' => nl2br($message),
        ];
      }
      else {

        // HTML not allowed in personal message, so use the
        // sanitized version converted to plain text.
        $message = [
          '#plain_text' => $form_state
            ->getValue('message'),
        ];
      }
    }

    // Build the email body.
    $recipient = implode(',', $recipients);
    $render_array = [
      '#theme' => 'forward',
      '#email' => $form_state
        ->getValue('email'),
      '#recipient' => $recipient,
      '#header' => $header,
      '#message' => $message,
      '#settings' => $this->settings,
      '#entity' => $entity,
      '#content' => $content,
      '#view_mode' => $view_mode,
      '#email_format' => $email_format,
      '#footer' => $footer,
    ];

    // Allow modules to alter the render array for the message.
    $this->moduleHandler
      ->alter('forward_mail_pre_render', $render_array, $form_state);

    // Render the message.
    $params['body'] = $this->renderer
      ->render($render_array);

    // Apply filters such as Pathologic for link correction.
    $format_setting = "forward_filter_format_{$email_format}";
    if ($this->settings[$format_setting]) {

      // This filter was setup by the Forward administrator for this
      // purpose only, whose permission to run the filter was checked
      // at that time. Therefore, no need to check filter access again here.
      $params['body'] = check_markup($params['body'], $this->settings[$format_setting], $langcode);
    }

    // Allow modules to alter the final message body.
    $this->moduleHandler
      ->alter('forward_mail_post_render', $params['body'], $form_state);
  } catch (Exception $e) {
    if ($switched) {
      $this->accountSwitcher
        ->switchBack();
      $switched = FALSE;
    }
    $this
      ->logger('forward')
      ->error($e
      ->getMessage());
  }

  // Switch back to logged in user if necessary.
  if ($switched) {
    $this->accountSwitcher
      ->switchBack();
  }

  // Build the from email address and Reply-To.
  $from = $this->settings['forward_email_from_address'];
  if (empty($from)) {
    $from = $this
      ->config('system.site')
      ->get('mail');
  }
  if (empty($from)) {
    $site_mail = ini_get('sendmail_from');
  }
  $params['headers']['Reply-To'] = trim(Unicode::mimeHeaderEncode($form_state
    ->getValue('name')) . ' <' . $form_state
    ->getValue('email') . '>');

  // Handle plain text vs. HTML setting.
  if ($email_format == 'plain_text') {
    $params['plain_text'] = TRUE;
  }

  // Prepare for Event dispatch.
  $account = $this->entityTypeManager
    ->getStorage('user')
    ->load($this
    ->currentUser()
    ->id());

  // Event dispatch - before forwarding.
  $event = new EntityPreforwardEvent($account, $entity, [
    'account' => $account,
    'entity' => $entity,
  ]);
  $this->eventDispatcher
    ->dispatch(EntityPreforwardEvent::EVENT_NAME, $event);

  // Send the email to the recipient. Set the key so the Forward mail plugin
  // is only used if the default plugin is still the core PHP Mail plugin.
  // If another module such as SMTP has been enabled, then that will be used.
  $mail_configuration = $this
    ->config('system.mail')
    ->get('interface');
  $key = $mail_configuration['default'] == 'php_mail' ? 'send_entity' : 'mail_entity';
  foreach ($recipients as $recipient) {
    $this->mailer
      ->mail('forward', $key, $recipient, $langcode, $params, $from);
  }

  // Log this for tracking purposes.
  $this
    ->logEvent($entity);

  // Register event for flood control.
  $event = $this
    ->getFloodControlEventName();
  $this->floodInterface
    ->register($event);

  // Event dispatch - after forwarding.
  $event = new EntityForwardEvent($account, $entity, [
    'account' => $account,
    'entity' => $entity,
  ]);
  $this->eventDispatcher
    ->dispatch(EntityForwardEvent::EVENT_NAME, $event);

  // Allow modules to post process the forward.
  $this->moduleHandler
    ->invokeAll('forward_entity', [
    $account,
    $entity,
    $form_state,
  ]);

  // Display a confirmation message.
  $message = $this->tokenService
    ->replace($this->settings['forward_form_confirmation'], $token, [
    'langcode' => $langcode,
  ]);
  if ($message) {
    $this
      ->messenger()
      ->addMessage($message);
  }

  // Redirect back to entity page unless a redirect is already set.
  if (!$this->details) {
    if (!$form_state
      ->getRedirect()) {
      $form_state
        ->setRedirectUrl($entity
        ->toUrl());
    }
  }
}