Bitrix-D7 23.9
 
Загрузка...
Поиск...
Не найдено
Utils.php
1<?php
2
4
10
11
12class Utils extends EdnaUtils
13{
14 protected function initializeDefaultExternalSender(): Providers\ExternalSender
15 {
16 return new ExternalSender(
17 $this->optionManager->getOption(Providers\Constants\InternalOption::API_KEY),
19 $this->optionManager->getSocketTimeout(),
20 $this->optionManager->getStreamTimeout()
21 );
22 }
23
24 public function getMessageTemplates(string $subject = ''): Result
25 {
26 $result = new Result();
27
28 if ($this->optionManager->getOption('enable_templates_stub', 'N') === 'Y')
29 {
30 $templates = $this->removeUnsupportedTemplates($this->getMessageTemplatesStub());
31 return $result->setData($templates);
32 }
33
34 $subjectList = [$subject];
35 if ($subject === '')
36 {
37 $subjectList = $this->optionManager->getOption('sender_id', []);
38 }
39
40 $verifiedSubjectIdResult = $this->getVerifiedSubjectIdList($subjectList);
41 if (!$verifiedSubjectIdResult->isSuccess())
42 {
43 return $verifiedSubjectIdResult;
44 }
45
46 $verifiedSubjectIdList = $verifiedSubjectIdResult->getData();
47
48 $templates = [];
49 foreach ($verifiedSubjectIdList as $subjectId)
50 {
51 $requestParams = [
52 'subjectId' => $subjectId
53 ];
54
55 $templatesRequestResult =
56 $this->externalSender->callExternalMethod(Providers\Edna\Constants\Method::GET_TEMPLATES, $requestParams);
57
58 if ($templatesRequestResult->isSuccess())
59 {
60 $templates = array_merge($templates, $templatesRequestResult->getData());
61 }
62 }
63
64 $checkErrors = $this->checkForErrors($templates);
65 if ($checkErrors->isSuccess())
66 {
67 $templates = $this->removeUnsupportedTemplates($templates);
68 $templates = $this->checkForPlaceholders($templates);
69 $result->setData($templates);
70 }
71 else
72 {
73 $result->addErrors($checkErrors->getErrors());
74 }
75
76 return $result;
77 }
78
79 public function prepareTemplateMessageText(array $message): string
80 {
81 $latestMessage = '';
82 if (isset($message['MESSAGE_HEADERS']['template']['header']['text']))
83 {
84 $latestMessage .= $message['MESSAGE_HEADERS']['template']['header']['text'] . '#BR#';
85 }
86
87 if (isset($message['MESSAGE_HEADERS']['template']['text']))
88 {
89 $latestMessage .= $message['MESSAGE_HEADERS']['template']['text'] . '#BR#';
90 }
91
92 if (isset($message['MESSAGE_HEADERS']['template']['footer']['text']))
93 {
94 $latestMessage .= $message['MESSAGE_HEADERS']['template']['footer']['text'];
95 }
96
97 return $latestMessage;
98 }
99
100 public function getSentTemplateMessage(string $from, string $to): string
101 {
102 $message = MessageTable::getList([
103 'select' => ['ID', 'MESSAGE_HEADERS'],
104 'filter' => [
105 '=SENDER_ID' => $this->providerId,
106 '=MESSAGE_FROM' => $from,
107 '=MESSAGE_TO' => '+' . $to,
108 ],
109 'limit' => 1,
110 'order' => ['ID' => 'DESC'],
111 ])->fetch();
112
113 if (!$message)
114 {
115 return '';
116 }
117
118 return $this->prepareTemplateMessageText($message);
119 }
120
121 protected function getMessageTemplatesStub(): array
122 {
123 return [
124 [
125 'id' => 242,
126 'name' => 'only text',
127 'channelType' => 'whatsapp',
128 'language' => 'RU',
129 'content' => [
130 'attachment' => null,
131 'action' => null,
132 'caption' => null,
133 'header' => null,
134 'text' => "Hello! Welcome to our platform.",
135 'footer' => null,
136 'keyboard' => null,
137 ],
138 'category' => 'ACCOUNT_UPDATE',
139 'status' => Providers\Edna\Constants\TemplateStatus::PENDING,
140 'locked' => false,
141 'type' => 'OPERATOR',
142 'createdAt' => '2021-07-15T14:16:54.417024Z',
143 'updatedAt' => '2021-07-16T13:08:26.275414Z',
144 ],
145 [
146 'id' => 267,
147 'name' => 'text + header + footer',
148 'channelType' => 'whatsapp',
149 'language' => 'RU',
150 'content' => [
151 'attachment' => null,
152 'action' => null,
153 'caption' => null,
154 'header' => [
155 'text' => 'Greetings',
156 ],
157 'text' => 'Hello! Welcome to our platform.',
158 'footer' => [
159 'text' => 'Have a nice day',
160 ],
161 'keyboard' => null,
162 ],
163 'category' => 'ACCOUNT_UPDATE',
164 'status' => Providers\Edna\Constants\TemplateStatus::APPROVED,
165 'locked' => false,
166 'type' => 'USER',
167 'createdAt' => '2021-07-20T09:21:42.444454Z',
168 'updatedAt' => '2021-07-20T09:21:42.444454Z',
169 ],
170 [
171 'id' => 268,
172 'name' => 'text + buttons',
173 'channelType' => 'whatsapp',
174 'language' => 'RU',
175 'content' => [
176 'attachment' => null,
177 'action' => null,
178 'caption' => null,
179 'header' => null,
180 'text' => "Hello! Welcome to our platform. Have you already tried it?",
181 'footer' => null,
182 'keyboard' => [
183 'rows' => [
184 [
185 'buttons' => [
186 [
187 'text' => 'Yes',
188 'buttonType' => "QUICK_REPLY",
189 'payload' => '1'
190 ],
191 [
192 'text' => 'No',
193 'buttonType' => "QUICK_REPLY",
194 'payload' => '2'
195 ],
196 ],
197 ],
198 ],
199 ],
200
201 ],
202 'category' => 'ACCOUNT_UPDATE',
203 'status' => Providers\Edna\Constants\TemplateStatus::APPROVED,
204 'locked' => false,
205 'type' => 'USER',
206 'createdAt' => '2021-07-20T09:21:42.444454Z',
207 'updatedAt' => '2021-07-20T09:21:42.444454Z',
208 ],
209 [
210 'id' => 269,
211 'name' => 'text + button-link',
212 'channelType' => 'whatsapp',
213 'language' => 'RU',
214 'content' => [
215 'attachment' => null,
216 'action' => null,
217 'caption' => null,
218 'header' => null,
219 'text' => 'Hello! Welcome to our platform. Follow the link bellow to read manuals:',
220 'footer' => null,
221 'keyboard' => [
222 'rows' => [
223 [
224 'buttons' => [
225 [
226 'text' => 'Manual',
227 'buttonType' => "URL",
228 'url' => "https://docs.edna.io/"
229 ],
230 ],
231 ],
232 ],
233 ],
234 ],
235 'category' => 'ACCOUNT_UPDATE',
236 'status' => Providers\Edna\Constants\TemplateStatus::DISABLED,
237 'locked' => false,
238 'type' => 'USER',
239 'createdAt' => '2021-07-20T09:21:42.444454Z',
240 'updatedAt' => '2021-07-20T09:21:42.444454Z',
241 ],
242 ];
243 }
244
245 private function getVerifiedSubjectIdList(array $subjectList): Result
246 {
247 $channelListResult = $this->getChannelList(Providers\Edna\Constants\ChannelType::WHATSAPP);
248 if (!$channelListResult->isSuccess())
249 {
250 return $channelListResult;
251 }
252
253 $filteredSubjectList = [];
254 foreach ($channelListResult->getData() as $channel)
255 {
256 if (isset($channel['subjectId']) && in_array($channel['subjectId'], $subjectList, true))
257 {
258 $filteredSubjectList[] = $channel['subjectId'];
259 }
260 }
261
262 $result = new Result();
263 if (empty($filteredSubjectList))
264 {
265 $result->addError(new Error('Verified subjects are missing'));
266
267 return $result;
268 }
269 $result->setData($filteredSubjectList);
270
271 return $result;
272 }
273
278 protected function checkApprovedStatus(array $template): bool
279 {
280 return isset($template['status']) && $template['status'] === Providers\Edna\Constants\TemplateStatus::APPROVED;
281 }
282
283 protected function checkForPlaceholders(array $templates): array
284 {
285 foreach ($templates as &$template)
286 {
287 $template['placeholders'] = [];
288
289 if (
290 !empty($template['content']['header']['text'])
291 && $this->hasPlaceholder($template['content']['header']['text'])
292 )
293 {
294 $template['placeholders']['header'] = $this->extractPlaceholders($template['content']['header']['text']);
295 }
296
297 if (
298 !empty($template['content']['text'])
299 && $this->hasPlaceholder($template['content']['text'])
300 )
301 {
302 $template['placeholders']['text'] = $this->extractPlaceholders($template['content']['text']);
303 }
304
305 if (
306 !empty($template['content']['footer']['text'])
307 && $this->hasPlaceholder($template['content']['footer']['text'])
308 )
309 {
310 $template['placeholders']['footer'] = $this->extractPlaceholders($template['content']['footer']['text']);
311 }
312 }
313
314 return $templates;
315 }
316
317 protected function hasPlaceholder(string $text): bool
318 {
319 return !empty($text) && preg_match("/{{[\d]+}}/", $text);
320 }
321
322 protected function extractPlaceholders(string $text): array
323 {
324 preg_match_all("/({{[\d]+}})/", $text, $matches);
325
326 return !empty($matches[0]) ? $matches[0] : [];
327 }
328
329 protected function checkForErrors(array $templates): Result
330 {
331 $checkResult = new Result();
332 foreach ($templates as $template)
333 {
334 if (!is_array($template))
335 {
336 $exception = new \Bitrix\Main\SystemException(
337 'Incorrect response from the Edna service: ' . var_export($templates, true)
338 );
339
340 \Bitrix\Main\Application::getInstance()->getExceptionHandler()->writeToLog($exception);
341
342 return $checkResult->addError(
343 new Error('Incorrect response from the Edna service.', 400, $templates)
344 );
345 }
346 }
347
348 return $checkResult;
349 }
350
351 protected function removeUnsupportedTemplates(array $templates): array
352 {
353 $filteredTemplates = [];
354 foreach ($templates as $template)
355 {
356 if (!is_array($template))
357 {
358 continue;
359 }
360
361 if (!$this->checkApprovedStatus($template))
362 {
363 continue;
364 }
365
366 $filteredTemplates[] = $template;
367 }
368
369 return $filteredTemplates;
370 }
371}
getSentTemplateMessage(string $from, string $to)
Definition Utils.php:100