Bitrix-D7 23.9
 
Загрузка...
Поиск...
Не найдено
subscribemanager.php
1<?php
3
15
16Loc::loadMessages(__FILE__);
17
23{
24 const ERROR_REQUIRED_PARAMATERS = 'ERROR_REQUIRED_PARAMATERS_12001';
25 const ERROR_ADD_SUBSCRIBE = 'ERROR_ADD_SUBSCRIBE_12002';
26 const ERROR_VALIDATE_FIELDS = 'ERROR_VALIDATE_FIELDS_12003';
27 const ERROR_SUBSCRIBER_IDENTIFICATION = 'ERROR_SUBSCRIBER_IDENTIFICATION_12004';
28 const ERROR_AUTHORIZATION = 'ERROR_AUTHORIZATION_12005';
29 const ERROR_DELETE_SUBSCRIBE = 'ERROR_ADD_SUBSCRIBE_12006';
30 const ERROR_ADD_SUBSCRIBE_ALREADY_EXISTS = 'ERROR_ADD_SUBSCRIBE_ALREADY_EXISTS_12007';
31 const ERROR_ACTIVITY_CHANGE = 'ERROR_ACTIVITY_CHANGE_12008';
32 const ERROR_UNSUBSCRIBE = 'ERROR_UNSUBSCRIBE_12009';
33
37 protected $userId = 0;
39 protected $isAdmin = false;
40
41 public $contactTypes = array();
42
43 protected $fields = array();
44 protected $listAvailableFields = array(
45 'DATE_TO',
46 'USER_CONTACT',
47 'CONTACT_TYPE',
48 'USER_ID',
49 'ITEM_ID',
50 'NEED_SENDING',
51 'SITE_ID',
52 'LANDING_SITE_ID'
53 );
54
55 public function __construct()
56 {
57 $this->errorCollection = new ErrorCollection;
58
59 $this->contactTypes = SubscribeTable::getContactTypes();
60
61 global $USER;
62 if (is_object($USER) && $USER->isAuthorized())
63 {
64 $this->isAdmin = ($USER->isAdmin() || $USER->canDoOperation('bitrix24_config'));
65 $this->userId = $USER->getId();
66 }
67 }
68
72 public function getErrors()
73 {
74 return $this->errorCollection->toArray();
75 }
76
86 public function addSubscribe(array $subscribeData)
87 {
88 $this->checkRequiredInputParams($subscribeData,
89 array('USER_CONTACT', 'ITEM_ID', 'SITE_ID', 'CONTACT_TYPE'));
90 if(!$this->errorCollection->isEmpty())
91 {
92 return false;
93 }
94
95 $resultObject = ProductTable::getList(array(
96 'select' => array(
97 'SUBSCRIBE',
98 'USER_CONTACT' => 'Bitrix\Catalog\SubscribeTable:PRODUCT.USER_CONTACT',
99 'CONTACT_TYPE' => 'Bitrix\Catalog\SubscribeTable:PRODUCT.CONTACT_TYPE',
100 'DATE_TO' => 'Bitrix\Catalog\SubscribeTable:PRODUCT.DATE_TO',
101 ),
102 'filter' => array(
103 '=ID' => $subscribeData['ITEM_ID'],
104 ),
105 ));
106 while($productSubscribeData = $resultObject->fetch())
107 {
108 if(!$this->checkDataBeforeSave($productSubscribeData, $subscribeData))
109 break;
110 }
111 if(!$this->errorCollection->isEmpty())
112 {
113 return false;
114 }
115
116 $this->fields = array();
117 foreach($subscribeData as $fieldId => $fieldValue)
118 {
119 if(in_array($fieldId, $this->listAvailableFields))
120 {
121 $this->fields[$fieldId] = $fieldValue;
122 }
123 }
124
125 $this->validateFields();
126 if(!$this->errorCollection->isEmpty())
127 {
128 return false;
129 }
130
131 $result = SubscribeTable::add($this->fields);
132 if($result->isSuccess())
133 {
134 $this->setSessionOfSibscribedProducts($subscribeData['ITEM_ID']);
135 return $result->getId();
136 }
137 else
138 {
139 foreach($result->getErrorMessages() as $errorMessage)
140 $this->errorCollection->add(array(new Error($errorMessage, self::ERROR_ADD_SUBSCRIBE)));
141 return false;
142 }
143 }
144
153 public function deleteManySubscriptions(array $listSubscribeId, $itemId = 0)
154 {
155 foreach($listSubscribeId as $subscribeId)
156 {
157 if($this->checkAccessToSubscription($subscribeId))
158 {
159 $result = SubscribeTable::delete($subscribeId);
160 if(!$result->isSuccess())
161 {
162 foreach($result->getErrorMessages() as $errorMessage)
163 $this->errorCollection->add(array(new Error($errorMessage, self::ERROR_DELETE_SUBSCRIBE)));
164 return false;
165 }
166 }
167 else
168 {
169 $this->errorCollection->add(array(new Error(
170 Loc::getMessage('ERROR_ACCESS_DENIDE_DELETE_SUBSCRIBE'), self::ERROR_DELETE_SUBSCRIBE)));
171 return false;
172 }
173 }
174
175 $this->deleteSessionOfSibscribedProducts($itemId);
176
177 return true;
178 }
179
188 public function checkAccessToSubscription($subscribeId)
189 {
190 if($this->isAdmin)
191 {
192 return true;
193 }
194
195 $resultObject = SubscribeTable::getList(array(
196 'select' => array(
197 'USER_ID',
198 'TOKEN' => 'Bitrix\Catalog\SubscribeAccessTable:SUBSCRIBE.TOKEN',
199 ),
200 'filter' => array('=ID' => intval($subscribeId)),
201 ));
202 if($subscribeData = $resultObject->fetch())
203 {
204 if($this->userId)
205 {
206 if($subscribeData['USER_ID'] == $this->userId)
207 {
208 return true;
209 }
210 }
211 else
212 {
213 if(isset($_SESSION['SUBSCRIBE_PRODUCT']['TOKEN'])
214 && $subscribeData['TOKEN'] == $_SESSION['SUBSCRIBE_PRODUCT']['TOKEN'])
215 {
216 return true;
217 }
218 }
219 }
220
221 return false;
222 }
223
232 public function runSubscriberIdentification(array $subscriberData, $sendLetter = true)
233 {
234 $this->checkRequiredInputParams($subscriberData,
235 array('contactType', 'userContact', 'siteId'));
236 if(!$this->errorCollection->isEmpty())
237 {
238 return false;
239 }
240
241 $currentContactType = $this->contactTypes[$subscriberData['contactType']];
242 if(!preg_match($currentContactType['RULE'], $subscriberData['userContact']))
243 {
244 $this->errorCollection->add(array(new Error(
245 Loc::getMessage('ERROR_SUBSCRIBE_ENTRY_CONFIRMATION_CODE'), self::ERROR_SUBSCRIBER_IDENTIFICATION)));
246 return false;
247 }
248
249 $token = Random::getString(6);
250
251 try
252 {
254 $accessRow = SubscribeAccessTable::getRow(
255 array(
256 'select' => array('ID'),
257 'filter' => array('=USER_CONTACT' => $subscriberData['userContact'])
258 )
259 );
260 if($accessRow['ID'])
261 {
262 $result = SubscribeAccessTable::update($accessRow['ID'], array(
263 'DATE_FROM' => new DateTime(),
264 'TOKEN' => $token
265 ));
266 }
267 else
268 {
269 $result = SubscribeAccessTable::add(array(
270 'DATE_FROM' => new DateTime(),
271 'USER_CONTACT' => $subscriberData['userContact'],
272 'TOKEN' => $token
273 ));
274 }
275 if(!$result->isSuccess())
276 {
277 $this->errorCollection->add(array(new Error(
278 Loc::getMessage('ERROR_SUBSCRIBE_ENTRY_CONFIRMATION_CODE'), self::ERROR_SUBSCRIBER_IDENTIFICATION)));
279 }
280 }
281 catch(\Exception $errorObject)
282 {
283 $this->errorCollection->add(array(new Error($errorObject->getMessage())));
284 }
285
286 if(!$this->errorCollection->isEmpty())
287 {
288 return false;
289 }
290
291 if(!$sendLetter)
292 {
293 return true;
294 }
295
296 /* Preparation of data for the mail template */
297 $dataSendToNotice = array();
298 $listSubscribesUrl = \CHTTP::URN2URI('/personal/subscribe/');
299 $dataSendToNotice[$subscriberData['contactType']][$subscriberData['userContact']][] = array(
300 'EVENT_NAME' => 'CATALOG_PRODUCT_SUBSCRIBE_LIST_CONFIRM',
301 'EMAIL_TO' => $subscriberData['userContact'],
302 'SITE_ID' => $subscriberData['siteId'],
303 'USER_NAME' => Loc::getMessage('EMAIL_TEMPLATE_USER_NAME'),
304 'TOKEN' => $token,
305 'LIST_SUBSCRIBES' => $listSubscribesUrl,
306 'TOKEN_URL' => \CHTTP::urlAddParams($listSubscribesUrl, array('accessCodeVerification' => 'Y',
307 'userContact' => $subscriberData['userContact'], 'subscribeToken' => $token)),
308 'URL_PARAMETERS' => \CHTTP::urlAddParams('', array('accessCodeVerification' => 'Y',
309 'userContact' => $subscriberData['userContact'], 'subscribeToken' => $token))
310 );
311
312 foreach($this->contactTypes as $typeId => $typeData)
313 {
314 $eventKey = EventManager::getInstance()
315 ->addEventHandler('catalog', 'OnSubscribeSubmit', $typeData['HANDLER']);
316
317 $event = new Event('catalog', 'OnSubscribeSubmit', $dataSendToNotice[$typeId]);
318 $event->send();
319
320 EventManager::getInstance()->removeEventHandler('catalog', 'OnSubscribeSubmit', $eventKey);
321 }
322
323 return true;
324 }
325
332 public function authorizeSubscriber(array $authorizationData)
333 {
334 $this->checkRequiredInputParams($authorizationData, array('userContact', 'subscribeToken'));
335 if(!$this->errorCollection->isEmpty())
336 {
337 return false;
338 }
339
340 try
341 {
343 $accessRow = SubscribeAccessTable::getRow(
344 array(
345 'select' => array('ID'),
346 'filter' => array(
347 'TOKEN' => $authorizationData['subscribeToken'],
348 'USER_CONTACT' => $authorizationData['userContact']
349 )
350 )
351 );
352
353 if(!$accessRow['ID'])
354 {
355 $this->errorCollection->add(array(new Error(
356 Loc::getMessage('ERROR_AUTHORIZATION_ACCESS_ROW_NOT_FOUND'), self::ERROR_AUTHORIZATION)));
357 return false;
358 }
359
360 $_SESSION['SUBSCRIBE_PRODUCT'] = array(
361 'TOKEN' => $authorizationData['subscribeToken'],
362 'USER_CONTACT' => $authorizationData['userContact']
363 );
364 }
365 catch(\Exception $errorObject)
366 {
367 $this->errorCollection->add(array(new Error($errorObject->getMessage())));
368 }
369
370 if(!$this->errorCollection->isEmpty())
371 {
372 return false;
373 }
374
375 return true;
376 }
377
386 public function unSubscribe(array $data)
387 {
388 $this->checkRequiredInputParams($data, array('unSubscribe', 'userContact', 'subscribeId', 'productId'));
389 if(!$this->errorCollection->isEmpty())
390 {
391 return false;
392 }
393
394 $itemId = intval($data['productId']);
395
396 $subscribe = SubscribeTable::getList(array(
397 'select' => array('CNT'),
398 'filter' => array(
399 '=ID' => intval($data['subscribeId']),
400 '=ITEM_ID' => $itemId,
401 '=USER_CONTACT' => $data['userContact'],
402 ),
403 'runtime' => array(new Entity\ExpressionField('CNT', 'COUNT(*)'))
404 ))->fetch();
405 if(intval($subscribe['CNT']))
406 {
407 SubscribeTable::delete($data['subscribeId']);
408 }
409 else
410 {
411 $this->errorCollection->add(array(new Error(
412 Loc::getMessage('ERROR_UNSUBSCRIBE_ALREADY_UNSUBSCRIBE'), self::ERROR_UNSUBSCRIBE)));
413 return false;
414 }
415
416 $this->deleteSessionOfSibscribedProducts($itemId);
417
418 return true;
419 }
420
429 public function activateSubscription(array $listSubscribeId, $timePeriod = 0)
430 {
431 if($timePeriod)
432 {
433 $fields = array('DATE_TO' => DateTime::createFromTimestamp(time() + intval($timePeriod)));
434 }
435 else
436 {
437 $fields = array('DATE_TO' => false);
438 }
439
440 foreach($listSubscribeId as $subscribeId)
441 {
442 $result = SubscribeTable::update($subscribeId, $fields);
443 if(!$result->isSuccess())
444 {
445 foreach($result->getErrorMessages() as $errorMessage)
446 $this->errorCollection->add(array(new Error($errorMessage, self::ERROR_ACTIVITY_CHANGE)));
447 return false;
448 }
449 }
450
451 return true;
452 }
453
461 public function deactivateSubscription(array $listSubscribeId)
462 {
463 foreach($listSubscribeId as $subscribeId)
464 {
465 $result = SubscribeTable::update($subscribeId, array('DATE_TO' => new DateTime()));
466 if(!$result->isSuccess())
467 {
468 foreach($result->getErrorMessages() as $errorMessage)
469 $this->errorCollection->add(array(new Error($errorMessage, self::ERROR_ACTIVITY_CHANGE)));
470 return false;
471 }
472 }
473
474 return true;
475 }
476
483 public function checkSubscriptionActivity($dateTo)
484 {
485 if($dateTo)
486 {
487 if($dateTo instanceof DateTime && $dateTo->getTimestamp() > time())
488 {
489 return true;
490 }
491 return false;
492 }
493 else
494 {
495 return true;
496 }
497 }
498
505 public function setSessionOfSibscribedProducts($itemId)
506 {
507 $itemId = intval($itemId);
508 if(!empty($_SESSION['SUBSCRIBE_PRODUCT']['LIST_PRODUCT_ID'])
509 && is_array($_SESSION['SUBSCRIBE_PRODUCT']['LIST_PRODUCT_ID']))
510 {
511 $_SESSION['SUBSCRIBE_PRODUCT']['LIST_PRODUCT_ID'][$itemId] = true;
512 }
513 else
514 {
515 if(empty($_SESSION['SUBSCRIBE_PRODUCT']))
516 $_SESSION['SUBSCRIBE_PRODUCT'] = array();
517
518 $_SESSION['SUBSCRIBE_PRODUCT']['LIST_PRODUCT_ID'] = array();
519 $_SESSION['SUBSCRIBE_PRODUCT']['LIST_PRODUCT_ID'][$itemId] = true;
520 }
521 }
522
523 private function deleteSessionOfSibscribedProducts($itemId = 0)
524 {
525 if(!empty($_SESSION['SUBSCRIBE_PRODUCT']['LIST_PRODUCT_ID'][$itemId]))
526 {
527 unset($_SESSION['SUBSCRIBE_PRODUCT']['LIST_PRODUCT_ID'][$itemId]);
528 }
529 }
530
531 private function checkDataBeforeSave($productSubscribeData, array $subscribeData)
532 {
533 if(!$productSubscribeData || !is_array($productSubscribeData))
534 {
535 $this->errorCollection->add(array(new Error(
536 Loc::getMessage('ERROR_PRODUCT_NOT_FOUND'), self::ERROR_ADD_SUBSCRIBE)));
537 return false;
538 }
539 if(!SubscribeTable::checkPermissionSubscribe($productSubscribeData['SUBSCRIBE']))
540 {
541 $this->errorCollection->add(array(new Error(
542 Loc::getMessage('ERROR_SUBSCRIBE_DENIED'), self::ERROR_ADD_SUBSCRIBE)));
543 return false;
544 }
545 if(!array_key_exists($subscribeData['CONTACT_TYPE'], $this->contactTypes))
546 {
547 $this->errorCollection->add(array(new Error(
548 Loc::getMessage('ERROR_CONTACT_TYPE'), self::ERROR_ADD_SUBSCRIBE)));
549 return false;
550 }
551 if($productSubscribeData['USER_CONTACT'] == $subscribeData['USER_CONTACT']
552 && $productSubscribeData['DATE_TO'] == null)
553 {
554 $this->setSessionOfSibscribedProducts($subscribeData['ITEM_ID']);
555 $this->errorCollection->add(array(new Error(
556 Loc::getMessage('ERROR_SUBSCRIBE_ALREADY_EXISTS'), self::ERROR_ADD_SUBSCRIBE_ALREADY_EXISTS)));
557 return false;
558 }
559 return true;
560 }
561
562 private function validateFields()
563 {
564 foreach($this->fields as $fieldId => $fieldValue)
565 {
566 switch($fieldId)
567 {
568 case 'DATE_TO':
569 if(!($fieldValue instanceof DateTime) ||
570 ($fieldValue instanceof DateTime && $fieldValue->getTimestamp() < time()))
571 {
572 $this->errorCollection->add(array(new Error(Loc::getMessage('ERROR_VALIDATE_FIELDS',
573 array('#FIELD#' => $fieldId)), self::ERROR_VALIDATE_FIELDS)));
574 }
575 break;
576 case 'USER_CONTACT':
577 $currentContactType = $this->contactTypes[$this->fields['CONTACT_TYPE']];
578 if(!preg_match($currentContactType['RULE'], $fieldValue))
579 {
580 $this->errorCollection->add(array(new Error(Loc::getMessage('ERROR_VALIDATE_FIELDS',
581 array('#FIELD#' => $fieldId)), self::ERROR_VALIDATE_FIELDS)));
582 }
583 break;
584 }
585 }
586 }
587
588 private function checkRequiredInputParams(array $inputParams, array $requiredParams)
589 {
590 foreach ($requiredParams as $param)
591 {
592 if(!isset($inputParams[$param]) || (!$inputParams[$param] &&
593 !(is_string($inputParams[$param]) && mb_strlen($inputParams[$param]))))
594 {
595 $this->errorCollection->add(array(new Error(Loc::getMessage('ERROR_REQUIRED_PARAMATERS',
596 array('#PARAM#' => $param)), self::ERROR_REQUIRED_PARAMATERS)));
597 return false;
598 }
599 }
600 return true;
601 }
602}
activateSubscription(array $listSubscribeId, $timePeriod=0)
authorizeSubscriber(array $authorizationData)
runSubscriberIdentification(array $subscriberData, $sendLetter=true)
deleteManySubscriptions(array $listSubscribeId, $itemId=0)
static checkPermissionSubscribe($subscribe)
static loadMessages($file)
Definition loc.php:64
static getMessage($code, $replace=null, $language=null)
Definition loc.php:29
static getList(array $parameters=array())
static createFromTimestamp($timestamp)
Definition datetime.php:246