1: <?php
2: /**
3: * @package OpenCart
4: *
5: * @author Daniel Kerr
6: * @copyright Copyright (c) 2005 - 2022, OpenCart, Ltd. (https://www.opencart.com/)
7: * @license https://opensource.org/licenses/GPL-3.0
8: *
9: * @see https://www.opencart.com
10: */
11: namespace Opencart\System\Library;
12: /**
13: * Class Session
14: */
15: class Session {
16: /**
17: * @var object
18: */
19: protected object $adaptor;
20: /**
21: * @var string
22: */
23: protected string $session_id;
24: /**
25: * @var array<mixed>
26: */
27: public array $data = [];
28:
29: /**
30: * Constructor
31: *
32: * @param string $adaptor
33: * @param \Opencart\System\Engine\Registry $registry
34: */
35: public function __construct(string $adaptor, \Opencart\System\Engine\Registry $registry) {
36: $class = 'Opencart\System\Library\Session\\' . $adaptor;
37:
38: if (class_exists($class)) {
39: $this->adaptor = new $class($registry);
40: register_shutdown_function([&$this, 'close']);
41: register_shutdown_function([&$this, 'gc']);
42: } else {
43: throw new \Exception('Error: Could not load session adaptor ' . $adaptor . ' session!');
44: }
45: }
46:
47: /**
48: * Get Session ID
49: *
50: * @return string
51: */
52: public function getId(): string {
53: return $this->session_id;
54: }
55:
56: /**
57: * Start
58: *
59: * Starts a session.
60: *
61: * @param string $session_id
62: *
63: * @return string returns the current session ID
64: */
65: public function start(string $session_id = ''): string {
66: if (!$session_id) {
67: if (function_exists('random_bytes')) {
68: $session_id = substr(bin2hex(random_bytes(26)), 0, 26);
69: } else {
70: $session_id = substr(bin2hex(openssl_random_pseudo_bytes(26)), 0, 26);
71: }
72: }
73:
74: if (preg_match('/^[a-zA-Z0-9,\-]{22,52}$/', $session_id)) {
75: $this->session_id = $session_id;
76: } else {
77: throw new \Exception('Error: Invalid session ID!');
78: }
79:
80: $this->data = $this->adaptor->read($session_id);
81:
82: return $session_id;
83: }
84:
85: /**
86: * Close
87: *
88: * Writes the session data to storage
89: *
90: * @return void
91: */
92: public function close(): void {
93: $this->adaptor->write($this->session_id, $this->data);
94: }
95:
96: /**
97: * Destroy
98: *
99: * Deletes the current session from storage
100: *
101: * @return void
102: */
103: public function destroy(): void {
104: $this->data = [];
105:
106: $this->adaptor->destroy($this->session_id);
107: }
108:
109: /**
110: * GC
111: *
112: * Garbage Collection
113: *
114: * @return void
115: */
116: public function gc(): void {
117: $this->adaptor->gc();
118: }
119: }
120: