You are here

class QueueForm in Notify 8

Same name and namespace in other branches
  1. 2.0.x src/Form/QueueForm.php \Drupal\notify\Form\QueueForm
  2. 1.0.x src/Form/QueueForm.php \Drupal\notify\Form\QueueForm

Defines a form that configures forms module settings.

Hierarchy

Expanded class hierarchy of QueueForm

1 string reference to 'QueueForm'
notify.routing.yml in ./notify.routing.yml
notify.routing.yml

File

src/Form/QueueForm.php, line 15

Namespace

Drupal\notify\Form
View source
class QueueForm extends ConfigFormBase {

  /**
   * Drupal\Core\Messenger\MessengerInterface definition.
   *
   * @var \Drupal\Core\Messenger\MessengerInterface
   */
  protected $messenger;

  /**
   * Class constructor.
   *
   * @param ConfigFactoryInterface $config_factory
   *   The config factory.
   * @param MessengerInterface $messenger
   *   The core messenger service.
   */
  public function __construct(ConfigFactoryInterface $config_factory, MessengerInterface $messenger) {
    parent::__construct($config_factory);
    $this->messenger = $messenger;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('config.factory'), $container
      ->get('messenger'));
  }

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

  /**
   * {@inheritdoc}
   */
  protected function getEditableConfigNames() {
    return [
      'notify.settings',
    ];
  }

  /*
   * Helper function to emulate count() prior to PHP 7.2.
   */
  private function _Count($arg) {
    return is_countable($arg) ? count($arg) : 0;
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state, Request $request = NULL) {
    $config = $this
      ->config('notify.settings');
    $period = $config
      ->get('notify_period');
    $since = $config
      ->get('notify_send_last') - $period;
    $lastdate = \Drupal::service('date.formatter')
      ->format($since, 'short');
    if (NULL !== $config
      ->get('notify_send_start')) {
      $start = \Drupal::time()
        ->getRequestTime();
    }
    else {
      $start = $config
        ->get('notify_send_start');
    }
    $start = $config
      ->get('notify_send_start') ?? 0;
    $startdate = \Drupal::service('date.formatter')
      ->format($start, 'short');
    $notify_send_last = $config
      ->get('notify_send_last');
    if (!isset($notify_send_last)) {
      $notify_send_last = \Drupal::time()
        ->getRequestTime();
    }
    $next_last = _notify_next_notificaton($notify_send_last);
    if ($next_last == -1) {
      $batch_msg = $this
        ->t('No more notifications scheduled');
    }
    elseif ($next_last == 0) {
      $batch_msg = $this
        ->t('The next notification is scheduled for the next cron run');
    }
    else {
      $next = \Drupal::service('date.formatter')
        ->format($next_last, 'short');
      $batch_msg = $this
        ->t('The next notification is scheduled for the first cron run after ') . $next;
    }
    $form['process'] = [
      '#type' => 'radios',
      '#title' => $this
        ->t('Notification queue operations'),
      '#default_value' => 0,
      '#options' => [
        $this
          ->t('Send batch now'),
        $this
          ->t('Truncate queue'),
        $this
          ->t('Override timestamp'),
      ],
      '#description' => $this
        ->t('Select &#8220;Send batch now&#8220; to send next batch of e-mails queued for notifications. Select &#8220;Truncate queue&#8220; to empty queue of pending notification <em>without</em> sending e-mails. Select &#8220;Override timestamp&#8220; to override the last notification timestamp. Press &#8220;Submit&#8220; to execute.'),
    ];
    $send_last = \Drupal::service('date.formatter')
      ->format($notify_send_last, 'custom', 'Y-m-d H:i:s');
    $form['lastdate'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Last notification timestamp'),
      '#default_value' => $send_last,
      '#size' => 19,
      '#maxlength' => 19,
      '#description' => $this
        ->t('To explicitly set the last notification timestamp, change the value of this field and select the &#8220;Override timestamp&#8220; option above, then press &#8220;Submit&#8220; to execute.'),
    ];
    $form['batch'] = [
      '#type' => 'fieldset',
      '#title' => $this
        ->t('Status'),
      '#collapsible' => TRUE,
    ];
    list($np, $cp, $nn, $cn, $nu, $cu) = _notify_count($config);
    $npcp = $np + $cp;
    if ($npcp) {
      $queue_msg = $this
        ->t('Notifications about at least @item queued', [
        '@item' => \Drupal::translation()
          ->formatPlural($npcp, '1 item is', '@count items are'),
      ]);
    }
    else {
      $queue_msg = $this
        ->t('No notifications queued');
    }
    $flagcnt = QueueForm::_Count($config
      ->get('notify_skip_nodes')) + QueueForm::_Count($config
      ->get('notify_skip_comments'));
    if ($flagcnt) {
      $skip_msg = $this
        ->t('@item flagged for skipping', [
        '@item' => \Drupal::translation()
          ->formatPlural($flagcnt, '1 item is', '@count items are'),
      ]);
    }
    else {
      $skip_msg = $this
        ->t('No item is flagged for skipping');
    }
    if ($np && $nu || $cp && $cu) {
      $nonew_msg = '';
    }
    else {
      $nonew_msg = $this
        ->t(', no notification about unpublished items are queued');
    }
    if ($nu + $cu) {
      $unpub_msg = $this
        ->t('Unpublished: @nodeup and @commup', [
        '@nodeup' => \Drupal::translation()
          ->formatPlural($nu, '1 node', '@count nodes'),
        '@commup' => \Drupal::translation()
          ->formatPlural($cu, '1 comment', '@count comments'),
      ]) . $nonew_msg;
    }
    else {
      $unpub_msg = $this
        ->t('No unpublished items');
    }
    $sent = $config
      ->get('notify_num_sent');
    $fail = $config
      ->get('notify_num_failed');
    $users = $config
      ->get('notify_users');
    $batch_remain = $users ? count($users) : 0;
    $creat_msg = $this
      ->t('There are @nodes and @comms created', [
      '@nodes' => \Drupal::translation()
        ->formatPlural($np, '1 node', '@count nodes'),
      '@comms' => \Drupal::translation()
        ->formatPlural($cp, '1 comment', '@count comments'),
    ]);
    if ($nn + $cn) {
      $publ_msg = $this
        ->t(', and in addition @noderp and @commrp published,', [
        '@noderp' => \Drupal::translation()
          ->formatPlural($nn, '1 node', '@count nodes'),
        '@commrp' => \Drupal::translation()
          ->formatPlural($cn, '1 comment', '@count comments'),
      ]);
    }
    else {
      $publ_msg = '';
    }
    if ($batch_remain) {
      $intrv_msg = $this
        ->t('between @last and @start', [
        '@last' => $lastdate,
        '@start' => $startdate,
      ]);
      $sent_msg = $this
        ->t('Batch not yet complete.  So far @sent has been sent (@fail, @remain to go)', [
        '@sent' => \Drupal::translation()
          ->formatPlural($sent, '1 e-mail', '@count e-mails'),
        '@fail' => \Drupal::translation()
          ->formatPlural($fail, '1 failure', '@count failures'),
        '@remain' => \Drupal::translation()
          ->formatPlural($batch_remain, '1 user', '@count users'),
      ]);
    }
    else {
      $intrv_msg = $this
        ->t('since @last', [
        '@last' => $lastdate,
      ]);
      $sent_msg = $this
        ->t('Last batch:') . ' ';
      if ($sent == 0) {
        $sent_msg = $this
          ->t('No e-mails were sent');
      }
      else {
        $sent_msg .= $this
          ->t('sent @sent', [
          '@sent' => \Drupal::translation()
            ->formatPlural($sent, '1 e-mail', '@count e-mails'),
        ]);
      }
      if ($fail > 0) {
        $sent_msg .= ', ' . $this
          ->t('@fail', [
          '@fail' => \Drupal::translation()
            ->formatPlural($fail, '1 failure', '@count failures'),
        ]);
      }
      elseif ($sent) {
        $sent_msg .= ', ' . $this
          ->t('no failures');
      }
    }
    $mailsystem = $config
      ->get('mail_system') ?? NULL;
    $ms = isset($mailsystem['default-system']) ? $mailsystem['default-system'] : $this
      ->t('system default');
    $form['batch']['schedule'] = [
      '#markup' => $creat_msg . $publ_msg . ' ' . $intrv_msg . '.<br>' . $unpub_msg . '.<br>' . $queue_msg . '.<br>' . $skip_msg . '.<br>' . $sent_msg . '.<br>' . $batch_msg . '.<br>' . $this
        ->t('Default MailSystem: ') . $ms . '.',
    ];
    return parent::buildForm($form, $form_state);
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $config = $this
      ->config('notify.settings');
    $values = $form_state
      ->getValues();
    $process = $values['process'];
    $notify_send_last = $config
      ->get('notify_send_last');
    $frform_send_last = strtotime($values['lastdate']);
    if (FALSE === $frform_send_last) {

      //      form_set_error('notify_queue_settings', $this->t('This does not look like a valid date format.'));
      $this->messenger
        ->addMessage($this
        ->t('This does not look like a valid date format.'), 'error');
      $form_state
        ->setRebuild();
      return;
    }
    if ($process < 2) {
      if ($notify_send_last != $frform_send_last) {
        $this->messenger
          ->addMessage($this
          ->t('You must select &#8220;Override timestamp&#8221; to override the timestamp.'), 'error');
        $form_state
          ->setRebuild();
        return;
      }
    }
    elseif ($process == 2) {
      if ($notify_send_last == $frform_send_last) {
        $this->messenger
          ->addMessage($this
          ->t('You selected &#8220;Override timestamp&#8221;, but the timestamp is not altered.'), 'error');
        $form_state
          ->setRebuild();
        return;
      }
    }
    $watchdog_level = $config
      ->get('notify_watchdog') ?? 0;
    if (0 == $values['process']) {

      // flush
      list($num_sent, $num_fail) = _notify_send();
      if ($num_fail > 0) {
        $this->messenger
          ->addMessage($this
          ->t('@sent notification @emsent sent successfully, @fail @emfail could not be sent.', [
          '@sent' => $num_sent,
          '@emsent' => \Drupal::translation()
            ->formatPlural($num_sent, 'e-mail', 'e-mails'),
          '@fail' => $num_fail,
          '@emfail' => \Drupal::translation()
            ->formatPlural($num_fail, 'notification', 'notifications'),
        ]), 'error');

        //        $watchdog_status = WATCHDOG_ERROR;
      }
      elseif ($num_sent > 0) {
        $this->messenger
          ->addMessage($this
          ->t('@count pending notification @emails have been sent in this pass.', [
          '@count' => $num_sent,
          '@emails' => \Drupal::translation()
            ->formatPlural($num_sent, 'e-mail', 'e-mails'),
        ]));

        //        $watchdog_status = WATCHDOG_INFO;
      }
      if (0 == $num_sent + $num_fail) {
        $this->messenger
          ->addMessage($this
          ->t('No notifications needed to be sent in this pass.'));
      }
      else {
        if ($watchdog_level <= 1) {
          \Drupal::logger('notify')
            ->notice('Notifications sent: @sent, failures: @fail.', [
            '@sent' => $num_sent,
            '@fail' => $num_fail,
          ]);
        }
      }
      $num_sent += $config
        ->get('notify_num_sent');
      $num_fail += $config
        ->get('notify_num_failed');
      \Drupal::configFactory()
        ->getEditable('notify.settings')
        ->set('notify_num_sent', $num_sent)
        ->set('notify_num_failed', $num_fail)
        ->set('notify_skip_nodes', [])
        ->set('notify_skip_comments', [])
        ->save();
    }
    elseif (1 == $values['process']) {

      // truncate
      list($res_nodes, $res_comms, $res_nopub, $res_copub, $res_nounp, $res_counp) = _notify_select_content();
      foreach ($res_nopub as $row) {
        $q = \Drupal::database()
          ->delete('notify_unpublished_queue', 'n');
        $q
          ->condition('n.cid', 0);
        $q
          ->condition('n.nid', $row->nid);
        $q
          ->execute();
      }
      foreach ($res_copub as $row) {
        $q = \Drupal::database()
          ->delete('notify_unpublished_queue', 'n');
        $q
          ->condition('n.cid', $row->cid);
        $q
          ->condition('n.nid', $row->nid);
        $q
          ->execute();
      }
      \Drupal::configFactory()
        ->getEditable('notify.settings')
        ->set('notify_send_start', \Drupal::time()
        ->getRequestTime())
        ->set('notify_send_last', \Drupal::time()
        ->getRequestTime())
        ->set('notify_cron_next', 0)
        ->set('notify_users', [])
        ->set('notify_skip_nodes', [])
        ->set('notify_skip_comments', [])
        ->save();
      $this->messenger
        ->addMessage($this
        ->t('The notification queue has been truncated. No e-mail were sent.'));
      if ($watchdog_level <= 1) {
        \Drupal::logger('notify')
          ->notice('Notification queue truncated.');
      }
      return;
    }
    elseif (2 == $values['process']) {

      // override
      $last_date = strtotime($values['lastdate']);
      \Drupal::configFactory()
        ->getEditable('notify.settings')
        ->set('notify_send_last', $last_date)
        ->set('notify_skip_nodes', [])
        ->set('notify_skip_comments', [])
        ->save();
      $this->messenger
        ->addMessage($this
        ->t('Timestamp overridden'));
    }
  }

}

Members

Namesort descending Modifiers Type Description Overrides
ConfigFormBaseTrait::config protected function Retrieves a configuration object.
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::$configFactory protected property The config factory. 1
FormBase::$requestStack protected property The request stack. 1
FormBase::$routeMatch protected property The route match.
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.
FormBase::validateForm public function Form validation handler. Overrides FormInterface::validateForm 62
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::$loggerFactory protected property The logger channel factory 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.
QueueForm::$messenger protected property Drupal\Core\Messenger\MessengerInterface definition. Overrides MessengerTrait::$messenger
QueueForm::buildForm public function Form constructor. Overrides ConfigFormBase::buildForm
QueueForm::create public static function Instantiates a new instance of this class. Overrides ConfigFormBase::create
QueueForm::getEditableConfigNames protected function Gets the configuration names that will be editable. Overrides ConfigFormBaseTrait::getEditableConfigNames
QueueForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
QueueForm::submitForm public function Form submission handler. Overrides ConfigFormBase::submitForm
QueueForm::_Count private function
QueueForm::__construct public function Class constructor. Overrides ConfigFormBase::__construct
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.