1: | <?php
2: | /*
3: | CREATE TABLE IF NOT EXISTS `session` (
4: | `session_id` varchar(32) NOT NULL,
5: | `data` text NOT NULL,
6: | `expire` datetime NOT NULL,
7: | PRIMARY KEY (`session_id`)
8: | ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci;
9: | */
10: | namespace Opencart\System\Library\Session;
11: | /**
12: | * Class DB
13: | *
14: | * @package Opencart\System\Library\Session
15: | */
16: | class DB {
17: | private object $db;
18: | private object $config;
19: |
20: | /**
21: | * Constructor
22: | *
23: | * @param \Opencart\System\Engine\Registry $registry
24: | */
25: | public function __construct(\Opencart\System\Engine\Registry $registry) {
26: | $this->db = $registry->get('db');
27: | $this->config = $registry->get('config');
28: | }
29: |
30: | /**
31: | * Read
32: | *
33: | * @param string $session_id
34: | *
35: | * @return array<mixed>
36: | */
37: | public function read(string $session_id): array {
38: | $query = $this->db->query("SELECT `data` FROM `" . DB_PREFIX . "session` WHERE `session_id` = '" . $this->db->escape($session_id) . "' AND `expire` > '" . $this->db->escape(gmdate('Y-m-d H:i:s')) . "'");
39: |
40: | if ($query->num_rows) {
41: | return (array)json_decode($query->row['data'], true);
42: | } else {
43: | return [];
44: | }
45: | }
46: |
47: | /**
48: | * Write
49: | *
50: | * @param string $session_id
51: | * @param array<mixed> $data
52: | *
53: | * @return bool
54: | */
55: | public function write(string $session_id, array $data): bool {
56: | if ($session_id) {
57: | $this->db->query("REPLACE INTO `" . DB_PREFIX . "session` SET `session_id` = '" . $this->db->escape($session_id) . "', `data` = '" . $this->db->escape($data ? json_encode($data) : '') . "', `expire` = '" . $this->db->escape(gmdate('Y-m-d H:i:s', time() + $this->config->get('session_expire'))) . "'");
58: | }
59: |
60: | return true;
61: | }
62: |
63: | /**
64: | * Destroy
65: | *
66: | * @param string $session_id
67: | *
68: | * @return bool
69: | */
70: | public function destroy(string $session_id): bool {
71: | $this->db->query("DELETE FROM `" . DB_PREFIX . "session` WHERE `session_id` = '" . $this->db->escape($session_id) . "'");
72: |
73: | return true;
74: | }
75: |
76: | /**
77: | * GC
78: | *
79: | * @return bool
80: | */
81: | public function gc(): bool {
82: | if (round(mt_rand(1, $this->config->get('session_divisor') / $this->config->get('session_probability'))) == 1) {
83: | $this->db->query("DELETE FROM `" . DB_PREFIX . "session` WHERE `expire` < '" . $this->db->escape(gmdate('Y-m-d H:i:s', time())) . "'");
84: | }
85: |
86: | return true;
87: | }
88: | }
89: |

OpenCart API API documentation generated by ApiGen dev-master