dolibarr 25.0.0-alpha
phpsessionindb.lib.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2020 Laurent Destailleur <eldy@users.sourceforge.net>
3 * Copyright (C) 2024-2026 Frédéric France <frederic.france@free.fr>
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 3 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <https://www.gnu.org/licenses/>.
17 * or see https://www.gnu.org/
18 */
19
26// This session handler file must be included just after the call of the master.inc.php into main.inc.php
27// The $conf is already defined from conf.php file.
28// To use it set
29// - create table ll_session from the llx_session-disabled.sql file
30// - uncomment the include DOL_DOCUMENT_ROOT.'/core/lib/phpsessionindb.inc.php into main.inc.php
31// - in your PHP.ini, set: session.save_handler = user
32// The session_set_save_handler() at end of this file will replace default session management.
33
34
42function dolSessionOpen($save_path, $session_name)
43{
44 global $dbsession;
45
46 global $dolibarr_main_db_type, $dolibarr_main_db_host;
47 global $dolibarr_main_db_user, $dolibarr_main_db_pass, $dolibarr_main_db_name, $dolibarr_main_db_port;
48
49 global $dolibarr_session_db_type, $dolibarr_session_db_host;
50 global $dolibarr_session_db_user, $dolibarr_session_db_pass, $dolibarr_session_db_name, $dolibarr_session_db_port;
51
52 if (empty($dolibarr_session_db_type)) {
53 $dolibarr_session_db_type = $dolibarr_main_db_type;
54 }
55 if (empty($dolibarr_session_db_host)) {
56 $dolibarr_session_db_host = $dolibarr_main_db_host;
57 }
58 if (empty($dolibarr_session_db_user)) {
59 $dolibarr_session_db_user = $dolibarr_main_db_user;
60 }
61 if (empty($dolibarr_session_db_pass)) {
62 $dolibarr_session_db_pass = $dolibarr_main_db_pass;
63 }
64 if (empty($dolibarr_session_db_name)) {
65 $dolibarr_session_db_name = $dolibarr_main_db_name;
66 }
67 if (empty($dolibarr_session_db_port)) {
68 $dolibarr_session_db_port = $dolibarr_main_db_port;
69 }
70
71 $dbsession = getDoliDBInstance($dolibarr_session_db_type, $dolibarr_session_db_host, $dolibarr_session_db_user, $dolibarr_session_db_pass, $dolibarr_session_db_name, (int) $dolibarr_session_db_port);
72
73 return true;
74}
75
82function dolSessionRead($sess_id)
83{
84 global $dbsession;
85 global $sessionlastvalueread;
86 global $sessionidfound;
87
88 $sql = "SELECT session_id, session_variable, last_accessed FROM ".MAIN_DB_PREFIX."session";
89 $sql .= " WHERE session_id = '".$dbsession->escape($sess_id)."'";
90
91 // Execute the query
92 $resql = $dbsession->query($sql);
93 $num_rows = $dbsession->num_rows($resql);
94 if ($num_rows == 0) {
95 // No session found - return an empty string
96 $sessionlastvalueread = '';
97 $sessionidfound = '';
98 return '';
99 }
100
101 $obj = $dbsession->fetch_object($resql);
102
103 // Enforce the session lifetime at read time, so an expired session is not honoured
104 // just because probabilistic garbage collection has not run yet (typically when
105 // session.gc_probability is 0). MAIN_SESSION_TIMEOUT is not available here (conf is
106 // not loaded yet during session_start()), so rely on session.gc_maxlifetime like
107 // PHP's native garbage collector does.
108 $max_lifetime = min(3600 * 24, (int) ini_get('session.gc_maxlifetime'));
109 if ($max_lifetime > 0 && $dbsession->jdate($obj->last_accessed) < (dol_now() - $max_lifetime)) {
110 // Expired: drop the stale row now, otherwise the INSERT done by dolSessionWrite()
111 // at the end of the request would collide with this still-existing primary key.
112 $delete_query = "DELETE FROM ".MAIN_DB_PREFIX."session";
113 $delete_query .= " WHERE session_id = '".$dbsession->escape($sess_id)."'";
114 $dbsession->query($delete_query);
115
116 $sessionlastvalueread = '';
117 $sessionidfound = '';
118 return '';
119 }
120
121 // Found a valid session - return the serialized string
122 $sessionlastvalueread = $obj->session_variable;
123 $sessionidfound = $obj->session_id;
124 return $obj->session_variable;
125}
126
135function dolSessionWrite($sess_id, $val)
136{
137 global $dbsession, $user;
138 global $sessionlastvalueread;
139 global $sessionidfound;
140
141 //var_dump('write '.$sess_id);
142 //var_dump($val);
143 //var_dump('sessionlastvalueread='.$sessionlastvalueread.' sessionidfound='.$sessionidfound);
144
145 //$sessionlastvalueread='';
146 if ($sessionlastvalueread != $val) {
147 $time_stamp = dol_now();
148
149 if (empty($sessionidfound)) {
150 // No session found, insert a new one
151 $insert_query = "INSERT INTO ".MAIN_DB_PREFIX."session";
152 $insert_query .= "(session_id, session_variable, date_creation, last_accessed, fk_user, remote_ip, user_agent)";
153 $insert_query .= " VALUES ('".$dbsession->escape($sess_id)."', '".$dbsession->escape($val)."', '".$dbsession->idate($time_stamp)."', '".$dbsession->idate($time_stamp)."', 0, '".$dbsession->escape(getUserRemoteIP())."', '".$dbsession->escape(substr($_SERVER['HTTP_USER_AGENT'] ?? '', 0, 255))."')";
154
155 $result = $dbsession->query($insert_query);
156 if (!$result) {
157 dol_print_error($dbsession);
158 return false;
159 }
160 } else {
161 if ($sessionidfound != $sess_id) {
162 // oops. How can this happen ?
163 dol_print_error($dbsession, 'Oops sess_id received in dolSessionWrite differs from the cache value $sessionidfound. How can this happen ?');
164 return false;
165 }
166 /*$sql = "SELECT session_id, session_variable FROM ".MAIN_DB_PREFIX."session";
167 $sql .= " WHERE session_id = '".$dbsession->escape($sess_id)."'";
168
169 // Execute the query
170 $resql = $dbsession->query($sql);
171 $num_rows = $dbsession->num_rows($resql);
172 if ($num_rows == 0) {
173 // No session found, insert a new one
174 $insert_query = "INSERT INTO ".MAIN_DB_PREFIX."session";
175 $insert_query .= "(session_id, session_variable, last_accessed, fk_user, remote_ip, user_agent)";
176 $insert_query .= " VALUES ('".$dbsession->escape($sess_id)."', '".$dbsession->escape($val)."', '".$dbsession->idate($time_stamp)."', 0, '".$dbsession->escape(getUserRemoteIP())."', '".$dbsession->escape(substr($_SERVER['HTTP_USER_AGENT'] ?? '', 0, 255)."')";
177 $result = $dbsession->query($insert_query);
178 if (!$result) {
179 dol_print_error($dbsession);
180 return false;
181 }
182 } else {
183 */
184 // Existing session found - Update the session variables
185 $update_query = "UPDATE ".MAIN_DB_PREFIX."session";
186 $update_query .= " SET session_variable = '".$dbsession->escape($val)."',";
187 $update_query .= " last_accessed = '".$dbsession->idate($time_stamp)."',";
188 $update_query .= " fk_user = ".(int) (!empty($user->id) ? $user->id : 0).",";
189 $update_query .= " remote_ip = '".$dbsession->escape(getUserRemoteIP())."',";
190 $update_query .= " user_agent = '".$dbsession->escape($_SERVER['HTTP_USER_AGENT'] ?? '')."'";
191 $update_query .= " WHERE session_id = '".$dbsession->escape($sess_id)."'";
192
193 $result = $dbsession->query($update_query);
194 if (!$result) {
195 dol_print_error($dbsession);
196 return false;
197 }
198 }
199
200 // When session.gc_probability is 0 (or the save handler was registered after
201 // session_start(), so PHP never rolled the GC dice), dolSessionGC() is never
202 // triggered by PHP. Emulate a probabilistic garbage collection here, using
203 // session.gc_divisor as the odds, so the llx_session table does not grow unbounded.
204 // Run it after the insert/update above (every session write, not only new rows) so
205 // the purge still happens on sites where no new session is created for a long time,
206 // and so the row we just wrote (last_accessed = now) can never be its own target.
207 if ((int) ini_get('session.gc_probability') == 0) {
208 $gc_divisor = max(1, (int) ini_get('session.gc_divisor'));
209 if (mt_rand(1, $gc_divisor) == 1) {
210 $max_lifetime = min(3600 * 24, max(getDolGlobalInt('MAIN_SESSION_TIMEOUT'), (int) ini_get('session.gc_maxlifetime')));
211 dolSessionGC($max_lifetime);
212 }
213 }
214 }
215
216 return true;
217}
218
225{
226 global $dbsession;
227
228 //var_dump('close');
229
230 $dbsession->close();
231
232 return true;
233}
234
241function dolSessionDestroy($sess_id)
242{
243 global $dbsession;
244
245 //var_dump('destroy');
246
247 $delete_query = "DELETE FROM ".MAIN_DB_PREFIX."session";
248 $delete_query .= " WHERE session_id = '".$dbsession->escape($sess_id)."'";
249 $dbsession->query($delete_query);
250
251 return true;
252}
253
261function dolSessionGC($max_lifetime)
262{
263 global $dbsession;
264
265 $time_stamp = dol_now();
266
267 $delete_query = "DELETE FROM ".MAIN_DB_PREFIX."session";
268 $delete_query .= " WHERE last_accessed < '".$dbsession->idate($time_stamp - $max_lifetime)."'";
269
270 $resql = $dbsession->query($delete_query);
271 if ($resql) {
272 return true;
273 } else {
274 dol_syslog("dolSessionGC failed to purge expired sessions: ".$dbsession->lasterror(), LOG_WARNING);
275 return false;
276 }
277}
278
293function dolSessionsLimitForUser($fk_user, $keepcount, $currentsessionid)
294{
295 global $dbsession;
296
297 $fk_user = (int) $fk_user;
298 $keepcount = (int) $keepcount;
299 if ($fk_user <= 0 || $keepcount <= 0) {
300 return 0;
301 }
302
303 // List the other sessions of this user, most recently accessed first.
304 $sql = "SELECT session_id FROM ".MAIN_DB_PREFIX."session";
305 $sql .= " WHERE fk_user = ".((int) $fk_user);
306 $sql .= " AND session_id <> '".$dbsession->escape($currentsessionid)."'";
307 $sql .= " ORDER BY last_accessed DESC, session_id DESC";
308
309 $resql = $dbsession->query($sql);
310 if (!$resql) {
311 dol_syslog("dolSessionsLimitForUser failed to list sessions: ".$dbsession->lasterror(), LOG_WARNING);
312 return 0;
313 }
314
315 $idstodelete = array();
316 $rank = 0;
317 while ($obj = $dbsession->fetch_object($resql)) {
318 $rank++;
319 if ($rank >= $keepcount) { // Keep the ($keepcount - 1) most recent ones, evict the rest
320 $idstodelete[] = $obj->session_id;
321 }
322 }
323
324 if (empty($idstodelete)) {
325 return 0;
326 }
327
328 $sqldel = "DELETE FROM ".MAIN_DB_PREFIX."session WHERE session_id IN (";
329 $i = 0;
330 foreach ($idstodelete as $idtodelete) {
331 $sqldel .= ($i > 0 ? ", " : "")."'".$dbsession->escape($idtodelete)."'";
332 $i++;
333 }
334 $sqldel .= ")";
335
336 $resqldel = $dbsession->query($sqldel);
337 if (!$resqldel) {
338 dol_syslog("dolSessionsLimitForUser failed to purge sessions: ".$dbsession->lasterror(), LOG_WARNING);
339 return 0;
340 }
341
342 dol_syslog("dolSessionsLimitForUser evicted ".count($idstodelete)." session(s) for fk_user=".$fk_user." to enforce a limit of ".$keepcount, LOG_NOTICE);
343
344 return count($idstodelete);
345}
346
347// Call to register user call back functions.
348session_set_save_handler("dolSessionOpen", "dolSessionClose", "dolSessionRead", "dolSessionWrite", "dolSessionDestroy", "dolSessionGC"); // @phpstan-ignore-line
349
356{
357 global $dbsession;
358
359 $arrayofsessions = [];
360 $sql = "SELECT s.session_id, s.session_variable, s.fk_user, s.date_creation, s.last_accessed, s.remote_ip, s.user_agent";
361 $sql .= ", u.login";
362 $sql .= " FROM ".MAIN_DB_PREFIX."session as s";
363 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."user as u ON u.rowid=s.fk_user";
364 $sql .= " LIMIT 500";
365 $resql = $dbsession->query($sql);
366 while ($resql && $obj = $dbsession->fetch_object($resql)) {
367 $arrayofsessions[$obj->session_id] = [
368 "login" => (string) $obj->login,
369 "age" => dol_now() - (int) $dbsession->jdate($obj->date_creation),
370 "creation" => $dbsession->idate($obj->date_creation),
371 "modification" => $dbsession->idate($obj->last_accessed),
372 "remote_ip" => $obj->remote_ip,
373 "user_agent" => $obj->user_agent,
374 "raw" => "",
375 ];
376 }
377
378 return $arrayofsessions;
379}
dol_now($mode='gmt')
Return date for now.
getDoliDBInstance($type, $host, $user, $pass, $name, $port, $forcenew=false)
Return a DoliDB instance (database handler).
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
getUserRemoteIP($trusted=0)
Return the real IP of remote user.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
dolSessionOpen($save_path, $session_name)
The session open handler called by PHP whenever a session is initialized.
dolSessionWrite($sess_id, $val)
This function is called when a session is initialized with a session_start( ) call,...
dolSessionDestroy($sess_id)
This is called whenever the session_destroy() function call is made.
dolSessionsLimitForUser($fk_user, $keepcount, $currentsessionid)
Enforce a maximum number of concurrent database sessions for a given user.
dolListSessions()
List sessions in db.
dolSessionClose()
This function is executed on shutdown of the session.
dolSessionGC($max_lifetime)
This function is called on a session's start up with the probability specified in session....
dolSessionRead($sess_id)
This function is called whenever a session_start() call is made and reads the session variables.