social_event_invite_flow-1.0.0-beta3/src/Service/SendEmails.php
src/Service/SendEmails.php
<?php
namespace Drupal\social_event_invite_flow\Service;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\Component\Utility\Environment;
use Drupal\Core\File\FileSystemInterface;
use Drupal\social_event_invite_flow\Service\EventInviteFlowService;
use Drupal\user\UserInterface;
/**
* Service description.
*/
class SendEmails {
/**
* The social_event_invite_flow.invite_flow_service service.
*
* @var \Drupal\social_event_invite_flow\Service\EventInviteFlowService
*/
protected $inviteFlowService;
/**
* The current user.
*
* @var \Drupal\Core\Session\AccountInterface
*/
protected $account;
/**
* The entity type manager.
*
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
*/
protected $entityTypeManager;
/**
* Constructs an ImportEmails object.
*
* @param \Drupal\social_event_invite_flow\Service\EventInviteFlowService $invite_flow_service
* The social_event_invite_flow.invite_flow_service service.
* @param \Drupal\Core\Session\AccountInterface $account
* The current user.
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
* The entity type manager.
*/
public function __construct(EventInviteFlowService $invite_flow_service, AccountInterface $account, EntityTypeManagerInterface $entity_type_manager) {
$this->inviteFlowService = $invite_flow_service;
$this->account = $account;
$this->entityTypeManager = $entity_type_manager;
}
/**
* Method description.
*/
public function doSomething() {
// @DCG place your code here.
}
/**
* Handle batch completion.
*
* Creates a new CSV file containing all failed rows if any.
*/
public static function csvImportFinished($success, $results, $operations) {
$messenger = \Drupal::messenger();
if (!empty($results['failed_rows'])) {
$dir = 'public://csvupload';
if (\Drupal::service('file_system')
->prepareDirectory($dir, FileSystemInterface::CREATE_DIRECTORY)) {
// We validated extension on upload.
$csv_filename = 'failed_rows-' . basename($results['uploaded_filename']);
$csv_filepath = $dir . '/' . $csv_filename;
$targs = [
':csv_url' => file_create_url($csv_filepath),
'@csv_filename' => $csv_filename,
'@csv_filepath' => $csv_filepath,
];
// Deprecated in PHP 8.1
//ini_set('auto_detect_line_endings', true);
if ($handle = fopen($csv_filepath, 'w+')) {
foreach ($results['failed_rows'] as $failed_row) {
fputcsv($handle, $failed_row);
}
fclose($handle);
$messenger->addMessage(t('Some rows failed to import. You may download a CSV of these rows: <a href=":csv_url">@csv_filename</a>', $targs), 'error');
}
else {
$messenger->addMessage(t('Some rows failed to import, but unable to write error CSV to @csv_filepath', $targs), 'error');
}
}
else {
$messenger->addMessage(t('Some rows failed to import, but unable to create directory for error CSV at @csv_directory', $targs), 'error');
}
}
if ($success) {
$message = t('Invites have been sent!');
// Here we do something meaningful with the results.
//$message = t("@count tasks were done.", array(
//'@count' => count($results),
//));
\Drupal::messenger()->addMessage($message);
}
}
/**
* Remember the uploaded CSV filename.
*
* @TODO Is there a better way to pass a value from inception of the batch to
* the finished function?
*/
public static function csvUploadRememberFilename($filename, &$context) {
$context['results']['uploaded_filename'] = $filename;
}
/**
* Process a single line.
*/
public static function csvUploadLine($line, $email, $nid, &$context) {
$invite_flow_service = \Drupal::service('social_event_invite_flow.invite_flow_service');
//if (!array_key_exists('rows_imported', $context['results'])) {
//$context['results']['rows_imported'] = 0;
//}
//$context['results']['rows_imported']++;
$context['results']['email'] = $email;
$context['results']['node'] = $nid;
// Simply show the import row count.
//$context['message'] = t('Importing row !c', ['!c' => $context['results']['email']]);
//$context['message'] = t('Importing %title', ['%title' => 'Importing Emails']);
// In order to slow importing and debug better, we can uncomment
// this line to make each import slightly slower.
// @codingStandardsIgnoreStart
//usleep(2500);
// @codingStandardsIgnoreEnd
// Convert the line of the CSV file into a new user.
// @codingStandardsIgnoreStart
// Default language & Timezone
$language_default = \Drupal::languageManager()->getCurrentLanguage()->getId();
$config = \Drupal::config('system.date');
$timezone_default = $config->get('timezone.default');
if (!empty($email)) {
if (!SendEmails::validateEmail($email)) {
$context['results']['failed_rows'][] = $line;
}
else {
$user = user_load_by_mail($email);
if ($user instanceof UserInterface) {
\Drupal::logger('debug')->debug('Yeah 1');
// Send emails when enrolled only
$invite_flow_service->enrollExistingAccount($user, $nid);
}
else {
$invite_flow_service->enrollNewAccount($email, $nid);
}
}
}
}
public static function isValidLangcode($langcode) {
$allowed_languages = \Drupal::languageManager()->getLanguages();
if(array_key_exists($langcode,$allowed_languages)) {
return true;
}
return false;
}
public static function isValidTimezone($timezone) {
$timezones = User::getAllowedTimezones();
if (in_array($timezone, $timezones)) {
return true;
}
return false;
}
public static function validateEmail(string $email) {
if (\Drupal::service('email.validator')->isValid($email)) {
return true;
}
return false;
}
public static function validateStatus(string $status) {
if ($status === "1" || $status === "0") {
return true;
}
return false;
}
public static function cleanPassword(string $password) {
return str_replace(' ','', $password);
}
/**
* Send the invites to emails in a batch.
*
* @param array $users
* Array containing user ids or user emails.
* @param string $nid
* The node id.
* @param array $context
* The context.
*
* @throws \Drupal\Core\Entity\EntityStorageException
*/
public static function bulkInviteUsersEmails(array $users, $nid, array &$context) {
$results = [];
\Drupal::logger('debug')->debug('TEST!!!');
$invite_flow_service = \Drupal::service('social_event_invite_flow.invite_flow_service');
foreach ($users as $user) {
\Drupal::logger('debug')->debug($user);
// @todo Should be merged with extractEmailsFrom from InviteEmailBaseForm.
// Remove select2 ID parameter.
$user = str_replace('$ID:', '', $user);
\Drupal::logger('debug')->debug($user);
preg_match_all("/[\._a-zA-Z0-9+-]+@[\._a-zA-Z0-9+-]+/i", $user, $email);
$email = $email[0];
// If the user is an email.
if ($email) {
$user = user_load_by_mail($email);
if ($user instanceof UserInterface) {
// Send emails when enrolled only
$invite_flow_service->enrollExistingAccount($user, $nid);
}
else {
$invite_flow_service->enrollNewAccount($email['0'], $nid);
}
}
// If the user is a UID.
else {
$account = \Drupal::entityTypeManager()->getStorage('user')->load($user);
// Send emails when enrolled only
$invite_flow_service->enrollExistingAccount($account, $nid);
}
$results[$nid] = $nid;
}
$context['results'] = $results;
}
/**
* Callback when the batch for inviting emails for an event has finished.
*/
public static function bulkInviteUserEmailsFinished($success, $results, $operations) {
$nid = NULL;
// We got the node event id in the results array so we will use that
// to provide the param in in redirect url.
if (!empty($results)) {
// We don't care about resetting the array first.
$nid = key($results);
}
if ($success && !empty($results)) {
\Drupal::messenger()->addStatus(t('Invite(s) have been successfully sent.'));
}
elseif ($success && empty($results)) {
\Drupal::messenger()->AddStatus(t('No invites were sent, recipients already received one before.'));
}
else {
\Drupal::messenger()->addError(t('There was an unexpected error.'));
}
}
}
