View source
<?php
namespace Drupal\social_group_invite\Form;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Logger\LoggerChannelFactoryInterface;
use Drupal\Core\Messenger\MessengerInterface;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\Core\TempStore\PrivateTempStoreFactory;
use Drupal\Core\Url;
use Drupal\Core\Utility\Token;
use Drupal\file\Entity\File;
use Drupal\ginvite\GroupInvitationLoader;
use Drupal\group\GroupMembershipLoaderInterface;
use Drupal\group\Plugin\GroupContentEnablerManagerInterface;
use Drupal\user\Entity\User;
use Drupal\user\UserInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\ginvite\Form\BulkGroupInvitation;
use Symfony\Component\HttpFoundation\RedirectResponse;
class SocialBulkGroupInvitation extends BulkGroupInvitation {
protected $routeMatch;
protected $entityTypeManager;
protected $tempStoreFactory;
protected $loggerFactory;
protected $messenger;
protected $group;
protected $configFactory;
protected $token;
protected $pluginManager;
public function __construct(RouteMatchInterface $route_match, EntityTypeManagerInterface $entity_type_manager, PrivateTempStoreFactory $temp_store_factory, LoggerChannelFactoryInterface $logger_factory, MessengerInterface $messenger, GroupMembershipLoaderInterface $group_membership_loader, GroupInvitationLoader $invitation_loader, GroupContentEnablerManagerInterface $plugin_manager, ConfigFactoryInterface $config_factory, Token $token) {
parent::__construct($route_match, $entity_type_manager, $temp_store_factory, $logger_factory, $messenger, $group_membership_loader, $invitation_loader);
$this->group = $this->routeMatch
->getParameter('group');
$this->pluginManager = $plugin_manager;
$this->configFactory = $config_factory;
$this->token = $token;
}
public static function create(ContainerInterface $container) {
return new static($container
->get('current_route_match'), $container
->get('entity_type.manager'), $container
->get('tempstore.private'), $container
->get('logger.factory'), $container
->get('messenger'), $container
->get('group.membership_loader'), $container
->get('ginvite.invitation_loader'), $container
->get('plugin.manager.group_content_enabler'), $container
->get('config.factory'), $container
->get('token'));
}
public function getFormId() {
return 'social_bulk_group_invitation';
}
public function buildForm(array $form, FormStateInterface $form_state) {
$form = parent::buildForm($form, $form_state);
$form['#attributes']['class'][] = 'form--default';
$group = $this->routeMatch
->getParameter('group');
$params = [
'user' => $this
->currentUser(),
'group' => $this->routeMatch
->getParameter('group'),
];
unset($form['email_address']);
$form['users_fieldset'] = [
'#type' => 'fieldset',
'#tree' => TRUE,
'#collapsible' => FALSE,
'#collapsed' => FALSE,
'#attributes' => [
'class' => [
'form-horizontal',
],
],
];
$form['users_fieldset']['user'] = [
'#title' => $this
->t('Find people by name or email address'),
'#type' => 'select2',
'#description' => $this
->t('You can enter or paste multiple entries separated by comma or semicolon'),
'#multiple' => TRUE,
'#tags' => TRUE,
'#autocomplete' => TRUE,
'#selection_handler' => 'social',
'#target_type' => 'user',
'#select2' => [
'tags' => TRUE,
'placeholder' => t('Jane Doe, johndoe@example.com'),
'tokenSeparators' => [
',',
';',
],
'autocomplete' => FALSE,
],
'#required' => TRUE,
'#validated' => TRUE,
];
$group_plugin_collection = $this->pluginManager
->getInstalled($group
->getGroupType());
$group_invite_config = $group_plugin_collection
->getConfiguration()['group_invitation'];
$invite_settings = $this->configFactory
->get('social_group.settings')
->get('group_invite');
$invitation_subject = $invite_settings['invite_subject'] ?? $group_invite_config['invitation_subject'];
$invitation_body = $invite_settings['invite_message'] ?? $group_invite_config['invitation_body'];
$invitation_body = $this->token
->replace($invitation_body, $params);
$invitation_body = preg_replace('/href="([^"]*)"/', 'href="#"', $invitation_body);
$theme_id = $this->configFactory
->get('system.theme')
->get('default');
$logo = $this
->getRequest()
->getBaseUrl() . theme_get_setting('logo.url', $theme_id);
$email_logo = theme_get_setting('email_logo', $theme_id);
if (is_array($email_logo) && !empty($email_logo)) {
$file = File::load(reset($email_logo));
if ($file instanceof File) {
$logo = file_create_url($file
->getFileUri());
}
}
$invite_config = $this->configFactory
->get('social_group_invite.settings');
$form['email_preview'] = [
'#type' => 'fieldset',
'#title' => [
'text' => [
'#markup' => t('Preview your email invite'),
],
'icon' => [
'#markup' => '<svg class="icon icon-expand_more"><use xlink:href="#icon-expand_more" /></svg>',
'#allowed_tags' => [
'svg',
'use',
],
],
],
'#tree' => TRUE,
'#collapsible' => TRUE,
'#collapsed' => TRUE,
'#attributes' => [
'class' => [
'form-horizontal',
'form-preview-email',
],
],
];
$form['email_preview']['preview'] = [
'#theme' => 'invite_email_preview',
'#logo' => $logo,
'#subject' => $this->token
->replace($invitation_subject, $params),
'#body' => $invitation_body,
'#helper' => $this->token
->replace($invite_config
->get('invite_helper'), $params),
];
$form['actions']['#type'] = 'actions';
unset($form['submit']);
$form['actions']['submit'] = [
'#type' => 'submit',
'#value' => $this
->t('Send your invite(s) by email'),
];
return $form;
}
public function validateForm(array &$form, FormStateInterface $form_state) {
foreach ($form_state
->getValue('users_fieldset')['user'] as $user) {
$email = $this
->extractEmailsFrom($user);
if ($email) {
$account = user_load_by_mail($email);
if ($account instanceof UserInterface) {
$membership = $this->groupMembershipLoader
->load($this->group, $account);
if (!empty($membership)) {
$form_state
->unsetValue([
'users_fieldset',
'user',
$user,
]);
}
}
else {
if ($this->groupInvitationLoader
->loadByGroup($this->group, NULL, $email)) {
$form_state
->unsetValue([
'users_fieldset',
'user',
$user,
]);
}
}
}
else {
$account = user::load($user);
if ($account instanceof UserInterface) {
$membership = $this->groupMembershipLoader
->load($this->group, $account);
if (!empty($membership)) {
$form_state
->unsetValue([
'users_fieldset',
'user',
$user,
]);
}
else {
$form_state
->setValue([
'users_fieldset',
'user',
$user,
], $account
->getEmail());
}
}
}
}
}
public function submitForm(array &$form, FormStateInterface $form_state) {
$batch = [
'title' => $this
->t('Inviting Members'),
'operations' => [],
'init_message' => $this
->t('Sending Invites'),
'progress_message' => $this
->t('Processed @current out of @total.'),
'error_message' => $this
->t('An error occurred during processing'),
'finished' => 'Drupal\\social_group_invite\\Form\\SocialBulkGroupInvitation::batchFinished',
];
foreach ($form_state
->getValue('users_fieldset')['user'] as $email) {
$email = $this
->extractEmailsFrom($email);
if ($email) {
$values = [
'type' => $this->group
->getGroupType()
->getContentPlugin('group_invitation')
->getContentTypeConfigId(),
'gid' => $this->group
->id(),
'invitee_mail' => $email,
'entity_id' => 0,
];
$batch['operations'][] = [
'\\Drupal\\ginvite\\Form\\BulkGroupInvitationConfirm::batchCreateInvite',
[
$values,
],
];
}
}
$params = [];
$params['gid'] = $this->group
->id();
$params['plugin'] = $this->group
->getGroupType()
->getContentPlugin('group_invitation')
->getContentTypeConfigId();
$params['emails'] = $this
->getSubmittedEmails($form_state);
$tempstore = $this->tempStoreFactory
->get('ginvite_bulk_invitation');
$tempstore
->set('params', $params);
batch_set($batch);
}
private function getSubmittedEmails(FormStateInterface $form_state) {
return array_map('trim', array_unique(explode("\r\n", trim($form_state
->getValue('email_address')))));
}
public static function batchFinished($success, $results, $operations) {
if ($success) {
try {
$tempstore = \Drupal::service('tempstore.private')
->get('ginvite_bulk_invitation');
$params = $tempstore
->get('params')['gid'];
$destination = new Url('entity.group.canonical', [
'group' => $tempstore
->get('params')['gid'],
]);
$redirect = new RedirectResponse($destination
->toString());
$tempstore
->delete('params');
$redirect
->send();
} catch (\Exception $error) {
\Drupal::service('logger.factory')
->get('social_group_invite')
->alert(new TranslatableMarkup('@err', [
'@err' => $error,
]));
}
}
else {
$error_operation = reset($operations);
\Drupal::service('messenger')
->addMessage(new TranslatableMarkup('An error occurred while processing @operation with arguments : @args', [
'@operation' => $error_operation[0],
'@args' => print_r($error_operation[0]),
]));
}
}
public function extractEmailsFrom($string) {
$string = str_replace('$ID:', '', $string);
preg_match_all("/[\\._a-zA-Z0-9+-]+@[\\._a-zA-Z0-9+-]+/i", $string, $matches);
return $matches[0];
}
}