You are here

class ProtectedPagesSendEmailForm in Protected Pages 8

Provides send protected pages details email form.

Hierarchy

Expanded class hierarchy of ProtectedPagesSendEmailForm

1 string reference to 'ProtectedPagesSendEmailForm'
protected_pages.routing.yml in ./protected_pages.routing.yml
protected_pages.routing.yml

File

src/Form/ProtectedPagesSendEmailForm.php, line 20

Namespace

Drupal\protected_pages\Form
View source
class ProtectedPagesSendEmailForm extends FormBase {

  /**
   * The protected pages storage service.
   *
   * @var \Drupal\protected_pages\ProtectedPagesStorage
   */
  protected $protectedPagesStorage;

  /**
   * The mail manager.
   *
   * @var \Drupal\Core\Mail\MailManagerInterface
   */
  protected $mailManager;

  /**
   * The email validator.
   *
   * @var \Egulias\EmailValidator\EmailValidator
   */
  protected $emailValidator;

  /**
   * Provides messenger service.
   *
   * @var \Drupal\Core\Messenger\Messenger
   */
  protected $messenger;

  /**
   * Config Factory service.
   *
   * @var \Drupal\Core\Config\ConfigFactoryInterface
   */
  protected $configFactory;

  /**
   * Language manager service.
   *
   * @var \Drupal\Core\Language\LanguageManager
   */
  protected $languageManager;

  /**
   * Logger channel factory.
   *
   * @var \Drupal\Core\Logger\LoggerChannelFactoryInterface
   */
  protected $loggerFactory;

  /**
   * Constructs a new ProtectedPagesSendEmailForm.
   *
   * @param \Drupal\Core\Mail\MailManagerInterface $mail_manager
   *   The mail manager.
   * @param \Egulias\EmailValidator\EmailValidator $email_validator
   *   The email validator.
   * @param \Drupal\protected_pages\ProtectedPagesStorage $protectedPagesStorage
   *   The protected pages storage.
   * @param \Drupal\Core\Messenger\Messenger $messenger
   *   The messenger service.
   * @param \Drupal\Core\Config\ConfigFactoryInterface $configFactory
   *   The config factory service interface.
   * @param \Drupal\Core\Language\LanguageManager $languageManager
   *   The language manager service.
   * @param \Drupal\Core\Logger\LoggerChannelFactoryInterface $loggerFactory
   *   The logger channel factory service.
   */
  public function __construct(MailManagerInterface $mail_manager, EmailValidator $email_validator, ProtectedPagesStorage $protectedPagesStorage, Messenger $messenger, ConfigFactoryInterface $configFactory, LanguageManager $languageManager, LoggerChannelFactoryInterface $loggerFactory) {
    $this->mailManager = $mail_manager;
    $this->emailValidator = $email_validator;
    $this->protectedPagesStorage = $protectedPagesStorage;
    $this->messenger = $messenger;
    $this->configFactory = $configFactory;
    $this->languageManager = $languageManager;
    $this->loggerFactory = $loggerFactory;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('plugin.manager.mail'), $container
      ->get('email.validator'), $container
      ->get('protected_pages.storage'), $container
      ->get('messenger'), $container
      ->get('config.factory'), $container
      ->get('language_manager'), $container
      ->get('logger.factory'));
  }

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'protected_pages_send_email';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state, $pid = NULL) {
    $config = $this->configFactory
      ->getEditable('protected_pages.settings');
    $form['send_email_box'] = [
      '#type' => 'details',
      '#title' => $this
        ->t('Send email'),
      '#description' => $this
        ->t('You send details of this protected page by email to multiple users. Please click <a href="@here">here</a> to configure email settings.', [
        '@here' => Url::fromUri('internal:/admin/config/system/protected_pages/settings', [
          'query' => $this
            ->getDestinationArray(),
        ])
          ->toString(),
      ]),
      '#open' => TRUE,
    ];
    $form_state
      ->set('pid', $pid);
    $form['send_email_box']['recipents'] = [
      '#type' => 'textarea',
      '#title' => $this
        ->t('Recipents'),
      '#rows' => 5,
      '#description' => $this
        ->t('Enter comma separated list of recipients.'),
      '#required' => TRUE,
    ];
    $form['send_email_box']['subject'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Subject'),
      '#default_value' => $config
        ->get('email.subject'),
      '#description' => $this
        ->t('Enter email subject.'),
      '#required' => TRUE,
    ];
    $form['send_email_box']['body'] = [
      '#type' => 'textarea',
      '#title' => $this
        ->t('Email body'),
      '#rows' => 15,
      '#default_value' => $config
        ->get('email.body'),
      '#description' => $this
        ->t('Enter the body of the email. Only [protected-page-url] and [site-name] tokens are available.
            Since password is encrypted, therefore we can not provide it by token.'),
      '#required' => TRUE,
    ];
    $form['send_email_box']['submit'] = [
      '#type' => 'submit',
      '#value' => $this
        ->t('Send email'),
    ];
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    $emails = explode(',', str_replace([
      "\r",
      "\n",
    ], ',', $form_state
      ->getValue('recipents')));
    foreach ($emails as $key => $email) {
      $email = trim($email);
      if ($email) {
        if (!$this->emailValidator
          ->isValid($email)) {
          $form_state
            ->setErrorByName('recipents', $this
            ->t('Invalid email address: @mail. Please correct this email.', [
            '@mail' => $email,
          ]));
          unset($emails[$key]);
        }
        else {
          $emails[$key] = $email;
        }
      }
      else {
        unset($emails[$key]);
      }
    }
    $form_state
      ->set('validated_recipents', implode(', ', $emails));
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $fields = [
      'path',
    ];
    $conditions = [];
    $conditions['general'][] = [
      'field' => 'pid',
      'value' => $form_state
        ->get('pid'),
      'operator' => '=',
    ];
    $path = $this->protectedPagesStorage
      ->loadProtectedPage($fields, $conditions, TRUE);
    $module = 'protected_pages';
    $key = 'protected_pages_details_mail';
    $to = $form_state
      ->get('validated_recipents');
    $from = $this->configFactory
      ->getEditable('system.site')
      ->get('mail');
    $language_code = $this->languageManager
      ->getDefaultLanguage()
      ->getId();
    $send = TRUE;
    $params = [];
    $params['subject'] = $form_state
      ->getValue('subject');
    $params['body'] = $form_state
      ->getValue('body');
    $params['protected_page_url'] = Url::fromUri('internal:' . $path, [
      'absolute' => TRUE,
    ])
      ->toString();
    $result = $this->mailManager
      ->mail($module, $key, $to, $language_code, $params, $from, $send);
    if ($result['result'] !== TRUE) {
      $message = $this
        ->t('There was a problem sending your email notification to @email.', [
        '@email' => $to,
      ]);
      $this->loggerFactory
        ->get('protected_pages')
        ->error($message);
    }
    else {
      $message = $this
        ->t('The Email has been sent to @email.', [
        '@email' => $to,
      ]);
      $this->loggerFactory
        ->get('protected_pages')
        ->notice($message);
    }
    $form_state
      ->setRedirect('protected_pages_list');
  }

}

Members

Namesort descending Modifiers Type Description Overrides
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
FormBase::$requestStack protected property The request stack. 1
FormBase::$routeMatch protected property The route match.
FormBase::config protected function Retrieves a configuration object.
FormBase::configFactory protected function Gets the config factory for this form. 1
FormBase::container private function Returns the service container.
FormBase::currentUser protected function Gets the current user.
FormBase::getRequest protected function Gets the request object.
FormBase::getRouteMatch protected function Gets the route match.
FormBase::logger protected function Gets the logger for a specific channel.
FormBase::redirect protected function Returns a redirect response object for the specified route. Overrides UrlGeneratorTrait::redirect
FormBase::resetConfigFactory public function Resets the configuration factory.
FormBase::setConfigFactory public function Sets the config factory for this form.
FormBase::setRequestStack public function Sets the request stack object to use.
LinkGeneratorTrait::$linkGenerator protected property The link generator. 1
LinkGeneratorTrait::getLinkGenerator Deprecated protected function Returns the link generator.
LinkGeneratorTrait::l Deprecated protected function Renders a link to a route given a route name and its parameters.
LinkGeneratorTrait::setLinkGenerator Deprecated public function Sets the link generator service.
LoggerChannelTrait::getLogger protected function Gets the logger for a specific channel.
LoggerChannelTrait::setLoggerFactory public function Injects the logger channel factory.
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
ProtectedPagesSendEmailForm::$configFactory protected property Config Factory service. Overrides FormBase::$configFactory
ProtectedPagesSendEmailForm::$emailValidator protected property The email validator.
ProtectedPagesSendEmailForm::$languageManager protected property Language manager service.
ProtectedPagesSendEmailForm::$loggerFactory protected property Logger channel factory. Overrides LoggerChannelTrait::$loggerFactory
ProtectedPagesSendEmailForm::$mailManager protected property The mail manager.
ProtectedPagesSendEmailForm::$messenger protected property Provides messenger service. Overrides MessengerTrait::$messenger
ProtectedPagesSendEmailForm::$protectedPagesStorage protected property The protected pages storage service.
ProtectedPagesSendEmailForm::buildForm public function Form constructor. Overrides FormInterface::buildForm
ProtectedPagesSendEmailForm::create public static function Instantiates a new instance of this class. Overrides FormBase::create
ProtectedPagesSendEmailForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
ProtectedPagesSendEmailForm::submitForm public function Form submission handler. Overrides FormInterface::submitForm
ProtectedPagesSendEmailForm::validateForm public function Form validation handler. Overrides FormBase::validateForm
ProtectedPagesSendEmailForm::__construct public function Constructs a new ProtectedPagesSendEmailForm.
RedirectDestinationTrait::$redirectDestination protected property The redirect destination service. 1
RedirectDestinationTrait::getDestinationArray protected function Prepares a 'destination' URL query parameter for use with \Drupal\Core\Url.
RedirectDestinationTrait::getRedirectDestination protected function Returns the redirect destination service.
RedirectDestinationTrait::setRedirectDestination public function Sets the redirect destination service.
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.
UrlGeneratorTrait::$urlGenerator protected property The url generator.
UrlGeneratorTrait::getUrlGenerator Deprecated protected function Returns the URL generator service.
UrlGeneratorTrait::setUrlGenerator Deprecated public function Sets the URL generator service.
UrlGeneratorTrait::url Deprecated protected function Generates a URL or path for a specific route based on the given parameters.