root/releases/elgg0.8rc2/lib/adodb/adodb-session.php

Revision 269, 12.5 kB (checked in by ben, 3 years ago)

--

  • Property svn:eol-style set to native
Line 
1 <?php
2 /*
3 V4.01 23 Oct 2003  (c) 2000-2003 John Lim (jlim@natsoft.com.my). All rights reserved.
4   Released under both BSD license and Lesser GPL library license.
5   Whenever there is any discrepancy between the two licenses,
6   the BSD license will take precedence.
7       Set tabs to 4 for best viewing.
8  
9   Latest version of ADODB is available at http://php.weblogs.com/adodb
10   ======================================================================
11  
12  This file provides PHP4 session management using the ADODB database
13 wrapper library.
14  
15  Example
16  =======
17  
18      GLOBAL $HTTP_SESSION_VARS;
19     include('adodb.inc.php');
20     include('adodb-session.php');
21     session_start();
22     session_register('AVAR');
23     $HTTP_SESSION_VARS['AVAR'] += 1;
24     print "<p>\$HTTP_SESSION_VARS['AVAR']={$HTTP_SESSION_VARS['AVAR']}</p>";
25     
26 To force non-persistent connections, call adodb_session_open first before session_start():
27
28      GLOBAL $HTTP_SESSION_VARS;
29     include('adodb.inc.php');
30     include('adodb-session.php');
31     adodb_sess_open(false,false,false);
32     session_start();
33     session_register('AVAR');
34     $HTTP_SESSION_VARS['AVAR'] += 1;
35     print "<p>\$HTTP_SESSION_VARS['AVAR']={$HTTP_SESSION_VARS['AVAR']}</p>";
36
37  
38  Installation
39  ============
40  1. Create this table in your database (syntax might vary depending on your db):
41  
42   create table sessions (
43        SESSKEY char(32) not null,
44        EXPIRY int(11) unsigned not null,
45        EXPIREREF varchar(64),
46        DATA text not null,
47       primary key (sesskey)
48   );
49  
50   For oracle:
51     create table sessions (
52        SESSKEY char(32) not null,
53        EXPIRY DECIMAL(16)  not null,
54        EXPIREREF varchar(64),
55        DATA varchar(4000) not null,
56       primary key (sesskey)
57   );
58
59
60   2. Then define the following parameters. You can either modify
61      this file, or define them before this file is included:
62     
63       $ADODB_SESSION_DRIVER='database driver, eg. mysql or ibase';
64     $ADODB_SESSION_CONNECT='server to connect to';
65     $ADODB_SESSION_USER ='user';
66     $ADODB_SESSION_PWD ='password';
67     $ADODB_SESSION_DB ='database';
68     $ADODB_SESSION_TBL = 'sessions'
69     
70   3. Recommended is PHP 4.0.6 or later. There are documented
71      session bugs in earlier versions of PHP.
72
73   4. If you want to receive notifications when a session expires, then
74        you can tag a session with an EXPIREREF, and before the session
75      record is deleted, we can call a function that will pass the EXPIREREF
76      as the first parameter, and the session key as the second parameter.
77     
78      To do this, define a notification function, say NotifyFn:
79     
80          function NotifyFn($expireref, $sesskey)
81          {
82          }
83     
84      Then you need to define a global variable $ADODB_SESSION_EXPIRE_NOTIFY.
85      This is an array with 2 elements, the first being the name of the variable
86      you would like to store in the EXPIREREF field, and the 2nd is the
87      notification function's name.
88     
89      In this example, we want to be notified when a user's session
90      has expired, so we store the user id in the global variable $USERID,
91      store this value in the EXPIREREF field:
92     
93          $ADODB_SESSION_EXPIRE_NOTIFY = array('USERID','NotifyFn');
94         
95     Then when the NotifyFn is called, we are passed the $USERID as the first
96     parameter, eg. NotifyFn($userid, $sesskey).
97 */
98
99 if (!defined('_ADODB_LAYER')) {
100     include (dirname(__FILE__).'/adodb.inc.php');
101 }
102
103 if (!defined('ADODB_SESSION')) {
104
105  define('ADODB_SESSION',1);
106  
107  /* if database time and system time is difference is greater than this, then give warning */
108  define('ADODB_SESSION_SYNCH_SECS',60);
109
110 /****************************************************************************************\
111     Global definitions
112 \****************************************************************************************/
113 GLOBAL     $ADODB_SESSION_CONNECT,
114     $ADODB_SESSION_DRIVER,
115     $ADODB_SESSION_USER,
116     $ADODB_SESSION_PWD,
117     $ADODB_SESSION_DB,
118     $ADODB_SESS_CONN,
119     $ADODB_SESS_LIFE,
120     $ADODB_SESS_DEBUG,
121     $ADODB_SESSION_EXPIRE_NOTIFY,
122     $ADODB_SESSION_CRC;
123     
124     
125     $ADODB_SESS_LIFE = ini_get('session.gc_maxlifetime');
126     if ($ADODB_SESS_LIFE <= 1) {
127      // bug in PHP 4.0.3 pl 1  -- how about other versions?
128      //print "<h3>Session Error: PHP.INI setting <i>session.gc_maxlifetime</i>not set: $ADODB_SESS_LIFE</h3>";
129          $ADODB_SESS_LIFE=1440;
130     }
131     $ADODB_SESSION_CRC = false;
132     //$ADODB_SESS_DEBUG = true;
133     
134     //////////////////////////////////
135     /* SET THE FOLLOWING PARAMETERS */
136     //////////////////////////////////
137     
138     if (empty($ADODB_SESSION_DRIVER)) {
139         $ADODB_SESSION_DRIVER='mysql';
140         $ADODB_SESSION_CONNECT='localhost';
141         $ADODB_SESSION_USER ='root';
142         $ADODB_SESSION_PWD ='';
143         $ADODB_SESSION_DB ='xphplens_2';
144     }
145     
146     if (empty($ADODB_SESSION_EXPIRE_NOTIFY)) {
147         $ADODB_SESSION_EXPIRE_NOTIFY = false;
148     }
149     //  Made table name configurable - by David Johnson djohnson@inpro.net
150     if (empty($ADODB_SESSION_TBL)){
151         $ADODB_SESSION_TBL = 'sessions';
152     }
153     
154     /*
155     $ADODB_SESS['driver'] = $ADODB_SESSION_DRIVER;
156     $ADODB_SESS['connect'] = $ADODB_SESSION_CONNECT;
157     $ADODB_SESS['user'] = $ADODB_SESSION_USER;
158     $ADODB_SESS['pwd'] = $ADODB_SESSION_PWD;
159     $ADODB_SESS['db'] = $ADODB_SESSION_DB;
160     $ADODB_SESS['life'] = $ADODB_SESS_LIFE;
161     $ADODB_SESS['debug'] = $ADODB_SESS_DEBUG;
162     
163     $ADODB_SESS['debug'] = $ADODB_SESS_DEBUG;
164     $ADODB_SESS['table'] = $ADODB_SESS_TBL;
165     */
166     
167 /****************************************************************************************\
168     Create the connection to the database.
169     
170     If $ADODB_SESS_CONN already exists, reuse that connection
171 \****************************************************************************************/
172 function adodb_sess_open($save_path, $session_name,$persist=true)
173 {
174 GLOBAL $ADODB_SESS_CONN;
175     if (isset($ADODB_SESS_CONN)) return true;
176     
177 GLOBAL     $ADODB_SESSION_CONNECT,
178     $ADODB_SESSION_DRIVER,
179     $ADODB_SESSION_USER,
180     $ADODB_SESSION_PWD,
181     $ADODB_SESSION_DB,
182     $ADODB_SESS_DEBUG;
183     
184     // cannot use & below - do not know why...
185     $ADODB_SESS_CONN = ADONewConnection($ADODB_SESSION_DRIVER);
186     if (!empty($ADODB_SESS_DEBUG)) {
187         $ADODB_SESS_CONN->debug = true;
188         ADOConnection::outp( " conn=$ADODB_SESSION_CONNECT user=$ADODB_SESSION_USER pwd=$ADODB_SESSION_PWD db=$ADODB_SESSION_DB ");
189     }
190     if ($persist) $ok = $ADODB_SESS_CONN->PConnect($ADODB_SESSION_CONNECT,
191             $ADODB_SESSION_USER,$ADODB_SESSION_PWD,$ADODB_SESSION_DB);
192     else $ok = $ADODB_SESS_CONN->Connect($ADODB_SESSION_CONNECT,
193             $ADODB_SESSION_USER,$ADODB_SESSION_PWD,$ADODB_SESSION_DB);
194     
195     if (!$ok) ADOConnection::outp( "<p>Session: connection failed</p>",false);
196 }
197
198 /****************************************************************************************\
199     Close the connection
200 \****************************************************************************************/
201 function adodb_sess_close()
202 {
203 global $ADODB_SESS_CONN;
204
205     if ($ADODB_SESS_CONN) $ADODB_SESS_CONN->Close();
206     return true;
207 }
208
209 /****************************************************************************************\
210     Slurp in the session variables and return the serialized string
211 \****************************************************************************************/
212 function adodb_sess_read($key)
213 {
214 global $ADODB_SESS_CONN,$ADODB_SESSION_TBL,$ADODB_SESSION_CRC;
215
216     $rs = $ADODB_SESS_CONN->Execute("SELECT data FROM $ADODB_SESSION_TBL WHERE sesskey = '$key' AND expiry >= " . time());
217     if ($rs) {
218         if ($rs->EOF) {
219             $v = '';
220         } else
221             $v = rawurldecode(reset($rs->fields));
222             
223         $rs->Close();
224         
225         // new optimization adodb 2.1
226         $ADODB_SESSION_CRC = strlen($v).crc32($v);
227         
228         return $v;
229     }
230     
231     return ''; // thx to Jorma Tuomainen, webmaster#wizactive.com
232 }
233
234 /****************************************************************************************\
235     Write the serialized data to a database.
236     
237     If the data has not been modified since adodb_sess_read(), we do not write.
238 \****************************************************************************************/
239 function adodb_sess_write($key, $val)
240 {
241     global
242         $ADODB_SESS_CONN,
243         $ADODB_SESS_LIFE,
244         $ADODB_SESSION_TBL,
245         $ADODB_SESS_DEBUG,
246         $ADODB_SESSION_CRC,
247         $ADODB_SESSION_EXPIRE_NOTIFY;
248
249     $expiry = time() + $ADODB_SESS_LIFE;
250     
251     // crc32 optimization since adodb 2.1
252     // now we only update expiry date, thx to sebastian thom in adodb 2.32
253     if ($ADODB_SESSION_CRC !== false && $ADODB_SESSION_CRC == strlen($val).crc32($val)) {
254         if ($ADODB_SESS_DEBUG) echo "<p>Session: Only updating date - crc32 not changed</p>";
255         $qry = "UPDATE $ADODB_SESSION_TBL SET expiry=$expiry WHERE sesskey='$key' AND expiry >= " . time();
256         $rs = $ADODB_SESS_CONN->Execute($qry);   
257         return true;
258     }
259     $val = rawurlencode($val);
260     
261     $arr = array('sesskey' => $key, 'expiry' => $expiry, 'data' => $val);
262     if ($ADODB_SESSION_EXPIRE_NOTIFY) {
263         $var = reset($ADODB_SESSION_EXPIRE_NOTIFY);
264         global $$var;
265         $arr['expireref'] = $$var;
266     }
267     $rs = $ADODB_SESS_CONN->Replace($ADODB_SESSION_TBL,$arr,
268         'sesskey',$autoQuote = true);
269     
270     if (!$rs) {
271         ADOConnection::outp( '<p>Session Replace: '.$ADODB_SESS_CONN->ErrorMsg().'</p>',false);
272     }  else {
273         // bug in access driver (could be odbc?) means that info is not commited
274         // properly unless select statement executed in Win2000
275         if ($ADODB_SESS_CONN->databaseType == 'access')
276             $rs = $ADODB_SESS_CONN->Execute("select sesskey from $ADODB_SESSION_TBL WHERE sesskey='$key'");
277     }
278     return !empty($rs);
279 }
280
281 function adodb_sess_destroy($key)
282 {
283     global $ADODB_SESS_CONN, $ADODB_SESSION_TBL,$ADODB_SESSION_EXPIRE_NOTIFY;
284     
285     if ($ADODB_SESSION_EXPIRE_NOTIFY) {
286         reset($ADODB_SESSION_EXPIRE_NOTIFY);
287         $fn = next($ADODB_SESSION_EXPIRE_NOTIFY);
288         $savem = $ADODB_SESS_CONN->SetFetchMode(ADODB_FETCH_NUM);
289         $rs = $ADODB_SESS_CONN->Execute("SELECT expireref,sesskey FROM $ADODB_SESSION_TBL WHERE sesskey='$key'");
290         $ADODB_SESS_CONN->SetFetchMode($savem);
291         if ($rs) {
292             $ADODB_SESS_CONN->BeginTrans();
293             while (!$rs->EOF) {
294                 $ref = $rs->fields[0];
295                 $key = $rs->fields[1];
296                 $fn($ref,$key);
297                 $del = $ADODB_SESS_CONN->Execute("DELETE FROM $ADODB_SESSION_TBL WHERE sesskey='$key'");
298                 $rs->MoveNext();
299             }
300             $ADODB_SESS_CONN->CommitTrans();
301         }
302     } else {
303         $qry = "DELETE FROM $ADODB_SESSION_TBL WHERE sesskey = '$key'";
304         $rs = $ADODB_SESS_CONN->Execute($qry);
305     }
306     return $rs ? true : false;
307 }
308
309 function adodb_sess_gc($maxlifetime)
310 {
311     global $ADODB_SESS_DEBUG, $ADODB_SESS_CONN, $ADODB_SESSION_TBL,$ADODB_SESSION_EXPIRE_NOTIFY;
312     
313     if ($ADODB_SESSION_EXPIRE_NOTIFY) {
314         reset($ADODB_SESSION_EXPIRE_NOTIFY);
315         $fn = next($ADODB_SESSION_EXPIRE_NOTIFY);
316         $savem = $ADODB_SESS_CONN->SetFetchMode(ADODB_FETCH_NUM);
317         $rs =& $ADODB_SESS_CONN->Execute("SELECT expireref,sesskey FROM $ADODB_SESSION_TBL WHERE expiry < " . time());
318         $ADODB_SESS_CONN->SetFetchMode($savem);
319         if ($rs) {
320             $ADODB_SESS_CONN->BeginTrans();
321             while (!$rs->EOF) {
322                 $ref = $rs->fields[0];
323                 $key = $rs->fields[1];
324                 $fn($ref,$key);
325                 $del = $ADODB_SESS_CONN->Execute("DELETE FROM $ADODB_SESSION_TBL WHERE sesskey='$key'");
326                 $rs->MoveNext();
327             }
328             $ADODB_SESS_CONN->CommitTrans();
329         }
330     } else {
331         $qry = "DELETE FROM $ADODB_SESSION_TBL WHERE expiry < " . time();
332         $ADODB_SESS_CONN->Execute($qry);
333     
334         if ($ADODB_SESS_DEBUG) ADOConnection::outp("<p><b>Garbage Collection</b>: $qry</p>");
335     }
336     // suggested by Cameron, "GaM3R" <gamr@outworld.cx>
337     if (defined('ADODB_SESSION_OPTIMIZE')) {
338     global $ADODB_SESSION_DRIVER;
339     
340         switch( $ADODB_SESSION_DRIVER ) {
341             case 'mysql':
342             case 'mysqlt':
343                 $opt_qry = 'OPTIMIZE TABLE '.$ADODB_SESSION_TBL;
344                 break;
345             case 'postgresql':
346             case 'postgresql7':
347                 $opt_qry = 'VACUUM '.$ADODB_SESSION_TBL;   
348                 break;
349         }
350         if (!empty($opt_qry)) {
351             $ADODB_SESS_CONN->Execute($opt_qry);
352         }
353     }
354     if ($ADODB_SESS_CONN->dataProvider === 'oci8') $sql = 'select  TO_CHAR('.($ADODB_SESS_CONN->sysTimeStamp).', \'RRRR-MM-DD HH24:MI:SS\') from '. $ADODB_SESSION_TBL;
355     else $sql = 'select '.$ADODB_SESS_CONN->sysTimeStamp.' from '. $ADODB_SESSION_TBL;
356     
357     $rs =& $ADODB_SESS_CONN->SelectLimit($sql,1);
358     if ($rs && !$rs->EOF) {
359     
360         $dbts = reset($rs->fields);
361         $rs->Close();
362         $dbt = $ADODB_SESS_CONN->UnixTimeStamp($dbts);
363         $t = time();
364     
365         if (abs($dbt - $t) >= ADODB_SESSION_SYNCH_SECS) {
366         global $HTTP_SERVER_VARS;
367             $msg =
368             __FILE__.": Server time for webserver {$HTTP_SERVER_VARS['HTTP_HOST']} not in synch with database: database=$dbt ($dbts), webserver=$t (diff=".(abs($dbt-$t)/3600)." hrs)";
369             error_log($msg);
370             if ($ADODB_SESS_DEBUG) ADOConnection::outp("<p>$msg</p>");
371         }
372     }
373     
374     return true;
375 }
376
377 session_module_name('user');
378 session_set_save_handler(
379     "adodb_sess_open",
380     "adodb_sess_close",
381     "adodb_sess_read",
382     "adodb_sess_write",
383     "adodb_sess_destroy",
384     "adodb_sess_gc");
385 }
386
387 /*  TEST SCRIPT -- UNCOMMENT */
388
389 if (0) {
390 GLOBAL $HTTP_SESSION_VARS;
391
392     session_start();
393     session_register('AVAR');
394     $HTTP_SESSION_VARS['AVAR'] += 1;
395     ADOConnection::outp( "<p>\$HTTP_SESSION_VARS['AVAR']={$HTTP_SESSION_VARS['AVAR']}</p>",false);
396 }
397
398 ?>
Note: See TracBrowser for help on using the browser.