You are here

public function SubscriptionManager::unsubscribe in Simplenews 8

Same name and namespace in other branches
  1. 8.2 src/Subscription/SubscriptionManager.php \Drupal\simplenews\Subscription\SubscriptionManager::unsubscribe()
  2. 3.x src/Subscription/SubscriptionManager.php \Drupal\simplenews\Subscription\SubscriptionManager::unsubscribe()

Unsubscribe a user from a mailing list or send a confirmation mail.

The $confirm parameter determines the action: FALSE = The user is unsubscribed TRUE = User receives an email to verify the address and complete the subscription cancellation.

Parameters

string $mail: The email address to unsubscribe from the mailing list.

string $newsletter_id: The newsletter ID.

bool|null $confirm: If TRUE, send a confirmation mail; if FALSE, unsubscribe immediately. NULL means the default from the chosen newsletter is used.

string $source: Indicates the unsubscribe source. Simplenews uses these sources:

  • website: Via any website form (with or without confirmation email).
  • mass subscribe: Mass admin UI.
  • mass unsubscribe: Mass admin UI.
  • action: Drupal actions.

Return value

$this

Overrides SubscriptionManagerInterface::unsubscribe

File

src/Subscription/SubscriptionManager.php, line 166

Class

SubscriptionManager
Default subscription manager.

Namespace

Drupal\simplenews\Subscription

Code

public function unsubscribe($mail, $newsletter_id, $confirm = NULL, $source = 'unknown') {
  $subscriber = simplenews_subscriber_load_by_mail($mail);
  if (!$subscriber) {
    throw new \Exception('The subscriber does not exist.');
  }

  // The unlikely case that a user is unsubscribed from a non existing mailing list is logged
  if (!($newsletter = simplenews_newsletter_load($newsletter_id))) {
    $this->logger
      ->error('Attempt to unsubscribe from non existing mailing list ID %id', array(
      '%id' => $newsletter_id,
    ));
    return $this;
  }

  // If confirmation is not explicitly specified, use the newsletter
  // configuration.
  if ($confirm === NULL) {
    $confirm = $this
      ->requiresConfirmation($newsletter, $subscriber
      ->getUserId());
  }
  if ($confirm) {

    // Make sure the mail address is set.
    if (empty($subscriber)) {
      $subscriber = Subscriber::create(array());
      $subscriber
        ->setMail($mail);
      $subscriber
        ->save();
    }
    $this
      ->addConfirmation('unsubscribe', $subscriber, $newsletter);
  }
  elseif ($subscriber && $subscriber
    ->isSubscribed($newsletter_id)) {

    // Unsubscribe the user from the mailing list.
    $subscriber
      ->unsubscribe($newsletter_id, $source);
    $subscriber
      ->save();
  }
  return $this;
}