Loading modules/mailchimp_marketing_subscribe_ct/src/Form/NodeTabForm.php +113 −49 Original line number Diff line number Diff line Loading @@ -2,6 +2,7 @@ namespace Drupal\mailchimp_marketing_subscribe_ct\Form; use Drupal\Component\Utility\EmailValidatorInterface; use Drupal\Core\Access\AccessResult; use Drupal\Core\Config\Config; use Drupal\Core\Config\ConfigFactoryInterface; Loading Loading @@ -48,6 +49,13 @@ class NodeTabForm extends FormBase { */ protected $logger; /** * The email validator service. * * @var \Drupal\Component\Utility\EmailValidatorInterface */ protected $emailValidator; /** * The mailchimp service. * Loading @@ -66,14 +74,17 @@ class NodeTabForm extends FormBase { * The messenger. * @param \Drupal\Core\Logger\LoggerChannelFactoryInterface $logger * The logger service. * @param \Drupal\Component\Utility\EmailValidatorInterface $email_validator * The email validator service. * @param \Drupal\mailchimp_marketing\MailchimpInterface $mailchimp * The mailchimp service. */ public function __construct(AccountInterface $current_user, ConfigFactoryInterface $config_factory, MessengerInterface $messenger, LoggerChannelFactoryInterface $logger, MailchimpInterface $mailchimp) { public function __construct(AccountInterface $current_user, ConfigFactoryInterface $config_factory, MessengerInterface $messenger, LoggerChannelFactoryInterface $logger, EmailValidatorInterface $email_validator, MailchimpInterface $mailchimp) { $this->currentUser = $current_user; $this->configMailchimpCt = $config_factory->get('mailchimp_marketing_subscribe_ct.settings'); $this->messenger = $messenger; $this->logger = $logger->get('mailchimp_marketing_subscribe_ct'); $this->emailValidator = $email_validator; $this->mailchimp = $mailchimp; } Loading @@ -86,6 +97,7 @@ class NodeTabForm extends FormBase { $container->get('config.factory'), $container->get('messenger'), $container->get('logger.factory'), $container->get('email.validator'), $container->get('mailchimp_marketing.mailchimp') ); } Loading @@ -102,7 +114,9 @@ class NodeTabForm extends FormBase { */ public function buildForm(array $form, FormStateInterface $form_state, NodeInterface $node = NULL) { //$config = $this->config('simplenews.settings'); $form['#title'] = $this->t('<em>Mailchimp campaign</em> @title', ['@title' => $node->getTitle()]); $form['#title'] = $this->t('<em>Mailchimp campaign</em> @title', [ '@title' => $node->getTitle(), ]); // We will need the node. $form_state->set('node', $node); Loading @@ -116,21 +130,30 @@ class NodeTabForm extends FormBase { '#title' => $this->t('Test'), ]; /*$form['test']['test_address'] = [ $form['test']['test_address'] = [ '#type' => 'textfield', '#title' => $this->t('Test email addresses'), '#description' => $this->t('A comma-separated list of email addresses to be used as test addresses.'), '#default_value' => $this->currentUser->getEmail(), '#size' => 60, '#maxlength' => 128, ];*/ ]; $form['test']['text'] = [ '#markup' => print_r($node->get('mailchimp_campaign')->getValue(), TRUE), '#prefix' => '<pre>', '#suffix' => '</pre>', ]; $mailchimpCampaign = $node->get('mailchimp_campaign')->getValue(); $existingCampaign = !empty($mailchimpCampaign); $form['test']['submit'] = [ '#type' => 'submit', '#value' => $this->t('Create test campaign'), '#value' => $existingCampaign ? $this->t('Update campaign and send test email') : $this->t('Create campaign and send test email'), '#name' => 'send_test', '#submit' => ['::submitTestCampaign'], //'#validate' => ['::validateTestAddress'], '#validate' => ['::validateTestAddress'], ]; $form['send'] = [ Loading Loading @@ -170,10 +193,10 @@ class NodeTabForm extends FormBase { * Form state. */ public function validateTestAddress(array $form, FormStateInterface $form_state) { $test_address = $form_state->getValue('test_address'); $test_address = trim($test_address); $test_address = trim($form_state->getValue('test_address')); if (!empty($test_address)) { $mails = explode(',', $test_address); foreach ($mails as $mail) { $mail = trim($mail); if (!$this->emailValidator->isValid($mail)) { Loading @@ -197,48 +220,65 @@ class NodeTabForm extends FormBase { */ public function submitTestCampaign(array &$form, FormStateInterface $form_state) { $mailchimp = $this->mailchimp->getConnection(); $request = NULL; $response = NULL; $campaignId = NULL; $campaign = NULL; $node = $form_state->get('node'); $mailchimpCampaign = $node->get('mailchimp_campaign')->getValue(); $existingCampaign = isset($mailchimpCampaign[0]) && count($mailchimpCampaign[0]); try { if ($existingCampaign) { $campaignId = $mailchimpCampaign[0]['value']; $response = $mailchimp->campaigns->get($campaignId); } } catch (\Exception $error) { $campaign = NULL; $campaignId = NULL; $node ->set('mailchimp_campaign', NULL) ->save(); } try { /*$response = $mailchimp->campaigns->list(NULL, NULL, 30); dump($response); $response = $mailchimp->campaigns->get("9006ff900f"); dump($response); die();*/ // Create campaign. $node = $form_state->get('node'); if (!$campaignId) { $request = $this->buildCampaignRequest([], $node); $response = $mailchimp->campaigns->create($request); $campaignId = $response->id; $node ->set('mailchimp_campaign', $campaignId) ->save(); } $value = <<< BODY <table cellpadding="0" cellspacing="0" border="0" width="100%"> <tbody><tr> <td bgcolor="#FAFAFA" style="padding:10px;border:1px solid #CCCCCC;"> <table cellpadding="0" cellspacing="0" border="0" width="100%" style="color:#333333;"><tbody><tr><td> <img alt="Australian Competition and Consumer Commission" src="https://www.accc.gov.au/sites/www.accc.gov.au/themes/accc_accc_responsive/images/top-logo.png" data-inlineimagemanipulating="true" style="width: 400px; max-width: 800px;"> </td><td align="right">[current-date:custom:'j F Y']</td></tr></tbody></table> </td> </tr> <tr> <td style="padding:10px; border-left:1px solid #CCCCCC; border-right:1px solid #CCCCCC;"> <h2>[node:title]</h2> <div>[node:body]</div> <a href="[node:url]" target="_blank" rel="noreferrer noopener">Read more</a> <!-- <p class="ydp790b47cyiv6349091600newsletter-footer"><a href="https://www.accc.gov.au/newsletter/confirm/remove/191886f9be65128t325" target="_blank" rel="noreferrer noopener">Unsubscribe from this newsletter</a></p>--> </td> </tr> <tr> <td bgcolor="#E1E1E1" style="padding:10px; border:1px solid #CCCCCC;"> <a href="https://www.accc.gov.au/" style="color:#464545;" target="_blank" rel="noreferrer noopener">www.accc.gov.au</a> | <a href="https://www.accc.gov.au/about-us/using-our-website/privacy-policy" style="color:#464545;" target="_blank" rel="noreferrer noopener">Privacy</a> </td> </tr> </tbody> </table> BODY; $body = \Drupal::token()->replace($value, [$node->getEntityType()->id() => $node], ['clear' => TRUE]); $value = $this->configMailchimpCt->get('mailchimp_ct_campaign_template_body'); $body = \Drupal::token()->replace($value, [ $node->getEntityType()->id() => $node, ], ['clear' => TRUE]); $mailchimp->campaigns->setContent($campaignId, [ //'html' => str_replace('[CONTENT]', $campaign['html'], $campaignTemplate), 'html' => $body, ]); $response = $mailchimp->campaigns->sendTestEmail($campaignId, [ "test_emails" => explode(',', $form_state->get('test_address')), "send_type" => "html", ]); dump([$campaignId, $response]); // Schedule campaign. /*if ($this->configAccc->get('campaign_schedule')) { $scheduleTime = $this->configAccc->get('campaign_schedule_time'); Loading @@ -265,13 +305,15 @@ BODY; } catch (\Exception $error) { $campaignError = TRUE; $message = $this->t('Create campaign: Failed to create campaign.'); $this->logger->error($this->t('Error message: @message<br />Details: @details<br /> Campaign details: <br /><pre>@campaign</pre><br /> Request details: <br /><pre>@request</pre>', [ '@message' => $message, $message = $this->t('Error message: @message<br />Details: @details<br /> Campaign details: <br /><pre>@campaign</pre><br /> Request details: <br /><pre>@request</pre>', [ '@message' => $this->t('Create campaign: Failed to create campaign.'), '@details' => $error->getMessage(), //'@campaign' => print_r($campaign, TRUE), '@campaign' => print_r($campaignId, TRUE), '@request' => print_r($request, TRUE), ])); ]); $this->logger->error($message); $this->messenger->addError($message); } } Loading @@ -294,7 +336,9 @@ BODY; * Request structure. */ private function buildCampaignRequest(array $tagIds, $node) { $segments = []; /*// Tag segments. foreach ($tagIds as $tagId) { if (isset($tagId)) { $segments[] = [ Loading @@ -304,7 +348,26 @@ BODY; "value" => $tagId, ]; } } }*/ $segments[] = [ "condition_type" => "Interests", "field" => "interests-bc80e41ec0", "op" => "interestnotcontains", "value" => [ "e99f2336c0", "ed2d0ca7e5", ], ]; $segments[] = [ "condition_type" => "Interests", "field" => "interests-f77cc142b8", "op" => "interestcontains", "value" => [ "2a07b1a77b", ], ]; /*$interestsSubject = ''; if (count($interests) > 0) { Loading Loading @@ -341,7 +404,8 @@ BODY; if (count($segments) > 0) { $request['recipients']['segment_opts'] = [ "match" => "any", "match" => "all", //"match" => "any", "conditions" => $segments, ]; } Loading Loading
modules/mailchimp_marketing_subscribe_ct/src/Form/NodeTabForm.php +113 −49 Original line number Diff line number Diff line Loading @@ -2,6 +2,7 @@ namespace Drupal\mailchimp_marketing_subscribe_ct\Form; use Drupal\Component\Utility\EmailValidatorInterface; use Drupal\Core\Access\AccessResult; use Drupal\Core\Config\Config; use Drupal\Core\Config\ConfigFactoryInterface; Loading Loading @@ -48,6 +49,13 @@ class NodeTabForm extends FormBase { */ protected $logger; /** * The email validator service. * * @var \Drupal\Component\Utility\EmailValidatorInterface */ protected $emailValidator; /** * The mailchimp service. * Loading @@ -66,14 +74,17 @@ class NodeTabForm extends FormBase { * The messenger. * @param \Drupal\Core\Logger\LoggerChannelFactoryInterface $logger * The logger service. * @param \Drupal\Component\Utility\EmailValidatorInterface $email_validator * The email validator service. * @param \Drupal\mailchimp_marketing\MailchimpInterface $mailchimp * The mailchimp service. */ public function __construct(AccountInterface $current_user, ConfigFactoryInterface $config_factory, MessengerInterface $messenger, LoggerChannelFactoryInterface $logger, MailchimpInterface $mailchimp) { public function __construct(AccountInterface $current_user, ConfigFactoryInterface $config_factory, MessengerInterface $messenger, LoggerChannelFactoryInterface $logger, EmailValidatorInterface $email_validator, MailchimpInterface $mailchimp) { $this->currentUser = $current_user; $this->configMailchimpCt = $config_factory->get('mailchimp_marketing_subscribe_ct.settings'); $this->messenger = $messenger; $this->logger = $logger->get('mailchimp_marketing_subscribe_ct'); $this->emailValidator = $email_validator; $this->mailchimp = $mailchimp; } Loading @@ -86,6 +97,7 @@ class NodeTabForm extends FormBase { $container->get('config.factory'), $container->get('messenger'), $container->get('logger.factory'), $container->get('email.validator'), $container->get('mailchimp_marketing.mailchimp') ); } Loading @@ -102,7 +114,9 @@ class NodeTabForm extends FormBase { */ public function buildForm(array $form, FormStateInterface $form_state, NodeInterface $node = NULL) { //$config = $this->config('simplenews.settings'); $form['#title'] = $this->t('<em>Mailchimp campaign</em> @title', ['@title' => $node->getTitle()]); $form['#title'] = $this->t('<em>Mailchimp campaign</em> @title', [ '@title' => $node->getTitle(), ]); // We will need the node. $form_state->set('node', $node); Loading @@ -116,21 +130,30 @@ class NodeTabForm extends FormBase { '#title' => $this->t('Test'), ]; /*$form['test']['test_address'] = [ $form['test']['test_address'] = [ '#type' => 'textfield', '#title' => $this->t('Test email addresses'), '#description' => $this->t('A comma-separated list of email addresses to be used as test addresses.'), '#default_value' => $this->currentUser->getEmail(), '#size' => 60, '#maxlength' => 128, ];*/ ]; $form['test']['text'] = [ '#markup' => print_r($node->get('mailchimp_campaign')->getValue(), TRUE), '#prefix' => '<pre>', '#suffix' => '</pre>', ]; $mailchimpCampaign = $node->get('mailchimp_campaign')->getValue(); $existingCampaign = !empty($mailchimpCampaign); $form['test']['submit'] = [ '#type' => 'submit', '#value' => $this->t('Create test campaign'), '#value' => $existingCampaign ? $this->t('Update campaign and send test email') : $this->t('Create campaign and send test email'), '#name' => 'send_test', '#submit' => ['::submitTestCampaign'], //'#validate' => ['::validateTestAddress'], '#validate' => ['::validateTestAddress'], ]; $form['send'] = [ Loading Loading @@ -170,10 +193,10 @@ class NodeTabForm extends FormBase { * Form state. */ public function validateTestAddress(array $form, FormStateInterface $form_state) { $test_address = $form_state->getValue('test_address'); $test_address = trim($test_address); $test_address = trim($form_state->getValue('test_address')); if (!empty($test_address)) { $mails = explode(',', $test_address); foreach ($mails as $mail) { $mail = trim($mail); if (!$this->emailValidator->isValid($mail)) { Loading @@ -197,48 +220,65 @@ class NodeTabForm extends FormBase { */ public function submitTestCampaign(array &$form, FormStateInterface $form_state) { $mailchimp = $this->mailchimp->getConnection(); $request = NULL; $response = NULL; $campaignId = NULL; $campaign = NULL; $node = $form_state->get('node'); $mailchimpCampaign = $node->get('mailchimp_campaign')->getValue(); $existingCampaign = isset($mailchimpCampaign[0]) && count($mailchimpCampaign[0]); try { if ($existingCampaign) { $campaignId = $mailchimpCampaign[0]['value']; $response = $mailchimp->campaigns->get($campaignId); } } catch (\Exception $error) { $campaign = NULL; $campaignId = NULL; $node ->set('mailchimp_campaign', NULL) ->save(); } try { /*$response = $mailchimp->campaigns->list(NULL, NULL, 30); dump($response); $response = $mailchimp->campaigns->get("9006ff900f"); dump($response); die();*/ // Create campaign. $node = $form_state->get('node'); if (!$campaignId) { $request = $this->buildCampaignRequest([], $node); $response = $mailchimp->campaigns->create($request); $campaignId = $response->id; $node ->set('mailchimp_campaign', $campaignId) ->save(); } $value = <<< BODY <table cellpadding="0" cellspacing="0" border="0" width="100%"> <tbody><tr> <td bgcolor="#FAFAFA" style="padding:10px;border:1px solid #CCCCCC;"> <table cellpadding="0" cellspacing="0" border="0" width="100%" style="color:#333333;"><tbody><tr><td> <img alt="Australian Competition and Consumer Commission" src="https://www.accc.gov.au/sites/www.accc.gov.au/themes/accc_accc_responsive/images/top-logo.png" data-inlineimagemanipulating="true" style="width: 400px; max-width: 800px;"> </td><td align="right">[current-date:custom:'j F Y']</td></tr></tbody></table> </td> </tr> <tr> <td style="padding:10px; border-left:1px solid #CCCCCC; border-right:1px solid #CCCCCC;"> <h2>[node:title]</h2> <div>[node:body]</div> <a href="[node:url]" target="_blank" rel="noreferrer noopener">Read more</a> <!-- <p class="ydp790b47cyiv6349091600newsletter-footer"><a href="https://www.accc.gov.au/newsletter/confirm/remove/191886f9be65128t325" target="_blank" rel="noreferrer noopener">Unsubscribe from this newsletter</a></p>--> </td> </tr> <tr> <td bgcolor="#E1E1E1" style="padding:10px; border:1px solid #CCCCCC;"> <a href="https://www.accc.gov.au/" style="color:#464545;" target="_blank" rel="noreferrer noopener">www.accc.gov.au</a> | <a href="https://www.accc.gov.au/about-us/using-our-website/privacy-policy" style="color:#464545;" target="_blank" rel="noreferrer noopener">Privacy</a> </td> </tr> </tbody> </table> BODY; $body = \Drupal::token()->replace($value, [$node->getEntityType()->id() => $node], ['clear' => TRUE]); $value = $this->configMailchimpCt->get('mailchimp_ct_campaign_template_body'); $body = \Drupal::token()->replace($value, [ $node->getEntityType()->id() => $node, ], ['clear' => TRUE]); $mailchimp->campaigns->setContent($campaignId, [ //'html' => str_replace('[CONTENT]', $campaign['html'], $campaignTemplate), 'html' => $body, ]); $response = $mailchimp->campaigns->sendTestEmail($campaignId, [ "test_emails" => explode(',', $form_state->get('test_address')), "send_type" => "html", ]); dump([$campaignId, $response]); // Schedule campaign. /*if ($this->configAccc->get('campaign_schedule')) { $scheduleTime = $this->configAccc->get('campaign_schedule_time'); Loading @@ -265,13 +305,15 @@ BODY; } catch (\Exception $error) { $campaignError = TRUE; $message = $this->t('Create campaign: Failed to create campaign.'); $this->logger->error($this->t('Error message: @message<br />Details: @details<br /> Campaign details: <br /><pre>@campaign</pre><br /> Request details: <br /><pre>@request</pre>', [ '@message' => $message, $message = $this->t('Error message: @message<br />Details: @details<br /> Campaign details: <br /><pre>@campaign</pre><br /> Request details: <br /><pre>@request</pre>', [ '@message' => $this->t('Create campaign: Failed to create campaign.'), '@details' => $error->getMessage(), //'@campaign' => print_r($campaign, TRUE), '@campaign' => print_r($campaignId, TRUE), '@request' => print_r($request, TRUE), ])); ]); $this->logger->error($message); $this->messenger->addError($message); } } Loading @@ -294,7 +336,9 @@ BODY; * Request structure. */ private function buildCampaignRequest(array $tagIds, $node) { $segments = []; /*// Tag segments. foreach ($tagIds as $tagId) { if (isset($tagId)) { $segments[] = [ Loading @@ -304,7 +348,26 @@ BODY; "value" => $tagId, ]; } } }*/ $segments[] = [ "condition_type" => "Interests", "field" => "interests-bc80e41ec0", "op" => "interestnotcontains", "value" => [ "e99f2336c0", "ed2d0ca7e5", ], ]; $segments[] = [ "condition_type" => "Interests", "field" => "interests-f77cc142b8", "op" => "interestcontains", "value" => [ "2a07b1a77b", ], ]; /*$interestsSubject = ''; if (count($interests) > 0) { Loading Loading @@ -341,7 +404,8 @@ BODY; if (count($segments) > 0) { $request['recipients']['segment_opts'] = [ "match" => "any", "match" => "all", //"match" => "any", "conditions" => $segments, ]; } Loading