Bitrix-D7 23.9
 
Загрузка...
Поиск...
Не найдено
transportmail.php
1<?php
10
11use Bitrix\Main;
24
25Loc::loadMessages(__FILE__);
26
32{
34
36 protected $configuration;
37
39 protected $mailContext;
40
42 protected $mailAddress;
43
47 public function __construct()
48 {
49 $this->configuration = new Message\Configuration();
50 }
51
57 public function getName()
58 {
59 return Loc::getMessage('SENDER_INTEGRATION_MAIL_TRANSPORT_NAME');
60 }
61
67 public function getCode()
68 {
69 return self::CODE;
70 }
71
78 {
79 return array(Recipient\Type::EMAIL);
80 }
81
89 public function loadConfiguration($id = null)
90 {
92 }
93
102 {
103 return null;
104 }
105
111 public function start()
112 {
113
114 }
115
123 public function send(Message\Adapter $message)
124 {
125 $headers = $message->getConfiguration()->get('HEADERS');
126 $headers = is_array($headers) ? $headers : array();
127 $fields = $message->getFields();
128 $preparedConsentLink = '';
129 $unsubLink = $message->getUnsubTracker()->getLink();
130 if (!isset($fields['UNSUBSCRIBE_LINK']))
131 {
132 $fields['UNSUBSCRIBE_LINK'] = $unsubLink;
133 }
134 if ($unsubLink)
135 {
136 if (!preg_match('/^http:|https:/', $unsubLink))
137 {
138 $unsubLink = $this->getSenderLinkProtocol() . '://' . $message->getSiteServerName() . $unsubLink;
139 }
140 $headers['List-Unsubscribe'] = '<'.$unsubLink.'>';
141 $headers['List-Unsubscribe-Post'] = 'List-Unsubscribe=One-Click';
142 }
143
144 $fields['SENDER_MAIL_CHARSET'] = $message->getCharset();
145
146 if (Integration\Bitrix24\Service::isCloud())
147 {
148 $headers['X-Bitrix-Mail-Count'] = $message->getTransport()->getSendCount() ?: 1;
149 $recipientData = $message->getRecipientData();
150 if ($recipientData['CONTACT_IS_SEND_SUCCESS'] !== 'Y')
151 {
152 $headers['X-Bitrix-Mail-Unverified'] = 1;
153 }
154 }
155
156 $linkParameters = $message->getConfiguration()->get('LINK_PARAMS');
157 if($linkParameters)
158 {
159 $parametersTmp = [];
160 parse_str($linkParameters, $parametersTmp);
161 if(is_array($parametersTmp))
162 {
163 $clickUriParameters = $message->getClickTracker()->getUriParameters();
164 $message->getClickTracker()->setUriParameters(
165 array_merge($clickUriParameters, $parametersTmp)
166 );
167 }
168 }
169
170 $mailAttachment = array();
171 $messageAttachment = $message->getConfiguration()->get('ATTACHMENT');
172 $messageAttachment = is_array($messageAttachment) ? $messageAttachment : array();
173 foreach ($messageAttachment as $key => $file)
174 {
175 if (is_numeric($file) && $file > 0)
176 {
177 continue;
178 }
179
180 if (is_array($file) && File::isFileExists($file['tmp_name']))
181 {
182 $mailAttachment[] = array(
183 'PATH' => $file['tmp_name'],
184 'ID' => md5($file['tmp_name']),
185 'CONTENT_TYPE' => File::getFileContents($file['tmp_name']),
186 'NAME' => ($file['name'] ?: 'some_file'),
187 );
188 }
189
190 unset($messageAttachment[$key]);
191 }
192
193 $canTrackMail = $message->getConfiguration()->get('TRACK_MAIL', $this->canTrackMails());
194 $mailMessageParams = array(
195 'EVENT' => [],
196 'FIELDS' => $this->prepareFields($fields, $message),
197 'MESSAGE' => array(
198 'BODY_TYPE' => 'html',
199 'EMAIL_FROM' => $this->getCleanMailAddress($message->getConfiguration()->get('EMAIL_FROM')),
200 'EMAIL_TO' => '#EMAIL_TO#',
201 'PRIORITY' => $message->getConfiguration()->get('PRIORITY'),
202 'SUBJECT' => $message->getConfiguration()->get('SUBJECT'),
203 'MESSAGE' => str_replace('#CONSENT_LINK#', $preparedConsentLink, $message->getConfiguration()->get('BODY')),
204 'MESSAGE_PHP' => $message->getConfiguration()->get('BODY_PHP'),
205 'FILE' => $messageAttachment
206 ),
207 'SITE' => $message->getSiteId(),
208 'CHARSET' => $message->getCharset(),
209 );
210 $mailMessage = Mail\EventMessageCompiler::createInstance($mailMessageParams);
211 $mailMessage->compile();
212
213 if (is_array($mailMessage->getMailAttachment()))
214 {
215 $mailAttachment = array_merge($mailAttachment, $mailMessage->getMailAttachment());
216 }
217
218 $mailParams = array(
219 'TO' => $mailMessage->getMailTo(),
220 'SUBJECT' => static::replaceTemplate($mailMessage->getMailSubject()),
221 'BODY' => $mailMessage->getMailBody(),
222 'HEADER' => $mailMessage->getMailHeaders() + $headers,
223 'CHARSET' => $mailMessage->getMailCharset(),
224 'CONTENT_TYPE' => $mailMessage->getMailContentType(),
225 'MESSAGE_ID' => '',
226 'ATTACHMENT' => $mailAttachment,
227 'LINK_PROTOCOL' => $this->getSenderLinkProtocol(),
228 'LINK_DOMAIN' => $message->getSiteServerName(),
229 'TRACK_READ' => $canTrackMail ? $message->getReadTracker()->getArray() : null,
230 'TRACK_CLICK' => $canTrackMail ? $message->getClickTracker()->getArray() : null,
231 'CONTEXT' => $this->getMailContextForMessage($message),
232 );
233 $linkDomain = $message->getReadTracker()->getLinkDomain();
234 if ($linkDomain)
235 {
236 $mailParams['LINK_DOMAIN'] = $linkDomain;
237 }
238
239 // event on sending email
240 $eventMailParams = $mailParams;
241 $eventMailParams['MAILING_CHAIN_ID'] = $message->getConfiguration()->get('LETTER_ID');
242 $event = new Main\Event('sender', 'OnPostingSendRecipientEmail', [$eventMailParams]);
243 $event->send();
244 foreach ($event->getResults() as $eventResult)
245 {
246 if($eventResult->getType() == Main\EventResult::ERROR)
247 {
248 return false;
249 }
250
251 if(is_array($eventResult->getParameters()))
252 {
253 $eventMailParams = array_merge($eventMailParams, $eventResult->getParameters());
254 }
255 }
256 unset($eventMailParams['MAILING_CHAIN_ID']);
257 $mailParams = $eventMailParams;
258
259 return Mail\Mail::send($mailParams);
260 }
261
267 public function end()
268 {
269
270 }
271
279 public function getDuration(Message\Adapter $message = null)
280 {
281 return 0.01;
282 }
283
290 public function getLimiters(Message\iBase $message = null)
291 {
292 $limiters = Integration\Bitrix24\Limitation\Limiter::getList();
293
294 if (Integration\Bitrix24\Service::isCloud())
295 {
296 $limiters[] = Integration\Bitrix24\Limitation\Limiter::getPortalVerification();
297 }
298
299 if ($message)
300 {
301 $limiters[] = self::getTimeLimiter($message);
302 $email = $message->getConfiguration()->get('EMAIL_FROM');
303 $address = new \Bitrix\Main\Mail\Address($email);
304 $limiters[] = Integration\Bitrix24\Limitation\Limiter::getEmailMonthly($address->getEmail());
305 }
306
307 return $limiters;
308 }
309
315 private static function getTimeLimiter($message)
316 {
317 return Transport\TimeLimiter::create()
318 ->withLetter($message);
319 }
320
321 protected function getSenderLinkProtocol()
322 {
323 $protocol = Option::get('sender', 'link_protocol', null);
324 $protocol = $protocol ?: (Integration\Bitrix24\Service::isCloud() ? 'https' : 'http');
325 return $protocol;
326 }
327
328 protected function canTrackMails()
329 {
330 return Option::get('sender', 'track_mails') === 'Y';
331 }
332
333 protected function getMailContext()
334 {
335 if (!$this->mailContext)
336 {
337 $this->mailContext = new Mail\Context();
338 $this->mailContext->setCategory(Mail\Context::CAT_EXTERNAL);
339 $this->mailContext->setPriority(Mail\Context::PRIORITY_LOW);
340 $this->mailContext->setKeepAlive(Mail\Smtp\Mailer::KEEP_ALIVE_ALWAYS);
341
342 if (Integration\Bitrix24\Service::isCloud())
343 {
344 $this->mailContext->setCallback(
345 (new Mail\Callback\Config())->setModuleId('sender')
346 );
347 }
348 }
349
350 return $this->mailContext;
351 }
352
359 protected function getCleanMailAddress($address)
360 {
361 if (!$this->mailAddress)
362 {
363 $this->mailAddress = new Mail\Address();
364 }
365
366 return $this->mailAddress->set($address)->get();
367 }
368
373 public static function replaceTemplate(?string $str)
374 {
375 preg_match_all("/#([0-9a-zA-Z_.|]+?)#/", $str, $matchesFindPlaceHolders);
376 if(!empty($matchesFindPlaceHolders) && isset($matchesFindPlaceHolders[1]))
377 {
378 foreach($matchesFindPlaceHolders[1] as $key)
379 {
380 $str = str_replace("#".$key."#", '', $str);
381 }
382 }
383
384 return $str;
385 }
386
395 {
396 $agreement = $this->getAgreement((int)$message->getConfiguration()->get('APPROVE_CONFIRMATION_CONSENT'));
397
398 if (!$agreement)
399 {
400 return false;
401 }
402
403 $builder->set('POSTING_ID', $message->getId());
404 $builder->set('CONSENT_ID', $agreement->getId());
405 $buildedMessage = $builder->buildMessage();
406
407 $contentBody = Security\Sanitizer::fixReplacedStyles($agreement->getText());
408 $contentBody = Security\Sanitizer::sanitizeHtml($contentBody, $agreement->getText());
409
410 $template = \Bitrix\Sender\Preset\Templates\Consent::getTemplateHtml();
411 $body = \Bitrix\Sender\Preset\Templates\Consent::replaceTemplateHtml($template, [
412 'APPROVE_BTN_TEXT' => $agreement->getLabelText(),
413 'CONSENT_BODY' => $contentBody,
414 'CONSENT_FOOTER' => '',
415 'APPLY_URL' => $buildedMessage['C_FIELDS']['SENDER_CONSENT_APPLY'],
416 'REJECT_URL' => $buildedMessage['C_FIELDS']['SENDER_CONSENT_REJECT'],
417 ]);
418
419 $mailMessageParams = array(
420 'EVENT' => [],
421 'FIELDS' => [],
422 'MESSAGE' => array(
423 'BODY_TYPE' => 'html',
424 'EMAIL_FROM' => $this->getCleanMailAddress($message->getConfiguration()->get('EMAIL_FROM')),
425 'EMAIL_TO' => $buildedMessage['C_FIELDS']['EMAIL'],
426 'PRIORITY' => $message->getConfiguration()->get('PRIORITY'),
427 'SUBJECT' => Loc::getMessage('SENDER_INTEGRATION_MAIL_CONSENT_SUBJECT'),
428 'MESSAGE' => $body,
429 'MESSAGE_PHP' => $message->getConfiguration()->get('BODY_PHP'),
430 ),
431 'SITE' => $message->getSiteId(),
432 'CHARSET' => $message->getCharset(),
433 );
434 $mailMessage = Mail\EventMessageCompiler::createInstance($mailMessageParams);
435 $mailMessage->compile();
436
437 $mailParams = array(
438 'TO' => $mailMessage->getMailTo(),
439 'SUBJECT' => static::replaceTemplate($mailMessage->getMailSubject()),
440 'BODY' => $mailMessage->getMailBody(),
441 'HEADER' => $mailMessage->getMailHeaders(),
442 'CHARSET' => $mailMessage->getMailCharset(),
443 'CONTENT_TYPE' => $mailMessage->getMailContentType(),
444 'MESSAGE_ID' => '',
445 'CONTEXT' => $this->getMailContextForMessage($message),
446 );
447
448 return Mail\Mail::send($mailParams);
449 }
450
452 {
453 $context = $this->getMailContext();
454
455 //set callback entity Id
456 if (Integration\Bitrix24\Service::isCloud())
457 {
458 if ($message->getRecipientId())
459 {
460 $context->getCallback()
461 ->setEntityType('rcpt')
462 ->setEntityId($message->getRecipientId());
463 }
464 else
465 {
466 $context->getCallback()
467 ->setEntityType('test')
468 ->setEntityId(time() . '.' . rand(100, 1000));
469 }
470 }
471
472 return $context;
473 }
474
475 private function getAgreement(int $agreementId): ?Main\UserConsent\Agreement
476 {
477 $agreement = new Main\UserConsent\Agreement($agreementId, ['fields' => ['IP']]);
478 if (!$agreement->isActive() || !$agreement->isExist())
479 {
480 return null;
481 }
482
483 return $agreement;
484 }
485
486 private function getAgreementUri(int $agreementId): ?string
487 {
488 return (string)\Bitrix\Main\UserConsent\AgreementLink::getUri($agreementId, [], '/pub/agreement.php');
489 }
490
495 public function isConsentNeed()
496 {
497 return Env::isTransportNeedConsent(static::CODE);
498 }
499
504 public function getConsentMaxRequests(): int
505 {
506 return Env::getMaxConsentRequests(static::CODE);
507 }
508
509 private function prepareFields(array $fields, Message\Adapter $message)
510 {
511 $result = [];
512
513 foreach ($fields as $key => $value)
514 {
515 $newKey = $message->preHandleReplaceCode($key, $fields['CRM_ENTITY_TYPE_ID']);
516 $newValue = $message->preHandleReaplaceValue($key, $value);
517 $result[$newKey] = $newValue;
518 }
519
520 return $result;
521 }
522}
static loadMessages($file)
Definition loc.php:64
static getMessage($code, $replace=null, $language=null)
Definition loc.php:29
sendConsent(Message\Adapter $message, Consent\AbstractConsentMessageBuilder $builder)
saveConfiguration(Message\Configuration $configuration)