1C-Bitrix 25.700.0
Загрузка...
Поиск...
Не найдено
im_rest.php
См. документацию.
1<?php
2
10
11if (!CModule::IncludeModule('rest'))
12{
13 return;
14}
15
17{
18 public static function OnRestServiceBuildDescription()
19 {
20 return array(
21 'im' => array(
22 'im.user.get' => array(__CLASS__, 'userGet'),
23 'im.user.list.get' => array(__CLASS__, 'userList'),
24 'im.user.business.list' => array(__CLASS__, 'userBusinessList'),
25 'im.user.business.get' => array('callback' => array(__CLASS__, 'userBusinessList'), 'options' => array('private' => true)),
26
27 'im.user.status.get' => array(__CLASS__, 'userStatusGet'),
28 'im.user.status.set' => array(__CLASS__, 'userStatusSet'),
29 'im.user.status.idle.start' => array(__CLASS__, 'userStatusIdleStart'),
30 'im.user.status.idle.end' => array(__CLASS__, 'userStatusIdleEnd'),
31
32 'im.recent.get' => array(__CLASS__, 'recentGet'),
33 'im.recent.list' => array(__CLASS__, 'recentList'),
34 'im.recent.pin' => array(__CLASS__, 'recentPin'),
35 'im.recent.hide' => array(__CLASS__, 'recentHide'),
36 'im.recent.unread' => array(__CLASS__, 'recentUnread'),
37
38 'im.department.get' => array(__CLASS__, 'departmentGet'),
39 'im.department.colleagues.list' => array(__CLASS__, 'departmentColleaguesList'),
40 'im.department.colleagues.get' => array('callback' => array(__CLASS__, 'departmentColleaguesList'), 'options' => array('private' => true)),
41 'im.department.managers.get' => array(__CLASS__, 'departmentManagersGet'),
42 'im.department.employees.get' => array(__CLASS__, 'departmentEmployeesGet'),
43
44 'im.chat.add' => array(__CLASS__, 'chatCreate'),
45 'im.chat.getEntityChat' => array(__CLASS__, 'chatGetEntityChat'),
46 'im.chat.get' => array(__CLASS__, 'chatGet'),
47 'im.chat.setOwner' => array(__CLASS__, 'chatSetOwner'),
48 'im.chat.setManager' => array(__CLASS__, 'chatSetManager'),
49 'im.chat.updateColor' => array(__CLASS__, 'chatUpdateColor'),
50 'im.chat.updateTitle' => array(__CLASS__, 'chatUpdateTitle'),
51 'im.chat.updateAvatar' => array(__CLASS__, 'chatUpdateAvatar'),
52 'im.chat.leave' => array(__CLASS__, 'chatUserDelete'),
53 'im.chat.user.add' => array(__CLASS__, 'chatUserAdd'),
54 'im.chat.user.delete' => array(__CLASS__, 'chatUserDelete'),
55 'im.chat.user.list' => array(__CLASS__, 'chatUserList'),
56 'im.chat.sendTyping' => array('callback' => array(__CLASS__, 'dialogWriting'), 'options' => array('private' => true)),
57 'im.chat.mute' => array(__CLASS__, 'chatMute'),
58 'im.chat.parent.join' => array('callback' => array(__CLASS__, 'chatParentJoin'), 'options' => array('private' => true)),
59 'im.chat.url.get' => array('callback' => array(__CLASS__, 'chatUrlGet'), 'options' => array('private' => true)),
60 'im.chat.url.delete' => array('callback' => array(__CLASS__, 'chatUrlDelete'), 'options' => array('private' => true)),
61 'im.chat.url.counter.get' => array('callback' => array(__CLASS__, 'chatUrlCounterGet'), 'options' => array('private' => true)),
62 'im.chat.file.get' => array('callback' => array(__CLASS__, 'chatFileGet'), 'options' => array('private' => true)),
63 'im.chat.file.collection.get' => array('callback' => array(__CLASS__, 'chatFileCollectionGet'), 'options' => array('private' => true)),
64 'im.chat.favorite.get' => array('callback' => array(__CLASS__, 'chatFavoriteGet'), 'options' => array('private' => true)),
65 'im.chat.favorite.add' => array('callback' => array(__CLASS__, 'chatFavoriteAdd'), 'options' => array('private' => true)),
66 'im.chat.favorite.delete' => array('callback' => array(__CLASS__, 'chatFavoriteDelete'), 'options' => array('private' => true)),
67 'im.chat.favorite.counter.get' => array('callback' => array(__CLASS__, 'chatFavoriteCounterGet'), 'options' => array('private' => true)),
68 'im.chat.task.get' => array('callback' => array(__CLASS__, 'chatTaskGet'), 'options' => array('private' => true)),
69 'im.chat.task.delete' => array('callback' => array(__CLASS__, 'chatTaskDelete'), 'options' => array('private' => true)),
70 'im.chat.task.prepare' => array('callback' => array(__CLASS__, 'chatTaskPrepare'), 'options' => array('private' => true)),
71 'im.chat.calendar.get' => array('callback' => array(__CLASS__, 'chatCalendarGet'), 'options' => array('private' => true)),
72 'im.chat.calendar.add' => array('callback' => array(__CLASS__, 'chatCalendarAdd'), 'options' => array('private' => true)),
73 'im.chat.calendar.delete' => array('callback' => array(__CLASS__, 'chatCalendarDelete'), 'options' => array('private' => true)),
74 'im.chat.calendar.prepare' => array('callback' => array(__CLASS__, 'chatCalendarPrepare'), 'options' => array('private' => true)),
75 'im.chat.sign.get' => array('callback' => array(__CLASS__, 'chatSignGet'), 'options' => array('private' => true)),
76 'im.chat.pin.get' => array('callback' => array(__CLASS__, 'chatPinGet'), 'options' => array('private' => true)),
77 'im.chat.pin.add' => array('callback' => array(__CLASS__, 'chatPinAdd'), 'options' => array('private' => true)),
78 'im.chat.pin.delete' => array('callback' => array(__CLASS__, 'chatPinDelete'), 'options' => array('private' => true)),
79 'im.chat.reminder.get' => array('callback' => array(__CLASS__, 'chatReminderGet'), 'options' => array('private' => true)),
80 'im.chat.reminder.add' => array('callback' => array(__CLASS__, 'chatReminderAdd'), 'options' => array('private' => true)),
81 'im.chat.reminder.delete' => array('callback' => array(__CLASS__, 'chatReminderDelete'), 'options' => array('private' => true)),
82
83 'im.dialog.get' => array(__CLASS__, 'dialogGet'),
84 'im.dialog.messages.get' => array(__CLASS__, 'dialogMessagesGet'),
85 'im.dialog.messages.search' => array('callback' => array(__CLASS__, 'dialogMessagesSearch'), 'options' => array('private' => true)),
86 'im.dialog.context.get' => array('callback' => array(__CLASS__, 'dialogContextGet'), 'options' => array('private' => true)),
87 'im.dialog.users.get' => array('callback' => array(__CLASS__, 'dialogUsersGet'), 'options' => array('private' => true)),
88 'im.dialog.users.list' => array(__CLASS__, 'dialogUsersList'),
89 'im.dialog.read' => array(__CLASS__, 'dialogRead'),
90 'im.dialog.readAll' => array('callback' => array(__CLASS__, 'dialogReadAll'), 'options' => array('private' => true)),
91 'im.dialog.read.all' => array(__CLASS__, 'dialogReadAll'),
92 'im.dialog.unread' => array(__CLASS__, 'dialogUnread'),
93 'im.dialog.writing' => array(__CLASS__, 'dialogWriting'),
94
95 'im.message.add' => array(__CLASS__, 'messageAdd'),
96 'im.message.delete' => array(__CLASS__, 'messageDelete'),
97 'im.message.update' => array(__CLASS__, 'messageUpdate'),
98 'im.message.like' => array(__CLASS__, 'messageLike'),
99 'im.message.command' => array('callback' => array(__CLASS__, 'messageCommand')),
100 'im.message.share' => array('callback' => array(__CLASS__, 'messageShare')),
101 'im.message.user.get' => array('callback' => array(__CLASS__, 'messageUserGet'), 'options' => array('private' => true)),
102
103 'im.notify' => array('callback' => array(__CLASS__, 'notifyAdd'), 'options' => array('private' => false)),
104 'im.notify.get' => array('callback' => array(__CLASS__, 'notifyGet'), 'options' => array('private' => true)),
105 'im.notify.personal.add' => array(__CLASS__, 'notifyAdd'),
106 'im.notify.system.add' => array(__CLASS__, 'notifyAdd'),
107 'im.notify.delete' => array(__CLASS__, 'notifyDelete'),
108 'im.notify.read' => array(__CLASS__, 'notifyRead'),
109 'im.notify.read.list' => array(__CLASS__, 'notifyReadList'),
110 'im.notify.read.all' => array(__CLASS__, 'notifyReadAll'),
111 'im.notify.confirm' => array(__CLASS__, 'notifyConfirm'),
112 'im.notify.answer' => array(__CLASS__, 'notifyAnswer'),
113 'im.notify.history.search' => array('callback' => array(__CLASS__, 'notifyHistorySearch'), 'options' => array('private' => true)),
114 'im.notify.schema.get' => array('callback' => array(__CLASS__, 'notifySchemaGet'), 'options' => array('private' => true)),
115
116 'im.disk.folder.list.get' => array('callback' => array(__CLASS__, 'diskFolderListGet'), 'options' => array('private' => true)),
117 'im.disk.folder.get' => array(__CLASS__, 'diskFolderGet'),
118 'im.disk.file.commit' => array(__CLASS__, 'diskFileCommit'),
119 'im.disk.file.delete' => array(__CLASS__, 'diskFileDelete'),
120 'im.disk.file.save' => array(__CLASS__, 'diskFileSave'),
121 'im.disk.record.share' => array(__CLASS__, 'diskRecordShare'),
122
123 'im.counters.get' => array(__CLASS__, 'counterGet'),
124
125 'im.search.user.list' => array(__CLASS__, 'searchUser'),
126 'im.search.user' => array('callback' => array(__CLASS__, 'searchUser'), 'options' => array('private' => true)),
127 'im.search.chat.list' => array(__CLASS__, 'searchChat'),
128 'im.search.chat' => array('callback' => array(__CLASS__, 'searchChat'), 'options' => array('private' => true)),
129 'im.search.department.list' => array(__CLASS__, 'searchDepartment'),
130 'im.search.department' => array('callback' => array(__CLASS__, 'searchDepartment'), 'options' => array('private' => true)),
131
132 'im.search.last.get' => array(__CLASS__, 'searchLastGet'),
133 'im.search.last.add' => array(__CLASS__, 'searchLastAdd'),
134 'im.search.last.delete' => array(__CLASS__, 'searchLastDelete'),
135
136 'im.promotion.get' => array('callback' => array(__CLASS__, 'promotionGet'), 'options' => array('private' => true)),
137 'im.promotion.read' => array('callback' => array(__CLASS__, 'promotionRead'), 'options' => array('private' => true)),
138
139 'im.mobile.config.get' => array('callback' => array(__CLASS__, 'mobileConfigGet'), 'options' => array('private' => true)),
140
141 'im.call.user.register' => array('callback' => array(__CLASS__, 'callUserRegister'), 'options' => array('private' => true)),
142 'im.call.user.update' => array('callback' => array(__CLASS__, 'callUserUpdate'), 'options' => array('private' => true)),
143 'im.call.user.force.rename' => array('callback' => array(__CLASS__, 'callUserForceRename'), 'options' => array('private' => true)),
144 'im.call.channel.public.list' => array('callback' => array(__CLASS__, 'callChannelPublicList'), 'options' => array('private' => true)),
145
146 'im.videoconf.share.change' => array('callback' => array(__CLASS__, 'videoconfShareChange'), 'options' => array('private' => true)),
147 'im.videoconf.password.check' => array('callback' => array(__CLASS__, 'videoconfPasswordCheck'), 'options' => array('private' => true)),
148 'im.videoconf.add' => array('callback' => array(__CLASS__, 'videoconfAdd'), 'options' => array('private' => true)),
149 'im.videoconf.update' => array('callback' => array(__CLASS__, 'videoconfUpdate'), 'options' => array('private' => true)),
150
151 'im.desktop.status.get' => array('callback' => array(__CLASS__, 'desktopStatusGet'), 'options' => array('private' => true)),
152 'im.desktop.page.open' => array('callback' => array(__CLASS__, 'desktopPageOpen'), 'options' => array('private' => true)),
153 ),
154 'imbot' => Array(
155 'imbot.register' => array(__CLASS__, 'botRegister'),
156 'imbot.unregister' => array(__CLASS__, 'botUnRegister'),
157 'imbot.update' => array(__CLASS__, 'botUpdate'),
158
159 'imbot.dialog.get' => array(__CLASS__, 'dialogGet'),
160 'imbot.dialog.vote' => array(__CLASS__, 'dialogVote'),
161
162 'imbot.chat.add' => array(__CLASS__, 'chatCreate'),
163 'imbot.chat.get' => array(__CLASS__, 'chatGet'),
164 'imbot.chat.setOwner' => array(__CLASS__, 'chatSetOwner'),
165 'imbot.chat.setManager' => array(__CLASS__, 'chatSetManager'),
166 'imbot.chat.updateColor' => array(__CLASS__, 'chatUpdateColor'),
167 'imbot.chat.updateTitle' => array(__CLASS__, 'chatUpdateTitle'),
168 'imbot.chat.updateAvatar' => array(__CLASS__, 'chatUpdateAvatar'),
169 'imbot.chat.leave' => array(__CLASS__, 'chatUserDelete'),
170 'imbot.chat.user.add' => array(__CLASS__, 'chatUserAdd'),
171 'imbot.chat.user.delete' => array(__CLASS__, 'chatUserDelete'),
172 'imbot.chat.user.list' => array(__CLASS__, 'chatUserList'),
173 'imbot.chat.sendTyping' => array(__CLASS__, 'botSendTyping'),
174 'imbot.chat.updateTextFieldEnabled' => array(__CLASS__, 'botUpdateTextFieldEnabled'),
175
176 'imbot.bot.list' => array(__CLASS__, 'botList'),
177
178 'imbot.message.add' => array(__CLASS__, 'botMessageAdd'),
179 'imbot.message.delete' => array(__CLASS__, 'botMessageDelete'),
180 'imbot.message.update' => array(__CLASS__, 'botMessageUpdate'),
181 'imbot.message.like' => array(__CLASS__, 'botMessageLike'),
182
183 'imbot.sendTyping' => array('callback' => array(__CLASS__, 'botSendTyping'), 'options' => array('private' => true)),
184
185 'imbot.command.register' => array(__CLASS__, 'commandRegister'),
186 'imbot.command.unregister' => array(__CLASS__, 'commandUnRegister'),
187 'imbot.command.update' => array(__CLASS__, 'commandUpdate'),
188 'imbot.command.answer' => array(__CLASS__, 'commandAnswer'),
189
190 'imbot.app.register' => array('callback' => array(__CLASS__, 'appRegister'), 'options' => array('private' => false)),
191 'imbot.app.unregister' => array('callback' => array(__CLASS__, 'appUnRegister'), 'options' => array('private' => false)),
192 'imbot.app.update' => array('callback' => array(__CLASS__, 'appUpdate'), 'options' => array('private' => false)),
193
194 CRestUtil::EVENTS => array(
195 'OnImBotMessageAdd' => array('im', 'onImBotMessageAdd', array(__CLASS__, 'onBotMessageAdd'), array("category" => \Bitrix\Rest\Sqs::CATEGORY_BOT, "sendRefreshToken" => true)),
196 'OnImBotMessageUpdate' => array('im', 'onImBotMessageUpdate', array(__CLASS__, 'onBotMessageUpdate'), array("category" => \Bitrix\Rest\Sqs::CATEGORY_BOT, "sendRefreshToken" => true)),
197 'OnImBotMessageDelete' => array('im', 'onImBotMessageDelete', array(__CLASS__, 'onBotMessageDelete'), array("category" => \Bitrix\Rest\Sqs::CATEGORY_BOT, "sendRefreshToken" => true)),
198 'OnImBotJoinChat' => array('im', 'onImBotJoinChat', array(__CLASS__, 'onBotJoinChat'), array("category" => \Bitrix\Rest\Sqs::CATEGORY_BOT)),
199 'OnImBotDelete' => array('im', 'onImBotDelete', array(__CLASS__, 'onBotDelete'), array("category" => \Bitrix\Rest\Sqs::CATEGORY_BOT)),
200 'OnImBotContextGet' => array('im', 'onImBotContextGet', array(__CLASS__, 'onBotContextGet'), array("category" => \Bitrix\Rest\Sqs::CATEGORY_BOT, "sendRefreshToken" => true)),
201 'OnImCommandAdd' => array('im', 'onImCommandAdd', array(__CLASS__, 'onCommandAdd'), array("category" => \Bitrix\Rest\Sqs::CATEGORY_BOT, "sendRefreshToken" => true)),
202 ),
203 )
204 );
205 }
206
207 public static function OnRestAppDelete($arParams)
208 {
209 if(!\Bitrix\Main\Loader::includeModule('rest'))
210 {
211 return;
212 }
213 $result = \Bitrix\Rest\AppTable::getList(array('filter' =>array('=ID' => $arParams['APP_ID'])));
214 if ($result = $result->fetch())
215 {
216 $bots = \Bitrix\Im\Bot::getListCache();
217 foreach ($bots as $bot)
218 {
219 if ($bot['APP_ID'] == $result['CLIENT_ID'])
220 {
221 \Bitrix\Im\Bot::unRegister(Array('BOT_ID' => $bot['BOT_ID']));
222 }
223 }
224 }
225 }
226
227 /* User api */
228 public static function userGet($arParams, $n, CRestServer $server)
229 {
230 $arParams = array_change_key_case($arParams, CASE_UPPER);
231
232 $userId = null;
233 if (isset($arParams['ID']))
234 {
235 $userId = intval($arParams['ID']);
236 if ($userId <= 0)
237 {
238 throw new Bitrix\Rest\RestException("User ID can't be empty", "ID_EMPTY", CRestServer::STATUS_WRONG_REQUEST);
239 }
240 }
241
243 if ($user->isExists())
244 {
245 $userId = $user->getId();
246 }
247 else
248 {
249 throw new Bitrix\Rest\RestException("User is not exists", "USER_NOT_EXISTS", CRestServer::STATUS_WRONG_REQUEST);
250 }
251
252 $currentUserId = \Bitrix\Im\User::getInstance()->getId();
253 $isExtranet = \Bitrix\Im\User::getInstance()->isExtranet();
254
255 if ($isExtranet && !\Bitrix\Im\Integration\Socialnetwork\Extranet::isUserInGroup($userId, $currentUserId))
256 {
257 throw new Bitrix\Rest\RestException("You can request only users who consist of your extranet group", "ACCESS_DENIED", CRestServer::STATUS_WRONG_REQUEST);
258 }
259
260 $result = $user->getArray(Array('JSON' => 'Y', 'HR_PHOTO' => isset($arParams['AVATAR_HR']) && $arParams['AVATAR_HR'] == 'Y'));
261
262 $result['desktop_last_date'] = \CIMMessenger::GetDesktopStatusOnline($userId);
263 $result['desktop_last_date'] = $result['desktop_last_date']? date('c', $result['desktop_last_date']): false;
264
265 return $result;
266 }
267
268 public static function userList($arParams, $offset, CRestServer $server)
269 {
270 $arParams = array_change_key_case($arParams, CASE_UPPER);
271
272 $users = Array();
273 if (is_string($arParams['ID']))
274 {
275 $arParams['ID'] = \CUtil::JsObjectToPhp($arParams['ID'], true);
276 }
277 if (is_array($arParams['ID']))
278 {
279 foreach ($arParams['ID'] as $userId)
280 {
281 $userId = intval($userId);
282 if ($userId > 0)
283 {
284 $users[$userId] = $userId;
285 }
286 }
287 }
288
289 if (empty($users))
290 {
291 throw new Bitrix\Rest\RestException("A wrong format for the ID field is passed", "INVALID_FORMAT", CRestServer::STATUS_WRONG_REQUEST);
292 }
293
294 $currentUserId = \Bitrix\Im\User::getInstance()->getId();
295 $isExtranet = \Bitrix\Im\User::getInstance()->isExtranet();
296
297 $extranetUsers = Array($currentUserId);
298 if ($isExtranet)
299 {
301 if (is_array($groups))
302 {
303 foreach ($groups as $group)
304 {
305 foreach ($group['USERS'] as $userId)
306 {
307 $extranetUsers[$userId] = $userId;
308 }
309 }
310 }
311 }
312
313 $result = Array();
314 foreach ($users as $userId)
315 {
316 if ($isExtranet && !isset($extranetUsers[$userId]))
317 {
318 continue;
319 }
320
321 $result[$userId] = \Bitrix\Im\User::getInstance($userId)->getArray(Array('JSON' => 'Y', 'HR_PHOTO' => isset($arParams['AVATAR_HR']) && $arParams['AVATAR_HR'] == 'Y'));
322 }
323
324 $arParams['RESULT_TYPE'] ??= '';
325 if (mb_strtolower(($arParams['RESULT_TYPE'] ?? '')) === 'array')
326 {
327 $result = array_values($result);
328 }
329
330 return $result;
331 }
332
333 public static function userBusinessList($arParams, $offset, CRestServer $server)
334 {
335 $arParams = array_change_key_case($arParams, CASE_UPPER);
336
337 $withUserData = $arParams['USER_DATA'] == 'Y';
338
339 $params['OFFSET'] = intval($offset) > 0? intval($offset): (isset($arParams['OFFSET']) && intval($arParams['OFFSET']) > 0? intval($arParams['OFFSET']): 0);
340 $params['LIMIT'] = isset($arParams['LIMIT'])? (intval($arParams['LIMIT']) > 50? 50: intval($arParams['LIMIT'])): 10;
341
342 $result = \Bitrix\Im\User::getBusiness(null, array('JSON' => 'Y', 'USER_DATA' => $withUserData? 'Y': 'N', 'LIST' => $params));
343 if ($result['available'])
344 {
346 $result['result'],
347 array(
348 "count" => $result['total'],
349 "offset" => $params['OFFSET']
350 )
351 );
352 }
353 else
354 {
355 $result = false;
356 }
357
358 return $result;
359 }
360 /* Status api */
361
362 public static function userStatusGet($params, $n, \CRestServer $server)
363 {
365 $result = \CIMStatus::GetStatus($userId);
366 if (!$result)
367 {
368 return false;
369 }
370
371 return $result['STATUS'];
372 }
373
374 public static function userStatusSet($params, $n, \CRestServer $server)
375 {
376 $params = array_change_key_case($params, CASE_UPPER);
377
378 if (!is_string($params['STATUS']))
379 {
380 $params['STATUS'] = mb_strtolower($params['STATUS']);
381 }
382
383 if (!in_array($params['STATUS'], \CIMStatus::$AVAILABLE_STATUSES))
384 {
385 throw new Bitrix\Rest\RestException("Status is not available", "STATUS_ERROR", CRestServer::STATUS_WRONG_REQUEST);
386 }
387
389
391
392 return true;
393 }
394
395 public static function userStatusIdleStart($params, $n, \CRestServer $server)
396 {
397 $params = array_change_key_case($params, CASE_UPPER);
398
400
401 if (isset($params['AGO']))
402 {
403 $ago = intval($params['AGO']);
404 if ($ago <= 1)
405 {
406 $ago = 1;
407 }
408 }
409 else
410 {
411 $ago = 10;
412 }
413
414 \CIMStatus::SetIdle($userId, true, $ago);
415
416 return true;
417 }
418
419 public static function userStatusIdleEnd($params, $n, \CRestServer $server)
420 {
422
423 \CIMStatus::SetIdle($userId, false);
424
425 return true;
426 }
427
428 /* Dialog api */
429
430 public static function dialogGet($arParams, $offset, CRestServer $server)
431 {
432 $arParams = array_change_key_case($arParams, CASE_UPPER);
433
434 if (!\Bitrix\Im\Common::isDialogId($arParams['DIALOG_ID']))
435 {
436 throw new Bitrix\Rest\RestException("Dialog ID can't be empty", "DIALOG_ID_EMPTY", CRestServer::STATUS_WRONG_REQUEST);
437 }
438
439 if (!\Bitrix\Im\Dialog::hasAccess($arParams['DIALOG_ID']))
440 {
441 throw new Bitrix\Rest\RestException("You do not have access to the specified dialog", "ACCESS_ERROR", CRestServer::STATUS_FORBIDDEN);
442 }
443
444 $chatId = \Bitrix\Im\Dialog::getChatId($arParams['DIALOG_ID']);
445 if (!$chatId)
446 {
447 throw new Bitrix\Rest\RestException("You don't have access to this chat", "ACCESS_ERROR", CRestServer::STATUS_WRONG_REQUEST);
448 }
449
450 $result = \Bitrix\Im\Chat::getById($chatId, ['LOAD_READED' => true, 'JSON' => true]);
451 if (!$result)
452 {
453 throw new Bitrix\Rest\RestException("You don't have access to this chat", "ACCESS_ERROR", CRestServer::STATUS_WRONG_REQUEST);
454 }
455
456 $result['dialog_id'] = $arParams['DIALOG_ID'];
457
458 return $result;
459
460 }
461
462 public static function dialogMessagesGet($arParams, $offset, CRestServer $server)
463 {
464 $arParams = array_change_key_case($arParams, CASE_UPPER);
465
466 if (isset($arParams['CHAT_ID']) && intval($arParams['CHAT_ID']) > 0)
467 {
468 $arParams['DIALOG_ID'] = 'chat'.$arParams['CHAT_ID'];
469 }
470
471 if (!\Bitrix\Im\Common::isDialogId($arParams['DIALOG_ID']))
472 {
473 throw new Bitrix\Rest\RestException("Dialog ID can't be empty", "DIALOG_ID_EMPTY", CRestServer::STATUS_WRONG_REQUEST);
474 }
475
476 if (!\Bitrix\Im\Dialog::hasAccess($arParams['DIALOG_ID']))
477 {
478 throw new Bitrix\Rest\RestException("You do not have access to the specified dialog", "ACCESS_ERROR", CRestServer::STATUS_FORBIDDEN);
479 }
480
481 $chatId = \Bitrix\Im\Dialog::getChatId($arParams['DIALOG_ID']);
482
483 if (isset($arParams['FIRST_ID']))
484 {
485 if (!preg_match('/^\d{1,}$/i', $arParams['FIRST_ID']))
486 {
487 throw new Bitrix\Rest\RestException("First ID can't be string", "FIRST_ID_STRING", CRestServer::STATUS_WRONG_REQUEST);
488 }
489 $options['FIRST_ID'] = intval($arParams['FIRST_ID']);
490 }
491 else if (isset($arParams['LAST_ID']))
492 {
493 if (!preg_match('/^\d{1,}$/i', $arParams['LAST_ID']))
494 {
495 throw new Bitrix\Rest\RestException("Last ID can't be string", "LAST_ID_STRING", CRestServer::STATUS_WRONG_REQUEST);
496 }
497 $options['LAST_ID'] = intval($arParams['LAST_ID']) > 0? intval($arParams['LAST_ID']): 0;
498 }
499 $options['LIMIT'] = isset($arParams['LIMIT'])? (intval($arParams['LIMIT']) > 50? 50: intval($arParams['LIMIT'])): 20;
500 $options['CONVERT_TEXT'] = isset($arParams['CONVERT_TEXT']) && $arParams['CONVERT_TEXT'] == 'Y';
501 $options['JSON'] = 'Y';
502
503 return \Bitrix\Im\Chat::getMessages($chatId, null, $options);
504 }
505
506 public static function dialogMessagesSearch($arParams, $n, CRestServer $server)
507 {
508 $arParams = array_change_key_case($arParams, CASE_UPPER);
509 $filter = [
510 'LAST_ID' => $arParams['LAST_ID'] ?? null,
511 'SEARCH_MESSAGE' => $arParams['SEARCH_MESSAGE'] ?? null,
512 'CHAT_ID' => $arParams['CHAT_ID'] ?? null,
513 'DATE_FROM' => $arParams['DATE_FROM'] ? new DateTime($arParams['DATE_FROM'], DateTimeInterface::RFC3339) : null,
514 'DATE_TO' => $arParams['DATE_TO'] ? new DateTime($arParams['DATE_TO'], DateTimeInterface::RFC3339) : null,
515 'DATE' => $arParams['DATE'] ? new DateTime($arParams['DATE'], DateTimeInterface::RFC3339) : null,
516 ];
517 $limit = self::getLimit($arParams);
518 $order = [
519 'ID' => $arParams['ORDER']['ID'] ?? 'DESC',
520 ];
521 if (!isset($filter['CHAT_ID']))
522 {
523 throw new \Bitrix\Rest\RestException('CHAT_ID can`t be empty', 'CHAT_ID_EMPTY', \CRestServer::STATUS_WRONG_REQUEST);
524 }
525
526 $chatId = $filter['CHAT_ID'];
527 $chat = \Bitrix\Im\V2\Chat::getInstance($chatId);
528
529 if (!$chat->checkAccess()->isSuccess())
530 {
531 throw new \Bitrix\Rest\RestException('You do not have access to this chat', Bitrix\Im\V2\Rest\RestError::ACCESS_ERROR, \CRestServer::STATUS_FORBIDDEN);
532 }
533
534 $startId = $chat->getStartId();
535
536 if ($startId > 0)
537 {
538 $filter['START_ID'] = $startId;
539 }
540
542
543 return (new RestAdapter($messages))->toRestFormat();
544 }
545
546 public static function dialogContextGet($arParams, $n, CRestServer $server)
547 {
548 $arParams = array_change_key_case($arParams, CASE_UPPER);
549 if (!isset($arParams['MESSAGE_ID']) || (int)$arParams['MESSAGE_ID'] <= 0)
550 {
551 throw new Bitrix\Rest\RestException('Message ID can`t be empty', 'MESSAGE_ID_EMPTY', CRestServer::STATUS_WRONG_REQUEST);
552 }
553
554 $messageId = (int)$arParams['MESSAGE_ID'];
555
556 $message = new \Bitrix\Im\V2\Message($messageId);
557
558 if ($message->getMessageId() === null)
559 {
560 throw new \Bitrix\Rest\RestException('Message not found', \Bitrix\Im\V2\Message\MessageError::MESSAGE_NOT_FOUND, \CRestServer::STATUS_WRONG_REQUEST);
561 }
562
563 if (!$message->getChat()->checkAccess()->isSuccess())
564 {
565 throw new \Bitrix\Rest\RestException('You do not have access to this chat', Bitrix\Im\V2\Rest\RestError::ACCESS_ERROR, \CRestServer::STATUS_FORBIDDEN);
566 }
567
568 if (!isset($arParams['RANGE']))
569 {
570 throw new Bitrix\Rest\RestException('Range can`t be empty', 'RANGE_EMPTY', CRestServer::STATUS_WRONG_REQUEST);
571 }
572
573 $range = (int)$arParams['RANGE'];
574 $range = ($range <= 50 && $range >= 0) ? $range : 50;
575
576 $result = (new \Bitrix\Im\V2\Message\MessageService($message))->getMessageContext($range);
577 if (!$result->isSuccess())
578 {
579 $error = $result->getErrors()[0];
580 if (isset($error))
581 {
582 throw new Bitrix\Rest\RestException($error->getMessage(), $error->getCode(), CRestServer::STATUS_WRONG_REQUEST);
583 }
584 }
585
587 $messages = $result->getResult();
588
589 return (new RestAdapter($messages))->toRestFormat();
590 }
591
592 public static function dialogUsersGet($arParams, $n, CRestServer $server)
593 {
594 $arParams = array_change_key_case($arParams, CASE_UPPER);
595
596 if (isset($arParams['CHAT_ID']) && intval($arParams['CHAT_ID']) > 0)
597 {
598 $arParams['DIALOG_ID'] = 'chat'.$arParams['CHAT_ID'];
599 }
600
601 if (!\Bitrix\Im\Common::isDialogId($arParams['DIALOG_ID']))
602 {
603 throw new Bitrix\Rest\RestException("Dialog ID can't be empty", "DIALOG_ID_EMPTY", CRestServer::STATUS_WRONG_REQUEST);
604 }
605
606 if (!\Bitrix\Im\Dialog::hasAccess($arParams['DIALOG_ID']))
607 {
608 throw new Bitrix\Rest\RestException("You do not have access to the specified dialog", "ACCESS_ERROR", CRestServer::STATUS_FORBIDDEN);
609 }
610
611 $chatId = \Bitrix\Im\Dialog::getChatId($arParams['DIALOG_ID']);
612
613 return \Bitrix\Im\Chat::getUsers($chatId, ['JSON' => 'Y']);
614 }
615
616 public static function dialogUsersList($params, $offset, CRestServer $server): Array
617 {
618 $params = array_change_key_case($params, CASE_UPPER);
619 if (!\Bitrix\Im\Common::isDialogId($params['DIALOG_ID']))
620 {
621 throw new Bitrix\Rest\RestException("Dialog ID can't be empty", "DIALOG_ID_EMPTY", CRestServer::STATUS_WRONG_REQUEST);
622 }
623
624 if (!\Bitrix\Im\Dialog::hasAccess($params['DIALOG_ID']))
625 {
626 throw new Bitrix\Rest\RestException("You do not have access to the specified dialog", "ACCESS_ERROR", CRestServer::STATUS_FORBIDDEN);
627 }
628
629 $chatId = \Bitrix\Im\Dialog::getChatId($params['DIALOG_ID']);
630 if (!$chatId)
631 {
632 throw new Bitrix\Rest\RestException("You don't have access to this chat", "ACCESS_ERROR", CRestServer::STATUS_WRONG_REQUEST);
633 }
634
635 $countFilter = [
636 '=CHAT_ID' => $chatId,
637 '=USER.ACTIVE' => 'Y',
638 ];
639 if (
640 isset($params['SKIP_EXTERNAL']) && $params['SKIP_EXTERNAL'] === 'Y'
641 || isset($params['SKIP_EXTERNAL_EXCEPT_TYPES']))
642 {
643 $options['SKIP_EXTERNAL'] = 'Y';
644 $options['SKIP_EXTERNAL_EXCEPT_TYPES'] = array_map('trim', mb_split(',', $params['SKIP_EXTERNAL_EXCEPT_TYPES']));
645
646 $exceptType = $options['SKIP_EXTERNAL_EXCEPT_TYPES'] ?? [];
647 $countFilter['!=USER.EXTERNAL_AUTH_ID'] = \Bitrix\Im\Model\UserTable::filterExternalUserTypes($exceptType);
648 }
649
650 $options['LIMIT'] = self::getLimit($params);
651 $options['JSON'] = true;
652
653 if (isset($params['LAST_ID']) && (int)$params['LAST_ID'] >= 0)
654 {
655 $options['LAST_ID'] = (int)$params['LAST_ID'];
656
657 return \Bitrix\Im\Chat::getUsers($chatId, $options);
658 }
659
660 $counter = \Bitrix\Im\Model\RelationTable::getCount($countFilter);
661 $options['OFFSET'] = self::getOffset($offset, $params);
662
663 $result = Array();
664 if ($counter > 0)
665 {
667 }
668
669 return self::setNavData(
670 $result,
671 array(
672 "count" => $counter,
673 "offset" => $options['OFFSET']
674 )
675 );
676 }
677
678 public static function dialogWriting($arParams, $n, CRestServer $server)
679 {
680 $arParams = array_change_key_case($arParams, CASE_UPPER);
681
682 if (isset($arParams['DIALOG_ID']))
683 {
684 if (!\Bitrix\Im\Common::isDialogId($arParams['DIALOG_ID']))
685 {
686 throw new Bitrix\Rest\RestException("Dialog ID can't be empty", "DIALOG_ID_EMPTY", CRestServer::STATUS_WRONG_REQUEST);
687 }
688 }
689 else if (isset($arParams['CHAT_ID']))
690 {
691 $arParams['CHAT_ID'] = intval($arParams['CHAT_ID']);
692
693 if ($arParams['CHAT_ID'] <= 0)
694 {
695 throw new Bitrix\Rest\RestException("Chat ID can't be empty", "CHAT_ID_EMPTY", CRestServer::STATUS_WRONG_REQUEST);
696 }
697
698 $arParams['DIALOG_ID'] = 'chat'.$arParams['CHAT_ID'];
699 }
700
701 $result = CIMMessenger::StartWriting($arParams['DIALOG_ID']);
702 if (!$result)
703 {
704 throw new Bitrix\Rest\RestException("Action unavailable", "ACCESS_ERROR", CRestServer::STATUS_FORBIDDEN);
705 }
706
707 return true;
708 }
709
710 public static function dialogRead($arParams, $n, CRestServer $server)
711 {
712 $arParams = array_change_key_case($arParams, CASE_UPPER);
713 if (isset($arParams['LAST_ID']))
714 {
715 $arParams['MESSAGE_ID'] = $arParams['LAST_ID'];
716 }
717 $arParams['MESSAGE_ID'] = intval($arParams['MESSAGE_ID']);
718
719 if ($arParams['MESSAGE_ID'] <= 0)
720 {
721 $arParams['MESSAGE_ID'] = null;
722 }
723
724 if ($arParams['DIALOG_ID'] !== 'notify' && !\Bitrix\Im\Common::isDialogId($arParams['DIALOG_ID']))
725 {
726 throw new Bitrix\Rest\RestException("Dialog ID can't be empty", "DIALOG_ID_EMPTY", CRestServer::STATUS_WRONG_REQUEST);
727 }
728
729 $result = \Bitrix\Im\Dialog::read($arParams['DIALOG_ID'], $arParams['MESSAGE_ID']);
730
732 }
733
734 public static function dialogReadAll($arParams, $n, CRestServer $server)
735 {
736 return \Bitrix\Im\Dialog::readAll();
737 }
738
739 public static function dialogUnread($arParams, $n, CRestServer $server)
740 {
741 $arParams = array_change_key_case($arParams, CASE_UPPER);
742
743 $arParams['MESSAGE_ID'] = intval($arParams['MESSAGE_ID']);
744 if ($arParams['MESSAGE_ID'] <= 0)
745 {
746 throw new Bitrix\Rest\RestException("First unread message id can't be empty", "MESSAGE_ID_ERROR", CRestServer::STATUS_WRONG_REQUEST);
747 }
748
749 if (!\Bitrix\Im\Common::isDialogId($arParams['DIALOG_ID']))
750 {
751 throw new Bitrix\Rest\RestException("Dialog ID can't be empty", "DIALOG_ID_EMPTY", CRestServer::STATUS_WRONG_REQUEST);
752 }
753
754 \Bitrix\Im\Dialog::unread($arParams['DIALOG_ID'], $arParams['MESSAGE_ID']);
755
756 return true;
757 }
758
759
760 /* Search api */
761 public static function searchUser($arParams, $offset, CRestServer $server)
762 {
763 $arParams = array_change_key_case($arParams, CASE_UPPER);
764
765 if (!isset($arParams['FIND']))
766 {
767 throw new Bitrix\Rest\RestException("Too short a search phrase.", "FIND_SHORT", CRestServer::STATUS_WRONG_REQUEST);
768 }
769
770 $params = Array(
771 'FILTER' => Array('SEARCH' => $arParams['FIND']),
772 'JSON' => 'Y'
773 );
774 if (isset($arParams['BUSINESS']) && $arParams['BUSINESS'] == 'Y')
775 {
776 $params['FILTER']['BUSINESS'] = 'Y';
777 }
778
780 if (is_null($ormParams))
781 {
782 throw new Bitrix\Rest\RestException("Too short a search phrase.", "FIND_SHORT", CRestServer::STATUS_WRONG_REQUEST);
783 }
784
785 $ormParams['select'] = array("CNT" => new \Bitrix\Main\Entity\ExpressionField('CNT', 'COUNT(1)'));
786
787 $counter = \Bitrix\Main\UserTable::getList($ormParams)->fetch();
788
789 $result = Array();
790 if ($counter && $counter["CNT"] > 0)
791 {
792 $params['OFFSET'] = intval($offset) > 0? intval($offset): (isset($arParams['OFFSET']) && intval($arParams['OFFSET']) > 0? intval($arParams['OFFSET']): 0);
793 $params['LIMIT'] = isset($arParams['LIMIT'])? (intval($arParams['LIMIT']) > 50? 50: intval($arParams['LIMIT'])): 10;
794 $params['HR_PHOTO'] = isset($arParams['AVATAR_HR']) && $arParams['AVATAR_HR'] == 'Y';
795 $params['JSON'] = true;
796
798 }
799
800 return self::setNavData(
801 $result,
802 array(
803 "count" => $counter['CNT'],
804 "offset" => $params['OFFSET']
805 )
806 );
807 }
808
809 public static function searchDepartment($arParams, $offset, CRestServer $server)
810 {
811 $arParams = array_change_key_case($arParams, CASE_UPPER);
812
813 if (!isset($arParams['FIND']))
814 {
815 throw new Bitrix\Rest\RestException("Too short a search phrase.", "FIND_SHORT", CRestServer::STATUS_WRONG_REQUEST);
816 }
817
818 $options = Array(
819 'FILTER' => Array('SEARCH' => $arParams['FIND']),
820 'LIST' => Array(
821 'OFFSET' => intval($offset) > 0? $offset: (isset($arParams['OFFSET']) && intval($arParams['OFFSET']) > 0? intval($arParams['OFFSET']): 0),
822 'LIMIT' => isset($arParams['LIMIT'])? (intval($arParams['LIMIT']) > 50? 50: intval($arParams['LIMIT'])): 10,
823 ),
824 'USER_DATA' => $arParams['USER_DATA'] == 'Y'? 'Y': 'N',
825 'JSON' => 'Y',
826 );
827
829
830 return self::setNavData(
831 $result['result'],
832 array(
833 "count" => $result['total'],
834 "offset" => $options['OFFSET']
835 )
836 );
837 }
838
839 public static function searchChat($arParams, $offset, CRestServer $server)
840 {
841 $arParams = array_change_key_case($arParams, CASE_UPPER);
842
843 if (!isset($arParams['FIND']) && !isset($arParams['FIND_LINES']))
844 {
845 throw new Bitrix\Rest\RestException("Too short a search phrase.", "FIND_SHORT", CRestServer::STATUS_WRONG_REQUEST);
846 }
847
848 $params = Array(
849 'FILTER' => Array('SEARCH' => $arParams['FIND'] ?? null, 'SEARCH_OL' => $arParams['FIND_LINES'] ?? null),
850 'JSON' => 'Y'
851 );
852
854 if (is_null($ormParams))
855 {
856 throw new Bitrix\Rest\RestException("Too short a search phrase.", "FIND_SHORT", CRestServer::STATUS_WRONG_REQUEST);
857 }
858
859 $ormParams['select'] = array("CNT" => new \Bitrix\Main\Entity\ExpressionField('CNT', 'COUNT(1)'));
860
861 $counter = \Bitrix\Im\Model\ChatTable::getList($ormParams)->fetch();
862
863 $result = Array();
864 if ($counter && $counter["CNT"] > 0)
865 {
866 $params['OFFSET'] = intval($offset) > 0? intval($offset): (isset($arParams['OFFSET']) && intval($arParams['OFFSET']) > 0? intval($arParams['OFFSET']): 0);
867 $params['LIMIT'] = isset($arParams['LIMIT'])? (intval($arParams['LIMIT']) > 50? 50: intval($arParams['LIMIT'])): 10;
868 $params['ORDER'] = Array('ID' => 'DESC');
869 $params['JSON'] = 'Y';
870
872
873 }
874
875 return self::setNavData(
876 $result,
877 array(
878 "count" => $counter['CNT'],
879 "offset" => $params['OFFSET']
880 )
881 );
882
883 return $result;
884 }
885
886 public static function searchLastGet($arParams, $n, CRestServer $server)
887 {
888 $arParams = array_change_key_case($arParams, CASE_UPPER);
889
890 $config = Array('JSON' => 'Y');
891 if ($arParams['SKIP_OPENLINES'] == 'Y')
892 {
893 $config['SKIP_OPENLINES'] = 'Y';
894 }
895 if ($arParams['SKIP_CHAT'] == 'Y')
896 {
897 $config['SKIP_CHAT'] = 'Y';
898 }
899 if ($arParams['SKIP_DIALOG'] == 'Y')
900 {
901 $config['SKIP_DIALOG'] = 'Y';
902 }
903
904 return \Bitrix\Im\LastSearch::get(null, $config);
905 }
906
907 public static function searchLastAdd($arParams, $n, CRestServer $server)
908 {
909 $arParams = array_change_key_case($arParams, CASE_UPPER);
910
911 if (!\Bitrix\Im\Common::isDialogId($arParams['DIALOG_ID']))
912 {
913 throw new Bitrix\Rest\RestException("Dialog ID can't be empty", "DIALOG_ID_EMPTY", CRestServer::STATUS_WRONG_REQUEST);
914 }
915
916 return \Bitrix\Im\LastSearch::add($arParams['DIALOG_ID'])? true: false;
917 }
918
919 public static function searchLastDelete($arParams, $n, CRestServer $server)
920 {
921 $arParams = array_change_key_case($arParams, CASE_UPPER);
922
923 if (!\Bitrix\Im\Common::isDialogId($arParams['DIALOG_ID']))
924 {
925 throw new Bitrix\Rest\RestException("Dialog ID can't be empty", "DIALOG_ID_EMPTY", CRestServer::STATUS_WRONG_REQUEST);
926 }
927
928 return \Bitrix\Im\LastSearch::delete($arParams['DIALOG_ID']);
929 }
930
931 /* Recent api */
932 public static function recentGet($arParams, $n, CRestServer $server)
933 {
934 $arParams = array_change_key_case($arParams, CASE_UPPER);
935
936 $config = Array('JSON' => 'Y');
937
938 if ($arParams['ONLY_OPENLINES'] === 'Y')
939 {
940 $config['ONLY_OPENLINES'] = 'Y';
941 }
942 else
943 {
944 $config['FORCE_OPENLINES'] = 'Y';
945 if ($arParams['SKIP_OPENLINES'] === 'Y')
946 {
947 $config['SKIP_OPENLINES'] = 'Y';
948 }
949 if ($arParams['SKIP_CHAT'] === 'Y')
950 {
951 $config['SKIP_CHAT'] = 'Y';
952 }
953 if ($arParams['SKIP_DIALOG'] === 'Y')
954 {
955 $config['SKIP_DIALOG'] = 'Y';
956 }
957 }
958
959 if (isset($arParams['LAST_UPDATE'])) // TODO remove this later
960 {
961 $arParams['LAST_SYNC_DATE'] = $arParams['LAST_UPDATE'];
962 }
963 if (isset($arParams['LAST_SYNC_DATE']) && $arParams['LAST_SYNC_DATE'])
964 {
965 try
966 {
967 $config['LAST_SYNC_DATE'] = new \Bitrix\Main\Type\DateTime($arParams['LAST_SYNC_DATE'], \DateTimeInterface::RFC3339);
968 }
969 catch (Exception $e){}
970 }
971
972 return \Bitrix\Im\Recent::get(null, $config);
973 }
974
975 public static function recentList($arParams, $offset, CRestServer $server)
976 {
977 $arParams = array_change_key_case($arParams, CASE_UPPER);
978
979 $skipChatParam = $arParams['SKIP_CHAT'] ?? null;
980 $skipDialogParam = $arParams['SKIP_DIALOG'] ?? null;
981 $unreadOnly = $arParams['UNREAD_ONLY'] ?? null;
982 $parseText = $arParams['PARSE_TEXT'] ?? null;
983
984 $config = Array('JSON' => 'Y');
985 if (isset($arParams['SKIP_OPENLINES']) && $arParams['SKIP_OPENLINES'] === 'Y')
986 {
987 $config['SKIP_OPENLINES'] = 'Y';
988 }
989 if (isset($arParams['SKIP_UNDISTRIBUTED_OPENLINES']) && $arParams['SKIP_UNDISTRIBUTED_OPENLINES'] === 'Y')
990 {
991 $config['SKIP_UNDISTRIBUTED_OPENLINES'] = 'Y';
992 }
993 if (isset($arParams['ONLY_COPILOT']) && $arParams['ONLY_COPILOT'] === 'Y')
994 {
995 $config['ONLY_COPILOT'] = 'Y';
996 }
997 if (isset($arParams['ONLY_CHANNEL']) && $arParams['ONLY_CHANNEL'] === 'Y')
998 {
999 $config['ONLY_CHANNEL'] = 'Y';
1000 }
1001 if (isset($arParams['CAN_MANAGE_MESSAGES']) && $arParams['CAN_MANAGE_MESSAGES'] === 'Y')
1002 {
1003 $config['CAN_MANAGE_MESSAGES'] = 'Y';
1004 }
1005 if ($skipChatParam === 'Y')
1006 {
1007 $config['SKIP_CHAT'] = 'Y';
1008 }
1009 if ($skipDialogParam === 'Y')
1010 {
1011 $config['SKIP_DIALOG'] = 'Y';
1012 }
1013 if ($unreadOnly === 'Y')
1014 {
1015 $config['UNREAD_ONLY'] = 'Y';
1016 }
1017 if (isset($arParams['GET_ORIGINAL_TEXT']) && $arParams['GET_ORIGINAL_TEXT'] === 'Y')
1018 {
1019 $config['GET_ORIGINAL_TEXT'] = 'Y';
1020 }
1021 else
1022 {
1023 $config['GET_ORIGINAL_TEXT'] = 'N';
1024 }
1025 if ($parseText === 'Y')
1026 {
1027 $config['PARSE_TEXT'] = 'Y';
1028 }
1029
1030 if (isset($arParams['DATE_LAST_ACTIVITY']) && $arParams['DATE_LAST_ACTIVITY'])
1031 {
1032 try
1033 {
1034 $config['LAST_MESSAGE_DATE'] = new \Bitrix\Main\Type\DateTime($arParams['DATE_LAST_ACTIVITY'], \DateTimeInterface::RFC3339);
1035 }
1036 catch (Exception $e){}
1037 }
1038
1039 if (isset($arParams['LAST_MESSAGE_DATE']) && $arParams['LAST_MESSAGE_DATE'])
1040 {
1041 try
1042 {
1043 $config['LAST_MESSAGE_DATE'] = new \Bitrix\Main\Type\DateTime($arParams['LAST_MESSAGE_DATE'], \DateTimeInterface::RFC3339);
1044 }
1045 catch (Exception $e){}
1046 }
1047
1048 $config['OFFSET'] = self::getOffset($offset, $arParams);
1049 $config['LIMIT'] = self::getLimit($arParams);
1050
1052
1053 if ($result['hasMore'])
1054 {
1055 $result['next'] = $config['OFFSET']+(count($result['items']));
1056 }
1057
1058 $result['total'] = -1;
1059
1060 return $result;
1061
1062 }
1063
1064 public static function recentPin($arParams, $n, CRestServer $server)
1065 {
1066 $arParams = array_change_key_case($arParams, CASE_UPPER);
1067
1068 if ($arParams['DIALOG_ID'] !== 'notify' && !\Bitrix\Im\Common::isDialogId($arParams['DIALOG_ID']))
1069 {
1070 throw new Bitrix\Rest\RestException("Dialog ID can't be empty", "DIALOG_ID_EMPTY", CRestServer::STATUS_WRONG_REQUEST);
1071 }
1072
1073 if (isset($arParams['ACTION']))
1074 {
1075 $arParams['PIN'] = $arParams['ACTION'];
1076 }
1077
1078 return \Bitrix\Im\Recent::pin($arParams['DIALOG_ID'], $arParams['PIN'] != 'N');
1079 }
1080
1081 public static function recentHide($arParams, $n, CRestServer $server)
1082 {
1083 $arParams = array_change_key_case($arParams, CASE_UPPER);
1084
1085 if ($arParams['DIALOG_ID'] !== 'notify' && !\Bitrix\Im\Common::isDialogId($arParams['DIALOG_ID']))
1086 {
1087 throw new Bitrix\Rest\RestException("Dialog ID can't be empty", "DIALOG_ID_EMPTY", CRestServer::STATUS_WRONG_REQUEST);
1088 }
1089
1090 return \Bitrix\Im\Recent::hide($arParams['DIALOG_ID']);
1091 }
1092
1093 public static function recentUnread($arParams, $n, CRestServer $server)
1094 {
1095 $arParams = array_change_key_case($arParams, CASE_UPPER);
1096
1097 if ($arParams['DIALOG_ID'] !== 'notify' && !\Bitrix\Im\Common::isDialogId($arParams['DIALOG_ID']))
1098 {
1099 throw new Bitrix\Rest\RestException("Dialog ID can't be empty", "DIALOG_ID_EMPTY", CRestServer::STATUS_WRONG_REQUEST);
1100 }
1101
1102 if (isset($arParams['ACTION']))
1103 {
1104 $arParams['UNREAD'] = $arParams['ACTION'];
1105 }
1106
1107 return \Bitrix\Im\Recent::unread($arParams['DIALOG_ID'], $arParams['UNREAD'] !== 'N');
1108 }
1109
1110 /* Promotion api */
1111
1112 public static function promotionGet($arParams, $n, CRestServer $server)
1113 {
1114 $arParams = array_change_key_case($arParams, CASE_UPPER);
1115
1117 if (in_array($arParams['DEVICE_TYPE'], \Bitrix\Im\Promotion::getDeviceTypes(), true))
1118 {
1119 $promoType = $arParams['DEVICE_TYPE'];
1120 }
1121
1122 return \Bitrix\Im\Promotion::getActive($promoType);
1123 }
1124
1125 public static function promotionRead($arParams, $n, CRestServer $server)
1126 {
1127 $arParams = array_change_key_case($arParams, CASE_UPPER);
1128
1129 return \Bitrix\Im\Promotion::read($arParams['ID']);
1130 }
1131
1132 /* Department api */
1133
1134 public static function departmentGet($arParams, $offset, CRestServer $server)
1135 {
1136 if (
1137 \Bitrix\Im\User::getInstance()->isExtranet()
1138 || \Bitrix\Im\User::getInstance()->isBot()
1139 )
1140 {
1141 throw new Bitrix\Rest\RestException("Only intranet users have access to this method.", "ACCESS_ERROR", CRestServer::STATUS_FORBIDDEN);
1142 }
1143
1144 $arParams = array_change_key_case($arParams, CASE_UPPER);
1145
1146 $ids = Array();
1147 if (is_string($arParams['ID']))
1148 {
1149 $arParams['ID'] = \CUtil::JsObjectToPhp($arParams['ID'], true);
1150 }
1151 if (is_array($arParams['ID']))
1152 {
1153 foreach ($arParams['ID'] as $id)
1154 {
1155 $id = intval($id);
1156 if ($id > 0)
1157 {
1158 $ids[$id] = $id;
1159 }
1160 }
1161 }
1162
1163 if (empty($ids))
1164 {
1165 throw new Bitrix\Rest\RestException("A wrong format for the ID field is passed", "INVALID_FORMAT", CRestServer::STATUS_WRONG_REQUEST);
1166 }
1167
1168 $options = Array(
1169 'FILTER' => Array('ID' => $ids),
1170 'USER_DATA' => $arParams['USER_DATA'] == 'Y'? 'Y': 'N',
1171 'JSON' => 'Y',
1172 );
1174
1175 return $result;
1176 }
1177
1178 public static function departmentManagersGet($arParams, $n, CRestServer $server)
1179 {
1180 if (
1181 \Bitrix\Im\User::getInstance()->isExtranet()
1182 || \Bitrix\Im\User::getInstance()->isBot()
1183 )
1184 {
1185 throw new Bitrix\Rest\RestException("Only intranet users have access to this method.", "ACCESS_ERROR", CRestServer::STATUS_FORBIDDEN);
1186 }
1187
1188 $arParams = array_change_key_case($arParams, CASE_UPPER);
1189
1190 $withUserData = $arParams['USER_DATA'] == 'Y';
1191
1192 $ids = Array();
1193 if (is_string($arParams['ID']))
1194 {
1195 $arParams['ID'] = \CUtil::JsObjectToPhp($arParams['ID']);
1196 }
1197 if (is_array($arParams['ID']))
1198 {
1199 foreach ($arParams['ID'] as $id)
1200 {
1201 $id = intval($id);
1202 if ($id > 0)
1203 {
1204 $ids[$id] = $id;
1205 }
1206 }
1207 }
1208
1209 if (empty($ids))
1210 {
1211 throw new Bitrix\Rest\RestException("Department ID can't be empty", "ID_EMPTY", CRestServer::STATUS_WRONG_REQUEST);
1212 }
1213
1214 return \Bitrix\Im\Department::getManagers($ids, array('JSON' => 'Y', 'USER_DATA' => $withUserData? 'Y': 'N'));
1215 }
1216
1217 public static function departmentEmployeesGet($arParams, $n, CRestServer $server)
1218 {
1219 if (
1220 \Bitrix\Im\User::getInstance()->isExtranet()
1221 || \Bitrix\Im\User::getInstance()->isBot()
1222 )
1223 {
1224 throw new Bitrix\Rest\RestException("Only intranet users have access to this method.", "ACCESS_ERROR", CRestServer::STATUS_FORBIDDEN);
1225 }
1226
1227 $arParams = array_change_key_case($arParams, CASE_UPPER);
1228
1229 $withUserData = $arParams['USER_DATA'] == 'Y';
1230
1231 $ids = Array();
1232 if (is_string($arParams['ID']))
1233 {
1234 $arParams['ID'] = \CUtil::JsObjectToPhp($arParams['ID']);
1235 }
1236 if (is_array($arParams['ID']))
1237 {
1238 foreach ($arParams['ID'] as $id)
1239 {
1240 $id = intval($id);
1241 if ($id > 0)
1242 {
1243 $ids[$id] = $id;
1244 }
1245 }
1246 }
1247
1248 if (empty($ids))
1249 {
1250 throw new Bitrix\Rest\RestException("Department ID can't be empty", "ID_EMPTY", CRestServer::STATUS_WRONG_REQUEST);
1251 }
1252
1253 return \Bitrix\Im\Department::getEmployees($ids, array('JSON' => 'Y', 'USER_DATA' => $withUserData? 'Y': 'N'));
1254 }
1255
1256 public static function departmentColleaguesList($arParams, $offset, CRestServer $server)
1257 {
1258 if (
1259 \Bitrix\Im\User::getInstance()->isExtranet()
1260 || \Bitrix\Im\User::getInstance()->isBot()
1261 )
1262 {
1263 throw new Bitrix\Rest\RestException("Only intranet users have access to this method.", "ACCESS_ERROR", CRestServer::STATUS_FORBIDDEN);
1264 }
1265
1266 $arParams = array_change_key_case($arParams, CASE_UPPER);
1267
1268 $withUserData = $arParams['USER_DATA'] == 'Y';
1269
1270 $params['OFFSET'] = intval($offset) > 0? intval($offset): (isset($arParams['OFFSET']) && intval($arParams['OFFSET']) > 0? intval($arParams['OFFSET']): 0);
1271 $params['LIMIT'] = isset($arParams['LIMIT'])? (intval($arParams['LIMIT']) > 50? 50: intval($arParams['LIMIT'])): 10;
1272
1273 $result = \Bitrix\Im\Department::getColleagues(null, array('JSON' => 'Y', 'USER_DATA' => $withUserData? 'Y': 'N', 'LIST' => $params));
1274
1275 return self::setNavData(
1276 $result['result'],
1277 array(
1278 "count" => $result['total'],
1279 "offset" => $params['OFFSET']
1280 )
1281 );
1282 }
1283
1284
1285 /* ChatAPI */
1286
1297 public static function chatCreate($arParams, $n, CRestServer $server)
1298 {
1299 $arParams = array_change_key_case($arParams, CASE_UPPER);
1300
1301 if (isset($arParams['USERS']))
1302 {
1303 if (is_string($arParams['USERS']))
1304 {
1305 $arParams['USERS'] = \CUtil::JsObjectToPhp($arParams['USERS'], true);
1306 }
1307 if (!is_array($arParams['USERS']))
1308 {
1309 $arParams['USERS'] = [];
1310 }
1311
1312 $arParams['USERS'] = array_filter(array_values($arParams['USERS']));
1313 foreach ($arParams['USERS'] as $uid)
1314 {
1315 if (!is_integer($uid) && !is_string($uid))
1316 {
1317 throw new Bitrix\Rest\RestException("Parameter USERS has wrong type", "INVALID_FORMAT", CRestServer::STATUS_WRONG_REQUEST);
1318 }
1319 }
1320 }
1321 else
1322 {
1323 $arParams['USERS'] = [];
1324 }
1325
1326 $add = [
1327 'TYPE' => $arParams['TYPE'] == 'OPEN' ? Chat::TYPE_OPEN : Chat::TYPE_GROUP,
1328 'USERS' => $arParams['USERS'],
1329 ];
1330
1331 if (isset($arParams['AVATAR']))
1332 {
1333 $add['AVATAR'] = $arParams['AVATAR'];
1334 }
1335 if (isset($arParams['COLOR']))
1336 {
1337 $add['COLOR'] = $arParams['COLOR'];
1338 }
1339 if (isset($arParams['MESSAGE']))
1340 {
1341 $add['MESSAGE'] = $arParams['MESSAGE'];
1342 }
1343 if (isset($arParams['TITLE']))
1344 {
1345 $add['TITLE'] = $arParams['TITLE'];
1346 }
1347 if (isset($arParams['DESCRIPTION']))
1348 {
1349 $add['DESCRIPTION'] = $arParams['DESCRIPTION'];
1350 }
1351
1352 if (\Bitrix\Im\User::getInstance()->isExtranet())
1353 {
1355 }
1356 else
1357 {
1358 if (isset($arParams['ENTITY_TYPE']))
1359 {
1360 $add['ENTITY_TYPE'] = $arParams['ENTITY_TYPE'];
1361 }
1362 if (isset($arParams['ENTITY_ID']))
1363 {
1364 $add['ENTITY_ID'] = $arParams['ENTITY_ID'];
1365 }
1366 }
1367
1368 if (isset($arParams['COPILOT_MAIN_ROLE']))
1369 {
1370 $add['CHAT_PARAMS'][] = [
1372 'PARAM_VALUE' => $arParams['COPILOT_MAIN_ROLE']
1373 ];
1374 }
1375
1376 global $USER;
1377 $userId = $USER->GetId();
1378 if ($server->getMethod() == "imbot.chat.add")
1379 {
1380 $userId = self::getBotId($arParams, $server);
1381 }
1382
1383 $CIMChat = new CIMChat($userId);
1384 $chatId = $CIMChat->Add($add);
1385 if (!$chatId)
1386 {
1387 throw new Bitrix\Rest\RestException("Chat can't be created", "WRONG_REQUEST", CRestServer::STATUS_WRONG_REQUEST);
1388 }
1389
1390 return $chatId;
1391 }
1392
1393 public static function chatGet($arParams, $n, CRestServer $server)
1394 {
1395 global $USER;
1396 if (!$USER->IsAuthorized())
1397 {
1398 throw new \Bitrix\Rest\RestException("Method not available for guest session.", "AUTHORIZE_ERROR", \CRestServer::STATUS_FORBIDDEN);
1399 }
1400
1401 $arParams = array_change_key_case($arParams, CASE_UPPER);
1402
1403 if (isset($arParams['DIALOG_ID']))
1404 {
1405 if (!\Bitrix\Im\Common::isDialogId($arParams['DIALOG_ID']))
1406 {
1407 throw new Bitrix\Rest\RestException("Dialog ID can't be empty", "DIALOG_ID_EMPTY", CRestServer::STATUS_WRONG_REQUEST);
1408 }
1409
1410 if (!\Bitrix\Im\Dialog::hasAccess($arParams['DIALOG_ID']))
1411 {
1412 throw new Bitrix\Rest\RestException("You do not have access to the specified dialog", "ACCESS_ERROR", CRestServer::STATUS_FORBIDDEN);
1413 }
1414
1415 $chatId = \Bitrix\Im\Dialog::getChatId($arParams['DIALOG_ID']);
1416 if (!$chatId)
1417 {
1418 throw new Bitrix\Rest\RestException("You don't have access to this chat", "ACCESS_ERROR", CRestServer::STATUS_WRONG_REQUEST);
1419 }
1420
1421 $result = \Bitrix\Im\Chat::getById($chatId, ['LOAD_READED' => true, 'JSON' => true]);
1422 if (!$result)
1423 {
1424 throw new Bitrix\Rest\RestException("You don't have access to this chat", "ACCESS_ERROR", CRestServer::STATUS_WRONG_REQUEST);
1425 }
1426
1427 $result['dialog_id'] = $arParams['DIALOG_ID'];
1428
1429 return $result;
1430 }
1431 else if (
1432 isset($arParams['ENTITY_TYPE']) && isset($arParams['ENTITY_ID'])
1433 && !empty($arParams['ENTITY_TYPE']) && !empty($arParams['ENTITY_ID'])
1434 )
1435 {
1436 $chatData = \Bitrix\Im\Model\ChatTable::getList(Array(
1437 'select' => ['ID'],
1438 'filter' => [
1439 '=ENTITY_TYPE' => $arParams['ENTITY_TYPE'],
1440 '=ENTITY_ID' => $arParams['ENTITY_ID'],
1441 ]
1442 ))->fetch();
1443 if ($chatData)
1444 {
1445 return Array(
1446 'ID' => (int)$chatData['ID']
1447 );
1448 }
1449 }
1450
1451 return null;
1452 }
1453
1454 public static function chatSetOwner($arParams, $n, CRestServer $server)
1455 {
1456 global $USER;
1457
1458 $arParams = array_change_key_case($arParams, CASE_UPPER);
1459
1460 if (isset($arParams['DIALOG_ID']))
1461 {
1462 if (\Bitrix\Im\Common::isChatId($arParams['DIALOG_ID']))
1463 {
1464 $arParams['CHAT_ID'] = \Bitrix\Im\Dialog::getChatId($arParams['DIALOG_ID']);
1465 }
1466 else
1467 {
1468 throw new Bitrix\Rest\RestException("Dialog ID can't be empty", "DIALOG_ID_EMPTY", CRestServer::STATUS_WRONG_REQUEST);
1469 }
1470 }
1471
1472 $arParams['CHAT_ID'] = intval($arParams['CHAT_ID']);
1473 $arParams['USER_ID'] = intval($arParams['USER_ID']);
1474
1475 if ($arParams['CHAT_ID'] <= 0)
1476 {
1477 throw new Bitrix\Rest\RestException("Chat ID can't be empty", "CHAT_ID_EMPTY", CRestServer::STATUS_WRONG_REQUEST);
1478 }
1479
1480 if ($arParams['USER_ID'] <= 0)
1481 {
1482 throw new Bitrix\Rest\RestException("User ID can't be empty", "USER_ID_EMPTY", CRestServer::STATUS_WRONG_REQUEST);
1483 }
1484
1485 $userId = $USER->GetId();
1486 if ($server->getMethod() == mb_strtolower("imbot.chat.setOwner"))
1487 {
1488 $userId = self::getBotId($arParams, $server);
1489 }
1490
1491 if (CIMChat::GetGeneralChatId() == $arParams['CHAT_ID'])
1492 {
1493 throw new Bitrix\Rest\RestException("Action unavailable", "ACCESS_ERROR", CRestServer::STATUS_FORBIDDEN);
1494 }
1495
1496 $chat = new CIMChat($userId);
1497 $result = $chat->SetOwner($arParams['CHAT_ID'], $arParams['USER_ID']);
1498 if (!$result)
1499 {
1500 throw new Bitrix\Rest\RestException("Change owner can only owner and user must be member in chat", "WRONG_REQUEST", CRestServer::STATUS_WRONG_REQUEST);
1501 }
1502
1503 return true;
1504 }
1505
1506 public static function chatSetManager($arParams, $n, CRestServer $server)
1507 {
1508 global $USER;
1509
1510 $arParams = array_change_key_case($arParams, CASE_UPPER);
1511
1512 if (isset($arParams['DIALOG_ID']))
1513 {
1514 if (\Bitrix\Im\Common::isChatId($arParams['DIALOG_ID']))
1515 {
1516 $arParams['CHAT_ID'] = \Bitrix\Im\Dialog::getChatId($arParams['DIALOG_ID']);
1517 }
1518 else
1519 {
1520 throw new Bitrix\Rest\RestException("Dialog ID can't be empty", "DIALOG_ID_EMPTY", CRestServer::STATUS_WRONG_REQUEST);
1521 }
1522 }
1523
1524 $arParams['CHAT_ID'] = intval($arParams['CHAT_ID']);
1525 $arParams['USER_ID'] = intval($arParams['USER_ID']);
1526 $arParams['IS_MANAGER'] = isset($arParams['IS_MANAGER']) && $arParams['IS_MANAGER'] == 'N'? false: true;
1527
1528 if ($arParams['CHAT_ID'] <= 0)
1529 {
1530 throw new Bitrix\Rest\RestException("Chat ID can't be empty", "CHAT_ID_EMPTY", CRestServer::STATUS_WRONG_REQUEST);
1531 }
1532
1533 if ($arParams['USER_ID'] <= 0)
1534 {
1535 throw new Bitrix\Rest\RestException("User ID can't be empty", "USER_ID_EMPTY", CRestServer::STATUS_WRONG_REQUEST);
1536 }
1537
1538 $userId = $USER->GetId();
1539 if ($server->getMethod() == mb_strtolower("imbot.chat.setManager"))
1540 {
1541 $userId = self::getBotId($arParams, $server);
1542 }
1543
1544 $chat = new CIMChat($userId);
1545 $result = $chat->SetManager($arParams['CHAT_ID'], $arParams['USER_ID'], $arParams['IS_MANAGER']);
1546 if (!$result)
1547 {
1548 throw new Bitrix\Rest\RestException("Change manager can only owner and user must be member in chat", "WRONG_REQUEST", CRestServer::STATUS_WRONG_REQUEST);
1549 }
1550
1551 return true;
1552 }
1553
1554 public static function chatUpdateColor($arParams, $n, CRestServer $server)
1555 {
1556 global $USER;
1557
1558 $arParams = array_change_key_case($arParams, CASE_UPPER);
1559
1560 if (isset($arParams['DIALOG_ID']))
1561 {
1562 if (\Bitrix\Im\Common::isChatId($arParams['DIALOG_ID']))
1563 {
1564 $arParams['CHAT_ID'] = \Bitrix\Im\Dialog::getChatId($arParams['DIALOG_ID']);
1565 }
1566 else
1567 {
1568 throw new Bitrix\Rest\RestException("Dialog ID can't be empty", "DIALOG_ID_EMPTY", CRestServer::STATUS_WRONG_REQUEST);
1569 }
1570 }
1571
1572 $arParams['CHAT_ID'] = intval($arParams['CHAT_ID']);
1573
1574 if ($arParams['CHAT_ID'] <= 0)
1575 {
1576 throw new Bitrix\Rest\RestException("Chat ID can't be empty", "CHAT_ID_EMPTY", CRestServer::STATUS_WRONG_REQUEST);
1577 }
1578
1579 $userId = $USER->GetId();
1580 if (CIMChat::GetGeneralChatId() == $arParams['CHAT_ID'] && !CIMChat::CanSendMessageToGeneralChat($userId))
1581 {
1582 throw new Bitrix\Rest\RestException("Action unavailable", "ACCESS_ERROR", CRestServer::STATUS_FORBIDDEN);
1583 }
1584
1585 if (!Bitrix\Im\Color::isSafeColor($arParams['COLOR']))
1586 {
1587 throw new Bitrix\Rest\RestException("This color currently unavailable", "WRONG_COLOR", CRestServer::STATUS_WRONG_REQUEST);
1588 }
1589
1590 $userId = $USER->GetId();
1591 if ($server->getMethod() == mb_strtolower("imbot.chat.updateColor"))
1592 {
1593 $userId = self::getBotId($arParams, $server);
1594 }
1595
1596 $chat = new CIMChat($userId);
1597 $result = $chat->SetColor($arParams['CHAT_ID'], $arParams['COLOR']);
1598
1599 if (!$result)
1600 {
1601 throw new Bitrix\Rest\RestException("This color currently set or chat isn't exists", "WRONG_REQUEST", CRestServer::STATUS_WRONG_REQUEST);
1602 }
1603
1604 return true;
1605 }
1606
1607 public static function chatUpdateTitle($arParams, $n, CRestServer $server)
1608 {
1609 global $USER;
1610
1611 $arParams = array_change_key_case($arParams, CASE_UPPER);
1612
1613 if (isset($arParams['DIALOG_ID']))
1614 {
1615 if (\Bitrix\Im\Common::isChatId($arParams['DIALOG_ID']))
1616 {
1617 $arParams['CHAT_ID'] = \Bitrix\Im\Dialog::getChatId($arParams['DIALOG_ID']);
1618 }
1619 else
1620 {
1621 throw new Bitrix\Rest\RestException("Dialog ID can't be empty", "DIALOG_ID_EMPTY", CRestServer::STATUS_WRONG_REQUEST);
1622 }
1623 }
1624
1625 $arParams['CHAT_ID'] = intval($arParams['CHAT_ID']);
1626 $arParams['TITLE'] = trim($arParams['TITLE']);
1627
1628 if ($arParams['CHAT_ID'] <= 0)
1629 {
1630 throw new Bitrix\Rest\RestException("Chat ID can't be empty", "CHAT_ID_EMPTY", CRestServer::STATUS_WRONG_REQUEST);
1631 }
1632 if (empty($arParams['TITLE']))
1633 {
1634 throw new Bitrix\Rest\RestException("Title can't be empty", "TITLE_EMPTY", CRestServer::STATUS_WRONG_REQUEST);
1635 }
1636
1637 $userId = $USER->GetId();
1638 if ($server->getMethod() == mb_strtolower("imbot.chat.updateTitle"))
1639 {
1640 $userId = self::getBotId($arParams, $server);
1641 }
1642
1643 if (CIMChat::GetGeneralChatId() == $arParams['CHAT_ID'] && !CIMChat::CanSendMessageToGeneralChat($userId))
1644 {
1645 throw new Bitrix\Rest\RestException("Action unavailable", "ACCESS_ERROR", CRestServer::STATUS_FORBIDDEN);
1646 }
1647
1648 if (!Chat::isActionAllowed('chat' . $arParams['CHAT_ID'], 'RENAME'))
1649 {
1650 throw new Bitrix\Rest\RestException('This chat cannot be renamed', 'ACCESS_ERROR', CRestServer::STATUS_FORBIDDEN);
1651 }
1652
1653 $chat = new CIMChat($userId);
1654 $chat->Rename($arParams['CHAT_ID'], $arParams['TITLE']);
1655
1656 return true;
1657 }
1658
1659 public static function chatUpdateAvatar($arParams, $n, CRestServer $server)
1660 {
1661 global $USER;
1662
1663 $arParams = array_change_key_case($arParams, CASE_UPPER);
1664
1665 if (isset($arParams['DIALOG_ID']))
1666 {
1667 if (\Bitrix\Im\Common::isChatId($arParams['DIALOG_ID']))
1668 {
1669 $arParams['CHAT_ID'] = \Bitrix\Im\Dialog::getChatId($arParams['DIALOG_ID']);
1670 }
1671 else
1672 {
1673 throw new Bitrix\Rest\RestException("Dialog ID can't be empty", "DIALOG_ID_EMPTY", CRestServer::STATUS_WRONG_REQUEST);
1674 }
1675 }
1676
1677 $arParams['CHAT_ID'] = intval($arParams['CHAT_ID']);
1678
1679 if ($arParams['CHAT_ID'] <= 0)
1680 {
1681 throw new Bitrix\Rest\RestException("Chat ID can't be empty", "CHAT_ID_EMPTY", CRestServer::STATUS_WRONG_REQUEST);
1682 }
1683
1684 $chat = \Bitrix\Im\Model\ChatTable::getById($arParams['CHAT_ID'])->fetch();
1685 $chatRelation = \CIMChat::GetRelationById($arParams['CHAT_ID'], false, true, false);
1686
1687 if (!CIMChat::canDo($chat, $chatRelation, \Bitrix\Im\V2\Permission\Action::ChangeAvatar))
1688 {
1689 throw new Bitrix\Rest\RestException("Access denied", "ACCESS_DENIED", CRestServer::STATUS_WRONG_REQUEST);
1690 }
1691
1692 $userId = $USER->GetId();
1693 if ($server->getMethod() == mb_strtolower("imbot.chat.updateAvatar"))
1694 {
1695 $userId = self::getBotId($arParams, $server);
1696 }
1697
1698 if (CIMChat::GetGeneralChatId() == $arParams['CHAT_ID'] && !CIMChat::CanSendMessageToGeneralChat($userId))
1699 {
1700 throw new Bitrix\Rest\RestException("Action unavailable", "ACCESS_ERROR", CRestServer::STATUS_FORBIDDEN);
1701 }
1702
1703 if (!Chat::isActionAllowed('chat' . $arParams['CHAT_ID'], 'AVATAR'))
1704 {
1705 throw new Bitrix\Rest\RestException('The avatar of this chat cannot be changed', 'ACCESS_ERROR', CRestServer::STATUS_FORBIDDEN);
1706 }
1707
1708 $arParams['AVATAR'] = CRestUtil::saveFile($arParams['AVATAR']);
1709 if (!$arParams['AVATAR'] || mb_strpos($arParams['AVATAR']['type'], "image/") !== 0)
1710 {
1711 throw new Bitrix\Rest\RestException("Avatar incorrect type", "AVATAR_ERROR", CRestServer::STATUS_WRONG_REQUEST);
1712 }
1713
1714 $imageCheck = (new \Bitrix\Main\File\Image($arParams['AVATAR']["tmp_name"]))->getInfo();
1715 if(
1716 !$imageCheck
1717 || !$imageCheck->getWidth()
1718 || $imageCheck->getWidth() > 5000
1719 || !$imageCheck->getHeight()
1720 || $imageCheck->getHeight() > 5000
1721 )
1722 {
1723 throw new Bitrix\Rest\RestException("Avatar incorrect size (max 5000x5000)", "AVATAR_ERROR", CRestServer::STATUS_WRONG_REQUEST);
1724 }
1725
1726 $arParams['AVATAR'] = CFile::saveFile($arParams['AVATAR'], 'im');
1727
1728 $result = CIMDisk::UpdateAvatarId($arParams['CHAT_ID'], $arParams['AVATAR'], $userId);
1729 if (!$result)
1730 {
1731 throw new Bitrix\Rest\RestException("Chat isn't exists", "WRONG_REQUEST", CRestServer::STATUS_WRONG_REQUEST);
1732 }
1733
1734 return true;
1735 }
1736
1737 public static function chatUserAdd($arParams, $n, CRestServer $server)
1738 {
1739 global $USER;
1740
1741 $arParams = array_change_key_case($arParams, CASE_UPPER);
1742
1743 if (isset($arParams['DIALOG_ID']))
1744 {
1745 if (\Bitrix\Im\Common::isChatId($arParams['DIALOG_ID']))
1746 {
1747 $arParams['CHAT_ID'] = \Bitrix\Im\Dialog::getChatId($arParams['DIALOG_ID']);
1748 }
1749 else
1750 {
1751 throw new Bitrix\Rest\RestException("Dialog ID can't be empty", "DIALOG_ID_EMPTY", CRestServer::STATUS_WRONG_REQUEST);
1752 }
1753 }
1754
1755 $arParams['CHAT_ID'] = intval($arParams['CHAT_ID']);
1756
1757 if ($arParams['CHAT_ID'] <= 0)
1758 {
1759 throw new Bitrix\Rest\RestException("Chat ID can't be empty", "CHAT_ID_EMPTY", CRestServer::STATUS_WRONG_REQUEST);
1760 }
1761
1762 if (CIMChat::GetGeneralChatId() == $arParams['CHAT_ID'])
1763 {
1764 throw new Bitrix\Rest\RestException("Action unavailable", "ACCESS_ERROR", CRestServer::STATUS_FORBIDDEN);
1765 }
1766
1767 if (!Chat::isActionAllowed('chat' . $arParams['CHAT_ID'], 'EXTEND'))
1768 {
1769 throw new Bitrix\Rest\RestException('It is forbidden to add users to this chat', 'ACCESS_ERROR', CRestServer::STATUS_FORBIDDEN);
1770 }
1771
1772 $userId = $USER->GetID();
1773 if ($server->getMethod() == "imbot.chat.user.add")
1774 {
1775 $userId = self::getBotId($arParams, $server);
1776 }
1777
1778 $hideHistory = null;
1779 if (isset($arParams['HIDE_HISTORY']))
1780 {
1781 if ($arParams['HIDE_HISTORY'] == 'N')
1782 {
1783 $hideHistory = false;
1784 }
1785 else
1786 {
1787 $hideHistory = (bool)$arParams['HIDE_HISTORY'];
1788 }
1789 }
1790
1791 if (\Bitrix\Im\User::getInstance($userId)->isExtranet())
1792 {
1793 if (is_string($arParams['USERS']))
1794 {
1795 $arParams['USERS'] = \CUtil::JsObjectToPhp($arParams['USERS']);
1796 }
1797 if (!is_array($arParams['USERS']))
1798 {
1799 throw new Bitrix\Rest\RestException("User IDs must be passed in array format", "WRONG_REQUEST", CRestServer::STATUS_WRONG_REQUEST);
1800 }
1802 }
1803
1804 $CIMChat = new CIMChat($userId);
1805 $result = $CIMChat->AddUser($arParams['CHAT_ID'], $arParams['USERS'], $hideHistory);
1806 if (!$result)
1807 {
1808 throw new Bitrix\Rest\RestException("You don't have access or user already member in chat", "WRONG_REQUEST", CRestServer::STATUS_WRONG_REQUEST);
1809 }
1810
1811 return true;
1812 }
1813
1814 public static function chatUserDelete($arParams, $n, CRestServer $server)
1815 {
1816 global $USER;
1817
1818 $arParams = array_change_key_case($arParams, CASE_UPPER);
1819
1820 if (isset($arParams['DIALOG_ID']))
1821 {
1822 if (\Bitrix\Im\Common::isChatId($arParams['DIALOG_ID']))
1823 {
1824 $arParams['CHAT_ID'] = \Bitrix\Im\Dialog::getChatId($arParams['DIALOG_ID']);
1825 }
1826 else
1827 {
1828 throw new Bitrix\Rest\RestException("Dialog ID can't be empty", "DIALOG_ID_EMPTY", CRestServer::STATUS_WRONG_REQUEST);
1829 }
1830 }
1831
1832 $arParams['CHAT_ID'] = intval($arParams['CHAT_ID']);
1833 $arParams['USER_ID'] = intval($arParams['USER_ID']);
1834
1835 if ($arParams['CHAT_ID'] <= 0)
1836 {
1837 throw new Bitrix\Rest\RestException("Chat ID can't be empty", "CHAT_ID_EMPTY", CRestServer::STATUS_WRONG_REQUEST);
1838 }
1839
1840 if (CIMChat::GetGeneralChatId() == $arParams['CHAT_ID'])
1841 {
1842 throw new Bitrix\Rest\RestException("Action unavailable", "ACCESS_ERROR", CRestServer::STATUS_FORBIDDEN);
1843 }
1844
1845 if (!Chat::isActionAllowed('chat' . $arParams['CHAT_ID'], 'LEAVE'))
1846 {
1847 throw new Bitrix\Rest\RestException('It is forbidden to delete users of this chat', 'ACCESS_ERROR', CRestServer::STATUS_FORBIDDEN);
1848 }
1849
1850 $userId = $USER->GetID();
1851 if (in_array($server->getMethod(), Array("imbot.chat.leave", "imbot.chat.user.delete")))
1852 {
1853 $userId = self::getBotId($arParams, $server);
1854 }
1855
1856 if (in_array($server->getMethod(), Array("im.chat.user.delete", "imbot.chat.user.delete")) && $arParams['USER_ID'] <= 0)
1857 {
1858 throw new Bitrix\Rest\RestException("User ID can't be empty", "USER_ID_EMPTY", CRestServer::STATUS_WRONG_REQUEST);
1859 }
1860
1861 $CIMChat = new CIMChat($userId);
1862 $result = $CIMChat->DeleteUser($arParams['CHAT_ID'], $arParams['USER_ID'] > 0? $arParams['USER_ID']: $userId);
1863 if (!$result)
1864 {
1865 $error = $GLOBALS['APPLICATION']->GetException();
1866 if ($error->GetID() === 'LEAVE_OWNER_FORBIDDEN')
1867 {
1868 throw new Bitrix\Rest\RestException($error->GetString(), "ACCESS_ERROR", CRestServer::STATUS_FORBIDDEN);
1869 }
1870
1871 throw new Bitrix\Rest\RestException("You don't have access or user isn't member in chat", "WRONG_REQUEST", CRestServer::STATUS_WRONG_REQUEST);
1872 }
1873
1874 return true;
1875 }
1876
1877 public static function chatUserList($arParams, $n, CRestServer $server)
1878 {
1879 global $USER;
1880
1881 $arParams = array_change_key_case($arParams, CASE_UPPER);
1882
1883 if (isset($arParams['DIALOG_ID']))
1884 {
1885 if (\Bitrix\Im\Common::isChatId($arParams['DIALOG_ID']))
1886 {
1887 $arParams['CHAT_ID'] = \Bitrix\Im\Dialog::getChatId($arParams['DIALOG_ID']);
1888 }
1889 else
1890 {
1891 throw new Bitrix\Rest\RestException("Dialog ID can't be empty", "DIALOG_ID_EMPTY", CRestServer::STATUS_WRONG_REQUEST);
1892 }
1893 }
1894
1895 $arParams['CHAT_ID'] = intval($arParams['CHAT_ID']);
1896
1897 if ($arParams['CHAT_ID'] <= 0)
1898 {
1899 throw new Bitrix\Rest\RestException("Chat ID can't be empty", "CHAT_ID_EMPTY", CRestServer::STATUS_WRONG_REQUEST);
1900 }
1901
1902 if (CIMChat::GetGeneralChatId() == $arParams['CHAT_ID'])
1903 {
1904 throw new Bitrix\Rest\RestException("Action unavailable", "ACCESS_ERROR", CRestServer::STATUS_FORBIDDEN);
1905 }
1906
1907 $userId = $USER->GetID();
1908 if ($server->getMethod() == "imbot.chat.user.list")
1909 {
1910 $userId = self::getBotId($arParams, $server);
1911 }
1912
1913 $arChat = CIMChat::GetChatData(array(
1914 'ID' => $arParams['CHAT_ID'],
1915 'USE_CACHE' => 'Y',
1916 'USER_ID' => $userId
1917 ));
1918
1919 return isset($arChat['userInChat'][$arParams['CHAT_ID']])? $arChat['userInChat'][$arParams['CHAT_ID']]: Array();
1920 }
1921
1922 public static function chatMute($arParams, $n, CRestServer $server)
1923 {
1924 $arParams = array_change_key_case($arParams, CASE_UPPER);
1925
1926 if (isset($arParams['DIALOG_ID']))
1927 {
1928 if (\Bitrix\Im\Common::isChatId($arParams['DIALOG_ID']))
1929 {
1930 $arParams['CHAT_ID'] = \Bitrix\Im\Dialog::getChatId($arParams['DIALOG_ID']);
1931 }
1932 else
1933 {
1934 throw new Bitrix\Rest\RestException("Dialog ID can't be empty", "DIALOG_ID_EMPTY", CRestServer::STATUS_WRONG_REQUEST);
1935 }
1936 }
1937
1938 $arParams['CHAT_ID'] = intval($arParams['CHAT_ID']);
1939 if ($arParams['CHAT_ID'] <= 0)
1940 {
1941 throw new Bitrix\Rest\RestException("Chat ID can't be empty", "CHAT_ID_EMPTY", CRestServer::STATUS_WRONG_REQUEST);
1942 }
1943
1944 if (!Chat::isActionAllowed('chat' . $arParams['CHAT_ID'], 'MUTE'))
1945 {
1946 throw new Bitrix\Rest\RestException('This chat cannot be muted', 'ACCESS_ERROR', CRestServer::STATUS_FORBIDDEN);
1947 }
1948
1949 if (isset($arParams['ACTION']))
1950 {
1951 $arParams['MUTE'] = $arParams['ACTION'];
1952 }
1953
1954 return \Bitrix\Im\Chat::mute($arParams['CHAT_ID'], $arParams['MUTE'] != 'N');
1955 }
1956
1957 public static function chatParentJoin($arParams, $n, CRestServer $server)
1958 {
1959 $arParams = array_change_key_case($arParams, CASE_UPPER);
1960
1961 if (isset($arParams['DIALOG_ID']))
1962 {
1963 if (\Bitrix\Im\Common::isChatId($arParams['DIALOG_ID']))
1964 {
1965 $arParams['CHAT_ID'] = \Bitrix\Im\Dialog::getChatId($arParams['DIALOG_ID']);
1966 }
1967 else
1968 {
1969 throw new Bitrix\Rest\RestException("Dialog ID can't be empty", "DIALOG_ID_EMPTY", CRestServer::STATUS_WRONG_REQUEST);
1970 }
1971 }
1972
1973 $arParams['CHAT_ID'] = intval($arParams['CHAT_ID']);
1974 if ($arParams['CHAT_ID'] <= 0)
1975 {
1976 throw new Bitrix\Rest\RestException("Chat ID can't be empty", "CHAT_ID_EMPTY", CRestServer::STATUS_WRONG_REQUEST);
1977 }
1978
1979 $arParams['MESSAGE_ID'] = intval($arParams['MESSAGE_ID']);
1980 if ($arParams['MESSAGE_ID'] <= 0)
1981 {
1982 throw new Bitrix\Rest\RestException("Message ID can't be empty", "MESSAGE_ID_EMPTY", CRestServer::STATUS_WRONG_REQUEST);
1983 }
1984
1985 $chat = new CIMChat();
1986
1987 if (!$chat->JoinParent($arParams['CHAT_ID'], $arParams['MESSAGE_ID']))
1988 {
1989 throw new Bitrix\Rest\RestException("Action unavailable", "ACCESS_ERROR", CRestServer::STATUS_WRONG_REQUEST);
1990 }
1991
1992 return true;
1993 }
1994
1995 public static function chatUrlGet($arParams, $n, CRestServer $server)
1996 {
1997 $arParams = array_change_key_case($arParams, CASE_UPPER);
1998 $filter = [
1999 'SEARCH_URL' => $arParams['SEARCH_URL'] ?? null,
2000 'USER_ID' => $arParams['USER_ID'] ?? null,
2001 'CHAT_ID' => $arParams['CHAT_ID'] ?? null,
2002 'DATE_FROM' => $arParams['DATE_FROM'] ? new DateTime($arParams['DATE_FROM'], DateTimeInterface::RFC3339) : null,
2003 'DATE_TO' => $arParams['DATE_TO'] ? new DateTime($arParams['DATE_TO'], DateTimeInterface::RFC3339) : null,
2004 ];
2005 $limit = self::getLimit($arParams);
2006 $offset = self::getOffset($n, $arParams);
2007 $order = [
2008 'MESSAGE_ID' => $arParams['ORDER']['MESSAGE_ID'] ?? 'DESC'
2009 ];
2010 if (!isset($filter['CHAT_ID']))
2011 {
2012 throw new \Bitrix\Rest\RestException('CHAT_ID can`t be empty', 'CHAT_ID_EMPTY', \CRestServer::STATUS_WRONG_REQUEST);
2013 }
2014
2015 $chatId = $filter['CHAT_ID'];
2016 $chat = \Bitrix\Im\V2\Chat::getInstance($chatId);
2017
2018 if (!$chat->checkAccess()->isSuccess())
2019 {
2020 throw new \Bitrix\Rest\RestException('You do not have access to this chat', Bitrix\Im\V2\Rest\RestError::ACCESS_ERROR, \CRestServer::STATUS_FORBIDDEN);
2021 }
2022
2023 $startId = $chat->getStartId();
2024
2025 if ($startId > 0)
2026 {
2027 $filter['START_ID'] = $startId;
2028 }
2029
2030 $urls = \Bitrix\Im\V2\Link\Url\UrlCollection::find($filter, $order, $limit, new \Bitrix\Im\V2\Service\Context(), $offset);
2031
2032 return (new RestAdapter($urls))->toRestFormat();
2033 }
2034
2035 public static function chatUrlDelete($arParams, $n, CRestServer $server)
2036 {
2037 $arParams = array_change_key_case($arParams, CASE_UPPER);
2038
2039 if (!isset($arParams['LINK_ID']) || (int)$arParams['LINK_ID'] <= 0)
2040 {
2041 throw new \Bitrix\Rest\RestException('LINK_ID can`t be empty', 'LINK_ID_EMPTY', \CRestServer::STATUS_WRONG_REQUEST);
2042 }
2043
2044 $linkId = (int)$arParams['LINK_ID'];
2045 $url = new \Bitrix\Im\V2\Link\Url\UrlItem($linkId);
2046 if ($url->getId() === null)
2047 {
2048 throw new \Bitrix\Rest\RestException('Url not found', \Bitrix\Im\V2\Entity\Url\UrlError::NOT_FOUND, \CRestServer::STATUS_NOT_FOUND);
2049 }
2050
2051 $chatId = $url->getChatId();
2052 $chat = \Bitrix\Im\V2\Chat::getInstance($chatId);
2053
2054 if (!$chat->checkAccess()->isSuccess())
2055 {
2056 throw new \Bitrix\Rest\RestException('You do not have access to this chat', Bitrix\Im\V2\Rest\RestError::ACCESS_ERROR, \CRestServer::STATUS_FORBIDDEN);
2057 }
2058
2059 global $USER;
2060 $userId = (int)$USER->GetID();
2061
2062 if ($userId !== $url->getAuthorId() && !$USER->IsAdmin())
2063 {
2064 throw new \Bitrix\Rest\RestException('You do not have access to delete this url', \Bitrix\Im\V2\Entity\Url\UrlError::ACCESS_ERROR, \CRestServer::STATUS_FORBIDDEN);
2065 }
2066
2067 $urls = new \Bitrix\Im\V2\Link\Url\UrlCollection();
2068 $urls->add($url);
2069
2070 $deleteResult = (new \Bitrix\Im\V2\Link\Url\UrlService())->deleteUrls($urls);
2071
2072 if (!$deleteResult->isSuccess())
2073 {
2074 throw new \Bitrix\Rest\RestException('Failed to delete url', \Bitrix\Im\V2\Entity\Url\UrlError::DELETE_ERROR, \CRestServer::STATUS_INTERNAL);
2075 }
2076
2077 return true;
2078 }
2079
2080 public static function chatUrlCounterGet($arParams, $n, CRestServer $server)
2081 {
2082 $arParams = array_change_key_case($arParams, CASE_UPPER);
2083 if (!isset($arParams['CHAT_ID']))
2084 {
2085 throw new \Bitrix\Rest\RestException('CHAT_ID can`t be empty', 'CHAT_ID_EMPTY', \CRestServer::STATUS_WRONG_REQUEST);
2086 }
2087
2088 $chatId = $arParams['CHAT_ID'];
2089 $chat = \Bitrix\Im\V2\Chat::getInstance($chatId);
2090
2091 if (!$chat->checkAccess()->isSuccess())
2092 {
2093 throw new \Bitrix\Rest\RestException('You do not have access to this chat', Bitrix\Im\V2\Rest\RestError::ACCESS_ERROR, \CRestServer::STATUS_FORBIDDEN);
2094 }
2095
2096 $startId = $chat->getStartId();
2097
2098 return [
2099 'counter' => (new \Bitrix\Im\V2\Link\Url\UrlService())->getCount($chatId, $startId)
2100 ];
2101 }
2102
2103 public static function chatFileGet($arParams, $n, CRestServer $server)
2104 {
2105 $arParams = array_change_key_case($arParams, CASE_UPPER);
2106 $filter = [
2107 'SEARCH_FILE_NAME' => $arParams['SEARCH_FILE_NAME'] ?? null,
2108 'LAST_ID' => $arParams['LAST_ID'] ?? null,
2109 'SUBTYPE' => $arParams['SUBTYPE'] ?? null,
2110 'USER_ID' => $arParams['USER_ID'] ?? null,
2111 'CHAT_ID' => $arParams['CHAT_ID'] ?? null,
2112 'DATE_FROM' => $arParams['DATE_FROM'] ? new DateTime($arParams['DATE_FROM'], DateTimeInterface::RFC3339) : null,
2113 'DATE_TO' => $arParams['DATE_TO'] ? new DateTime($arParams['DATE_TO'], DateTimeInterface::RFC3339) : null,
2114 'GROUP' => $arParams['GROUP'] ?? null,
2115 ];
2116 $limit = self::getLimit($arParams);
2117 $order = [
2118 'ID' => $arParams['ORDER']['ID'] ?? 'DESC',
2119 ];
2120 if (!isset($filter['CHAT_ID']))
2121 {
2122 throw new \Bitrix\Rest\RestException('CHAT_ID can`t be empty', 'CHAT_ID_EMPTY', \CRestServer::STATUS_WRONG_REQUEST);
2123 }
2124
2125 $chatId = $filter['CHAT_ID'];
2126 $chat = \Bitrix\Im\V2\Chat::getInstance($chatId);
2127
2128 if (!$chat->checkAccess()->isSuccess())
2129 {
2130 throw new \Bitrix\Rest\RestException('You do not have access to this chat', Bitrix\Im\V2\Rest\RestError::ACCESS_ERROR, \CRestServer::STATUS_FORBIDDEN);
2131 }
2132
2133 if (isset($filter['SUBTYPE']))
2134 {
2135 $filter['SUBTYPE'] = FileItem::normalizeFilterFromJsonFormat($filter['SUBTYPE']);
2136 }
2137 elseif (isset($filter['GROUP']))
2138 {
2139 $filter['GROUP'] = FileItem::normalizeFilterFromJsonFormat($filter['GROUP']);
2140 }
2141
2142 $startId = $chat->getStartId();
2143
2144 if ($startId > 0)
2145 {
2146 $filter['START_ID'] = $startId;
2147 }
2148
2149 $files = FileCollection::find($filter, $order, $limit, new \Bitrix\Im\V2\Service\Context());
2150
2151 return (new RestAdapter($files))->toRestFormat();
2152 }
2153
2154 public static function chatFileCollectionGet($arParams, $n, CRestServer $server)
2155 {
2156 $arParams = array_change_key_case($arParams, CASE_UPPER);
2157 $filter = [
2158 'CHAT_ID' => $arParams['CHAT_ID'] ?? null,
2159 ];
2160 $limit = self::getLimit($arParams);
2161 if (!isset($filter['CHAT_ID']))
2162 {
2163 throw new \Bitrix\Rest\RestException('CHAT_ID can`t be empty', 'CHAT_ID_EMPTY', \CRestServer::STATUS_WRONG_REQUEST);
2164 }
2165
2166 $chatId = $filter['CHAT_ID'];
2167 $chat = \Bitrix\Im\V2\Chat::getInstance($chatId);
2168
2169 if (!$chat->checkAccess()->isSuccess())
2170 {
2171 throw new \Bitrix\Rest\RestException('You do not have access to this chat', Bitrix\Im\V2\Rest\RestError::ACCESS_ERROR, \CRestServer::STATUS_FORBIDDEN);
2172 }
2173
2174 $startId = $chat->getStartId();
2175
2176 if ($startId > 0)
2177 {
2178 $filter['START_ID'] = $startId;
2179 }
2180
2181 $files = new FileCollection();
2182
2183 foreach (SubtypeGroup::cases() as $subtypeGroup)
2184 {
2185 $filter['GROUP'] = $subtypeGroup->value;
2186 $filesBySubtype = FileCollection::find($filter, [], $limit);
2187
2188 foreach ($filesBySubtype as $fileBySubtype)
2189 {
2190 $files[] = $fileBySubtype;
2191 }
2192 }
2193
2194 return (new RestAdapter($files))->toRestFormat();
2195 }
2196
2197 public static function chatFavoriteGet($arParams, $n, CRestServer $server)
2198 {
2199 $arParams = array_change_key_case($arParams, CASE_UPPER);
2200 $filter = [
2201 'LAST_ID' => $arParams['LAST_ID'] ?? null,
2202 'SEARCH_MESSAGE' => $arParams['SEARCH_MESSAGE'] ?? null,
2203 'USER_ID' => $arParams['USER_ID'] ?? null,
2204 'CHAT_ID' => $arParams['CHAT_ID'] ?? null,
2205 'DATE_FROM' => $arParams['DATE_FROM'] ? new DateTime($arParams['DATE_FROM'], DateTimeInterface::RFC3339) : null,
2206 'DATE_TO' => $arParams['DATE_TO'] ? new DateTime($arParams['DATE_TO'], DateTimeInterface::RFC3339) : null,
2207 ];
2208 $limit = self::getLimit($arParams);
2209 $order = [
2210 'ID' => $arParams['ORDER']['ID'] ?? 'DESC',
2211 ];
2212 if (!isset($filter['CHAT_ID']))
2213 {
2214 throw new \Bitrix\Rest\RestException('CHAT_ID can`t be empty', 'CHAT_ID_EMPTY', \CRestServer::STATUS_WRONG_REQUEST);
2215 }
2216
2217 $chatId = $filter['CHAT_ID'];
2218 $chat = \Bitrix\Im\V2\Chat::getInstance($chatId);
2219
2220 if (!$chat->checkAccess()->isSuccess())
2221 {
2222 throw new \Bitrix\Rest\RestException('You do not have access to this chat', Bitrix\Im\V2\Rest\RestError::ACCESS_ERROR, \CRestServer::STATUS_FORBIDDEN);
2223 }
2224
2226
2227 return (new RestAdapter($favoriteMessage))->toRestFormat();
2228 }
2229
2230 public static function chatFavoriteAdd($arParams, $n, CRestServer $server)
2231 {
2232 $arParams = array_change_key_case($arParams, CASE_UPPER);
2233 if (!isset($arParams['MESSAGE_ID']) || (int)$arParams['MESSAGE_ID'] <= 0)
2234 {
2235 throw new \Bitrix\Rest\RestException('MESSAGE_ID can`t be empty', 'MESSAGE_ID_EMPTY', \CRestServer::STATUS_WRONG_REQUEST);
2236 }
2237
2238 $messageId = (int)$arParams['MESSAGE_ID'];
2239
2240 $message = new \Bitrix\Im\V2\Message($messageId);
2241
2242 if ($message->getMessageId() === null)
2243 {
2244 throw new \Bitrix\Rest\RestException('Message not found', \Bitrix\Im\V2\Message\MessageError::MESSAGE_NOT_FOUND, \CRestServer::STATUS_WRONG_REQUEST);
2245 }
2246
2247 $chat = $message->getChat();
2248
2249 if (!$chat->checkAccess()->isSuccess())
2250 {
2251 throw new \Bitrix\Rest\RestException('You do not have access to this chat', Bitrix\Im\V2\Rest\RestError::ACCESS_ERROR, \CRestServer::STATUS_FORBIDDEN);
2252 }
2253
2254 if ($chat->getStartId() > $messageId)
2255 {
2256 throw new \Bitrix\Rest\RestException('You do not have access to this message', \Bitrix\Im\V2\Message\MessageError::ACCESS_DENIED, \CRestServer::STATUS_FORBIDDEN);
2257 }
2258
2259 $markResult = $message->markAsFavorite();
2260 if (!$markResult->isSuccess())
2261 {
2262 $error = $markResult->getErrors()[0];
2263 if (isset($error))
2264 {
2265 throw new \Bitrix\Rest\RestException($error->getMessage(), $error->getCode(), \CRestServer::STATUS_WRONG_REQUEST);
2266 }
2267 }
2268
2269 return $markResult->isSuccess();
2270 }
2271
2272 public static function chatFavoriteDelete($arParams, $n, CRestServer $server)
2273 {
2274 $arParams = array_change_key_case($arParams, CASE_UPPER);
2275 if (!isset($arParams['MESSAGE_ID']) || (int)$arParams['MESSAGE_ID'] <= 0)
2276 {
2277 throw new \Bitrix\Rest\RestException('MESSAGE_ID can`t be empty', 'MESSAGE_ID_EMPTY', \CRestServer::STATUS_WRONG_REQUEST);
2278 }
2279
2280 $messageId = (int)$arParams['MESSAGE_ID'];
2281
2282 $message = new \Bitrix\Im\V2\Message($messageId);
2283
2284 if ($message->getMessageId() === null)
2285 {
2286 throw new \Bitrix\Rest\RestException('Message not found', \Bitrix\Im\V2\Message\MessageError::MESSAGE_NOT_FOUND, \CRestServer::STATUS_WRONG_REQUEST);
2287 }
2288
2289 $unmarkResult = $message->unmarkAsFavorite();
2290 if (!$unmarkResult->isSuccess())
2291 {
2292 $error = $unmarkResult->getErrors()[0];
2293 if (isset($error))
2294 {
2295 throw new \Bitrix\Rest\RestException($error->getMessage(), $error->getCode(), \CRestServer::STATUS_WRONG_REQUEST);
2296 }
2297 }
2298
2299 return $unmarkResult->isSuccess();
2300 }
2301
2302 public static function chatFavoriteCounterGet($arParams, $n, CRestServer $server)
2303 {
2304 $arParams = array_change_key_case($arParams, CASE_UPPER);
2305 if (!isset($arParams['CHAT_ID']))
2306 {
2307 throw new \Bitrix\Rest\RestException('CHAT_ID can`t be empty', 'CHAT_ID_EMPTY', \CRestServer::STATUS_WRONG_REQUEST);
2308 }
2309
2310 $chatId = $arParams['CHAT_ID'];
2311 $chat = \Bitrix\Im\V2\Chat::getInstance($chatId);
2312
2313 if (!$chat->checkAccess()->isSuccess())
2314 {
2315 throw new \Bitrix\Rest\RestException('You do not have access to this chat', Bitrix\Im\V2\Rest\RestError::ACCESS_ERROR, \CRestServer::STATUS_FORBIDDEN);
2316 }
2317
2318 return [
2319 'counter' => (new \Bitrix\Im\V2\Link\Favorite\FavoriteService())->getCount($chatId)
2320 ];
2321 }
2322
2323 public static function chatTaskGet($arParams, $n, CRestServer $server)
2324 {
2325 $arParams = array_change_key_case($arParams, CASE_UPPER);
2326 $filter = [
2327 'CHAT_ID' => $arParams['CHAT_ID'] ?? null,
2328 'USER_ID' => $arParams['USER_ID'] ?? null,
2329 'DATE_FROM' => $arParams['DATE_FROM'] ? new DateTime($arParams['DATE_FROM'], DateTimeInterface::RFC3339) : null,
2330 'DATE_TO' => $arParams['DATE_TO'] ? new DateTime($arParams['DATE_TO'], DateTimeInterface::RFC3339) : null,
2331 'SEARCH_TASK_NAME' => $arParams['SEARCH_TASK_NAME'] ?? null,
2332 'LAST_ID' => $arParams['LAST_ID'] ?? null,
2333 ];
2334 $limit = self::getLimit($arParams);
2335 $order = [
2336 'ID' => $arParams['ORDER']['ID'] ?? 'DESC'
2337 ];
2338 if (!isset($filter['CHAT_ID']))
2339 {
2340 throw new \Bitrix\Rest\RestException('CHAT_ID can`t be empty', 'CHAT_ID_EMPTY', \CRestServer::STATUS_WRONG_REQUEST);
2341 }
2342
2343 $chatId = $filter['CHAT_ID'];
2344 $chat = \Bitrix\Im\V2\Chat::getInstance($chatId);
2345
2346 if (!$chat->checkAccess()->isSuccess())
2347 {
2348 throw new \Bitrix\Rest\RestException('You do not have access to this chat', Bitrix\Im\V2\Rest\RestError::ACCESS_ERROR, \CRestServer::STATUS_FORBIDDEN);
2349 }
2350
2352
2353 return (new RestAdapter($tasks))->toRestFormat();
2354 }
2355
2356 public static function chatTaskDelete($arParams, $n, CRestServer $server)
2357 {
2358 $arParams = array_change_key_case($arParams, CASE_UPPER);
2359
2360 if (!isset($arParams['LINK_ID']) || (int)$arParams['LINK_ID'] <= 0)
2361 {
2362 throw new \Bitrix\Rest\RestException('LINK_ID can`t be empty', 'LINK_ID_EMPTY', \CRestServer::STATUS_WRONG_REQUEST);
2363 }
2364
2365 $linkId = (int)$arParams['LINK_ID'];
2366 $task = new \Bitrix\Im\V2\Link\Task\TaskItem($linkId);
2367 if ($task->getId() === null)
2368 {
2369 throw new \Bitrix\Rest\RestException('Task not found', \Bitrix\Im\V2\Entity\Task\TaskError::NOT_FOUND, \CRestServer::STATUS_NOT_FOUND);
2370 }
2371
2372 $chatId = $task->getChatId();
2373 $chat = \Bitrix\Im\V2\Chat::getInstance($chatId);
2374
2375 if (!$chat->checkAccess()->isSuccess() || !$chat->canDo(\Bitrix\Im\V2\Permission\Action::CreateTask))
2376 {
2377 throw new \Bitrix\Rest\RestException('You do not have access to this chat', Bitrix\Im\V2\Rest\RestError::ACCESS_ERROR, \CRestServer::STATUS_FORBIDDEN);
2378 }
2379
2380 global $USER;
2381 $userId = (int)$USER->GetID();
2382
2383 if ($userId !== $task->getAuthorId() && !$USER->IsAdmin())
2384 {
2385 throw new \Bitrix\Rest\RestException('You do not have access to delete this task', \Bitrix\Im\V2\Entity\Task\TaskError::ACCESS_ERROR, \CRestServer::STATUS_FORBIDDEN);
2386 }
2387
2388 $deleteResult = (new \Bitrix\Im\V2\Link\Task\TaskService())->unregisterTask($task, false);
2389
2390 if (!$deleteResult->isSuccess())
2391 {
2392 throw new \Bitrix\Rest\RestException('Failed to delete task', \Bitrix\Im\V2\Entity\Task\TaskError::DELETE_ERROR, \CRestServer::STATUS_INTERNAL);
2393 }
2394
2395 return true;
2396 }
2397
2398 public static function chatTaskPrepare($arParams, $n, CRestServer $server)
2399 {
2400 $arParams = array_change_key_case($arParams, CASE_UPPER);
2401 if ($server->getAuthType() !== \Bitrix\Rest\SessionAuth\Auth::AUTH_TYPE && !self::isDebugEnabled())
2402 {
2403 throw new \Bitrix\Rest\RestException('This method is available only with session auth type', 'WRONG_AUTH_TYPE', \CRestServer::STATUS_WRONG_REQUEST);
2404 }
2405
2406 $message = null;
2407 $messageId = null;
2408
2409 if (isset($arParams['MESSAGE_ID']) && (int)$arParams['MESSAGE_ID'] > 0)
2410 {
2411 $messageId = (int)$arParams['MESSAGE_ID'];
2412
2413 $message = new \Bitrix\Im\V2\Message($messageId);
2414
2415 if ($message->getMessageId() === null)
2416 {
2417 throw new \Bitrix\Rest\RestException('Message not found', \Bitrix\Im\V2\Message\MessageError::MESSAGE_NOT_FOUND, \CRestServer::STATUS_WRONG_REQUEST);
2418 }
2419
2420 $chat = $message->getChat();
2421 }
2422 elseif (isset($arParams['CHAT_ID']) && (int)$arParams['CHAT_ID'] > 0)
2423 {
2424 $chatId = (int)$arParams['CHAT_ID'];
2425
2426 $chat = \Bitrix\Im\V2\Chat::getInstance($chatId);
2427 }
2428 else
2429 {
2430 throw new Bitrix\Rest\RestException('Message ID and chat ID can`t be empty together', 'CHAT_ID_MESSAGE_ID_EMPTY', CRestServer::STATUS_WRONG_REQUEST);
2431 }
2432
2433 if (!$chat->checkAccess()->isSuccess())
2434 {
2435 throw new \Bitrix\Rest\RestException('You do not have access to this chat', Bitrix\Im\V2\Rest\RestError::ACCESS_ERROR, \CRestServer::STATUS_FORBIDDEN);
2436 }
2437
2438 if (isset($messageId) && $messageId < $chat->getStartId())
2439 {
2440 throw new \Bitrix\Rest\RestException('You do not have access to this message', \Bitrix\Im\V2\Message\MessageError::ACCESS_DENIED, \CRestServer::STATUS_FORBIDDEN);
2441 }
2442
2443 $taskService = new \Bitrix\Im\V2\Link\Task\TaskService();
2444 $result = $taskService->prepareDataForCreateSlider($chat, $message);
2445 if (!$result->isSuccess())
2446 {
2447 $error = $result->getErrors()[0];
2448 if (isset($error))
2449 {
2450 throw new Bitrix\Rest\RestException($error->getMessage(), $error->getCode(), CRestServer::STATUS_WRONG_REQUEST);
2451 }
2452 }
2453
2454 $data = $result->getResult();
2455
2456 return [
2457 'link' => $data['LINK'],
2458 'params' => $data['PARAMS']
2459 ];
2460 }
2461
2462 public static function chatCalendarGet($arParams, $n, CRestServer $server)
2463 {
2464 $arParams = array_change_key_case($arParams, CASE_UPPER);
2465 $filter = [
2466 'CHAT_ID' => $arParams['CHAT_ID'] ?? null,
2467 'USER_ID' => $arParams['USER_ID'] ?? null,
2468 'DATE_FROM' => $arParams['DATE_FROM'] ? new DateTime($arParams['DATE_FROM'], DateTimeInterface::RFC3339) : null,
2469 'DATE_TO' => $arParams['DATE_TO'] ? new DateTime($arParams['DATE_TO'], DateTimeInterface::RFC3339) : null,
2470 'CALENDAR_DATE_FROM' => $arParams['CALENDAR_DATE_FROM'] ? new DateTime($arParams['CALENDAR_DATE_FROM'], DateTimeInterface::RFC3339) : null,
2471 'CALENDAR_DATE_TO' => $arParams['CALENDAR_DATE_TO'] ? new DateTime($arParams['CALENDAR_DATE_TO'], DateTimeInterface::RFC3339) : null,
2472 'LAST_ID' => $arParams['LAST_ID'] ?? null,
2473 'SEARCH_TITLE' => $arParams['SEARCH_TITLE'] ?? null,
2474 ];
2475 $limit = self::getLimit($arParams);
2476 $order = [
2477 'ID' => $arParams['ORDER']['ID'] ?? 'DESC'
2478 ];
2479 if (!isset($filter['CHAT_ID']))
2480 {
2481 throw new \Bitrix\Rest\RestException('CHAT_ID can`t be empty', 'CHAT_ID_EMPTY', \CRestServer::STATUS_WRONG_REQUEST);
2482 }
2483
2484 $chatId = $filter['CHAT_ID'];
2485 $chat = \Bitrix\Im\V2\Chat::getInstance($chatId);
2486
2487 if (!$chat->checkAccess()->isSuccess())
2488 {
2489 throw new \Bitrix\Rest\RestException('You do not have access to this chat', Bitrix\Im\V2\Rest\RestError::ACCESS_ERROR, \CRestServer::STATUS_FORBIDDEN);
2490 }
2491
2492 $startId = $chat->getStartId();
2493
2494 if ($startId > 0)
2495 {
2496 $filter['START_ID'] = $startId;
2497 }
2498
2500
2501 return (new RestAdapter($calendars))->toRestFormat();
2502 }
2503
2504 public static function chatCalendarAdd($arParams, $n, CRestServer $server)
2505 {
2506 $arParams = array_change_key_case($arParams, CASE_UPPER);
2507
2508 $messageId = null;
2509 $chatId = null;
2510
2511 if (isset($arParams['MESSAGE_ID']) && (int)$arParams['MESSAGE_ID'] > 0)
2512 {
2513 $messageId = (int)$arParams['MESSAGE_ID'];
2514
2515 $message = new \Bitrix\Im\V2\Message($messageId);
2516
2517 if ($message->getMessageId() === null)
2518 {
2519 throw new \Bitrix\Rest\RestException('Message not found', \Bitrix\Im\V2\Message\MessageError::MESSAGE_NOT_FOUND, \CRestServer::STATUS_WRONG_REQUEST);
2520 }
2521
2522 $chat = $message->getChat();
2523 }
2524 elseif (isset($arParams['CHAT_ID']) && (int)$arParams['CHAT_ID'] > 0)
2525 {
2526 $chatId = (int)$arParams['CHAT_ID'];
2527
2528 $chat = \Bitrix\Im\V2\Chat::getInstance($chatId);
2529 }
2530 else
2531 {
2532 throw new Bitrix\Rest\RestException('Message ID and chat ID can`t be empty together', 'CHAT_ID_MESSAGE_ID_EMPTY', CRestServer::STATUS_WRONG_REQUEST);
2533 }
2534
2535 if (!isset($arParams['CALENDAR_ID']) || (int)$arParams['CALENDAR_ID'] <= 0)
2536 {
2537 throw new \Bitrix\Rest\RestException('CALENDAR_ID can`t be empty', 'CALENDAR_ID_EMPTY', \CRestServer::STATUS_WRONG_REQUEST);
2538 }
2539
2540 if (!$chat->checkAccess()->isSuccess() || !$chat->canDo(\Bitrix\Im\V2\Permission\Action::CreateMeeting))
2541 {
2542 throw new \Bitrix\Rest\RestException('You do not have access to this chat', Bitrix\Im\V2\Rest\RestError::ACCESS_ERROR, \CRestServer::STATUS_FORBIDDEN);
2543 }
2544
2545 if (isset($messageId))
2546 {
2547 $startId = $chat->getStartId();
2548
2549 if ($messageId < $startId)
2550 {
2551 throw new \Bitrix\Rest\RestException('You do not have access to this message', \Bitrix\Im\V2\Message\MessageError::ACCESS_DENIED, \CRestServer::STATUS_FORBIDDEN);
2552 }
2553 }
2554
2555 $chatId = $chat->getChatId();
2556
2557 $calendarId = $arParams['CALENDAR_ID'];
2558
2559 $calendarService = new \Bitrix\Im\V2\Link\Calendar\CalendarService();
2561
2562 global $USER;
2563 $userId = (int)$USER->GetID();
2564 if ($userId !== $calendar->getCreatedBy())
2565 {
2566 throw new \Bitrix\Rest\RestException('You do not have access to this calendar event', Bitrix\Im\V2\Entity\Calendar\CalendarError::ACCESS_ERROR, \CRestServer::STATUS_FORBIDDEN);
2567 }
2568
2569 $saveResult = $calendarService->registerCalendar($chatId, $messageId, $calendar);
2570 if (!$saveResult->isSuccess())
2571 {
2572 $error = $saveResult->getErrors()[0];
2573 if (isset($error))
2574 {
2575 throw new \Bitrix\Rest\RestException($error->getMessage(), $error->getCode(), \CRestServer::STATUS_WRONG_REQUEST);
2576 }
2577 }
2578
2579 return $saveResult->isSuccess();
2580 }
2581
2582 public static function chatCalendarDelete($arParams, $n, CRestServer $server)
2583 {
2584 $arParams = array_change_key_case($arParams, CASE_UPPER);
2585
2586 if (!isset($arParams['LINK_ID']) || (int)$arParams['LINK_ID'] <= 0)
2587 {
2588 throw new \Bitrix\Rest\RestException('LINK_ID can`t be empty', 'LINK_ID_EMPTY', \CRestServer::STATUS_WRONG_REQUEST);
2589 }
2590
2591 $linkId = (int)$arParams['LINK_ID'];
2592 $calendar = new \Bitrix\Im\V2\Link\Calendar\CalendarItem($linkId);
2593 if ($calendar->getId() === null)
2594 {
2595 throw new \Bitrix\Rest\RestException('Calendar event not found', \Bitrix\Im\V2\Entity\Calendar\CalendarError::NOT_FOUND, \CRestServer::STATUS_NOT_FOUND);
2596 }
2597
2598 $chatId = $calendar->getChatId();
2599 $chat = \Bitrix\Im\V2\Chat::getInstance($chatId);
2600
2601 if (!$chat->checkAccess()->isSuccess() || !$chat->canDo(\Bitrix\Im\V2\Permission\Action::CreateMeeting))
2602 {
2603 throw new \Bitrix\Rest\RestException('You do not have access to this chat', Bitrix\Im\V2\Rest\RestError::ACCESS_ERROR, \CRestServer::STATUS_FORBIDDEN);
2604 }
2605
2606 global $USER;
2607 $userId = (int)$USER->GetID();
2608
2609 if ($userId !== $calendar->getAuthorId() && !$USER->IsAdmin())
2610 {
2611 throw new \Bitrix\Rest\RestException('You do not have access to delete this calendar event', \Bitrix\Im\V2\Entity\Calendar\CalendarError::ACCESS_ERROR, \CRestServer::STATUS_FORBIDDEN);
2612 }
2613
2614 $deleteResult = (new \Bitrix\Im\V2\Link\Calendar\CalendarService())->unregisterCalendar($calendar);
2615
2616 if (!$deleteResult->isSuccess())
2617 {
2618 throw new \Bitrix\Rest\RestException('Failed to delete calendar event', \Bitrix\Im\V2\Entity\Calendar\CalendarError::DELETE_ERROR, \CRestServer::STATUS_INTERNAL);
2619 }
2620
2621 return true;
2622 }
2623
2624 public static function chatCalendarPrepare($arParams, $n, CRestServer $server)
2625 {
2626 $arParams = array_change_key_case($arParams, CASE_UPPER);
2627 if ($server->getAuthType() !== \Bitrix\Rest\SessionAuth\Auth::AUTH_TYPE && !self::isDebugEnabled())
2628 {
2629 throw new \Bitrix\Rest\RestException('This method is available only with session auth type', 'WRONG_AUTH_TYPE', \CRestServer::STATUS_WRONG_REQUEST);
2630 }
2631
2632 $message = null;
2633 $messageId = null;
2634
2635 if (isset($arParams['MESSAGE_ID']) && (int)$arParams['MESSAGE_ID'] > 0)
2636 {
2637 $messageId = (int)$arParams['MESSAGE_ID'];
2638
2639 $message = new \Bitrix\Im\V2\Message($messageId);
2640
2641 if ($message->getMessageId() === null)
2642 {
2643 throw new \Bitrix\Rest\RestException('Message not found', \Bitrix\Im\V2\Message\MessageError::MESSAGE_NOT_FOUND, \CRestServer::STATUS_WRONG_REQUEST);
2644 }
2645
2646 $chat = $message->getChat();
2647 }
2648 elseif (isset($arParams['CHAT_ID']) && (int)$arParams['CHAT_ID'] > 0)
2649 {
2650 $chatId = (int)$arParams['CHAT_ID'];
2651
2652 $chat = \Bitrix\Im\V2\Chat::getInstance($chatId);
2653 }
2654 else
2655 {
2656 throw new Bitrix\Rest\RestException('Message ID and chat ID can`t be empty together', 'CHAT_ID_MESSAGE_ID_EMPTY', CRestServer::STATUS_WRONG_REQUEST);
2657 }
2658
2659 if (!$chat->checkAccess()->isSuccess())
2660 {
2661 throw new \Bitrix\Rest\RestException('You do not have access to this chat', Bitrix\Im\V2\Rest\RestError::ACCESS_ERROR, \CRestServer::STATUS_FORBIDDEN);
2662 }
2663
2664 if (isset($messageId))
2665 {
2666 $startId = $chat->getStartId();
2667
2668 if ($messageId < $startId)
2669 {
2670 throw new \Bitrix\Rest\RestException('You do not have access to this message', \Bitrix\Im\V2\Message\MessageError::ACCESS_DENIED, \CRestServer::STATUS_FORBIDDEN);
2671 }
2672 }
2673
2674 $calendarService = new \Bitrix\Im\V2\Link\Calendar\CalendarService();
2675 $result = $calendarService->prepareDataForCreateSlider($chat, $message);
2676 if (!$result->isSuccess())
2677 {
2678 $error = $result->getErrors()[0];
2679 if (isset($error))
2680 {
2681 throw new Bitrix\Rest\RestException($error->getMessage(), $error->getCode(), CRestServer::STATUS_WRONG_REQUEST);
2682 }
2683 }
2684
2685 return $result->getResult();
2686 }
2687
2688 public static function chatSignGet($arParams, $n, CRestServer $server)
2689 {
2690 $arParams = array_change_key_case($arParams, CASE_UPPER);
2691 return [
2692 'list' => [
2693 [
2694 'id' => 1,
2695 'messageId' => 2345,
2696 'chatId' => 92,
2697 'authorId' => 1,
2698 'dateCreate' => '2022-08-22T12:37:10+02:00',
2699 'sign' => [
2700 'id' => 1,
2701 'title' => 'Important document #1',
2702 'status' => 'signed',
2703 'from' => [
2704 'company' => 'Bitrix',
2705 'userId' => 1
2706 ],
2707 'to' => [
2708 'company' => null,
2709 'userId' => 1
2710 ],
2711 'links' => [
2712 'detail' => 'https://...'
2713 ]
2714 ],
2715 ],
2716 [
2717 'id' => 2,
2718 'messageId' => 2346,
2719 'chatId' => 92,
2720 'authorId' => 1,
2721 'dateCreate' => '2022-08-24T12:37:10+02:00',
2722 'sign' => [
2723 'id' => 1,
2724 'title' => 'Important document #2',
2725 'status' => 'signed',
2726 'from' => [
2727 'company' => 'Bitrix',
2728 'userId' => 1
2729 ],
2730 'to' => [
2731 'company' => null,
2732 'userId' => 1
2733 ],
2734 'links' => [
2735 'detail' => 'https://...'
2736 ]
2737 ],
2738 ]
2739 ],
2740 'users' => [\Bitrix\Im\User::getInstance(1)->getArray(['JSON' => 'Y'])]
2741 ];
2742 }
2743
2744 public static function chatPinGet($arParams, $n, CRestServer $server)
2745 {
2746 $arParams = array_change_key_case($arParams, CASE_UPPER);
2747 $filter = [
2748 'LAST_ID' => $arParams['LAST_ID'] ?? null,
2749 'CHAT_ID' => $arParams['CHAT_ID'] ?? null,
2750 ];
2751 $limit = self::getLimit($arParams);
2752 $order = [
2753 'ID' => $arParams['ORDER']['ID'] ?? 'DESC',
2754 ];
2755 if (!isset($filter['CHAT_ID']))
2756 {
2757 throw new \Bitrix\Rest\RestException('CHAT_ID can`t be empty', 'CHAT_ID_EMPTY', \CRestServer::STATUS_WRONG_REQUEST);
2758 }
2759
2760 $chatId = $filter['CHAT_ID'];
2761 $chat = \Bitrix\Im\V2\Chat::getInstance($chatId);
2762
2763 if (!$chat->checkAccess()->isSuccess())
2764 {
2765 throw new \Bitrix\Rest\RestException('You do not have access to this chat', Bitrix\Im\V2\Rest\RestError::ACCESS_ERROR, \CRestServer::STATUS_FORBIDDEN);
2766 }
2767
2768 $startId = $chat->getStartId();
2769
2770 if ($startId > 0)
2771 {
2772 $filter['START_ID'] = $startId;
2773 }
2774
2776
2777 return (new RestAdapter($pins))->toRestFormat();
2778 }
2779
2780 public static function chatPinAdd($arParams, $n, CRestServer $server)
2781 {
2782 $arParams = array_change_key_case($arParams, CASE_UPPER);
2783 if (!isset($arParams['MESSAGE_ID']) || (int)$arParams['MESSAGE_ID'] <= 0)
2784 {
2785 throw new \Bitrix\Rest\RestException('MESSAGE_ID can`t be empty', 'MESSAGE_ID_EMPTY', \CRestServer::STATUS_WRONG_REQUEST);
2786 }
2787
2788 $messageId = (int)$arParams['MESSAGE_ID'];
2789
2790 $message = new \Bitrix\Im\V2\Message($messageId);
2791
2792 if ($message->getMessageId() === null)
2793 {
2794 throw new \Bitrix\Rest\RestException('Message not found', \Bitrix\Im\V2\Message\MessageError::MESSAGE_NOT_FOUND, \CRestServer::STATUS_WRONG_REQUEST);
2795 }
2796
2797 $chat = $message->getChat();
2798
2799 if (!$chat->checkAccess()->isSuccess())
2800 {
2801 throw new \Bitrix\Rest\RestException('You do not have access to this chat', Bitrix\Im\V2\Rest\RestError::ACCESS_ERROR, \CRestServer::STATUS_FORBIDDEN);
2802 }
2803
2804 if ($chat->getStartId() > $messageId)
2805 {
2806 throw new \Bitrix\Rest\RestException('You do not have access to this message', \Bitrix\Im\V2\Message\MessageError::ACCESS_DENIED, \CRestServer::STATUS_FORBIDDEN);
2807 }
2808
2809 $pinResult = $message->pin();
2810 if (!$pinResult->isSuccess())
2811 {
2812 $error = $pinResult->getErrors()[0];
2813 if (isset($error))
2814 {
2815 throw new \Bitrix\Rest\RestException($error->getMessage(), $error->getCode(), \CRestServer::STATUS_WRONG_REQUEST);
2816 }
2817 }
2818
2819 return $pinResult->isSuccess();
2820 }
2821
2822 public static function chatPinDelete($arParams, $n, CRestServer $server)
2823 {
2824 $arParams = array_change_key_case($arParams, CASE_UPPER);
2825 if (!isset($arParams['MESSAGE_ID']) || (int)$arParams['MESSAGE_ID'] <= 0)
2826 {
2827 throw new \Bitrix\Rest\RestException('MESSAGE_ID can`t be empty', 'MESSAGE_ID_EMPTY', \CRestServer::STATUS_WRONG_REQUEST);
2828 }
2829
2830 $messageId = (int)$arParams['MESSAGE_ID'];
2831
2832 $message = new \Bitrix\Im\V2\Message($messageId);
2833
2834 if ($message->getMessageId() === null)
2835 {
2836 throw new \Bitrix\Rest\RestException('Message not found', \Bitrix\Im\V2\Message\MessageError::MESSAGE_NOT_FOUND, \CRestServer::STATUS_WRONG_REQUEST);
2837 }
2838
2839 $chat = $message->getChat();
2840
2841 if (!$chat->checkAccess()->isSuccess())
2842 {
2843 throw new \Bitrix\Rest\RestException('You do not have access to this chat', Bitrix\Im\V2\Rest\RestError::ACCESS_ERROR, \CRestServer::STATUS_FORBIDDEN);
2844 }
2845
2846 $unpinResult = $message->unpin();
2847 if (!$unpinResult->isSuccess())
2848 {
2849 $error = $unpinResult->getErrors()[0];
2850 if (isset($error))
2851 {
2852 throw new \Bitrix\Rest\RestException($error->getMessage(), $error->getCode(), \CRestServer::STATUS_WRONG_REQUEST);
2853 }
2854 }
2855
2856 return $unpinResult->isSuccess();
2857 }
2858
2859 public static function chatReminderGet($arParams, $n, CRestServer $server)
2860 {
2861 $arParams = array_change_key_case($arParams, CASE_UPPER);
2862 $filter = [
2863 'LAST_ID' => $arParams['LAST_ID'] ?? null,
2864 'SEARCH_MESSAGE' => $arParams['SEARCH_MESSAGE'] ?? null,
2865 'USER_ID' => $arParams['USER_ID'] ?? null,
2866 'CHAT_ID' => $arParams['CHAT_ID'] ?? null,
2867 'DATE_FROM' => $arParams['DATE_FROM'] ? new DateTime($arParams['DATE_FROM'], DateTimeInterface::RFC3339) : null,
2868 'DATE_TO' => $arParams['DATE_TO'] ? new DateTime($arParams['DATE_TO'], DateTimeInterface::RFC3339) : null,
2869 ];
2870 if ($arParams['IS_REMINDED'] === 'Y')
2871 {
2872 $filter['IS_REMINDED'] = true;
2873 }
2874 if ($arParams['IS_REMINDED'] === 'N')
2875 {
2876 $filter['IS_REMINDED'] = false;
2877 }
2878 $limit = self::getLimit($arParams);
2879 $order = [
2880 'ID' => $arParams['ORDER']['ID'] ?? 'DESC',
2881 ];
2882 if (!isset($filter['CHAT_ID']))
2883 {
2884 throw new \Bitrix\Rest\RestException('CHAT_ID can`t be empty', 'CHAT_ID_EMPTY', \CRestServer::STATUS_WRONG_REQUEST);
2885 }
2886
2887 $chatId = $filter['CHAT_ID'];
2888 $chat = \Bitrix\Im\V2\Chat::getInstance($chatId);
2889
2890 if (!$chat->checkAccess()->isSuccess())
2891 {
2892 throw new \Bitrix\Rest\RestException('You do not have access to this chat', Bitrix\Im\V2\Rest\RestError::ACCESS_ERROR, \CRestServer::STATUS_FORBIDDEN);
2893 }
2894
2896
2897 return (new RestAdapter($reminders))->toRestFormat();
2898 }
2899
2900 public static function chatReminderAdd($arParams, $n, CRestServer $server)
2901 {
2902 $arParams = array_change_key_case($arParams, CASE_UPPER);
2903
2904 if (!isset($arParams['DATE_REMIND']))
2905 {
2906 throw new \Bitrix\Rest\RestException('DATE_REMIND can`t be empty', \Bitrix\Im\V2\Link\Reminder\ReminderError::DATE_REMIND_EMPTY, \CRestServer::STATUS_FORBIDDEN);
2907 }
2908
2909 $dateRemind = new DateTime($arParams['DATE_REMIND'], DateTimeInterface::RFC3339);
2910
2911 if (!isset($arParams['MESSAGE_ID']) || (int)$arParams['MESSAGE_ID'] <= 0)
2912 {
2913 throw new \Bitrix\Rest\RestException('MESSAGE_ID can`t be empty', 'MESSAGE_ID_EMPTY', \CRestServer::STATUS_WRONG_REQUEST);
2914 }
2915
2916 $messageId = (int)$arParams['MESSAGE_ID'];
2917
2918 $message = new \Bitrix\Im\V2\Message($messageId);
2919
2920 if ($message->getMessageId() === null)
2921 {
2922 throw new \Bitrix\Rest\RestException('Message not found', \Bitrix\Im\V2\Message\MessageError::MESSAGE_NOT_FOUND, \CRestServer::STATUS_WRONG_REQUEST);
2923 }
2924
2925 $chat = $message->getChat();
2926
2927 if (!$chat->checkAccess()->isSuccess())
2928 {
2929 throw new \Bitrix\Rest\RestException('You do not have access to this chat', Bitrix\Im\V2\Rest\RestError::ACCESS_ERROR, \CRestServer::STATUS_FORBIDDEN);
2930 }
2931
2932 if ($chat->getStartId() > $messageId)
2933 {
2934 throw new \Bitrix\Rest\RestException('You do not have access to this message', \Bitrix\Im\V2\Message\MessageError::ACCESS_DENIED, \CRestServer::STATUS_FORBIDDEN);
2935 }
2936
2937 $addResult = $message->addToReminder($dateRemind);
2938 if (!$addResult->isSuccess())
2939 {
2940 $error = $addResult->getErrors()[0];
2941 if (isset($error))
2942 {
2943 throw new \Bitrix\Rest\RestException($error->getMessage(), $error->getCode(), \CRestServer::STATUS_WRONG_REQUEST);
2944 }
2945 }
2946
2947 return $addResult->isSuccess();
2948 }
2949
2950 public static function chatReminderDelete($arParams, $n, CRestServer $server)
2951 {
2952 $arParams = array_change_key_case($arParams, CASE_UPPER);
2953 if (!isset($arParams['REMINDER_ID']) || (int)$arParams['REMINDER_ID'] <= 0)
2954 {
2955 throw new \Bitrix\Rest\RestException('REMINDER_ID can`t be empty', 'REMINDER_ID_EMPTY', \CRestServer::STATUS_WRONG_REQUEST);
2956 }
2957
2958 $reminderId = (int)$arParams['REMINDER_ID'];
2959
2960 $reminder = new \Bitrix\Im\V2\Link\Reminder\ReminderItem($reminderId);
2961
2962 if ($reminder->getId() === null)
2963 {
2964 throw new \Bitrix\Rest\RestException('Reminder not found', \Bitrix\Im\V2\Link\Reminder\ReminderError::REMINDER_NOT_FOUND, \CRestServer::STATUS_WRONG_REQUEST);
2965 }
2966
2967 $deleteResult = (new \Bitrix\Im\V2\Link\Reminder\ReminderService())->deleteReminder($reminder);
2968 if (!$deleteResult->isSuccess())
2969 {
2970 $error = $deleteResult->getErrors()[0];
2971 if (isset($error))
2972 {
2973 throw new \Bitrix\Rest\RestException($error->getMessage(), $error->getCode(), \CRestServer::STATUS_WRONG_REQUEST);
2974 }
2975 }
2976
2977 return $deleteResult->isSuccess();
2978 }
2979
2980 public static function botList($arParams, $n, CRestServer $server)
2981 {
2982 if ($server->getAuthType() == \Bitrix\Rest\SessionAuth\Auth::AUTH_TYPE)
2983 {
2984 throw new \Bitrix\Rest\RestException("Access for this method not allowed by session authorization.", "WRONG_AUTH_TYPE", \CRestServer::STATUS_FORBIDDEN);
2985 }
2986 $result = Array();
2987 $list = \Bitrix\Im\Bot::getListCache();
2988 foreach ($list as $botId => $botData)
2989 {
2990 if ($botData['TYPE'] == \Bitrix\Im\Bot::TYPE_NETWORK)
2991 continue;
2992
2993 $result[$botId] = Array(
2994 'ID' => $botId,
2995 'NAME' => \Bitrix\Im\User::getInstance($botId)->getFullName(),
2996 'CODE' => $botData['CODE'],
2997 'OPENLINE' => $botData['OPENLINE'],
2998 );
2999 }
3000
3001 return $result;
3002 }
3003
3004 public static function messageAdd($arParams, $n, CRestServer $server)
3005 {
3006 global $USER;
3007
3008 $arParams = array_change_key_case($arParams, CASE_UPPER);
3009 $arParams['MESSAGE'] = self::getRawParam('MESSAGE') ?? $arParams['MESSAGE'] ?? null;
3010
3011 if (
3012 isset($arParams['PLATFORM_CONTEXT'])
3013 && is_string($arParams['PLATFORM_CONTEXT'])
3014 && $server->getAuthType() !== \Bitrix\Rest\SessionAuth\Auth::AUTH_TYPE
3015 )
3016 {
3017 \Bitrix\Im\Bot::setPlatformContext($arParams['PLATFORM_CONTEXT']);
3018 }
3019
3020 if (isset($arParams['MESSAGE']))
3021 {
3022 if (!is_string($arParams['MESSAGE']))
3023 {
3024 throw new Bitrix\Rest\RestException("Wrong message type", "MESSAGE_EMPTY", CRestServer::STATUS_WRONG_REQUEST);
3025 }
3026
3027 $arParams['MESSAGE'] = trim($arParams['MESSAGE']);
3028
3029 if ($arParams['MESSAGE'] == '' && empty($arParams['ATTACH']))
3030 {
3031 throw new Bitrix\Rest\RestException("Message can't be empty", "MESSAGE_EMPTY", CRestServer::STATUS_WRONG_REQUEST);
3032 }
3033 }
3034 else if (!isset($arParams['ATTACH']))
3035 {
3036 throw new Bitrix\Rest\RestException("Message can't be empty", "MESSAGE_EMPTY", CRestServer::STATUS_WRONG_REQUEST);
3037 }
3038
3039 if (isset($arParams['DIALOG_ID']))
3040 {
3041 if (\Bitrix\Im\Common::isChatId($arParams['DIALOG_ID']))
3042 {
3043 $arParams['CHAT_ID'] = \Bitrix\Im\Dialog::getChatId($arParams['DIALOG_ID']);
3044 }
3045 else
3046 {
3047 $arParams['USER_ID'] = intval($arParams['DIALOG_ID']);
3048 }
3049 }
3050
3051 $arParams['FROM_USER_ID'] = $USER->GetId();
3052 if (isset($arParams['USER_ID']))
3053 {
3054 $arParams['USER_ID'] = intval($arParams['USER_ID']);
3055 if ($arParams['USER_ID'] <= 0)
3056 {
3057 throw new Bitrix\Rest\RestException("User ID can't be empty", "USER_ID_EMPTY", CRestServer::STATUS_WRONG_REQUEST);
3058 }
3059
3060 if (!Bitrix\Im\User::getInstance($arParams['USER_ID'])->isExists())
3061 {
3062 throw new Bitrix\Rest\RestException("User not found", "USER_NOT_FOUND", CRestServer::STATUS_WRONG_REQUEST);
3063 }
3064
3065 $arMessageFields = Array(
3066 "MESSAGE_TYPE" => IM_MESSAGE_PRIVATE,
3067 "FROM_USER_ID" => $arParams['FROM_USER_ID'],
3068 "DIALOG_ID" => $arParams['USER_ID'],
3069 );
3070 }
3071 else if (isset($arParams['CHAT_ID']))
3072 {
3073 $arParams['CHAT_ID'] = intval($arParams['CHAT_ID']);
3074 if ($arParams['CHAT_ID'] <= 0)
3075 {
3076 throw new Bitrix\Rest\RestException("Chat ID can't be empty", "CHAT_ID_EMPTY", CRestServer::STATUS_WRONG_REQUEST);
3077 }
3078
3079 if (
3080 CIMChat::GetGeneralChatId() == $arParams['CHAT_ID']
3081 && !CIMChat::CanSendMessageToGeneralChat($arParams['FROM_USER_ID'])
3082 )
3083 {
3084 throw new Bitrix\Rest\RestException("Action unavailable", "ACCESS_ERROR", CRestServer::STATUS_FORBIDDEN);
3085 }
3086
3087 if (!Chat::isActionAllowed('chat' . $arParams['CHAT_ID'], 'SEND'))
3088 {
3089 throw new Bitrix\Rest\RestException('It is forbidden to send messages to this chat', 'ACCESS_ERROR', CRestServer::STATUS_FORBIDDEN);
3090 }
3091
3092 if (isset($arParams['SYSTEM']) && $arParams['SYSTEM'] == 'Y')
3093 {
3094 $clientId = $server->getClientId();
3095 if ($clientId)
3096 {
3097 $result = \Bitrix\Rest\AppTable::getList(
3098 array(
3099 'filter' => array(
3100 '=CLIENT_ID' => $clientId
3101 ),
3102 'select' => array(
3103 'CODE',
3104 'APP_NAME',
3105 'APP_NAME_DEFAULT' => 'LANG_DEFAULT.MENU_NAME',
3106 )
3107 )
3108 );
3109 $result = $result->fetch();
3110 $moduleName = !empty($result['APP_NAME'])
3111 ? $result['APP_NAME']
3112 : (!empty($result['APP_NAME_DEFAULT'])
3113 ? $result['APP_NAME_DEFAULT']
3114 : $result['CODE']
3115 )
3116 ;
3117
3118 $arParams['MESSAGE'] = "[b]".$moduleName."[/b]\n".$arParams['MESSAGE'];
3119 }
3120 }
3121
3122 $arMessageFields = Array(
3123 "MESSAGE_TYPE" => IM_MESSAGE_CHAT,
3124 "FROM_USER_ID" => $arParams['FROM_USER_ID'],
3125 "DIALOG_ID" => 'chat'.$arParams['CHAT_ID'],
3126 );
3127 }
3128 else
3129 {
3130 throw new Bitrix\Rest\RestException("Incorrect params", "PARAMS_ERROR", CRestServer::STATUS_WRONG_REQUEST);
3131 }
3132
3133 if (isset($arParams['MESSAGE']))
3134 {
3135 $arMessageFields["MESSAGE"] = $arParams['MESSAGE'];
3136 }
3137
3138 $attach = CIMMessageParamAttach::GetAttachByJson($arParams['ATTACH']);
3139 if ($attach)
3140 {
3141 if ($attach->IsAllowSize())
3142 {
3143 $arMessageFields['ATTACH'] = $attach;
3144 }
3145 else
3146 {
3147 throw new Bitrix\Rest\RestException("You have exceeded the maximum allowable size of attach", "ATTACH_OVERSIZE", CRestServer::STATUS_WRONG_REQUEST);
3148 }
3149 }
3150 else if ($arParams['ATTACH'])
3151 {
3152 throw new Bitrix\Rest\RestException("Incorrect attach params", "ATTACH_ERROR", CRestServer::STATUS_WRONG_REQUEST);
3153 }
3154
3155 if (isset($arParams['KEYBOARD']) && !empty($arParams['KEYBOARD']))
3156 {
3157 $keyboard = Array();
3158 if (is_string($arParams['KEYBOARD']))
3159 {
3160 $arParams['KEYBOARD'] = \CUtil::JsObjectToPhp($arParams['KEYBOARD']);
3161 }
3162 if (!isset($arParams['KEYBOARD']['BUTTONS']))
3163 {
3164 $keyboard['BUTTONS'] = $arParams['KEYBOARD'];
3165 }
3166 else
3167 {
3168 $keyboard = $arParams['KEYBOARD'];
3169 }
3170 $keyboard['BOT_ID'] = $arParams['BOT_ID'];
3171
3172 $keyboard = \Bitrix\Im\Bot\Keyboard::getKeyboardByJson($keyboard);
3173 if ($keyboard)
3174 {
3175 $arMessageFields['KEYBOARD'] = $keyboard;
3176 }
3177 else
3178 {
3179 throw new Bitrix\Rest\RestException("Incorrect keyboard params", "KEYBOARD_ERROR", CRestServer::STATUS_WRONG_REQUEST);
3180 }
3181 }
3182
3183 if (isset($arParams['MENU']) && !empty($arParams['MENU']))
3184 {
3185 $menu = Array();
3186 if (is_string($arParams['MENU']))
3187 {
3188 $arParams['MENU'] = \CUtil::JsObjectToPhp($arParams['MENU']);
3189 }
3190 if (!isset($arParams['MENU']['ITEMS']))
3191 {
3192 $menu['ITEMS'] = $arParams['MENU'];
3193 }
3194 else
3195 {
3196 $menu = $arParams['MENU'];
3197 }
3198 $menu['BOT_ID'] = $arParams['BOT_ID'];
3199
3201 if ($menu)
3202 {
3203 $arMessageFields['MENU'] = $menu;
3204 }
3205 else
3206 {
3207 throw new Bitrix\Rest\RestException("Incorrect menu params", "MENU_ERROR", CRestServer::STATUS_WRONG_REQUEST);
3208 }
3209 }
3210
3211 if (
3212 isset($arParams['SYSTEM']) && $arParams['SYSTEM'] == 'Y'
3213 && $server->getAuthType() !== \Bitrix\Rest\SessionAuth\Auth::AUTH_TYPE
3214 && \Bitrix\Im\Dialog::hasAccess($arMessageFields['DIALOG_ID'])
3215 && !\Bitrix\Im\User::getInstance()->isExtranet()
3216 )
3217 {
3218 $arMessageFields['SYSTEM'] = 'Y';
3219 }
3220
3221 if (isset($arParams['URL_PREVIEW']) && $arParams['URL_PREVIEW'] == 'N')
3222 {
3223 $arMessageFields['URL_PREVIEW'] = 'N';
3224 }
3225 if (isset($arParams['SKIP_CONNECTOR']) && mb_strtoupper($arParams['SKIP_CONNECTOR']) == 'Y')
3226 {
3227 $arMessageFields['SKIP_CONNECTOR'] = 'Y';
3228 $arMessageFields['SILENT_CONNECTOR'] = 'Y';
3229 }
3230 if (isset($arParams['TEMPLATE_ID']) && !empty($arParams['TEMPLATE_ID']))
3231 {
3232 $arMessageFields['TEMPLATE_ID'] = mb_substr((string)$arParams['TEMPLATE_ID'], 0, 255);
3233 }
3234 if (isset($arParams['REPLY_ID']) && (int)$arParams['REPLY_ID'] > 0)
3235 {
3236 $message = new \Bitrix\Im\V2\Message((int)$arParams['REPLY_ID']);
3237 if (!$message->checkAccess()->isSuccess())
3238 {
3239 throw new Bitrix\Rest\RestException("Action unavailable", "REPLY_ACCESS_ERROR", CRestServer::STATUS_FORBIDDEN);
3240 }
3241 if ($message->getChat()->getDialogId() !== (string)$arMessageFields['DIALOG_ID'])
3242 {
3243 throw new Bitrix\Rest\RestException("You can only reply to a message within the same chat", "REPLY_FROM_OTHER_CHAT_ERROR", CRestServer::STATUS_FORBIDDEN);
3244 }
3245 $arMessageFields['PARAMS']['REPLY_ID'] = $message->getId();
3246 }
3247
3248 $arMessageFields['WAIT_FULL_EXECUTION'] = 'N';
3249
3250 $id = CIMMessenger::Add($arMessageFields);
3251 if (!$id)
3252 {
3253 throw new Bitrix\Rest\RestException("Message isn't added", "PARAMS_ERROR", CRestServer::STATUS_WRONG_REQUEST);
3254 }
3255
3256 return (int)$id;
3257
3258 }
3259
3260 public static function messageDelete($arParams, $n, CRestServer $server)
3261 {
3262 $arParams = array_change_key_case($arParams, CASE_UPPER);
3263
3264 if (isset($arParams['MESSAGE_ID']))
3265 {
3266 $arParams['ID'] = $arParams['MESSAGE_ID'];
3267 }
3268
3269 $arParams['ID'] = intval($arParams['ID']);
3270 if ($arParams['ID'] <= 0)
3271 {
3272 throw new Bitrix\Rest\RestException("Message ID can't be empty", "MESSAGE_ID_ERROR", CRestServer::STATUS_WRONG_REQUEST);
3273 }
3274
3275 $res = CIMMessenger::Delete($arParams['ID']);
3276 if (!$res)
3277 {
3278 throw new Bitrix\Rest\RestException("Time has expired for modification or you don't have access", "CANT_EDIT_MESSAGE", CRestServer::STATUS_FORBIDDEN);
3279 }
3280
3281 return true;
3282 }
3283
3284 public static function messageUpdate($arParams, $n, CRestServer $server)
3285 {
3286 $arParams = array_change_key_case($arParams, CASE_UPPER);
3287 $arParams['MESSAGE'] = self::getRawParam('MESSAGE') ?? $arParams['MESSAGE'] ?? null;
3288
3289 if (
3290 isset($arParams['PLATFORM_CONTEXT'])
3291 && is_string($arParams['PLATFORM_CONTEXT'])
3292 && $server->getAuthType() !== \Bitrix\Rest\SessionAuth\Auth::AUTH_TYPE
3293 )
3294 {
3295 \Bitrix\Im\Bot::setPlatformContext($arParams['PLATFORM_CONTEXT']);
3296 }
3297
3298 if (isset($arParams['MESSAGE_ID']))
3299 {
3300 $arParams['ID'] = $arParams['MESSAGE_ID'];
3301 }
3302
3303 $arParams['ID'] = intval($arParams['ID']);
3304 if ($arParams['ID'] <= 0)
3305 {
3306 throw new Bitrix\Rest\RestException("Message ID can't be empty", "MESSAGE_ID_ERROR", CRestServer::STATUS_WRONG_REQUEST);
3307 }
3308 $arParams['IS_EDITED'] = $arParams['IS_EDITED'] == 'N'? 'N': 'Y';
3309
3310 $message = null;
3311 if (isset($arParams['ATTACH']))
3312 {
3313 $message = CIMMessenger::CheckPossibilityUpdateMessage(IM_CHECK_UPDATE, $arParams['ID']);
3314 if (!$message)
3315 {
3316 throw new Bitrix\Rest\RestException("Time has expired for modification or you don't have access", "CANT_EDIT_MESSAGE", CRestServer::STATUS_FORBIDDEN);
3317 }
3318
3319 if (empty($arParams['ATTACH']) || $arParams['ATTACH'] == 'N')
3320 {
3321 CIMMessageParam::Set($arParams['ID'], Array('IS_EDITED' => $arParams['IS_EDITED'], 'ATTACH' => Array()));
3322 }
3323 else
3324 {
3325 $attach = CIMMessageParamAttach::GetAttachByJson($arParams['ATTACH']);
3326 if ($attach)
3327 {
3328 if ($attach->IsAllowSize())
3329 {
3330 CIMMessageParam::Set($arParams['ID'], Array('IS_EDITED' => $arParams['IS_EDITED'], 'ATTACH' => $attach));
3331 }
3332 else
3333 {
3334 throw new Bitrix\Rest\RestException("You have exceeded the maximum allowable size of attach", "ATTACH_OVERSIZE", CRestServer::STATUS_WRONG_REQUEST);
3335 }
3336 }
3337 else if ($arParams['ATTACH'])
3338 {
3339 throw new Bitrix\Rest\RestException("Incorrect attach params", "ATTACH_ERROR", CRestServer::STATUS_WRONG_REQUEST);
3340 }
3341 }
3342 }
3343
3344 if (isset($arParams['KEYBOARD']))
3345 {
3346 if (is_null($message))
3347 {
3348 $message = CIMMessenger::CheckPossibilityUpdateMessage(IM_CHECK_UPDATE, $arParams['ID']);
3349 }
3350 if (!$message)
3351 {
3352 throw new Bitrix\Rest\RestException("Time has expired for modification or you don't have access", "CANT_EDIT_MESSAGE", CRestServer::STATUS_FORBIDDEN);
3353 }
3354
3355 if (empty($arParams['KEYBOARD']) || $arParams['KEYBOARD'] == 'N')
3356 {
3357 CIMMessageParam::Set($arParams['ID'], Array('KEYBOARD' => 'N'));
3358 }
3359 else
3360 {
3361 $keyboard = Array();
3362 if (is_string($arParams['KEYBOARD']))
3363 {
3364 $arParams['KEYBOARD'] = \CUtil::JsObjectToPhp($arParams['KEYBOARD']);
3365 }
3366 if (!isset($arParams['KEYBOARD']['BUTTONS']))
3367 {
3368 $keyboard['BUTTONS'] = $arParams['KEYBOARD'];
3369 }
3370 else
3371 {
3372 $keyboard = $arParams['KEYBOARD'];
3373 }
3374 $keyboard['BOT_ID'] = $arParams['BOT_ID'];
3375
3376 $keyboard = \Bitrix\Im\Bot\Keyboard::getKeyboardByJson($keyboard);
3377 if ($keyboard)
3378 {
3379 if ($keyboard->isAllowSize())
3380 {
3381 CIMMessageParam::Set($arParams['ID'], Array('KEYBOARD' => $keyboard));
3382 }
3383 else
3384 {
3385 throw new Bitrix\Rest\RestException("You have exceeded the maximum allowable size of keyboard", "KEYBOARD_OVERSIZE", CRestServer::STATUS_WRONG_REQUEST);
3386 }
3387 }
3388 else if ($arParams['KEYBOARD'])
3389 {
3390 throw new Bitrix\Rest\RestException("Incorrect keyboard params", "KEYBOARD_ERROR", CRestServer::STATUS_WRONG_REQUEST);
3391 }
3392 }
3393 }
3394
3395 if (isset($arParams['MENU']))
3396 {
3397 if (is_null($message))
3398 {
3399 $message = CIMMessenger::CheckPossibilityUpdateMessage(IM_CHECK_UPDATE, $arParams['MESSAGE_ID'], $arParams['BOT_ID']);
3400 }
3401 if (!$message)
3402 {
3403 throw new Bitrix\Rest\RestException("Time has expired for modification or you don't have access", "CANT_EDIT_MESSAGE", CRestServer::STATUS_FORBIDDEN);
3404 }
3405
3406 if (empty($arParams['MENU']) || $arParams['MENU'] == 'N')
3407 {
3408 CIMMessageParam::Set($arParams['MESSAGE_ID'], Array('MENU' => 'N'));
3409 }
3410 else
3411 {
3412 $menu = Array();
3413 if (is_string($arParams['MENU']))
3414 {
3415 $arParams['MENU'] = \CUtil::JsObjectToPhp($arParams['MENU']);
3416 }
3417 if (!isset($arParams['MENU']['ITEMS']))
3418 {
3419 $menu['ITEMS'] = $arParams['MENU'];
3420 }
3421 else
3422 {
3423 $menu = $arParams['MENU'];
3424 }
3425 $menu['BOT_ID'] = $arParams['BOT_ID'];
3426
3428 if ($menu)
3429 {
3430 if ($menu->isAllowSize())
3431 {
3432 CIMMessageParam::Set($arParams['MESSAGE_ID'], Array('MENU' => $menu));
3433 }
3434 else
3435 {
3436 throw new Bitrix\Rest\RestException("You have exceeded the maximum allowable size of menu", "MENU_OVERSIZE", CRestServer::STATUS_WRONG_REQUEST);
3437 }
3438 }
3439 else if ($arParams['MENU'])
3440 {
3441 throw new Bitrix\Rest\RestException("Incorrect menu params", "menu_ERROR", CRestServer::STATUS_WRONG_REQUEST);
3442 }
3443 }
3444 }
3445
3446 if (isset($arParams['MESSAGE']))
3447 {
3448 $urlPreview = isset($arParams['URL_PREVIEW']) && $arParams['URL_PREVIEW'] == "N"? false: true;
3449
3450 $res = CIMMessenger::Update($arParams['ID'], $arParams['MESSAGE'], $urlPreview);
3451 if (!$res)
3452 {
3453 throw new Bitrix\Rest\RestException("Time has expired for modification or you don't have access", "CANT_EDIT_MESSAGE", CRestServer::STATUS_FORBIDDEN);
3454 }
3455 }
3456 CIMMessageParam::SendPull($arParams['ID'], Array('KEYBOARD', 'ATTACH', 'MENU'));
3457
3458 return true;
3459 }
3460
3461 public static function messageLike($arParams, $n, CRestServer $server)
3462 {
3463 $arParams = array_change_key_case($arParams, CASE_UPPER);
3464
3465 if (isset($arParams['MESSAGE_ID']))
3466 {
3467 $arParams['ID'] = $arParams['MESSAGE_ID'];
3468 }
3469
3470 $arParams['ID'] = intval($arParams['ID']);
3471 if ($arParams['ID'] <= 0)
3472 {
3473 throw new Bitrix\Rest\RestException("Message ID can't be empty", "MESSAGE_ID_ERROR", CRestServer::STATUS_WRONG_REQUEST);
3474 }
3475
3476 $arParams['ACTION'] = mb_strtolower($arParams['ACTION']);
3477 if (!in_array($arParams['ACTION'], Array('auto', 'plus', 'minus')))
3478 {
3479 $arParams['ACTION'] = 'auto';
3480 }
3481
3482 $result = CIMMessenger::Like($arParams['ID'], $arParams['ACTION']);
3483 if ($result === false)
3484 {
3485 throw new Bitrix\Rest\RestException("Action completed without changes", "WITHOUT_CHANGES", CRestServer::STATUS_WRONG_REQUEST);
3486 }
3487
3488 return true;
3489 }
3490
3491 public static function messageCommand($arParams, $n, CRestServer $server)
3492 {
3493 $arParams = array_change_key_case($arParams, CASE_UPPER);
3494
3495 if (isset($arParams['MESSAGE_ID']))
3496 {
3497 $arParams['ID'] = $arParams['MESSAGE_ID'];
3498 }
3499
3500 $arParams['ID'] = intval($arParams['ID']);
3501 if ($arParams['ID'] <= 0)
3502 {
3503 throw new Bitrix\Rest\RestException("Message ID can't be empty", "MESSAGE_ID_ERROR", CRestServer::STATUS_WRONG_REQUEST);
3504 }
3505
3506 $arParams['BOT_ID'] = intval($arParams['BOT_ID']);
3507 if ($arParams['BOT_ID'] <= 0)
3508 {
3509 throw new Bitrix\Rest\RestException("Bot ID can't be empty", "BOT_ID_ERROR", CRestServer::STATUS_WRONG_REQUEST);
3510 }
3511
3512 if ($arParams['COMMAND'] == '')
3513 {
3514 throw new Bitrix\Rest\RestException("Command can't be empty", "COMMAND_ERROR", CRestServer::STATUS_WRONG_REQUEST);
3515 }
3516
3517 $result = CIMMessenger::ExecCommand($arParams['ID'], $arParams['BOT_ID'], $arParams['COMMAND'], $arParams['COMMAND_PARAMS']);
3518 if ($result === false)
3519 {
3520 throw new Bitrix\Rest\RestException("Incorrect params", "PARAMS_ERROR", CRestServer::STATUS_WRONG_REQUEST);
3521 }
3522
3523 return true;
3524 }
3525
3526
3527 public static function messageShare($arParams, $n, CRestServer $server)
3528 {
3529 $arParams = array_change_key_case($arParams, CASE_UPPER);
3530
3531 if (isset($arParams['MESSAGE_ID']))
3532 {
3533 $arParams['ID'] = $arParams['MESSAGE_ID'];
3534 }
3535
3536 $arParams['ID'] = intval($arParams['ID']);
3537 if ($arParams['ID'] <= 0)
3538 {
3539 throw new Bitrix\Rest\RestException("Message ID can't be empty", "MESSAGE_ID_ERROR", CRestServer::STATUS_WRONG_REQUEST);
3540 }
3541
3542 if (!\Bitrix\Im\Common::isDialogId($arParams['DIALOG_ID']))
3543 {
3544 throw new Bitrix\Rest\RestException("Dialog ID can't be empty", "DIALOG_ID_EMPTY", CRestServer::STATUS_WRONG_REQUEST);
3545 }
3546
3547 if (!\Bitrix\Im\Dialog::hasAccess($arParams['DIALOG_ID']))
3548 {
3549 throw new Bitrix\Rest\RestException("You do not have access to the specified dialog", "ACCESS_ERROR", CRestServer::STATUS_FORBIDDEN);
3550 }
3551
3552 $chatId = \Bitrix\Im\Dialog::getChatId($arParams['DIALOG_ID']);
3553 if (!$chatId)
3554 {
3555 throw new Bitrix\Rest\RestException("You don't have access to this chat", "ACCESS_ERROR", CRestServer::STATUS_WRONG_REQUEST);
3556 }
3557
3558 $result = CIMMessenger::Share($arParams['ID'], $arParams['TYPE']);
3559 if ($result === false)
3560 {
3561 throw new Bitrix\Rest\RestException("Incorrect params", "PARAMS_ERROR", CRestServer::STATUS_WRONG_REQUEST);
3562 }
3563
3564 return true;
3565 }
3566
3567 public static function messageUserGet($arParams, $offset, CRestServer $server)
3568 {
3569 $arParams = array_change_key_case($arParams, CASE_UPPER);
3570
3571 if (
3572 $server->getAuthType() != \Bitrix\Rest\OAuth\Auth::AUTH_TYPE
3573 && !self::isDebugEnabled()
3574 )
3575 {
3576 throw new \Bitrix\Rest\RestException("Access for this method allowed only by OAuth authorization.", "WRONG_AUTH_TYPE", \CRestServer::STATUS_WRONG_REQUEST);
3577 }
3578
3579 global $USER;
3580 $userId = $USER->GetID();
3581 if ($userId <= 0)
3582 {
3583 throw new Bitrix\Rest\RestException("User ID can't be empty", "ID_EMPTY", CRestServer::STATUS_WRONG_REQUEST);
3584 }
3585
3586 if (isset($arParams['FIRST_ID']))
3587 {
3588 $options['FIRST_ID'] = intval($arParams['FIRST_ID']);
3589 }
3590 else
3591 {
3592 $options['LAST_ID'] = isset($arParams['LAST_ID']) && intval($arParams['LAST_ID']) > 0? intval($arParams['LAST_ID']): 0;
3593 }
3594
3595 $options['LIMIT'] = isset($arParams['LIMIT'])? (intval($arParams['LIMIT']) > 500? 500: intval($arParams['LIMIT'])): 50;
3596 $options['JSON'] = 'Y';
3597
3598 $forUser = $userId;
3599 if (isset($arParams['USER_ID']) && intval($arParams['USER_ID']) > 0 && $arParams['USER_ID'] != $userId)
3600 {
3601 if (
3602 (
3603 !\Bitrix\Im\User::getInstance($arParams['USER_ID'])->isActive() && !\Bitrix\Im\User::getInstance($arParams['USER_ID'])->isExtranet()
3604 || \Bitrix\Im\User::getInstance($arParams['USER_ID'])->isConnector()
3605 )
3606 &&
3607 (
3608 $USER->IsAdmin()
3609 || \Bitrix\Main\Loader::includeModule('bitrix24') && CBitrix24::IsPortalAdmin($userId)
3610 )
3611 )
3612 {
3613 $forUser = intval($arParams['USER_ID']);
3614 $options['SKIP_MESSAGE'] = 'Y';
3615 }
3616 else
3617 {
3618 throw new Bitrix\Rest\RestException("You don't have access to this user", "ACCESS_ERROR", CRestServer::STATUS_WRONG_REQUEST);
3619 }
3620 }
3621
3622 return \Bitrix\Im\User::getMessages($forUser, $options);
3623 }
3624
3625 public static function notifyAdd($arParams, $n, CRestServer $server)
3626 {
3627 global $USER;
3628
3629 if ($server->getAuthType() == \Bitrix\Rest\SessionAuth\Auth::AUTH_TYPE)
3630 {
3631 throw new \Bitrix\Rest\RestException("Access for this method not allowed by session authorization.", "WRONG_AUTH_TYPE", \CRestServer::STATUS_FORBIDDEN);
3632 }
3633
3634 $arParams = array_change_key_case($arParams, CASE_UPPER);
3635
3636 if (isset($arParams['TO']))
3637 {
3638 $arParams['USER_ID'] = $arParams['TO'];
3639 }
3640 $arParams['USER_ID'] = intval($arParams['USER_ID']);
3641 if ($arParams['USER_ID'] <= 0)
3642 {
3643 throw new Bitrix\Rest\RestException("User ID can't be empty", "USER_ID_EMPTY", CRestServer::STATUS_WRONG_REQUEST);
3644 }
3645
3646 if ($server->getMethod() == "im.notify.personal.add")
3647 {
3648 $arParams['TYPE'] = 'USER';
3649 }
3650 else if ($server->getMethod() == "im.notify.system.add")
3651 {
3652 $arParams['TYPE'] = 'SYSTEM';
3653 }
3654 else if (!isset($arParams['TYPE']) || !in_array($arParams['TYPE'], Array('USER', 'SYSTEM')))
3655 {
3656 $arParams['TYPE'] = 'USER';
3657 }
3658
3659 $arParams['MESSAGE'] = isset($arParams['MESSAGE']) && is_string($arParams['MESSAGE'])
3660 ? trim($arParams['MESSAGE'])
3661 : ''
3662 ;
3663
3664 if ($arParams['MESSAGE'] == '')
3665 {
3666 throw new Bitrix\Rest\RestException("Message can't be empty", "MESSAGE_EMPTY", CRestServer::STATUS_WRONG_REQUEST);
3667 }
3668
3669 $messageOut = "";
3670 $arParams['MESSAGE_OUT'] = isset($arParams['MESSAGE_OUT']) && is_string($arParams['MESSAGE_OUT'])
3671 ? trim($arParams['MESSAGE_OUT'])
3672 : ''
3673 ;
3674
3675 if ($arParams['TYPE'] == 'SYSTEM')
3676 {
3677 $fromUserId = 0;
3678 $notifyType = IM_NOTIFY_SYSTEM;
3679
3680 $clientId = $server->getClientId();
3681 if ($clientId)
3682 {
3683 $result = \Bitrix\Rest\AppTable::getList(array('filter' => array('=CLIENT_ID' => $clientId)));
3684 $result = $result->fetch();
3685 $moduleName = !empty($result['APP_NAME'])
3686 ? $result['APP_NAME']
3687 : (!empty($result['APP_NAME_DEFAULT'])
3688 ? $result['APP_NAME_DEFAULT']
3689 : $result['CODE']
3690 )
3691 ;
3692 $message = $moduleName."#BR#".$arParams['MESSAGE'];
3693
3694 if (!empty($arParams['MESSAGE_OUT']))
3695 {
3696 $messageOut = $moduleName."#BR#".$arParams['MESSAGE_OUT'];
3697 }
3698 }
3699 else
3700 {
3701 $message = $arParams['MESSAGE'];
3702 }
3703 }
3704 else
3705 {
3706 $fromUserId = $USER->GetID();
3707 $notifyType = IM_NOTIFY_FROM;
3708 $message = $arParams['MESSAGE'];
3709 if (!empty($arParams['MESSAGE_OUT']))
3710 {
3711 $messageOut = $arParams['MESSAGE_OUT'];
3712 }
3713 }
3714
3715 $arMessageFields = array(
3716 "TO_USER_ID" => $arParams['USER_ID'],
3717 "FROM_USER_ID" => $fromUserId,
3718 "NOTIFY_TYPE" => $notifyType,
3719 "NOTIFY_MODULE" => "rest",
3720 "NOTIFY_EVENT" => "rest_notify",
3721 "NOTIFY_MESSAGE" => $message,
3722 "NOTIFY_MESSAGE_OUT" => $messageOut,
3723 );
3724
3725 $clientId = $server->getClientId();
3726 if ($clientId)
3727 {
3728 if (!empty($arParams['TAG']))
3729 {
3730 $appKey = mb_substr(md5($server->getClientId()), 0, 5);
3731 $arMessageFields['NOTIFY_TAG'] = 'MP|'.$appKey.'|'.$arParams['TAG'];
3732 }
3733 if (!empty($arParams['SUB_TAG']))
3734 {
3735 $appKey = mb_substr(md5($server->getClientId()), 0, 5);
3736 $arMessageFields['NOTIFY_SUB_TAG'] = 'MP|'.$appKey.'|'.$arParams['SUB_TAG'];
3737 }
3738 }
3739
3740 $attach = CIMMessageParamAttach::GetAttachByJson($arParams['ATTACH']);
3741 if ($attach)
3742 {
3743 if ($attach->IsAllowSize())
3744 {
3745 $arMessageFields['ATTACH'] = $attach;
3746 }
3747 else
3748 {
3749 throw new Bitrix\Rest\RestException("You have exceeded the maximum allowable size of attach", "ATTACH_OVERSIZE", CRestServer::STATUS_WRONG_REQUEST);
3750 }
3751 }
3752 else if ($arParams['ATTACH'])
3753 {
3754 throw new Bitrix\Rest\RestException("Incorrect attach params", "ATTACH_ERROR", CRestServer::STATUS_WRONG_REQUEST);
3755 }
3756
3757 return CIMNotify::Add($arMessageFields);
3758 }
3759
3760 public static function notifyGet($arParams, $n, CRestServer $server)
3761 {
3762 $arParams = array_change_key_case($arParams, CASE_UPPER);
3763
3764 if (
3765 (isset($arParams['LAST_ID']) && !isset($arParams['LAST_TYPE'])) ||
3766 (!isset($arParams['LAST_ID']) && isset($arParams['LAST_TYPE']))
3767 )
3768 {
3769 throw new Bitrix\Rest\RestException(
3770 "Parameters LAST_ID and LAST_TYPE should be used together.",
3771 "LAST_ID_AND_LAST_TYPE",
3772 CRestServer::STATUS_WRONG_REQUEST
3773 );
3774 }
3775
3776 if (isset($arParams['LAST_ID']) )
3777 {
3778 if (!preg_match('/^\d+$/', $arParams['LAST_ID']))
3779 {
3780 throw new Bitrix\Rest\RestException(
3781 "Last notification ID can't be string",
3782 "LAST_ID_STRING",
3783 CRestServer::STATUS_WRONG_REQUEST
3784 );
3785 }
3786
3787 $options['LAST_ID'] = (int)$arParams['LAST_ID'];
3788 $options['LAST_TYPE'] = (int)$arParams['LAST_TYPE'];
3789 }
3790
3791 if (isset($arParams['LIMIT']))
3792 {
3793 $options['LIMIT'] = (int)$arParams['LIMIT'] > 50 ? 50 : (int)$arParams['LIMIT'];
3794 }
3795 else
3796 {
3797 $options['LIMIT'] = 50;
3798 }
3799
3800 $options['CONVERT_TEXT'] = isset($arParams['CONVERT_TEXT']) && $arParams['CONVERT_TEXT'] === 'Y';
3801
3802 return (new \Bitrix\Im\Notify($options))->get();
3803 }
3804
3805 public static function notifyDelete($arParams, $n, CRestServer $server)
3806 {
3807 $arParams = array_change_key_case($arParams, CASE_UPPER);
3808
3809 if (isset($arParams['ID']))
3810 {
3811 $CIMNotify = new CIMNotify();
3812 return $CIMNotify->DeleteWithCheck($arParams['ID']);
3813 }
3814
3815 if ($server->getAuthType() == \Bitrix\Rest\SessionAuth\Auth::AUTH_TYPE)
3816 {
3817 throw new Bitrix\Rest\RestException("Incorrect params", "PARAMS_ERROR", CRestServer::STATUS_WRONG_REQUEST);
3818 }
3819
3820 $clientId = $server->getClientId();
3821 if (!$clientId)
3822 {
3823 if (!empty($arParams['CLIENT_ID']))
3824 {
3825 $clientId = 'custom'.$arParams['CLIENT_ID'];
3826 }
3827 else
3828 {
3829 throw new \Bitrix\Rest\AccessException("Client ID not specified");
3830 }
3831 }
3832
3833 if (!empty($arParams['TAG']))
3834 {
3835 $appKey = mb_substr(md5($clientId), 0, 5);
3836 $result = CIMNotify::DeleteByTag('MP|'.$appKey.'|'.$arParams['TAG']);
3837 }
3838 else if (!empty($arParams['SUB_TAG']))
3839 {
3840 $appKey = mb_substr(md5($clientId), 0, 5);
3841 $result = CIMNotify::DeleteBySubTag('MP|'.$appKey.'|'.$arParams['SUB_TAG']);
3842 }
3843 else
3844 {
3845 throw new Bitrix\Rest\RestException("Incorrect params", "PARAMS_ERROR", CRestServer::STATUS_WRONG_REQUEST);
3846 }
3847
3848 return $result;
3849 }
3850
3851 public static function notifyRead($arParams, $n, CRestServer $server)
3852 {
3853 $arParams = array_change_key_case($arParams, CASE_UPPER);
3854
3855 if (!isset($arParams['ACTION']))
3856 {
3857 $arParams['ACTION'] = 'Y';
3858 }
3859
3860 if (isset($arParams['ID']) && (int)$arParams['ID'] >= 0)
3861 {
3862 $CIMNotify = new CIMNotify();
3863
3864 $onlyCurrent = $arParams['ONLY_CURRENT'] ?? null;
3865 $readAllFromId = $onlyCurrent !== 'Y';
3866 if ($arParams['ACTION'] === 'Y')
3867 {
3868 $CIMNotify->MarkNotifyRead($arParams['ID'], $readAllFromId);
3869 }
3870 else
3871 {
3872 $CIMNotify->MarkNotifyUnRead($arParams['ID'], $readAllFromId);
3873 }
3874 }
3875
3876 return true;
3877 }
3878
3879 public static function notifyReadList($arParams, $n, CRestServer $server)
3880 {
3881 $arParams = array_change_key_case($arParams, CASE_UPPER);
3882
3883 if (!isset($arParams['ACTION']))
3884 {
3885 $arParams['ACTION'] = 'Y';
3886 }
3887
3888 if (!isset($arParams['IDS']) || !is_array($arParams['IDS']))
3889 {
3890 throw new Bitrix\Rest\RestException("No IDS param or it is not an array", "PARAMS_ERROR", CRestServer::STATUS_WRONG_REQUEST);
3891 }
3892
3893 $CIMNotify = new CIMNotify();
3894 foreach ($arParams['IDS'] as $notificationId)
3895 {
3896 $notificationId = (int)$notificationId;
3897 if ($notificationId <= 0)
3898 {
3899 break;
3900 }
3901
3902 if ($arParams['ACTION'] === 'Y')
3903 {
3904 $CIMNotify->MarkNotifyRead($notificationId);
3905 }
3906 else
3907 {
3908 $CIMNotify->MarkNotifyUnRead($notificationId);
3909 }
3910 }
3911
3912 return true;
3913 }
3914
3915 public static function notifyReadAll($arParams, $n, CRestServer $server)
3916 {
3917 $notify = new \CIMNotify();
3918 $notify->MarkNotifyRead(0, true);
3919
3920 return true;
3921 }
3922
3923 public static function notifyConfirm($arParams, $n, CRestServer $server): array
3924 {
3925 $arParams = array_change_key_case($arParams, CASE_UPPER);
3926
3927 if (isset($arParams['NOTIFY_ID']))
3928 {
3929 $arParams['NOTIFY_ID'] = (int)$arParams['NOTIFY_ID'];
3930 }
3931
3932 if (isset($arParams['ID']))
3933 {
3934 $arParams['NOTIFY_ID'] = (int)$arParams['ID'];
3935 }
3936
3937 if ($arParams['NOTIFY_ID'] <= 0)
3938 {
3939 throw new Bitrix\Rest\RestException("Notification ID can't be empty", "ID_ERROR", CRestServer::STATUS_WRONG_REQUEST);
3940 }
3941
3942 if (empty($arParams['NOTIFY_VALUE']))
3943 {
3944 throw new Bitrix\Rest\RestException("Notification Value can't be empty", "NOTIFY_VALUE_ERROR", CRestServer::STATUS_WRONG_REQUEST);
3945 }
3946
3947 $CIMNotify = new CIMNotify();
3948 $result = $CIMNotify->Confirm($arParams['NOTIFY_ID'], $arParams['NOTIFY_VALUE']);
3949
3950 return [
3951 'result_message' => $result
3952 ];
3953 }
3954
3955 public static function notifyAnswer($arParams, $n, CRestServer $server): array
3956 {
3957 $arParams = array_change_key_case($arParams, CASE_UPPER);
3958
3959 if (isset($arParams['NOTIFY_ID']))
3960 {
3961 $arParams['NOTIFY_ID'] = (int)$arParams['NOTIFY_ID'];
3962 }
3963
3964 if (isset($arParams['ID']))
3965 {
3966 $arParams['NOTIFY_ID'] = (int)$arParams['ID'];
3967 }
3968
3969 if ($arParams['NOTIFY_ID'] <= 0)
3970 {
3971 throw new Bitrix\Rest\RestException("Notification ID can't be empty", "ID_ERROR", CRestServer::STATUS_WRONG_REQUEST);
3972 }
3973
3974 if (empty($arParams['ANSWER_TEXT']))
3975 {
3976 throw new Bitrix\Rest\RestException("ANSWER_TEXT can't be empty", "ANSWER_TEXT_ERROR", CRestServer::STATUS_WRONG_REQUEST);
3977 }
3978
3979 $CIMNotify = new CIMNotify();
3980 $result = $CIMNotify->Answer($arParams['NOTIFY_ID'], $arParams['ANSWER_TEXT']);
3981
3982 return [
3983 'result_message' => $result
3984 ];
3985 }
3986
3987 public static function notifyHistorySearch($arParams, $n, CRestServer $server): array
3988 {
3989 $arParams = array_change_key_case($arParams, CASE_UPPER);
3990
3991 if (
3992 !($arParams['SEARCH_TYPE'] ?? null)
3993 && !($arParams['SEARCH_DATE'] ?? null)
3994 && mb_strlen(trim($arParams['SEARCH_TEXT'])) < 3
3995 )
3996 {
3997 throw new Bitrix\Rest\RestException("SEARCH_TEXT can't be less then 3 symbols", "SEARCH_TEXT_ERROR", CRestServer::STATUS_WRONG_REQUEST);
3998 }
3999
4000 if (isset($arParams['SEARCH_TEXT']))
4001 {
4002 $options['SEARCH_TEXT'] = $arParams['SEARCH_TEXT'];
4003 }
4004 if (isset($arParams['SEARCH_TYPE']))
4005 {
4006 $options['SEARCH_TYPE'] = $arParams['SEARCH_TYPE'];
4007 }
4008 if (isset($arParams['SEARCH_DATE']))
4009 {
4010 $options['SEARCH_DATE'] = $arParams['SEARCH_DATE'];
4011 }
4012 if (isset($arParams['LAST_ID']))
4013 {
4014 if (!preg_match('/^\d+$/', $arParams['LAST_ID']))
4015 {
4016 throw new Bitrix\Rest\RestException(
4017 "Last notification ID can't be string",
4018 "LAST_ID_STRING",
4019 CRestServer::STATUS_WRONG_REQUEST
4020 );
4021 }
4022
4023 $options['LAST_ID'] = (int)$arParams['LAST_ID'];
4024 }
4025
4026 if (isset($arParams['LIMIT']))
4027 {
4028 $options['LIMIT'] = (int)$arParams['LIMIT'] > 50 ? 50 : (int)$arParams['LIMIT'];
4029 }
4030 else
4031 {
4032 $options['LIMIT'] = 50;
4033 }
4034
4035 $options['CONVERT_TEXT'] = isset($arParams['CONVERT_TEXT']) && $arParams['CONVERT_TEXT'] === 'Y';
4036 $options['GROUP_TAG'] = (string)($arParams['GROUP_TAG'] ?? '');
4037
4038 $notify = new \Bitrix\Im\Notify($options);
4039
4040 return $notify->search();
4041 }
4042
4043 public static function notifySchemaGet($arParams, $n, CRestServer $server): array
4044 {
4045 $schemaResult = [];
4047 foreach ($schema as $moduleId => $notifyTypes)
4048 {
4049 $list = [];
4050 foreach ($notifyTypes['NOTIFY'] as $notifyId => $notify)
4051 {
4052 $list[] = [
4053 'ID' => $moduleId.'|'.$notifyId,
4054 'NAME' => $notify['NAME']
4055 ];
4056 }
4057
4058 if ($notifyTypes['NAME'] === '')
4059 {
4060 $module = CModule::CreateModuleObject($moduleId);
4061 $moduleName = $module->MODULE_NAME;
4062 }
4063 else
4064 {
4065 $moduleName = $notifyTypes['NAME'];
4066 }
4067
4068 $schemaResult[$moduleId] = [
4069 'NAME' => $moduleName,
4070 'MODULE_ID' => $moduleId,
4071 'LIST' => $list,
4072 ];
4073 }
4074
4075 return $schemaResult;
4076 }
4077
4078 public static function diskFolderListGet($arParams, $n, CRestServer $server)
4079 {
4080 $arParams = array_change_key_case($arParams, CASE_UPPER);
4081 $lastId = $arParams['LAST_ID'] ?? null;
4082 $fileName = $arParams['SEARCH_FILE_NAME'] ?? null;
4083 $limit = self::getLimit($arParams);
4084 if (!isset($arParams['CHAT_ID']))
4085 {
4086 throw new \Bitrix\Rest\RestException('CHAT_ID can`t be empty', 'CHAT_ID_EMPTY', \CRestServer::STATUS_WRONG_REQUEST);
4087 }
4088
4089 $chatId = $arParams['CHAT_ID'];
4090 $chat = \Bitrix\Im\V2\Chat::getInstance($chatId);
4091
4092 if (!$chat->checkAccess()->isSuccess())
4093 {
4094 throw new \Bitrix\Rest\RestException('You do not have access to this chat', Bitrix\Im\V2\Rest\RestError::ACCESS_ERROR, \CRestServer::STATUS_FORBIDDEN);
4095 }
4096
4097 $files = (new \Bitrix\Im\V2\Link\File\FileService())->getFilesBeforeMigrationFinished($chatId, $limit, $lastId, $fileName);
4098
4099 return (new RestAdapter($files))->toRestFormat();
4100 }
4101
4102 public static function diskFolderGet($arParams, $n, CRestServer $server)
4103 {
4104 $arParams = array_change_key_case($arParams, CASE_UPPER);
4105
4106 if (isset($arParams['DIALOG_ID']))
4107 {
4108 if (!\Bitrix\Im\Common::isDialogId($arParams['DIALOG_ID']))
4109 {
4110 throw new Bitrix\Rest\RestException("Dialog ID can't be empty", "DIALOG_ID_EMPTY", CRestServer::STATUS_WRONG_REQUEST);
4111 }
4112
4113 if (!\Bitrix\Im\Dialog::hasAccess($arParams['DIALOG_ID']))
4114 {
4115 throw new Bitrix\Rest\RestException("You do not have access to the specified dialog", "ACCESS_ERROR", CRestServer::STATUS_FORBIDDEN);
4116 }
4117
4118 $chatId = \Bitrix\Im\Dialog::getChatId($arParams['DIALOG_ID']);
4119 if (!$chatId)
4120 {
4121 throw new Bitrix\Rest\RestException("You don't have access to this chat", "ACCESS_ERROR", CRestServer::STATUS_WRONG_REQUEST);
4122 }
4123 }
4124 else
4125 {
4126 $chatId = intval($arParams['CHAT_ID']);
4127
4128 if ($chatId <= 0)
4129 {
4130 throw new Bitrix\Rest\RestException("Chat ID can't be empty", "CHAT_ID_EMPTY", CRestServer::STATUS_WRONG_REQUEST);
4131 }
4132
4133 if (!\Bitrix\Im\Dialog::hasAccess('chat'.$chatId))
4134 {
4135 throw new Bitrix\Rest\RestException("You do not have access to the specified dialog", "ACCESS_ERROR", CRestServer::STATUS_FORBIDDEN);
4136 }
4137 }
4138
4139 $folderModel = CIMDisk::GetFolderModel($chatId);
4140 if (!$folderModel)
4141 {
4142 throw new Bitrix\Rest\RestException("Internal server error.", "INTERNAL_ERROR", CRestServer::STATUS_INTERNAL);
4143 }
4144
4145 return Array(
4146 'ID' => (int)$folderModel->getId()
4147 );
4148 }
4149
4150 public static function diskFileCommit($arParams, $n, CRestServer $server)
4151 {
4152 $arParams = array_change_key_case($arParams, CASE_UPPER);
4153
4154 if (isset($arParams['DIALOG_ID']))
4155 {
4156 if (\Bitrix\Im\Common::isDialogId($arParams['DIALOG_ID']))
4157 {
4158 $arParams['CHAT_ID'] = \Bitrix\Im\Dialog::getChatId($arParams['DIALOG_ID']);
4159 }
4160 else
4161 {
4162 throw new Bitrix\Rest\RestException("Dialog ID can't be empty", "DIALOG_ID_EMPTY", CRestServer::STATUS_WRONG_REQUEST);
4163 }
4164 }
4165
4166 $chatId = intval($arParams['CHAT_ID']);
4167 if ($chatId <= 0)
4168 {
4169 throw new Bitrix\Rest\RestException("Chat ID can't be empty", "CHAT_ID_EMPTY", CRestServer::STATUS_WRONG_REQUEST);
4170 }
4171
4172 $arParams['MESSAGE'] = trim($arParams['MESSAGE']);
4173 if ($arParams['MESSAGE'] == '')
4174 {
4175 unset($arParams['MESSAGE']);
4176 }
4177
4178 $arParams['SILENT_MODE'] = $arParams['SILENT_MODE'] == 'Y';
4179
4180 $chatRelation = \Bitrix\Im\V2\Chat::getInstance($chatId)->getRelations();
4181 if (!$chatRelation->hasUser(CIMDisk::GetUserId(), $chatId))
4182 {
4183 throw new Bitrix\Rest\RestException("You don't have access to this chat", "ACCESS_ERROR", CRestServer::STATUS_WRONG_REQUEST);
4184 }
4185
4186 if (
4187 CIMChat::GetGeneralChatId() == $chatId
4188 && !CIMChat::CanSendMessageToGeneralChat()
4189 )
4190 {
4191 throw new Bitrix\Rest\RestException("Action unavailable", "ACCESS_ERROR", CRestServer::STATUS_FORBIDDEN);
4192 }
4193
4194 $files = Array();
4195 if (isset($arParams['FILE_ID']))
4196 {
4197 if (!is_array($arParams['FILE_ID']))
4198 {
4199 $arParams['FILE_ID'] = Array($arParams['FILE_ID']);
4200 }
4201 foreach ($arParams['FILE_ID'] as $fileId)
4202 {
4203 $files[$fileId] = 'disk'.$fileId;
4204 }
4205 }
4206 else if (isset($arParams['DISK_ID']))
4207 {
4208 if (!is_array($arParams['DISK_ID']))
4209 {
4210 $arParams['DISK_ID'] = Array($arParams['DISK_ID']);
4211 }
4212 foreach ($arParams['DISK_ID'] as $fileId)
4213 {
4214 $files[$fileId] = 'disk'.$fileId;
4215 }
4216
4217 if (isset($arParams['SYMLINK']))
4218 {
4219 $arParams['SYMLINK'] = $arParams['SYMLINK'] == 'Y';
4220 }
4221 }
4222 else if (isset($arParams['UPLOAD_ID']))
4223 {
4224 if (!is_array($arParams['UPLOAD_ID']))
4225 {
4226 $arParams['UPLOAD_ID'] = Array($arParams['UPLOAD_ID']);
4227 }
4228 foreach ($arParams['UPLOAD_ID'] as $fileId)
4229 {
4230 $files[$fileId] = 'upload'.$fileId;
4231 }
4232 }
4233
4234 if (empty($files))
4235 {
4236 throw new Bitrix\Rest\RestException("List of files in not specified", "FILES_ERROR", CRestServer::STATUS_WRONG_REQUEST);
4237 }
4238
4239 if (isset($arParams['TEMPLATE_ID']) && !empty($arParams['TEMPLATE_ID']))
4240 {
4241 $arParams['TEMPLATE_ID'] = mb_substr((string)$arParams['TEMPLATE_ID'], 0, 255);
4242 }
4243
4244 if (isset($arParams['FILE_TEMPLATE_ID']) && !empty($arParams['FILE_TEMPLATE_ID']))
4245 {
4246 $arParams['FILE_TEMPLATE_ID'] = mb_substr((string)$arParams['FILE_TEMPLATE_ID'], 0, 255);
4247 }
4248
4249 $result = CIMDisk::UploadFileFromDisk($chatId, array_values($files), $arParams['MESSAGE'], [
4250 'LINES_SILENT_MODE' => $arParams['SILENT_MODE'],
4251 'TEMPLATE_ID' => $arParams['TEMPLATE_ID']?:'',
4252 'FILE_TEMPLATE_ID' => $arParams['FILE_TEMPLATE_ID']?:'',
4253 'SYMLINK' => $arParams['SYMLINK']?:false,
4254 'AS_FILE' => $arParams['AS_FILE'] ?? 'N',
4255 'WAIT_FULL_EXECUTION' => 'N',
4256 ]);
4257 if (!$result)
4258 {
4259 throw new Bitrix\Rest\RestException("Error during saving file to chat", "SAVE_ERROR", CRestServer::STATUS_WRONG_REQUEST);
4260 }
4261
4262 return $result;
4263 }
4264
4265 public static function diskRecordShare($arParams, $n, CRestServer $server)
4266 {
4267 $arParams = array_change_key_case($arParams, CASE_UPPER);
4268
4269 $dialogId = $arParams['DIALOG_ID'];
4270 if (!\Bitrix\Im\Common::isDialogId($dialogId))
4271 {
4272 throw new Bitrix\Rest\RestException("Dialog ID can't be empty", "DIALOG_ID_EMPTY", CRestServer::STATUS_WRONG_REQUEST);
4273 }
4274
4275 if (!\Bitrix\Im\Dialog::hasAccess($dialogId))
4276 {
4277 throw new Bitrix\Rest\RestException("You don't have access to this chat", "ACCESS_ERROR", CRestServer::STATUS_WRONG_REQUEST);
4278 }
4279
4280 $chatId = \Bitrix\Im\Dialog::getChatId($dialogId);
4281 if ($chatId <= 0)
4282 {
4283 throw new Bitrix\Rest\RestException("Chat ID isn't found", "CHAT_NOT_FOUND", CRestServer::STATUS_WRONG_REQUEST);
4284 }
4285
4286 $diskId = (int)$arParams['DISK_ID'];
4287 if ($diskId <= 0)
4288 {
4289 throw new Bitrix\Rest\RestException("Disk ID can't be empty", "DISK_ID_EMPTY", CRestServer::STATUS_WRONG_REQUEST);
4290 }
4291
4292 $result = \CIMDisk::RecordShare($chatId, $diskId);
4293 if (!$result)
4294 {
4295 throw new Bitrix\Rest\RestException("Error during record share", "EXECUTE_ERROR", CRestServer::STATUS_WRONG_REQUEST);
4296 }
4297
4298 return true;
4299 }
4300
4301
4302 public static function diskFileDelete($arParams, $n, CRestServer $server)
4303 {
4304 $arParams = array_change_key_case($arParams, CASE_UPPER);
4305
4306 $chatId = intval($arParams['CHAT_ID']);
4307 if ($chatId <= 0)
4308 {
4309 throw new Bitrix\Rest\RestException("Chat ID can't be empty", "CHAT_ID_EMPTY", CRestServer::STATUS_WRONG_REQUEST);
4310 }
4311
4312 $fileId = isset($arParams['FILE_ID'])? intval($arParams['FILE_ID']): intval($arParams['DISK_ID']);
4313 if ($fileId <= 0)
4314 {
4315 throw new Bitrix\Rest\RestException("File ID can't be empty", "FILE_ID_EMPTY", CRestServer::STATUS_WRONG_REQUEST);
4316 }
4317
4318 return CIMDisk::DeleteFile($chatId, $fileId);
4319 }
4320
4321 public static function diskFileSave($arParams, $n, CRestServer $server)
4322 {
4323 $arParams = array_change_key_case($arParams, CASE_UPPER);
4324
4325 $fileId = isset($arParams['FILE_ID'])? intval($arParams['FILE_ID']): intval($arParams['DISK_ID']);
4326 if ($fileId <= 0)
4327 {
4328 throw new Bitrix\Rest\RestException("File ID can't be empty", "FILE_ID_EMPTY", CRestServer::STATUS_WRONG_REQUEST);
4329 }
4330
4332 if (!$result)
4333 {
4334 throw new Bitrix\Rest\RestException("File ID can't be saved", "FILE_SAVE_ERROR", CRestServer::STATUS_WRONG_REQUEST);
4335 }
4336
4337 return [
4338 'folder' => [
4339 'id' => (int)$result['FOLDER']->getId(),
4340 'name' => $result['FOLDER']->getName()
4341 ],
4342 'file' => [
4343 'id' => (int)$result['FILE']->getId(),
4344 'name' => $result['FILE']->getName()
4345 ],
4346 ];
4347 }
4348
4349 public static function counterGet($arParams, $n, CRestServer $server)
4350 {
4352
4353 $onlyCounterParam = $arParams['ONLY_COUNTER'] ?? null;
4354 $jsonParam = $arParams['JSON'] ?? null;
4355
4356 if ($onlyCounterParam)
4357 {
4358 $counters = $counters['TYPE'];
4359 }
4360
4361 if ($jsonParam === 'Y')
4362 {
4364 }
4365
4366 return $counters;
4367 }
4368
4369 public static function notImplemented($arParams, $n, CRestServer $server)
4370 {
4371 throw new Bitrix\Rest\RestException("Method isn't implemented yet", "NOT_IMPLEMENTED", CRestServer::STATUS_NOT_FOUND);
4372 }
4373
4374 /* BotAPI */
4375
4376 public static function botRegister($arParams, $n, CRestServer $server)
4377 {
4378 if ($server->getAuthType() == \Bitrix\Rest\SessionAuth\Auth::AUTH_TYPE)
4379 {
4380 throw new \Bitrix\Rest\RestException("Access for this method not allowed by session authorization.", "WRONG_AUTH_TYPE", \CRestServer::STATUS_FORBIDDEN);
4381 }
4382
4383 $arParams = array_change_key_case($arParams, CASE_UPPER);
4384
4385 $customClientId = false;
4386 $clientId = $server->getClientId();
4387 if (!$clientId)
4388 {
4389 if (!empty($arParams['CLIENT_ID']))
4390 {
4391 $customClientId = true;
4392 $clientId = 'custom'.$arParams['CLIENT_ID'];
4393 }
4394 else
4395 {
4396 throw new \Bitrix\Rest\AccessException("Client ID not specified");
4397 }
4398 }
4399
4400 if ($customClientId)
4401 {
4402 $arApp = ['ID' => '', 'CLIENT_ID' => $arParams['CLIENT_ID']];
4403 }
4404 else
4405 {
4406 $dbRes = \Bitrix\Rest\AppTable::getList(array('filter' => array('=CLIENT_ID' => $clientId)));
4407 $arApp = $dbRes->fetch();
4408 }
4409
4410 if (isset($arParams['EVENT_HANDLER']) && !empty($arParams['EVENT_HANDLER']))
4411 {
4412 $arParams['EVENT_MESSAGE_ADD'] = $arParams['EVENT_MESSAGE_UPDATE'] = $arParams['EVENT_MESSAGE_DELETE'] = $arParams['EVENT_WELCOME_MESSAGE'] = $arParams['EVENT_BOT_DELETE'] = $arParams['EVENT_CONTEXT_GET'] = $arParams['EVENT_HANDLER'];
4413 }
4414
4415 if (isset($arParams['EVENT_MESSAGE_ADD']) && !empty($arParams['EVENT_MESSAGE_ADD']))
4416 {
4417 if ($customClientId)
4418 {
4419 $arParams['EVENT_MESSAGE_ADD'] = $arParams['EVENT_MESSAGE_ADD'].(mb_strpos($arParams['EVENT_MESSAGE_ADD'], '?') === false? '?': '&').'CLIENT_ID='.$arParams['CLIENT_ID'];
4420 }
4421 try
4422 {
4423 \Bitrix\Rest\HandlerHelper::checkCallback($arParams['EVENT_MESSAGE_ADD'], $arApp);
4424 }
4425 catch(Exception $e)
4426 {
4427 throw new Bitrix\Rest\RestException($e->getMessage(), "EVENT_MESSAGE_ADD_ERROR", CRestServer::STATUS_WRONG_REQUEST);
4428 }
4429 }
4430 else
4431 {
4432 throw new Bitrix\Rest\RestException("Handler for \"Message add\" event isn't specified", "EVENT_MESSAGE_ADD_ERROR", CRestServer::STATUS_WRONG_REQUEST);
4433 }
4434
4435 if (isset($arParams['EVENT_MESSAGE_UPDATE']) && !empty($arParams['EVENT_MESSAGE_UPDATE']))
4436 {
4437 if ($customClientId)
4438 {
4439 $arParams['EVENT_MESSAGE_UPDATE'] = $arParams['EVENT_MESSAGE_UPDATE'].(mb_strpos($arParams['EVENT_MESSAGE_UPDATE'], '?') === false? '?': '&').'CLIENT_ID='.$arParams['CLIENT_ID'];
4440 }
4441 try
4442 {
4443 \Bitrix\Rest\HandlerHelper::checkCallback($arParams['EVENT_MESSAGE_UPDATE'], $arApp);
4444 }
4445 catch(Exception $e)
4446 {
4447 throw new Bitrix\Rest\RestException($e->getMessage(), "EVENT_MESSAGE_UPDATE_ERROR", CRestServer::STATUS_WRONG_REQUEST);
4448 }
4449 }
4450
4451 if (isset($arParams['EVENT_MESSAGE_DELETE']) && !empty($arParams['EVENT_MESSAGE_DELETE']))
4452 {
4453 if ($customClientId)
4454 {
4455 $arParams['EVENT_MESSAGE_DELETE'] = $arParams['EVENT_MESSAGE_DELETE'].(mb_strpos($arParams['EVENT_MESSAGE_DELETE'], '?') === false? '?': '&').'CLIENT_ID='.$arParams['CLIENT_ID'];
4456 }
4457 try
4458 {
4459 \Bitrix\Rest\HandlerHelper::checkCallback($arParams['EVENT_MESSAGE_DELETE'], $arApp);
4460 }
4461 catch(Exception $e)
4462 {
4463 throw new Bitrix\Rest\RestException($e->getMessage(), "EVENT_MESSAGE_DELETE_ERROR", CRestServer::STATUS_WRONG_REQUEST);
4464 }
4465 }
4466
4467 if (isset($arParams['EVENT_CONTEXT_GET']) && !empty($arParams['EVENT_CONTEXT_GET']))
4468 {
4469 if ($customClientId)
4470 {
4471 $arParams['EVENT_CONTEXT_GET'] .= (mb_strpos($arParams['EVENT_CONTEXT_GET'], '?') === false ? '?' : '&') . 'CLIENT_ID=' . $arParams['CLIENT_ID'];
4472 }
4473 try
4474 {
4475 \Bitrix\Rest\HandlerHelper::checkCallback($arParams['EVENT_CONTEXT_GET'], $arApp);
4476 }
4477 catch(Exception $e)
4478 {
4479 throw new Bitrix\Rest\RestException($e->getMessage(), "EVENT_CONTEXT_GET_ERROR", CRestServer::STATUS_WRONG_REQUEST);
4480 }
4481 }
4482
4483 if (isset($arParams['EVENT_WELCOME_MESSAGE']) && !empty($arParams['EVENT_WELCOME_MESSAGE']))
4484 {
4485 if ($customClientId)
4486 {
4487 $arParams['EVENT_WELCOME_MESSAGE'] = $arParams['EVENT_WELCOME_MESSAGE'].(mb_strpos($arParams['EVENT_WELCOME_MESSAGE'], '?') === false? '?': '&').'CLIENT_ID='.$arParams['CLIENT_ID'];
4488 }
4489 try
4490 {
4491 \Bitrix\Rest\HandlerHelper::checkCallback($arParams['EVENT_WELCOME_MESSAGE'], $arApp);
4492 }
4493 catch(Exception $e)
4494 {
4495 throw new Bitrix\Rest\RestException($e->getMessage(), "EVENT_WELCOME_MESSAGE_ERROR", CRestServer::STATUS_WRONG_REQUEST);
4496 }
4497 }
4498 else
4499 {
4500 throw new Bitrix\Rest\RestException("Handler for \"Welcome message\" event isn't specified", "EVENT_WELCOME_MESSAGE_ERROR", CRestServer::STATUS_WRONG_REQUEST);
4501 }
4502
4503 if (isset($arParams['EVENT_BOT_DELETE']) && !empty($arParams['EVENT_BOT_DELETE']))
4504 {
4505 if ($customClientId)
4506 {
4507 $arParams['EVENT_BOT_DELETE'] = $arParams['EVENT_BOT_DELETE'].(mb_strpos($arParams['EVENT_BOT_DELETE'], '?') === false? '?': '&').'CLIENT_ID='.$arParams['CLIENT_ID'];
4508 }
4509 try
4510 {
4511 \Bitrix\Rest\HandlerHelper::checkCallback($arParams['EVENT_BOT_DELETE'], $arApp);
4512 }
4513 catch(Exception $e)
4514 {
4515 throw new Bitrix\Rest\RestException($e->getMessage(), "EVENT_BOT_DELETE_ERROR", CRestServer::STATUS_WRONG_REQUEST);
4516 }
4517 }
4518 else
4519 {
4520 throw new Bitrix\Rest\RestException("Handler for \"Bot delete\" event isn't specified", "EVENT_BOT_DELETE_ERROR", CRestServer::STATUS_WRONG_REQUEST);
4521 }
4522
4523 if (!isset($arParams['CODE']) || empty($arParams['CODE']))
4524 {
4525 throw new Bitrix\Rest\RestException("Bot code isn't specified", "CODE_ERROR", CRestServer::STATUS_WRONG_REQUEST);
4526 }
4527
4528 if (CModule::IncludeModule('bitrix24'))
4529 {
4530 $counter = \Bitrix\Im\Model\BotTable::getCount(array('=APP_ID' => $clientId));
4531 $restRegisterLimit = \Bitrix\Bitrix24\Feature::getVariable('imbot_rest_register_limit')?: 5;
4532
4533 if ($counter >= $restRegisterLimit)
4534 {
4535 throw new Bitrix\Rest\RestException("Has reached the maximum number of bots for application (max: $restRegisterLimit)", "MAX_COUNT_ERROR", CRestServer::STATUS_WRONG_REQUEST);
4536 }
4537 }
4538
4539 $arParams['TYPE'] = in_array($arParams['TYPE'], Array('O', 'B', 'H', 'S'))? $arParams['TYPE']: 'B';
4540 $arParams['OPENLINE'] = $arParams['OPENLINE'] == 'Y'? 'Y': 'N';
4541
4542 if (!(in_array($arParams['TYPE'], Array('S', 'O')) || $arParams['OPENLINE'] == 'Y'))
4543 {
4544 unset($arParams['EVENT_MESSAGE_UPDATE']);
4545 unset($arParams['EVENT_MESSAGE_DELETE']);
4546 }
4547
4548 $properties = Array();
4549 if (isset($arParams['PROPERTIES']['NAME']))
4550 {
4551 $properties['NAME'] = $arParams['PROPERTIES']['NAME'];
4552 }
4553 if (isset($arParams['PROPERTIES']['LAST_NAME']))
4554 {
4555 $properties['LAST_NAME'] = $arParams['PROPERTIES']['LAST_NAME'];
4556 }
4557 if (!(isset($properties['NAME']) || isset($properties['LAST_NAME'])))
4558 {
4559 throw new Bitrix\Rest\RestException("Bot name isn't specified", "NAME_ERROR", CRestServer::STATUS_WRONG_REQUEST);
4560 }
4561
4562 if (isset($arParams['PROPERTIES']['COLOR']))
4563 {
4564 $properties['COLOR'] = $arParams['PROPERTIES']['COLOR'];
4565 }
4566 if (isset($arParams['PROPERTIES']['EMAIL']))
4567 {
4568 $properties['EMAIL'] = $arParams['PROPERTIES']['EMAIL'];
4569 }
4570 if (isset($arParams['PROPERTIES']['PERSONAL_BIRTHDAY']))
4571 {
4572 $birthday = new \Bitrix\Main\Type\DateTime($arParams['PROPERTIES']['PERSONAL_BIRTHDAY'].' 19:45:00', 'Y-m-d H:i:s');
4573 $birthday = $birthday->format(\Bitrix\Main\Type\Date::convertFormatToPhp(\CSite::GetDateFormat('SHORT')));
4574
4575 $properties['PERSONAL_BIRTHDAY'] = $birthday;
4576 }
4577 if (isset($arParams['PROPERTIES']['WORK_POSITION']))
4578 {
4579 $properties['WORK_POSITION'] = $arParams['PROPERTIES']['WORK_POSITION'];
4580 }
4581 if (isset($arParams['PROPERTIES']['PERSONAL_WWW']))
4582 {
4583 $properties['PERSONAL_WWW'] = $arParams['PROPERTIES']['PERSONAL_WWW'];
4584 }
4585 if (isset($arParams['PROPERTIES']['PERSONAL_GENDER']))
4586 {
4587 $properties['PERSONAL_GENDER'] = $arParams['PROPERTIES']['PERSONAL_GENDER'];
4588 }
4589 if (isset($arParams['PROPERTIES']['PERSONAL_PHOTO']))
4590 {
4591 $avatar = \CRestUtil::saveFile($arParams['PROPERTIES']['PERSONAL_PHOTO'], $arParams['CODE'].'.png');
4592 $imageCheck = (new \Bitrix\Main\File\Image($avatar["tmp_name"]))->getInfo();
4593 if(
4594 !$imageCheck
4595 || !$imageCheck->getWidth()
4596 || $imageCheck->getWidth() > 5000
4597 || !$imageCheck->getHeight()
4598 || $imageCheck->getHeight() > 5000
4599 )
4600 {
4601 $avatar = null;
4602 }
4603
4604 if (isset($avatar) && mb_strpos($avatar['type'], "image/") === 0)
4605 {
4606 $avatar['MODULE_ID'] = 'imbot';
4607 $properties['PERSONAL_PHOTO'] = $avatar;
4608 }
4609 }
4610
4611 $botId = \Bitrix\Im\Bot::register(Array(
4612 'APP_ID' => $clientId,
4613 'CODE' => $arParams['CODE'],
4614 'TYPE' => $arParams['TYPE'],
4615 'OPENLINE' => $arParams['OPENLINE'],
4616 'MODULE_ID' => 'rest',
4617 'PROPERTIES' => $properties
4618 ));
4619 if ($botId)
4620 {
4621 self::unbindEvent($arApp['ID'], $arApp['CLIENT_ID'], 'im', 'onImBotMessageAdd', 'OnImBotMessageAdd', true);
4622 self::bindEvent($arApp['ID'], $arApp['CLIENT_ID'], 'im', 'onImBotMessageAdd', 'OnImBotMessageAdd', $arParams['EVENT_MESSAGE_ADD']);
4623
4624 if ($arParams['EVENT_MESSAGE_UPDATE'])
4625 {
4626 self::unbindEvent($arApp['ID'], $arApp['CLIENT_ID'], 'im', 'onImBotMessageUpdate', 'OnImBotMessageUpdate', true);
4627 self::bindEvent($arApp['ID'], $arApp['CLIENT_ID'], 'im', 'onImBotMessageUpdate', 'OnImBotMessageUpdate', $arParams['EVENT_MESSAGE_UPDATE']);
4628 }
4629
4630 if ($arParams['EVENT_MESSAGE_DELETE'])
4631 {
4632 self::unbindEvent($arApp['ID'], $arApp['CLIENT_ID'], 'im', 'onImBotMessageDelete', 'OnImBotMessageDelete', true);
4633 self::bindEvent($arApp['ID'], $arApp['CLIENT_ID'], 'im', 'onImBotMessageDelete', 'OnImBotMessageDelete', $arParams['EVENT_MESSAGE_DELETE']);
4634 }
4635
4636 if ($arParams['EVENT_CONTEXT_GET'])
4637 {
4638 self::unbindEvent($arApp['ID'], $arApp['CLIENT_ID'], 'im', 'onImBotContextGet', 'OnImBotContextGet', true);
4639 self::bindEvent($arApp['ID'], $arApp['CLIENT_ID'], 'im', 'onImBotContextGet', 'OnImBotContextGet', $arParams['EVENT_CONTEXT_GET']);
4640 }
4641
4642 self::unbindEvent($arApp['ID'], $arApp['CLIENT_ID'], 'im', 'onImBotJoinChat', 'OnImBotJoinChat', true);
4643 self::bindEvent($arApp['ID'], $arApp['CLIENT_ID'], 'im', 'onImBotJoinChat', 'OnImBotJoinChat', $arParams['EVENT_WELCOME_MESSAGE']);
4644
4645 self::unbindEvent($arApp['ID'], $arApp['CLIENT_ID'], 'im', 'onImBotDelete', 'OnImBotDelete', true);
4646 self::bindEvent($arApp['ID'], $arApp['CLIENT_ID'], 'im', 'onImBotDelete', 'OnImBotDelete', $arParams['EVENT_BOT_DELETE']);
4647 }
4648 else
4649 {
4650 throw new Bitrix\Rest\RestException("Bot can't be created", "WRONG_REQUEST", CRestServer::STATUS_WRONG_REQUEST);
4651 }
4652
4653 return $botId;
4654 }
4655
4656 public static function botUnRegister($arParams, $n, CRestServer $server)
4657 {
4658 if ($server->getAuthType() == \Bitrix\Rest\SessionAuth\Auth::AUTH_TYPE)
4659 {
4660 throw new \Bitrix\Rest\RestException("Access for this method not allowed by session authorization.", "WRONG_AUTH_TYPE", \CRestServer::STATUS_FORBIDDEN);
4661 }
4662
4663 $arParams = array_change_key_case($arParams, CASE_UPPER);
4664
4665 $customClientId = false;
4666 $clientId = $server->getClientId();
4667 if (!$clientId)
4668 {
4669 if (!empty($arParams['CLIENT_ID']))
4670 {
4671 $customClientId = true;
4672 $clientId = 'custom'.$arParams['CLIENT_ID'];
4673 }
4674 else
4675 {
4676 throw new \Bitrix\Rest\AccessException("Client ID not specified");
4677 }
4678 }
4679
4680 $bots = \Bitrix\Im\Bot::getListCache();
4681 if (!isset($bots[$arParams['BOT_ID']]))
4682 {
4683 throw new Bitrix\Rest\RestException("Bot not found", "BOT_ID_ERROR", CRestServer::STATUS_WRONG_REQUEST);
4684 }
4685 if ($bots[$arParams['BOT_ID']]['APP_ID'] != $clientId)
4686 {
4687 throw new Bitrix\Rest\RestException("Bot was installed by another rest application", "APP_ID_ERROR", CRestServer::STATUS_WRONG_REQUEST);
4688 }
4689
4690 $result = \Bitrix\Im\Bot::unRegister(Array('BOT_ID' => $arParams['BOT_ID']));
4691 if (!$result)
4692 {
4693 throw new Bitrix\Rest\RestException("Bot can't be deleted", "WRONG_REQUEST", CRestServer::STATUS_WRONG_REQUEST);
4694 }
4695
4696 if ($customClientId)
4697 {
4698 self::unbindEvent("", $arParams['CLIENT_ID'], 'im', 'onImBotMessageAdd', 'OnImBotMessageAdd', true);
4699 self::unbindEvent("", $arParams['CLIENT_ID'], 'im', 'onImBotMessageUpdate', 'OnImBotMessageUpdate', true);
4700 self::unbindEvent("", $arParams['CLIENT_ID'], 'im', 'onImBotMessageDelete', 'OnImBotMessageDelete', true);
4701 self::unbindEvent("", $arParams['CLIENT_ID'], 'im', 'onImBotJoinChat', 'OnImBotJoinChat', true);
4702 self::unbindEvent("", $arParams['CLIENT_ID'], 'im', 'onImBotDelete', 'OnImBotDelete', true);
4703 self::unbindEvent("", $arParams['CLIENT_ID'], 'im', 'onImBotContextGet', 'OnImBotContextGet', true);
4704 }
4705
4706 return true;
4707 }
4708
4709 public static function botUpdate($arParams, $n, CRestServer $server)
4710 {
4711 if ($server->getAuthType() == \Bitrix\Rest\SessionAuth\Auth::AUTH_TYPE)
4712 {
4713 throw new \Bitrix\Rest\RestException("Access for this method not allowed by session authorization.", "WRONG_AUTH_TYPE", \CRestServer::STATUS_FORBIDDEN);
4714 }
4715 $arParams = array_change_key_case($arParams, CASE_UPPER);
4716
4717 $clientId = $server->getClientId();
4718 $customClientId = false;
4719 if (!$clientId)
4720 {
4721 if (!empty($arParams['CLIENT_ID']))
4722 {
4723 $customClientId = true;
4724 $clientId = 'custom'.$arParams['CLIENT_ID'];
4725 }
4726 else
4727 {
4728 throw new \Bitrix\Rest\AccessException("Client ID not specified");
4729 }
4730 }
4731
4732 $bots = \Bitrix\Im\Bot::getListCache();
4733 if (!isset($bots[$arParams['BOT_ID']]))
4734 {
4735 throw new Bitrix\Rest\RestException("Bot not found", "BOT_ID_ERROR", CRestServer::STATUS_WRONG_REQUEST);
4736 }
4737 if ($bots[$arParams['BOT_ID']]['APP_ID'] != $clientId)
4738 {
4739 throw new Bitrix\Rest\RestException("Bot was installed by another rest application", "APP_ID_ERROR", CRestServer::STATUS_WRONG_REQUEST);
4740 }
4741
4742 if ($customClientId)
4743 {
4744 $arApp = ['ID' => '', 'CLIENT_ID' => $arParams['CLIENT_ID']];
4745 }
4746 else
4747 {
4748 $dbRes = \Bitrix\Rest\AppTable::getList(array('filter' => array('=CLIENT_ID' => $clientId)));
4749 $arApp = $dbRes->fetch();
4750 }
4751
4752 $updateEvents = Array();
4753
4754 if (isset($arParams['FIELDS']['EVENT_HANDLER']) && !empty($arParams['FIELDS']['EVENT_HANDLER']))
4755 {
4756 $arParams['FIELDS']['EVENT_MESSAGE_ADD'] = $arParams['FIELDS']['EVENT_MESSAGE_UPDATE'] = $arParams['FIELDS']['EVENT_MESSAGE_DELETE'] = $arParams['FIELDS']['EVENT_WELCOME_MESSAGE'] = $arParams['FIELDS']['EVENT_BOT_DELETE'] = $arParams['FIELDS']['EVENT_CONTEXT_GET'] = $arParams['FIELDS']['EVENT_HANDLER'];
4757 }
4758
4759 if (isset($arParams['FIELDS']['EVENT_MESSAGE_ADD']) && !empty($arParams['FIELDS']['EVENT_MESSAGE_ADD']))
4760 {
4761 $updateEvents['EVENT_MESSAGE_ADD'] = $arParams['FIELDS']['EVENT_MESSAGE_ADD'];
4762 if ($customClientId)
4763 {
4764 $updateEvents['EVENT_MESSAGE_ADD'] = $updateEvents['EVENT_MESSAGE_ADD'].(mb_strpos($updateEvents['EVENT_MESSAGE_ADD'], '?') === false? '?': '&').'CLIENT_ID='.$arParams['CLIENT_ID'];
4765 }
4766 try
4767 {
4768 \Bitrix\Rest\HandlerHelper::checkCallback($arParams['FIELDS']['EVENT_MESSAGE_ADD'], $arApp);
4769 }
4770 catch(Exception $e)
4771 {
4772 throw new Bitrix\Rest\RestException($e->getMessage(), "EVENT_MESSAGE_ADD_ERROR", CRestServer::STATUS_WRONG_REQUEST);
4773 }
4774 }
4775
4776 if (isset($arParams['FIELDS']['EVENT_MESSAGE_UPDATE']) && !empty($arParams['FIELDS']['EVENT_MESSAGE_UPDATE']))
4777 {
4778 $updateEvents['EVENT_MESSAGE_UPDATE'] = $arParams['FIELDS']['EVENT_MESSAGE_UPDATE'];
4779 if ($customClientId)
4780 {
4781 $updateEvents['EVENT_MESSAGE_UPDATE'] = $updateEvents['EVENT_MESSAGE_UPDATE'].(mb_strpos($updateEvents['EVENT_MESSAGE_UPDATE'], '?') === false? '?': '&').'CLIENT_ID='.$arParams['CLIENT_ID'];
4782 }
4783 try
4784 {
4785 \Bitrix\Rest\HandlerHelper::checkCallback($arParams['FIELDS']['EVENT_MESSAGE_UPDATE'], $arApp);
4786 }
4787 catch(Exception $e)
4788 {
4789 throw new Bitrix\Rest\RestException($e->getMessage(), "EVENT_MESSAGE_UPDATE_ERROR", CRestServer::STATUS_WRONG_REQUEST);
4790 }
4791 }
4792
4793 if (isset($arParams['FIELDS']['EVENT_MESSAGE_DELETE']) && !empty($arParams['FIELDS']['EVENT_MESSAGE_DELETE']))
4794 {
4795 $updateEvents['EVENT_MESSAGE_DELETE'] = $arParams['FIELDS']['EVENT_MESSAGE_DELETE'];
4796 if ($customClientId)
4797 {
4798 $updateEvents['EVENT_MESSAGE_DELETE'] = $updateEvents['EVENT_MESSAGE_DELETE'].(mb_strpos($updateEvents['EVENT_MESSAGE_DELETE'], '?') === false? '?': '&').'CLIENT_ID='.$arParams['CLIENT_ID'];
4799 }
4800 try
4801 {
4802 \Bitrix\Rest\HandlerHelper::checkCallback($arParams['FIELDS']['EVENT_MESSAGE_DELETE'], $arApp);
4803 }
4804 catch(Exception $e)
4805 {
4806 throw new Bitrix\Rest\RestException($e->getMessage(), "EVENT_MESSAGE_DELETE_ERROR", CRestServer::STATUS_WRONG_REQUEST);
4807 }
4808 }
4809
4810 if (!empty($arParams['FIELDS']['EVENT_CONTEXT_GET']))
4811 {
4812 $updateEvents['EVENT_CONTEXT_GET'] = $arParams['FIELDS']['EVENT_CONTEXT_GET'];
4813 if ($customClientId)
4814 {
4815 $updateEvents['EVENT_CONTEXT_GET'] .= (mb_strpos($updateEvents['EVENT_CONTEXT_GET'], '?') === false ? '?' : '&') . 'CLIENT_ID=' . $arParams['CLIENT_ID'];
4816 }
4817 try
4818 {
4819 \Bitrix\Rest\HandlerHelper::checkCallback($arParams['FIELDS']['EVENT_CONTEXT_GET'], $arApp);
4820 }
4821 catch(Exception $e)
4822 {
4823 throw new Bitrix\Rest\RestException($e->getMessage(), "EVENT_CONTEXT_GET_ERROR", CRestServer::STATUS_WRONG_REQUEST);
4824 }
4825 }
4826
4827 if (isset($arParams['FIELDS']['EVENT_WELCOME_MESSAGE']) && !empty($arParams['FIELDS']['EVENT_WELCOME_MESSAGE']))
4828 {
4829 $updateEvents['EVENT_WELCOME_MESSAGE'] = $arParams['FIELDS']['EVENT_WELCOME_MESSAGE'];
4830 if ($customClientId)
4831 {
4832 $updateEvents['EVENT_WELCOME_MESSAGE'] = $updateEvents['EVENT_WELCOME_MESSAGE'].(mb_strpos($updateEvents['EVENT_WELCOME_MESSAGE'], '?') === false? '?': '&').'CLIENT_ID='.$arParams['CLIENT_ID'];
4833 }
4834 try
4835 {
4836 \Bitrix\Rest\HandlerHelper::checkCallback($arParams['FIELDS']['EVENT_WELCOME_MESSAGE'], $arApp);
4837 }
4838 catch(Exception $e)
4839 {
4840 throw new Bitrix\Rest\RestException($e->getMessage(), "EVENT_WELCOME_MESSAGE_ERROR", CRestServer::STATUS_WRONG_REQUEST);
4841 }
4842 }
4843
4844 if (isset($arParams['FIELDS']['EVENT_BOT_DELETE']) && !empty($arParams['FIELDS']['EVENT_BOT_DELETE']))
4845 {
4846 $updateEvents['EVENT_BOT_DELETE'] = $arParams['FIELDS']['EVENT_BOT_DELETE'];
4847 if ($customClientId)
4848 {
4849 $updateEvents['EVENT_BOT_DELETE'] = $updateEvents['EVENT_BOT_DELETE'].(mb_strpos($updateEvents['EVENT_BOT_DELETE'], '?') === false? '?': '&').'CLIENT_ID='.$arParams['CLIENT_ID'];
4850 }
4851 try
4852 {
4853 \Bitrix\Rest\HandlerHelper::checkCallback($arParams['FIELDS']['EVENT_BOT_DELETE'], $arApp);
4854 }
4855 catch(Exception $e)
4856 {
4857 throw new Bitrix\Rest\RestException($e->getMessage(), "EVENT_BOT_DELETE_ERROR", CRestServer::STATUS_WRONG_REQUEST);
4858 }
4859 }
4860
4861 $updateFields = Array();
4862
4863 if (isset($arParams['FIELDS']['CODE']) && !empty($arParams['FIELDS']['CODE']))
4864 {
4865 $updateFields['CODE'] = $arParams['FIELDS']['CODE'];
4866 }
4867
4868 if (isset($arParams['FIELDS']['TYPE']) && !empty($arParams['FIELDS']['TYPE']) && in_array($arParams['TYPE'], Array('O', 'B', 'H')))
4869 {
4870 $updateFields['TYPE'] = $arParams['FIELDS']['TYPE'];
4871 }
4872
4873 if (isset($arParams['FIELDS']['OPENLINE']) && !empty($arParams['FIELDS']['OPENLINE']))
4874 {
4875 $updateFields['OPENLINE'] = $arParams['FIELDS']['OPENLINE'];
4876 }
4877
4878 $properties = Array();
4879 if (isset($arParams['FIELDS']['PROPERTIES']['NAME']))
4880 {
4881 $properties['NAME'] = $arParams['FIELDS']['PROPERTIES']['NAME'];
4882 }
4883 if (isset($arParams['FIELDS']['PROPERTIES']['LAST_NAME']))
4884 {
4885 $properties['LAST_NAME'] = $arParams['FIELDS']['PROPERTIES']['LAST_NAME'];
4886 }
4887
4888 if (isset($properties['NAME']) && empty($properties['NAME']) && isset($properties['LAST_NAME']) && empty($properties['LAST_NAME']))
4889 {
4890 throw new Bitrix\Rest\RestException("Bot name isn't specified", "NAME_ERROR", CRestServer::STATUS_WRONG_REQUEST);
4891 }
4892
4893 if (isset($arParams['FIELDS']['PROPERTIES']['COLOR']))
4894 {
4895 $properties['COLOR'] = $arParams['FIELDS']['PROPERTIES']['COLOR'];
4896 }
4897 if (isset($arParams['FIELDS']['PROPERTIES']['EMAIL']))
4898 {
4899 $properties['EMAIL'] = $arParams['FIELDS']['PROPERTIES']['EMAIL'];
4900 }
4901 if (isset($arParams['FIELDS']['PROPERTIES']['PERSONAL_BIRTHDAY']))
4902 {
4903 $birthday = new \Bitrix\Main\Type\DateTime($arParams['FIELDS']['PROPERTIES']['PERSONAL_BIRTHDAY'].' 19:45:00', 'Y-m-d H:i:s');
4904 $birthday = $birthday->format(\Bitrix\Main\Type\Date::convertFormatToPhp(\CSite::GetDateFormat('SHORT')));
4905
4906 $properties['PERSONAL_BIRTHDAY'] = $birthday;
4907 }
4908 if (isset($arParams['FIELDS']['PROPERTIES']['WORK_POSITION']))
4909 {
4910 $properties['WORK_POSITION'] = $arParams['FIELDS']['PROPERTIES']['WORK_POSITION'];
4911 }
4912 if (isset($arParams['FIELDS']['PROPERTIES']['PERSONAL_WWW']))
4913 {
4914 $properties['PERSONAL_WWW'] = $arParams['FIELDS']['PROPERTIES']['PERSONAL_WWW'];
4915 }
4916 if (isset($arParams['FIELDS']['PROPERTIES']['PERSONAL_GENDER']))
4917 {
4918 $properties['PERSONAL_GENDER'] = $arParams['FIELDS']['PROPERTIES']['PERSONAL_GENDER'];
4919 }
4920 if (isset($arParams['FIELDS']['PROPERTIES']['PERSONAL_PHOTO']))
4921 {
4922 $avatar = \CRestUtil::saveFile($arParams['FIELDS']['PROPERTIES']['PERSONAL_PHOTO'], $bots[$arParams['BOT_ID']]['CODE'].'.png');
4923 $imageCheck = (new \Bitrix\Main\File\Image($avatar["tmp_name"]))->getInfo();
4924 if(
4925 !$imageCheck
4926 || !$imageCheck->getWidth()
4927 || $imageCheck->getWidth() > 5000
4928 || !$imageCheck->getHeight()
4929 || $imageCheck->getHeight() > 5000
4930 )
4931 {
4932 $avatar = null;
4933 }
4934
4935 if ($avatar && mb_strpos($avatar['type'], "image/") === 0)
4936 {
4937 $avatar['MODULE_ID'] = 'imbot';
4938 $properties['PERSONAL_PHOTO'] = $avatar;
4939 }
4940 }
4941
4942 if (!empty($properties))
4943 {
4944 $updateFields['PROPERTIES'] = $properties;
4945 }
4946
4947 if (empty($updateFields))
4948 {
4949 if (empty($updateEvents))
4950 {
4951 throw new Bitrix\Rest\RestException("Update fields can't be empty", "WRONG_REQUEST", CRestServer::STATUS_WRONG_REQUEST);
4952 }
4953 }
4954 else
4955 {
4956 $result = \Bitrix\Im\Bot::update(Array('BOT_ID' => $arParams['BOT_ID']), $updateFields);
4957 if (!$result)
4958 {
4959 throw new Bitrix\Rest\RestException("Bot can't be updated", "WRONG_REQUEST", CRestServer::STATUS_WRONG_REQUEST);
4960 }
4961 }
4962
4963 if (isset($updateEvents['EVENT_MESSAGE_ADD']))
4964 {
4965 self::unbindEvent($arApp['ID'], $arApp['CLIENT_ID'], 'im', 'onImBotMessageAdd', 'OnImBotMessageAdd', true);
4966 self::bindEvent($arApp['ID'], $arApp['CLIENT_ID'], 'im', 'onImBotMessageAdd', 'OnImBotMessageAdd', $updateEvents['EVENT_MESSAGE_ADD']);
4967 }
4968 if (isset($updateEvents['EVENT_MESSAGE_UPDATE']))
4969 {
4970 self::unbindEvent($arApp['ID'], $arApp['CLIENT_ID'], 'im', 'onImBotMessageUpdate', 'OnImBotMessageUpdate', true);
4971 self::bindEvent($arApp['ID'], $arApp['CLIENT_ID'], 'im', 'onImBotMessageUpdate', 'OnImBotMessageUpdate', $updateEvents['EVENT_MESSAGE_UPDATE']);
4972 }
4973 if (isset($updateEvents['EVENT_MESSAGE_DELETE']))
4974 {
4975 self::unbindEvent($arApp['ID'], $arApp['CLIENT_ID'], 'im', 'onImBotMessageDelete', 'OnImBotMessageDelete', true);
4976 self::bindEvent($arApp['ID'], $arApp['CLIENT_ID'], 'im', 'onImBotMessageDelete', 'OnImBotMessageDelete', $updateEvents['EVENT_MESSAGE_DELETE']);
4977 }
4978 if (isset($updateEvents['EVENT_WELCOME_MESSAGE']))
4979 {
4980 self::unbindEvent($arApp['ID'], $arApp['CLIENT_ID'], 'im', 'onImBotJoinChat', 'OnImBotJoinChat', true);
4981 self::bindEvent($arApp['ID'], $arApp['CLIENT_ID'], 'im', 'onImBotJoinChat', 'OnImBotJoinChat', $updateEvents['EVENT_WELCOME_MESSAGE']);
4982 }
4983 if (isset($updateEvents['EVENT_BOT_DELETE']))
4984 {
4985 self::unbindEvent($arApp['ID'], $arApp['CLIENT_ID'], 'im', 'onImBotDelete', 'OnImBotDelete', true);
4986 self::bindEvent($arApp['ID'], $arApp['CLIENT_ID'], 'im', 'onImBotDelete', 'OnImBotDelete', $updateEvents['EVENT_BOT_DELETE']);
4987 }
4988 if (isset($updateEvents['EVENT_CONTEXT_GET']))
4989 {
4990 self::unbindEvent($arApp['ID'], $arApp['CLIENT_ID'], 'im', 'onImBotContextGet', 'OnImBotContextGet', true);
4991 self::bindEvent($arApp['ID'], $arApp['CLIENT_ID'], 'im', 'onImBotContextGet', 'OnImBotContextGet', $updateEvents['EVENT_CONTEXT_GET']);
4992 }
4993
4994 return true;
4995 }
4996
4997 public static function botMessageAdd($arParams, $n, CRestServer $server)
4998 {
4999 $arParams = array_change_key_case($arParams, CASE_UPPER);
5000
5001 $clientId = $server->getClientId();
5002 if (!$clientId)
5003 {
5004 if (!empty($arParams['CLIENT_ID']))
5005 {
5006 $clientId = 'custom'.$arParams['CLIENT_ID'];
5007 }
5008 else
5009 {
5010 throw new \Bitrix\Rest\AccessException("Client ID not specified");
5011 }
5012 }
5013
5014 $bots = \Bitrix\Im\Bot::getListCache();
5015 if (isset($arParams['BOT_ID']))
5016 {
5017 if (!isset($bots[$arParams['BOT_ID']]))
5018 {
5019 throw new Bitrix\Rest\RestException("Bot not found", "BOT_ID_ERROR", CRestServer::STATUS_WRONG_REQUEST);
5020 }
5021 if ($clientId && $bots[$arParams['BOT_ID']]['APP_ID'] != $clientId)
5022 {
5023 throw new Bitrix\Rest\RestException("Bot was installed by another rest application", "APP_ID_ERROR", CRestServer::STATUS_WRONG_REQUEST);
5024 }
5025 }
5026 else
5027 {
5028 $botFound = false;
5029 foreach ($bots as $bot)
5030 {
5031 if ($bot['APP_ID'] == $clientId)
5032 {
5033 $botFound = true;
5034 $arParams['BOT_ID'] = $bot['BOT_ID'];
5035 break;
5036 }
5037 }
5038 if (!$botFound)
5039 {
5040 throw new Bitrix\Rest\RestException("Bot not found", "BOT_ID_ERROR", CRestServer::STATUS_WRONG_REQUEST);
5041 }
5042 }
5043
5044 $arMessageFields = Array();
5045
5046 if (intval($arParams['FROM_USER_ID']) && intval($arParams['TO_USER_ID']))
5047 {
5048 $arParams['SYSTEM'] = 'Y';
5049 $arMessageFields['FROM_USER_ID'] = intval($arParams['FROM_USER_ID']);
5050 $arMessageFields['TO_USER_ID'] = intval($arParams['TO_USER_ID']);
5051 }
5052 else
5053 {
5054 $arMessageFields['DIALOG_ID'] = $arParams['DIALOG_ID'];
5055 if (!\Bitrix\Im\Common::isDialogId($arMessageFields['DIALOG_ID']))
5056 {
5057 throw new Bitrix\Rest\RestException("Dialog ID can't be empty", "DIALOG_ID_EMPTY", CRestServer::STATUS_WRONG_REQUEST);
5058 }
5059 }
5060
5061 $arMessageFields['MESSAGE'] = isset($arParams['MESSAGE']) && is_string($arParams['MESSAGE'])
5062 ? trim($arParams['MESSAGE'])
5063 : ''
5064 ;
5065 if ($arMessageFields['MESSAGE'] == '')
5066 {
5067 throw new Bitrix\Rest\RestException("Message can't be empty", "MESSAGE_EMPTY", CRestServer::STATUS_WRONG_REQUEST);
5068 }
5069
5070 if (isset($arParams['ATTACH']) && !empty($arParams['ATTACH']))
5071 {
5072 $attach = CIMMessageParamAttach::GetAttachByJson($arParams['ATTACH']);
5073 if ($attach)
5074 {
5075 if ($attach->IsAllowSize())
5076 {
5077 $arMessageFields['ATTACH'] = $attach;
5078 }
5079 else
5080 {
5081 throw new Bitrix\Rest\RestException("You have exceeded the maximum allowable size of attach", "ATTACH_OVERSIZE", CRestServer::STATUS_WRONG_REQUEST);
5082 }
5083 }
5084 else if ($arParams['ATTACH'])
5085 {
5086 throw new Bitrix\Rest\RestException("Incorrect attach params", "ATTACH_ERROR", CRestServer::STATUS_WRONG_REQUEST);
5087 }
5088 }
5089
5090 if (isset($arParams['KEYBOARD']) && !empty($arParams['KEYBOARD']))
5091 {
5092 $keyboard = Array();
5093 if (is_string($arParams['KEYBOARD']))
5094 {
5095 $arParams['KEYBOARD'] = \CUtil::JsObjectToPhp($arParams['KEYBOARD']);
5096 }
5097 if (!isset($arParams['KEYBOARD']['BUTTONS']))
5098 {
5099 $keyboard['BUTTONS'] = $arParams['KEYBOARD'];
5100 }
5101 else
5102 {
5103 $keyboard = $arParams['KEYBOARD'];
5104 }
5105 $keyboard['BOT_ID'] = $arParams['BOT_ID'];
5106
5107 $keyboard = \Bitrix\Im\Bot\Keyboard::getKeyboardByJson($keyboard);
5108 if ($keyboard)
5109 {
5110 $arMessageFields['KEYBOARD'] = $keyboard;
5111 }
5112 else
5113 {
5114 throw new Bitrix\Rest\RestException("Incorrect keyboard params", "KEYBOARD_ERROR", CRestServer::STATUS_WRONG_REQUEST);
5115 }
5116 }
5117
5118 if (isset($arParams['MENU']) && !empty($arParams['MENU']))
5119 {
5120 $menu = Array();
5121 if (is_string($arParams['MENU']))
5122 {
5123 $arParams['MENU'] = \CUtil::JsObjectToPhp($arParams['MENU']);
5124 }
5125 if (!isset($arParams['MENU']['ITEMS']))
5126 {
5127 $menu['ITEMS'] = $arParams['MENU'];
5128 }
5129 else
5130 {
5131 $menu = $arParams['MENU'];
5132 }
5133 $menu['BOT_ID'] = $arParams['BOT_ID'];
5134
5136 if ($menu)
5137 {
5138 $arMessageFields['MENU'] = $menu;
5139 }
5140 else
5141 {
5142 throw new Bitrix\Rest\RestException("Incorrect menu params", "MENU_ERROR", CRestServer::STATUS_WRONG_REQUEST);
5143 }
5144 }
5145
5146 if (isset($arParams['SYSTEM']) && $arParams['SYSTEM'] == 'Y')
5147 {
5148 $arMessageFields['SYSTEM'] = 'Y';
5149 }
5150
5151 if (isset($arParams['URL_PREVIEW']) && $arParams['URL_PREVIEW'] == 'N')
5152 {
5153 $arMessageFields['URL_PREVIEW'] = 'N';
5154 }
5155
5156 if (isset($arParams['SKIP_CONNECTOR']) && mb_strtoupper($arParams['SKIP_CONNECTOR']) == 'Y')
5157 {
5158 $arMessageFields['SKIP_CONNECTOR'] = 'Y';
5159 $arMessageFields['SILENT_CONNECTOR'] = 'Y';
5160 }
5161
5162 $id = \Bitrix\Im\Bot::addMessage(array('BOT_ID' => $arParams['BOT_ID']), $arMessageFields);
5163 if (!$id)
5164 {
5165 throw new Bitrix\Rest\RestException("Message isn't added", "WRONG_REQUEST", CRestServer::STATUS_WRONG_REQUEST);
5166 }
5167
5168 return $id;
5169
5170 }
5171
5172 public static function botMessageUpdate($arParams, $n, CRestServer $server)
5173 {
5174 $arParams = array_change_key_case($arParams, CASE_UPPER);
5175
5176 $clientId = $server->getClientId();
5177 if (!$clientId)
5178 {
5179 if (!empty($arParams['CLIENT_ID']))
5180 {
5181 $clientId = 'custom'.$arParams['CLIENT_ID'];
5182 }
5183 else
5184 {
5185 throw new \Bitrix\Rest\AccessException("Client ID not specified");
5186 }
5187 }
5188
5189 $bots = \Bitrix\Im\Bot::getListCache();
5190 if (isset($arParams['BOT_ID']))
5191 {
5192 if (!isset($bots[$arParams['BOT_ID']]))
5193 {
5194 throw new Bitrix\Rest\RestException("Bot not found", "BOT_ID_ERROR", CRestServer::STATUS_WRONG_REQUEST);
5195 }
5196 if ($clientId && $bots[$arParams['BOT_ID']]['APP_ID'] != $clientId)
5197 {
5198 throw new Bitrix\Rest\RestException("Bot was installed by another rest application", "APP_ID_ERROR", CRestServer::STATUS_WRONG_REQUEST);
5199 }
5200 }
5201 else
5202 {
5203 $botFound = false;
5204 foreach ($bots as $bot)
5205 {
5206 if ($bot['APP_ID'] == $clientId)
5207 {
5208 $botFound = true;
5209 $arParams['BOT_ID'] = $bot['BOT_ID'];
5210 break;
5211 }
5212 }
5213 if (!$botFound)
5214 {
5215 throw new Bitrix\Rest\RestException("Bot not found", "BOT_ID_ERROR", CRestServer::STATUS_WRONG_REQUEST);
5216 }
5217 }
5218
5219 $arParams['MESSAGE_ID'] = intval($arParams['MESSAGE_ID']);
5220 if ($arParams['MESSAGE_ID'] <= 0)
5221 {
5222 throw new Bitrix\Rest\RestException("Message ID can't be empty", "MESSAGE_ID_ERROR", CRestServer::STATUS_WRONG_REQUEST);
5223 }
5224
5225 $message = null;
5226 if (isset($arParams['ATTACH']))
5227 {
5228 $message = CIMMessenger::CheckPossibilityUpdateMessage(IM_CHECK_UPDATE, $arParams['MESSAGE_ID'], $arParams['BOT_ID']);
5229 if (!$message)
5230 {
5231 throw new Bitrix\Rest\RestException("Time has expired for modification or you don't have access", "CANT_EDIT_MESSAGE", CRestServer::STATUS_FORBIDDEN);
5232 }
5233
5234 if (empty($arParams['ATTACH']) || $arParams['ATTACH'] == 'N')
5235 {
5236 CIMMessageParam::Set($arParams['MESSAGE_ID'], Array('ATTACH' => Array()));
5237 }
5238 else
5239 {
5240 $attach = CIMMessageParamAttach::GetAttachByJson($arParams['ATTACH']);
5241 if ($attach)
5242 {
5243 if ($attach->IsAllowSize())
5244 {
5245 CIMMessageParam::Set($arParams['MESSAGE_ID'], Array('ATTACH' => $attach));
5246 }
5247 else
5248 {
5249 throw new Bitrix\Rest\RestException("You have exceeded the maximum allowable size of attach", "ATTACH_OVERSIZE", CRestServer::STATUS_WRONG_REQUEST);
5250 }
5251 }
5252 else if ($arParams['ATTACH'])
5253 {
5254 throw new Bitrix\Rest\RestException("Incorrect attach params", "ATTACH_ERROR", CRestServer::STATUS_WRONG_REQUEST);
5255 }
5256 }
5257 }
5258
5259
5260 if (isset($arParams['KEYBOARD']))
5261 {
5262 if (is_null($message))
5263 {
5264 $message = CIMMessenger::CheckPossibilityUpdateMessage(IM_CHECK_UPDATE, $arParams['MESSAGE_ID'], $arParams['BOT_ID']);
5265 }
5266 if (!$message)
5267 {
5268 throw new Bitrix\Rest\RestException("Time has expired for modification or you don't have access", "CANT_EDIT_MESSAGE", CRestServer::STATUS_FORBIDDEN);
5269 }
5270
5271 if (empty($arParams['KEYBOARD']) || $arParams['KEYBOARD'] == 'N')
5272 {
5273 CIMMessageParam::Set($arParams['MESSAGE_ID'], Array('KEYBOARD' => 'N'));
5274 }
5275 else
5276 {
5277 $keyboard = Array();
5278 if (is_string($arParams['KEYBOARD']))
5279 {
5280 $arParams['KEYBOARD'] = \CUtil::JsObjectToPhp($arParams['KEYBOARD']);
5281 }
5282 if (!isset($arParams['KEYBOARD']['BUTTONS']))
5283 {
5284 $keyboard['BUTTONS'] = $arParams['KEYBOARD'];
5285 }
5286 else
5287 {
5288 $keyboard = $arParams['KEYBOARD'];
5289 }
5290 $keyboard['BOT_ID'] = $arParams['BOT_ID'];
5291
5292 $keyboard = \Bitrix\Im\Bot\Keyboard::getKeyboardByJson($keyboard);
5293 if ($keyboard)
5294 {
5295 if ($keyboard->isAllowSize())
5296 {
5297 CIMMessageParam::Set($arParams['MESSAGE_ID'], Array('KEYBOARD' => $keyboard));
5298 }
5299 else
5300 {
5301 throw new Bitrix\Rest\RestException("You have exceeded the maximum allowable size of keyboard", "KEYBOARD_OVERSIZE", CRestServer::STATUS_WRONG_REQUEST);
5302 }
5303 }
5304 else if ($arParams['KEYBOARD'])
5305 {
5306 throw new Bitrix\Rest\RestException("Incorrect keyboard params", "KEYBOARD_ERROR", CRestServer::STATUS_WRONG_REQUEST);
5307 }
5308 }
5309 }
5310
5311 if (isset($arParams['MENU']))
5312 {
5313 if (is_null($message))
5314 {
5315 $message = CIMMessenger::CheckPossibilityUpdateMessage(IM_CHECK_UPDATE, $arParams['MESSAGE_ID'], $arParams['BOT_ID']);
5316 }
5317 if (!$message)
5318 {
5319 throw new Bitrix\Rest\RestException("Time has expired for modification or you don't have access", "CANT_EDIT_MESSAGE", CRestServer::STATUS_FORBIDDEN);
5320 }
5321
5322 if (empty($arParams['MENU']) || $arParams['MENU'] == 'N')
5323 {
5324 CIMMessageParam::Set($arParams['MESSAGE_ID'], Array('MENU' => 'N'));
5325 }
5326 else
5327 {
5328 $menu = Array();
5329 if (is_string($arParams['MENU']))
5330 {
5331 $arParams['MENU'] = \CUtil::JsObjectToPhp($arParams['MENU']);
5332 }
5333 if (!isset($arParams['MENU']['ITEMS']))
5334 {
5335 $menu['ITEMS'] = $arParams['MENU'];
5336 }
5337 else
5338 {
5339 $menu = $arParams['MENU'];
5340 }
5341 $menu['BOT_ID'] = $arParams['BOT_ID'];
5342
5344 if ($menu)
5345 {
5346 if ($menu->isAllowSize())
5347 {
5348 CIMMessageParam::Set($arParams['MESSAGE_ID'], Array('MENU' => $menu));
5349 }
5350 else
5351 {
5352 throw new Bitrix\Rest\RestException("You have exceeded the maximum allowable size of menu", "MENU_OVERSIZE", CRestServer::STATUS_WRONG_REQUEST);
5353 }
5354 }
5355 else if ($arParams['MENU'])
5356 {
5357 throw new Bitrix\Rest\RestException("Incorrect menu params", "menu_ERROR", CRestServer::STATUS_WRONG_REQUEST);
5358 }
5359 }
5360 }
5361
5362 if (isset($arParams['MESSAGE']))
5363 {
5364 $urlPreview = isset($arParams['URL_PREVIEW']) && $arParams['URL_PREVIEW'] == "N"? false: true;
5365 $skipConnector = isset($arParams['SKIP_CONNECTOR']) && mb_strtoupper($arParams['SKIP_CONNECTOR']) == "Y"? true: false;
5366
5367 $res = CIMMessenger::Update($arParams['MESSAGE_ID'], $arParams['MESSAGE'], $urlPreview, false, $arParams['BOT_ID'], $skipConnector);
5368 if (!$res)
5369 {
5370 throw new Bitrix\Rest\RestException("Time has expired for modification or you don't have access", "CANT_EDIT_MESSAGE", CRestServer::STATUS_FORBIDDEN);
5371 }
5372 }
5373
5374 CIMMessageParam::SendPull($arParams['MESSAGE_ID'], Array('KEYBOARD', 'ATTACH', 'MENU'));
5375
5376 return true;
5377 }
5378
5379 public static function botMessageDelete($arParams, $n, CRestServer $server)
5380 {
5381 $arParams = array_change_key_case($arParams, CASE_UPPER);
5382
5383 $clientId = $server->getClientId();
5384 if (!$clientId)
5385 {
5386 if (!empty($arParams['CLIENT_ID']))
5387 {
5388 $clientId = 'custom'.$arParams['CLIENT_ID'];
5389 }
5390 else
5391 {
5392 throw new \Bitrix\Rest\AccessException("Client ID not specified");
5393 }
5394 }
5395
5396 $bots = \Bitrix\Im\Bot::getListCache();
5397 if (isset($arParams['BOT_ID']))
5398 {
5399 if (!isset($bots[$arParams['BOT_ID']]))
5400 {
5401 throw new Bitrix\Rest\RestException("Bot not found", "BOT_ID_ERROR", CRestServer::STATUS_WRONG_REQUEST);
5402 }
5403 if ($clientId && $bots[$arParams['BOT_ID']]['APP_ID'] != $clientId)
5404 {
5405 throw new Bitrix\Rest\RestException("Bot was installed by another rest application", "APP_ID_ERROR", CRestServer::STATUS_WRONG_REQUEST);
5406 }
5407 }
5408 else
5409 {
5410 $botFound = false;
5411 foreach ($bots as $bot)
5412 {
5413 if ($bot['APP_ID'] == $clientId)
5414 {
5415 $botFound = true;
5416 $arParams['BOT_ID'] = $bot['BOT_ID'];
5417 break;
5418 }
5419 }
5420 if (!$botFound)
5421 {
5422 throw new Bitrix\Rest\RestException("Bot not found", "BOT_ID_ERROR", CRestServer::STATUS_WRONG_REQUEST);
5423 }
5424 }
5425
5426 $arParams['MESSAGE_ID'] = intval($arParams['MESSAGE_ID']);
5427 if ($arParams['MESSAGE_ID'] <= 0)
5428 {
5429 throw new Bitrix\Rest\RestException("Message ID can't be empty", "MESSAGE_ID_ERROR", CRestServer::STATUS_WRONG_REQUEST);
5430 }
5431
5432 $res = CIMMessenger::Delete($arParams['MESSAGE_ID'], $arParams['BOT_ID'], $arParams['COMPLETE'] == 'Y');
5433 if (!$res)
5434 {
5435 throw new Bitrix\Rest\RestException("Time has expired for modification or you don't have access", "CANT_EDIT_MESSAGE", CRestServer::STATUS_FORBIDDEN);
5436 }
5437
5438 return true;
5439 }
5440
5441 public static function botMessageLike($arParams, $n, CRestServer $server)
5442 {
5443 $arParams = array_change_key_case($arParams, CASE_UPPER);
5444
5445 $clientId = $server->getClientId();
5446 if (!$clientId)
5447 {
5448 if (!empty($arParams['CLIENT_ID']))
5449 {
5450 $clientId = 'custom'.$arParams['CLIENT_ID'];
5451 }
5452 else
5453 {
5454 throw new \Bitrix\Rest\AccessException("Client ID not specified");
5455 }
5456 }
5457
5458 $bots = \Bitrix\Im\Bot::getListCache();
5459 if (isset($arParams['BOT_ID']))
5460 {
5461 if (!isset($bots[$arParams['BOT_ID']]))
5462 {
5463 throw new Bitrix\Rest\RestException("Bot not found", "BOT_ID_ERROR", CRestServer::STATUS_WRONG_REQUEST);
5464 }
5465 if ($clientId && $bots[$arParams['BOT_ID']]['APP_ID'] != $clientId)
5466 {
5467 throw new Bitrix\Rest\RestException("Bot was installed by another rest application", "APP_ID_ERROR", CRestServer::STATUS_WRONG_REQUEST);
5468 }
5469 }
5470 else
5471 {
5472 $botFound = false;
5473 foreach ($bots as $bot)
5474 {
5475 if ($bot['APP_ID'] == $clientId)
5476 {
5477 $botFound = true;
5478 $arParams['BOT_ID'] = $bot['BOT_ID'];
5479 break;
5480 }
5481 }
5482 if (!$botFound)
5483 {
5484 throw new Bitrix\Rest\RestException("Bot not found", "BOT_ID_ERROR", CRestServer::STATUS_WRONG_REQUEST);
5485 }
5486 }
5487
5488 $arParams['MESSAGE_ID'] = intval($arParams['MESSAGE_ID']);
5489 if ($arParams['MESSAGE_ID'] <= 0)
5490 {
5491 throw new Bitrix\Rest\RestException("Message ID can't be empty", "MESSAGE_ID_ERROR", CRestServer::STATUS_WRONG_REQUEST);
5492 }
5493
5494 $arParams['ACTION'] = mb_strtolower($arParams['ACTION']);
5495 if (!in_array($arParams['ACTION'], Array('auto', 'plus', 'minus')))
5496 {
5497 $arParams['ACTION'] = 'auto';
5498 }
5499
5500 $result = CIMMessenger::Like($arParams['MESSAGE_ID'], $arParams['ACTION'], $arParams['BOT_ID']);
5501 if ($result === false)
5502 {
5503 throw new Bitrix\Rest\RestException("Action completed without changes", "WITHOUT_CHANGES", CRestServer::STATUS_WRONG_REQUEST);
5504 }
5505
5506 return true;
5507 }
5508
5509 public static function botSendTyping($arParams, $n, CRestServer $server)
5510 {
5511 $arParams = array_change_key_case($arParams, CASE_UPPER);
5512
5513 $clientId = $server->getClientId();
5514 if (!$clientId)
5515 {
5516 if (!empty($arParams['CLIENT_ID']))
5517 {
5518 $clientId = 'custom'.$arParams['CLIENT_ID'];
5519 }
5520 else
5521 {
5522 throw new \Bitrix\Rest\AccessException("Client ID not specified");
5523 }
5524 }
5525
5526 $bots = \Bitrix\Im\Bot::getListCache();
5527 if (isset($arParams['BOT_ID']))
5528 {
5529 if (!isset($bots[$arParams['BOT_ID']]))
5530 {
5531 throw new Bitrix\Rest\RestException("Bot not found", "BOT_ID_ERROR", CRestServer::STATUS_WRONG_REQUEST);
5532 }
5533 if ($clientId && $bots[$arParams['BOT_ID']]['APP_ID'] != $clientId)
5534 {
5535 throw new Bitrix\Rest\RestException("Bot was installed by another rest application", "APP_ID_ERROR", CRestServer::STATUS_WRONG_REQUEST);
5536 }
5537 }
5538 else
5539 {
5540 $botFound = false;
5541 foreach ($bots as $bot)
5542 {
5543 if ($bot['APP_ID'] == $clientId)
5544 {
5545 $botFound = true;
5546 $arParams['BOT_ID'] = $bot['BOT_ID'];
5547 break;
5548 }
5549 }
5550 if (!$botFound)
5551 {
5552 throw new Bitrix\Rest\RestException("Bot not found", "BOT_ID_ERROR", CRestServer::STATUS_WRONG_REQUEST);
5553 }
5554 }
5555
5556 if (!\Bitrix\Im\Common::isDialogId($arParams['DIALOG_ID']))
5557 {
5558 throw new Bitrix\Rest\RestException("Dialog ID can't be empty", "DIALOG_ID_EMPTY", CRestServer::STATUS_WRONG_REQUEST);
5559 }
5560
5561 \Bitrix\Im\Bot::startWriting(Array('BOT_ID' => $arParams['BOT_ID']), $arParams['DIALOG_ID']);
5562
5563 return true;
5564 }
5565
5566 public static function botUpdateTextFieldEnabled($arParams, $n, CRestServer $server)
5567 {
5568 $arParams = array_change_key_case($arParams, CASE_UPPER);
5569
5570 if (isset($arParams['DIALOG_ID']))
5571 {
5572 if (\Bitrix\Im\Common::isChatId($arParams['DIALOG_ID']))
5573 {
5574 $arParams['CHAT_ID'] = \Bitrix\Im\Dialog::getChatId($arParams['DIALOG_ID']);
5575 }
5576 else
5577 {
5578 throw new Bitrix\Rest\RestException("Dialog ID can't be empty", "DIALOG_ID_EMPTY", CRestServer::STATUS_WRONG_REQUEST);
5579 }
5580 }
5581
5582 $arParams['CHAT_ID'] = (int)$arParams['CHAT_ID'];
5583
5584 if ($arParams['CHAT_ID'] <= 0)
5585 {
5586 throw new Bitrix\Rest\RestException("Chat ID can't be empty", "CHAT_ID_EMPTY", CRestServer::STATUS_WRONG_REQUEST);
5587 }
5588
5589 if (!isset($arParams['TEXT_FIELD_ENABLED']))
5590 {
5591 throw new Bitrix\Rest\RestException(" text field enabled can't be empty", "TEXT_FIELD_ENABLED_EMPTY", CRestServer::STATUS_WRONG_REQUEST);
5592 }
5593
5594 $arParams['TEXT_FIELD_ENABLED'] = $arParams['TEXT_FIELD_ENABLED'] !== 'N';
5595
5596 $botId = self::getBotId($arParams, $server);
5597
5598 $chat = \Bitrix\Im\V2\Chat::getInstance($arParams['CHAT_ID']);
5599 if (!$chat->withContextUser((int)$botId)->checkAccess()->isSuccess())
5600 {
5601 throw new Bitrix\Rest\RestException("Bot don't have access to this chat", "ACCESS_ERROR", CRestServer::STATUS_WRONG_REQUEST);
5602 }
5603
5604 (new \Bitrix\Im\V2\Chat\TextField\TextFieldEnabled($chat->getChatId()))->set($arParams['TEXT_FIELD_ENABLED']);
5605
5606 return true;
5607 }
5608
5609 public static function dialogVote($arParams, $offset, CRestServer $server)
5610 {
5611 $arParams = array_change_key_case($arParams, CASE_UPPER);
5612
5613 if (!isset($arParams['MESSAGE_ID']))
5614 {
5615 throw new Bitrix\Rest\RestException("Message ID can't be empty", "MESSAGE_ID_EMPTY", CRestServer::STATUS_WRONG_REQUEST);
5616 }
5617
5618 if (!isset($arParams['DIALOG_ID']) || !\Bitrix\Im\Common::isDialogId($arParams['DIALOG_ID']))
5619 {
5620 throw new Bitrix\Rest\RestException("Dialog ID can't be empty", "DIALOG_ID_EMPTY", CRestServer::STATUS_WRONG_REQUEST);
5621 }
5622
5623 if (!\Bitrix\Im\Dialog::hasAccess($arParams['DIALOG_ID']))
5624 {
5625 throw new Bitrix\Rest\RestException("You do not have access to the specified dialog", "ACCESS_ERROR", CRestServer::STATUS_FORBIDDEN);
5626 }
5627
5628 if (!isset($arParams['RATING']))
5629 {
5630 $arParams['RATING'] = 'like';
5631 }
5632
5633 $arParams['RATING'] = $arParams['RATING'] == 'dislike' ? 'dislike': 'like';
5634
5635 if (!\CIMMessenger::LinesSessionVote($arParams['DIALOG_ID'], $arParams['MESSAGE_ID'], $arParams['RATING']))
5636 {
5637 throw new Bitrix\Rest\RestException("Action completed without changes", "WITHOUT_CHANGES", CRestServer::STATUS_WRONG_REQUEST);
5638 }
5639
5640 return true;
5641 }
5642
5643 public static function onCommandAdd($arParams, $arHandler)
5644 {
5645 $arParams = array_change_key_case($arParams, CASE_UPPER);
5646
5647 if (!$arHandler['APP_CODE'])
5648 {
5649 $parts = parse_url($arHandler['EVENT_HANDLER']);
5650 parse_str($parts['query'], $query);
5651 $query = array_change_key_case($query, CASE_UPPER);
5652
5653 if ($query['CLIENT_ID'])
5654 {
5655 $arHandler['APP_CODE'] = 'custom'.$query['CLIENT_ID'];
5656 }
5657 }
5658
5659 if (!$arHandler['APP_CODE'])
5660 {
5661 throw new Exception('Event is intended for another application');
5662 }
5663
5664 $bot = \Bitrix\Im\Bot::getListCache();
5665
5666 $commandId = Array();
5667 foreach ($arParams[0] as $commandData)
5668 {
5669 if ($commandData['APP_ID'] == $arHandler['APP_CODE'] && $commandData['BOT_ID'] > 0)
5670 {
5671 $sendBotData = self::getAccessToken($arHandler['APP_ID'], $commandData['BOT_ID']);
5672 $sendBotData['AUTH'] = $sendBotData;
5673 $sendBotData['BOT_ID'] = $commandData['BOT_ID'];
5674 $sendBotData['BOT_CODE'] = $bot[$commandData['BOT_ID']]['CODE'];
5675 $sendBotData['COMMAND'] = $commandData['COMMAND'];
5676 $sendBotData['COMMAND_ID'] = $commandData['ID'];
5677 $sendBotData['COMMAND_PARAMS'] = $commandData['EXEC_PARAMS'];
5678 $sendBotData['COMMAND_CONTEXT'] = $commandData['CONTEXT'];
5679 $sendBotData['MESSAGE_ID'] = $arParams[1];
5680 $commandId[$sendBotData['COMMAND_ID']] = $sendBotData;
5681 if ($commandData['CONTEXT'] != 'KEYBOARD')
5682 {
5683 if (
5684 $arParams[2]['MESSAGE_TYPE'] != IM_MESSAGE_PRIVATE ||
5685 $arParams[2]['FROM_USER_ID'] == $commandData['BOT_ID'] ||
5686 $arParams[2]['TO_USER_ID'] == $commandData['BOT_ID']
5687 )
5688 {
5689 \Bitrix\Im\Bot::startWriting(Array('BOT_ID' => $commandData['BOT_ID']), $arParams[2]['DIALOG_ID']);
5690 }
5691 }
5692 }
5693 }
5694 if (empty($commandId))
5695 {
5696 throw new Exception('Event is intended for another application');
5697 }
5698 $arParams[2]['MESSAGE_ID'] = $arParams[1];
5699 $arParams[2]['CHAT_TYPE'] = $arParams[2]['MESSAGE_TYPE'];
5700 $arParams[2]['LANGUAGE'] = \Bitrix\Im\Bot::getDefaultLanguage();
5701
5702 if ($arParams[2]['FROM_USER_ID'] > 0)
5703 {
5704 $fromUser = \Bitrix\Im\User::getInstance($arParams[2]['FROM_USER_ID'])->getFields();
5705
5706 $user = Array(
5707 'ID' => $fromUser['id'],
5708 'NAME' => $fromUser['name'],
5709 'FIRST_NAME' => $fromUser['first_name'],
5710 'LAST_NAME' => $fromUser['last_name'],
5711 'WORK_POSITION' => $fromUser['work_position'],
5712 'GENDER' => $fromUser['gender'],
5713 );
5714 }
5715 else
5716 {
5717 $user = Array();
5718 }
5719
5720 return Array(
5721 'COMMAND' => $commandId,
5722 'PARAMS' => $arParams[2],
5723 'USER' => $user
5724 );
5725 }
5726
5727 public static function onBotMessageAdd($arParams, $arHandler)
5728 {
5729 $arParams = array_change_key_case($arParams, CASE_UPPER);
5730
5731 if (!$arHandler['APP_CODE'])
5732 {
5733 $parts = parse_url($arHandler['EVENT_HANDLER']);
5734 parse_str($parts['query'], $query);
5735 $query = array_change_key_case($query, CASE_UPPER);
5736
5737 if ($query['CLIENT_ID'])
5738 {
5739 $arHandler['APP_CODE'] = 'custom'.$query['CLIENT_ID'];
5740 }
5741 }
5742
5743 if (!$arHandler['APP_CODE'])
5744 {
5745 throw new Exception('Event is intended for another application');
5746 }
5747
5748 $bots = Array();
5749 foreach ($arParams[0] as $botData)
5750 {
5751 if ($botData['APP_ID'] == $arHandler['APP_CODE'])
5752 {
5753 $sendBotData = self::getAccessToken($arHandler['APP_ID'], $botData['BOT_ID']);
5754 $sendBotData['AUTH'] = $sendBotData;
5755 $sendBotData['BOT_ID'] = $botData['BOT_ID'];
5756 $sendBotData['BOT_CODE'] = $botData['CODE'];
5757 $bots[$botData['BOT_ID']] = $sendBotData;
5758
5759 if ($arParams[2]['CHAT_ENTITY_TYPE'] != 'LINES' && $botData['TYPE'] != \Bitrix\Im\Bot::TYPE_SUPERVISOR)
5760 {
5761 \Bitrix\Im\Bot::startWriting(Array('BOT_ID' => $botData['BOT_ID']), $arParams[2]['DIALOG_ID']);
5762 }
5763 }
5764 }
5765
5766 if (empty($bots))
5767 {
5768 throw new Exception('Event is intended for another application');
5769 }
5770 $arParams[2]['MESSAGE_ID'] = $arParams[1];
5771 $arParams[2]['CHAT_TYPE'] = $arParams[2]['MESSAGE_TYPE'];
5772 $arParams[2]['LANGUAGE'] = \Bitrix\Im\Bot::getDefaultLanguage();
5773
5774 if ($arParams[2]['FROM_USER_ID'] > 0)
5775 {
5776 $fromUser = \Bitrix\Im\User::getInstance($arParams[2]['FROM_USER_ID'])->getFields();
5777
5778 $user = Array(
5779 'ID' => $fromUser['id'],
5780 'NAME' => $fromUser['name'],
5781 'FIRST_NAME' => $fromUser['first_name'],
5782 'LAST_NAME' => $fromUser['last_name'],
5783 'WORK_POSITION' => $fromUser['work_position'],
5784 'GENDER' => $fromUser['gender'],
5785 'IS_BOT' => $fromUser['bot']? 'Y':'N',
5786 'IS_CONNECTOR' => $fromUser['connector']? 'Y':'N',
5787 'IS_NETWORK' => $fromUser['network']? 'Y':'N',
5788 'IS_EXTRANET' => $fromUser['extranet']? 'Y':'N',
5789 );
5790 }
5791 else
5792 {
5793 $user = Array();
5794 }
5795
5796 return Array(
5797 'BOT' => $bots,
5798 'PARAMS' => $arParams[2],
5799 'USER' => $user
5800 );
5801 }
5802
5803 public static function onBotMessageUpdate($arParams, $arHandler)
5804 {
5805 $arParams = array_change_key_case($arParams, CASE_UPPER);
5806
5807 if (!$arHandler['APP_CODE'])
5808 {
5809 $parts = parse_url($arHandler['EVENT_HANDLER']);
5810 parse_str($parts['query'], $query);
5811 $query = array_change_key_case($query, CASE_UPPER);
5812
5813 if ($query['CLIENT_ID'])
5814 {
5815 $arHandler['APP_CODE'] = 'custom'.$query['CLIENT_ID'];
5816 }
5817 }
5818
5819 if (!$arHandler['APP_CODE'])
5820 {
5821 throw new Exception('Event is intended for another application');
5822 }
5823
5824 $bots = Array();
5825 foreach ($arParams[0] as $botData)
5826 {
5827 if ($botData['APP_ID'] == $arHandler['APP_CODE'])
5828 {
5829 $sendBotData = self::getAccessToken($arHandler['APP_ID'], $botData['BOT_ID']);
5830 $sendBotData['AUTH'] = $sendBotData;
5831 $sendBotData['BOT_ID'] = $botData['BOT_ID'];
5832 $sendBotData['BOT_CODE'] = $botData['CODE'];
5833 $bots[$botData['BOT_ID']] = $sendBotData;
5834 }
5835 }
5836
5837 if (empty($bots))
5838 {
5839 throw new Exception('Event is intended for another application');
5840 }
5841
5842 $arParams[2]['MESSAGE_ID'] = $arParams[1];
5843 $arParams[2]['CHAT_TYPE'] = $arParams[2]['MESSAGE_TYPE'];
5844 $arParams[2]['LANGUAGE'] = \Bitrix\Im\Bot::getDefaultLanguage();
5845
5846 if ($arParams[2]['FROM_USER_ID'] > 0)
5847 {
5848 $fromUser = \Bitrix\Im\User::getInstance($arParams[2]['FROM_USER_ID'])->getFields();
5849
5850 $user = Array(
5851 'ID' => $fromUser['id'],
5852 'NAME' => $fromUser['name'],
5853 'FIRST_NAME' => $fromUser['first_name'],
5854 'LAST_NAME' => $fromUser['last_name'],
5855 'WORK_POSITION' => $fromUser['work_position'],
5856 'GENDER' => $fromUser['gender'],
5857 'IS_BOT' => $fromUser['bot']? 'Y':'N',
5858 'IS_CONNECTOR' => $fromUser['connector']? 'Y':'N',
5859 'IS_NETWORK' => $fromUser['network']? 'Y':'N',
5860 'IS_EXTRANET' => $fromUser['extranet']? 'Y':'N',
5861 );
5862 }
5863 else
5864 {
5865 $user = Array();
5866 }
5867
5868 return Array(
5869 'BOT' => $bots,
5870 'PARAMS' => $arParams[2],
5871 'USER' => $user
5872 );
5873 }
5874
5875 public static function onBotMessageDelete($arParams, $arHandler)
5876 {
5877 $arParams = array_change_key_case($arParams, CASE_UPPER);
5878
5879 if (!$arHandler['APP_CODE'])
5880 {
5881 $parts = parse_url($arHandler['EVENT_HANDLER']);
5882 parse_str($parts['query'], $query);
5883 $query = array_change_key_case($query, CASE_UPPER);
5884
5885 if ($query['CLIENT_ID'])
5886 {
5887 $arHandler['APP_CODE'] = 'custom'.$query['CLIENT_ID'];
5888 }
5889 }
5890
5891 if (!$arHandler['APP_CODE'])
5892 {
5893 throw new Exception('Event is intended for another application');
5894 }
5895
5896 $bots = Array();
5897 foreach ($arParams[0] as $botData)
5898 {
5899 if ($botData['APP_ID'] == $arHandler['APP_CODE'])
5900 {
5901 $sendBotData = self::getAccessToken($arHandler['APP_ID'], $botData['BOT_ID']);
5902 $sendBotData['AUTH'] = $sendBotData;
5903 $sendBotData['BOT_ID'] = $botData['BOT_ID'];
5904 $sendBotData['BOT_CODE'] = $botData['CODE'];
5905 $bots[$botData['BOT_ID']] = $sendBotData;
5906 }
5907 }
5908
5909 if (empty($bots))
5910 {
5911 throw new Exception('Event is intended for another application');
5912 }
5913
5914 $arParams[2]['MESSAGE_ID'] = $arParams[1];
5915 $arParams[2]['CHAT_TYPE'] = $arParams[2]['MESSAGE_TYPE'];
5916 $arParams[2]['LANGUAGE'] = \Bitrix\Im\Bot::getDefaultLanguage();
5917
5918 if ($arParams[2]['FROM_USER_ID'] > 0)
5919 {
5920 $fromUser = \Bitrix\Im\User::getInstance($arParams[2]['FROM_USER_ID'])->getFields();
5921
5922 $user = Array(
5923 'ID' => $fromUser['id'],
5924 'NAME' => $fromUser['name'],
5925 'FIRST_NAME' => $fromUser['first_name'],
5926 'LAST_NAME' => $fromUser['last_name'],
5927 'WORK_POSITION' => $fromUser['work_position'],
5928 'GENDER' => $fromUser['gender'],
5929 'IS_BOT' => $fromUser['bot']? 'Y':'N',
5930 'IS_CONNECTOR' => $fromUser['connector']? 'Y':'N',
5931 'IS_NETWORK' => $fromUser['network']? 'Y':'N',
5932 'IS_EXTRANET' => $fromUser['extranet']? 'Y':'N',
5933 );
5934 }
5935 else
5936 {
5937 $user = Array();
5938 }
5939
5940 return Array(
5941 'BOT' => $bots,
5942 'PARAMS' => $arParams[2],
5943 'USER' => $user
5944 );
5945 }
5946
5947 public static function onBotJoinChat($arParams, $arHandler)
5948 {
5949 $arParams = array_change_key_case($arParams, CASE_UPPER);
5950
5951 if (!$arHandler['APP_CODE'])
5952 {
5953 $parts = parse_url($arHandler['EVENT_HANDLER']);
5954 parse_str($parts['query'], $query);
5955 $query = array_change_key_case($query, CASE_UPPER);
5956 if ($query['CLIENT_ID'])
5957 {
5958 $arHandler['APP_CODE'] = 'custom'.$query['CLIENT_ID'];
5959 }
5960 }
5961
5962 if (!$arHandler['APP_CODE'])
5963 {
5964 throw new Exception('Event is intended for another application');
5965 }
5966
5967 $bots = Array();
5968 if ($arParams[0]['APP_ID'] == $arHandler['APP_CODE'])
5969 {
5970 $sendBotData = self::getAccessToken($arHandler['APP_ID'], $arParams[0]['BOT_ID']);
5971 $sendBotData['AUTH'] = $sendBotData;
5972 $sendBotData['BOT_ID'] = $arParams[0]['BOT_ID'];
5973 $sendBotData['BOT_CODE'] = $arParams[0]['CODE'];
5974 $bots[$arParams[0]['BOT_ID']] = $sendBotData;
5975 }
5976
5977 if (empty($bots))
5978 {
5979 throw new Exception('Event is intended for another application');
5980 }
5981
5982 $params = $arParams[2];
5983 $params['DIALOG_ID'] = $arParams[1];
5984 $params['LANGUAGE'] = \Bitrix\Im\Bot::getDefaultLanguage();
5985
5986 if ($params['USER_ID'] > 0)
5987 {
5988 $fromUser = \Bitrix\Im\User::getInstance($params['USER_ID'])->getFields();
5989
5990 $user = Array(
5991 'ID' => $fromUser['id'],
5992 'NAME' => $fromUser['name'],
5993 'FIRST_NAME' => $fromUser['first_name'],
5994 'LAST_NAME' => $fromUser['last_name'],
5995 'WORK_POSITION' => $fromUser['work_position'],
5996 'GENDER' => $fromUser['gender'],
5997 );
5998 }
5999 else
6000 {
6001 $user = Array();
6002 }
6003
6004 if ($arParams[2]['CHAT_TYPE'] != 'LINES' && $arParams[0]['TYPE'] != \Bitrix\Im\Bot::TYPE_SUPERVISOR)
6005 {
6006 \Bitrix\Im\Bot::startWriting(Array('BOT_ID' => $params['BOT_ID']), $params['DIALOG_ID']);
6007 }
6008
6009 return Array(
6010 'BOT' => $bots,
6011 'PARAMS' => $params,
6012 'USER' => $user
6013 );
6014 }
6015
6016 public static function onBotDelete($arParams, $arHandler)
6017 {
6018 $arParams = array_change_key_case($arParams, CASE_UPPER);
6019
6020 if (!$arHandler['APP_CODE'])
6021 {
6022 $parts = parse_url($arHandler['EVENT_HANDLER']);
6023 parse_str($parts['query'], $query);
6024 $query = array_change_key_case($query, CASE_UPPER);
6025 if ($query['CLIENT_ID'])
6026 {
6027 $arHandler['APP_CODE'] = 'custom'.$query['CLIENT_ID'];
6028 }
6029 }
6030
6031 if (!$arHandler['APP_CODE'])
6032 {
6033 throw new Exception('Event is intended for another application');
6034 }
6035
6036 $botCode = "";
6037 if ($arParams[0]['APP_ID'] == $arHandler['APP_CODE'])
6038 {
6039 $botCode = $arParams[0]['CODE'];
6040 }
6041
6042 if (!$botCode)
6043 {
6044 throw new Exception('Event is intended for another application');
6045 }
6046
6047 $botId = $arParams[1];
6048
6049 $result = self::unbindEvent($arHandler['APP_ID'], $arHandler['APP_CODE'], 'im', 'onImBotMessageAdd', 'OnImBotMessageAdd');
6050 if ($result)
6051 {
6052 self::unbindEvent($arHandler['APP_ID'], $arHandler['APP_CODE'], 'im', 'onImBotJoinChat', 'OnImBotJoinChat');
6053 self::unbindEvent($arHandler['APP_ID'], $arHandler['APP_CODE'], 'im', 'onImBotDelete', 'OnImBotDelete');
6054 }
6055
6056 return Array(
6057 'BOT_ID' => $botId,
6058 'BOT_CODE' => $botCode
6059 );
6060 }
6061
6062 public static function onBotContextGet($arParams, $arHandler): array
6063 {
6064 $arParams = array_change_key_case($arParams, CASE_UPPER);
6065
6066 if (!$arHandler['APP_CODE'])
6067 {
6068 $parts = parse_url($arHandler['EVENT_HANDLER']);
6069 parse_str($parts['query'], $query);
6070 $query = array_change_key_case($query, CASE_UPPER);
6071 if ($query['CLIENT_ID'])
6072 {
6073 $arHandler['APP_CODE'] = 'custom'.$query['CLIENT_ID'];
6074 }
6075 }
6076
6077 if (!$arHandler['APP_CODE'])
6078 {
6079 throw new Exception('Event is intended for another application');
6080 }
6081
6082
6083 $bots = [];
6084 foreach ($arParams[0] as $botData)
6085 {
6086 if ($botData['APP_ID'] == $arHandler['APP_CODE'])
6087 {
6088 $sendBotData = self::getAccessToken($arHandler['APP_ID'], $botData['BOT_ID']);
6089 $sendBotData['AUTH'] = $sendBotData;
6090 $sendBotData['BOT_ID'] = $botData['BOT_ID'];
6091 $sendBotData['BOT_CODE'] = $botData['CODE'];
6092 $bots[$botData['BOT_ID']] = $sendBotData;
6093 }
6094 }
6095
6096 if (empty($bots))
6097 {
6098 throw new Exception('Event is intended for another application');
6099 }
6100
6101 $params = $arParams[2];
6102 $params['DIALOG_ID'] = $arParams[1];
6103 $params['LANGUAGE'] = \Bitrix\Im\Bot::getDefaultLanguage();
6104
6105 $user = [];
6106 if ($params['USER_ID'] > 0)
6107 {
6108 $fromUser = \Bitrix\Im\User::getInstance($params['USER_ID'])->getFields();
6109
6110 $user = [
6111 'ID' => $fromUser['id'],
6112 'NAME' => $fromUser['name'],
6113 'FIRST_NAME' => $fromUser['first_name'],
6114 'LAST_NAME' => $fromUser['last_name'],
6115 'WORK_POSITION' => $fromUser['work_position'],
6116 'GENDER' => $fromUser['gender'],
6117 ];
6118 }
6119
6120 return [
6121 'BOT' => $bots,
6122 'PARAMS' => $params,
6123 'USER' => $user,
6124 ];
6125 }
6126
6127 public static function commandRegister($arParams, $n, CRestServer $server)
6128 {
6129 if ($server->getAuthType() == \Bitrix\Rest\SessionAuth\Auth::AUTH_TYPE)
6130 {
6131 throw new \Bitrix\Rest\RestException("Access for this method not allowed by session authorization.", "WRONG_AUTH_TYPE", \CRestServer::STATUS_FORBIDDEN);
6132 }
6133 $arParams = array_change_key_case($arParams, CASE_UPPER);
6134
6135 $customClientId = false;
6136 $clientId = $server->getClientId();
6137 if (!$clientId)
6138 {
6139 if (!empty($arParams['CLIENT_ID']))
6140 {
6141 $customClientId = true;
6142 $clientId = 'custom'.$arParams['CLIENT_ID'];
6143 }
6144 else
6145 {
6146 throw new \Bitrix\Rest\AccessException("Client ID not specified");
6147 }
6148 }
6149
6150 if ($customClientId)
6151 {
6152 $arApp = ['ID' => '', 'CLIENT_ID' => $arParams['CLIENT_ID']];
6153 }
6154 else
6155 {
6156 $dbRes = \Bitrix\Rest\AppTable::getList(array('filter' => array('=CLIENT_ID' => $clientId)));
6157 $arApp = $dbRes->fetch();
6158 }
6159
6160 if (isset($arParams['EVENT_COMMAND_ADD']) && !empty($arParams['EVENT_COMMAND_ADD']))
6161 {
6162 if ($customClientId)
6163 {
6164 $arParams['EVENT_COMMAND_ADD'] = $arParams['EVENT_COMMAND_ADD'].(mb_strpos($arParams['EVENT_COMMAND_ADD'], '?') === false? '?': '&').'CLIENT_ID='.$arParams['CLIENT_ID'];
6165 }
6166 try
6167 {
6168 \Bitrix\Rest\HandlerHelper::checkCallback($arParams['EVENT_COMMAND_ADD'], $arApp);
6169 }
6170 catch(Exception $e)
6171 {
6172 throw new Bitrix\Rest\RestException($e->getMessage(), "EVENT_COMMAND_ADD_ERROR", CRestServer::STATUS_WRONG_REQUEST);
6173 }
6174 }
6175 else
6176 {
6177 throw new Bitrix\Rest\RestException("Handler for \"Command add\" event isn't specified", "EVENT_COMMAND_ADD_ERROR", CRestServer::STATUS_WRONG_REQUEST);
6178 }
6179
6180 if (!isset($arParams['COMMAND']) || empty($arParams['COMMAND']))
6181 {
6182 throw new Bitrix\Rest\RestException("Command isn't specified", "COMMAND_ERROR", CRestServer::STATUS_WRONG_REQUEST);
6183 }
6184
6185 $arParams['BOT_ID'] = intval($arParams['BOT_ID']);
6186 if ($arParams['BOT_ID'] > 0)
6187 {
6188 $bots = \Bitrix\Im\Bot::getListCache();
6189 if (!isset($bots[$arParams['BOT_ID']]))
6190 {
6191 throw new Bitrix\Rest\RestException("Bot not found", "BOT_ID_ERROR", CRestServer::STATUS_WRONG_REQUEST);
6192 }
6193 if ($bots[$arParams['BOT_ID']]['APP_ID'] != $clientId)
6194 {
6195 throw new Bitrix\Rest\RestException("Bot was installed by another rest application", "APP_ID_ERROR", CRestServer::STATUS_WRONG_REQUEST);
6196 }
6197 }
6198 else
6199 {
6200 throw new Bitrix\Rest\RestException("Bot not found", "BOT_ID_ERROR", CRestServer::STATUS_WRONG_REQUEST);
6201 }
6202 $arParams['COMMON'] = isset($arParams['COMMON']) && $arParams['COMMON'] == 'Y'? 'Y': 'N';
6203 $arParams['HIDDEN'] = isset($arParams['HIDDEN']) && $arParams['HIDDEN'] == 'Y'? 'Y': 'N';
6204 $arParams['EXTRANET_SUPPORT'] = isset($arParams['EXTRANET_SUPPORT']) && $arParams['EXTRANET_SUPPORT'] == 'Y'? 'Y': 'N';
6205
6206 if (!isset($arParams['LANG']) || empty($arParams['LANG']))
6207 {
6208 throw new Bitrix\Rest\RestException("Lang set can't be empty", "LANG_ERROR", CRestServer::STATUS_WRONG_REQUEST);
6209 }
6210
6211 $commandId = \Bitrix\Im\Command::register(Array(
6212 'APP_ID' => $clientId,
6213 'BOT_ID' => $arParams['BOT_ID'],
6214 'COMMAND' => $arParams['COMMAND'],
6215 'COMMON' => $arParams['COMMON'],
6216 'HIDDEN' => $arParams['HIDDEN'],
6217 'SONET_SUPPORT' => $arParams['SONET_SUPPORT'],
6218 'EXTRANET_SUPPORT' => $arParams['EXTRANET_SUPPORT'],
6219 'MODULE_ID' => 'rest',
6220 'LANG' => $arParams['LANG'],
6221 ));
6222 if ($commandId)
6223 {
6224 self::unbindEvent($arApp['ID'], $arApp['CLIENT_ID'], 'im', 'onImCommandAdd', 'onImCommandAdd', true);
6225 self::bindEvent($arApp['ID'], $arApp['CLIENT_ID'], 'im', 'onImCommandAdd', 'onImCommandAdd', $arParams['EVENT_COMMAND_ADD']);
6226 }
6227 else
6228 {
6229 throw new Bitrix\Rest\RestException("Command can't be created", "WRONG_REQUEST", CRestServer::STATUS_WRONG_REQUEST);
6230 }
6231
6232 return $commandId;
6233 }
6234
6235 public static function commandUnRegister($arParams, $n, CRestServer $server)
6236 {
6237 if ($server->getAuthType() == \Bitrix\Rest\SessionAuth\Auth::AUTH_TYPE)
6238 {
6239 throw new \Bitrix\Rest\RestException("Access for this method not allowed by session authorization.", "WRONG_AUTH_TYPE", \CRestServer::STATUS_FORBIDDEN);
6240 }
6241 $arParams = array_change_key_case($arParams, CASE_UPPER);
6242
6243 $clientId = $server->getClientId();
6244 if (!$clientId)
6245 {
6246 if (!empty($arParams['CLIENT_ID']))
6247 {
6248 $clientId = 'custom'.$arParams['CLIENT_ID'];
6249 }
6250 else
6251 {
6252 throw new \Bitrix\Rest\AccessException("Client ID not specified");
6253 }
6254 }
6255
6257 if (!isset($commands[$arParams['COMMAND_ID']]))
6258 {
6259 throw new Bitrix\Rest\RestException("Command not found", "COMMAND_ID_ERROR", CRestServer::STATUS_WRONG_REQUEST);
6260 }
6261 if ($commands[$arParams['COMMAND_ID']]['APP_ID'] != $clientId)
6262 {
6263 throw new Bitrix\Rest\RestException("Command was installed by another rest application", "APP_ID_ERROR", CRestServer::STATUS_WRONG_REQUEST);
6264 }
6265
6266 $result = \Bitrix\Im\Command::unRegister(Array('COMMAND_ID' => $arParams['COMMAND_ID']));
6267 if (!$result)
6268 {
6269 throw new Bitrix\Rest\RestException("Command can't be deleted", "WRONG_REQUEST", CRestServer::STATUS_WRONG_REQUEST);
6270 }
6271
6272 return true;
6273 }
6274
6275 public static function commandUpdate($arParams, $n, CRestServer $server)
6276 {
6277 if ($server->getAuthType() == \Bitrix\Rest\SessionAuth\Auth::AUTH_TYPE)
6278 {
6279 throw new \Bitrix\Rest\RestException("Access for this method not allowed by session authorization.", "WRONG_AUTH_TYPE", \CRestServer::STATUS_FORBIDDEN);
6280 }
6281 $arParams = array_change_key_case($arParams, CASE_UPPER);
6282
6283 $clientId = $server->getClientId();
6284 $customClientId = false;
6285 if (!$clientId)
6286 {
6287 if (!empty($arParams['CLIENT_ID']))
6288 {
6289 $customClientId = true;
6290 $clientId = 'custom'.$arParams['CLIENT_ID'];
6291 }
6292 else
6293 {
6294 throw new \Bitrix\Rest\AccessException("Client ID not specified");
6295 }
6296 }
6297
6299 if (!isset($bots[$arParams['COMMAND_ID']]))
6300 {
6301 throw new Bitrix\Rest\RestException("Command not found", "COMMAND_ID_ERROR", CRestServer::STATUS_WRONG_REQUEST);
6302 }
6303 if ($bots[$arParams['COMMAND_ID']]['APP_ID'] != $clientId)
6304 {
6305 throw new Bitrix\Rest\RestException("Command was installed by another rest application", "APP_ID_ERROR", CRestServer::STATUS_WRONG_REQUEST);
6306 }
6307
6308 if ($customClientId)
6309 {
6310 $arApp = ['ID' => '', 'CLIENT_ID' => $arParams['CLIENT_ID']];
6311 }
6312 else
6313 {
6314 $dbRes = \Bitrix\Rest\AppTable::getList(array('filter' => array('=CLIENT_ID' => $clientId)));
6315 $arApp = $dbRes->fetch();
6316 }
6317
6318 $updateEvents = Array();
6319 if (isset($arParams['FIELDS']['EVENT_COMMAND_ADD']) && !empty($arParams['FIELDS']['EVENT_COMMAND_ADD']))
6320 {
6321 $updateEvents['EVENT_COMMAND_ADD'] = $arParams['FIELDS']['EVENT_COMMAND_ADD'];
6322 if ($customClientId)
6323 {
6324 $updateEvents['EVENT_COMMAND_ADD'] = $updateEvents['EVENT_COMMAND_ADD'].(mb_strpos($updateEvents['EVENT_COMMAND_ADD'], '?') === false? '?': '&').'CLIENT_ID='.$arParams['CLIENT_ID'];
6325 }
6326 try
6327 {
6328 \Bitrix\Rest\HandlerHelper::checkCallback($arParams['FIELDS']['EVENT_COMMAND_ADD'], $arApp);
6329 }
6330 catch(Exception $e)
6331 {
6332 throw new Bitrix\Rest\RestException($e->getMessage(), "EVENT_COMMAND_ADD_ERROR", CRestServer::STATUS_WRONG_REQUEST);
6333 }
6334 }
6335
6336 $updateFields = Array();
6337
6338 if (isset($arParams['FIELDS']['COMMAND']) && !empty($arParams['FIELDS']['COMMAND']))
6339 {
6340 $updateFields['COMMAND'] = $arParams['FIELDS']['COMMAND'];
6341 }
6342
6343 if (isset($arParams['FIELDS']['HIDDEN']) && !empty($arParams['FIELDS']['HIDDEN']))
6344 {
6345 $updateFields['HIDDEN'] = $arParams['FIELDS']['HIDDEN'] == 'Y'? 'Y': 'N';
6346 }
6347
6348 if (isset($arParams['FIELDS']['EXTRANET_SUPPORT']) && !empty($arParams['FIELDS']['EXTRANET_SUPPORT']))
6349 {
6350 $updateFields['EXTRANET_SUPPORT'] = $arParams['FIELDS']['EXTRANET_SUPPORT'] == 'Y'? 'Y': 'N';
6351 }
6352
6353 if (isset($arParams['FIELDS']['LANG']) && !empty($arParams['FIELDS']['LANG']))
6354 {
6355 $updateFields['LANG'] = $arParams['FIELDS']['LANG'];
6356 }
6357
6358 if (empty($updateFields))
6359 {
6360 if (empty($updateEvents))
6361 {
6362 throw new Bitrix\Rest\RestException("Update fields can't be empty", "WRONG_REQUEST", CRestServer::STATUS_WRONG_REQUEST);
6363 }
6364 }
6365 else
6366 {
6367 $result = \Bitrix\Im\Command::update(Array('COMMAND_ID' => $arParams['COMMAND_ID']), $updateFields);
6368 if (!$result)
6369 {
6370 throw new Bitrix\Rest\RestException("Command can't be updated", "WRONG_REQUEST", CRestServer::STATUS_WRONG_REQUEST);
6371 }
6372 }
6373
6374 if (isset($updateEvents['EVENT_COMMAND_ADD']))
6375 {
6376 self::unbindEvent($arApp['ID'], $arApp['CLIENT_ID'], 'im', 'onImCommandAdd', 'onImCommandAdd', true);
6377 self::bindEvent($arApp['ID'], $arApp['CLIENT_ID'], 'im', 'onImCommandAdd', 'onImCommandAdd', $updateEvents['EVENT_COMMAND_ADD']);
6378 }
6379
6380 return true;
6381 }
6382
6383 public static function commandAnswer($arParams, $n, CRestServer $server)
6384 {
6385 if ($server->getAuthType() == \Bitrix\Rest\SessionAuth\Auth::AUTH_TYPE)
6386 {
6387 throw new \Bitrix\Rest\RestException("Access for this method not allowed by session authorization.", "WRONG_AUTH_TYPE", \CRestServer::STATUS_FORBIDDEN);
6388 }
6389 $arParams = array_change_key_case($arParams, CASE_UPPER);
6390
6391 $clientId = $server->getClientId();
6392 if (!$clientId)
6393 {
6394 if (!empty($arParams['CLIENT_ID']))
6395 {
6396 $clientId = 'custom'.$arParams['CLIENT_ID'];
6397 }
6398 else
6399 {
6400 throw new \Bitrix\Rest\AccessException("Client ID not specified");
6401 }
6402 }
6403
6405 if (isset($arParams['COMMAND_ID']))
6406 {
6407 if (!isset($commands[$arParams['COMMAND_ID']]))
6408 {
6409 throw new Bitrix\Rest\RestException("Command not found", "COMMAND_ID_ERROR", CRestServer::STATUS_WRONG_REQUEST);
6410 }
6411 if ($commands[$arParams['COMMAND_ID']]['APP_ID'] != $clientId)
6412 {
6413 throw new Bitrix\Rest\RestException("Command was installed by another rest application", "APP_ID_ERROR", CRestServer::STATUS_WRONG_REQUEST);
6414 }
6415 }
6416 else if (isset($arParams['COMMAND']))
6417 {
6418 $commandFound = false;
6419 foreach ($commands as $command)
6420 {
6421 if ($command['APP_ID'] == $clientId && $command['COMMAND'] == $arParams['COMMAND'])
6422 {
6423 $commandFound = true;
6424 $arParams['COMMAND_ID'] = $command['COMMAND_ID'];
6425 break;
6426 }
6427 }
6428 if (!$commandFound)
6429 {
6430 throw new Bitrix\Rest\RestException("Command not found", "COMMAND_ID_ERROR", CRestServer::STATUS_WRONG_REQUEST);
6431 }
6432 }
6433 $botId = intval($commands[$arParams['COMMAND_ID']]['BOT_ID']);
6434
6435 $arMessageFields = Array();
6436
6437 $arParams['MESSAGE_ID'] = intval($arParams['MESSAGE_ID']);
6438 if ($arParams['MESSAGE_ID'] <= 0)
6439 {
6440 throw new Bitrix\Rest\RestException("Message ID can't be empty", "MESSAGE_ID_EMPTY", CRestServer::STATUS_WRONG_REQUEST);
6441 }
6442
6443 $arMessageFields['MESSAGE'] = trim($arParams['MESSAGE']);
6444 if ($arMessageFields['MESSAGE'] == '')
6445 {
6446 throw new Bitrix\Rest\RestException("Message can't be empty", "MESSAGE_EMPTY", CRestServer::STATUS_WRONG_REQUEST);
6447 }
6448
6449 $attach = CIMMessageParamAttach::GetAttachByJson($arParams['ATTACH']);
6450 if ($attach)
6451 {
6452 if ($attach->IsAllowSize())
6453 {
6454 $arMessageFields['ATTACH'] = $attach;
6455 }
6456 else
6457 {
6458 throw new Bitrix\Rest\RestException("You have exceeded the maximum allowable size of attach", "ATTACH_OVERSIZE", CRestServer::STATUS_WRONG_REQUEST);
6459 }
6460 }
6461 else if ($arParams['ATTACH'])
6462 {
6463 throw new Bitrix\Rest\RestException("Incorrect attach params", "ATTACH_ERROR", CRestServer::STATUS_WRONG_REQUEST);
6464 }
6465
6466 if (isset($arParams['KEYBOARD']) && !empty($arParams['KEYBOARD']) && $botId > 0)
6467 {
6468 $keyboard = Array();
6469 if (is_string($arParams['KEYBOARD']))
6470 {
6471 $arParams['KEYBOARD'] = \CUtil::JsObjectToPhp($arParams['KEYBOARD']);
6472 }
6473 if (!isset($arParams['KEYBOARD']['BUTTONS']))
6474 {
6475 $keyboard['BUTTONS'] = $arParams['KEYBOARD'];
6476 }
6477 else
6478 {
6479 $keyboard = $arParams['KEYBOARD'];
6480 }
6481 $keyboard['BOT_ID'] = $botId;
6482
6483 $keyboard = \Bitrix\Im\Bot\Keyboard::getKeyboardByJson($keyboard);
6484 if ($keyboard)
6485 {
6486 if ($keyboard->isAllowSize())
6487 {
6488 $arMessageFields['KEYBOARD'] = $keyboard;
6489 }
6490 else
6491 {
6492 throw new Bitrix\Rest\RestException("You have exceeded the maximum allowable size of keyboard", "KEYBOARD_OVERSIZE", CRestServer::STATUS_WRONG_REQUEST);
6493 }
6494 }
6495 else
6496 {
6497 throw new Bitrix\Rest\RestException("Incorrect keyboard params", "KEYBOARD_ERROR", CRestServer::STATUS_WRONG_REQUEST);
6498 }
6499 }
6500
6501 if (isset($arParams['MENU']) && !empty($arParams['MENU']))
6502 {
6503 $menu = Array();
6504 if (is_string($arParams['MENU']))
6505 {
6506 $arParams['MENU'] = \CUtil::JsObjectToPhp($arParams['MENU']);
6507 }
6508 if (!isset($arParams['MENU']['ITEMS']))
6509 {
6510 $menu['ITEMS'] = $arParams['MENU'];
6511 }
6512 else
6513 {
6514 $menu = $arParams['MENU'];
6515 }
6516 $menu['BOT_ID'] = $arParams['BOT_ID'];
6517
6519 if ($menu)
6520 {
6521 $arMessageFields['MENU'] = $menu;
6522 }
6523 else
6524 {
6525 throw new Bitrix\Rest\RestException("Incorrect menu params", "MENU_ERROR", CRestServer::STATUS_WRONG_REQUEST);
6526 }
6527 }
6528
6529 if (isset($arParams['SYSTEM']) && $arParams['SYSTEM'] == 'Y')
6530 {
6531 $arMessageFields['SYSTEM'] = 'Y';
6532 }
6533
6534 if (isset($arParams['URL_PREVIEW']) && $arParams['URL_PREVIEW'] == 'N')
6535 {
6536 $arMessageFields['URL_PREVIEW'] = 'N';
6537 }
6538
6540 'MESSAGE_ID' => $arParams['MESSAGE_ID'],
6541 'COMMAND_ID' => $arParams['COMMAND_ID']
6542 ), $arMessageFields);
6543 if (!$id)
6544 {
6545 throw new Bitrix\Rest\RestException("Message isn't added", "WRONG_REQUEST", CRestServer::STATUS_WRONG_REQUEST);
6546 }
6547
6548 return $id;
6549 }
6550
6551
6552
6553 public static function appRegister($arParams, $n, CRestServer $server)
6554 {
6555 if ($server->getAuthType() == \Bitrix\Rest\SessionAuth\Auth::AUTH_TYPE)
6556 {
6557 throw new \Bitrix\Rest\RestException("Access for this method not allowed by session authorization.", "WRONG_AUTH_TYPE", \CRestServer::STATUS_FORBIDDEN);
6558 }
6559 $arParams = array_change_key_case($arParams, CASE_UPPER);
6560
6561 $clientId = $server->getClientId();
6562 if (!$clientId)
6563 {
6564 if (!empty($arParams['CLIENT_ID']))
6565 {
6566 $clientId = 'custom'.$arParams['CLIENT_ID'];
6567 }
6568 else
6569 {
6570 throw new \Bitrix\Rest\AccessException("Client ID not specified");
6571 }
6572 }
6573
6574 if (!isset($arParams['CODE']) || empty($arParams['CODE']))
6575 {
6576 throw new Bitrix\Rest\RestException("App code isn't specified", "CODE_ERROR", CRestServer::STATUS_WRONG_REQUEST);
6577 }
6578
6579 $iframe = '';
6580 $iframeWidth = 0;
6581 $iframeHeight = 0;
6582 $iframePopup = 'N';
6583 $hash = '';
6584
6585 $js = '';
6586 if (
6587 isset($arParams['JS_METHOD']) && in_array($arParams['JS_METHOD'], Array('PUT', 'SEND', 'CALL', 'SUPPORT')) &&
6588 isset($arParams['JS_PARAM']) && !empty($arParams['JS_PARAM'])
6589 )
6590 {
6591 if ($arParams['JS_METHOD'] == 'SEND')
6592 {
6593 if (preg_match('/\/([a-zA-Z0-9\-\_\+]+)((\s)?([a-zA-Z0-9\-\_\+]+))+/im', $arParams['JS_PARAM'], $matches))
6594 {
6595 $js = "BXIM.sendMessage('".$matches[0]."');";
6596 }
6597 }
6598 else if ($arParams['JS_METHOD'] == 'PUT')
6599 {
6600 if (preg_match('/\/([a-zA-Z0-9\-\_\+]+)((\s)?([a-zA-Z0-9\-\_\+]+))+/im', $arParams['JS_PARAM'], $matches))
6601 {
6602 $js = "BXIM.putMessage('".$matches[0]."');";
6603 }
6604 }
6605 else if ($arParams['JS_METHOD'] == 'CALL')
6606 {
6607 if (preg_match('/\+?[ \-\d+\‍(\‍)\#]+$/im', $arParams['JS_PARAM'], $matches))
6608 {
6609 $js = "BXIM.phoneTo('".$matches[0]."');";
6610 }
6611 }
6612 else if ($arParams['JS_METHOD'] == 'SUPPORT')
6613 {
6614 if (preg_match('/[a-f0-9]{32}$/im', $arParams['JS_PARAM'], $matches))
6615 {
6616 $js = "BXIM.openMessenger('networkLines".$matches[0]."');";
6617 }
6618 }
6619 }
6620 else if (isset($arParams['IFRAME']) && !empty($arParams['IFRAME']))
6621 {
6622 $check = parse_url($arParams['IFRAME']);
6623 if (!isset($check['scheme']) && !isset($check['host']))
6624 {
6625 throw new Bitrix\Rest\RestException("Iframe params must be HTTPS site", "IFRAME_HTTPS", CRestServer::STATUS_WRONG_REQUEST);
6626 }
6627 else if ($check['scheme'] != 'https' || empty($check['host']))
6628 {
6629 throw new Bitrix\Rest\RestException("Iframe params must be HTTPS site", "IFRAME_HTTPS", CRestServer::STATUS_WRONG_REQUEST);
6630 }
6631 $iframe = $arParams['IFRAME'];
6632 $iframeWidth = 320;
6633 if (isset($arParams['IFRAME_WIDTH']))
6634 {
6635 $iframeWidth = intval($arParams['IFRAME_WIDTH']) > 250? $arParams['IFRAME_WIDTH']: 250;
6636 }
6637 $iframeHeight = 250;
6638 if (isset($arParams['IFRAME_HEIGHT']))
6639 {
6640 $iframeHeight = intval($arParams['IFRAME_HEIGHT']) > 50? $arParams['IFRAME_HEIGHT']: 50;
6641 }
6642 $iframePopup = isset($arParams['IFRAME_POPUP']) && $arParams['IFRAME_POPUP'] == 'Y'? 'Y': 'N';
6643
6644 if (!isset($arParams['HASH']) || empty($arParams['HASH']))
6645 {
6646 throw new Bitrix\Rest\RestException("Hash can't be empty", "HASH_ERROR", CRestServer::STATUS_WRONG_REQUEST);
6647 }
6648 $hash = mb_substr($arParams['HASH'], 0, 32);
6649 }
6650
6651 if (!$iframe && !$js)
6652 {
6653 throw new Bitrix\Rest\RestException("Iframe or JS method isn't specified", "PARAMS_ERROR", CRestServer::STATUS_WRONG_REQUEST);
6654 }
6655
6656 $iconId = 0;
6657 if (isset($arParams['ICON_FILE']) && $arParams['ICON_FILE'])
6658 {
6659 $iconFile = \CRestUtil::saveFile($arParams['ICON_FILE']);
6660 $imageCheck = (new \Bitrix\Main\File\Image($iconFile["tmp_name"]))->getInfo();
6661 if(
6662 !$imageCheck
6663 || !$imageCheck->getWidth()
6664 || $imageCheck->getWidth() > 5000
6665 || !$imageCheck->getHeight()
6666 || $imageCheck->getHeight() > 5000
6667 )
6668 {
6669 $iconFile = null;
6670 }
6671 if ($iconFile && mb_strpos($iconFile['type'], "image/") === 0)
6672 {
6673 $iconFile['MODULE_ID'] = 'imbot';
6674 $iconId = \CFile::saveFile($iconFile, 'imbot');
6675 }
6676 }
6677
6678
6679 $context = isset($arParams['CONTEXT'])? $arParams['CONTEXT']: 'ALL';
6680 $hidden = isset($arParams['HIDDEN']) && $arParams['HIDDEN'] == 'Y'? 'Y': 'N';
6681 $extranetSupport = isset($arParams['EXTRANET_SUPPORT']) && $arParams['EXTRANET_SUPPORT'] == 'Y'? 'Y': 'N';
6682 $livechatSupport = isset($arParams['LIVECHAT_SUPPORT']) && $arParams['LIVECHAT_SUPPORT'] == 'Y'? 'Y': 'N';
6683
6684 $arParams['BOT_ID'] = intval($arParams['BOT_ID']);
6685 if ($arParams['BOT_ID'] > 0)
6686 {
6687 $bots = \Bitrix\Im\Bot::getListCache();
6688 if (!isset($bots[$arParams['BOT_ID']]))
6689 {
6690 throw new Bitrix\Rest\RestException("Bot not found", "BOT_ID_ERROR", CRestServer::STATUS_WRONG_REQUEST);
6691 }
6692 if ($bots[$arParams['BOT_ID']]['APP_ID'] != $clientId)
6693 {
6694 throw new Bitrix\Rest\RestException("Bot was installed by another rest application", "APP_ID_ERROR", CRestServer::STATUS_WRONG_REQUEST);
6695 }
6696 }
6697 else
6698 {
6699 throw new Bitrix\Rest\RestException("Bot not found", "BOT_ID_ERROR", CRestServer::STATUS_WRONG_REQUEST);
6700 }
6701
6702 if (!isset($arParams['LANG']) || empty($arParams['LANG']))
6703 {
6704 throw new Bitrix\Rest\RestException("Lang set can't be empty", "LANG_ERROR", CRestServer::STATUS_WRONG_REQUEST);
6705 }
6706
6707 $id = \Bitrix\Im\App::register(Array(
6708 'APP_ID' => $clientId,
6709 'BOT_ID' => $arParams['BOT_ID'],
6710 'CODE' => $arParams['CODE'],
6711 'ICON_ID' => $iconId,
6712 'HASH' => $hash,
6713 'CONTEXT' => $context,
6714 'HIDDEN' => $hidden,
6715 'REGISTERED' => 'Y',
6716 'JS' => $js,
6717 'IFRAME' => $iframe,
6718 'IFRAME_HEIGHT' => $iframeHeight,
6719 'IFRAME_WIDTH' => $iframeWidth,
6720 'IFRAME_POPUP' => $iframePopup,
6721 'EXTRANET_SUPPORT' => $extranetSupport,
6722 'LIVECHAT_SUPPORT' => $livechatSupport,
6723 'MODULE_ID' => 'rest',
6724 'LANG' => $arParams['LANG'],
6725 ));
6726 if (!$id)
6727 {
6728 throw new Bitrix\Rest\RestException("App can't be registered".\var_export(Array(
6729 'APP_ID' => $clientId,
6730 'BOT_ID' => $arParams['BOT_ID'],
6731 'CODE' => $arParams['CODE'],
6732 'ICON_ID' => $iconId,
6733 'HASH' => $hash,
6734 'CONTEXT' => $context,
6735 'HIDDEN' => $hidden,
6736 'JS' => $js,
6737 'IFRAME' => $iframe,
6738 'IFRAME_HEIGHT' => $iframeHeight,
6739 'IFRAME_WIDTH' => $iframeWidth,
6740 'IFRAME_POPUP' => $iframePopup,
6741 'EXTRANET_SUPPORT' => $extranetSupport,
6742 'LIVECHAT_SUPPORT' => $livechatSupport,
6743 'MODULE_ID' => 'rest',
6744 'LANG' => $arParams['LANG'],
6745 ),1), "WRONG_REQUEST", CRestServer::STATUS_WRONG_REQUEST);
6746 }
6747
6748 return $id;
6749 }
6750
6751 public static function appUnRegister($arParams, $n, CRestServer $server)
6752 {
6753 if ($server->getAuthType() == \Bitrix\Rest\SessionAuth\Auth::AUTH_TYPE)
6754 {
6755 throw new \Bitrix\Rest\RestException("Access for this method not allowed by session authorization.", "WRONG_AUTH_TYPE", \CRestServer::STATUS_FORBIDDEN);
6756 }
6757 $arParams = array_change_key_case($arParams, CASE_UPPER);
6758
6759 $clientId = $server->getClientId();
6760 if (!$clientId)
6761 {
6762 if (!empty($arParams['CLIENT_ID']))
6763 {
6764 $clientId = 'custom'.$arParams['CLIENT_ID'];
6765 }
6766 else
6767 {
6768 throw new \Bitrix\Rest\AccessException("Client ID not specified");
6769 }
6770 }
6771
6773 if (!isset($apps[$arParams['APP_ID']]))
6774 {
6775 throw new Bitrix\Rest\RestException("App not found", "CHAT_APP_ID_ERROR", CRestServer::STATUS_WRONG_REQUEST);
6776 }
6777 if ($apps[$arParams['APP_ID']]['APP_ID'] != $clientId)
6778 {
6779 throw new Bitrix\Rest\RestException("App was installed by another rest application", "APP_ID_ERROR", CRestServer::STATUS_WRONG_REQUEST);
6780 }
6781
6782 $result = \Bitrix\Im\App::unRegister(Array('ID' => $arParams['APP_ID']));
6783 if (!$result)
6784 {
6785 throw new Bitrix\Rest\RestException("App can't be deleted", "WRONG_REQUEST", CRestServer::STATUS_WRONG_REQUEST);
6786 }
6787
6788 return true;
6789 }
6790
6791 public static function appUpdate($arParams, $n, CRestServer $server)
6792 {
6793 if ($server->getAuthType() == \Bitrix\Rest\SessionAuth\Auth::AUTH_TYPE)
6794 {
6795 throw new \Bitrix\Rest\RestException("Access for this method not allowed by session authorization.", "WRONG_AUTH_TYPE", \CRestServer::STATUS_FORBIDDEN);
6796 }
6797 $arParams = array_change_key_case($arParams, CASE_UPPER);
6798
6799 $clientId = $server->getClientId();
6800 if (!$clientId)
6801 {
6802 if (!empty($arParams['CLIENT_ID']))
6803 {
6804 $clientId = 'custom'.$arParams['CLIENT_ID'];
6805 }
6806 else
6807 {
6808 throw new \Bitrix\Rest\AccessException("Client ID not specified");
6809 }
6810 }
6811
6813 if (!isset($apps[$arParams['APP_ID']]))
6814 {
6815 throw new Bitrix\Rest\RestException("App not found", "CHAT_APP_ID_ERROR", CRestServer::STATUS_WRONG_REQUEST);
6816 }
6817 if ($apps[$arParams['APP_ID']]['APP_ID'] != $clientId)
6818 {
6819 throw new Bitrix\Rest\RestException("App was installed by another rest application", "APP_ID_ERROR", CRestServer::STATUS_WRONG_REQUEST);
6820 }
6821
6822 $updateFields = Array();
6823
6824 if (isset($arParams['FIELDS']['CONTEXT']) && !empty($arParams['FIELDS']['CONTEXT']))
6825 {
6826 $updateFields['CONTEXT'] = $arParams['FIELDS']['CONTEXT'];
6827 }
6828 if (isset($arParams['FIELDS']['HASH']) && !empty($arParams['FIELDS']['HASH']))
6829 {
6830 $updateFields['HASH'] = $arParams['FIELDS']['HASH'];
6831 }
6832
6833 if (
6834 isset($arParams['FIELDS']['JS_METHOD']) && in_array($arParams['FIELDS']['JS_METHOD'], Array('PUT', 'SEND', 'CALL', 'SUPPORT')) &&
6835 isset($arParams['FIELDS']['JS_PARAM']) && !empty($arParams['FIELDS']['JS_PARAM'])
6836 )
6837 {
6838 if ($arParams['FIELDS']['JS_METHOD'] == 'SEND')
6839 {
6840 if (preg_match('/\/([a-zA-Z0-9\-\_\+]+)((\s)?([a-zA-Z0-9\-\_\+]+))+/im', $arParams['FIELDS']['JS_PARAM'], $matches))
6841 {
6842 $updateFields['JS'] = "BXIM.sendMessage('".$matches[0]."');";
6843 }
6844 }
6845 else if ($arParams['FIELDS']['JS_METHOD'] == 'PUT')
6846 {
6847 if (preg_match('/\/([a-zA-Z0-9\-\_\+]+)((\s)?([a-zA-Z0-9\-\_\+]+))+/im', $arParams['FIELDS']['JS_PARAM'], $matches))
6848 {
6849 $updateFields['JS'] = "BXIM.putMessage('".$matches[0]."');";
6850 }
6851 }
6852 else if ($arParams['FIELDS']['JS_METHOD'] == 'CALL')
6853 {
6854 if (preg_match('/\+?[ \-\d+\‍(\‍)\#]+$/im', $arParams['FIELDS']['JS_PARAM'], $matches))
6855 {
6856 $updateFields['JS'] = "BXIM.phoneTo('".$matches[0]."');";
6857 }
6858 }
6859 else if ($arParams['FIELDS']['JS_METHOD'] == 'SUPPORT')
6860 {
6861 if (preg_match('/[a-f0-9]{32}$/im', $arParams['FIELDS']['JS_PARAM'], $matches))
6862 {
6863 $updateFields['JS'] = "BXIM.openMessenger('networkLines".$matches[0]."');";
6864 }
6865 }
6866 if (isset($updateFields['JS']))
6867 {
6868 $updateFields['IFRAME'] = '';
6869 }
6870 }
6871 else if (isset($arParams['FIELDS']['IFRAME']) && !empty($arParams['FIELDS']['IFRAME']))
6872 {
6873 $check = parse_url($arParams['FIELDS']['IFRAME']);
6874 if (!isset($check['scheme']) && !isset($check['host']))
6875 {
6876 throw new Bitrix\Rest\RestException("Iframe params must be HTTPS site", "IFRAME_HTTPS", CRestServer::STATUS_WRONG_REQUEST);
6877 }
6878 else if ($check['scheme'] != 'https' || empty($check['host']))
6879 {
6880 throw new Bitrix\Rest\RestException("Iframe params must be HTTPS site", "IFRAME_HTTPS", CRestServer::STATUS_WRONG_REQUEST);
6881 }
6882 $updateFields['IFRAME'] = $arParams['FIELDS']['IFRAME'];
6883 $updateFields['JS'] = '';
6884 }
6885
6886 if (isset($arParams['FIELDS']['IFRAME_WIDTH']))
6887 {
6888 $updateFields['IFRAME_WIDTH'] = intval($arParams['FIELDS']['IFRAME_WIDTH']);
6889 }
6890 if (isset($arParams['FIELDS']['IFRAME_HEIGHT']))
6891 {
6892 $updateFields['IFRAME_HEIGHT'] = intval($arParams['FIELDS']['IFRAME_HEIGHT']);
6893 }
6894 if (isset($arParams['FIELDS']['IFRAME_POPUP']) && !empty($arParams['FIELDS']['IFRAME_POPUP']))
6895 {
6896 $updateFields['IFRAME_POPUP'] = $arParams['FIELDS']['IFRAME_POPUP'] == 'Y'? 'Y': 'N';
6897 }
6898
6899 if (isset($arParams['FIELDS']['HIDDEN']) && !empty($arParams['FIELDS']['HIDDEN']))
6900 {
6901 $updateFields['HIDDEN'] = $arParams['FIELDS']['HIDDEN'] == 'Y'? 'Y': 'N';
6902 }
6903
6904 if (isset($arParams['FIELDS']['EXTRANET_SUPPORT']) && !empty($arParams['FIELDS']['EXTRANET_SUPPORT']))
6905 {
6906 $updateFields['EXTRANET_SUPPORT'] = $arParams['FIELDS']['EXTRANET_SUPPORT'] == 'Y'? 'Y': 'N';
6907 }
6908
6909 if (isset($arParams['FIELDS']['LIVECHAT_SUPPORT']) && !empty($arParams['FIELDS']['LIVECHAT_SUPPORT']))
6910 {
6911 $updateFields['LIVECHAT_SUPPORT'] = $arParams['FIELDS']['LIVECHAT_SUPPORT'] == 'Y'? 'Y': 'N';
6912 }
6913
6914 if (isset($arParams['FIELDS']['LANG']) && !empty($arParams['FIELDS']['LANG']))
6915 {
6916 $updateFields['LANG'] = $arParams['FIELDS']['LANG'];
6917 }
6918
6919 if (isset($arParams['FIELDS']['ICON_FILE']))
6920 {
6921 $iconFile = \CRestUtil::saveFile($arParams['FIELDS']['ICON_FILE']);
6922 $imageCheck = (new \Bitrix\Main\File\Image($iconFile["tmp_name"]))->getInfo();
6923 if(
6924 !$imageCheck
6925 || !$imageCheck->getWidth()
6926 || $imageCheck->getWidth() > 5000
6927 || !$imageCheck->getHeight()
6928 || $imageCheck->getHeight() > 5000
6929 )
6930 {
6931 $iconFile = null;
6932 }
6933 if ($iconFile && mb_strpos($iconFile['type'], "image/") === 0)
6934 {
6935 $iconFile['MODULE_ID'] = 'imbot';
6936 $updateFields['ICON_FILE_ID'] = \CFile::saveFile($iconFile, 'imbot');
6937 }
6938 }
6939
6940 if (!empty($updateFields))
6941 {
6942 $result = \Bitrix\Im\App::update(Array('ID' => $arParams['APP_ID']), $updateFields);
6943 if (!$result)
6944 {
6945 throw new Bitrix\Rest\RestException("Command can't be updated", "WRONG_REQUEST", CRestServer::STATUS_WRONG_REQUEST);
6946 }
6947 }
6948
6949 return true;
6950 }
6951
6952
6953
6954 private static function getAccessToken($appId, $userId)
6955 {
6957 if(!$session)
6958 {
6959 return Array();
6960 }
6961 $auth = \Bitrix\Rest\Event\Sender::getAuth(
6962 $appId,
6963 $userId,
6964 array('EVENT_SESSION' => $session),
6965 [
6966 'sendRefreshToken' => 1,
6967 'sendAuth' => 1
6968 ]
6969 );
6970 return $auth? $auth: Array();
6971 }
6972
6973 private static function bindEvent($appId, $appCode, $bitrixEventModule, $bitrixEventName, $restEventName, $restEventHandler)
6974 {
6975 $res = \Bitrix\Rest\EventTable::getList(array(
6976 'filter' => array(
6977 '=EVENT_NAME' => mb_strtoupper($restEventName),
6978 '=APPLICATION_TOKEN' => $appCode,
6979 '=APP_ID' => $appId,
6980 ),
6981 'select' => array('ID')
6982 ));
6983
6984 if ($handler = $res->fetch())
6985 {
6986 return true;
6987 }
6988
6989 $updateFields = [
6990 'APP_ID' => $appId,
6991 'EVENT_NAME' => mb_strtoupper($restEventName),
6992 'EVENT_HANDLER' => $restEventHandler,
6993 'APPLICATION_TOKEN' => $appCode,
6994 ];
6995 $insertFields = [
6996 ...$updateFields,
6997 'USER_ID' => 0,
6998 ];
6999
7000 \Bitrix\Rest\EventTable::merge($insertFields, $updateFields);
7001 \Bitrix\Rest\Event\Sender::bind($bitrixEventModule, $bitrixEventName);
7002
7003 return true;
7004 }
7005
7006 private static function unbindEvent($appId, $appCode, $bitrixEventModule, $bitrixEventName, $restEventName, $skipCheck = false)
7007 {
7008 if (!$skipCheck)
7009 {
7010 $res = \Bitrix\Im\Model\BotTable::getList(array(
7011 'filter' => array(
7012 '=APP_ID' => $appCode,
7013 ),
7014 'select' => array('BOT_ID')
7015 ));
7016 if ($handler = $res->fetch())
7017 {
7018 return false;
7019 }
7020 }
7021
7022 $res = \Bitrix\Rest\EventTable::getList(array(
7023 'filter' => array(
7024 '=EVENT_NAME' => mb_strtoupper($restEventName),
7025 '=APP_ID' => $appId,
7026 '=APPLICATION_TOKEN' => $appCode,
7027 ),
7028 'select' => array('ID', 'EVENT_HANDLER')
7029 ));
7030 while($handler = $res->fetch())
7031 {
7032 \Bitrix\Rest\EventTable::delete($handler['ID']);
7033 }
7034
7035 return true;
7036 }
7037
7038 public static function mobileConfigGet($params, $n, \CRestServer $server)
7039 {
7040 if (
7041 $server->getAuthType() != \Bitrix\Rest\SessionAuth\Auth::AUTH_TYPE
7042 && !self::isDebugEnabled()
7043 )
7044 {
7045 throw new \Bitrix\Rest\RestException("Get access to browser const available only for session authorization.", "WRONG_AUTH_TYPE", \CRestServer::STATUS_FORBIDDEN);
7046
7047 }
7048
7049 $config = Array();
7050
7052 $config['SETTINGS'] = $settings['settings'];
7053
7054 $userId = $GLOBALS['USER']->GetID();
7055 if (!isset($config['CONTACT_LIST']['users'][$userId]))
7056 {
7057 $arUsers = CIMContactList::GetUserData(array(
7058 'ID' => $userId,
7059 'DEPARTMENT' => 'N',
7060 'USE_CACHE' => 'Y',
7061 'SHOW_ONLINE' => 'N'
7062 ));
7063 $config['CONTACT_LIST']['users'][$userId] = $arUsers['users'][$userId];
7064 }
7065
7066 $config["ACTION"] = 'DIALOG';
7067 $config["PATH_TO_USER_PROFILE"] = SITE_DIR.'mobile/users/?user_id='.$userId.'&FROM_DIALOG=Y';
7068 $config["PATH_TO_USER_PROFILE_TEMPLATE"] = SITE_DIR.'mobile/users/?user_id=#user_id#&FROM_DIALOG=Y';
7069
7070 $config['WEBRTC_MOBILE_SUPPORT'] = \Bitrix\Main\Loader::includeModule('mobileapp')? \Bitrix\MobileApp\Mobile::getInstance()->isWebRtcSupported(): false;
7071
7072 return \CIMMessenger::GetMobileDialogTemplateJS([], $config);
7073 }
7074
7075 public static function callUserRegister($params, $n, \CRestServer $server)
7076 {
7077 global $APPLICATION;
7078
7079 if ($server->getAuthType() !== 'call')
7080 {
7081 throw new \Bitrix\Rest\RestException("Access for this method allowed only by call authorization.", "WRONG_AUTH_TYPE", \CRestServer::STATUS_FORBIDDEN);
7082 }
7083
7084 $params = array_change_key_case($params, CASE_UPPER);
7085
7086 //1. check session info $_SESSION['LIVECHAT']['REGISTER'] - already registered?
7087 if (
7088 isset($_SESSION['CALL']['REGISTER'])
7089 && $_SESSION['CALL']['REGISTER']
7090 &&
7091 !(
7092 isset($params['USER_HASH'])
7093 && trim($params['USER_HASH'])
7094 && preg_match("/^[a-fA-F0-9]{32}$/i", $params['USER_HASH'])
7095 )
7096 )
7097 {
7098 $params['USER_HASH'] = $_SESSION['CALL']['REGISTER']['hash'];
7099 }
7100
7101 //2. register user
7102 $userData = \Bitrix\Im\Call\User::register([
7103 'NAME' => $params['NAME'] ?? '',
7104 'LAST_NAME' => $params['LAST_NAME'] ?? '',
7105 'AVATAR' => $params['AVATAR'] ?? '',
7106 'EMAIL' => $params['EMAIL'] ?? '',
7107 'PERSONAL_WWW' => $params['WWW'] ?? '',
7108 'PERSONAL_GENDER' => $params['GENDER'] ?? '',
7109 'WORK_POSITION' => $params['POSITION'] ?? '',
7110 'USER_HASH' => $params['USER_HASH'] ?? '',
7111 ]);
7112 if (!$userData)
7113 {
7114 throw new \Bitrix\Rest\RestException(
7115 \Bitrix\Im\Call\User::getError()->msg,
7116 \Bitrix\Im\Call\User::getError()->code,
7117 \CRestServer::STATUS_WRONG_REQUEST
7118 );
7119 }
7120
7121 $aliasData = \Bitrix\Im\Alias::get($params['ALIAS']);
7122 if (!$aliasData)
7123 {
7124 throw new \Bitrix\Rest\RestException("Wrong alias.", "WRONG_ALIAS", \CRestServer::STATUS_FORBIDDEN);
7125 }
7126
7127 //3. authorize
7128 \Bitrix\Im\Call\Auth::authorizeById($userData['ID'], true, true);
7129
7130 //4. add to dialog
7131 $chat = new CIMChat(0);
7132 $chat->AddUser(
7133 chatId: $aliasData['ENTITY_ID'],
7134 userId: $userData['ID'],
7135 hideHistory: null,
7136 skipMessage: true,
7137 skipRecent: true
7138 );
7139 if ($exception = $APPLICATION->GetException())
7140 {
7141 if ($exception->GetID() !== 'NOTHING_TO_ADD')
7142 {
7143 throw new Bitrix\Rest\RestException(
7144 "You don't have access",
7145 "WRONG_REQUEST",
7146 CRestServer::STATUS_WRONG_REQUEST
7147 );
7148 }
7149 }
7150
7152 //5. return id and hash
7153 $result = [
7154 'id' => (int)$userData['ID'],
7155 'hash' => $userData['HASH'],
7156 'created' => $userData['CREATED'],
7157 'userToken' => \Bitrix\Call\JwtCall::getUserJwt(),
7158 ];
7159
7160 $_SESSION['CALL']['REGISTER'] = $result;
7161
7162 //6. send notification to chat owner
7163 $chatData = CIMChat::GetChatData(['ID' => $aliasData['ENTITY_ID']]);
7164 $chatTitle = $chatData['chat'][$aliasData['ENTITY_ID']]['name'];
7165 $chatOwnerId = $chatData['chat'][$aliasData['ENTITY_ID']]['owner'];
7166
7167 $publicLink = $aliasData['LINK'];
7168 CIMNotify::Add(
7169 [
7170 'TO_USER_ID' => $chatOwnerId,
7171 'MESSAGE' => fn (?string $languageId = null) => Loc::getMessage(
7172 "IM_VIDEOCONF_NEW_GUEST",
7173 ['#CHAT_TITLE#' => $chatTitle],
7174 $languageId
7175 ) . "[br]" . "<a href='{$publicLink}'>" . Loc::getMessage("IM_VIDEOCONF_JOIN_LINK", null, $languageId) . "</a>",
7176 ]
7177 );
7178
7179 return $result;
7180 }
7181
7182 public static function callUserUpdate($params, $n, \CRestServer $server)
7183 {
7184 if ($server->getAuthType() !== 'call')
7185 {
7186 throw new \Bitrix\Rest\RestException(
7187 "Access for this method allowed only by call authorization.",
7188 "WRONG_AUTH_TYPE",
7189 \CRestServer::STATUS_FORBIDDEN
7190 );
7191 }
7192
7193 $params = array_change_key_case($params, CASE_UPPER);
7194 if (empty($params['NAME']))
7195 {
7196 throw new Bitrix\Rest\RestException("User NAME can't be empty", "USER_NAME_EMPTY", CRestServer::STATUS_WRONG_REQUEST);
7197 }
7198
7200 global $USER;
7201
7202 if ($USER->GetParam("NAME") == $params['NAME'])
7203 {
7204 return;
7205 }
7206
7207 $userManager = new \CUser;
7208 $userManager->Update($USER->GetID(), [
7209 'NAME' => $params['NAME']
7210 ]);
7211
7212 $relations = \Bitrix\Im\Chat::getRelation($params['CHAT_ID'], ['WITHOUT_COUNTERS' => 'Y']);
7213
7214 if (\CModule::IncludeModule("pull"))
7215 {
7216 \Bitrix\Pull\Event::add(array_keys($relations), [
7217 'module_id' => 'im',
7218 'command' => 'callUserNameUpdate',
7219 'params' => [
7220 'userId' => $USER->GetID(),
7221 'name' => $params['NAME']
7222 ],
7223 'extra' => \Bitrix\Im\Common::getPullExtra()
7224 ]);
7225 }
7226 }
7227
7228 public static function callUserForceRename($params, $n, \CRestServer $server)
7229 {
7230 global $USER;
7231
7232 $params = array_change_key_case($params, CASE_UPPER);
7233 $params['CHAT_ID'] = (int)$params['CHAT_ID'];
7234 $params['USER_ID'] = (int)$params['USER_ID'];
7235
7236 if ($params['CHAT_ID'] <= 0)
7237 {
7238 throw new Bitrix\Rest\RestException("Chat ID can't be empty", "CHAT_ID_EMPTY", CRestServer::STATUS_WRONG_REQUEST);
7239 }
7240 if ($params['USER_ID'] <= 0)
7241 {
7242 throw new Bitrix\Rest\RestException("User ID can't be empty", "USER_ID_EMPTY", CRestServer::STATUS_WRONG_REQUEST);
7243 }
7244
7245 //check if current user if owner of chat
7246 $chat = \Bitrix\Im\Model\ChatTable::getRowById($params['CHAT_ID']);
7247 if (!$chat)
7248 {
7249 throw new Bitrix\Rest\RestException("Chat was not found", "CHAT_NOT_FOUND", CRestServer::STATUS_WRONG_REQUEST);
7250 }
7251 $owner = (int)$chat['AUTHOR_ID'];
7252 if ((int)$USER->GetID() !== $owner)
7253 {
7254 throw new Bitrix\Rest\RestException("You cannot perform this operation", "NO_ACCESS", CRestServer::STATUS_WRONG_REQUEST);
7255 }
7256
7257 //check if renamed user is call auth
7258 $userToRename = \Bitrix\Im\User::getInstance($params['USER_ID']);
7259 if (!$userToRename)
7260 {
7261 throw new Bitrix\Rest\RestException("User was not found", "USER_NOT_FOUND", CRestServer::STATUS_WRONG_REQUEST);
7262 }
7263 $externalAuth = $userToRename->getExternalAuthId();
7264 if ($externalAuth !== 'call')
7265 {
7266 throw new Bitrix\Rest\RestException("You cannot rename this user", "WRONG_USER_AUTH_TYPE", CRestServer::STATUS_WRONG_REQUEST);
7267 }
7268
7269 $userManager = new \CUser;
7270 $userManager->Update($params['USER_ID'], [
7271 'NAME' => $params['NAME']
7272 ]);
7273
7274 $relations = \Bitrix\Im\Chat::getRelation($params['CHAT_ID'], ['WITHOUT_COUNTERS' => 'Y']);
7275
7276 if (\CModule::IncludeModule("pull"))
7277 {
7278 \Bitrix\Pull\Event::add(array_keys($relations), [
7279 'module_id' => 'im',
7280 'command' => 'callUserNameUpdate',
7281 'params' => [
7282 'userId' => $params['USER_ID'],
7283 'name' => $params['NAME']
7284 ],
7285 'extra' => \Bitrix\Im\Common::getPullExtra()
7286 ]);
7287 }
7288 }
7289
7290 public static function callChannelPublicList($params, $n, \CRestServer $server)
7291 {
7292 $params = array_change_key_case($params, CASE_UPPER);
7293
7295 if ($params['APPLICATION'] == 'Y')
7296 {
7297 $clientId = $server->getClientId();
7298 if (!$clientId)
7299 {
7300 throw new \Bitrix\Rest\RestException("Get application public channel available only for application authorization.", "WRONG_AUTH_TYPE", \CRestServer::STATUS_WRONG_REQUEST);
7301 }
7302 $type = $clientId;
7303 }
7304
7305 $users = Array();
7306 if (is_string($params['USERS']))
7307 {
7308 $params['USERS'] = \CUtil::JsObjectToPhp($params['USERS']);
7309 }
7310 if (is_array($params['USERS']))
7311 {
7312 foreach ($params['USERS'] as $userId)
7313 {
7314 $userId = intval($userId);
7315 if ($userId > 0)
7316 {
7317 $users[$userId] = $userId;
7318 }
7319 }
7320 }
7321
7322 if (empty($users))
7323 {
7324 throw new \Bitrix\Rest\RestException("A wrong format for the USERS field is passed", "INVALID_FORMAT", \CRestServer::STATUS_WRONG_REQUEST);
7325 }
7326
7327 $chatId = (int)$params['CALL_CHAT_ID'];
7328
7329 if (!$chatId)
7330 {
7331 throw new \Bitrix\Rest\RestException("No chat id", "INVALID_FORMAT", \CRestServer::STATUS_WRONG_REQUEST);
7332 }
7333
7334 $configParams = Array();
7335 $configParams['TYPE'] = $type;
7336 $configParams['USERS'] = $users;
7337 $configParams['JSON'] = true;
7338
7340 if ($config === false)
7341 {
7342 throw new \Bitrix\Rest\RestException("Push & Pull server is not configured", "SERVER_ERROR", \CRestServer::STATUS_INTERNAL);
7343 }
7344
7345 return $config;
7346 }
7347
7348 public static function videoconfShareChange($params, $n, \CRestServer $server)
7349 {
7350 global $USER;
7351 $userName = $USER->GetFullName();
7352 $params = array_change_key_case($params, CASE_UPPER);
7353
7354 if (!\Bitrix\Im\Common::isDialogId($params['DIALOG_ID']))
7355 {
7356 throw new Bitrix\Rest\RestException("Dialog ID can't be empty", "DIALOG_ID_EMPTY", CRestServer::STATUS_WRONG_REQUEST);
7357 }
7358
7359 //check owner
7360 $chatId = \Bitrix\Im\Dialog::getChatId($params['DIALOG_ID']);
7361 $chatData = \Bitrix\Im\Chat::getById($chatId);
7362
7363 if ($USER->GetID() != $chatData['OWNER'])
7364 {
7365 throw new Bitrix\Rest\RestException("You don't have access to this chat", "ACCESS_ERROR", CRestServer::STATUS_WRONG_REQUEST);
7366 }
7367
7368 //get chat users and delete guests
7369 $chatUsers = \Bitrix\Im\Chat::getUsers($chatId);
7371
7372 $chat = new CIMChat($USER->GetId());
7373 foreach($chatUsers as $user)
7374 {
7375 if (in_array($user['external_auth_id'], $externalTypes, true))
7376 {
7377 $chat->DeleteUser($chatId, $user['id']);
7378 }
7379 }
7380
7381 //get alias
7382 $aliasData = \Bitrix\Im\Alias::getByEntity('VIDEOCONF', $chatId);
7383
7384 //generate new alias and update
7386 $updateResult = \Bitrix\Im\Alias::update($aliasData['ID'], [
7387 'ALIAS' => $newCode,
7388 'ENTITY_TYPE' => 'VIDEOCONF',
7389 'ENTITY_ID' => $chatId
7390 ]);
7391
7392 if (!$updateResult)
7393 {
7394 throw new Bitrix\Rest\RestException("Can't update alias", "ACCESS_ERROR", CRestServer::STATUS_WRONG_REQUEST);
7395 }
7396
7397 $newLink = \Bitrix\Im\Alias::get($newCode)['LINK'];
7398
7399 //add message to chat
7400 $attach = new CIMMessageParamAttach(null);
7401 $attach->AddLink(
7402 [
7403 "NAME" => $newLink,
7404 "DESC" => GetMessage("IM_VIDEOCONF_SHARE_UPDATED_LINK", ['#USER_NAME#' => htmlspecialcharsback($userName)]),
7405 "LINK" => $newLink
7406 ]
7407 );
7408
7409 CIMChat::AddMessage(
7410 [
7411 "TO_CHAT_ID" => $chatId,
7412 "SYSTEM" => 'Y',
7413 "FROM_USER_ID" => $USER->GetID(),
7414 "MESSAGE" => GetMessage("IM_VIDEOCONF_LINK_TITLE"),
7415 "ATTACH" => $attach
7416 ]
7417 );
7418
7419 //send pull with changed alias
7420
7421 $relations = \Bitrix\Im\Chat::getRelation($chatId, ['WITHOUT_COUNTERS' => 'Y']);
7422 if (\CModule::IncludeModule("pull"))
7423 {
7424 \Bitrix\Pull\Event::add(array_keys($relations), [
7425 'module_id' => 'im',
7426 'command' => 'videoconfShareUpdate',
7427 'params' => [
7428 'newCode' => $newCode,
7429 'newLink' => $newLink,
7430 'dialogId' => $params['DIALOG_ID']
7431 ],
7432 'extra' => \Bitrix\Im\Common::getPullExtra()
7433 ]);
7434 }
7435
7436 return true;
7437 }
7438
7439 public static function videoconfPasswordCheck($params, $n, \CRestServer $server)
7440 {
7441 $params = array_change_key_case($params, CASE_UPPER);
7442
7443 if (!$params['PASSWORD'])
7444 {
7445 throw new Bitrix\Rest\RestException("Password can't be empty", "PASSWORD_EMPTY", CRestServer::STATUS_WRONG_REQUEST);
7446 }
7447
7448 if (!$params['ALIAS'])
7449 {
7450 throw new Bitrix\Rest\RestException("Alias can't be empty", "ALIAS_EMPTY", CRestServer::STATUS_WRONG_REQUEST);
7451 }
7452
7453 $conference = \Bitrix\Im\Call\Conference::getByAlias($params['ALIAS']);
7454 if ($conference && $conference->getPassword() === $params['PASSWORD'])
7455 {
7456 //create cache for current confId and sessId
7457 $storage = \Bitrix\Main\Application::getInstance()->getLocalSession('conference_check_' . $conference->getId());
7458 $storage->set('checked', true);
7459
7460 //add user to chat
7461 $currentUserId = \Bitrix\Main\Engine\CurrentUser::get()->getId();
7462 $isUserInChat = Chat::isUserInChat($conference->getChatId());
7463 if ($currentUserId && !$isUserInChat)
7464 {
7465 $chat = new \CIMChat(0);
7466 $addingResult = $chat->AddUser(
7467 chatId: $conference->getChatId(),
7468 userId: $currentUserId,
7469 hideHistory: null,
7470 skipMessage: true,
7471 skipRecent: true
7472 );
7473 if (!$addingResult)
7474 {
7475 throw new Bitrix\Rest\RestException("Error during adding user to chat", "ADDING_TO_CHAT_ERROR", CRestServer::STATUS_WRONG_REQUEST);
7476 }
7477 }
7478
7479 return true;
7480 }
7481
7482 return false;
7483 }
7484
7485 public static function videoconfAdd($arParams, $n, CRestServer $server)
7486 {
7487 throw new \Bitrix\Rest\RestException('This method is not available', 'METHOD_NOT_AVAILABLE', CRestServer::STATUS_WRONG_REQUEST);
7488
7489 $arParams = array_change_key_case($arParams, CASE_UPPER);
7490
7491 if (
7492 \Bitrix\Im\User::getInstance()->isExtranet()
7493 || \Bitrix\Im\User::getInstance()->isBot()
7494 )
7495 {
7496 throw new Bitrix\Rest\RestException("Only intranet users have access to this method.", "ACCESS_ERROR", CRestServer::STATUS_FORBIDDEN);
7497 }
7498
7499 $arParams['BROADCAST_MODE'] = ($arParams['BROADCAST_MODE'] ?? 'N') === 'Y';
7500
7502
7503 if (!$createResult->isSuccess())
7504 {
7505 $error = $createResult->getErrors()[0];
7506 throw new Bitrix\Rest\RestException($error->getMessage(), $error->getCode(), CRestServer::STATUS_WRONG_REQUEST);
7507 }
7508
7509 return [
7510 'chatId' => $createResult->getData()['CHAT_ID'],
7511 'alias' => $createResult->getData()['ALIAS_DATA']['ALIAS'],
7512 'link' => $createResult->getData()['ALIAS_DATA']['LINK']
7513 ];
7514 }
7515
7516 public static function videoconfUpdate($arParams, $n, CRestServer $server)
7517 {
7518 throw new \Bitrix\Rest\RestException('This method is not available', 'METHOD_NOT_AVAILABLE', CRestServer::STATUS_WRONG_REQUEST);
7519
7520 $arParams = array_change_key_case($arParams, CASE_UPPER);
7521
7522 if (
7523 \Bitrix\Im\User::getInstance()->isExtranet()
7524 || \Bitrix\Im\User::getInstance()->isBot()
7525 )
7526 {
7527 throw new Bitrix\Rest\RestException("Only intranet users have access to this method.", "ACCESS_ERROR", CRestServer::STATUS_FORBIDDEN);
7528 }
7529
7530 $arParams['BROADCAST_MODE'] = ($arParams['BROADCAST_MODE'] ?? 'N') === 'Y';
7531
7532 if (!isset($arParams['ID']) || (int)$arParams['ID'] <= 0)
7533 {
7534 throw new Bitrix\Rest\RestException("Conference ID can't be empty", "CONFERENCE_ID_EMPTY", CRestServer::STATUS_WRONG_REQUEST);
7535 }
7536
7537 $conference = \Bitrix\Im\Call\Conference::getById((int)$arParams['ID']);
7538
7539 if (!$conference)
7540 {
7541 throw new Bitrix\Rest\RestException("Conference with such id not found.", "CONFERENCE_NOT_FOUND", CRestServer::STATUS_WRONG_REQUEST);
7542 }
7543
7544 if (!$conference->canUserEdit(\Bitrix\Main\Engine\CurrentUser::get()->getId()))
7545 {
7546 throw new Bitrix\Rest\RestException("You can't edit the conference.", "ACCESS_ERROR", CRestServer::STATUS_FORBIDDEN);
7547 }
7548
7549 $updateResult = $conference->update($arParams);
7550
7551 if (!$updateResult->isSuccess())
7552 {
7553 $error = $updateResult->getErrors()[0];
7554 throw new Bitrix\Rest\RestException($error->getMessage(), $error->getCode(), CRestServer::STATUS_WRONG_REQUEST);
7555 }
7556
7557 return $updateResult->isSuccess();
7558 }
7559
7560 public static function desktopStatusGet($params, $n, \CRestServer $server)
7561 {
7562 return [
7563 'isOnline' => CIMMessenger::CheckDesktopStatusOnline(),
7564 'version' => CIMMessenger::GetDesktopVersion()
7565 ];
7566 }
7567
7568 public static function desktopPageOpen($params, $n, \CRestServer $server)
7569 {
7570 $params = array_change_key_case($params, CASE_UPPER);
7571
7572 if (CIMMessenger::GetDesktopVersion() === 0)
7573 {
7574 throw new Bitrix\Rest\RestException("Desktop was never installed", "NO_DESKTOP", CRestServer::STATUS_WRONG_REQUEST);
7575 }
7576
7577 if (!CIMMessenger::CheckDesktopStatusOnline())
7578 {
7579 throw new Bitrix\Rest\RestException("Desktop is not online", "DESKTOP_CLOSED", CRestServer::STATUS_WRONG_REQUEST);
7580 }
7581
7582 if (\CModule::IncludeModule("pull"))
7583 {
7585 if (!$userId)
7586 {
7587 return false;
7588 }
7589
7591 'module_id' => 'im',
7592 'command' => 'desktopOpenPage',
7593 'params' => [
7594 'url' => $params['URL']
7595 ],
7596 'extra' => \Bitrix\Im\Common::getPullExtra()
7597 ]);
7598 }
7599
7600 return true;
7601 }
7602
7603 private static function getBotId($arParams, \CRestServer $server)
7604 {
7605 $arParams = array_change_key_case($arParams, CASE_UPPER);
7606
7607 $clientId = $server->getClientId();
7608 if (!$clientId)
7609 {
7610 if (!empty($arParams['CLIENT_ID']))
7611 {
7612 $clientId = 'custom'.$arParams['CLIENT_ID'];
7613 }
7614 else
7615 {
7616 throw new \Bitrix\Rest\AccessException("Client ID not specified");
7617 }
7618 }
7619
7620 $bots = \Bitrix\Im\Bot::getListCache();
7621 if (isset($arParams['BOT_ID']))
7622 {
7623 if (!isset($bots[$arParams['BOT_ID']]))
7624 {
7625 throw new Bitrix\Rest\RestException("Bot not found", "BOT_ID_ERROR", CRestServer::STATUS_WRONG_REQUEST);
7626 }
7627 if ($clientId && $bots[$arParams['BOT_ID']]['APP_ID'] != $clientId)
7628 {
7629 throw new Bitrix\Rest\RestException("Bot was installed by another rest application", "APP_ID_ERROR", CRestServer::STATUS_WRONG_REQUEST);
7630 }
7631 }
7632 else
7633 {
7634 $botFound = false;
7635 foreach ($bots as $bot)
7636 {
7637 if ($bot['APP_ID'] == $clientId)
7638 {
7639 $botFound = true;
7640 $arParams['BOT_ID'] = $bot['BOT_ID'];
7641 break;
7642 }
7643 }
7644 if (!$botFound)
7645 {
7646 throw new Bitrix\Rest\RestException("Bot not found", "BOT_ID_ERROR", CRestServer::STATUS_WRONG_REQUEST);
7647 }
7648 }
7649
7650 return $arParams['BOT_ID'];
7651 }
7652
7653 private static function getLimit($options = [])
7654 {
7655 $max = 200;
7656 $default = 50;
7657
7658 if (!isset($options['LIMIT']))
7659 {
7660 return $default;
7661 }
7662
7663 $limit = (int)$options['LIMIT'];
7664 if ($limit <= 0)
7665 {
7666 return $default;
7667 }
7668
7669 if ($limit >= $max)
7670 {
7671 return $max;
7672 }
7673
7674 return $limit;
7675 }
7676
7677 private static function getOffset(int $offset, $options = [])
7678 {
7679 if ($offset > 0)
7680 {
7681 return $offset;
7682 }
7683
7684 if (!isset($options['OFFSET']) || (int)$options['OFFSET'] <= 0)
7685 {
7686 return 0;
7687 }
7688
7689 return (int)$options['OFFSET'];
7690 }
7691
7692 private static function getRawParam(string $paramName)
7693 {
7694 $context = \Bitrix\Main\Context::getCurrent();
7695
7696 if ($context === null)
7697 {
7698 return null;
7699 }
7700
7701 $paramName = mb_strtoupper($paramName);
7702 $request = $context->getRequest();
7703 $postRawData = array_change_key_case($request->getPostList()->toArrayRaw() ?? [], CASE_UPPER);
7704 $getRawData = array_change_key_case($request->getQueryList()->toArrayRaw() ?? [], CASE_UPPER);
7705
7706 return $postRawData[$paramName] ?? $getRawData[$paramName] ?? null;
7707 }
7708
7709 /* Utils */
7710 public static function objectEncode($data, $options = [])
7711 {
7712 if (!is_array($options['IMAGE_FIELD']))
7713 {
7714 $options['IMAGE_FIELD'] = ['AVATAR', 'AVATAR_HR'];
7715 }
7716
7717
7718 if (is_array($data))
7719 {
7720 $result = [];
7721 foreach ($data as $key => $value)
7722 {
7723 if (is_array($value))
7724 {
7725 $value = self::objectEncode($value, $options);
7726 }
7727 else if ($value instanceof \Bitrix\Main\Type\DateTime)
7728 {
7729 $value = date('c', $value->getTimestamp());
7730 }
7731 else if (is_string($key) && in_array($key, $options['IMAGE_FIELD']) && is_string($value) && $value && mb_strpos($value, 'http') !== 0)
7732 {
7733 $value = self::getServerAddress().$value;
7734 }
7735
7736 $key = str_replace('_', '', lcfirst(ucwords(mb_strtolower($key), '_')));
7737
7738 $result[$key] = $value;
7739 }
7740 $data = $result;
7741 }
7742
7743 return $data;
7744 }
7745
7746 public static function getServerAddress()
7747 {
7748 $publicUrl = \Bitrix\Main\Config\Option::get('main', 'last_site_url', '');
7749
7750 if ($publicUrl)
7751 {
7752 return $publicUrl;
7753 }
7754 else
7755 {
7756 return (\Bitrix\Main\Context::getCurrent()->getRequest()->isHttps() ? "https" : "http")."://".$_SERVER['SERVER_NAME'].(in_array($_SERVER['SERVER_PORT'], Array(80, 443))?'':':'.$_SERVER['SERVER_PORT']);
7757 }
7758 }
7759
7760 public static function isDebugEnabled()
7761 {
7763 return $settings['rest_debug'] === true;
7764 }
7765}
7766?>
$arParams
Определения access_dialog.php:21
$hash
Определения ajax_redirector.php:8
$type
Определения options.php:106
if(! $messageFields||!isset($messageFields['message_id'])||!isset($messageFields['status'])||!CModule::IncludeModule("messageservice")) $messageId
Определения callback_ismscenter.php:26
global $APPLICATION
Определения include.php:80
if(!Loader::includeModule('catalog')) if(!AccessController::getCurrent() ->check(ActionDictionary::ACTION_PRICE_EDIT)) if(!check_bitrix_sessid()) $request
Определения catalog_reindex.php:36
if(!is_object($USER)||! $USER->IsAuthorized()) $userId
Определения check_mail.php:18
static generateUnique()
Определения alias.php:242
static update($id, $fields)
Определения alias.php:75
static getByEntity($entityType, $entityId)
Определения alias.php:202
static get($alias)
Определения alias.php:141
static register(array $fields)
Определения app.php:22
static update(array $app, array $updateFields)
Определения app.php:241
static getListCache($lang=LANGUAGE_ID)
Определения app.php:581
static unRegister(array $app)
Определения app.php:191
static getByJson($params, $textReplace=array(), $options=Array())
Определения contextmenu.php:83
static getKeyboardByJson($params, $textReplace=array(), $options=Array())
Определения keyboard.php:196
static authorizeById($userId, $setCookie=null, $skipAuthorizeCheck=false)
Определения auth.php:261
static add(array $fields=[])
Определения conference.php:734
static getById(int $id)
Определения conference.php:833
static getByAlias(string $alias)
Определения conference.php:815
static register($userFields=[])
Определения user.php:22
static getUsers($chatId, $options=[])
Определения chat.php:736
static getById($id, $params=array())
Определения chat.php:800
static getListParams($params)
Определения chat.php:1031
static getList($params=array())
Определения chat.php:876
static getRelation($chatId, $params=[])
Определения chat.php:93
static register(array $fields)
Определения command.php:21
static addMessage(array $access, array $messageFields)
Определения command.php:400
static update(array $command, array $updateFields)
Определения command.php:197
static getListCache($lang=LANGUAGE_ID)
Определения command.php:727
static unRegister(array $command)
Определения command.php:147
static toJson($array, $camelCase=true)
Определения common.php:89
static getUserId($userId=null)
Определения common.php:73
static get($userId=null, $options=[])
Определения counter.php:18
static getColleagues($userId=null, $options=array())
Определения department.php:8
static getStructure($options=array())
Определения department.php:176
static getChatId($dialogId, $userId=null)
Определения dialog.php:93
static unread($dialogId, $messageId=null, $userId=null)
Определения dialog.php:246
static read($dialogId, $messageId=null, $userId=null)
Определения dialog.php:202
static getGroup($params, $userId=null, bool $filterActiveUser=true)
Определения extranet.php:15
static filterUserList(array $userList, $currentUserId=null)
Определения extranet.php:141
static filterExternalUserTypes(array $skipTypes=[])
Определения user.php:31
const DEVICE_TYPE_ALL
Определения promotion.php:19
static getList($userId=null, $options=[])
Определения recent.php:237
static getList($params)
Определения user.php:720
static getInstance($userId=null)
Определения user.php:45
static getListParams($params)
Определения user.php:905
static getBusiness($userId=null, $options=array())
Определения user.php:979
const COPILOT_MAIN_ROLE
Определения Params.php:26
static initById(int $id, ?Context $context=null)
Определения CalendarItem.php:64
static find(array $filter, array $order, ?int $limit=null, ?Context $context=null, array $select=[])
Определения MessageCollection.php:68
static getInstance()
Определения application.php:98
static getValue($name)
Определения configuration.php:24
static get($moduleId, $name, $default="", $siteId=false)
Определения option.php:30
static get()
Определения currentuser.php:33
static includeModule($moduleName)
Определения loader.php:67
static getList(array $parameters=array())
Определения datamanager.php:431
static getExternalUserTypes()
Определения user.php:307
static getInstance()
Определения mobile.php:226
static getPublicIds($params=[])
Определения channel.php:25
static add($recipient, array $parameters, $channelType=\CPullChannel::TYPE_PRIVATE)
Определения event.php:22
static get()
Определения session.php:20
static checkCallback($handlerUrl, $appInfo=array(), $checkInstallUrl=true)
Определения handlerhelper.php:31
Определения im_chat.php:15
static RecordShare(int $chatId, int $fileId, ?int $userId=null)
Определения im_disk.php:1147
static GetFolderModel($chatId, $createFolder=true)
Определения im_disk.php:1786
static SaveToLocalDisk($fileId)
Определения im_disk.php:889
static UploadFileFromDisk($chatId, $files, $text='', $options=[], $robot=false)
Определения im_disk.php:487
static DeleteFile($chatId, $fileId)
Определения im_disk.php:392
static GetUserId()
Определения im_disk.php:2458
static UpdateAvatarId($chatId, $fileId, $userId=null)
Определения im_disk.php:1333
Определения im_notify.php:14
static GetNotifySchema()
Определения im_notify_schema.php:15
Определения im_rest.php:17
static chatFileCollectionGet($arParams, $n, CRestServer $server)
Определения im_rest.php:2154
static userStatusIdleEnd($params, $n, \CRestServer $server)
Определения im_rest.php:419
static chatTaskPrepare($arParams, $n, CRestServer $server)
Определения im_rest.php:2398
static userStatusIdleStart($params, $n, \CRestServer $server)
Определения im_rest.php:395
static commandAnswer($arParams, $n, CRestServer $server)
Определения im_rest.php:6383
static botMessageUpdate($arParams, $n, CRestServer $server)
Определения im_rest.php:5172
static botUpdate($arParams, $n, CRestServer $server)
Определения im_rest.php:4709
static onBotJoinChat($arParams, $arHandler)
Определения im_rest.php:5947
static dialogUsersList($params, $offset, CRestServer $server)
Определения im_rest.php:616
static videoconfAdd($arParams, $n, CRestServer $server)
Определения im_rest.php:7485
static diskFolderGet($arParams, $n, CRestServer $server)
Определения im_rest.php:4102
static recentGet($arParams, $n, CRestServer $server)
Определения im_rest.php:932
static dialogMessagesGet($arParams, $offset, CRestServer $server)
Определения im_rest.php:462
static appUnRegister($arParams, $n, CRestServer $server)
Определения im_rest.php:6751
static recentHide($arParams, $n, CRestServer $server)
Определения im_rest.php:1081
static dialogMessagesSearch($arParams, $n, CRestServer $server)
Определения im_rest.php:506
static notImplemented($arParams, $n, CRestServer $server)
Определения im_rest.php:4369
static chatGet($arParams, $n, CRestServer $server)
Определения im_rest.php:1393
static notifyConfirm($arParams, $n, CRestServer $server)
Определения im_rest.php:3923
static notifyDelete($arParams, $n, CRestServer $server)
Определения im_rest.php:3805
static onBotMessageDelete($arParams, $arHandler)
Определения im_rest.php:5875
static departmentManagersGet($arParams, $n, CRestServer $server)
Определения im_rest.php:1178
static chatReminderDelete($arParams, $n, CRestServer $server)
Определения im_rest.php:2950
static notifyAdd($arParams, $n, CRestServer $server)
Определения im_rest.php:3625
static searchChat($arParams, $offset, CRestServer $server)
Определения im_rest.php:839
static getServerAddress()
Определения im_rest.php:7746
static chatPinDelete($arParams, $n, CRestServer $server)
Определения im_rest.php:2822
static botMessageAdd($arParams, $n, CRestServer $server)
Определения im_rest.php:4997
static searchLastGet($arParams, $n, CRestServer $server)
Определения im_rest.php:886
static notifyRead($arParams, $n, CRestServer $server)
Определения im_rest.php:3851
static chatCalendarGet($arParams, $n, CRestServer $server)
Определения im_rest.php:2462
static chatFileGet($arParams, $n, CRestServer $server)
Определения im_rest.php:2103
static recentList($arParams, $offset, CRestServer $server)
Определения im_rest.php:975
static dialogReadAll($arParams, $n, CRestServer $server)
Определения im_rest.php:734
static commandUpdate($arParams, $n, CRestServer $server)
Определения im_rest.php:6275
static messageDelete($arParams, $n, CRestServer $server)
Определения im_rest.php:3260
static videoconfUpdate($arParams, $n, CRestServer $server)
Определения im_rest.php:7516
static dialogRead($arParams, $n, CRestServer $server)
Определения im_rest.php:710
static onBotContextGet($arParams, $arHandler)
Определения im_rest.php:6062
static botMessageDelete($arParams, $n, CRestServer $server)
Определения im_rest.php:5379
static desktopPageOpen($params, $n, \CRestServer $server)
Определения im_rest.php:7568
static chatFavoriteGet($arParams, $n, CRestServer $server)
Определения im_rest.php:2197
static chatCalendarPrepare($arParams, $n, CRestServer $server)
Определения im_rest.php:2624
static searchDepartment($arParams, $offset, CRestServer $server)
Определения im_rest.php:809
static chatSignGet($arParams, $n, CRestServer $server)
Определения im_rest.php:2688
static messageUpdate($arParams, $n, CRestServer $server)
Определения im_rest.php:3284
static chatUrlDelete($arParams, $n, CRestServer $server)
Определения im_rest.php:2035
static dialogUsersGet($arParams, $n, CRestServer $server)
Определения im_rest.php:592
static chatPinGet($arParams, $n, CRestServer $server)
Определения im_rest.php:2744
static chatSetManager($arParams, $n, CRestServer $server)
Определения im_rest.php:1506
static recentUnread($arParams, $n, CRestServer $server)
Определения im_rest.php:1093
static dialogGet($arParams, $offset, CRestServer $server)
Определения im_rest.php:430
static messageCommand($arParams, $n, CRestServer $server)
Определения im_rest.php:3491
static botUnRegister($arParams, $n, CRestServer $server)
Определения im_rest.php:4656
static chatUpdateAvatar($arParams, $n, CRestServer $server)
Определения im_rest.php:1659
static videoconfShareChange($params, $n, \CRestServer $server)
Определения im_rest.php:7348
static messageUserGet($arParams, $offset, CRestServer $server)
Определения im_rest.php:3567
static notifySchemaGet($arParams, $n, CRestServer $server)
Определения im_rest.php:4043
static desktopStatusGet($params, $n, \CRestServer $server)
Определения im_rest.php:7560
static userStatusSet($params, $n, \CRestServer $server)
Определения im_rest.php:374
static botList($arParams, $n, CRestServer $server)
Определения im_rest.php:2980
static chatTaskGet($arParams, $n, CRestServer $server)
Определения im_rest.php:2323
static OnRestServiceBuildDescription()
Определения im_rest.php:18
static departmentEmployeesGet($arParams, $n, CRestServer $server)
Определения im_rest.php:1217
static diskFileSave($arParams, $n, CRestServer $server)
Определения im_rest.php:4321
static onCommandAdd($arParams, $arHandler)
Определения im_rest.php:5643
static onBotMessageUpdate($arParams, $arHandler)
Определения im_rest.php:5803
static notifyReadList($arParams, $n, CRestServer $server)
Определения im_rest.php:3879
static chatTaskDelete($arParams, $n, CRestServer $server)
Определения im_rest.php:2356
static isDebugEnabled()
Определения im_rest.php:7760
static onBotDelete($arParams, $arHandler)
Определения im_rest.php:6016
static chatMute($arParams, $n, CRestServer $server)
Определения im_rest.php:1922
static diskFileDelete($arParams, $n, CRestServer $server)
Определения im_rest.php:4302
static notifyHistorySearch($arParams, $n, CRestServer $server)
Определения im_rest.php:3987
static messageAdd($arParams, $n, CRestServer $server)
Определения im_rest.php:3004
static chatFavoriteCounterGet($arParams, $n, CRestServer $server)
Определения im_rest.php:2302
static searchLastAdd($arParams, $n, CRestServer $server)
Определения im_rest.php:907
static chatCalendarDelete($arParams, $n, CRestServer $server)
Определения im_rest.php:2582
static promotionRead($arParams, $n, CRestServer $server)
Определения im_rest.php:1125
static notifyAnswer($arParams, $n, CRestServer $server)
Определения im_rest.php:3955
static userBusinessList($arParams, $offset, CRestServer $server)
Определения im_rest.php:333
static chatReminderAdd($arParams, $n, CRestServer $server)
Определения im_rest.php:2900
static userList($arParams, $offset, CRestServer $server)
Определения im_rest.php:268
static chatReminderGet($arParams, $n, CRestServer $server)
Определения im_rest.php:2859
static commandUnRegister($arParams, $n, CRestServer $server)
Определения im_rest.php:6235
static chatPinAdd($arParams, $n, CRestServer $server)
Определения im_rest.php:2780
static chatCalendarAdd($arParams, $n, CRestServer $server)
Определения im_rest.php:2504
static commandRegister($arParams, $n, CRestServer $server)
Определения im_rest.php:6127
static botMessageLike($arParams, $n, CRestServer $server)
Определения im_rest.php:5441
static chatFavoriteDelete($arParams, $n, CRestServer $server)
Определения im_rest.php:2272
static chatFavoriteAdd($arParams, $n, CRestServer $server)
Определения im_rest.php:2230
static onBotMessageAdd($arParams, $arHandler)
Определения im_rest.php:5727
static callUserRegister($params, $n, \CRestServer $server)
Определения im_rest.php:7075
static mobileConfigGet($params, $n, \CRestServer $server)
Определения im_rest.php:7038
static chatCreate($arParams, $n, CRestServer $server)
Определения im_rest.php:1297
static diskFileCommit($arParams, $n, CRestServer $server)
Определения im_rest.php:4150
static botSendTyping($arParams, $n, CRestServer $server)
Определения im_rest.php:5509
static chatUrlGet($arParams, $n, CRestServer $server)
Определения im_rest.php:1995
static chatParentJoin($arParams, $n, CRestServer $server)
Определения im_rest.php:1957
static botUpdateTextFieldEnabled($arParams, $n, CRestServer $server)
Определения im_rest.php:5566
static OnRestAppDelete($arParams)
Определения im_rest.php:207
static counterGet($arParams, $n, CRestServer $server)
Определения im_rest.php:4349
static diskFolderListGet($arParams, $n, CRestServer $server)
Определения im_rest.php:4078
static chatUpdateTitle($arParams, $n, CRestServer $server)
Определения im_rest.php:1607
static callUserForceRename($params, $n, \CRestServer $server)
Определения im_rest.php:7228
static promotionGet($arParams, $n, CRestServer $server)
Определения im_rest.php:1112
static callChannelPublicList($params, $n, \CRestServer $server)
Определения im_rest.php:7290
static departmentGet($arParams, $offset, CRestServer $server)
Определения im_rest.php:1134
static chatSetOwner($arParams, $n, CRestServer $server)
Определения im_rest.php:1454
static chatUpdateColor($arParams, $n, CRestServer $server)
Определения im_rest.php:1554
static notifyGet($arParams, $n, CRestServer $server)
Определения im_rest.php:3760
static departmentColleaguesList($arParams, $offset, CRestServer $server)
Определения im_rest.php:1256
static videoconfPasswordCheck($params, $n, \CRestServer $server)
Определения im_rest.php:7439
static messageShare($arParams, $n, CRestServer $server)
Определения im_rest.php:3527
static objectEncode($data, $options=[])
Определения im_rest.php:7710
static userStatusGet($params, $n, \CRestServer $server)
Определения im_rest.php:362
static recentPin($arParams, $n, CRestServer $server)
Определения im_rest.php:1064
static chatUserDelete($arParams, $n, CRestServer $server)
Определения im_rest.php:1814
static dialogVote($arParams, $offset, CRestServer $server)
Определения im_rest.php:5609
static notifyReadAll($arParams, $n, CRestServer $server)
Определения im_rest.php:3915
static chatUrlCounterGet($arParams, $n, CRestServer $server)
Определения im_rest.php:2080
static appUpdate($arParams, $n, CRestServer $server)
Определения im_rest.php:6791
static dialogWriting($arParams, $n, CRestServer $server)
Определения im_rest.php:678
static botRegister($arParams, $n, CRestServer $server)
Определения im_rest.php:4376
static dialogUnread($arParams, $n, CRestServer $server)
Определения im_rest.php:739
static searchLastDelete($arParams, $n, CRestServer $server)
Определения im_rest.php:919
static chatUserAdd($arParams, $n, CRestServer $server)
Определения im_rest.php:1737
static messageLike($arParams, $n, CRestServer $server)
Определения im_rest.php:3461
static userGet($arParams, $n, CRestServer $server)
Определения im_rest.php:228
static searchUser($arParams, $offset, CRestServer $server)
Определения im_rest.php:761
static appRegister($arParams, $n, CRestServer $server)
Определения im_rest.php:6553
static diskRecordShare($arParams, $n, CRestServer $server)
Определения im_rest.php:4265
static chatUserList($arParams, $n, CRestServer $server)
Определения im_rest.php:1877
static SetSetting($type, $value, $userId=false)
Определения im_settings.php:144
const SETTINGS
Определения im_settings.php:12
static Get($userId=false)
Определения im_settings.php:34
const TYPE_PRIVATE
Определения pull_channel.php:9
Определения rest.php:24
getAuthType()
Определения rest.php:347
getClientId()
Определения rest.php:362
getMethod()
Определения rest.php:372
Определения rest.php:896
static setNavData($result, $dbRes)
Определения rest.php:927
if(!\Bitrix\Main\Loader::includeModule('clouds')) $lastId
Определения sync.php:68
$options
Определения commerceml2.php:49
$data['IS_AVAILABLE']
Определения .description.php:13
</td ></tr ></table ></td ></tr >< tr >< td class="bx-popup-label bx-width30"><?=GetMessage("PAGE_NEW_TAGS")?> array( $site)
Определения file_new.php:804
$res
Определения filter_act.php:7
$result
Определения get_property_values.php:14
$query
Определения get_search.php:11
$auth
Определения get_user.php:29
$getRawData
Определения get_user.php:21
$moduleId
$uid
Определения hot_keys_act.php:8
$filter
Определения iblock_catalog_list.php:54
const IM_CHECK_UPDATE
Определения include.php:69
const IM_MESSAGE_CHAT
Определения include.php:23
const IM_NOTIFY_SYSTEM
Определения include.php:38
const IM_NOTIFY_FROM
Определения include.php:37
const IM_MESSAGE_PRIVATE
Определения include.php:22
$_SERVER["DOCUMENT_ROOT"]
Определения cron_frame.php:9
global $USER
Определения csv_new_run.php:40
$context
Определения csv_new_setup.php:223
const SITE_DIR(!defined('LANG'))
Определения include.php:72
$groups
Определения options.php:30
htmlspecialcharsback($str)
Определения tools.php:2693
GetMessage($name, $aReplace=null)
Определения tools.php:3397
$order
Определения payment.php:8
$message
Определения payment.php:8
$counter
Определения options.php:5
$settings
Определения product_settings.php:43
if( $daysToExpire >=0 &&$daysToExpire< 60 elseif)( $daysToExpire< 0)
Определения prolog_main_admin.php:393
$config
Определения quickway.php:69
$fileName
Определения quickway.php:305
if(empty($signedUserToken)) $key
Определения quickway.php:257
if(empty($decryptedData)) $storage
Определения quickway.php:270
else $userName
Определения order_form.php:75
</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
$messages
Определения template.php:8
if($inWords) echo htmlspecialcharsbx(Number2Word_Rus(roundEx($totalVatSum $params['CURRENCY']
Определения template.php:799
$reminder
Определения options.php:2415
$matches
Определения index.php:22
$counters
Определения options.php:100
$clientId
Определения seo_client.php:18
$error
Определения subscription_card_product.php:20
$max
Определения template_copy.php:262
$GLOBALS['_____370096793']
Определения update_client.php:1
$n
Определения update_log.php:107
$url
Определения iframe.php:7
$dbRes
Определения yandex_detail.php:168