1C-Bitrix 25.700.0
Загрузка...
Поиск...
Не найдено
sender.php
См. документацию.
1<?php
2
3namespace Bitrix\Rest\Event;
4
5use Bitrix\Main\Context;
6use Bitrix\Main\Event;
7use Bitrix\Main\EventManager;
8use Bitrix\Rest\Application;
9use Bitrix\Rest\AppTable;
10use Bitrix\Rest\OAuth\Auth;
11use Bitrix\Rest\OAuthService;
12use Bitrix\Rest\Sqs;
13use Bitrix\Rest\Tools\Diagnostics\Event\Logger;
14use Bitrix\Rest\Tools\Diagnostics\Event\LogType;
15use Bitrix\Rest\UsageStatTable;
16use Bitrix\Rest\Tools\Diagnostics\LoggerManager;
17
25class Sender
26{
27 protected static $initialized = false;
28 protected static $forkSet = false;
29 protected static $queryData = array();
30
34 protected static $provider;
35
39 protected static $providerOffline;
40
41 protected static $defaultEventParams = array(
42 "category" => Sqs::CATEGORY_DEFAULT,
43 "sendAuth" => true,
44 "sendRefreshToken" => false,
45 );
46
47 protected static array $appData = [];
48
56 public static function parseEventName($name)
57 {
58 $res = array();
59 [$res['MODULE_ID'], $res['EVENT']] = explode('__', $name);
60
61 $res['EVENT'] = str_replace('_0_', '\\', $res['EVENT']);
62 $res['EVENT'] = str_replace('_1_', '::', $res['EVENT']);
63
64 return $res;
65 }
66
73 public static function bind($moduleId, $eventName)
74 {
76 $eventManager->registerEventHandler($moduleId, $eventName, "rest", "\\Bitrix\\Rest\\Event\\Callback", static::getHandlerName($moduleId, $eventName));
77 }
78
85 public static function unbind($moduleId, $eventName)
86 {
88 $eventManager->unRegisterEventHandler($moduleId, $eventName, "rest", "\\Bitrix\\Rest\\Event\\Callback", static::getHandlerName($moduleId, $eventName));
89
90 /* compatibility */
91 $eventManager->unRegisterEventHandler($moduleId, $eventName, "rest", "CRestEventCallback", static::getHandlerName($moduleId, $eventName));
92 }
93
99 public static function getDefaultEventParams()
100 {
101 return static::$defaultEventParams;
102 }
103
114 public static function getAuth($appId, $userId, array $additionalData = array(), array $additional = array())
115 {
116 $auth = null;
117
119 if($application)
120 {
121 if($userId > 0 && $additional["sendAuth"])
122 {
123 if(OAuthService::getEngine()->isRegistered())
124 {
125 $auth = Application::getAuthProvider()->get($application['CLIENT_ID'], $application['SCOPE'], $additionalData, $userId);
126
127 if(is_array($auth) && !$additional["sendRefreshToken"])
128 {
129 unset($auth['refresh_token']);
130 }
131 }
132 }
133
134 if(!is_array($auth))
135 {
136 $auth = array(
137 "domain" => Context::getCurrent()->getRequest()->getHttpHost(),
138 "member_id" => \CRestUtil::getMemberId()
139 );
140 }
141
142 $auth["application_token"] = \CRestUtil::getApplicationToken($application);
143 }
144
145 return $auth;
146 }
147
157 public static function call($handlersList)
158 {
159 global $USER;
160
161 $offlineEvents = array();
162 LoggerManager::getInstance()->getLogger()?->debug(
163 "\n{delimiter}\n"
164 . "{date} - {host}\n{delimiter}\n"
165 . " Sender::call() starts.\n"
166 . "{handlersList}\n{delimiter} ", [
167 'handlersList' => $handlersList,
168 'MESSAGE' => LogType::SENDER_CALL_START->value,
169 ]);
170
171 foreach($handlersList as $handlerInfo)
172 {
173 $handler = $handlerInfo[0];
174 $data = $handlerInfo[1];
175 $additional = $handlerInfo[2];
176
177 foreach(static::$defaultEventParams as $key => $value)
178 {
179 if(!isset($additional[$key]))
180 {
181 $additional[$key] = $value;
182 }
183 }
184
185 $session = Session::get();
186 if(!$session)
187 {
188 LoggerManager::getInstance()->getLogger()?->info(
189 "\n{delimiter}\n"
190 . "{date} - {host}\n{delimiter}\n"
191 . "Session ttl exceeded {session}.\n", [
192 'session' => $session,
193 'MESSAGE' => LogType::CYCLIC_CALL_LIMIT->value,
194 ]);
195
196 // ttl exceeded, kill session
197 return;
198 }
199
200 $userId = $handler['USER_ID'] > 0
201 ? $handler['USER_ID']
202 : (
203 // USER object can be null if event runs in BP or agent
204 is_object($USER) && $USER->isAuthorized()
205 ? $USER->getId()
206 : 0
207 );
208
209 $authData = null;
210 if(isset($handler['APP_ID']) && $handler['APP_ID'] > 0)
211 {
212 if (isset(static::$appData[$handler['APP_ID']]) && is_array(static::$appData[$handler['APP_ID']]))
213 {
214 $application = static::$appData[$handler['APP_ID']];
215 }
216 else
217 {
218 $select = [
219 'CLIENT_ID',
220 'ID',
221 'CODE',
222 'STATUS',
223 'DATE_FINISH',
224 'IS_TRIALED',
225 'URL_DEMO',
226 'APPLICATION_TOKEN',
227 'CLIENT_SECRET',
228 'SHARED_KEY',
229 ];
230 $dbRes = AppTable::getByPrimary($handler['APP_ID'], ['select' => $select]);
231 $application = $dbRes->fetch();
232 static::$appData[$handler['APP_ID']] = $application;
233 }
234
235
237 if($appStatus['PAYMENT_ALLOW'] === 'Y')
238 {
239 $authData = array(
240 Session::PARAM_SESSION => $session,
241 Auth::PARAM_LOCAL_USER => $userId,
242 "application_token" => \CRestUtil::getApplicationToken($application),
243 );
244 }
245
246 if($handler['EVENT_HANDLER'] <> '')
247 {
248 UsageStatTable::logEvent($application['CLIENT_ID'], $handler['EVENT_NAME']);
249 }
250 }
251 else
252 {
253 $application = array('CLIENT_ID' => null);
254
255 $authData = array(
256 Session::PARAM_SESSION => $session,
257 Auth::PARAM_LOCAL_USER => $userId,
258 'application_token' => $handler['APPLICATION_TOKEN'],
259 );
260 }
261
262 if($authData)
263 {
264 if ($handler['EVENT_HANDLER'] !== '')
265 {
266 $eventBufferAddResult = Buffer::getInstance()->addEvent([
267 $application['CLIENT_ID'],
268 $handler['EVENT_HANDLER'],
269 $handler['EVENT_NAME'],
270 $authData,
271 $data,
272 $additional
273 ]);
274
275 if ($eventBufferAddResult->isSuccess())
276 {
277 self::$queryData[] = Sqs::queryItem(
278 $application['CLIENT_ID'],
279 $handler['EVENT_HANDLER'],
280 array(
281 'event' => $handler['EVENT_NAME'],
282 'event_handler_id' => $handler['ID'],
283 'data' => $data,
284 'ts' => time(),
285 ),
286 $authData,
287 $additional
288 );
289 }
290 }
291 else
292 {
293 $offlineEvents[] = array(
294 'HANDLER' => $handler,
295 'APPLICATION' => $application,
296 'AUTH' => $authData,
297 'DATA' => $data,
298 );
299 }
300 }
301 }
302
303 if (count($offlineEvents) > 0)
304 {
305 LoggerManager::getInstance()->getLogger()?->debug(
306 "\n{delimiter}\n"
307 . "{date} - {host}\n{delimiter}\n"
308 . "Event count: {eventCount}\n{delimiter}"
309 . "Offline event list:\n"
310 . "{offlineEvents}", [
311 'eventCount' => count($offlineEvents),
312 'offlineEvents' => $offlineEvents,
313 'MESSAGE' => LogType::READY_OFFLINE_EVENT_LIST->value,
314 ]);
315 static::getProviderOffline()->send($offlineEvents);
316 }
317
318 if (count(static::$queryData) > 0)
319 {
320 self::enqueueBackgroundJob();
321 }
322 }
323
327 public static function send(): void
328 {
329 LoggerManager::getInstance()->getLogger()?->debug(
330 "\n{delimiter}\n"
331 . "{date} - {host}\n{delimiter}\n"
332 . "Starts method Sender::send()\n"
333 . "count: {eventCount}"
334 . "Event list:\n"
335 . "{eventList}", [
336 'eventCount' => count(static::$queryData),
337 'eventList' => static::$queryData,
338 'MESSAGE' => LogType::SENDER_SEND_START->value,
339 ]);
340 if (count(self::$queryData) > 0)
341 {
343 static::getProvider()->send(self::$queryData);
344 self::$queryData = [];
345 self::$forkSet = false;
346 }
347 }
348
349 public static function queueEvent($queryItem)
350 {
351 self::$queryData[] = $queryItem;
352 self::enqueueBackgroundJob();
353 }
354
358 public static function getProvider()
359 {
360 static::initialize();
361
362 if(!static::$provider)
363 {
364 static::$provider = static::getDefaultProvider();
365 }
366
367 return static::$provider;
368 }
369
374 {
375 static::$provider = $provider;
376 }
377
378 protected static function getDefaultProvider()
379 {
381 }
382
386 public static function getProviderOffline()
387 {
388 static::initialize();
389
390 if(!static::$providerOffline)
391 {
392 static::$providerOffline = static::getDefaultProviderOffline();
393 }
394
395 return static::$providerOffline;
396 }
397
402 {
403 static::$providerOffline = $providerOffline;
404 }
405
406 protected static function enqueueBackgroundJob(): void
407 {
408 if (!static::$forkSet)
409 {
410 LoggerManager::getInstance()->getLogger()?->debug(
411 "\n{delimiter}\n"
412 . "{date} - {host}\n{delimiter}\n"
413 . "Registers the background job to send the event.\n"
414 . "count: {eventCount}", [
415 'eventCount' => count(static::$queryData),
416 'MESSAGE' => LogType::READY_ONLINE_EVENT_LIST->value,
417 ]);
419 $application->addBackgroundJob(
420 job: [__CLASS__, 'send'],
421 priority: $application::JOB_PRIORITY_LOW
422 );
423 static::$forkSet = true;
424 }
425 }
426
427 protected static function getDefaultProviderOffline()
428 {
430 }
431
432 protected static function initialize()
433 {
434 if(!static::$initialized)
435 {
436 static::$initialized = true;
437
438 $event = new Event('rest', 'onEventManagerInitialize');
439 $event->send();
440 }
441 }
442
443 protected static function getHandlerName($moduleId, $eventName)
444 {
445 // \Bitrix\Rest\EventTable::on
446 if(mb_strpos($eventName, '::') >= 0)
447 {
448 $handlerName = $moduleId.'__'.mb_strtoupper(str_replace(array("\\", '::'), array('_0_', '_1_'), $eventName));
449 }
450 else
451 {
452 $handlerName = $moduleId.'__'.mb_strtoupper($eventName);
453 }
454
455 return $handlerName;
456 }
457}
if(!is_object($USER)||! $USER->IsAuthorized()) $userId
Определения check_mail.php:18
static getInstance()
Определения application.php:98
static getInstance()
Определения eventmanager.php:31
static getAppStatusInfo($app, $detailUrl)
Определения app.php:713
static getByClientId($clientId)
Определения app.php:967
static getAuthProvider()
Определения application.php:19
static getInstance()
Определения buffer.php:13
static instance()
Определения provideroauth.php:17
static queueEvent($queryItem)
Определения sender.php:349
static bind($moduleId, $eventName)
Определения sender.php:73
static initialize()
Определения sender.php:432
static $initialized
Определения sender.php:27
static parseEventName($name)
Определения sender.php:56
static getHandlerName($moduleId, $eventName)
Определения sender.php:443
static array $appData
Определения sender.php:47
static send()
Определения sender.php:327
static $defaultEventParams
Определения sender.php:41
static setProviderOffline(ProviderOfflineInterface $providerOffline)
Определения sender.php:401
static getAuth($appId, $userId, array $additionalData=array(), array $additional=array())
Определения sender.php:114
static $queryData
Определения sender.php:29
static $forkSet
Определения sender.php:28
static $providerOffline
Определения sender.php:39
static getProvider()
Определения sender.php:358
static getDefaultEventParams()
Определения sender.php:99
static $provider
Определения sender.php:34
static getProviderOffline()
Определения sender.php:386
static call($handlersList)
Определения sender.php:157
static enqueueBackgroundJob()
Определения sender.php:406
static unbind($moduleId, $eventName)
Определения sender.php:85
static getDefaultProviderOffline()
Определения sender.php:427
static setProvider(ProviderInterface $provider)
Определения sender.php:373
static getDefaultProvider()
Определения sender.php:378
const PARAM_SESSION
Определения session.php:13
static getEngine()
Определения oauthservice.php:49
static queryItem($clientId, $url, $data, array $authData=array(), array $additional=array())
Определения sqs.php:18
const CATEGORY_DEFAULT
Определения sqs.php:11
static finalize()
Определения usagestat.php:374
static logEvent($clientId, $eventName)
Определения usagestat.php:230
$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
$auth
Определения get_user.php:29
$moduleId
$select
Определения iblock_catalog_list.php:194
global $USER
Определения csv_new_run.php:40
$application
Определения bitrix.php:23
$name
Определения menu_edit.php:35
$event
Определения prolog_after.php:141
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
$eventManager
Определения include.php:412
$dbRes
Определения yandex_detail.php:168