1C-Bitrix 25.700.0
Загрузка...
Поиск...
Не найдено
pull_push.php
См. документацию.
1<?php
2
11
12
19{
29 public static function GetList($arOrder = [], $arFilter = [], $arSelect = [], $arNavStartParams = [])
30 {
31 $params = [
32 "filter" => $arFilter,
33 "order" => $arOrder
34 ];
35 if (!empty($arSelect))
36 {
37 $params["select"] = $arSelect;
38 }
39
40 if (isset($arNavStartParams["nTopCount"]) && intval($arNavStartParams["nTopCount"]) > 0)
41 {
42 $params["limit"] = intval($arNavStartParams["nTopCount"]);
43 }
44
45 $res = \Bitrix\Pull\Model\PushTable::getList($params);
46
47 return $res;
48 }
49
50
58 public static function Add($arFields = Array())
59 {
60 $result = \Bitrix\Pull\Model\PushTable::add($arFields);
61
62 return $result->getId();
63 }
64
65 public static function getUniqueHash($user_id, $app_id)
66 {
68 $handlers = $eventManager->findEventHandlers("pull", "onPushTokenUniqueHashGet");
69 foreach ($handlers as $handler)
70 {
71 $uniqueHash = ExecuteModuleEventEx($handler, [$user_id, $app_id]);
72 if ($uniqueHash)
73 {
74 return $uniqueHash;
75 }
76 }
77
78 return md5($user_id . $app_id);
79 }
80
89 public static function Update($ID, $arFields = Array())
90 {
91 $result = \Bitrix\Pull\Model\PushTable::update($ID, $arFields);
92 return $result->getId();
93 }
94
102 public static function Delete($ID = false)
103 {
104 $result = \Bitrix\Pull\Model\PushTable::delete(intval($ID));
105 return $result->isSuccess();
106 }
107
108 public static function cleanTokens()
109 {
110 global $DB;
111
115 $killTime = ConvertTimeStamp(microtime(true) - 24 * 3600 * 14, "FULL");
116 $sqlString = "DELETE FROM b_pull_push WHERE DATE_AUTH < " . $DB->CharToDateFunction($killTime);
117
118 $DB->Query($sqlString);
119
120 return "CPullPush::cleanTokens();";
121 }
122}
123
125{
126 const SEND_IMMEDIATELY = 'IMMEDIATELY';
127 const SEND_IMMEDIATELY_SILENT = 'IMMEDIATELY_SILENT';
128 const SEND_DEFERRED = 'DEFERRED';
129 const SEND_SKIP = 'SKIP';
130 const RECORD_NOT_FOUND = 'NOT_FOUND';
131
132 public const DEFAULT_APP_ID = "Bitrix24";
133
134 public static ?array $pushServices;
135
136 private string $remoteProviderUrl ;
137
138 public function __construct()
139 {
140 if (!isset(self::$pushServices))
141 {
142 self::$pushServices = \Bitrix\Pull\Push\ServiceList::getServiceList();
143 }
144 $this->remoteProviderUrl = Option::get("pull", "push_service_url");
145 }
146
147 public static function DeleteFromQueueByTag($userId, $tag, $appId = self::DEFAULT_APP_ID)
148 {
149 global $DB;
150 if ($tag == '' || intval($userId) == 0)
151 {
152 return false;
153 }
154
155 $strSql = "DELETE FROM b_pull_push_queue WHERE USER_ID = " . intval($userId) . " AND TAG = '" . $DB->ForSQL($tag) . "'";
156 $DB->Query($strSql);
157
158 \Bitrix\Pull\Push::add($userId, [
159 'module_id' => 'pull',
160 'push' => [
161 'advanced_params' => [
162 "notificationsToCancel" => [$tag],
163 ],
164 'send_immediately' => 'Y',
165 'app_id' => $appId
166 ]
167 ]);
168
169 return true;
170 }
171
176 public function AddQueue($arParams)
177 {
178 if (!CPullOptions::GetPushStatus())
179 {
180 return false;
181 }
182
183 global $DB;
184
185 if (is_array($arParams['USER_ID']))
186 {
187 foreach ($arParams['USER_ID'] as $key => $userId)
188 {
189 $userId = intval($userId);
190 if ($userId > 0)
191 {
192 $arFields['USER_ID'][$userId] = $userId;
193 }
194 }
195 if (empty($arFields['USER_ID']))
196 {
197 return false;
198 }
199 }
200 else
201 {
202 if (isset($arParams['USER_ID']) && intval($arParams['USER_ID']) > 0)
203 {
204 $userId = intval($arParams['USER_ID']);
205 $arFields['USER_ID'][$userId] = $userId;
206 }
207 else
208 {
209 return false;
210 }
211 }
212
213 $arFields['SKIP_USERS'] = array();
214 if (is_array($arParams['SKIP_USERS']))
215 {
216 foreach ($arParams['SKIP_USERS'] as $key => $userId)
217 {
218 $userId = intval($userId);
219 if ($userId > 0)
220 {
221 $arFields['SKIP_USERS'][] = $userId;
222 }
223 }
224 }
225
226 if (isset($arParams['MESSAGE']) && trim($arParams['MESSAGE']) <> '')
227 {
228 $arFields['MESSAGE'] = str_replace(["\r\n", "\n\r", "\n", "\r"], " ", trim($arParams['MESSAGE']));
229 }
230
231 $arFields['TAG'] = '';
232 if (isset($arParams['TAG']) && trim($arParams['TAG']) <> '' && mb_strlen(trim($arParams['TAG'])) <= 255)
233 {
234 $arFields['TAG'] = trim($arParams['TAG']);
235 }
236
237 $arFields['SUB_TAG'] = '';
238 if (isset($arParams['SUB_TAG']) && trim($arParams['SUB_TAG']) <> '' && mb_strlen(trim($arParams['SUB_TAG'])) <= 255)
239 {
240 $arFields['SUB_TAG'] = trim($arParams['SUB_TAG']);
241 }
242
243 $arFields['BADGE'] = -1;
244 if (isset($arParams['BADGE']) && $arParams['BADGE'] != '' && intval($arParams['BADGE']) >= 0)
245 {
246 $arFields['BADGE'] = intval($arParams['BADGE']);
247 }
248
249 $arFields['PARAMS'] = '';
250 if (isset($arParams['PARAMS']))
251 {
252 if (is_array($arParams['PARAMS']) || trim($arParams['PARAMS']) <> '')
253 {
254 $arFields['PARAMS'] = $arParams['PARAMS'];
255 }
256 }
257
258 $arFields['ADVANCED_PARAMS'] = [];
259 if (isset($arParams['ADVANCED_PARAMS']) && is_array($arParams['ADVANCED_PARAMS']))
260 {
261 $arFields['ADVANCED_PARAMS'] = $arParams['ADVANCED_PARAMS'];
262 }
263 if (!isset($arParams['ADVANCED_PARAMS']['id']) && $arFields['SUB_TAG'] <> '')
264 {
265 $arFields['ADVANCED_PARAMS']['id'] = $arFields['SUB_TAG'];
266 }
267 if (!isset($arFields['ADVANCED_PARAMS']['extra']['server_time']))
268 {
269 $arFields['ADVANCED_PARAMS']['extra']['server_time'] = date('c');
270 }
271 if (!isset($arFields['ADVANCED_PARAMS']['extra']['server_time_unix']))
272 {
273 $arFields['ADVANCED_PARAMS']['extra']['server_time_unix'] = microtime(true);
274 }
275
276 $arFields['EXPIRY'] = 43200;
277 if (isset($arParams['EXPIRY']) && intval($arParams['EXPIRY']) >= 0)
278 {
279 $arFields['EXPIRY'] = intval($arParams['EXPIRY']);
280 }
281
282 if ($arParams['SOUND'] <> '')
283 {
284 $arFields['SOUND'] = $arParams['SOUND'];
285 }
286
287 $arFields['APP_ID'] = ($arParams['APP_ID'] <> '') ? $arParams['APP_ID'] : self::DEFAULT_APP_ID;
288
289 $groupMode = [
290 self::SEND_IMMEDIATELY => [],
291 self::SEND_IMMEDIATELY_SILENT => [],
292 self::SEND_DEFERRED => [],
293 self::SEND_SKIP => [],
294 ];
295
296 $devices = [];
297
298 $options = [];
299 if (isset($arParams['IMPORTANT']) && $arParams['IMPORTANT'] === 'Y')
300 {
301 $options['IMPORTANT'] = 'Y';
302 }
303
304 $info = self::GetDeviceInfo($arFields['USER_ID'], $options, $arFields['APP_ID']);
305 foreach ($info as $userId => $params)
306 {
307 if (in_array($userId, $arFields['SKIP_USERS']))
308 {
309 $params['mode'] = self::SEND_SKIP;
310 }
311 else if ($params['mode'] == self::SEND_DEFERRED && isset($arParams['SEND_IMMEDIATELY']) && $arParams['SEND_IMMEDIATELY'] === 'Y')
312 {
313 $params['mode'] = self::SEND_IMMEDIATELY;
314 }
315 elseif (
316 in_array($params['mode'], [self::SEND_IMMEDIATELY, self::SEND_IMMEDIATELY_SILENT])
317 && isset($arParams['SEND_DEFERRED']) && $arParams['SEND_DEFERRED'] === 'Y'
318 )
319 {
320 $params['mode'] = self::SEND_DEFERRED;
321 }
322
323 if ($params['mode'] != self::RECORD_NOT_FOUND)
324 {
325 foreach(GetModuleEvents("pull", "OnBeforeSendPush", true) as $arEvent)
326 {
327 $resultEvent = ExecuteModuleEventEx($arEvent, [$userId, $params['mode'], $arFields]);
328 if ($resultEvent)
329 {
330 $resultEvent = mb_strtoupper($resultEvent);
331 if (in_array($resultEvent, [
332 self::SEND_IMMEDIATELY,
333 self::SEND_IMMEDIATELY_SILENT,
334 self::SEND_DEFERRED,
335 self::SEND_SKIP
336 ]))
337 {
338 $params['mode'] = $resultEvent;
339 }
340 }
341 }
342 }
343
344 if (isset($groupMode[$params['mode']]))
345 {
346 $groupMode[$params['mode']][$userId] = $userId;
347 }
348 if (
349 in_array($params['mode'], [self::SEND_IMMEDIATELY, self::SEND_IMMEDIATELY_SILENT])
350 && !empty($params['device'])
351 && !(isset($arParams['SEND_IMMEDIATELY']) && $arParams['SEND_IMMEDIATELY'] == 'Y')
352 )
353 {
354 $devices = array_merge($devices, $params['device']);
355 }
356 }
357
358 $pushImmediately = [];
359 foreach ($groupMode as $type => $users)
360 {
361 foreach ($users as $userId)
362 {
363 $pushImmediately[] = self::prepareSend($userId, $arFields, $type);
364 }
365 }
366 if (!empty($pushImmediately))
367 {
368 $CPushManager = new CPushManager();
369 $CPushManager->SendMessage($pushImmediately, $devices);
370 }
371
372 foreach ($groupMode[self::SEND_DEFERRED] as $userId)
373 {
374 $arAdd = [
375 'USER_ID' => $userId,
376 'TAG' => $arFields['TAG'],
377 'SUB_TAG' => $arFields['SUB_TAG'],
378 '~DATE_CREATE' => $DB->CurrentTimeFunction()
379 ];
380
381 if ($arFields['MESSAGE'] <> '')
382 {
383 $arAdd['MESSAGE'] = $arFields['MESSAGE'];
384 }
385 if (is_array($arFields['ADVANCED_PARAMS']))
386 {
387 $arAdd['ADVANCED_PARAMS'] = Bitrix\Main\Web\Json::encode($arFields['ADVANCED_PARAMS']);
388 }
389 if (is_array($arFields['PARAMS']))
390 {
391 $arAdd['PARAMS'] = Bitrix\Main\Web\Json::encode($arFields['PARAMS']);
392 }
393 else
394 {
395 if ($arFields['PARAMS'] <> '')
396 {
397 $arAdd['PARAMS'] = $arFields['PARAMS'];
398 }
399 }
400
401 $arAdd['APP_ID'] = $arFields['APP_ID'];
402
403 $DB->Add("b_pull_push_queue", $arAdd, ["MESSAGE", "PARAMS", "ADVANCED_PARAMS"]);
404
405 CAgent::AddAgent("CPushManager::SendAgent();", "pull", "N", 30, "", "Y", ConvertTimeStamp(time() + CTimeZone::GetOffset() + 30, "FULL"), 100, false, false);
406 }
407
408 return true;
409 }
410
411 private static function prepareSend($userId, $fields, $type = self::SEND_IMMEDIATELY)
412 {
413 $result = [
414 'USER_ID' => $userId,
415 ];
416
417 if ($type != self::SEND_DEFERRED)
418 {
419 if (is_array($fields['PARAMS']))
420 {
421 if (isset($fields['PARAMS']['CATEGORY']))
422 {
423 $result['CATEGORY'] = $fields['PARAMS']['CATEGORY'];
424 unset($fields['PARAMS']['CATEGORY']);
425 }
426 $result['PARAMS'] = Bitrix\Main\Web\Json::encode($fields['PARAMS']);
427 }
428 elseif ($fields['PARAMS'] <> '')
429 {
430 $result['PARAMS'] = $fields['PARAMS'];
431 }
432
433 if (isset($fields['MESSAGE']) && $fields['MESSAGE'] <> '')
434 {
435 $result['MESSAGE'] = $fields['MESSAGE'];
436 }
437
438 if (isset($fields['SOUND']) && $fields['SOUND'] <> '')
439 {
440 $result['SOUND'] = $fields['SOUND'];
441 }
442 else if ($type == self::SEND_IMMEDIATELY_SILENT)
443 {
444 $result['SOUND'] = 'silence.aif';
445 }
446
447 if (count($fields['ADVANCED_PARAMS']) > 0)
448 {
449 $result['ADVANCED_PARAMS'] = $fields['ADVANCED_PARAMS'];
450 }
451 }
452
453 if ($type == self::SEND_SKIP)
454 {
455 unset($result['MESSAGE']);
456 unset($result['ADVANCED_PARAMS']['senderName']);
457 }
458
459 if ($fields['EXPIRY'] <> '')
460 {
461 $result['EXPIRY'] = $fields['EXPIRY'];
462 }
463
464 if (intval($fields['BADGE']) >= 0)
465 {
466 $result['BADGE'] = $fields['BADGE'];
467 }
468 else
469 {
470 $result['BADGE'] = \Bitrix\Pull\MobileCounter::get($result['USER_ID']);
471 }
472
473 $result['APP_ID'] = $fields['APP_ID'];
474
475 return $result;
476 }
477
484 public static function GetDeviceInfo($userId, $options = Array(), $appId = self::DEFAULT_APP_ID)
485 {
486 $result = [];
487 if (!is_array($userId))
488 {
489 $userId = [$userId];
490 }
491
492 foreach ($userId as $id)
493 {
494 $id = intval($id);
495 if ($id <= 0)
496 {
497 continue;
498 }
499
500 $result[$id] = [
501 'mode' => self::RECORD_NOT_FOUND,
502 'device' => [],
503 ];
504 }
505
506 if (empty($result))
507 {
508 return false;
509 }
510
511 $imInclude = \Bitrix\Main\Loader::includeModule('im');
512
514
515 $sago = Bitrix\Main\Application::getConnection()->getSqlHelper()->addSecondsToDateTime('-300');
516 $query->registerRuntimeField(new ExpressionField('SAGO', $sago));
517 $query->registerRuntimeField(new ExpressionField(
518 'IS_ONLINE_CUSTOM',
519 "CASE WHEN %s > %s THEN 'Y' ELSE 'N' END",
520 ['LAST_ACTIVITY_DATE', 'SAGO']
521 ));
522 $query
523 ->addSelect('ID')
524 ->addSelect('ACTIVE')
525 ->addSelect('EMAIL')
526 ->addSelect('IS_ONLINE_CUSTOM');
527
528 if ($imInclude)
529 {
530 $query->registerRuntimeField(new Reference(
531 'im',
532 \Bitrix\Im\Model\StatusTable::class,
533 ['=this.ID' => 'ref.USER_ID']
534 ));
535 $query
536 ->addSelect('im.IDLE', 'IDLE')
537 ->addSelect('im.DESKTOP_LAST_DATE', 'DESKTOP_LAST_DATE')
538 ->addSelect('im.MOBILE_LAST_DATE', 'MOBILE_LAST_DATE')
539 ;
540 }
541
542 $query->registerRuntimeField(new Reference(
543 'push',
544 \Bitrix\Pull\Model\PushTable::class,
545 ['=this.ID' => 'ref.USER_ID']
546 ));
547 $query->registerRuntimeField(new ExpressionField(
548 'HAS_MOBILE',
549 "CASE WHEN %s > 0 THEN 'Y' ELSE 'N' END",
550 ['push.USER_ID']
551 ));
552 $query
553 ->addSelect('HAS_MOBILE')
554 ->addSelect('push.APP_ID', 'APP_ID')
555 ->addSelect('push.UNIQUE_HASH', 'UNIQUE_HASH')
556 ->addSelect('push.DEVICE_TYPE', 'DEVICE_TYPE')
557 ->addSelect('push.DEVICE_TOKEN', 'DEVICE_TOKEN')
558 ->addSelect('push.VOIP_TYPE', 'VOIP_TYPE')
559 ->addSelect('push.VOIP_TOKEN', 'VOIP_TOKEN');
560
561 $query->addFilter('=ID', array_keys($result));
562 $queryResult = $query->exec();
563
564 while ($user = $queryResult->fetch())
565 {
566 $uniqueHashes[] = CPullPush::getUniqueHash($user["ID"], $appId);
567
568 if (in_array($user['UNIQUE_HASH'], $uniqueHashes) && $user['ACTIVE'] == 'Y')
569 {
570 $result[$user['ID']]['device'][] = [
571 'APP_ID' => $user['APP_ID'],
572 'USER_ID' => $user['ID'],
573 'DEVICE_TYPE' => $user['DEVICE_TYPE'],
574 'DEVICE_TOKEN' => $user['DEVICE_TOKEN'],
575 'VOIP_TYPE' => $user['VOIP_TYPE'],
576 'VOIP_TOKEN' => $user['VOIP_TOKEN'],
577 ];
578 }
579 else
580 {
581 continue;
582 }
583
584 if ($result[$user['ID']]['mode'] != self::RECORD_NOT_FOUND)
585 {
586 continue;
587 }
588
589 if ($user['HAS_MOBILE'] == 'N')
590 {
591 $result[$user['ID']]['mode'] = self::RECORD_NOT_FOUND;
592 $result[$user['ID']]['device'] = [];
593 continue;
594 }
595
596 if (isset($options['IMPORTANT']) && $options['IMPORTANT'] == 'Y')
597 {
598 $result[$user['ID']]['mode'] = self::SEND_IMMEDIATELY;
599 continue;
600 }
601
602 if (!\Bitrix\Pull\Push::getStatus($user['ID']))
603 {
604 $result[$user['ID']]['mode'] = self::RECORD_NOT_FOUND;
605 $result[$user['ID']]['device'] = [];
606 continue;
607 }
608
609 $isMobile = false;
610 $isOnline = false;
611 $isDesktop = false;
612 $isDesktopIdle = false;
613
614 if ($user['IS_ONLINE_CUSTOM'] == 'Y')
615 {
616 $isOnline = true;
617 }
618
619 if ($imInclude)
620 {
621 $user = CIMStatus::prepareLastDate($user);
622
623 $mobileLastDate = $user['MOBILE_LAST_DATE']? $user['MOBILE_LAST_DATE']->getTimestamp(): 0;
624 if ($mobileLastDate > 0 && $mobileLastDate + 300 > time())
625 {
626 $isMobile = true;
627 }
628
629 $isDesktop = CIMMessenger::CheckDesktopStatusOnline($user['ID']);
630 if ($isDesktop && $isOnline && is_object($user['IDLE']))
631 {
632 if ($user['IDLE']->getTimestamp() > 0 )
633 {
634 $isDesktopIdle = true;
635 }
636 }
637 }
638
639 $status = self::SEND_IMMEDIATELY;
640 if ($isMobile)
641 {
642 $status = self::SEND_IMMEDIATELY;
643 }
644 else if ($isOnline)
645 {
646 if (!\Bitrix\Pull\PushSmartfilter::getStatus($user['ID']))
647 {
648 $status = self::SEND_IMMEDIATELY_SILENT;
649 }
650 else
651 {
652 $status = self::SEND_DEFERRED;
653 if ($isDesktop)
654 {
655 $status = self::SEND_SKIP;
656 if ($isDesktopIdle)
657 {
658 $status = self::SEND_IMMEDIATELY;
659 }
660 }
661 else
662 {
663 $result[$user['ID']]['device'] = [];
664 }
665 }
666 }
667 $result[$user['ID']]['mode'] = $status;
668 }
669
670 return $result;
671 }
672
673 private function getAppMode(string $appId): string
674 {
675 return mb_strpos($appId, "_bxdev") > 0 ? "SANDBOX" : "PRODUCTION";
676 }
677
678 static private function getPureAppId($appId): string
679 {
680 return str_replace("_bxdev", "", $appId);
681 }
682
683 protected function shouldSendMessage($message)
684 {
685 if (!$message['USER_ID'])
686 {
687 return false;
688 }
689 $delegates = \Bitrix\Main\EventManager::getInstance()->findEventHandlers("pull", "ShouldMessageBeSent");
690 $shouldBeSent = true;
691 foreach ($delegates as $delegate)
692 {
693 $shouldBeSent = ExecuteModuleEventEx($delegate, [$message]);
694 if (!$shouldBeSent)
695 {
696 break;
697 }
698 }
699 return $shouldBeSent;
700 }
701
707 public function SendMessage(array $arMessages = [], array $arDevices = []): bool
708 {
709 if (empty($arMessages))
710 {
711 return false;
712 }
713
714 $uniqueHashes = [];
715 $arTmpMessages = [];
716 $arVoipMessages = [];
717 foreach ($arMessages as $message)
718 {
719 if (!$this->shouldSendMessage($message))
720 {
721 continue;
722 }
723 if($message["ADVANCED_PARAMS"]["isVoip"])
724 {
725 if (!array_key_exists("USER_" . $message["USER_ID"], $arVoipMessages))
726 {
727 $arVoipMessages["USER_" . $message["USER_ID"]] = [];
728 }
729 $arVoipMessages["USER_" . $message["USER_ID"]][] = htmlspecialcharsback($message);
730 }
731 else
732 {
733 if (!array_key_exists("USER_" . $message["USER_ID"], $arTmpMessages))
734 {
735 $arTmpMessages["USER_" . $message["USER_ID"]] = [];
736 }
737 $arTmpMessages["USER_" . $message["USER_ID"]][] = htmlspecialcharsback($message);
738 }
739
740 $hash = CPullPush::getUniqueHash($message["USER_ID"], $message["APP_ID"]);
741
742 if (!in_array($hash, $uniqueHashes))
743 {
744 $uniqueHashes[] = $hash;
745 }
746 }
747 if (empty($arDevices))
748 {
749 $arDevices = \Bitrix\Pull\Model\PushTable::getList([
750 'filter' => [
751 "=UNIQUE_HASH" => array_unique($uniqueHashes)
752 ]
753 ])->fetchAll();
754
755 if (empty($arDevices))
756 {
757 return false;
758 }
759 }
760
761 $arPushMessages = [];
762
763 foreach ($arDevices as $arDevice)
764 {
765 $arDevice["APP_ID"] = \Bitrix\Main\Config\Option::get("mobileapp", "app_id_replaced_".$arDevice["APP_ID"], $arDevice["APP_ID"]);
766 $mode = $this->getAppMode($arDevice["APP_ID"]);
767
768 $tmpMessage = $arTmpMessages["USER_" . $arDevice["USER_ID"]] ?? null;
769 $voipMessage = $arVoipMessages["USER_" . $arDevice["USER_ID"]] ?? null;
770
771 if(is_array($tmpMessage))
772 {
773 $tmpMessage = array_map(function($message) use ($arDevice) {
774 $message["APP_ID"] = self::getPureAppId($arDevice["APP_ID"]);
775 return $message;
776 }, $tmpMessage);
777
778 $deviceType = $arDevice["DEVICE_TYPE"];
779 $deviceToken = $arDevice["DEVICE_TOKEN"];
780 $filteredMessages = static::filterMessagesBeforeSend($tmpMessage, $deviceType, $deviceToken);
781 if(isset(static::$pushServices[$deviceType]) && count($filteredMessages) > 0)
782 {
783 $arPushMessages[$deviceType][$deviceToken] = [
784 "messages" => $filteredMessages,
785 "mode" => $mode
786 ];
787 }
788 }
789 if(is_array($voipMessage))
790 {
791 $voipMessage = array_map(function($message) use ($arDevice) {
792 $message["APP_ID"] = self::getPureAppId($arDevice["APP_ID"]);
793 return $message;
794 }, $voipMessage);
795 $deviceType = $arDevice["VOIP_TYPE"] && $arDevice["VOIP_TOKEN"] ? $arDevice["VOIP_TYPE"]: $arDevice["DEVICE_TYPE"];
796 $deviceToken = $arDevice["VOIP_TYPE"] && $arDevice["VOIP_TOKEN"] ? $arDevice["VOIP_TOKEN"] : $arDevice["DEVICE_TOKEN"];
797 $filteredMessages = static::filterMessagesBeforeSend($voipMessage, $deviceType, $deviceToken);
798 if(isset(static::$pushServices[$deviceType]) && count($filteredMessages) > 0)
799 {
800 $arPushMessages[$deviceType][$deviceToken] = [
801 "messages" => $filteredMessages,
802 "mode" => $mode
803 ];
804 }
805 }
806 }
807
808 if (empty($arPushMessages))
809 {
810 return false;
811 }
812
813 $batches = [];
814
815 $batchMessageCount = CPullOptions::GetPushMessagePerHit();
816 $useChunks = ($batchMessageCount > 0);
817 if(!$useChunks)
818 {
819 $batches[0] = "";
820 }
821 foreach (static::$pushServices as $serviceID => $serviceFields)
822 {
823 $className = $serviceFields["CLASS"];
824 if (empty($arPushMessages[$serviceID]))
825 {
826 continue;
827 }
828 // replace with check of interface implementation maybe
829 $service = new $className;
830 if (!($service instanceof PushService))
831 {
832 continue;
833 }
834
835 if(!$useChunks)
836 {
837 $batches[0] .= $service->getBatch($arPushMessages[$serviceID]);
838 }
839 else
840 {
841 $offset = 0;
842 $messages = null;
843 while($messages = array_slice($arPushMessages[$serviceID],$offset, $batchMessageCount))
844 {
845 if (!empty($service->getBatch($messages)))
846 {
847 $batches[] = $service->getBatch($messages);
848 }
849
850 $offset += count($messages);
851 }
852 }
853 }
854
855 foreach ($batches as $chunkBatch)
856 {
857 $this->sendBatch($chunkBatch);
858 }
859
860 return true;
861 }
862
863 private function sendBatch($batch)
864 {
865 if ($batch <> '')
866 {
868 Web\Http\Method::POST,
869 new Web\Uri($this->remoteProviderUrl . "?key=" . Application::getInstance()->getLicense()->getHashLicenseKey()),
870 null,
871 new Web\Http\FormStream([
872 "Action" => "SendMessage",
873 "MessageBody" => $batch
874 ])
875 );
876 $httpClient = new Web\HttpClient(["waitResponse" => false]);
877 $httpClient->sendAsyncRequest($request);
878
879 return true;
880 }
881
882 return false;
883 }
884
885 protected static function filterMessagesBeforeSend(array $messages, string $deviceType, string $deviceToken): array
886 {
887 foreach ($messages as $k => $message)
888 {
889 if (isset($message['ADVANCED_PARAMS']['filterCallback']) && is_callable($message['ADVANCED_PARAMS']['filterCallback']))
890 {
891 $filterResult = call_user_func_array(
892 $message['ADVANCED_PARAMS']['filterCallback'],
893 [
894 'message' => $message,
895 'deviceType' => $deviceType,
896 'deviceToken' => $deviceToken
897 ]
898 );
899 if (!$filterResult)
900 {
901 unset($messages[$k]);
902 }
903 else
904 {
905 unset($messages[$k]['ADVANCED_PARAMS']['filterCallback']);
906 }
907 }
908 }
909 return $messages;
910 }
911
912 public static function DeleteFromQueueBySubTag($userId, $tag, $appId = self::DEFAULT_APP_ID)
913 {
914 global $DB;
915 if ($tag == '' || intval($userId) == 0)
916 {
917 return false;
918 }
919
920 $strSql = "DELETE FROM b_pull_push_queue WHERE USER_ID = " . intval($userId) . " AND SUB_TAG = '" . $DB->ForSQL($tag) . "'";
921 $DB->Query($strSql);
922
923 \Bitrix\Pull\Push::add($userId, [
924 'module_id' => 'pull',
925 'push' => [
926 'advanced_params' => [
927 "notificationsToCancel" => [$tag],
928 ],
929 'send_immediately' => 'Y',
930 'app_id' => $appId
931 ]
932 ]);
933
934 return true;
935 }
936
937 public static function SendAgent()
938 {
939 global $DB;
940
941 if (!CPullOptions::GetPushStatus())
942 {
943 return false;
944 }
945
946 $count = 0;
947 $maxId = 0;
948 $pushLimit = 10;
949 $arPush = [];
950
951 $sqlDate = "";
952 if ($DB->type == "MYSQL" || $DB->type == "PGSQL")
953 {
954 $helper = \Bitrix\Main\Application::getConnection()->getSqlHelper();
955 $sqlDate = " WHERE DATE_CREATE < ".$helper->addSecondsToDateTime(-15);
956 }
957 elseif ($DB->type == "MSSQL")
958 {
959 $sqlDate = " WHERE DATE_CREATE < dateadd(SECOND, -15, getdate()) ";
960 }
961 elseif ($DB->type == "ORACLE")
962 {
963 $sqlDate = " WHERE DATE_CREATE < SYSDATE-(1/24/60/60*15) ";
964 }
965
966 $strSql = $DB->TopSql("SELECT ID, USER_ID, MESSAGE, PARAMS, ADVANCED_PARAMS, BADGE, APP_ID FROM b_pull_push_queue" . $sqlDate, 280);
967 $dbRes = $DB->Query($strSql);
968 while ($arRes = $dbRes->Fetch())
969 {
970 if ($arRes['BADGE'] == '')
971 {
972 $arRes['BADGE'] = \Bitrix\Pull\MobileCounter::get($arRes['USER_ID']);
973 }
974
975 try
976 {
977 $arRes['PARAMS'] = $arRes['PARAMS'] ? Bitrix\Main\Web\Json::decode($arRes['PARAMS']) : "";
978 }
979 catch (Exception $e)
980 {
981 $arRes['PARAMS'] = "";
982 }
983 if (is_array($arRes['PARAMS']))
984 {
985 if (isset($arRes['PARAMS']['CATEGORY']))
986 {
987 $arRes['CATEGORY'] = $arRes['PARAMS']['CATEGORY'];
988 unset($arRes['PARAMS']['CATEGORY']);
989 }
990 $arRes['PARAMS'] = Bitrix\Main\Web\Json::encode($arRes['PARAMS']);
991 }
992 try
993 {
994 $arRes['ADVANCED_PARAMS'] = $arRes['ADVANCED_PARAMS'] != '' ? Bitrix\Main\Web\Json::decode($arRes['ADVANCED_PARAMS']) : [];
995 }
996 catch (Exception $e)
997 {
998 $arRes['ADVANCED_PARAMS'] = [];
999 }
1000
1001 $arPush[$count][] = $arRes;
1002 if ($pushLimit <= count($arPush[$count]))
1003 {
1004 $count++;
1005 }
1006
1007 $maxId = max($maxId, $arRes['ID']);
1008 }
1009
1010 if ($maxId > 0)
1011 {
1012 $strSql = "DELETE FROM b_pull_push_queue WHERE ID <= " . $maxId;
1013 $DB->Query($strSql);
1014 }
1015
1016 $CPushManager = new CPushManager();
1017 foreach ($arPush as $arStack)
1018 {
1019 $CPushManager->SendMessage($arStack);
1020 }
1021
1022 $strSql = "SELECT COUNT(ID) CNT FROM b_pull_push_queue";
1023 $dbRes = $DB->Query($strSql);
1024 if ($arRes = $dbRes->Fetch())
1025 {
1026 global $pPERIOD;
1027 if ($arRes['CNT'] > 280)
1028 {
1029 $pPERIOD = 10;
1030 return "CPushManager::SendAgent();";
1031 }
1032 else
1033 {
1034 if ($arRes['CNT'] > 0)
1035 {
1036 $pPERIOD = 30;
1037 return "CPushManager::SendAgent();";
1038 }
1039 }
1040 }
1041
1042 return false;
1043 }
1044
1045 public function getServices()
1046 {
1047 return self::$pushServices;
1048 }
1049
1050 public function sendBadges($userId = null, $appId = self::DEFAULT_APP_ID)
1051 {
1052 return \Bitrix\Pull\MobileCounter::send($userId, $appId);
1053 }
1054}
$arParams
Определения access_dialog.php:21
$count
Определения admin_tab.php:4
$hash
Определения ajax_redirector.php:8
$type
Определения options.php:106
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 getConnection($name="")
Определения application.php:638
static get($moduleId, $name, $default="", $siteId=false)
Определения option.php:30
static getInstance()
Определения eventmanager.php:31
static includeModule($moduleName)
Определения loader.php:67
static getEntity()
Определения datamanager.php:65
static decode($data)
Определения json.php:50
static encode($data, $options=null)
Определения json.php:22
static get($userId=null)
Определения mobilecounter.php:41
static getServiceList()
Определения servicelist.php:13
Определения pull_push.php:19
static Update($ID, $arFields=Array())
Определения pull_push.php:89
static GetList($arOrder=[], $arFilter=[], $arSelect=[], $arNavStartParams=[])
Определения pull_push.php:29
static Add($arFields=Array())
Определения pull_push.php:58
static getUniqueHash($user_id, $app_id)
Определения pull_push.php:65
static Delete($ID=false)
Определения pull_push.php:102
Определения pull_push.php:125
__construct()
Определения pull_push.php:138
const SEND_IMMEDIATELY
Определения pull_push.php:126
const RECORD_NOT_FOUND
Определения pull_push.php:130
const SEND_IMMEDIATELY_SILENT
Определения pull_push.php:127
sendBadges($userId=null, $appId=self::DEFAULT_APP_ID)
Определения pull_push.php:1050
getServices()
Определения pull_push.php:1045
static GetDeviceInfo($userId, $options=Array(), $appId=self::DEFAULT_APP_ID)
Определения pull_push.php:484
static DeleteFromQueueByTag($userId, $tag, $appId=self::DEFAULT_APP_ID)
Определения pull_push.php:147
const SEND_DEFERRED
Определения pull_push.php:128
const DEFAULT_APP_ID
Определения pull_push.php:132
static SendAgent()
Определения pull_push.php:937
shouldSendMessage($message)
Определения pull_push.php:683
static array $pushServices
Определения pull_push.php:134
const SEND_SKIP
Определения pull_push.php:129
AddQueue($arParams)
Определения pull_push.php:176
static DeleteFromQueueBySubTag($userId, $tag, $appId=self::DEFAULT_APP_ID)
Определения pull_push.php:912
static filterMessagesBeforeSend(array $messages, string $deviceType, string $deviceToken)
Определения pull_push.php:885
SendMessage(array $arMessages=[], array $arDevices=[])
Определения pull_push.php:707
$options
Определения commerceml2.php:49
$arFields
Определения dblapprove.php:5
</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
if($ajaxMode) $ID
Определения get_user.php:27
global $DB
Определения cron_frame.php:29
$status
Определения session.php:10
if($NS['step']==6) if( $NS[ 'step']==7) if(COption::GetOptionInt('main', 'disk_space', 0) > 0) $info
Определения backup.php:924
ExecuteModuleEventEx($arEvent, $arParams=[])
Определения tools.php:5214
htmlspecialcharsback($str)
Определения tools.php:2693
GetModuleEvents($MODULE_ID, $MESSAGE_ID, $bReturnArray=false)
Определения tools.php:5177
Определения chain.php:3
Определения cookie.php:3
$user
Определения mysql_to_pgsql.php:33
$service
Определения payment.php:18
$message
Определения payment.php:8
if( $daysToExpire >=0 &&$daysToExpire< 60 elseif)( $daysToExpire< 0)
Определения prolog_main_admin.php:393
if(empty($signedUserToken)) $key
Определения quickway.php:257
</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
$eventManager
Определения include.php:412
$arRes
Определения options.php:104
$k
Определения template_pdf.php:567
$arFilter
Определения user_search.php:106
$dbRes
Определения yandex_detail.php:168
$fields
Определения yandex_run.php:501