Bitrix-D7 23.9
 
Загрузка...
Поиск...
Не найдено
fuser.php
1<?php
8namespace Bitrix\Sale;
9
10use Bitrix\Main;
16
17class Fuser
18{
19 protected const SESSION_USER_ID = 'SALE_USER_ID';
20 protected const COOKIE_USER_ID = 'SALE_UID';
21
22 function __construct()
23 {
24
25 }
26
33 public static function getId($skipCreate = false): ?int
34 {
35 $id = static::getIdFromSession();
36 if ($id !== null)
37 {
38 return $id;
39 }
40
41 $filter = static::getFilterFromCookie(static::getIdFromCookie());
42 if ($filter !== null)
43 {
44 $id = static::getIdByFilter($filter);
45 }
46 if ($id === null)
47 {
48 $id = static::getIdByCurrentUser();
49 }
50 if ($id !== null)
51 {
52 $internalResult = static::update($id);
53 if (!$internalResult->isSuccess())
54 {
55 $id = null;
56 }
57 unset($internalResult);
58 }
59
60 if ($id === null && !$skipCreate)
61 {
62 $options = [];
63 if (
64 self::getCurrentUserId() === null
65 && self::isSaveAnonymousUserCookie()
66 )
67 {
68 $options['save'] = true;
69 }
70 $internalResult = static::add($options);
71 if ($internalResult->isSuccess())
72 {
73 $id = $internalResult->getId();
74 }
75 unset($internalResult);
76 }
77
78 return $id;
79 }
80
81 public static function refreshSessionCurrentId(): ?int
82 {
83 $id = static::getIdFromSession();
84 if ($id !== null)
85 {
86 return $id;
87 }
88
89 return static::getId(true);
90 }
91
97 public static function getCode(): int
98 {
99 $result = static::getRegeneratedId();
100
101 return $result ?? 0;
102 }
103
109 public static function getRegeneratedId(): ?int
110 {
111 $userId = static::getCurrentUserId();
112 if ($userId === null)
113 {
114 return null;
115 }
116 $id = static::getIdByFilter([
117 '=USER_ID' => $userId,
118 ]);
119 if ($id === null)
120 {
121 return null;
122 }
123
124 $userCode = static::generateCode();
125
127 $internalResult = static::save(
128 $id,
129 [
130 'CODE' => $userCode,
131 ]
132 );
133 if (!$internalResult->isSuccess())
134 {
135 return null;
136 }
137
138 $cookieValue = (static::isEncodeCookie() ? $userCode : (string)$id);
139 static::setIdToCookie($cookieValue);
140 static::setIdToSession($id);
141
142 return $id;
143 }
144
151 public static function getIdByUserId($userId)
152 {
153 $userId = (int)$userId;
154 $id = static::getIdByFilter([
155 '=USER_ID' => (int)$userId,
156 ]);
157 if ($id === null)
158 {
159 $internalResult = static::createForUserId($userId);
160 if ($internalResult->isSuccess())
161 {
162 $id = (int)$internalResult->getId();
163 }
164 unset($internalResult);
165 }
166
167 return $id === null ? false : $id;
168 }
169
177 public static function getUserIdById($fuserId): int
178 {
179 $fuserId = (int)$fuserId;
180 if ($fuserId <= 0)
181 {
182 return 0;
183 }
184 $row = Internals\FuserTable::getRow([
185 'select' => [
186 'ID',
187 'USER_ID',
188 ],
189 'filter' => [
190 '=ID' => $fuserId,
191 ],
192 'order' => [
193 'ID' => 'DESC',
194 ],
195 ]);
196 return (int)($row['USER_ID'] ?? 0);
197 }
198
205 public static function deleteOld($days)
206 {
207 $expired = new Main\Type\DateTime();
208 $expired->add('-'.$days.' days');
209 $expiredValue = $expired->format('Y-m-d H:i:s');
210
212 $connection = Main\Application::getConnection();
213 $sqlHelper = $connection->getSqlHelper();
214
215 $query = "DELETE FROM b_sale_fuser WHERE
216 b_sale_fuser.DATE_UPDATE < ".$sqlHelper->getDateToCharFunction("'".$expiredValue."'")."
217 AND b_sale_fuser.USER_ID IS NULL
218 AND b_sale_fuser.id NOT IN (select FUSER_ID from b_sale_basket)";
219 $connection->queryExecute($query);
220 }
221
228 protected static function createForUserId(int $userId): ORM\Data\AddResult
229 {
230 $currentTime = new Main\Type\DateTime();
231
233 $result = static::save(
234 null,
235 [
236 'DATE_INSERT' => $currentTime,
237 'DATE_UPDATE' => $currentTime,
238 'USER_ID' => $userId,
239 'CODE' => static::generateCode(),
240 ]
241 );
242
243 return $result;
244 }
245
253 protected static function getSession(): ?Session
254 {
256 $session = Application::getInstance()->getSession();
257 if (!$session->isAccessible())
258 {
259 return null;
260 }
261
262 return $session;
263 }
264
265 protected static function isEncodeCookie(): bool
266 {
267 return Option::get('sale', 'encode_fuser_id') === 'Y';
268 }
269
270 protected static function isSecureCookie(): bool
271 {
272 return
273 Option::get('sale', 'use_secure_cookies') === 'Y'
274 && Main\Context::getCurrent()->getRequest()->isHttps()
275 ;
276 }
277
278 protected static function isSaveAnonymousUserCookie(): bool
279 {
280 return Option::get('sale', 'save_anonymous_fuser_cookie') === 'Y';
281 }
282
283 protected static function getIdFromSession(): ?int
284 {
285 $session = static::getSession();
286 if ($session === null)
287 {
288 return null;
289 }
290 if (!$session->has(self::SESSION_USER_ID))
291 {
292 return null;
293 }
294 $rawValue = $session->get(self::SESSION_USER_ID);
295 unset($session);
296
297 $value = (int)$rawValue;
298 $rawValue = (string)$rawValue;
299 if ((string)$value !== $rawValue)
300 {
301 $value = 0;
302 }
303
304 return ($value > 0 ? $value : null);
305 }
306
307 protected static function setIdToSession(int $id): void
308 {
309 $session = static::getSession();
310 if ($session === null)
311 {
312 return;
313 }
314 if ($id <= 0)
315 {
316 return;
317 }
318 $session->set(self::SESSION_USER_ID, $id);
319 }
320
321 protected static function clearSession(): void
322 {
323 $session = static::getSession();
324 if ($session === null)
325 {
326 return;
327 }
328 $session->remove(self::SESSION_USER_ID);
329 }
330
331 protected static function getIdFromCookie(): ?string
332 {
333 $request = Main\Context::getCurrent()->getRequest();
334
335 return $request->getCookie(self::COOKIE_USER_ID);
336 }
337
338 protected static function setIdToCookie(string $id): void
339 {
340 $cookie = new Main\Web\Cookie(self::COOKIE_USER_ID, $id, null);
341 $cookie
342 ->setSecure(static::isSecureCookie())
343 ->setHttpOnly(false)
344 ->setSpread(Main\Web\Cookie::SPREAD_DOMAIN | Main\Web\Cookie::SPREAD_SITES)
345 ;
346
347 $response = Main\Context::getCurrent()->getResponse();
348
349 $response->addCookie($cookie);
350
351 unset($response);
352 unset($cookie);
353 }
354
355 protected static function clearCookie(): void
356 {
357 static::setIdToCookie('0');
358 }
359
360 protected static function getFilterFromCookie(?string $cookie): ?array
361 {
362 if ($cookie === null || $cookie === '')
363 {
364 return null;
365 }
366
367 $filter = [];
368 if (static::isEncodeCookie())
369 {
370 $filter = [
371 '=CODE' => $cookie,
372 ];
373 }
374 else
375 {
376 $cookie = (int)$cookie;
377 if ($cookie > 0)
378 {
379 $filter = [
380 '=ID' => $cookie,
381 ];
382 }
383 }
384
385 return (!empty($filter) ? $filter : null);
386 }
387
388 protected static function getIdByFilter(array $filter): ?int
389 {
390 $row = Internals\FuserTable::getRow([
391 'select' => [
392 'ID',
393 ],
394 'filter' => $filter,
395 'order' => [
396 'ID' => 'DESC',
397 ]
398 ]);
399 $result = (int)($row['ID'] ?? 0);
400
401 return $result > 0 ? $result: null;
402 }
403
404 protected static function getIdByCurrentUser(): ?int
405 {
406 $userId = self::getCurrentUserId();
407 if ($userId === null)
408 {
409 return null;
410 }
411
412 return static::getIdByFilter([
413 '=USER_ID' => $userId,
414 ]);
415 }
416
417 private static function getCurrentUserId(): ?int
418 {
419 global $USER;
420
421 if (!(
422 isset($USER)
423 && $USER instanceof \CUser
424 ))
425 {
426 return null;
427 }
428
429 $userId = (int)$USER->GetID();
430
431 return $userId > 0 ? $userId : null;
432 }
433
434 protected static function generateCode(): string
435 {
436 return md5(time() . Main\Security\Random::getString(10, true));
437 }
438
439 public static function add(array $options = []): Result
440 {
441 $result = new Result();
442
443 $currentTime = new Main\Type\DateTime();
444 $userCode = static::generateCode();
445 $currentUserId = self::getCurrentUserId();
446
447 $options['update'] ??= true;
448 if (!is_bool($options['update']))
449 {
450 $options['update'] = true;
451 }
452 $options['save'] ??= false;
453 if (!is_bool($options['save']))
454 {
455 $options['save'] = false;
456 }
457
459 $internalResult = static::save(
460 null,
461 [
462 'DATE_INSERT' => $currentTime,
463 'DATE_UPDATE' => $currentTime,
464 'USER_ID' => $currentUserId,
465 'CODE' => $userCode,
466 ]
467 );
468 if (!$internalResult->isSuccess())
469 {
470 $result->addErrors($internalResult->getErrors());
471
472 return $result;
473 }
474
475 $id = (int)$internalResult->getId();
476 if (
477 $options['save']
478 && $options['update']
479 && ($currentUserId !== null || self::isSaveAnonymousUserCookie())
480 )
481 {
482 $cookieValue = (static::isEncodeCookie() ? $userCode : (string)$id);
483 static::setIdToCookie($cookieValue);
484 }
485 static::setIdToSession($id);
486 $result->setId($id);
487
488 return $result;
489 }
490
491 public static function update(int $id, array $options = []): Result
492 {
493 $result = new Result();
494
495 if ($id <= 0)
496 {
497 return $result;
498 }
499
500 $options['update'] ??= true;
501 if (!is_bool($options['update']))
502 {
503 $options['update'] = true;
504 }
505 $options['save'] ??= false;
506 if (!is_bool($options['save']))
507 {
508 $options['save'] = false;
509 }
510
511 $fuser = Internals\FuserTable::getRow([
512 'select' => [
513 'ID',
514 'USER_ID',
515 'CODE'
516 ],
517 'filter' => [
518 '=ID' => $id,
519 ]
520 ]);
521
522 $databaseUpdate = $options['update'] && $fuser !== null;
523 $encodeCookie = static::isEncodeCookie();
524
525 $userCode = trim((string)($fuser['CODE'] ?? null));
526 $currentUserId = self::getCurrentUserId();
527
528 if ($databaseUpdate)
529 {
530 $fields = [
531 'DATE_UPDATE' => new Main\Type\DateTime(),
532 ];
533 if ($currentUserId !== null)
534 {
535 $userId = (int)$fuser['USER_ID'];
536 if ($userId === 0 || $userId === $currentUserId)
537 {
538 $fields['USER_ID'] = $currentUserId;
539 }
540 }
541 if ($encodeCookie && $userCode === '')
542 {
543 $userCode = static::generateCode();
544 $fields['CODE'] = $userCode;
545 }
546
548 $internalResult = static::save($id, $fields);
549 if (!$internalResult->isSuccess())
550 {
551 $result->addErrors($internalResult->getErrors());
552
553 return $result;
554 }
555 }
556 else
557 {
558 if ($encodeCookie && $userCode === '')
559 {
560 $userCode = static::generateCode();
561 }
562 }
563
564 if ($options['save'] && $options['update'] && $currentUserId !== null)
565 {
566 $cookieValue = (static::isEncodeCookie() ? $userCode : (string)$id);
567 static::setIdToCookie($cookieValue);
568 }
569 static::setIdToSession($id);
570
571 return $result;
572 }
573
574 protected static function save(?int $id, array $fields): ORM\Data\Result
575 {
576 $pool = Application::getInstance()->getConnectionPool();
577 $pool->useMasterOnly(true);
578 if ($id === null)
579 {
580 $internalResult = Internals\FuserTable::add($fields);
581 }
582 else
583 {
584 $internalResult = Internals\FuserTable::update($id, $fields);
585 }
586 $pool->useMasterOnly(false);
587 unset($pool);
588
589 return $internalResult;
590 }
591
592 public static function handlerOnUserLogin($userId, array $params): void
593 {
594 $userId = (int)$userId;
595 if ($userId <= 0)
596 {
597 return;
598 }
599 $options = [
600 'update' => ($params['update'] ?? true) === true,
601 'save' => ($params['save'] ?? false) === true,
602 ];
603
604 $id = static::getIdFromSession();
605 if ($id === null && $options['update'])
606 {
607 $filter = static::getFilterFromCookie(static::getIdFromCookie());
608 if ($filter !== null)
609 {
610 $id = static::getIdByFilter($filter);
611 }
612 }
613
614 $filter = [
615 '=USER_ID' => $userId
616 ];
617 if ($id !== null)
618 {
619 $filter['!=ID'] = $id;
620 }
621 $row = Internals\FuserTable::getRow([
622 'select' => [
623 'ID',
624 ],
625 'filter' => $filter,
626 'order' => [
627 'ID' => 'DESC',
628 ],
629 ]);
630 if ($row !== null)
631 {
632 $newId = (int)$row['ID'];
633 if ($id !== null && $options['update'])
634 {
635 if (\CSaleBasket::TransferBasket($id, $newId))
636 {
637 \CSaleUser::Delete($id);
638 }
639 }
640 $id = $newId;
641 }
642
643 if ($id !== null)
644 {
645 static::update($id, $options);
646 }
647 elseif ($options['update'])
648 {
649 unset($options['update']);
650 static::add($options);
651 }
652 }
653
654 public static function handlerOnUserLogout($userId)
655 {
656 static::clearSession();
657 static::clearCookie();
658 }
659}
static getFilterFromCookie(?string $cookie)
Definition fuser.php:360
static getIdFromCookie()
Definition fuser.php:331
static setIdToSession(int $id)
Definition fuser.php:307
static save(?int $id, array $fields)
Definition fuser.php:574
static getId($skipCreate=false)
Definition fuser.php:33
const COOKIE_USER_ID
Definition fuser.php:20
static clearCookie()
Definition fuser.php:355
static handlerOnUserLogout($userId)
Definition fuser.php:654
static getIdByCurrentUser()
Definition fuser.php:404
static getUserIdById($fuserId)
Definition fuser.php:177
static getCode()
Definition fuser.php:97
static clearSession()
Definition fuser.php:321
static isEncodeCookie()
Definition fuser.php:265
static handlerOnUserLogin($userId, array $params)
Definition fuser.php:592
static getIdByFilter(array $filter)
Definition fuser.php:388
static setIdToCookie(string $id)
Definition fuser.php:338
static generateCode()
Definition fuser.php:434
const SESSION_USER_ID
Definition fuser.php:19
static isSaveAnonymousUserCookie()
Definition fuser.php:278
static getIdByUserId($userId)
Definition fuser.php:151
static getIdFromSession()
Definition fuser.php:283
static isSecureCookie()
Definition fuser.php:270
static refreshSessionCurrentId()
Definition fuser.php:81