Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
SendFriend.php
Go to the documentation of this file.
1 <?php
7 
9 
25 {
31  protected $_names = [];
32 
38  protected $_emails = [];
39 
45  protected $_sender = [];
46 
52  protected $_product;
53 
59  protected $_sentCount;
60 
66  protected $_lastCookieValue = [];
67 
73  protected $_sendfriendData = null;
74 
80  protected $_catalogImage = null;
81 
85  protected $_transportBuilder;
86 
90  protected $_storeManager;
91 
95  protected $_escaper;
96 
101 
105  protected $cookieManager;
106 
110  protected $remoteAddress;
111 
128  public function __construct(
129  \Magento\Framework\Model\Context $context,
130  \Magento\Framework\Registry $registry,
131  \Magento\Store\Model\StoreManagerInterface $storeManager,
132  \Magento\Framework\Mail\Template\TransportBuilder $transportBuilder,
133  \Magento\Catalog\Helper\Image $catalogImage,
134  \Magento\SendFriend\Helper\Data $sendfriendData,
135  \Magento\Framework\Escaper $escaper,
136  \Magento\Framework\HTTP\PhpEnvironment\RemoteAddress $remoteAddress,
137  \Magento\Framework\Stdlib\CookieManagerInterface $cookieManager,
138  \Magento\Framework\Translate\Inline\StateInterface $inlineTranslation,
139  \Magento\Framework\Model\ResourceModel\AbstractResource $resource = null,
140  \Magento\Framework\Data\Collection\AbstractDb $resourceCollection = null,
141  array $data = []
142  ) {
143  $this->_storeManager = $storeManager;
144  $this->_transportBuilder = $transportBuilder;
145  $this->_catalogImage = $catalogImage;
146  $this->_sendfriendData = $sendfriendData;
147  $this->_escaper = $escaper;
148  $this->remoteAddress = $remoteAddress;
149  $this->cookieManager = $cookieManager;
150  $this->inlineTranslation = $inlineTranslation;
151  parent::__construct($context, $registry, $resource, $resourceCollection, $data);
152  }
153 
159  protected function _construct()
160  {
161  $this->_init(\Magento\SendFriend\Model\ResourceModel\SendFriend::class);
162  }
163 
168  public function send()
169  {
170  if ($this->isExceedLimit()) {
171  throw new \Magento\Framework\Exception\LocalizedException(
172  __('You\'ve met your limit of %1 sends in an hour.', $this->getMaxSendsToFriend())
173  );
174  }
175 
176  $this->inlineTranslation->suspend();
177 
178  $message = nl2br(htmlspecialchars($this->getSender()->getMessage()));
179  $sender = [
180  'name' => $this->_escaper->escapeHtml($this->getSender()->getName()),
181  'email' => $this->_escaper->escapeHtml($this->getSender()->getEmail()),
182  ];
183 
184  foreach ($this->getRecipients()->getEmails() as $k => $email) {
185  $name = $this->getRecipients()->getNames($k);
186  $this->_transportBuilder->setTemplateIdentifier(
187  $this->_sendfriendData->getEmailTemplate()
188  )->setTemplateOptions(
189  [
190  'area' => \Magento\Framework\App\Area::AREA_FRONTEND,
191  'store' => $this->_storeManager->getStore()->getId(),
192  ]
193  )->setFrom(
194  $sender
195  )->setTemplateVars(
196  [
197  'name' => $name,
198  'email' => $email,
199  'product_name' => $this->getProduct()->getName(),
200  'product_url' => $this->getProduct()->getUrlInStore(),
201  'message' => $message,
202  'sender_name' => $sender['name'],
203  'sender_email' => $sender['email'],
204  'product_image' => $this->_catalogImage->init($this->getProduct(), 'sendfriend_small_image')
205  ->getUrl(),
206  ]
207  )->addTo(
208  $email,
209  $name
210  );
211  $transport = $this->_transportBuilder->getTransport();
212  $transport->sendMessage();
213  }
214 
215  $this->inlineTranslation->resume();
216 
217  $this->_incrementSentCount();
218 
219  return $this;
220  }
221 
229  public function validate()
230  {
231  $errors = [];
232 
233  $name = $this->getSender()->getName();
234  if (empty($name)) {
235  $errors[] = __('Please enter a sender name.');
236  }
237 
238  $email = $this->getSender()->getEmail();
239  if (empty($email) or !\Zend_Validate::is($email, \Magento\Framework\Validator\EmailAddress::class)) {
240  $errors[] = __('Invalid Sender Email');
241  }
242 
243  $message = $this->getSender()->getMessage();
244  if (empty($message)) {
245  $errors[] = __('Please enter a message.');
246  }
247 
248  if (!$this->getRecipients()->getEmails()) {
249  $errors[] = __('Please specify at least one recipient.');
250  }
251 
252  // validate recipients email addresses
253  foreach ($this->getRecipients()->getEmails() as $email) {
254  if (!\Zend_Validate::is($email, \Magento\Framework\Validator\EmailAddress::class)) {
255  $errors[] = __('Please enter a correct recipient email address.');
256  break;
257  }
258  }
259 
260  $maxRecipients = $this->getMaxRecipients();
261  if (count($this->getRecipients()->getEmails()) > $maxRecipients) {
262  $errors[] = __('No more than %1 emails can be sent at a time.', $this->getMaxRecipients());
263  }
264 
265  if (empty($errors)) {
266  return true;
267  }
268 
269  return $errors;
270  }
271 
279  public function setRecipients($recipients)
280  {
281  // validate array
282  if (!is_array(
283  $recipients
284  ) or !isset(
285  $recipients['email']
286  ) or !isset(
287  $recipients['name']
288  ) or !is_array(
289  $recipients['email']
290  ) or !is_array(
291  $recipients['name']
292  )
293  ) {
294  return $this;
295  }
296 
297  $emails = [];
298  $names = [];
299  foreach ($recipients['email'] as $k => $email) {
300  if (!isset($emails[$email]) && isset($recipients['name'][$k])) {
301  $emails[$email] = true;
302  $names[] = $recipients['name'][$k];
303  }
304  }
305 
306  if ($emails) {
307  $emails = array_keys($emails);
308  }
309 
310  return $this->setData(
311  '_recipients',
312  new \Magento\Framework\DataObject(['emails' => $emails, 'names' => $names])
313  );
314  }
315 
321  public function getRecipients()
322  {
323  $recipients = $this->_getData('_recipients');
324  if (!$recipients instanceof \Magento\Framework\DataObject) {
325  $recipients = new \Magento\Framework\DataObject(['emails' => [], 'names' => []]);
326  $this->setData('_recipients', $recipients);
327  }
328  return $recipients;
329  }
330 
337  public function setProduct($product)
338  {
339  return $this->setData('_product', $product);
340  }
341 
348  public function getProduct()
349  {
350  $product = $this->_getData('_product');
351  if (!$product instanceof \Magento\Catalog\Model\Product) {
352  throw new \Magento\Framework\Exception\LocalizedException(__('Please define a correct product instance.'));
353  }
354  return $product;
355  }
356 
363  public function setSender($sender)
364  {
365  if (!is_array($sender)) {
366  __('Invalid Sender Information');
367  }
368 
369  return $this->setData('_sender', new \Magento\Framework\DataObject($sender));
370  }
371 
378  public function getSender()
379  {
380  $sender = $this->_getData('_sender');
381  if (!$sender instanceof \Magento\Framework\DataObject) {
382  throw new \Magento\Framework\Exception\LocalizedException(
383  __('Please define the correct sender information.')
384  );
385  }
386  return $sender;
387  }
388 
394  public function getMaxSendsToFriend()
395  {
396  return $this->_sendfriendData->getMaxEmailPerPeriod();
397  }
398 
404  public function getMaxRecipients()
405  {
406  return $this->_sendfriendData->getMaxRecipients();
407  }
408 
414  public function canEmailToFriend()
415  {
416  return $this->_sendfriendData->isEnabled();
417  }
418 
424  public function isExceedLimit()
425  {
426  return $this->getSentCount() >= $this->getMaxSendsToFriend();
427  }
428 
435  public function getSentCount($useCache = true)
436  {
437  if ($useCache && $this->_sentCount !== null) {
438  return $this->_sentCount;
439  }
440 
441  switch ($this->_sendfriendData->getLimitBy()) {
442  case \Magento\SendFriend\Helper\Data::CHECK_COOKIE:
443  return $this->_sentCount = $this->_sentCountByCookies(false);
444  case \Magento\SendFriend\Helper\Data::CHECK_IP:
445  return $this->_sentCount = $this->_sentCountByIp(false);
446  default:
447  return 0;
448  }
449  }
450 
456  protected function _incrementSentCount()
457  {
458  switch ($this->_sendfriendData->getLimitBy()) {
459  case \Magento\SendFriend\Helper\Data::CHECK_COOKIE:
460  return $this->_sentCount = $this->_sentCountByCookies(true);
461  case \Magento\SendFriend\Helper\Data::CHECK_IP:
462  return $this->_sentCount = $this->_sentCountByIp(true);
463  default:
464  return 0;
465  }
466  }
467 
474  protected function _sentCountByCookies($increment = false)
475  {
476  $cookieName = $this->_sendfriendData->getCookieName();
477  $time = time();
478  $newTimes = [];
479 
480  if (isset($this->_lastCookieValue[$cookieName])) {
481  $oldTimes = $this->_lastCookieValue[$cookieName];
482  } else {
483  $oldTimes = $this->cookieManager->getCookie($cookieName);
484  }
485 
486  if ($oldTimes) {
487  $oldTimes = explode(',', $oldTimes);
488  foreach ($oldTimes as $oldTime) {
489  $periodTime = $time - $this->_sendfriendData->getPeriod();
490  if (is_numeric($oldTime) and $oldTime >= $periodTime) {
491  $newTimes[] = $oldTime;
492  }
493  }
494  }
495 
496  if ($increment) {
497  $newTimes[] = $time;
498  $newValue = implode(',', $newTimes);
499  $this->cookieManager->setSensitiveCookie($cookieName, $newValue);
500  $this->_lastCookieValue[$cookieName] = $newValue;
501  }
502 
503  return count($newTimes);
504  }
505 
512  protected function _sentCountByIp($increment = false)
513  {
514  $time = time();
515  $period = $this->_sendfriendData->getPeriod();
516  $websiteId = $this->_storeManager->getStore()->getWebsiteId();
517 
518  if ($increment) {
519  // delete expired logs
520  $this->_getResource()->deleteLogsBefore($time - $period);
521  // add new item
522  $this->_getResource()->addSendItem($this->remoteAddress->getRemoteAddress(true), $time, $websiteId);
523  }
524 
525  return $this->_getResource()->getSendCount(
526  $this,
527  $this->remoteAddress->getRemoteAddress(true),
528  time() - $period,
529  $websiteId
530  );
531  }
532 }
__construct(\Magento\Framework\Model\Context $context, \Magento\Framework\Registry $registry, \Magento\Store\Model\StoreManagerInterface $storeManager, \Magento\Framework\Mail\Template\TransportBuilder $transportBuilder, \Magento\Catalog\Helper\Image $catalogImage, \Magento\SendFriend\Helper\Data $sendfriendData, \Magento\Framework\Escaper $escaper, \Magento\Framework\HTTP\PhpEnvironment\RemoteAddress $remoteAddress, \Magento\Framework\Stdlib\CookieManagerInterface $cookieManager, \Magento\Framework\Translate\Inline\StateInterface $inlineTranslation, \Magento\Framework\Model\ResourceModel\AbstractResource $resource=null, \Magento\Framework\Data\Collection\AbstractDb $resourceCollection=null, array $data=[])
Definition: SendFriend.php:128
$email
Definition: details.phtml:13
$storeManager
_sentCountByCookies($increment=false)
Definition: SendFriend.php:474
__()
Definition: __.php:13
$resource
Definition: bulk.php:12
$message
static is($value, $classBaseName, array $args=array(), $namespaces=array())
Definition: Validate.php:195
$errors
Definition: overview.phtml:9
if(!isset($_GET['name'])) $name
Definition: log.php:14