cforge-2.0.x-dev/src/Forms/MassContact.php

src/Forms/MassContact.php
<?php

namespace Drupal\cforge\Forms;

Use Drupal\user\Entity\User;
Use Drupal\user\Entity\Role;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Batch\BatchBuilder;
use Drupal\user\UserStorageInterface;
use Drupal\Core\Mail\MailManager;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Send an email to all members of the site, regardless of preferences.
 */
class MassContact extends FormBase {

  protected $userStorage;
  protected $mailPluginManager;

  /**
   * @param UserStorageInterface $user_storage
   * @param MailManager $mail_plugin_manger
   */
  function __construct(UserStorageInterface $user_storage, MailManager $mail_plugin_manger) {
    $this->userStorage = $user_storage;
    $this->mailPluginManager = $mail_plugin_manger;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('entity_type.manager')->getStorage('user'),
      $container->get('plugin.manager.mail')
    );
  }

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

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $options['test'] = $this->t('Just me (test)');
    foreach (Role::loadMultiple() as $rid => $role) {
      if ($rid == 'anonymous') continue;
      $options[$rid] = $role->label();
    }
    $options['never'] = $this->t('Never logged in');
    $form['role_id'] = [
      '#title' => $this->t('Recipients'),
      '#type' => 'radios',
      '#options' => $options,
      '#default_value' => 'anonymous',
      '#weight' => 0,
    ];
    $form['subject'] = [
      '#title' => $this->t('Message subject'),
      '#type' => 'textfield',
      '#weight' => 1,
    ];
    $form['body'] = [
      '#title' => $this->t('Message body'),
      '#type' => 'text_format',
      '#format' => 'mail_authoring',
      '#rows' => 10,
      '#weight' => 2,
    ];

    $form['tokens'] = \Drupal::service('token.tree_builder')
      ->buildRenderable(['user'], ['global_types' => FALSE]);
    $form['tokens']['#weight'] = 3;
    $form['tokens']['#click_insert'] = FALSE;
    $form['tokens']['#columns'] = ['token'];

    $form['submit'] = [
      '#type' => 'submit',
      '#value' => $this->t('Send'),
      '#weight' => 4,
    ];

    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $audience = $form_state->getValue('role_id');
    if ($audience == 'test') {
      $uids = [$this->currentUser()->id()];
    }
    elseif ($audience == 'never') {
      $uids = $this->userStorage->getQuery()
        ->accessCheck(TRUE)
        ->condition('access', 0)
        ->execute();
    }
    else {
      $uids = $this->userStorage->getQuery()
        ->accessCheck(TRUE)
        ->condition('status', 1)
        ->condition('roles', $form_state->getValue('role_id'))
        ->execute();
    }

    $batch_builder = (new BatchBuilder())
      ->setTitle($this->t('Sending @count mails', ['@count' => count($uids)]))
      ->setFile('profiles/cforge/src/Forms/MassContact.php')
      ->setProgressMessage($this->t('Processed @current out of @total.'));

    foreach (array_chunk($uids, 20) as $chunk) {
      $batch_builder->addOperation(
        [$this, 'sendBatchMails'],
        [$chunk, $form_state->getValue('subject'), $form_state->getValue('body')['value']]
      );
    }

    batch_set($batch_builder->toArray());
  }


  /**
   * Batch callback.
   */
  public function sendBatchMails($uids, $subject, $body) {
    $users = User::loadMultiple($uids);
    foreach ($users as $account) {
      $this->mailPluginManager->mail(
        'cforge',
        'mass',
        $account->getEmail(),
        \Drupal::currentuser()->getPreferredLangcode(),
        [
          'subject' => $subject,
          'body' => $body,
          'recipient' => $account
        ]
      );
    }
  }

}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc