Bitrix-D7 23.9
 
Загрузка...
Поиск...
Не найдено
sender.php
1<?php
2
3namespace Bitrix\Rest\Event;
4
15
23class Sender
24{
25 protected static $initialized = false;
26 protected static $forkSet = false;
27 protected static $queryData = array();
28
32 protected static $provider;
33
37 protected static $providerOffline;
38
39 protected static $defaultEventParams = array(
40 "category" => Sqs::CATEGORY_DEFAULT,
41 "sendAuth" => true,
42 "sendRefreshToken" => false,
43 );
44
52 public static function parseEventName($name)
53 {
54 $res = array();
55 list($res['MODULE_ID'], $res['EVENT']) = explode('__', $name);
56
57 $res['EVENT'] = str_replace('_0_', '\\', $res['EVENT']);
58 $res['EVENT'] = str_replace('_1_', '::', $res['EVENT']);
59
60 return $res;
61 }
62
69 public static function bind($moduleId, $eventName)
70 {
71 $eventManager = EventManager::getInstance();
72 $eventManager->registerEventHandler($moduleId, $eventName, "rest", "\\Bitrix\\Rest\\Event\\Callback", static::getHandlerName($moduleId, $eventName));
73 }
74
81 public static function unbind($moduleId, $eventName)
82 {
83 $eventManager = EventManager::getInstance();
84 $eventManager->unRegisterEventHandler($moduleId, $eventName, "rest", "\\Bitrix\\Rest\\Event\\Callback", static::getHandlerName($moduleId, $eventName));
85
86 /* compatibility */
87 $eventManager->unRegisterEventHandler($moduleId, $eventName, "rest", "CRestEventCallback", static::getHandlerName($moduleId, $eventName));
88 }
89
95 public static function getDefaultEventParams()
96 {
97 return static::$defaultEventParams;
98 }
99
110 public static function getAuth($appId, $userId, array $additionalData = array(), array $additional = array())
111 {
112 $auth = null;
113
114 $application = AppTable::getByClientId($appId);
115 if($application)
116 {
117 if($userId > 0 && $additional["sendAuth"])
118 {
119 if(OAuthService::getEngine()->isRegistered())
120 {
121 $auth = Application::getAuthProvider()->get($application['CLIENT_ID'], $application['SCOPE'], $additionalData, $userId);
122
123 if(is_array($auth) && !$additional["sendRefreshToken"])
124 {
125 unset($auth['refresh_token']);
126 }
127 }
128 }
129
130 if(!is_array($auth))
131 {
132 $auth = array(
133 "domain" => Context::getCurrent()->getRequest()->getHttpHost(),
134 "member_id" => \CRestUtil::getMemberId()
135 );
136 }
137
138 $auth["application_token"] = \CRestUtil::getApplicationToken($application);
139 }
140
141 return $auth;
142 }
143
153 public static function call($handlersList)
154 {
155 global $USER;
156
157 $offlineEvents = array();
158 $logger = LoggerManager::getInstance()->getLogger();
159 if ($logger)
160 {
161 $logger->debug(
162 "\n{delimiter}\n"
163 . "{date} - {host}\n{delimiter}\n"
164 . " Sender::call() starts.\n"
165 . "{handlersList}\n{delimiter} ",
166 [
167 'handlersList' => $handlersList,
168 ]
169 );
170 }
171
172 foreach($handlersList as $handlerInfo)
173 {
174 $handler = $handlerInfo[0];
175 $data = $handlerInfo[1];
176 $additional = $handlerInfo[2];
177
178 foreach(static::$defaultEventParams as $key => $value)
179 {
180 if(!isset($additional[$key]))
181 {
182 $additional[$key] = $value;
183 }
184 }
185
186 $session = Session::get();
187 if(!$session)
188 {
189 if ($logger)
190 {
191 $logger->debug(
192 "\n{delimiter}\n"
193 . "{date} - {host}\n{delimiter}\n"
194 . "Session ttl exceeded {session}.\n",
195 [
196 'session' => $session,
197 ]
198 );
199 }
200
201 // ttl exceeded, kill session
202 return;
203 }
204
205 $userId = $handler['USER_ID'] > 0
206 ? $handler['USER_ID']
207 : (
208 // USER object can be null if event runs in BP or agent
209 is_object($USER) && $USER->isAuthorized()
210 ? $USER->getId()
211 : 0
212 );
213
214 $authData = null;
215 if($handler['APP_ID'] > 0)
216 {
217 $dbRes = AppTable::getById($handler['APP_ID']);
218 $application = $dbRes->fetch();
219
220 $appStatus = \Bitrix\Rest\AppTable::getAppStatusInfo($application, '');
221 if($appStatus['PAYMENT_ALLOW'] === 'Y')
222 {
223 $authData = array(
224 Session::PARAM_SESSION => $session,
225 Auth::PARAM_LOCAL_USER => $userId,
226 "application_token" => \CRestUtil::getApplicationToken($application),
227 );
228 }
229
230 if($handler['EVENT_HANDLER'] <> '')
231 {
232 UsageStatTable::logEvent($application['CLIENT_ID'], $handler['EVENT_NAME']);
233 }
234 }
235 else
236 {
237 $application = array('CLIENT_ID' => null);
238
239 $authData = array(
240 Session::PARAM_SESSION => $session,
241 Auth::PARAM_LOCAL_USER => $userId,
242 'application_token' => $handler['APPLICATION_TOKEN'],
243 );
244 }
245
246 if($authData)
247 {
248 if($handler['EVENT_HANDLER'] <> '')
249 {
250 self::$queryData[] = Sqs::queryItem(
251 $application['CLIENT_ID'],
252 $handler['EVENT_HANDLER'],
253 array(
254 'event' => $handler['EVENT_NAME'],
255 'data' => $data,
256 'ts' => time(),
257 ),
258 $authData,
259 $additional
260 );
261 }
262 else
263 {
264 $offlineEvents[] = array(
265 'HANDLER' => $handler,
266 'APPLICATION' => $application,
267 'AUTH' => $authData,
268 'DATA' => $data,
269 );
270 }
271 }
272 }
273
274 if (count($offlineEvents) > 0)
275 {
276 if ($logger)
277 {
278 $logger->debug(
279 "\n{delimiter}\n"
280 . "{date} - {host}\n{delimiter}\n"
281 . "Event count: {eventCount}\n{delimiter}"
282 . "Offline event list:\n"
283 . "{offlineEvents}",
284 [
285 'eventCount' => count($offlineEvents),
286 'offlineEvents' => $offlineEvents,
287 ]
288 );
289 }
290 static::getProviderOffline()->send($offlineEvents);
291 }
292
293 if (count(static::$queryData) > 0 && !static::$forkSet)
294 {
295 if ($logger)
296 {
297 $logger->debug(
298 "\n{delimiter}\n"
299 . "{date} - {host}\n{delimiter}\n"
300 . "Registers send event background job.\n"
301 . "count: {eventCount}",
302 [
303 'eventCount' => count(static::$queryData),
304 ]
305 );
306 }
307 \Bitrix\Main\Application::getInstance()->addBackgroundJob(array(__CLASS__, "send"));
308 static::$forkSet = true;
309 }
310 }
311
315 public static function send()
316 {
317 $logger = LoggerManager::getInstance()->getLogger();
318 if ($logger)
319 {
320 $logger->debug(
321 "\n{delimiter}\n"
322 . "{date} - {host}\n{delimiter}\n"
323 . "Starts method Sender::send()\n"
324 . "count: {eventCount}"
325 . "Event list:\n"
326 . "{eventList}",
327 [
328 'eventCount' => count(static::$queryData),
329 'eventList' => static::$queryData,
330 ]
331 );
332 }
333 if (count(self::$queryData) > 0)
334 {
335 UsageStatTable::finalize();
336 static::getProvider()->send(self::$queryData);
337 self::$queryData = array();
338 }
339 }
340
344 public static function getProvider()
345 {
346 static::initialize();
347
348 if(!static::$provider)
349 {
350 static::$provider = static::getDefaultProvider();
351 }
352
353 return static::$provider;
354 }
355
359 public static function setProvider(ProviderInterface $provider)
360 {
361 static::$provider = $provider;
362 }
363
364 protected static function getDefaultProvider()
365 {
366 return ProviderOAuth::instance();
367 }
368
372 public static function getProviderOffline()
373 {
374 static::initialize();
375
376 if(!static::$providerOffline)
377 {
378 static::$providerOffline = static::getDefaultProviderOffline();
379 }
380
381 return static::$providerOffline;
382 }
383
387 public static function setProviderOffline(ProviderOfflineInterface $providerOffline)
388 {
389 static::$providerOffline = $providerOffline;
390 }
391
392 protected static function getDefaultProviderOffline()
393 {
394 return ProviderOffline::instance();
395 }
396
397 protected static function initialize()
398 {
399 if(!static::$initialized)
400 {
401 static::$initialized = true;
402
403 $event = new Event('rest', 'onEventManagerInitialize');
404 $event->send();
405 }
406 }
407
408 protected static function getHandlerName($moduleId, $eventName)
409 {
410 // \Bitrix\Rest\EventTable::on
411 if(mb_strpos($eventName, '::') >= 0)
412 {
413 $handlerName = $moduleId.'__'.ToUpper(str_replace(array("\\", '::'), array('_0_', '_1_'), $eventName));
414 }
415 else
416 {
417 $handlerName = $moduleId.'__'.ToUpper($eventName);
418 }
419
420 return $handlerName;
421 }
422}
static getCurrent()
Definition context.php:241
static bind($moduleId, $eventName)
Definition sender.php:69
static parseEventName($name)
Definition sender.php:52
static getHandlerName($moduleId, $eventName)
Definition sender.php:408
static setProviderOffline(ProviderOfflineInterface $providerOffline)
Definition sender.php:387
static getAuth($appId, $userId, array $additionalData=array(), array $additional=array())
Definition sender.php:110
static getDefaultEventParams()
Definition sender.php:95
static getProviderOffline()
Definition sender.php:372
static call($handlersList)
Definition sender.php:153
static unbind($moduleId, $eventName)
Definition sender.php:81
static getDefaultProviderOffline()
Definition sender.php:392
static setProvider(ProviderInterface $provider)
Definition sender.php:359
static getDefaultProvider()
Definition sender.php:364