Bitrix-D7 23.9
 
Загрузка...
Поиск...
Не найдено
provider.php
1<?php
2
3namespace Bitrix\Rest\Preset;
4
11use Bitrix\Main\Entity\ReferenceField;
27
33{
34 public const URI_METHOD_INFO = 'https://util.bitrixsoft.com/example_b24/redirect.php';
35 public const URI_EXAMPLE_DOWNLOAD = 'https://util.bitrixsoft.com/example_b24/';
36 public const APP_MODE_SERVER = 'SERVER';
37 public const APP_MODE_ZIP = 'ZIP';
38
48 public static function deleteIntegration($id)
49 {
50 $result = [
51 'result' => 'success'
52 ];
53 $errorList = [];
54
55 $res = IntegrationTable::getList(
56 [
57 'filter' => [
58 '=ID' => $id
59 ],
60 'select' => [
61 'ID',
62 'APP_ID',
63 'BOT_ID',
64 'PASSWORD_ID',
65 'USER_ID'
66 ],
67 'limit' => 1
68 ]
69 );
70 if ($integration = $res->fetch())
71 {
72 global $USER;
73 if ($integration['USER_ID'] === $USER->GetID() || \CRestUtil::isAdmin())
74 {
75 $filterEvent = [
76 '=INTEGRATION_ID' => $integration['ID']
77 ];
78 if ($integration['BOT_ID'] > 0 && Loader::includeModule('im'))
79 {
80 $res = BotTable::getList(
81 [
82 'filter' => [
83 '=BOT_ID' => $integration['BOT_ID'],
84 ]
85 ]
86 );
87 if ($bot = $res->fetch())
88 {
89 $filterEvent = [
90 'LOGIC' => 'OR',
91 $filterEvent,
92 [
93 '=APP_ID' => '',
94 '=APPLICATION_TOKEN' => $bot['APP_ID'],
95 ]
96 ];
98 [
99 'BOT_ID' => $integration['BOT_ID'],
100 'MODULE_ID' => 'rest'
101 ]
102 );
103 }
104 }
105 if (($integration['PASSWORD_ID'] > 0) && !static::deleteWebHook($integration['PASSWORD_ID']))
106 {
107 $errorList[] = Loc::getMessage('INTEGRATION_PRESET_PROVIDER_ERROR_DELETE_WEBHOOK');
108 }
109 $resEvent = EventTable::getList(
110 [
111 'filter' => $filterEvent,
112 'select' => [
113 'ID'
114 ]
115 ]
116 );
117 while ($event = $resEvent->fetch())
118 {
119 $res = EventTable::delete($event['ID']);
120 if (!$res->isSuccess())
121 {
122 $errorList[] = $res->getErrorMessages();
123 }
124 }
125 $res = AppTable::getList(
126 [
127 'filter' => [
128 '=ID' => $integration['APP_ID']
129 ],
130 'select' => [
131 'ID'
132 ]
133 ]
134 );
135 if ($app = $res->fetch())
136 {
137 $resPlacement = PlacementTable::getList(
138 [
139 'filter' => [
140 '=APP_ID' => $app['ID']
141 ],
142 'select' => [
143 'ID'
144 ]
145 ]
146 );
147 while ($placement = $resPlacement->fetch())
148 {
149 $res = PlacementTable::delete($placement['ID']);
150 if (!$res->isSuccess())
151 {
152 $errorList[] = $res->getErrorMessages();
153 }
154 }
155 $res = AppTable::delete($app['ID']);
156 if (!$res->isSuccess())
157 {
158 $errorList[] = $res->getErrorMessages();
159 }
160 }
161
162 if (empty($errorList))
163 {
164 $res = IntegrationTable::delete($integration['ID']);
165 if (!$res->isSuccess())
166 {
167 $errorList[] = $res->getErrorMessages();
168 }
169 }
170 }
171 else
172 {
173 $errorList[] = Loc::getMessage('INTEGRATION_PRESET_PROVIDER_ERROR_ACCESS_DENIED');
174 }
175 }
176
177 if (!empty($errorList))
178 {
179 $result['result'] = 'error';
180 $result['errors'] = $errorList;
181 }
182
183 \Bitrix\Rest\Engine\Access::getActiveEntity(true);
184
185 return $result;
186 }
187
197 public static function getIntegration($id)
198 {
199 $id = intVal($id);
200 $return = [];
201 $runtime = [
202 new ReferenceField(
203 'APPLICATION_DATA',
204 AppTable::class,
205 [
206 '=ref.ID' => 'this.APP_ID'
207 ],
208 [
209 'join_type' => 'LEFT'
210 ]
211 ),
212 new ReferenceField(
213 'PASSWORD_DATA',
214 PasswordTable::class,
215 [
216 '=ref.ID' => 'this.PASSWORD_ID'
217 ],
218 [
219 'join_type' => 'LEFT'
220 ]
221 ),
222 ];
223 $select = [
224 '*',
225 'APPLICATION_DATA_' => 'APPLICATION_DATA',
226 'PASSWORD_DATA_' => 'PASSWORD_DATA'
227 ];
228 if (Loader::includeModule('im'))
229 {
230 $runtime[] = new ReferenceField(
231 'BOT_DATA',
232 BotTable::class,
233 [
234 '=ref.BOT_ID' => 'this.BOT_ID'
235 ],
236 [
237 'join_type' => 'LEFT'
238 ]
239 );
240 $select['BOT_DATA_'] = 'BOT_DATA';
241
242 $runtime[] = new ReferenceField(
243 'BOT_ACCOUNT',
244 UserTable::class,
245 [
246 '=ref.ID' => 'this.BOT_ID'
247 ],
248 [
249 'join_type' => 'LEFT'
250 ]
251 );
252 $select['BOT_ACCOUNT_NAME'] = 'BOT_ACCOUNT.NAME';
253 }
254
255 $res = IntegrationTable::getList(
256 [
257 'filter' => [
258 '=ID' => $id
259 ],
260 'limit' => 1,
261 'select' => $select,
262 'runtime' => $runtime
263 ]
264 );
265 if ($item = $res->fetch())
266 {
267 if ($item['PASSWORD_DATA_ID'] > 0)
268 {
269 $item['PASSWORD_DATA_URL'] = \CRestUtil::getWebhookEndpoint(
270 $item['PASSWORD_DATA_PASSWORD'],
271 $item['PASSWORD_DATA_USER_ID']
272 );
273 }
274
275 if (!empty($item['BOT_DATA_APP_ID']) && mb_strpos($item['BOT_DATA_APP_ID'], 'custom') === 0)
276 {
277 //clear 'custom' prefix only for webhook bot
278 $item['BOT_DATA_APP_ID'] = mb_substr($item['BOT_DATA_APP_ID'], 6);
279 }
280
281 if ($item['APP_ID'] > 0 && $item['APPLICATION_ONLY_API'] == 'N')
282 {
283 $resLang = AppLangTable::getList(
284 [
285 'filter' => [
286 '=APP_ID' => $item['APP_ID']
287 ]
288 ]
289 );
290 while ($lang = $resLang->fetch())
291 {
292 $item['APPLICATION_LANG_DATA'][$lang['LANGUAGE_ID']] = $lang['MENU_NAME'];
293 }
294 }
295
296 if ($item['APP_ID'] > 0 && !empty($item['WIDGET_LIST']))
297 {
298 $resLang = PlacementTable::getList(
299 [
300 'filter' => [
301 '=APP_ID' => $item['APP_ID'],
302 ],
303 'select' => [
304 'ID',
305 'LANG_ALL',
306 ],
307 ]
308 );
309 foreach ($resLang->fetchCollection() as $placement)
310 {
311 if (!is_null($placement->getLangAll()))
312 {
313 foreach ($placement->getLangAll() as $lang)
314 {
315 $item['WIDGET_LANG_LIST'][$lang->getLanguageId()] = [
316 'TITLE' => $lang->getTitle(),
317 'DESCRIPTION' => $lang->getDescription(),
318 'GROUP_NAME' => $lang->getGroupName(),
319 ];
320 }
321 }
322 }
323 }
324
325 $return = $item;
326 }
327
328 return $return;
329 }
330
342 public static function saveIntegration($requestData, $elementCode = '', $id = 0)
343 {
344 global $USER;
345 $result = [
346 'status' => true,
347 ];
348 $itemsEvent = [];
349 $errorList = [];
350 $id = (isset($requestData['ID']) && intVal($requestData['ID']) > 0) ? intVal($requestData['ID']) : $id;
351 $userId = $GLOBALS['USER']->getID();
352 $isAdmin = \CRestUtil::isAdmin();
353
354 $presetData = Element::get($elementCode);
355
356 if (
357 !$isAdmin
358 &&
359 (
360 $presetData['ADMIN_ONLY'] === 'Y'
361 || $presetData['OPTIONS']['WIDGET_NEEDED'] !== 'D'
362 || $presetData['OPTIONS']['APPLICATION_NEEDED'] !== 'D'
363 )
364 )
365 {
366 $result['status'] = false;
367 $result['errors'][] = Loc::getMessage('INTEGRATION_PRESET_PROVIDER_ERROR_ACCESS_DENIED');
368 return $result;
369 }
370
371 if (!OAuthService::getEngine()->isRegistered())
372 {
373 try
374 {
376 OAuthService::getEngine()->getClient()->getApplicationList();
377 }
378 catch (SystemException $e)
379 {
380 $result['status'] = false;
381 $result['errors'][] = $e->getCode() . ': ' . $e->getMessage();
382 return $result;
383 }
384 }
385
386 $presetData = $presetData['OPTIONS'];
387
388 $saveData = [
389 'ELEMENT_CODE' => $elementCode,
390 'USER_ID' => $USER->GetID(),
391 'TITLE' => $requestData['TITLE'],
392 'SCOPE' => is_array($requestData['SCOPE']) ? $requestData['SCOPE'] : [],
393 'QUERY' => $requestData['QUERY'],
394 'OUTGOING_HANDLER_URL' => trim($requestData['OUTGOING_HANDLER_URL'] ?? null),
395 'OUTGOING_EVENTS' => is_array($requestData['OUTGOING_EVENTS']) ? $requestData['OUTGOING_EVENTS'] : [],
396 'APPLICATION_ONLY_API' => (isset($requestData['APPLICATION_ONLY_API']) && $requestData['APPLICATION_ONLY_API'] === 'Y') ? 'Y' : 'N',
397 'APPLICATION_NEEDED' => (isset($requestData['APPLICATION_NEEDED']) && $requestData['APPLICATION_NEEDED'] === 'Y') ? 'Y' : 'N',
398 'APPLICATION_EVENTS' => (isset($requestData['APPLICATION_EVENTS']) && is_array($requestData['APPLICATION_EVENTS'])) ? $requestData['APPLICATION_EVENTS'] : [],
399 'OUTGOING_NEEDED' => ($requestData['OUTGOING_NEEDED'] === 'Y') ? 'Y' : 'N',
400 'WIDGET_NEEDED' => ($requestData['WIDGET_NEEDED'] === 'Y') ? 'Y' : 'N',
401 'WIDGET_HANDLER_URL' => trim($requestData['WIDGET_HANDLER_URL'] ?? null),
402 'WIDGET_LIST' => $requestData['WIDGET_LIST'],
403 'WIDGET_LANG_LIST' => (isset($requestData['WIDGET_LANG_LIST']) && is_array($requestData['WIDGET_LANG_LIST'])) ? $requestData['WIDGET_LANG_LIST'] : [],
404 'BOT_HANDLER_URL' => trim($requestData['BOT_HANDLER_URL'] ?? null)
405 ];
406
407 if ($id > 0)
408 {
409 $itemsEvent = EventTable::getList(
410 [
411 'filter' => [
412 '=INTEGRATION_ID' => $id
413 ]
414 ]
415 )->fetchAll();
416 }
417
418 if (!empty($itemsEvent['0']['APPLICATION_TOKEN']))
419 {
420 $saveData['APPLICATION_TOKEN'] = $itemsEvent['0']['APPLICATION_TOKEN'];
421 }
422 else
423 {
424 $saveData['APPLICATION_TOKEN'] = Random::getString(32);
425 }
426
427 $isAdd = false;
428 if ($id == 0)
429 {
430 $saveResult = IntegrationTable::add($saveData);
431 $isAdd = true;
432 $id = $saveResult->getId();
433 if (!$result['status'] = $saveResult->isSuccess())
434 {
435 $errorList = $saveResult->getErrorMessages();
436 }
437 }
438
439 if ($id > 0 || $result['status'])
440 {
442 if (!empty($saveData['TITLE']))
443 {
444 $title = $saveData['TITLE'];
445 }
446 else
447 {
448 $title = Loc::getMessage('INTEGRATION_PRESET_PROVIDER_TITLE_PREFIX', ['#ID#' => $id]);
449 }
450
451 if (!$isAdd)
452 {
453 $resIntegration = IntegrationTable::getList(
454 [
455 'filter' => [
456 'ID' => $id
457 ]
458 ]
459 );
460 if ($integrationData = $resIntegration->fetch())
461 {
462 if (!$isAdmin && $integrationData['USER_ID'] != $userId)
463 {
464 $result['status'] = false;
465 $result['errors'][] = Loc::getMessage('INTEGRATION_PRESET_PROVIDER_ERROR_ACCESS_DENIED');
466 return $result;
467 }
468 if ($integrationData['PASSWORD_ID'] > 0 && ($requestData['MODE'] === 'GEN_SAVE' || $integrationData['USER_ID'] != $userId))
469 {
471 'integrationRegen',
472 'integration' . $integrationData['ID'],
473 $integrationData['ELEMENT_CODE'],
474 'code'
475 );
476 if (static::deleteWebHook($integrationData['PASSWORD_ID']))
477 {
478 $integrationData['PASSWORD_ID'] = 0;
479 }
480 else
481 {
482 $result['status'] = false;
483 $errorList[] = Loc::getMessage('INTEGRATION_PRESET_PROVIDER_ERROR_DELETE_WEBHOOK');
484 return $result;
485 }
486 }
487
488 $saveData = array_merge($integrationData, $saveData);
489 }
490 //bot on webhooks
491 if ($presetData['BOT_NEEDED'] !== 'D' && Loader::includeModule('im'))
492 {
493 if (!empty($requestData['BOT_NAME']) && !empty($requestData['BOT_HANDLER_URL']))
494 {
495 $botId = 0;
496 $allEvents = [
497 'onImBotMessageAdd',
498 'onImBotJoinChat',
499 'onImBotDelete',
500 'onImBotMessageUpdate',
501 'onImBotMessageDelete'
502 ];
503 $params = [
504 'TYPE' => $requestData['BOT_TYPE'],
505 'EVENT_MESSAGE_ADD' => $saveData['BOT_HANDLER_URL'],
506 'EVENT_WELCOME_MESSAGE' => $saveData['BOT_HANDLER_URL'],
507 'EVENT_BOT_DELETE' => $saveData['BOT_HANDLER_URL'],
508 'MODULE_ID' => 'rest',
509 'PROPERTIES' => [
510 'NAME' => $requestData['BOT_NAME']
511 ]
512 ];
513
514 if ($integrationData['BOT_ID'] > 0)
515 {
516 $res = BotTable::getList(
517 [
518 'filter' => [
519 '=BOT_ID' => $integrationData['BOT_ID'],
520 ]
521 ]
522 );
523 if ($bot = $res->fetch())
524 {
525 $params = array_merge($bot, $params);
526 }
527 }
528 $clientId = $params['APP_ID'];
529 if (!$params['APP_ID'])
530 {
531 $clientId = Random::getString(32);
532 $params['APP_ID'] = 'custom' . $clientId;
533 $params['CODE'] = Random::getString(16);
534 }
535 elseif (mb_stripos($clientId, 'custom') === 0)
536 {
537 $clientId = mb_substr($clientId, 6);
538 }
539
540 $uriWithClientId = $saveData['BOT_HANDLER_URL']
541 . (mb_strpos($saveData['BOT_HANDLER_URL'], '?') === false ? '?' : '&')
542 . 'CLIENT_ID=' . $clientId;
543 $events = [
544 'onImBotMessageAdd' => $uriWithClientId,
545 'onImBotJoinChat' => $uriWithClientId,
546 'onImBotDelete' => $uriWithClientId,
547 ];
548 if (in_array($requestData['BOT_TYPE'], ['S', 'O']))
549 {
550 $events['onImBotMessageUpdate'] = $uriWithClientId;
551 $events['onImBotMessageDelete'] = $uriWithClientId;
552 $params['EVENT_MESSAGE_UPDATE'] = $uriWithClientId;
553 $params['EVENT_MESSAGE_DELETE'] = $uriWithClientId;
554 }
555
556 if ($integrationData['BOT_ID'] > 0)
557 {
558 if (Bot::update(['BOT_ID' => $integrationData['BOT_ID']], $params) === true)
559 {
560 $botId = $integrationData['BOT_ID'];
561 }
562 }
563 else
564 {
565 $botId = Bot::register($params);
566 }
567
568 if ($botId > 0)
569 {
570 $allEvents = array_change_key_case(array_combine($allEvents, $allEvents), CASE_UPPER);
571 $saveData['BOT_ID'] = $botId;
572 if ($integrationData['BOT_ID'] > 0)
573 {
574 $res = EventTable::getList(
575 [
576 'filter' => [
577 '=APP_ID' => '',
578 '=EVENT_NAME' => array_keys($allEvents),
579 '=APPLICATION_TOKEN' => [
580 $clientId,
581 $params['APP_ID'],
582 ],
583 ],
584 'select' => [
585 'ID',
586 'EVENT_NAME',
587 'EVENT_HANDLER'
588 ]
589 ]
590 );
591 while ($event = $res->fetch())
592 {
593 if (isset($events[$allEvents[$event['EVENT_NAME']]]) &&
594 $event['EVENT_HANDLER'] === $events[$allEvents[$event['EVENT_NAME']]])
595 {
596 unset($events[$allEvents[$event['EVENT_NAME']]]);
597 }
598 else
599 {
600 EventTable::delete($event['ID']);
601 }
602 }
603 }
604 if ($params['APP_ID'])
605 {
606 foreach ($events as $event => $eventHandler)
607 {
608 $res = EventTable::add(
609 [
610 'APP_ID' => '',
611 'EVENT_NAME' => toUpper($event),
612 'EVENT_HANDLER' => $eventHandler,
613 'APPLICATION_TOKEN' => $clientId,
614 'USER_ID' => 0,
615 ]
616 );
617 if ($result['status'] = $res->isSuccess())
618 {
619 Sender::bind('im', $event);
620 }
621 else
622 {
623 $errors = $res->getErrorMessages();
624 if (is_array($errors))
625 {
626 $errorList = array_merge($errorList, $errors);
627 }
628 break;
629 }
630 }
631 }
632 }
633 else
634 {
635 $errorList[] = Loc::getMessage('INTEGRATION_PRESET_PROVIDER_ERROR_BOT_CREATE');
636 }
637 }
638 else
639 {
640 $errorList[] = Loc::getMessage(
641 'INTEGRATION_PRESET_PROVIDER_ERROR_BOT_REQUIRED_FIELD_EMPTY'
642 );
643 }
644 }
645 }
646
647 if (!isset($presetData['QUERY_NEEDED']) || $presetData['QUERY_NEEDED'] !== 'D')
648 {
649 $webhook = static::getWebHook($saveData['SCOPE'], $saveData['PASSWORD_ID'] ?? null, $title);
650 $saveData['PASSWORD_ID'] = $webhook['ID'];
651 }
652
653 if (
654 $presetData['OUTGOING_NEEDED'] !== 'D'
655 && !empty($saveData['OUTGOING_HANDLER_URL'])
656 && !empty($saveData['OUTGOING_EVENTS'])
657 && $saveData['OUTGOING_NEEDED'] == 'Y'
658 )
659 {
660 $eventAddList = [];
661 $eventUpdateList = [];
662 if (!empty($itemsEvent))
663 {
664 $itemsEvent = array_column($itemsEvent, null, 'EVENT_NAME');
665 }
666
667 foreach ($saveData['OUTGOING_EVENTS'] as $event)
668 {
669 if ($itemsEvent[$event])
670 {
671 $eventUpdateList[] = $itemsEvent[$event]['ID'];
672 unset($itemsEvent[$event]);
673 }
674 else
675 {
676 $eventAddList[] = [
677 'TITLE' => $title,
678 'EVENT_NAME' => $event,
679 'EVENT_HANDLER' => $saveData['OUTGOING_HANDLER_URL'],
680 'USER_ID' => $userId,
681 'DATE_CREATE' => new DateTime(),
682 'APPLICATION_TOKEN' => $saveData['APPLICATION_TOKEN'],
683 'INTEGRATION_ID' => $saveData['ID']
684 ];
685 }
686 }
687
688 foreach ($itemsEvent as $event)
689 {
690 EventTable::delete($event['ID']);
691 }
692
693 foreach ($eventAddList as $item)
694 {
695 $res = EventTable::add($item);
696 if (!$result['status'] = $res->isSuccess())
697 {
698 $errors = $res->getErrorMessages();
699 if (is_array($errors))
700 {
701 $errorList = array_merge($errorList, $errors);
702 }
703 break;
704 }
705 }
706
707 if ($result['status'] && !empty($eventUpdateList))
708 {
709 $res = EventTable::updateMulti(
710 $eventUpdateList,
711 [
712 'TITLE' => $title,
713 'EVENT_HANDLER' => $saveData['OUTGOING_HANDLER_URL'],
714 'USER_ID' => $userId,
715 'APPLICATION_TOKEN' => $saveData['APPLICATION_TOKEN'],
716 ]
717 );
718 if (!$result['status'] = $res->isSuccess())
719 {
720 $errors = $res->getErrorMessages();
721 if (is_array($errors))
722 {
723 $errorList = array_merge($errorList, $errors);
724 }
725 }
726 }
727 }
728 else
729 {
730 foreach ($itemsEvent as $event)
731 {
732 EventTable::delete($event['ID']);
733 }
734 }
735
736 if (
737 $presetData['WIDGET_NEEDED'] !== 'D'
738 && $saveData['WIDGET_NEEDED'] == 'Y'
739 && !empty($saveData['WIDGET_HANDLER_URL'])
740 && is_array($saveData['WIDGET_LIST'])
741 )
742 {
743 $app = static::saveApp(
744 [
745 'ID' => $saveData['APP_ID'],
746 'FIELDS' => [
747 'URL' => $saveData['WIDGET_HANDLER_URL'],
748 'URL_INSTALL' => $saveData['WIDGET_HANDLER_URL'],
749 'SCOPE' => $saveData['SCOPE'],
750 'ONLY_API' => 'Y',
751 'MOBILE' => 'N',
752 'APP_NAME' => $saveData['TITLE'],
753 ],
754 'PLACEMENTS' => $saveData['WIDGET_LIST'],
755 'PLACEMENTS_LANG_LIST' => $saveData['WIDGET_LANG_LIST'],
756 'PLACEMENT_HANDLER_URL' => $saveData['WIDGET_HANDLER_URL'],
757 'INTEGRATION_CODE' => $saveData['ELEMENT_CODE'],
758 'INTEGRATION_ID' => $saveData['ID']
759 ]
760 );
761 if ($app['ID'] > 0)
762 {
763 $saveData['APP_ID'] = $app['ID'];
764 }
765
766 if (!empty($app['errors']))
767 {
768 $errorList = array_merge($errorList, $app['errors']);
769 }
770 }
771 elseif (
772 $presetData['APPLICATION_NEEDED'] !== 'D'
773 && $saveData['APPLICATION_NEEDED'] == 'Y'
774 )
775 {
776 $app = static::saveApp(
777 [
778 'ID' => $saveData['APP_ID'],
779 'FIELDS' => [
780 'URL' => trim($requestData['APPLICATION_URL_HANDLER']),
781 'URL_INSTALL' => trim($requestData['APPLICATION_URL_INSTALL']),
782 'SCOPE' => $saveData['SCOPE'],
783 'ONLY_API' => ($saveData['APPLICATION_ONLY_API'] == 'Y') ? 'Y' : 'N',
784 'MOBILE' => ($saveData['APPLICATION_ONLY_API'] != 'Y'
785 && $requestData['APPLICATION_MOBILE'] === 'Y') ? 'Y' : 'N',
786 'APP_NAME' => $saveData['TITLE'],
787 ],
788 'LANG_NAME' => ($saveData['APPLICATION_ONLY_API'] != 'Y' && is_array($requestData['APPLICATION_LANG_NAME'])) ?
789 $requestData['APPLICATION_LANG_NAME']
790 :
791 [],
792 'INTEGRATION_CODE' => $saveData['ELEMENT_CODE'],
793 'INTEGRATION_ID' => $saveData['ID']
794 ]
795 );
796
797 if ($app['ID'] > 0)
798 {
799 $saveData['APP_ID'] = $app['ID'];
800 }
801
802 if (!empty($app['errors']))
803 {
804 $errorList = array_merge($errorList, $app['errors']);
805 }
806 }
807 elseif (isset($saveData['APP_ID']) && $saveData['APP_ID'] > 0)
808 {
809 $res = AppTable::getList(
810 [
811 'filter' => [
812 '=ID' => $saveData['APP_ID']
813 ]
814 ]
815 );
816 if ($app = $res->fetch())
817 {
818 AppTable::delete($app['ID']);
819 }
820 $placementList = PlacementTable::getList(
821 [
822 'filter' => [
823 '=APP_ID' => $app['ID']
824 ]
825 ]
826 )->fetchAll();
827 if (is_array($placementList))
828 {
829 foreach ($placementList as $placement)
830 {
831 PlacementTable::delete($placement['ID']);
832 }
833 }
834 }
835
836 $resultSave = IntegrationTable::update($id, $saveData);
837 if (!$resultSave->isSuccess())
838 {
839 $errors = $resultSave->getErrorMessages();
840 if (is_array($errors))
841 {
842 $errorList = array_merge($errorList, $errors);
843 }
844 }
845
847 }
848
849 $result['ID'] = $id;
850 if (!empty($errorList))
851 {
852 $result['status'] = false;
853 $result['errors'] = $errorList;
854 }
855 \Bitrix\Rest\Engine\Access::getActiveEntity(true);
856
857 return $result;
858 }
859
860 private static function saveApp($data)
861 {
862 $app = [];
863 $return = [];
864 $errorList = [];
865 if ($data['ID'] > 0)
866 {
867 $dbApp = AppTable::getList(
868 [
869 'filter' => [
870 '=ID' => $data['ID'],
871 ],
872 'limit' => 1
873 ]
874 );
875 if ($app = $dbApp->fetch())
876 {
877 $data['FIELDS'] = array_merge($app, $data['FIELDS']);
878 }
879 }
880
881 if (count($data['FIELDS']['SCOPE']) <= 0)
882 {
883 $errorList[] = Loc::getMessage('INTEGRATION_PRESET_PROVIDER_ERROR_EMPTY_SCOPE');
884 }
885
886 if (empty($errorList))
887 {
888 foreach (GetModuleEvents('rest', 'OnRestLocalAppSave', true) as $eventHandler)
889 {
890 $eventResult = ExecuteModuleEventEx($eventHandler, [$app, &$data['FIELDS']]);
891 if ($eventResult !== null)
892 {
893 $errorList[] = strip_tags($eventResult);
894 }
895 }
896 }
897
898 if (empty($errorList) && empty($data['FIELDS']['URL']))
899 {
900 $errorList[] = Loc::getMessage('INTEGRATION_PRESET_PROVIDER_ERROR_INCORRECT_URL');
901 }
902
903 if (empty($errorList))
904 {
905 try
906 {
907 $appFields = [
908 'URL' => $data['FIELDS']['URL'],
909 'URL_INSTALL' => $data['FIELDS']['URL_INSTALL'],
910 'CLIENT_ID' => $data['FIELDS']['CLIENT_ID'],
911 'CODE' => $data['FIELDS']['CLIENT_ID'],
912 'SCOPE' => implode(',', $data['FIELDS']['SCOPE']),
913 'STATUS' => AppTable::STATUS_LOCAL,
914 'APP_NAME' => $data['FIELDS']['APP_NAME'],
915 'MOBILE' => $data['FIELDS']['MOBILE'],
916 ];
917 if ($app['ID'] > 0)
918 {
919 $result = AppTable::update($app['ID'], $appFields);
920 }
921 else
922 {
923 $appFields['INSTALLED'] = (!empty($data['FIELDS']['URL_INSTALL'])
924 && $data['FIELDS']['ONLY_API'] !== 'Y') ? AppTable::NOT_INSTALLED : AppTable::INSTALLED;
925 $result = AppTable::add($appFields);
926 if ($result->isSuccess())
927 {
929 'integrationAppCreated',
930 'integration' . $data['INTEGRATION_ID'],
931 $data['INTEGRATION_CODE'],
932 'code'
933 );
934 }
935 }
936
937 if ($result->isSuccess())
938 {
939 $return['ID'] = $result->getId();
940
941 AppLangTable::deleteByApp($return['ID']);
942 if ($data['FIELDS']['ONLY_API'] === 'N')
943 {
944 foreach ($data['LANG_NAME'] as $lang => $name)
945 {
946 AppLangTable::add(
947 [
948 'APP_ID' => $return['ID'],
949 'LANGUAGE_ID' => $lang,
950 'MENU_NAME' => $name
951 ]
952 );
953 }
954 }
955 else
956 {
957 if (
958 $data['FIELDS']['ONLY_API'] === 'Y'
959 && !empty($app['URL_INSTALL'])
960 && $data['FIELDS']['URL_INSTALL'] != $app['URL_INSTALL']
961 )
962 {
963 $event = EventTable::getList(
964 [
965 'filter' => [
966 '=APP_ID' => $return['ID'],
967 '=EVENT_NAME' => 'ONAPPINSTALL',
968 ],
969 'limit' => 1
970 ]
971 );
972 if ($eventInstall = $event->fetch())
973 {
974 // checkCallback is already called inside checkFields
975 $result = EventTable::update(
976 $eventInstall['ID'],
977 [
978 'APP_ID' => $return['ID'],
979 'EVENT_NAME' => 'ONAPPINSTALL',
980 'EVENT_HANDLER' => $data['FIELDS']['URL_INSTALL'],
981 ]
982 );
983 }
984 }
985
986 if (!empty($data['FIELDS']['URL_INSTALL']) && empty($app['URL_INSTALL']))
987 {
988 // checkCallback is already called inside checkFields
989 $result = EventTable::add(
990 [
991 'APP_ID' => $return['ID'],
992 'EVENT_NAME' => 'ONAPPINSTALL',
993 'EVENT_HANDLER' => $data['FIELDS']['URL_INSTALL'],
994 ]
995 );
996 if ($result->isSuccess())
997 {
998 Sender::bind('rest', 'OnRestAppInstall');
999 }
1000 }
1001
1002 if ($app['ID'] <= 0)
1003 {
1004 AppTable::install($return['ID']);
1005 }
1006 }
1007
1008 if (defined('BX_COMP_MANAGED_CACHE'))
1009 {
1010 global $CACHE_MANAGER;
1011 $CACHE_MANAGER->ClearByTag('sonet_group');
1012 }
1013 }
1014 else
1015 {
1016 $errorList = $result->getErrorMessages();
1017 }
1018 }
1019 catch (\Bitrix\Rest\OAuthException $e)
1020 {
1021 $errorList[] = $e->getMessage();
1022 }
1023
1024 if (empty($errorList) && $data['PLACEMENTS'])
1025 {
1026 $title = '';
1027 $placementListOld = [];
1028 $updateIDList = [];
1029 $addList = [];
1030 $data['PLACEMENTS'] = is_array($data['PLACEMENTS']) ? $data['PLACEMENTS'] : [];
1031
1032 $placementLangList = [];
1033 foreach ($data['PLACEMENTS_LANG_LIST'] as $lang => $fields)
1034 {
1035 if (!empty($fields['TITLE']))
1036 {
1037 $placementLangList[$lang] = [
1038 'LANGUAGE_ID' => $lang,
1039 'TITLE' => $fields['TITLE'],
1040 ];
1041 }
1042 }
1043
1044 $langList = Lang::listLanguage();
1045 $defaultLang = $langList[0];
1046 if (!empty($placementLangList))
1047 {
1048 foreach ($langList as $lang)
1049 {
1050 if (isset($placementLangList[$lang]))
1051 {
1052 $title = $placementLangList[$lang]['TITLE'];
1053 break;
1054 }
1055 }
1056 }
1057
1058 if ($title === '')
1059 {
1060 $title = $data['APP_NAME'];
1061 $placementLangList[$defaultLang] = [
1062 'LANGUAGE_ID' => $defaultLang,
1063 'TITLE' => $title,
1064 ];
1065 }
1066
1067 $accessPlacement = Rest::getAccessPlacement($data['FIELDS']['SCOPE']);
1068 $placementRes = PlacementTable::getList(
1069 [
1070 'filter' => [
1071 '=APP_ID' => $return['ID']
1072 ]
1073 ]
1074 );
1075 if ($placementList = $placementRes->fetchAll())
1076 {
1077 $placementListOld = array_column($placementList, 'PLACEMENT', 'ID');
1078 }
1079
1080 foreach ($data['PLACEMENTS'] as $placement)
1081 {
1082 if (!in_array($placement, $accessPlacement))
1083 {
1084 $errorList[] = Loc::getMessage(
1085 "INTEGRATION_PRESET_PROVIDER_ERROR_ACCESS_PLACEMENT",
1086 [
1087 '#PLACEMENT_CODE#' => $placement
1088 ]
1089 ) ;
1090 continue;
1091 }
1092
1093 $key = array_search($placement, $placementListOld);
1094 if ($key !== false)
1095 {
1096 $updateIDList[] = $key;
1097 unset($placementListOld[$key]);
1098 }
1099 else
1100 {
1101 $addList[] = [
1102 'APP_ID' => $return['ID'],
1103 'PLACEMENT' => $placement,
1104 'PLACEMENT_HANDLER' => $data['PLACEMENT_HANDLER_URL'],
1105 'TITLE' => $title,
1106 ];
1107 }
1108 }
1109 if (!empty($placementListOld))
1110 {
1111 foreach (array_keys($placementListOld) as $place)
1112 {
1113 PlacementTable::delete($place);
1114 }
1115 }
1116
1117 if (!empty($updateIDList))
1118 {
1119 $resultPlacementBind = PlacementTable::updateMulti(
1120 $updateIDList,
1121 [
1122 'PLACEMENT_HANDLER' => $data['PLACEMENT_HANDLER_URL'],
1123 'TITLE' => $title,
1124 ]
1125 );
1126 if ($resultPlacementBind->isSuccess())
1127 {
1128 foreach ($updateIDList as $id)
1129 {
1131 foreach ($placementLangList as $fields)
1132 {
1133 $fields['PLACEMENT_ID'] = $id;
1134 $resultPlacementLang = PlacementLangTable::add($fields);
1135 if (!$resultPlacementLang->isSuccess())
1136 {
1137 $errors = $resultPlacementLang->getErrorMessages();
1138 if (is_array($errors))
1139 {
1140 $errorList = array_merge($errorList, $errors);
1141 }
1142 }
1143 }
1144 }
1145 }
1146 else
1147 {
1148 $errors = $resultPlacementBind->getErrorMessages();
1149 if (is_array($errors))
1150 {
1151 $errorList = array_merge($errorList, $errors);
1152 }
1153 }
1154 }
1155
1156 if (count($addList) > 0)
1157 {
1159 'integrationPlacementCreated',
1160 'integration' . $data['INTEGRATION_ID'],
1161 $data['INTEGRATION_CODE'],
1162 'integrationCode'
1163 );
1164 foreach ($addList as $item)
1165 {
1166 $resultPlacementBind = PlacementTable::add($item);
1167 if ($resultPlacementBind->isSuccess())
1168 {
1169 $id = (int) $resultPlacementBind->getId();
1170 foreach ($placementLangList as $fields)
1171 {
1172 $fields['PLACEMENT_ID'] = $id;
1173 $resultPlacementLang = PlacementLangTable::add($fields);
1174 if (!$resultPlacementLang->isSuccess())
1175 {
1176 $errors = $resultPlacementLang->getErrorMessages();
1177 if (is_array($errors))
1178 {
1179 $errorList = array_merge($errorList, $errors);
1180 }
1181 }
1182 }
1184 'integrationPlacementCreated',
1185 'integration' . $data['INTEGRATION_ID'],
1186 $item['PLACEMENT'],
1187 'placementCode'
1188 );
1189 }
1190 else
1191 {
1192 $errors = $resultPlacementBind->getErrorMessages();
1193 if (is_array($errors))
1194 {
1195 $errorList = array_merge($errorList, $errors);
1196 }
1197 }
1198 }
1199 }
1200 }
1201 }
1202
1203 if (!empty($errorList))
1204 {
1205 $return['errors'] = $errorList;
1206 }
1207
1208 return $return;
1209 }
1210
1211 private static function getWebHook($scopeList = [], $id = 0, $title = '')
1212 {
1213 $password = [];
1214 $id = intVal($id);
1215 $scopeList = is_array($scopeList) ? $scopeList : [];
1216 if ($id !== 0)
1217 {
1218 $passData = PasswordTable::getList(
1219 [
1220 'filter' => [
1221 '=ID' => $id,
1222 ],
1223 'select' => [
1224 'PASSWORD',
1225 'USER_ID',
1226 'TITLE',
1227 'ID'
1228 ],
1229 'limit' => 1
1230 ]
1231 );
1232 if ($passwordData = $passData->fetch())
1233 {
1234 $scopeListOld = [];
1235 $scopeIdList = [];
1236 $permData = PermissionTable::getList(
1237 [
1238 'filter' => [
1239 '=PASSWORD_ID' => $passwordData['ID']
1240 ]
1241 ]
1242 );
1243 while ($scopeItem = $permData->fetch())
1244 {
1245 $scopeIdList[$scopeItem['PERM']] = $scopeItem['ID'];
1246 $scopeListOld[] = $scopeItem['PERM'];
1247 }
1248 $resultList = array_diff($scopeList, $scopeListOld);
1249 foreach ($resultList as $scope)
1250 {
1251 PermissionTable::add(
1252 [
1253 'PASSWORD_ID' => $passwordData['ID'],
1254 'PERM' => $scope,
1255 ]
1256 );
1257 }
1258 $resultList = array_diff($scopeListOld, $scopeList);
1259 foreach ($resultList as $scope)
1260 {
1261 if (isset($scopeIdList[$scope]))
1262 {
1263 PermissionTable::delete($scopeIdList[$scope]);
1264 }
1265 }
1266
1267 if ($title !== '' && $passwordData['TITLE'] !== $title)
1268 {
1269 PasswordTable::update(
1270 $passwordData['ID'],
1271 [
1272 'TITLE' => $title
1273 ]
1274 );
1275 }
1276
1277 $password = $passwordData;
1278 }
1279 }
1280
1281 if (empty($password))
1282 {
1283 $userId = $GLOBALS['USER']->GetID();
1284 $passwordCreat = PasswordTable::createPassword(
1285 $userId,
1286 $scopeList,
1287 $title,
1288 true
1289 );
1290 if ($passwordCreat !== false)
1291 {
1292 $password = $passwordCreat;
1293 }
1294 }
1295 if (!empty($password['PASSWORD']))
1296 {
1297 $password['URL'] = \CRestUtil::getWebhookEndpoint($password['PASSWORD'], $password['USER_ID']);
1298 }
1299
1300 return $password;
1301 }
1302
1303 private static function deleteWebHook($id)
1304 {
1305 $result = false;
1306 $passData = PasswordTable::getList(
1307 [
1308 'filter' => [
1309 '=ID' => $id,
1310 ],
1311 'select' => [
1312 'PASSWORD',
1313 'USER_ID',
1314 'ID'
1315 ],
1316 'limit' => 1
1317 ]
1318 );
1319 if ($passwordData = $passData->fetch())
1320 {
1321 $permData = PermissionTable::getList(
1322 [
1323 'filter' => [
1324 '=PASSWORD_ID' => $passwordData['ID']
1325 ],
1326 'select' => [
1327 'ID'
1328 ]
1329 ]
1330 );
1331 while ($scopeItem = $permData->fetch())
1332 {
1333 PermissionTable::delete($scopeItem['ID']);
1334 }
1335 $deleteResult = PasswordTable::delete($passwordData['ID']);
1336 if ($deleteResult->isSuccess())
1337 {
1338 $result = true;
1339 }
1340 }
1341 return $result;
1342 }
1343}
static register(array $fields)
Definition bot.php:35
static unRegister(array $bot)
Definition bot.php:245
static update(array $bot, array $updateFields)
Definition bot.php:326
static getMessage($code, $replace=null, $language=null)
Definition loc.php:29
static createPassword($userId, array $scopeList, $siteTitle, $returnArray=false)
Definition password.php:117
static logToFile($action, $tag='', $label='', $actionType='')
Definition analytic.php:20
static deleteByApp($appId)
Definition applang.php:77
static install($appId)
Definition app.php:459
const STATUS_LOCAL
Definition app.php:74
const NOT_INSTALLED
Definition app.php:63
static listLanguage()
Definition lang.php:19
static deleteByPlacement(int $placementId)
static getAccessPlacement($scopeList)
Definition rest.php:99
static deleteIntegration($id)
Definition provider.php:48
static saveIntegration($requestData, $elementCode='', $id=0)
Definition provider.php:342
$GLOBALS['____1444769544']
Definition license.php:1