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 // Force a genuinely new connection: the parameters above fall back to the ones of the main
72 // database, so without this flag pg_connect() returns the handle already opened for $db, and
73 // the close() done by dolSessionClose() would close the connection still in use by the request.
74 $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, true);
75
76 return true;
77}
78
85function dolSessionRead($sess_id)
86{
87 global $dbsession;
88 global $sessionlastvalueread;
89 global $sessionidfound;
90
91 $sql = "SELECT session_id, session_variable, last_accessed FROM ".MAIN_DB_PREFIX."session";
92 $sql .= " WHERE session_id = '".$dbsession->escape($sess_id)."'";
93
94 // Execute the query
95 $resql = $dbsession->query($sql);
96 $num_rows = $dbsession->num_rows($resql);
97 if ($num_rows == 0) {
98 // No session found - return an empty string
99 $sessionlastvalueread = '';
100 $sessionidfound = '';
101 return '';
102 }
103
104 $obj = $dbsession->fetch_object($resql);
105
106 // Enforce the session lifetime at read time, so an expired session is not honoured
107 // just because probabilistic garbage collection has not run yet (typically when
108 // session.gc_probability is 0). MAIN_SESSION_TIMEOUT is not available here (conf is
109 // not loaded yet during session_start()), so rely on session.gc_maxlifetime like
110 // PHP's native garbage collector does.
111 $max_lifetime = min(3600 * 24, (int) ini_get('session.gc_maxlifetime'));
112 if ($max_lifetime > 0 && $dbsession->jdate($obj->last_accessed) < (dol_now() - $max_lifetime)) {
113 // Expired: drop the stale row now, otherwise the INSERT done by dolSessionWrite()
114 // at the end of the request would collide with this still-existing primary key.
115 $delete_query = "DELETE FROM ".MAIN_DB_PREFIX."session";
116 $delete_query .= " WHERE session_id = '".$dbsession->escape($sess_id)."'";
117 $dbsession->query($delete_query);
118
119 $sessionlastvalueread = '';
120 $sessionidfound = '';
121 return '';
122 }
123
124 // Found a valid session - return the serialized string
125 $sessionlastvalueread = $obj->session_variable;
126 $sessionidfound = $obj->session_id;
127 return $obj->session_variable;
128}
129
138function dolSessionWrite($sess_id, $val)
139{
140 global $dbsession, $user;
141 global $sessionlastvalueread;
142 global $sessionidfound;
143
144 //var_dump('write '.$sess_id);
145 //var_dump($val);
146 //var_dump('sessionlastvalueread='.$sessionlastvalueread.' sessionidfound='.$sessionidfound);
147
148 //$sessionlastvalueread='';
149 if ($sessionlastvalueread != $val) {
150 $time_stamp = dol_now();
151
152 if (empty($sessionidfound)) {
153 // No session found, insert a new one
154 $insert_query = "INSERT INTO ".MAIN_DB_PREFIX."session";
155 $insert_query .= "(session_id, session_variable, date_creation, last_accessed, fk_user, remote_ip, user_agent)";
156 $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))."')";
157
158 $result = $dbsession->query($insert_query);
159 if (!$result) {
160 dol_print_error($dbsession);
161 return false;
162 }
163 } else {
164 if ($sessionidfound != $sess_id) {
165 // oops. How can this happen ?
166 dol_print_error($dbsession, 'Oops sess_id received in dolSessionWrite differs from the cache value $sessionidfound. How can this happen ?');
167 return false;
168 }
169 /*$sql = "SELECT session_id, session_variable FROM ".MAIN_DB_PREFIX."session";
170 $sql .= " WHERE session_id = '".$dbsession->escape($sess_id)."'";
171
172 // Execute the query
173 $resql = $dbsession->query($sql);
174 $num_rows = $dbsession->num_rows($resql);
175 if ($num_rows == 0) {
176 // No session found, insert a new one
177 $insert_query = "INSERT INTO ".MAIN_DB_PREFIX."session";
178 $insert_query .= "(session_id, session_variable, last_accessed, fk_user, remote_ip, user_agent)";
179 $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)."')";
180 $result = $dbsession->query($insert_query);
181 if (!$result) {
182 dol_print_error($dbsession);
183 return false;
184 }
185 } else {
186 */
187 // Existing session found - Update the session variables
188 $update_query = "UPDATE ".MAIN_DB_PREFIX."session";
189 $update_query .= " SET session_variable = '".$dbsession->escape($val)."',";
190 $update_query .= " last_accessed = '".$dbsession->idate($time_stamp)."',";
191 $update_query .= " fk_user = ".(int) (!empty($user->id) ? $user->id : 0).",";
192 $update_query .= " remote_ip = '".$dbsession->escape(getUserRemoteIP())."',";
193 $update_query .= " user_agent = '".$dbsession->escape($_SERVER['HTTP_USER_AGENT'] ?? '')."'";
194 $update_query .= " WHERE session_id = '".$dbsession->escape($sess_id)."'";
195
196 $result = $dbsession->query($update_query);
197 if (!$result) {
198 dol_print_error($dbsession);
199 return false;
200 }
201 }
202
203 // When session.gc_probability is 0 (or the save handler was registered after
204 // session_start(), so PHP never rolled the GC dice), dolSessionGC() is never
205 // triggered by PHP. Emulate a probabilistic garbage collection here, using
206 // session.gc_divisor as the odds, so the llx_session table does not grow unbounded.
207 // Run it after the insert/update above (every session write, not only new rows) so
208 // the purge still happens on sites where no new session is created for a long time,
209 // and so the row we just wrote (last_accessed = now) can never be its own target.
210 if ((int) ini_get('session.gc_probability') == 0) {
211 $gc_divisor = max(1, (int) ini_get('session.gc_divisor'));
212 if (mt_rand(1, $gc_divisor) == 1) {
213 $max_lifetime = min(3600 * 24, max(getDolGlobalInt('MAIN_SESSION_TIMEOUT'), (int) ini_get('session.gc_maxlifetime')));
214 dolSessionGC($max_lifetime);
215 }
216 }
217 }
218
219 return true;
220}
221
228{
229 global $dbsession;
230
231 //var_dump('close');
232
233 $dbsession->close();
234
235 return true;
236}
237
244function dolSessionDestroy($sess_id)
245{
246 global $dbsession;
247
248 //var_dump('destroy');
249
250 $delete_query = "DELETE FROM ".MAIN_DB_PREFIX."session";
251 $delete_query .= " WHERE session_id = '".$dbsession->escape($sess_id)."'";
252 $dbsession->query($delete_query);
253
254 return true;
255}
256
264function dolSessionGC($max_lifetime)
265{
266 global $dbsession;
267
268 $time_stamp = dol_now();
269
270 $delete_query = "DELETE FROM ".MAIN_DB_PREFIX."session";
271 $delete_query .= " WHERE last_accessed < '".$dbsession->idate($time_stamp - $max_lifetime)."'";
272
273 $resql = $dbsession->query($delete_query);
274 if ($resql) {
275 return true;
276 } else {
277 dol_syslog("dolSessionGC failed to purge expired sessions: ".$dbsession->lasterror(), LOG_WARNING);
278 return false;
279 }
280}
281
296function dolSessionsLimitForUser($fk_user, $keepcount, $currentsessionid)
297{
298 global $dbsession;
299
300 $fk_user = (int) $fk_user;
301 $keepcount = (int) $keepcount;
302 if ($fk_user <= 0 || $keepcount <= 0) {
303 return 0;
304 }
305
306 // List the other sessions of this user, most recently accessed first.
307 $sql = "SELECT session_id FROM ".MAIN_DB_PREFIX."session";
308 $sql .= " WHERE fk_user = ".((int) $fk_user);
309 $sql .= " AND session_id <> '".$dbsession->escape($currentsessionid)."'";
310 $sql .= " ORDER BY last_accessed DESC, session_id DESC";
311
312 $resql = $dbsession->query($sql);
313 if (!$resql) {
314 dol_syslog("dolSessionsLimitForUser failed to list sessions: ".$dbsession->lasterror(), LOG_WARNING);
315 return 0;
316 }
317
318 $idstodelete = array();
319 $rank = 0;
320 while ($obj = $dbsession->fetch_object($resql)) {
321 $rank++;
322 if ($rank >= $keepcount) { // Keep the ($keepcount - 1) most recent ones, evict the rest
323 $idstodelete[] = $obj->session_id;
324 }
325 }
326
327 if (empty($idstodelete)) {
328 return 0;
329 }
330
331 $sqldel = "DELETE FROM ".MAIN_DB_PREFIX."session WHERE session_id IN (";
332 $i = 0;
333 foreach ($idstodelete as $idtodelete) {
334 $sqldel .= ($i > 0 ? ", " : "")."'".$dbsession->escape($idtodelete)."'";
335 $i++;
336 }
337 $sqldel .= ")";
338
339 $resqldel = $dbsession->query($sqldel);
340 if (!$resqldel) {
341 dol_syslog("dolSessionsLimitForUser failed to purge sessions: ".$dbsession->lasterror(), LOG_WARNING);
342 return 0;
343 }
344
345 dol_syslog("dolSessionsLimitForUser evicted ".count($idstodelete)." session(s) for fk_user=".$fk_user." to enforce a limit of ".$keepcount, LOG_NOTICE);
346
347 return count($idstodelete);
348}
349
350// Call to register user call back functions.
351session_set_save_handler("dolSessionOpen", "dolSessionClose", "dolSessionRead", "dolSessionWrite", "dolSessionDestroy", "dolSessionGC"); // @phpstan-ignore-line
352
359{
360 global $dbsession;
361
362 $arrayofsessions = [];
363 $sql = "SELECT s.session_id, s.session_variable, s.fk_user, s.date_creation, s.last_accessed, s.remote_ip, s.user_agent";
364 $sql .= ", u.login";
365 $sql .= " FROM ".MAIN_DB_PREFIX."session as s";
366 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."user as u ON u.rowid=s.fk_user";
367 $sql .= " LIMIT 500";
368 $resql = $dbsession->query($sql);
369 while ($resql && $obj = $dbsession->fetch_object($resql)) {
370 $arrayofsessions[$obj->session_id] = [
371 "login" => (string) $obj->login,
372 "age" => dol_now() - (int) $dbsession->jdate($obj->date_creation),
373 "creation" => $dbsession->idate($obj->date_creation),
374 "modification" => $dbsession->idate($obj->last_accessed),
375 "remote_ip" => $obj->remote_ip,
376 "user_agent" => $obj->user_agent,
377 "raw" => "",
378 ];
379 }
380
381 return $arrayofsessions;
382}
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.