1C-Bitrix 25.700.0
Загрузка...
Поиск...
Не найдено
fuser.php
См. документацию.
1<?php
8namespace Bitrix\Sale;
9
10use Bitrix\Main;
11use Bitrix\Main\Application;
12use Bitrix\Main\Config\Option;
13use Bitrix\Main\ORM;
14use Bitrix\Main\Session\Session;
15use Bitrix\Sale\Internals;
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): void
206 {
207 $days = (int)$days;
208
210 $helper = $connection->getSqlHelper();
211
212 $query = "
213 DELETE FROM b_sale_fuser
214 WHERE
215 b_sale_fuser.DATE_UPDATE < " . $helper->addDaysToDateTime(-$days) . "
216 AND b_sale_fuser.USER_ID IS NULL
217 AND b_sale_fuser.ID NOT IN (select FUSER_ID from b_sale_basket)
218 ";
219
220 $connection->queryExecute($query);
221 }
222
229 protected static function createForUserId(int $userId): ORM\Data\AddResult
230 {
231 $currentTime = new Main\Type\DateTime();
232
234 $result = static::save(
235 null,
236 [
237 'DATE_INSERT' => $currentTime,
238 'DATE_UPDATE' => $currentTime,
239 'USER_ID' => $userId,
240 'CODE' => static::generateCode(),
241 ]
242 );
243
244 return $result;
245 }
246
254 protected static function getSession(): ?Session
255 {
257 $session = Application::getInstance()->getSession();
258 if (!$session->isAccessible())
259 {
260 return null;
261 }
262
263 return $session;
264 }
265
266 protected static function isEncodeCookie(): bool
267 {
268 return Option::get('sale', 'encode_fuser_id') === 'Y';
269 }
270
271 protected static function isSecureCookie(): bool
272 {
273 return
274 Option::get('sale', 'use_secure_cookies') === 'Y'
275 && Main\Context::getCurrent()->getRequest()->isHttps()
276 ;
277 }
278
279 protected static function isSaveAnonymousUserCookie(): bool
280 {
281 return Option::get('sale', 'save_anonymous_fuser_cookie') === 'Y';
282 }
283
284 protected static function getIdFromSession(): ?int
285 {
286 $session = static::getSession();
287 if ($session === null)
288 {
289 return null;
290 }
291 if (!$session->has(self::SESSION_USER_ID))
292 {
293 return null;
294 }
295 $rawValue = $session->get(self::SESSION_USER_ID);
296 unset($session);
297
298 $value = (int)$rawValue;
299 $rawValue = (string)$rawValue;
300 if ((string)$value !== $rawValue)
301 {
302 $value = 0;
303 }
304
305 return ($value > 0 ? $value : null);
306 }
307
308 protected static function setIdToSession(int $id): void
309 {
310 $session = static::getSession();
311 if ($session === null)
312 {
313 return;
314 }
315 if ($id <= 0)
316 {
317 return;
318 }
319 $session->set(self::SESSION_USER_ID, $id);
320 }
321
322 protected static function clearSession(): void
323 {
324 $session = static::getSession();
325 if ($session === null)
326 {
327 return;
328 }
329 $session->remove(self::SESSION_USER_ID);
330 }
331
332 protected static function getIdFromCookie(): ?string
333 {
334 $request = Main\Context::getCurrent()->getRequest();
335
336 return $request->getCookie(self::COOKIE_USER_ID);
337 }
338
339 protected static function setIdToCookie(string $id): void
340 {
341 $cookie = new Main\Web\Cookie(self::COOKIE_USER_ID, $id, null);
342 $cookie
343 ->setSecure(static::isSecureCookie())
344 ->setHttpOnly(false)
346 ;
347
348 $response = Main\Context::getCurrent()->getResponse();
349
350 $response->addCookie($cookie);
351
352 unset($response);
353 unset($cookie);
354 }
355
356 protected static function clearCookie(): void
357 {
358 static::setIdToCookie('0');
359 }
360
361 protected static function getFilterFromCookie(?string $cookie): ?array
362 {
363 if ($cookie === null || $cookie === '')
364 {
365 return null;
366 }
367
368 $filter = [];
369 if (static::isEncodeCookie())
370 {
371 $filter = [
372 '=CODE' => $cookie,
373 ];
374 }
375 else
376 {
377 $cookie = (int)$cookie;
378 if ($cookie > 0)
379 {
380 $filter = [
381 '=ID' => $cookie,
382 ];
383 }
384 }
385
386 return (!empty($filter) ? $filter : null);
387 }
388
389 protected static function getIdByFilter(array $filter): ?int
390 {
391 $row = Internals\FuserTable::getRow([
392 'select' => [
393 'ID',
394 ],
395 'filter' => $filter,
396 'order' => [
397 'ID' => 'DESC',
398 ]
399 ]);
400 $result = (int)($row['ID'] ?? 0);
401
402 return $result > 0 ? $result: null;
403 }
404
405 protected static function getIdByCurrentUser(): ?int
406 {
407 $userId = self::getCurrentUserId();
408 if ($userId === null)
409 {
410 return null;
411 }
412
413 return static::getIdByFilter([
414 '=USER_ID' => $userId,
415 ]);
416 }
417
418 private static function getCurrentUserId(): ?int
419 {
420 global $USER;
421
422 if (!(
423 isset($USER)
424 && $USER instanceof \CUser
425 ))
426 {
427 return null;
428 }
429
430 $userId = (int)$USER->GetID();
431
432 return $userId > 0 ? $userId : null;
433 }
434
435 protected static function generateCode(): string
436 {
437 return md5(time() . Main\Security\Random::getString(10, true));
438 }
439
440 public static function add(array $options = []): Result
441 {
442 $result = new Result();
443
444 $currentTime = new Main\Type\DateTime();
445 $userCode = static::generateCode();
446 $currentUserId = self::getCurrentUserId();
447
448 $options['save'] ??= false;
449 if (!is_bool($options['save']))
450 {
451 $options['save'] = false;
452 }
453
455 $internalResult = static::save(
456 null,
457 [
458 'DATE_INSERT' => $currentTime,
459 'DATE_UPDATE' => $currentTime,
460 'USER_ID' => $currentUserId,
461 'CODE' => $userCode,
462 ]
463 );
464 if (!$internalResult->isSuccess())
465 {
466 $result->addErrors($internalResult->getErrors());
467
468 return $result;
469 }
470
471 $id = (int)$internalResult->getId();
472 if (
473 $options['save']
474 && ($currentUserId !== null || self::isSaveAnonymousUserCookie())
475 )
476 {
477 $cookieValue = (static::isEncodeCookie() ? $userCode : (string)$id);
478 static::setIdToCookie($cookieValue);
479 }
480 static::setIdToSession($id);
481 $result->setId($id);
482
483 return $result;
484 }
485
486 public static function update(int $id, array $options = []): Result
487 {
488 $result = new Result();
489
490 if ($id <= 0)
491 {
492 return $result;
493 }
494
495 $options['update'] ??= true;
496 if (!is_bool($options['update']))
497 {
498 $options['update'] = true;
499 }
500 $options['save'] ??= false;
501 if (!is_bool($options['save']))
502 {
503 $options['save'] = false;
504 }
505
506 $fuser = Internals\FuserTable::getRow([
507 'select' => [
508 'ID',
509 'USER_ID',
510 'CODE'
511 ],
512 'filter' => [
513 '=ID' => $id,
514 ]
515 ]);
516
517 $databaseUpdate = $options['update'] && $fuser !== null;
518 $encodeCookie = static::isEncodeCookie();
519
520 $userCode = trim((string)($fuser['CODE'] ?? null));
521 $currentUserId = self::getCurrentUserId();
522
523 if ($databaseUpdate)
524 {
525 $fields = [
526 'DATE_UPDATE' => new Main\Type\DateTime(),
527 ];
528 if ($currentUserId !== null)
529 {
530 $userId = (int)$fuser['USER_ID'];
531 if ($userId === 0 || $userId === $currentUserId)
532 {
533 $fields['USER_ID'] = $currentUserId;
534 }
535 }
536 if ($encodeCookie && $userCode === '')
537 {
538 $userCode = static::generateCode();
539 $fields['CODE'] = $userCode;
540 }
541
543 $internalResult = static::save($id, $fields);
544 if (!$internalResult->isSuccess())
545 {
546 $result->addErrors($internalResult->getErrors());
547
548 return $result;
549 }
550 }
551 else
552 {
553 if ($encodeCookie && $userCode === '')
554 {
555 $userCode = static::generateCode();
556 }
557 }
558
559 if ($options['save'] && $currentUserId !== null)
560 {
561 $cookieValue = (static::isEncodeCookie() ? $userCode : (string)$id);
562 static::setIdToCookie($cookieValue);
563 }
564 static::setIdToSession($id);
565
566 return $result;
567 }
568
569 protected static function save(?int $id, array $fields): ORM\Data\Result
570 {
571 $pool = Application::getInstance()->getConnectionPool();
572 $pool->useMasterOnly(true);
573 if ($id === null)
574 {
575 $internalResult = Internals\FuserTable::add($fields);
576 }
577 else
578 {
579 $internalResult = Internals\FuserTable::update($id, $fields);
580 }
581 $pool->useMasterOnly(false);
582 unset($pool);
583
584 return $internalResult;
585 }
586
587 public static function handlerOnUserLogin($userId, array $params): void
588 {
589 $userId = (int)$userId;
590 if ($userId <= 0)
591 {
592 return;
593 }
594 $options = [
595 'update' => ($params['update'] ?? true) === true,
596 'save' => ($params['save'] ?? false) === true,
597 ];
598 if (!$options['update'])
599 {
600 return;
601 }
602
603 $id = static::getIdFromSession();
604 if ($id === null)
605 {
606 $filter = static::getFilterFromCookie(static::getIdFromCookie());
607 if ($filter !== null)
608 {
609 $id = static::getIdByFilter($filter);
610 }
611 }
612
613 $filter = [
614 '=USER_ID' => $userId
615 ];
616 if ($id !== null)
617 {
618 $filter['!=ID'] = $id;
619 }
620 $row = Internals\FuserTable::getRow([
621 'select' => [
622 'ID',
623 ],
624 'filter' => $filter,
625 'order' => [
626 'ID' => 'DESC',
627 ],
628 ]);
629 if ($row !== null)
630 {
631 $newId = (int)$row['ID'];
632 if ($id !== null)
633 {
634 if (\CSaleBasket::TransferBasket($id, $newId))
635 {
637 }
638 }
639 $id = $newId;
640 }
641
642 if ($id !== null)
643 {
644 static::update($id, $options);
645 }
646 else
647 {
648 unset($options['update']);
649 static::add($options);
650 }
651 }
652
653 public static function handlerOnUserLogout($userId)
654 {
655 static::clearSession();
656 static::clearCookie();
657 }
658}
$connection
Определения actionsdefinitions.php:38
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
__construct()
Определения fuser.php:22
static getFilterFromCookie(?string $cookie)
Определения fuser.php:361
static getIdFromCookie()
Определения fuser.php:332
static setIdToSession(int $id)
Определения fuser.php:308
static save(?int $id, array $fields)
Определения fuser.php:569
static getId($skipCreate=false)
Определения fuser.php:33
const COOKIE_USER_ID
Определения fuser.php:20
static clearCookie()
Определения fuser.php:356
static handlerOnUserLogout($userId)
Определения fuser.php:653
static getIdByCurrentUser()
Определения fuser.php:405
static getUserIdById($fuserId)
Определения fuser.php:177
static getCode()
Определения fuser.php:97
static clearSession()
Определения fuser.php:322
static isEncodeCookie()
Определения fuser.php:266
static handlerOnUserLogin($userId, array $params)
Определения fuser.php:587
static getIdByFilter(array $filter)
Определения fuser.php:389
static setIdToCookie(string $id)
Определения fuser.php:339
static generateCode()
Определения fuser.php:435
static deleteOld($days)
Определения fuser.php:205
const SESSION_USER_ID
Определения fuser.php:19
static isSaveAnonymousUserCookie()
Определения fuser.php:279
static getIdByUserId($userId)
Определения fuser.php:151
static getIdFromSession()
Определения fuser.php:284
static isSecureCookie()
Определения fuser.php:271
static refreshSessionCurrentId()
Определения fuser.php:81
static Delete($ID)
Определения basket.php:3877
$options
Определения commerceml2.php:49
</td ></tr ></table ></td ></tr >< tr >< td class="bx-popup-label bx-width30"><?=GetMessage("PAGE_NEW_TAGS")?> array( $site)
Определения file_new.php:804
$result
Определения get_property_values.php:14
$query
Определения get_search.php:11
$filter
Определения iblock_catalog_list.php:54
global $USER
Определения csv_new_run.php:40
Определения aliases.php:105
Определения cookie.php:3
return false
Определения prolog_main_admin.php:185
if($inWords) echo htmlspecialcharsbx(Number2Word_Rus(roundEx($totalVatSum $params['CURRENCY']
Определения template.php:799
$response
Определения result.php:21
$fields
Определения yandex_run.php:501