public function setUp()
 {
     parent::setUp();
     $this->drupalPlaceBlock('local_tasks_block');
     $this->drupalPlaceBlock('local_actions_block');
     $this->drupalPlaceBlock('page_title_block');
     $this->config = $this->config('simplenews.settings');
     $site_config = $this->config('system.site');
     $site_config->set('site_mail', '*****@*****.**');
     // The default newsletter has already been created, so we need to make sure
     // that the defaut newsletter has a valid from address.
     $newsletter = Newsletter::load('default');
     $newsletter->from_address = $site_config->get('site_mail');
     $newsletter->save();
 }
 /**
  * Set the newsletters available to select from.
  *
  * Unless called otherwise, all newsletters will be available.
  *
  * @param string[] $newsletters
  *   An array of Newsletter IDs.
  */
 public function setNewsletterIds(array $newsletters)
 {
     $this->newsletters = Newsletter::loadMultiple($newsletters);
 }
 function testNewsletterIssueTranslation()
 {
     // Sign up three users, one in english and two in spanish.
     $english_mail = $this->randomEmail();
     $spanish_mail = $this->randomEmail();
     $spanish_mail2 = $this->randomEmail();
     $newsletter_id = $this->getRandomNewsletter();
     /** @var \Drupal\simplenews\Subscription\SubscriptionManagerInterface $subscription_manager */
     $subscription_manager = \Drupal::service('simplenews.subscription_manager');
     $subscription_manager->subscribe($english_mail, $newsletter_id, FALSE, 'english', 'en');
     $subscription_manager->subscribe($spanish_mail, $newsletter_id, FALSE, 'spanish', 'es');
     $subscription_manager->subscribe($spanish_mail2, $newsletter_id, FALSE, 'spanish', 'es');
     // Enable translation for newsletters.
     $edit = array('language_configuration[content_translation]' => TRUE);
     $this->drupalPostForm('admin/structure/types/manage/simplenews_issue', $edit, t('Save content type'));
     // Create a Newsletter including a translation.
     $newsletter_id = $this->getRandomNewsletter();
     $english = array('title[0][value]' => $this->randomMachineName(), 'simplenews_issue' => $newsletter_id, 'body[0][value]' => 'Link to node: [node:url]');
     $this->drupalPostForm('node/add/simplenews_issue', $english, 'Save and publish');
     $this->assertTrue(preg_match('|node/(\\d+)$|', $this->getUrl(), $matches), 'Node created');
     $node = Node::load($matches[1]);
     $this->clickLink(t('Translate'));
     $this->clickLink(t('Add'));
     $spanish = array('title[0][value]' => $this->randomMachineName(), 'body[0][value]' => 'Link to node: [node:url] ES');
     $this->drupalPostForm(NULL, $spanish, t('Save and keep published (this translation)'));
     \Drupal::entityManager()->getStorage('node')->resetCache(array($node->id()));
     $node = Node::load($node->id());
     $translation = $node->getTranslation($this->secondaryLanguage);
     // Send newsletter.
     $this->clickLink(t('Newsletter'));
     $this->drupalPostForm(NULL, array(), t('Send now'));
     $this->cronRun();
     //simplenews_cron();
     $this->assertEqual(3, count($this->drupalGetMails()));
     $newsletter = Newsletter::load($newsletter_id);
     foreach ($this->drupalGetMails() as $mail) {
         if ($mail['to'] == $english_mail) {
             $this->assertEqual('en', $mail['langcode']);
             $this->assertEqual('[' . $newsletter->label() . '] ' . $node->getTitle(), $mail['subject']);
             $node_url = $node->url('canonical', ['absolute' => TRUE]);
             $title = $node->getTitle();
         } elseif ($mail['to'] == $spanish_mail || $mail['to'] == $spanish_mail2) {
             $this->assertEqual('es', $mail['langcode']);
             // @todo: Verify newsletter translation once supported again.
             $this->assertEqual('[' . $newsletter->name . '] ' . $translation->label(), $mail['subject']);
             $node_url = $translation->url('canonical', ['absolute' => TRUE, 'language' => $translation->language()]);
             $title = $translation->getTitle();
         } else {
             $this->fail(t('Mail not sent to expected recipient'));
         }
         // Verify that the link is in the correct language.
         $this->assertTrue(strpos($mail['body'], $node_url) !== FALSE);
         $this->assertTrue(strpos($mail['body'], $title) !== FALSE);
     }
     // Verify sent subscriber count for each node.
     \Drupal::entityManager()->getStorage('node')->resetCache(array($node->id()));
     $node = Node::load($node->id());
     $translation = $node->getTranslation($this->secondaryLanguage);
     $this->assertEqual(1, $node->simplenews_issue->sent_count, 'subscriber count is correct for english');
     $this->assertEqual(2, $translation->simplenews_issue->sent_count, 'subscriber count is correct for spanish');
     // Make sure the language of a node can be changed.
     $english = array('title[0][value]' => $this->randomMachineName(), 'langcode[0][value]' => 'en', 'body[0][value]' => 'Link to node: [node:url]');
     $this->drupalPostForm('node/add/simplenews_issue', $english, 'Save and publish');
     $this->clickLink(t('Edit'));
     $edit = array('langcode[0][value]' => 'es');
     $this->drupalPostForm(NULL, $edit, t('Save and keep published'));
 }
 /**
  * Test newsletter subscription management.
  *
  * Steps performed:
  */
 function testSubscriptionManagement()
 {
     $admin_user = $this->drupalCreateUser(array('administer newsletters', 'administer simplenews settings', 'administer simplenews subscriptions', 'administer users'));
     $this->drupalLogin($admin_user);
     // Create a newsletter.
     $newsletter_name = Unicode::strtolower($this->randomMachineName());
     $edit = array('name' => $newsletter_name, 'id' => $newsletter_name);
     $this->drupalPostForm('admin/config/services/simplenews/add', $edit, t('Save'));
     // Add a number of users to each newsletter separately and then add another
     // bunch to both.
     $subscribers = array();
     $groups = array();
     $newsletters = simplenews_newsletter_get_all();
     foreach ($newsletters as $newsletter) {
         $groups[$newsletter->id()] = array($newsletter->id());
     }
     $groups['all'] = array_keys($groups);
     $subscribers_flat = array();
     foreach ($groups as $key => $group) {
         for ($i = 0; $i < 5; $i++) {
             $mail = $this->randomEmail();
             $subscribers[$key][$mail] = $mail;
             $subscribers_flat[$mail] = $mail;
         }
     }
     // Create a user and assign him one of the mail addresses of the all group.
     $user = $this->drupalCreateUser(array('subscribe to newsletters'));
     // Make sure that user_save() does not update the user object, as it will
     // override the pass_raw property which we'll need to log this user in
     // later on.
     $user_mail = current($subscribers['all']);
     $user->setEmail($user_mail);
     $user->save();
     $delimiters = array(',', ' ', "\n");
     // Visit subscribers by clicking menu tab in people.
     $this->drupalGet('admin/people');
     $this->clickLink('Subscribers');
     $i = 0;
     foreach ($groups as $key => $group) {
         $this->clickLink(t('Mass subscribe'));
         $edit = array('emails' => implode($delimiters[$i++], $subscribers[$key]));
         foreach ($group as $newsletter_id) {
             $edit['newsletters[' . $newsletter_id . ']'] = TRUE;
         }
         $this->drupalPostForm(NULL, $edit, t('Subscribe'));
     }
     // The user to which the mail was assigned should be listed too.
     $this->assertText($user->label());
     // Verify that all addresses are displayed in the table.
     $rows = $this->xpath('//tbody/tr');
     $mail_addresses = array();
     for ($i = 0; $i < count($subscribers_flat); $i++) {
         $mail_addresses[] = trim((string) $rows[$i]->td[0]);
     }
     $this->assertEqual(15, count($mail_addresses));
     foreach ($mail_addresses as $mail_address) {
         $mail_address = (string) $mail_address;
         $this->assertTrue(isset($subscribers_flat[$mail_address]));
         unset($subscribers_flat[$mail_address]);
     }
     // All entries of the array should be removed by now.
     $this->assertTrue(empty($subscribers_flat));
     reset($groups);
     $first = 'default';
     $first_mail = array_rand($subscribers[$first]);
     $all_mail = array_rand($subscribers['all']);
     // Limit list to subscribers of the first newsletter only.
     // Build a flat list of the subscribers of this list.
     $subscribers_flat = array_merge($subscribers[$first], $subscribers['all']);
     $this->drupalGet('admin/people/simplenews', array('query' => array('subscriptions_target_id' => $first)));
     // Verify that all addresses are displayed in the table.
     $rows = $this->xpath('//tbody/tr');
     $mail_addresses = array();
     for ($i = 0; $i < count($subscribers_flat); $i++) {
         $mail_addresses[] = trim((string) $rows[$i]->td[0]);
     }
     $this->assertEqual(10, count($mail_addresses));
     foreach ($mail_addresses as $mail_address) {
         $mail_address = (string) $mail_address;
         $this->assertTrue(isset($subscribers_flat[$mail_address]));
         unset($subscribers_flat[$mail_address]);
     }
     // All entries of the array should be removed by now.
     $this->assertTrue(empty($subscribers_flat));
     // Filter a single mail address, the one assigned to a user.
     $edit = array('mail' => Unicode::substr(current($subscribers['all']), 0, 4));
     $this->drupalGet('admin/people/simplenews', array('query' => array('mail' => $edit['mail'])));
     $rows = $this->xpath('//tbody/tr');
     $this->assertEqual(1, count($rows));
     $this->assertEqual(current($subscribers['all']), trim((string) $rows[0]->td[0]));
     $this->assertEqual($user->label(), trim((string) $rows[0]->td[1]->span));
     // Reset the filter.
     $this->drupalGet('admin/people/simplenews');
     // Test mass-unsubscribe, unsubscribe one from the first group and one from
     // the all group, but only from the first newsletter.
     unset($subscribers[$first][$first_mail]);
     $edit = array('emails' => $first_mail . ', ' . $all_mail, 'newsletters[' . $first . ']' => TRUE);
     $this->clickLink(t('Mass unsubscribe'));
     $this->drupalPostForm(NULL, $edit, t('Unsubscribe'));
     // The all mail is still displayed because it's still subscribed to the
     // second newsletter. Reload the page to get rid of the confirmation
     // message.
     $this->drupalGet('admin/people/simplenews');
     $this->assertNoText($first_mail);
     $this->assertText($all_mail);
     // Limit to first newsletter, the all mail shouldn't be shown anymore.
     $this->drupalGet('admin/people/simplenews', array('query' => array('subscriptions_target_id' => $first)));
     $this->assertNoText($first_mail);
     $this->assertNoText($all_mail);
     // Check exporting.
     $this->clickLink(t('Export'));
     $this->drupalPostForm(NULL, array('newsletters[' . $first . ']' => TRUE), t('Export'));
     $export_field = $this->xpath($this->constructFieldXpath('name', 'emails'));
     $exported_mails = (string) $export_field[0];
     foreach ($subscribers[$first] as $mail) {
         $this->assertTrue(strpos($exported_mails, $mail) !== FALSE, t('Mail address exported correctly.'));
     }
     foreach ($subscribers['all'] as $mail) {
         if ($mail != $all_mail) {
             $this->assertTrue(strpos($exported_mails, $mail) !== FALSE, t('Mail address exported correctly.'));
         } else {
             $this->assertFALSE(strpos($exported_mails, $mail) !== FALSE, t('Unsubscribed mail address not exported.'));
         }
     }
     // Only export unsubscribed mail addresses.
     $edit = array('subscribed[subscribed]' => FALSE, 'subscribed[unsubscribed]' => TRUE, 'newsletters[' . $first . ']' => TRUE);
     $this->drupalPostForm(NULL, $edit, t('Export'));
     $export_field = $this->xpath($this->constructFieldXpath('name', 'emails'));
     $exported_mails = (string) $export_field[0];
     $exported_mails = explode(', ', $exported_mails);
     $this->assertEqual(2, count($exported_mails));
     $this->assertTrue(in_array($all_mail, $exported_mails));
     $this->assertTrue(in_array($first_mail, $exported_mails));
     /** @var \Drupal\simplenews\Subscription\SubscriptionManagerInterface $subscription_manager */
     $subscription_manager = \Drupal::service('simplenews.subscription_manager');
     // Make sure there are unconfirmed subscriptions.
     $unconfirmed = array();
     $unconfirmed[] = $this->randomEmail();
     $unconfirmed[] = $this->randomEmail();
     foreach ($unconfirmed as $mail) {
         $subscription_manager->subscribe($mail, $first, TRUE);
     }
     // Only export unconfirmed mail addresses.
     $edit = array('subscribed[subscribed]' => FALSE, 'subscribed[unconfirmed]' => TRUE, 'subscribed[unsubscribed]' => FALSE, 'newsletters[' . $first . ']' => TRUE);
     $this->drupalPostForm(NULL, $edit, t('Export'));
     $export_field = $this->xpath($this->constructFieldXpath('name', 'emails'));
     $exported_mails = (string) $export_field[0];
     $exported_mails = explode(', ', $exported_mails);
     $this->assertEqual(2, count($exported_mails));
     $this->assertTrue(in_array($unconfirmed[0], $exported_mails));
     $this->assertTrue(in_array($unconfirmed[1], $exported_mails));
     // Make sure the user is subscribed to the first newsletter_id.
     $subscription_manager->subscribe($user_mail, $first, FALSE);
     $before_count = simplenews_count_subscriptions($first);
     // Block the user.
     $user->block();
     $user->save();
     $this->drupalGet('admin/people/simplenews');
     // Verify updated subscriptions count.
     drupal_static_reset('simplenews_count_subscriptions');
     $after_count = simplenews_count_subscriptions($first);
     $this->assertEqual($before_count - 1, $after_count, t('Blocked users are not counted in subscription count.'));
     // Test mass subscribe with previously unsubscribed users.
     for ($i = 0; $i < 3; $i++) {
         $tested_subscribers[] = $this->randomEmail();
     }
     $subscription_manager->subscribe($tested_subscribers[0], $first, FALSE);
     $subscription_manager->subscribe($tested_subscribers[1], $first, FALSE);
     $subscription_manager->unsubscribe($tested_subscribers[0], $first, FALSE);
     $subscription_manager->unsubscribe($tested_subscribers[1], $first, FALSE);
     $unsubscribed = implode(', ', array_slice($tested_subscribers, 0, 2));
     $edit = array('emails' => implode(', ', $tested_subscribers), 'newsletters[' . $first . ']' => TRUE);
     $this->drupalPostForm('admin/people/simplenews/import', $edit, t('Subscribe'));
     \Drupal::entityManager()->getStorage('simplenews_subscriber')->resetCache();
     $subscription_manager->reset();
     $this->assertFalse($subscription_manager->isSubscribed($tested_subscribers[0], $first), t('Subscriber not resubscribed through mass subscription.'));
     $this->assertFalse($subscription_manager->isSubscribed($tested_subscribers[1], $first), t('Subscriber not resubscribed through mass subscription.'));
     $this->assertTrue($subscription_manager->isSubscribed($tested_subscribers[2], $first), t('Subscriber subscribed through mass subscription.'));
     $substitutes = array('@name' => SafeMarkup::checkPlain(simplenews_newsletter_load($first)->label()), '@mail' => $unsubscribed);
     $this->assertText(t('The following addresses were skipped because they have previously unsubscribed from @name: @mail.', $substitutes));
     $this->assertText(t("If you would like to resubscribe them, use the 'Force resubscription' option."));
     // Try to mass subscribe without specifying newsletters.
     $tested_subscribers[2] = $this->randomEmail();
     $edit = array('emails' => implode(', ', $tested_subscribers), 'resubscribe' => TRUE);
     $this->drupalPostForm('admin/people/simplenews/import', $edit, t('Subscribe'));
     $this->assertText('Subscribe to field is required.');
     // Test mass subscribe with previously unsubscribed users and force
     // resubscription.
     $tested_subscribers[2] = $this->randomEmail();
     $edit = array('emails' => implode(', ', $tested_subscribers), 'newsletters[' . $first . ']' => TRUE, 'resubscribe' => TRUE);
     $this->drupalPostForm('admin/people/simplenews/import', $edit, t('Subscribe'));
     $subscription_manager->reset();
     \Drupal::entityManager()->getStorage('simplenews_subscriber')->resetCache();
     $this->assertTrue($subscription_manager->isSubscribed($tested_subscribers[0], $first, t('Subscriber resubscribed trough mass subscription.')));
     $this->assertTrue($subscription_manager->isSubscribed($tested_subscribers[1], $first, t('Subscriber resubscribed trough mass subscription.')));
     $this->assertTrue($subscription_manager->isSubscribed($tested_subscribers[2], $first, t('Subscriber subscribed trough mass subscription.')));
     // Try to mass unsubscribe without specifying newsletters.
     $tested_subscribers[2] = $this->randomEmail();
     $edit = array('emails' => implode(', ', $tested_subscribers));
     $this->drupalPostForm('admin/people/simplenews/unsubscribe', $edit, t('Unsubscribe'));
     $this->assertText('Unsubscribe from field is required.');
     // Create two blocks, to ensure that they are updated/deleted when a
     // newsletter is deleted.
     $only_first_block = $this->setupSubscriptionBlock(['newsletters' => [$first]]);
     $all_block = $this->setupSubscriptionBlock(['newsletters' => array_keys($groups)]);
     $enabled_newsletters = $all_block->get('settings')['newsletters'];
     $this->assertTrue(in_array($first, $enabled_newsletters));
     // Delete newsletter.
     \Drupal::entityManager()->getStorage('simplenews_newsletter')->resetCache();
     $this->drupalGet('admin/config/services/simplenews/manage/' . $first);
     $this->clickLink(t('Delete'));
     $this->drupalPostForm(NULL, array(), t('Delete'));
     $this->assertText(t('All subscriptions to newsletter @newsletter have been deleted.', array('@newsletter' => $newsletters[$first]->name)));
     // Verify that all related data has been deleted/updated.
     $this->assertNull(Newsletter::load($first));
     $this->assertNull(Block::load($only_first_block->id()));
     $all_block = Block::load($all_block->id());
     $enabled_newsletters = $all_block->get('settings')['newsletters'];
     $this->assertFalse(in_array($first, $enabled_newsletters));
     // Verify that all subscriptions of that newsletter have been removed.
     $this->drupalGet('admin/people/simplenews');
     foreach ($subscribers[$first] as $mail) {
         $this->assertNoText($mail);
     }
     $this->clickLink(t('Edit'), 1);
     // Get the subscriber id from the path.
     $this->assertTrue(preg_match('|admin/people/simplenews/edit/(\\d+)\\?destination|', $this->getUrl(), $matches), 'Subscriber found');
     $subscriber = Subscriber::load($matches[1]);
     $this->assertTitle(t('Edit subscriber @mail', array('@mail' => $subscriber->getMail())) . ' | Drupal');
     $this->assertFieldChecked('edit-status');
     // Disable account.
     $edit = array('status' => FALSE);
     $this->drupalPostForm(NULL, $edit, t('Save'));
     \Drupal::entityManager()->getStorage('simplenews_subscriber')->resetCache();
     $subscription_manager->reset();
     $this->assertFalse($subscription_manager->isSubscribed($subscriber->getMail(), $this->getRandomNewsletter()), t('Subscriber is not active'));
     // Re-enable account.
     $this->drupalGet('admin/people/simplenews/edit/' . $subscriber->id());
     $this->assertTitle(t('Edit subscriber @mail', array('@mail' => $subscriber->getMail())) . ' | Drupal');
     $this->assertNoFieldChecked('edit-status');
     $edit = array('status' => TRUE);
     $this->drupalPostForm(NULL, $edit, t('Save'));
     \Drupal::entityManager()->getStorage('simplenews_subscriber')->resetCache();
     $subscription_manager->reset();
     $this->assertTrue($subscription_manager->isSubscribed($subscriber->getMail(), $this->getRandomNewsletter()), t('Subscriber is active again.'));
     // Remove the newsletter.
     $this->drupalGet('admin/people/simplenews/edit/' . $subscriber->id());
     $this->assertTitle(t('Edit subscriber @mail', array('@mail' => $subscriber->getMail())) . ' | Drupal');
     \Drupal::entityManager()->getStorage('simplenews_subscriber')->resetCache();
     $subscriber = Subscriber::load($subscriber->id());
     $nlids = $subscriber->getSubscribedNewsletterIds();
     // If the subscriber still has subscribed to newsletter, try to unsubscribe.
     $newsletter_id = reset($nlids);
     $edit['subscriptions[' . $newsletter_id . ']'] = FALSE;
     $this->drupalPostForm(NULL, $edit, t('Save'));
     \Drupal::entityManager()->getStorage('simplenews_subscriber')->resetCache();
     $subscription_manager->reset();
     $nlids = $subscriber->getSubscribedNewsletterIds();
     $this->assertFalse($subscription_manager->isSubscribed($subscriber->getMail(), reset($nlids)), t('Subscriber not subscribed anymore.'));
     // @todo Test Admin subscriber edit preferred language $subscription->language
     // Register a subscriber with an insecure e-mail address through the API
     // and make sure the address is correctly encoded.
     $xss_mail = "<script>alert('XSS');</script>";
     $subscription_manager->subscribe($xss_mail, $this->getRandomNewsletter(), FALSE);
     $this->drupalGet('admin/people/simplenews');
     $this->assertNoRaw($xss_mail);
     $this->assertRaw(SafeMarkup::checkPlain($xss_mail));
     $xss_subscriber = simplenews_subscriber_load_by_mail($xss_mail);
     $this->drupalGet('admin/people/simplenews/edit/' . $xss_subscriber->id());
     $this->assertNoRaw($xss_mail);
     $this->assertRaw(SafeMarkup::checkPlain($xss_mail));
     // Create a new user for the next test.
     $new_user = $this->drupalCreateUser(array('subscribe to newsletters'));
     // Test for saving the subscription for no newsletter.
     $this->drupalPostForm('user/' . $new_user->id() . '/simplenews', null, t('Save'));
     $this->assertText('The newsletter subscriptions for user ' . $new_user->getUsername() . ' have been updated.');
     // Editing a subscriber with subscription.
     $edit = array('subscriptions[' . $newsletter_name . ']' => TRUE, 'status' => TRUE, 'mail[0][value]' => '*****@*****.**');
     $this->drupalPostForm('admin/people/simplenews/edit/' . $xss_subscriber->id(), $edit, t('Save'));
     $this->assertText('Subscriber edit@example.com has been updated.');
     // Create a second newsletter.
     $second_newsletter_name = Unicode::strtolower($this->randomMachineName());
     $edit2 = array('name' => $second_newsletter_name, 'id' => $second_newsletter_name);
     $this->drupalPostForm('admin/config/services/simplenews/add', $edit2, t('Save'));
     // Test for adding a subscriber.
     $subscribe = array('newsletters[' . $newsletter_name . ']' => TRUE, 'emails' => '*****@*****.**');
     $this->drupalPostForm('admin/people/simplenews/import', $subscribe, t('Subscribe'));
     // The subscriber should appear once in the list.
     $rows = $this->xpath('//tbody/tr');
     $counter = 0;
     foreach ($rows as $value) {
         if (trim((string) $value->td[0]) == '*****@*****.**') {
             $counter++;
         }
     }
     $this->assertEqual(1, $counter);
     $this->assertText(t('The following addresses were added or updated: @email.', ['@email' => '*****@*****.**']));
     $this->assertText(t('The addresses were subscribed to the following newsletters: @newsletter.', ['@newsletter' => $newsletter_name]));
     // Check exact subscription statuses.
     $subscriber = simplenews_subscriber_load_by_mail('*****@*****.**');
     $this->assertEqual($subscriber->getSubscription($newsletter_name)->get('status')->getValue(), SIMPLENEWS_SUBSCRIPTION_STATUS_SUBSCRIBED);
     // The second newsletter was not subscribed, so there should be no
     // subscription record at all.
     $this->assertFalse($subscriber->getSubscription($second_newsletter_name));
 }