1C-Bitrix 25.700.0
Загрузка...
Поиск...
Не найдено
message.php
См. документацию.
1<?php
2namespace Bitrix\MessageService;
3
4use Bitrix\Main\Localization\Loc;
5use Bitrix\Main\ArgumentTypeException;
6use Bitrix\Main\ORM\Data\AddResult;
7use Bitrix\Main\Error;
8use Bitrix\Main;
9use Bitrix\Main\Type\DateTime;
10use Bitrix\MessageService\Integration\Pull;
11use Bitrix\MessageService\Internal\Entity\MessageTable;
12use Bitrix\MessageService\Restriction\RestrictionManager;
13use Bitrix\MessageService\Sender\Result;
14
15Loc::loadMessages(__FILE__);
16
18{
19 public const EVENT_MESSAGE_UPDATED = 'messageUpdated';
20
21 protected $id;
22
24 protected $sender;
25
27 protected $type;
29 protected $authorId = 0;
31 protected $from;
33 protected $to;
35 protected $headers = array();
37 protected $body;
38
39 protected $statusId;
40 protected $externalStatus;
41
42 protected ?Error $error = null;
43
44 protected bool $checkRestrictions = false;
45
50 public function __construct(Sender\Base $sender = null)
51 {
52 if ($sender)
53 {
54 $this->setSender($sender);
55 }
56 }
57
58 public static function loadById(int $id): ?Message
59 {
60 $fields = MessageTable::getRowById($id);
61 if (!$fields)
62 {
63 return null;
64 }
65 $instance = new static();
66 $instance->setFields($fields);
67
68 return $instance;
69 }
70
71 public static function loadByExternalId(string $senderId, string $externalId, ?string $from = null): ?Message
72 {
73 $fields = MessageTable::getByExternalId($senderId, $externalId, $from)->fetch();
74 if (!$fields)
75 {
76 return null;
77 }
78 $instance = new static();
79 $instance->setFields($fields);
80
81 return $instance;
82 }
83
89 public static function createFromFields(array $fields, Sender\Base $sender = null): Message
90 {
91 $message = new static($sender);
92 $message->setFields($fields);
93
94 return $message;
95 }
96
97 public static function getFieldsById($messageId)
98 {
100 return $iterator->fetch();
101 }
102
108 public function setType(string $type): Message
109 {
111 {
112 throw new ArgumentTypeException('Unsupported message type');
113 }
114
115 $this->type = $type;
116 return $this;
117 }
118
122 public function getType(): string
123 {
124 return $this->type;
125 }
126
127 public function checkFields(): Main\Result
128 {
129 $result = new Main\Result();
130
131 $sender = $this->getSender();
132 $from = $this->getFrom();
133
134 if (!$sender)
135 {
136 $result->addError(new Error(Loc::getMessage('MESSAGESERVICE_MESSAGE_ERROR_SENDER')));
137 }
138 elseif (!$sender->canUse())
139 {
140 $result->addError(new Error(Loc::getMessage('MESSAGESERVICE_MESSAGE_ERROR_SENDER_CAN_USE')));
141 }
142 elseif ($sender->getType() !== $this->getType())
143 {
144 $result->addError(new Error(Loc::getMessage('MESSAGESERVICE_MESSAGE_ERROR_TYPE')));
145 }
146 elseif (!$from || !$sender->isCorrectFrom($from))
147 {
148 $result->addError(new Error(Loc::getMessage('MESSAGESERVICE_MESSAGE_ERROR_FROM')));
149 }
150
151 return $result;
152 }
153
157 public function send(): Main\Result
158 {
159 global $USER;
160
161 $checkResult = $this->checkFields();
162
163 if (!$checkResult->isSuccess())
164 {
165 $result = new AddResult();
166 $result->addErrors($checkResult->getErrors());
167 return $result;
168 }
169
170 if ($this->checkRestrictions)
171 {
172 $restrictionManager = new RestrictionManager($this);
173 if (!$restrictionManager->isCanSendMessage())
174 {
175 return (new Main\Result())->addError(
176 new Error(Loc::getMessage('MESSAGESERVICE_MESSAGE_ERROR_RESTRICTION'))
177 );
178 }
179 }
180
181 $sender = $this->getSender();
182 $headers = $this->getHeaders();
183
185 'TYPE' => $this->getType(),
186 'SENDER_ID' => $sender->getId(),
187 'AUTHOR_ID' => $this->getAuthorId(),
188 'MESSAGE_FROM' => $this->getFrom(),
189 'MESSAGE_TO' => $this->getTo(),
190 'MESSAGE_HEADERS' => count($headers) > 0 ? $headers : null,
191 'MESSAGE_BODY' => $this->getBody(),
192 'CLUSTER_GROUP' => defined('BX_CLUSTER_GROUP') ? BX_CLUSTER_GROUP : null
193 ]);
194 if ($result->isSuccess())
195 {
196 $this->id = $result->getId();
197 if (Main\Config\Option::get('messageservice', 'event_log_message_send', 'N') === 'Y')
198 {
199 $userId = $USER instanceof \CUser ? $USER->getId() : 0;
200 \CEventLog::Log('INFO', 'MESSAGE_SEND', 'messageservice', $userId, $this->getTo());
201 }
202 }
203
204 return $result;
205 }
206
207 public function sendDirectly(): Result\SendMessage
208 {
209 global $USER;
210
211 $checkResult = $this->checkFields();
212
213 if (!$checkResult->isSuccess())
214 {
215 $result = new Result\SendMessage();
216 return $result->addErrors($checkResult->getErrors());
217 }
218
219 if ($this->checkRestrictions)
220 {
221 $restrictionManager = new RestrictionManager($this);
222 if (!$restrictionManager->isCanSendMessage())
223 {
224 return (new Result\SendMessage)->addError(
225 new Error(Loc::getMessage('MESSAGESERVICE_MESSAGE_ERROR_RESTRICTION'))
226 );
227 }
228 }
229
230 $sender = $this->getSender();
231
232 if (!Sender\Limitation::checkDailyLimit($sender->getId(), $this->getFrom()))
233 {
234 $result = new Result\SendMessage();
235 $result->addError(new Error(Loc::getMessage('MESSAGESERVICE_MESSAGE_ERROR_LIMITATION')));
237
238 return $result;
239 }
240
241 $headers = $this->getHeaders();
243 'TYPE' => $this->getType(),
244 'SENDER_ID' => $sender->getId(),
245 'AUTHOR_ID' => $this->getAuthorId(),
246 'MESSAGE_FROM' => $this->getFrom(),
247 'MESSAGE_TO' => $this->getTo(),
248 'MESSAGE_HEADERS' => count($headers) > 0 ? $headers : null,
249 'MESSAGE_BODY' => $this->getBody(),
250 'CLUSTER_GROUP' => defined('BX_CLUSTER_GROUP') ? BX_CLUSTER_GROUP : null
251 ];
252
253 $sender->setSocketTimeout(5);
254 $sender->setStreamTimeout(15);
255
256 $result = $sender->sendMessage($messageFields);
257
258 $messageFields['DATE_EXEC'] = new DateTime();
259 $messageFields['SUCCESS_EXEC'] = $result->isSuccess() ? 'Y' : 'N';
260
261 if ($result->getExternalId() !== null)
262 {
263 $messageFields['EXTERNAL_ID'] = $result->getExternalId();
264 }
265 if ($result->getStatus() !== null)
266 {
267 $messageFields['STATUS_ID'] = $result->getStatus();
268 }
269
271 if (!$addResult->isSuccess())
272 {
273 $result->addErrors($addResult->getErrors());
274 $result->setStatus(MessageStatus::ERROR);
275
276 return $result;
277 }
278
279 $this->id = $addResult->getId();
280 $result->setId($this->id);
281
282 if (Main\Config\Option::get('messageservice', 'event_log_message_send', 'N') === 'Y')
283 {
284 $userId = $USER instanceof \CUser ? $USER->getId() : 0;
285 \CEventLog::Log('INFO', 'MESSAGE_SEND', 'messageservice', $userId, $this->getTo());
286 }
287
288 return $result;
289 }
290
294 public function getFrom()
295 {
296 return $this->from;
297 }
298
303 public function setFrom($from): Message
304 {
305 $this->from = (string)$from;
306 return $this;
307 }
308
312 public function getBody()
313 {
314 return $this->body;
315 }
316
321 public function setBody($body): Message
322 {
323 $this->body = (string)$body;
324 return $this;
325 }
326
330 public function getTo()
331 {
332 return $this->to;
333 }
334
339 public function setTo($to): Message
340 {
341 $this->to = (string)$to;
342 return $this;
343 }
344
348 public function getSender(): ?Sender\Base
349 {
350 return $this->sender;
351 }
352
357 public function setSender(Sender\Base $sender)
358 {
359 $this->sender = $sender;
360 return $this;
361 }
362
368 {
369 $this->headers = $headers;
370 return $this;
371 }
372
376 public function getHeaders()
377 {
378 return $this->headers;
379 }
380
385 public function setAuthorId(int $authorId): Message
386 {
387 $this->authorId = $authorId;
388 return $this;
389 }
390
394 public function getAuthorId()
395 {
396 return $this->authorId;
397 }
398
402 public function getError(): ?Error
403 {
404 return $this->error;
405 }
406
411 public function setError(Error $error): self
412 {
413 $this->error = $error;
414
415 return $this;
416 }
417
418 public function getStatusId()
419 {
420 return $this->statusId;
421 }
422
423 public function update(array $fields): bool
424 {
425 $updateResult = MessageTable::update($this->id, $fields);
426 if (!$updateResult->isSuccess())
427 {
428 return false;
429 }
430
431 $this->setFields($fields);
432
433 // events
434 $eventFields = array_merge(['ID' => $this->id], $fields);
436 'messageservice',
437 static::EVENT_MESSAGE_UPDATED,
438 $eventFields)
439 );
440 Pull::onMessagesUpdate([$eventFields]);
441
442 return true;
443 }
444
445 public function updateWithSendResult(Result\SendMessage $result, DateTime $nextExec): void
446 {
447 $toUpdate = ['SUCCESS_EXEC' => 'E', 'DATE_EXEC' => new DateTime()];
448 if ($result->isSuccess())
449 {
450 $toUpdate['SUCCESS_EXEC'] = 'Y';
451 if ($result->getExternalId() !== null)
452 {
453 if (is_array($result->getExternalId()))
454 {
455 $systemException = new \Bitrix\Main\SystemException('ExternalId is array: ' . print_r($result->getExternalId(), true));
456 \Bitrix\Main\Application::getInstance()->getExceptionHandler()->writeToLog($systemException);
457
458 $result->addError(new \Bitrix\Main\Error(
459 'ExternalId is array',
460 'WRONG_EXTERNAL_ID',
461 $result->getExternalId()
462 ));
463 }
464
465 $toUpdate['EXTERNAL_ID'] = $result->getExternalId();
466 }
467 if ($result->getStatus() !== null)
468 {
469 $toUpdate['STATUS_ID'] = $result->getStatus();
470 }
471 }
472 elseif ($result->getStatus() === MessageStatus::DEFERRED)
473 {
474 $toUpdate = array(
475 'SUCCESS_EXEC' => 'N',
476 'NEXT_EXEC' => $nextExec,
477 'STATUS_ID' => MessageStatus::DEFERRED
478 );
479 }
480 else
481 {
482 $toUpdate['STATUS_ID'] = MessageStatus::ERROR;
483 }
484
485 $errors = $result->getErrorMessages();
486 if ($errors)
487 {
488 $toUpdate['EXEC_ERROR'] = implode(PHP_EOL, $errors);
489 }
490
491 $this->update($toUpdate);
492 }
493
494 public function updateStatusByExternalStatus(string $externalStatus): bool
495 {
496
497 $newInternalStatus = $this->sender::resolveStatus($externalStatus);
498
499 $isUpdateSuccess = MessageTable::updateMessageStatuses(
500 $this->id,
501 $newInternalStatus,
503 );
504
505 if (!$isUpdateSuccess)
506 {
507 return false;
508 }
509
510 $this->statusId = $newInternalStatus;
511
512 // events
513 $eventFields = ['ID' => $this->id, 'STATUS_ID' => $this->statusId];
515 'messageservice',
516 static::EVENT_MESSAGE_UPDATED,
517 $eventFields)
518 );
519 Pull::onMessagesUpdate([$eventFields]);
520
521 return true;
522 }
523
524 public function updateStatus(int $newStatusId): bool
525 {
526 $updateResult = MessageTable::updateStatusId($this->id, $newStatusId);
527 if (!$updateResult)
528 {
529 return false;
530 }
531
532 $this->statusId = $newStatusId;
533
534 // events
535 $eventFields = ['ID' => $this->id, 'STATUS_ID' => $this->statusId];
537 'messageservice',
538 static::EVENT_MESSAGE_UPDATED,
539 $eventFields)
540 );
541 Pull::onMessagesUpdate([$eventFields]);
542
543 return true;
544 }
545
546 private function setFields(array $fields): void
547 {
548 if (!$this->sender && isset($fields['SENDER_ID']))
549 {
551 if ($sender)
552 {
553 $this->setSender($sender);
554 }
555 }
556 if (isset($fields['ID']))
557 {
558 $this->id = (int)$fields['ID'];
559 }
560 if (isset($fields['TYPE']))
561 {
562 $this->setType($fields['TYPE']);
563 }
564 if (isset($fields['AUTHOR_ID']))
565 {
566 $this->setAuthorId((int)$fields['AUTHOR_ID']);
567 }
568 if (isset($fields['MESSAGE_FROM']))
569 {
570 $this->setFrom($fields['MESSAGE_FROM']);
571 }
572 if (isset($fields['MESSAGE_TO']))
573 {
574 $this->setTo($fields['MESSAGE_TO']);
575 }
576 if (
577 isset($fields['MESSAGE_TEMPLATE'])
578 && $this->sender->isConfigurable()
579 && $this->sender->isTemplatesBased()
580 )
581 {
582 $fields['MESSAGE_HEADERS'] = is_array($fields['MESSAGE_HEADERS']) ? $fields['MESSAGE_HEADERS'] : [];
583 $fields['MESSAGE_HEADERS']['template'] = $this->sender->prepareTemplate($fields['MESSAGE_TEMPLATE']);
584 }
585 if (isset($fields['MESSAGE_HEADERS']) && is_array($fields['MESSAGE_HEADERS']))
586 {
587 $this->setHeaders($fields['MESSAGE_HEADERS']);
588 }
589 if (isset($fields['MESSAGE_BODY']))
590 {
591 $messageBody = $this->sender
592 ? $this->sender->prepareMessageBodyForSave($fields['MESSAGE_BODY'])
593 : $fields['MESSAGE_BODY']
594 ;
595 $this->setBody($messageBody);
596 }
597 if (isset($fields['STATUS_ID']))
598 {
599 $this->statusId = $fields['STATUS_ID'];
600 }
601 if (isset($fields['EXTERNAL_STATUS']))
602 {
603 $this->externalStatus = $fields['EXTERNAL_STATUS'];
604 }
605 }
606
610 public function setCheckRestrictions(bool $checkRestrictions): void
611 {
612 $this->checkRestrictions = $checkRestrictions;
613 }
614}
$messageFields
Определения callback_ednaru.php:22
if(! $messageFields||!isset($messageFields['message_id'])||!isset($messageFields['status'])||!CModule::IncludeModule("messageservice")) $messageId
Определения callback_ismscenter.php:26
if(!is_object($USER)||! $USER->IsAuthorized()) $userId
Определения check_mail.php:18
static getInstance()
Определения application.php:98
Определения error.php:15
Определения event.php:5
static getInstance()
Определения eventmanager.php:31
static getById($id)
Определения datamanager.php:364
static add(array $data)
Определения datamanager.php:877
static onMessagesUpdate(array $messages)
Определения pull.php:24
setBody($body)
Определения message.php:321
setCheckRestrictions(bool $checkRestrictions)
Определения message.php:610
updateWithSendResult(Result\SendMessage $result, DateTime $nextExec)
Определения message.php:445
__construct(Sender\Base $sender=null)
Определения message.php:50
updateStatus(int $newStatusId)
Определения message.php:524
setError(Error $error)
Определения message.php:411
static loadById(int $id)
Определения message.php:58
static createFromFields(array $fields, Sender\Base $sender=null)
Определения message.php:89
Error $error
Определения message.php:42
setFrom($from)
Определения message.php:303
setSender(Sender\Base $sender)
Определения message.php:357
bool $checkRestrictions
Определения message.php:44
static getFieldsById($messageId)
Определения message.php:97
updateStatusByExternalStatus(string $externalStatus)
Определения message.php:494
setHeaders(array $headers)
Определения message.php:367
static loadByExternalId(string $senderId, string $externalId, ?string $from=null)
Определения message.php:71
update(array $fields)
Определения message.php:423
setAuthorId(int $authorId)
Определения message.php:385
setType(string $type)
Определения message.php:108
const EVENT_MESSAGE_UPDATED
Определения message.php:19
static isSupported($type)
Определения messagetype.php:8
static getSenderById($id)
Определения smsmanager.php:158
static Log($SEVERITY, $AUDIT_TYPE_ID, $MODULE_ID, $ITEM_ID, $DESCRIPTION=false, $SITE_ID=false)
Определения event_log.php:32
</td ></tr ></table ></td ></tr >< tr >< td class="bx-popup-label bx-width30"><?=GetMessage("PAGE_NEW_TAGS")?> array( $site)
Определения file_new.php:804
$result
Определения get_property_values.php:14
$errors
Определения iblock_catalog_edit.php:74
global $USER
Определения csv_new_run.php:40
$message
Определения payment.php:8
if( $daysToExpire >=0 &&$daysToExpire< 60 elseif)( $daysToExpire< 0)
Определения prolog_main_admin.php:393
$instance
Определения ps_b24_final.php:14
</p ></td >< td valign=top style='border-top:none;border-left:none;border-bottom:solid windowtext 1.0pt;border-right:solid windowtext 1.0pt;padding:0cm 2.0pt 0cm 2.0pt;height:9.0pt'>< p class=Normal align=center style='margin:0cm;margin-bottom:.0001pt;text-align:center;line-height:normal'>< a name=ТекстовоеПоле54 ></a ><?=($taxRate > count( $arTaxList) > 0) ? $taxRate."%"
Определения waybill.php:936
$iterator
Определения yandex_run.php:610
$fields
Определения yandex_run.php:501