View source
<?php
namespace Drupal\sendinblue;
use Drupal\Component\Serialization\Json;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Database\Connection;
use Drupal\Core\Form\FormBuilderInterface;
use Drupal\Core\Mail\MailManagerInterface;
use Drupal\Core\Render\Renderer;
use Drupal\Core\Session\AccountProxyInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\sendinblue\Form\ConfigurationSendinblueForm;
use Drupal\sendinblue\Form\LogoutForm;
use Drupal\sendinblue\Form\RegisteringUserForm;
use Drupal\sendinblue\Form\TransactionnalEmailForm;
use Drupal\sendinblue\Tools\Api\SendInBlueApiInterface;
use Drupal\sendinblue\Tools\Api\SendinblueApiV2;
use Drupal\sendinblue\Tools\Api\SendinblueApiV3;
class SendinblueManager {
use StringTranslationTrait;
const SENDINBLUE_SIGNUP_ENTITY = 'sendinblue_signup_form';
const SENDINBLUE_SIGNUP_BLOCK = 1;
const SENDINBLUE_SIGNUP_PAGE = 2;
const SENDINBLUE_SIGNUP_BOTH = 3;
const SENDINBLUE_API_VERSION_V2 = 'v2';
const SENDINBLUE_API_VERSION_V3 = 'v3';
const SIB_URL = 'https://my.sendinblue.com';
const CONFIG_SETTINGS = 'sendinblue.config_global.settings';
const CONFIG_SETTINGS_REGISTERING_USER = 'sendinblue.config_registering_user.settings';
const CONFIG_SETTINGS_SEND_EMAIL = 'sendinblue.config_send_email.settings';
const ACCESS_KEY = 'sendinblue_access_key';
const ACCOUNT_EMAIL = 'sendinblue_account_email';
const ACCOUNT_USERNAME = 'sendinblue_account_username';
const ACCOUNT_DATA = 'sendinblue_account_data';
const ACCESS_TOKEN = 'sendinblue_access_token';
const SMTP_DETAILS = 'sendinblue_smtp_details';
private $configFactory;
private $formBuilder;
private $renderer;
private $sendinblueMailin;
private $connection;
private $mailManager;
private $accountProxy;
private $sendinblueApiV2;
private $sendinblueApiV3;
public function __construct(SendinblueApiV2 $sendinblueApiV2, SendinblueApiV3 $sendinblueApiV3, ConfigFactoryInterface $configFactory, Connection $connection, FormBuilderInterface $formBuilder, Renderer $renderer, MailManagerInterface $mailManager, AccountProxyInterface $accountProxy) {
$this->configFactory = $configFactory;
$this->connection = $connection;
$this->formBuilder = $formBuilder;
$this->renderer = $renderer;
$this->mailManager = $mailManager;
$this->accountProxy = $accountProxy;
$this->sendinblueApiV2 = $sendinblueApiV2;
$this->sendinblueApiV3 = $sendinblueApiV3;
$this
->updateSendinblueMailin($this
->getAccessKey());
}
public function getAccessKey() {
return $this->configFactory
->get(self::CONFIG_SETTINGS)
->get(self::ACCESS_KEY);
}
public function getApiVersion($accessKey) {
if (strlen($accessKey) > 20 && strpos($accessKey, 'xkeysib') !== FALSE) {
return self::SENDINBLUE_API_VERSION_V3;
}
return self::SENDINBLUE_API_VERSION_V2;
}
public function getSendinblueMailin() : SendInBlueApiInterface {
return $this->sendinblueMailin;
}
public function updateSendinblueMailin($accessKey) {
if ($this
->getApiVersion($accessKey) === self::SENDINBLUE_API_VERSION_V3) {
$this->sendinblueMailin = $this->sendinblueApiV3;
}
else {
$this->sendinblueMailin = $this->sendinblueApiV2;
}
$this->sendinblueMailin
->setApiKey($accessKey);
return $this->sendinblueMailin;
}
public function getAccountEmail() {
return $this->configFactory
->get(self::CONFIG_SETTINGS)
->get(self::ACCOUNT_EMAIL);
}
public function getAccountUsername() {
return $this->configFactory
->get(self::CONFIG_SETTINGS)
->get(self::ACCOUNT_USERNAME);
}
public function getAccountData() {
return $this->configFactory
->get(self::CONFIG_SETTINGS)
->get(self::ACCOUNT_DATA);
}
public function getSmtpDetails() {
return $this->configFactory
->get(self::CONFIG_SETTINGS_SEND_EMAIL)
->get(self::SMTP_DETAILS);
}
public function getAccessKeyToken() {
return $this->configFactory
->get(self::CONFIG_SETTINGS)
->get(self::ACCESS_TOKEN);
}
public function generateHomeLogout() {
$form = $this->formBuilder
->getForm(ConfigurationSendinblueForm::class);
return [
'#formulaire_api_key' => $this->renderer
->render($form),
];
}
public function generateHomeLogin() {
$lists = $this->sendinblueMailin
->getLists();
$totalSubscribers = 0;
$listIds = [];
if ($lists
->getCount() > 0) {
$listData = $lists
->getLists();
foreach ($listData as $list) {
$listIds[] = $list['id'];
}
$totalSubscribers = $this->sendinblueMailin
->countUserlists($listIds);
}
$accountEmail = $this
->getAccountEmail();
$accountUsername = $this
->getAccountUsername();
$account_data = Json::decode($this
->getAccountData());
$sendinblue_logout_form = $this->formBuilder
->getForm(LogoutForm::class);
$sendinblue_send_email_form = $this->formBuilder
->getForm(TransactionnalEmailForm::class);
$sendinblue_user_register_form = $this->formBuilder
->getForm(RegisteringUserForm::class);
return [
'#account_username' => [
'#plain_text' => $accountUsername,
],
'#account_email' => [
'#plain_text' => $accountEmail,
],
'#total_subscribers' => [
'#plain_text' => $totalSubscribers,
],
'#account_data' => $account_data,
'#api_version' => $this
->getApiVersion($this
->getAccessKey()),
'#sendinblue_logout_form' => $this->renderer
->render($sendinblue_logout_form),
'#sendinblue_send_email_form' => $this->renderer
->render($sendinblue_send_email_form),
'#sendinblue_user_register_form' => $this->renderer
->render($sendinblue_user_register_form),
];
}
public function generateListLogin() {
$access_token = $this
->updateAccessToken();
return sprintf(self::SIB_URL . '/lists/index/access_token/%s', $access_token);
}
public function generateCampaignLogin() {
$access_token = $this
->updateAccessToken();
return sprintf(self::SIB_URL . '/camp/listing/access_token/%s', $access_token);
}
public function generateStatisticLogin() {
$access_token = $this
->updateAccessToken();
return sprintf(self::SIB_URL . '/camp/message/access_token/%s', $access_token);
}
public function isLoggedInState() {
$access_key = $this
->getAccessKey();
if (!empty($access_key)) {
return TRUE;
}
return FALSE;
}
public function updateAccessToken() {
$config = $this->configFactory
->getEditable('sendinblue.settings');
$access_token = $this->sendinblueMailin
->getAccessTokens();
$config
->set(self::ACCESS_TOKEN, $access_token);
return $access_token;
}
public function getEmailTemplate($type = 'test') {
$file = 'temp';
$file_path = drupal_get_path('module', 'sendinblue') . '/asset/email-templates/' . $type . '/';
$html_content = file_get_contents($file_path . $file . '.html');
$text_content = file_get_contents($file_path . $file . '.txt');
$templates = [
'html_content' => $html_content,
'text_content' => $text_content,
];
return $templates;
}
public function sendEmail($type, $to_email, $template_id = '-1') {
$subjects = [
'confirm' => $this
->t('Subscription confirmed'),
'test' => $this
->t('[SendinBlue SMTP] test email'),
];
$account_email = $this
->getAccountEmail();
$account_username = $this
->getAccountUsername();
$subject = $subjects[$type] ?? '[SendinBlue]';
$sender_email = !empty($account_email) ? $account_email : $this
->t('no-reply@sendinblue.com');
$sender_name = !empty($account_username) ? $account_username : $this
->t('SendinBlue');
$template_contents = $this
->getEmailTemplate($type);
$html_content = $template_contents['html_content'];
$text_content = $template_contents['text_content'];
if ($type === "confirm" && $template_id !== '-1') {
$template = $this->sendinblueMailin
->getTemplate($template_id);
if ($template !== NULL) {
$html_content = $template
->getHtmlContent();
$subject = $template
->getSubject();
if ($template
->getFromName() !== '[DEFAULT_FROM_NAME]' && $template
->getFromEmail() !== '[DEFAULT_FROM_EMAIL]') {
$sender_name = $template
->getFromName();
$sender_email = $template
->getFromEmail();
}
}
}
$replyTo = [
'email' => $sender_email,
'name' => $sender_name,
];
$from = [
'email' => $sender_email,
'name' => $sender_name,
];
$to = [
'email' => $to_email,
];
$base_url = $this
->getBaseUrl();
$site_domain = str_replace([
'https://',
'http://',
], '', $base_url);
$html_content = str_replace([
'{title}',
'{site_domain}',
], [
$subject,
$site_domain,
], $html_content);
$text_content = str_replace('{site_domain}', $base_url, $text_content);
$this->sendinblueMailin
->sendEmail($to, $subject, $html_content, $text_content, $from, $replyTo);
}
public function getBaseUrl() {
global $base_url;
return $base_url;
}
public function getAttributeLists() {
$sibAttributes = $this->sendinblueMailin
->getAttributes();
if (!empty($sibAttributes
->getAttributes())) {
$attributes = [];
foreach ($sibAttributes
->getAttributes() as $attribute) {
if ($attribute
->getCategory() === 'normal') {
$attributes[] = $attribute;
}
}
return $attributes;
}
return [];
}
public function getTemplateList() {
return $this->sendinblueMailin
->getTemplates();
}
public function getLists() {
$lists = $this->sendinblueMailin
->getLists();
if ($lists !== NULL) {
return $lists
->getLists();
}
return [];
}
public function getListNameById($list_id) {
$list = $this->sendinblueMailin
->getList($list_id);
return $list !== NULL ? $list
->getName() : NULL;
}
public function validationEmail($email, $list_id) {
$contactInfo = $this->sendinblueMailin
->getUser($email);
if ($contactInfo === NULL) {
$ret = [
'code' => 'success',
'listid' => [],
];
return $ret;
}
$listId = $contactInfo
->getListIds();
if ($contactInfo
->isEmailBlacklisted()) {
$ret = [
'code' => 'update',
'listid' => $listId,
];
}
else {
if (!in_array($list_id, $listId)) {
$ret = [
'code' => 'success',
'listid' => $listId,
];
}
else {
$ret = [
'code' => 'already_exist',
'listid' => $listId,
];
}
}
return $ret;
}
public function subscribeUser($email, array $info = [], array $listids = []) {
$this->sendinblueMailin
->createUpdateUser($email, $info, [], $listids, NULL);
}
public function getSubscriberByEmail($email) {
$record = $this->connection
->select('sendinblue_contact', 'c')
->fields('c', [
'email',
])
->condition('c.email', $email)
->execute()
->fetchAssoc();
return $record;
}
public function addSubscriberTable(array $data = []) {
$this->connection
->insert('sendinblue_contact')
->fields([
'email' => $data['email'],
'info' => $data['info'],
'code' => $data['code'],
'is_active' => $data['is_active'],
])
->execute();
}
public function updateSmtpDetails() {
$smtpDetails = $this->sendinblueMailin
->getSmtpDetails();
$config = $this->configFactory
->getEditable(self::CONFIG_SETTINGS_SEND_EMAIL);
$drupalEmailconfig = $this->configFactory
->getEditable('system.mail');
if (isset($smtpDetails) && $smtpDetails
->isEnabled()) {
$config
->set('sendinblue_on', 1)
->save();
$config
->set(self::SMTP_DETAILS, Json::encode($smtpDetails))
->save();
$drupalEmailconfig
->set('interface.default', 'sendinblue_mail')
->save();
return $smtpDetails;
}
$config
->set('sendinblue_on', 0)
->save();
$config
->set(self::SMTP_DETAILS, NULL)
->save();
$drupalEmailconfig
->set('interface.default', 'php_mail')
->save();
return NULL;
}
}