Bitrix-D7 23.9
 
Загрузка...
Поиск...
Не найдено
rest.php
1<?php
3
14
15Loc::loadMessages(__FILE__);
16
17class Rest extends Sender\Base
18{
19 public const ID = 'rest';
20
21 public static $langFields;
22 public static ?int $countRestApps = null;
23
24 public static function isSupported(): bool
25 {
27 }
28
29 public function getId(): string
30 {
31 return static::ID;
32 }
33
34 public function getName(): ?string
35 {
36 return Loc::getMessage('MESSAGESERVICE_SENDER_SMS_REST_NAME');
37 }
38
39 public function getShortName(): string
40 {
41 return 'REST';
42 }
43
44 public function canUse(): bool
45 {
46 if (Loader::includeModule('rest') && \Bitrix\Rest\OAuthService::getEngine()->isRegistered())
47 {
48 static::$countRestApps ??= RestAppTable::getCount();
49
50 return static::$countRestApps > 0;
51 }
52
53 return false;
54 }
55
56 public function getFromList(): array
57 {
58 $list = [];
59 if (!$this->canUse())
60 {
61 return $list;
62 }
63
64 $result = RestAppTable::getList();
65 while ($row = $result->fetch())
66 {
67 $list[] = [
68 'id' => $row['APP_ID'].'|'.$row['CODE'],
69 'name' => sprintf('[%s] %s',
70 $this->getLangField($row['ID'], 'APP_NAME'),
71 $this->getLangField($row['ID'], 'NAME')
72 ),
73 'description' => $this->getLangField($row['ID'], 'DESCRIPTION')
74 ];
75 }
76 return $list;
77 }
78
79 public function isCorrectFrom($from): bool
80 {
81 [$appId, $code] = explode('|', $from);
82 $restSender = RestAppTable::getList(
83 [
84 'filter' => [
85 '=APP_ID' => $appId,
86 '=CODE' => $code
87 ],
88 'select' => ['ID']
89 ]
90 )->fetch();
91
92 return $restSender !== false;
93 }
94
95 public function sendMessage(array $messageFields): Result\SendMessage
96 {
97 $sendResult = new Result\SendMessage();
98
99 if (!$this->canUse())
100 {
101 $sendResult->addError(new Error(Loc::getMessage('MESSAGESERVICE_SENDER_SMS_REST_ERROR_APP_NOT_FOUND')));
102 return $sendResult;
103 }
104
105 [$appId, $code] = explode('|', $messageFields['MESSAGE_FROM']);
106 $restSender = null;
107
108 if ($appId && $code)
109 {
110 $restSender = RestAppTable::getList(
111 ['filter' =>
112 [
113 '=APP_ID' => $appId,
114 '=CODE' => $code
115 ]
116 ]
117 )->fetch();
118 }
119
120 if (!$restSender)
121 {
122 $sendResult->addError(new Error(Loc::getMessage('MESSAGESERVICE_SENDER_SMS_REST_ERROR_APP_NOT_FOUND')));
123 return $sendResult;
124 }
125 /*
126 $session = \Bitrix\Rest\Event\Session::get();
127 if(!$session)
128 {
129 $sendResult->addError(new Error(Loc::getMessage('MESSAGESERVICE_SENDER_SMS_REST_ERROR_SESSION')));
130 return $sendResult;
131 }
132 */
133 $dbRes = \Bitrix\Rest\AppTable::getList([
134 'filter' => [
135 '=CLIENT_ID' => $restSender['APP_ID'],
136 ]
137 ]);
138 $application = $dbRes->fetch();
139
140 if (!$application)
141 {
142 $sendResult->addError(new Error(Loc::getMessage('MESSAGESERVICE_SENDER_SMS_REST_ERROR_APP_NOT_FOUND')));
143 return $sendResult;
144 }
145
146 $appStatus = \Bitrix\Rest\AppTable::getAppStatusInfo($application, '');
147 if($appStatus['PAYMENT_ALLOW'] === 'N')
148 {
149 $sendResult->addError(new Error(Loc::getMessage('MESSAGESERVICE_SENDER_SMS_REST_ERROR_PAYMENT_ALLOW')));
150 return $sendResult;
151 }
152
153 $auth = $messageFields['AUTHOR_ID'] > 0 ? [
154 'CODE' => $restSender['CODE'],
155 \Bitrix\Rest\Event\Session::PARAM_SESSION => \Bitrix\Rest\Event\Session::get(),
156 \Bitrix\Rest\OAuth\Auth::PARAM_LOCAL_USER => $messageFields['AUTHOR_ID'],
157 "application_token" => \CRestUtil::getApplicationToken($application),
158 ] : [];
159
160 $messageId = $messageFields['EXTERNAL_ID'] ?? 0;
161 if (!$messageId)
162 {
163 $messageId = md5(($messageFields['ID'] ?? 0).'|'.uniqid());
164 $this->setExternalMessageId((int)$messageFields['ID'], $messageId);
165 }
166
167 $restData = is_array($messageFields['MESSAGE_HEADERS']) ? $messageFields['MESSAGE_HEADERS'] : array();
168 //compatible parameters
169 $restData['properties'] = [
170 'phone_number' => $messageFields['MESSAGE_TO'],
171 'message_text' => $this->prepareMessageBodyForSend($messageFields['MESSAGE_BODY']),
172 ];
173 $restData['type'] = $restSender['TYPE'];
174 $restData['code'] = $restSender['CODE'];
175 $restData['message_id'] = $messageId;
176 $restData['message_to'] = $messageFields['MESSAGE_TO'];
177 $restData['message_body'] = $this->prepareMessageBodyForSend($messageFields['MESSAGE_BODY']);
178 $restData['ts'] = time();
179
180 $queryItems = [
182 $restSender['APP_ID'],
183 $restSender['HANDLER'],
184 $restData,
185 $auth,
186 [
187 "sendAuth" => (bool)$auth,
188 "sendRefreshToken" => false,
189 "category" => Sqs::CATEGORY_DEFAULT,
190 ]
191 ),
192 ];
193
194 \Bitrix\Rest\OAuthService::getEngine()->getClient()->sendEvent($queryItems);
195 $sendResult->setExternalId($messageId);
196 $sendResult->setStatus(MessageService\MessageStatus::SENT);
197
198 if ($application['CODE'])
199 {
200 AddEventToStatFile(
201 'messageservice',
202 'sendRest' . $restSender['TYPE'],
203 uniqid($application['CODE'], true),
204 $application['CODE']
205 );
206 }
207
208 if (is_callable(['\Bitrix\Rest\UsageStatTable', 'logMessage']))
209 {
210 \Bitrix\Rest\UsageStatTable::logMessage($application['CLIENT_ID'], $restSender['TYPE']);
211 \Bitrix\Rest\UsageStatTable::finalize();
212 }
213
214 return $sendResult;
215 }
216
217 public static function resolveStatus($serviceStatus): int
218 {
219 $status = parent::resolveStatus($serviceStatus);
220
221 switch ((string)$serviceStatus)
222 {
223 case 'queued':
224 return MessageService\MessageStatus::QUEUED;
225 break;
226 case 'sent':
227 return MessageService\MessageStatus::SENT;
228 break;
229 case 'delivered':
230 return MessageService\MessageStatus::DELIVERED;
231 break;
232 case 'undelivered':
233 return MessageService\MessageStatus::UNDELIVERED;
234 break;
235 case 'failed':
236 return MessageService\MessageStatus::FAILED;
237 break;
238 }
239
240 return $status;
241 }
242
243 private function getLangField($appId, $fieldName)
244 {
245 $fields = $this->getAppLangFields($appId);
246 if (!$fields)
247 {
248 return '';
249 }
250
251 $fieldLangs = $fields[$fieldName];
252 if (isset($fieldLangs[LANGUAGE_ID]))
253 {
254 return $fieldLangs[LANGUAGE_ID];
255 }
256 else
257 {
258 $defaultLang = Loc::getDefaultLang(LANGUAGE_ID);
259 if (isset($fieldLangs[$defaultLang]))
260 {
261 return $fieldLangs[$defaultLang];
262 }
263 }
264 return $fieldLangs['**'];
265 }
266
267 private function getAppLangFields($appId)
268 {
269 if (static::$langFields === null)
270 {
271 $orm = RestAppLangTable::getList();
272 while ($row = $orm->fetch())
273 {
274 static::$langFields[$row['APP_ID']]['NAME'][$row['LANGUAGE_ID']] = $row['NAME'];
275 static::$langFields[$row['APP_ID']]['APP_NAME'][$row['LANGUAGE_ID']] = $row['APP_NAME'];
276 static::$langFields[$row['APP_ID']]['DESCRIPTION'][$row['LANGUAGE_ID']] = $row['DESCRIPTION'];
277 }
278 }
279
280 return static::$langFields[$appId] ?? null;
281 }
282
283 private function setExternalMessageId(int $internalId, string $externalId): void
284 {
285 MessageService\Internal\Entity\MessageTable::update($internalId, [
286 'EXTERNAL_ID' => $externalId
287 ]);
288 }
289}
static includeModule($moduleName)
Definition loader.php:69
static loadMessages($file)
Definition loc.php:64
static getDefaultLang($lang)
Definition loc.php:460
static getMessage($code, $replace=null, $language=null)
Definition loc.php:29
static isModuleInstalled($moduleName)
prepareMessageBodyForSend(string $text)
Definition base.php:176
sendMessage(array $messageFields)
Definition rest.php:95
static resolveStatus($serviceStatus)
Definition rest.php:217
static queryItem($clientId, $url, $data, array $authData=array(), array $additional=array())
Definition sqs.php:18
const CATEGORY_DEFAULT
Definition sqs.php:11