Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
Subscriber.php
Go to the documentation of this file.
1 <?php
7 
12 use Magento\Customer\Api\Data\CustomerInterfaceFactory;
15 
41 {
42  const STATUS_SUBSCRIBED = 1;
43  const STATUS_NOT_ACTIVE = 2;
45  const STATUS_UNCONFIRMED = 4;
46 
47  const XML_PATH_CONFIRM_EMAIL_TEMPLATE = 'newsletter/subscription/confirm_email_template';
48  const XML_PATH_CONFIRM_EMAIL_IDENTITY = 'newsletter/subscription/confirm_email_identity';
49  const XML_PATH_SUCCESS_EMAIL_TEMPLATE = 'newsletter/subscription/success_email_template';
50  const XML_PATH_SUCCESS_EMAIL_IDENTITY = 'newsletter/subscription/success_email_identity';
51  const XML_PATH_UNSUBSCRIBE_EMAIL_TEMPLATE = 'newsletter/subscription/un_email_template';
52  const XML_PATH_UNSUBSCRIBE_EMAIL_IDENTITY = 'newsletter/subscription/un_email_identity';
53  const XML_PATH_CONFIRMATION_FLAG = 'newsletter/subscription/confirm';
54  const XML_PATH_ALLOW_GUEST_SUBSCRIBE_FLAG = 'newsletter/subscription/allow_guest_subscribe';
55 
61  protected $_eventPrefix = 'newsletter_subscriber';
62 
70  protected $_eventObject = 'subscriber';
71 
77  protected $_isStatusChanged = false;
78 
84  protected $_newsletterData = null;
85 
91  protected $_scopeConfig;
92 
98  protected $_customerSession;
99 
104  private $dateTime;
105 
111  protected $_storeManager;
112 
117 
122 
127 
132 
136  private $customerFactory;
137 
141  private $dataObjectHelper;
142 
164  public function __construct(
165  \Magento\Framework\Model\Context $context,
166  \Magento\Framework\Registry $registry,
167  \Magento\Newsletter\Helper\Data $newsletterData,
168  \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
169  \Magento\Framework\Mail\Template\TransportBuilder $transportBuilder,
170  \Magento\Store\Model\StoreManagerInterface $storeManager,
171  \Magento\Customer\Model\Session $customerSession,
174  \Magento\Framework\Translate\Inline\StateInterface $inlineTranslation,
175  \Magento\Framework\Model\ResourceModel\AbstractResource $resource = null,
176  \Magento\Framework\Data\Collection\AbstractDb $resourceCollection = null,
177  array $data = [],
178  \Magento\Framework\Stdlib\DateTime\DateTime $dateTime = null,
179  CustomerInterfaceFactory $customerFactory = null,
180  DataObjectHelper $dataObjectHelper = null
181  ) {
182  $this->_newsletterData = $newsletterData;
183  $this->_scopeConfig = $scopeConfig;
184  $this->_transportBuilder = $transportBuilder;
185  $this->_storeManager = $storeManager;
186  $this->_customerSession = $customerSession;
187  $this->dateTime = $dateTime ?: \Magento\Framework\App\ObjectManager::getInstance()->get(
188  \Magento\Framework\Stdlib\DateTime\DateTime::class
189  );
190  $this->customerFactory = $customerFactory ?: ObjectManager::getInstance()
191  ->get(CustomerInterfaceFactory::class);
192  $this->dataObjectHelper = $dataObjectHelper ?: ObjectManager::getInstance()
193  ->get(DataObjectHelper::class);
194  $this->customerRepository = $customerRepository;
195  $this->customerAccountManagement = $customerAccountManagement;
196  $this->inlineTranslation = $inlineTranslation;
197  parent::__construct($context, $registry, $resource, $resourceCollection, $data);
198  }
199 
205  protected function _construct()
206  {
207  $this->_init(\Magento\Newsletter\Model\ResourceModel\Subscriber::class);
208  }
209 
215  public function getId()
216  {
217  return $this->getSubscriberId();
218  }
219 
226  public function setId($value)
227  {
228  return $this->setSubscriberId($value);
229  }
230 
236  public function getCode()
237  {
238  return $this->getSubscriberConfirmCode();
239  }
240 
246  public function getConfirmationLink()
247  {
248  return $this->_newsletterData->getConfirmationUrl($this);
249  }
250 
256  public function getUnsubscriptionLink()
257  {
258  return $this->_newsletterData->getUnsubscribeUrl($this);
259  }
260 
267  public function setCode($value)
268  {
269  return $this->setSubscriberConfirmCode($value);
270  }
271 
277  public function getStatus()
278  {
279  return $this->getSubscriberStatus();
280  }
281 
288  public function setStatus($value)
289  {
290  return $this->setSubscriberStatus($value);
291  }
292 
299  public function setMessagesScope($scope)
300  {
301  $this->getResource()->setMessagesScope($scope);
302  return $this;
303  }
304 
310  public function getEmail()
311  {
312  return $this->getSubscriberEmail();
313  }
314 
321  public function setEmail($value)
322  {
323  return $this->setSubscriberEmail($value);
324  }
325 
332  public function setStatusChanged($value)
333  {
334  $this->_isStatusChanged = (boolean) $value;
335  return $this;
336  }
337 
343  public function isStatusChanged()
344  {
346  }
347 
353  public function isSubscribed()
354  {
355  if ($this->getId() && $this->getStatus() == self::STATUS_SUBSCRIBED) {
356  return true;
357  }
358 
359  return false;
360  }
361 
368  public function loadByEmail($subscriberEmail)
369  {
370  $storeId = $this->_storeManager->getStore()->getId();
371  $customerData = ['store_id' => $storeId, 'email'=> $subscriberEmail];
372 
374  $customer = $this->customerFactory->create();
375  $this->dataObjectHelper->populateWithArray(
376  $customer,
378  \Magento\Customer\Api\Data\CustomerInterface::class
379  );
380  $this->addData($this->getResource()->loadByCustomerData($customer));
381  return $this;
382  }
383 
390  public function loadByCustomerId($customerId)
391  {
392  try {
393  $customerData = $this->customerRepository->getById($customerId);
394  $customerData->setStoreId($this->_storeManager->getStore()->getId());
395  $data = $this->getResource()->loadByCustomerData($customerData);
396  $this->addData($data);
397  if (!empty($data) && $customerData->getId() && !$this->getCustomerId()) {
398  $this->setCustomerId($customerData->getId());
399  $this->setSubscriberConfirmCode($this->randomSequence());
400  $this->save();
401  }
402  } catch (NoSuchEntityException $e) {
403  }
404  return $this;
405  }
406 
413  public function randomSequence($length = 32)
414  {
415  $id = '';
416  $par = [];
417  $char = array_merge(range('a', 'z'), range(0, 9));
418  $charLen = count($char) - 1;
419  for ($i = 0; $i < $length; $i++) {
421  $par[$i] = $char[$disc];
422  $id = $id . $char[$disc];
423  }
424  return $id;
425  }
426 
437  public function subscribe($email)
438  {
439  $this->loadByEmail($email);
440 
441  if ($this->getId() && $this->getStatus() == self::STATUS_SUBSCRIBED) {
442  return $this->getStatus();
443  }
444 
445  if (!$this->getId()) {
446  $this->setSubscriberConfirmCode($this->randomSequence());
447  }
448 
449  $isConfirmNeed = $this->_scopeConfig->getValue(
450  self::XML_PATH_CONFIRMATION_FLAG,
452  ) == 1 ? true : false;
453 
454  $isSubscribeOwnEmail = $this->_customerSession->isLoggedIn()
455  && $this->_customerSession->getCustomerDataObject()->getEmail() == $email;
456 
457  if (!$this->getId() || $this->getStatus() == self::STATUS_UNSUBSCRIBED
458  || $this->getStatus() == self::STATUS_NOT_ACTIVE
459  ) {
460  if ($isConfirmNeed === true) {
461  $this->setStatus(self::STATUS_NOT_ACTIVE);
462  } else {
463  $this->setStatus(self::STATUS_SUBSCRIBED);
464  }
465  $this->setSubscriberEmail($email);
466  }
467 
468  if ($isSubscribeOwnEmail) {
469  try {
470  $customer = $this->customerRepository->getById($this->_customerSession->getCustomerId());
471  $this->setStoreId($customer->getStoreId());
472  $this->setCustomerId($customer->getId());
473  } catch (NoSuchEntityException $e) {
474  $this->setStoreId($this->_storeManager->getStore()->getId());
475  $this->setCustomerId(0);
476  }
477  } else {
478  $this->setStoreId($this->_storeManager->getStore()->getId());
479  $this->setCustomerId(0);
480  }
481 
482  $this->setStatusChanged(true);
483 
484  try {
485  /* Save model before sending out email */
486  $this->save();
487  if ($isConfirmNeed === true) {
489  } else {
491  }
492  return $this->getStatus();
493  } catch (\Exception $e) {
494  throw new \Exception($e->getMessage());
495  }
496  }
497 
504  public function unsubscribe()
505  {
506  if ($this->hasCheckCode() && $this->getCode() != $this->getCheckCode()) {
507  throw new \Magento\Framework\Exception\LocalizedException(
508  __('This is an invalid subscription confirmation code.')
509  );
510  }
511 
512  if ($this->getSubscriberStatus() != self::STATUS_UNSUBSCRIBED) {
513  $this->setSubscriberStatus(self::STATUS_UNSUBSCRIBED)->save();
514  $this->sendUnsubscriptionEmail();
515  }
516  return $this;
517  }
518 
526  {
527  return $this->_updateCustomerSubscription($customerId, true);
528  }
529 
537  {
538  return $this->_updateCustomerSubscription($customerId, false);
539  }
540 
548  {
551  return $this;
552  }
553 
564  protected function _updateCustomerSubscription($customerId, $subscribe)
565  {
566  try {
567  $customerData = $this->customerRepository->getById($customerId);
568  } catch (NoSuchEntityException $e) {
569  return $this;
570  }
571 
573  if (!$subscribe && !$this->getId()) {
574  return $this;
575  }
576 
577  if (!$this->getId()) {
578  $this->setSubscriberConfirmCode($this->randomSequence());
579  }
580 
581  $sendInformationEmail = false;
583  $isConfirmNeed = $this->_scopeConfig->getValue(
584  self::XML_PATH_CONFIRMATION_FLAG,
586  ) == 1 ? true : false;
587  if ($subscribe) {
589  == $this->customerAccountManagement->getConfirmationStatus($customerId)
590  ) {
592  } elseif ($isConfirmNeed) {
593  if ($this->getStatus() != self::STATUS_SUBSCRIBED) {
595  }
596  }
597  } elseif (($this->getStatus() == self::STATUS_UNCONFIRMED) && ($customerData->getConfirmation() === null)) {
599  $sendInformationEmail = true;
600  } else {
602  }
606  if ($status != self::STATUS_UNCONFIRMED && $status != $this->getStatus()) {
607  $sendInformationEmail = true;
608  }
609 
610  if ($status != $this->getStatus()) {
611  $this->setStatusChanged(true);
612  }
613 
614  $this->setStatus($status);
615 
616  if (!$this->getId()) {
617  $storeId = $customerData->getStoreId();
618  if ($customerData->getStoreId() == 0) {
619  $storeId = $this->_storeManager->getWebsite($customerData->getWebsiteId())->getDefaultStore()->getId();
620  }
621  $this->setStoreId($storeId)
622  ->setCustomerId($customerData->getId())
623  ->setEmail($customerData->getEmail());
624  } else {
625  $this->setStoreId($customerData->getStoreId())
626  ->setEmail($customerData->getEmail());
627  }
628 
629  $this->save();
630  $sendSubscription = $sendInformationEmail;
631  if ($sendSubscription === null xor $sendSubscription && $this->isStatusChanged()) {
632  try {
633  switch ($status) {
635  $this->sendUnsubscriptionEmail();
636  break;
639  break;
641  if ($isConfirmNeed) {
643  }
644  break;
645  }
646  } catch (MailException $e) {
647  // If we are not able to send a new account email, this should be ignored
648  $this->_logger->critical($e);
649  }
650  }
651  return $this;
652  }
653 
660  public function confirm($code)
661  {
662  if ($this->getCode() == $code) {
663  $this->setStatus(self::STATUS_SUBSCRIBED)
664  ->setStatusChanged(true)
665  ->save();
666 
668  return true;
669  }
670 
671  return false;
672  }
673 
680  public function received(\Magento\Newsletter\Model\Queue $queue)
681  {
682  $this->getResource()->received($this, $queue);
683  return $this;
684  }
685 
692  {
693  if ($this->getImportMode()) {
694  return $this;
695  }
696 
697  if (!$this->_scopeConfig->getValue(
698  self::XML_PATH_CONFIRM_EMAIL_TEMPLATE,
700  ) || !$this->_scopeConfig->getValue(
701  self::XML_PATH_CONFIRM_EMAIL_IDENTITY,
703  )
704  ) {
705  return $this;
706  }
707 
708  $this->inlineTranslation->suspend();
709 
710  $this->_transportBuilder->setTemplateIdentifier(
711  $this->_scopeConfig->getValue(
712  self::XML_PATH_CONFIRM_EMAIL_TEMPLATE,
714  )
715  )->setTemplateOptions(
716  [
717  'area' => \Magento\Framework\App\Area::AREA_FRONTEND,
718  'store' => $this->_storeManager->getStore()->getId(),
719  ]
720  )->setTemplateVars(
721  ['subscriber' => $this, 'store' => $this->_storeManager->getStore()]
722  )->setFrom(
723  $this->_scopeConfig->getValue(
724  self::XML_PATH_CONFIRM_EMAIL_IDENTITY,
726  )
727  )->addTo(
728  $this->getEmail(),
729  $this->getName()
730  );
731  $transport = $this->_transportBuilder->getTransport();
732  $transport->sendMessage();
733 
734  $this->inlineTranslation->resume();
735 
736  return $this;
737  }
738 
745  {
746  if ($this->getImportMode()) {
747  return $this;
748  }
749 
750  if (!$this->_scopeConfig->getValue(
751  self::XML_PATH_SUCCESS_EMAIL_TEMPLATE,
753  ) || !$this->_scopeConfig->getValue(
754  self::XML_PATH_SUCCESS_EMAIL_IDENTITY,
756  )
757  ) {
758  return $this;
759  }
760 
761  $this->inlineTranslation->suspend();
762 
763  $this->_transportBuilder->setTemplateIdentifier(
764  $this->_scopeConfig->getValue(
765  self::XML_PATH_SUCCESS_EMAIL_TEMPLATE,
767  )
768  )->setTemplateOptions(
769  [
770  'area' => \Magento\Framework\App\Area::AREA_FRONTEND,
771  'store' => $this->_storeManager->getStore()->getId(),
772  ]
773  )->setTemplateVars(
774  ['subscriber' => $this]
775  )->setFrom(
776  $this->_scopeConfig->getValue(
777  self::XML_PATH_SUCCESS_EMAIL_IDENTITY,
779  )
780  )->addTo(
781  $this->getEmail(),
782  $this->getName()
783  );
784  $transport = $this->_transportBuilder->getTransport();
785  $transport->sendMessage();
786 
787  $this->inlineTranslation->resume();
788 
789  return $this;
790  }
791 
797  public function sendUnsubscriptionEmail()
798  {
799  if ($this->getImportMode()) {
800  return $this;
801  }
802  if (!$this->_scopeConfig->getValue(
803  self::XML_PATH_UNSUBSCRIBE_EMAIL_TEMPLATE,
805  ) || !$this->_scopeConfig->getValue(
806  self::XML_PATH_UNSUBSCRIBE_EMAIL_IDENTITY,
808  )
809  ) {
810  return $this;
811  }
812 
813  $this->inlineTranslation->suspend();
814 
815  $this->_transportBuilder->setTemplateIdentifier(
816  $this->_scopeConfig->getValue(
817  self::XML_PATH_UNSUBSCRIBE_EMAIL_TEMPLATE,
819  )
820  )->setTemplateOptions(
821  [
822  'area' => \Magento\Framework\App\Area::AREA_FRONTEND,
823  'store' => $this->_storeManager->getStore()->getId(),
824  ]
825  )->setTemplateVars(
826  ['subscriber' => $this]
827  )->setFrom(
828  $this->_scopeConfig->getValue(
829  self::XML_PATH_UNSUBSCRIBE_EMAIL_IDENTITY,
831  )
832  )->addTo(
833  $this->getEmail(),
834  $this->getName()
835  );
836  $transport = $this->_transportBuilder->getTransport();
837  $transport->sendMessage();
838 
839  $this->inlineTranslation->resume();
840 
841  return $this;
842  }
843 
849  public function getSubscriberFullName()
850  {
851  $name = null;
852  if ($this->hasFirstname() || $this->hasLastname()) {
853  $name = $this->getFirstname() . ' ' . $this->getLastname();
854  }
855  return $name;
856  }
857 
864  public function beforeSave()
865  {
866  parent::beforeSave();
867  if ($this->dataHasChangedFor('subscriber_status')) {
868  $this->setChangeStatusAt($this->dateTime->gmtDate());
869  }
870  return $this;
871  }
872 }
__construct(\Magento\Framework\Model\Context $context, \Magento\Framework\Registry $registry, \Magento\Newsletter\Helper\Data $newsletterData, \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig, \Magento\Framework\Mail\Template\TransportBuilder $transportBuilder, \Magento\Store\Model\StoreManagerInterface $storeManager, \Magento\Customer\Model\Session $customerSession, CustomerRepositoryInterface $customerRepository, AccountManagementInterface $customerAccountManagement, \Magento\Framework\Translate\Inline\StateInterface $inlineTranslation, \Magento\Framework\Model\ResourceModel\AbstractResource $resource=null, \Magento\Framework\Data\Collection\AbstractDb $resourceCollection=null, array $data=[], \Magento\Framework\Stdlib\DateTime\DateTime $dateTime=null, CustomerInterfaceFactory $customerFactory=null, DataObjectHelper $dataObjectHelper=null)
Definition: Subscriber.php:164
$queue
Definition: queue.php:21
$customerData
static getRandomNumber($min=0, $max=null)
Definition: Random.php:62
elseif(isset( $params[ 'redirect_parent']))
Definition: iframe.phtml:17
$customer
Definition: customers.php:11
$email
Definition: details.phtml:13
$id
Definition: fieldset.phtml:14
$storeManager
__()
Definition: __.php:13
$resource
Definition: bulk.php:12
received(\Magento\Newsletter\Model\Queue $queue)
Definition: Subscriber.php:680
$value
Definition: gender.phtml:16
$status
Definition: order_status.php:8
_updateCustomerSubscription($customerId, $subscribe)
Definition: Subscriber.php:564
$i
Definition: gallery.phtml:31
$code
Definition: info.phtml:12
if(!isset($_GET['name'])) $name
Definition: log.php:14