JasonWoof Got questions, comments, patches, etc.? Contact Jason Woofenden
session_new() returns id, fixed db_count()
[wfpl.git] / session.php
1 <?php
2
3 #  Copyright (C) 2006 Jason Woofenden
4 #
5 #  This file is part of wfpl.
6 #
7 #  wfpl is free software; you can redistribute it and/or modify it under the
8 #  terms of the GNU Lesser General Public License as published by the Free
9 #  Software Foundation; either version 2.1 of the License, or (at your option)
10 #  any later version.
11 #
12 #  wfpl is distributed in the hope that it will be useful, but WITHOUT ANY
13 #  WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
14 #  FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License for
15 #  more details.
16 #
17 #  You should have received a copy of the GNU Lesser General Public License
18 #  along with wfpl; if not, write to the Free Software Foundation, Inc., 51
19 #  Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
20
21 # you'll need this file that calls db_connect()
22 if(!isset($GLOBALS['wfpl_db_handle'])) {
23         if(file_exists('db_connect.php')) {
24                 require_once('db_connect.php');
25         } elseif(file_exists('code/db_connect.php')) {
26                 require_once('code/db_connect.php');
27         } else {
28                 die("session.php requires a file db_connect.php or that you call db_connect() first. See code/wfpl/db.php for more information.");
29         }
30 }
31
32 # and these database tables:
33 # create table wfpl_sessions (id int unique auto_increment, session_key varchar(16), length int, expires int);
34 # create table wfpl_session_data (id int unique auto_increment, session_id int, name varchar(100), value text);
35 # run this command to install/clear the tables:
36 #   mysql DATABASE_NAME < code/wfpl/examples/session.sql
37 # note: you may need these parameters for mysql:  -u USERNAME -p
38
39 # GLOSSARY
40 #
41 # session_key  16 digit string identifying the session
42 # session_id   integer id of the record in the "sessions" table of the database
43 # UNTIL_CLOSE  a constant passed as session length to indicate "until browser window closes"
44
45
46 # session_id is kept in $GLOBALS
47 # session_key is sent as a cookie, and thus appears in $_REQUEST. The clean version is in $GLOBALS
48
49 # generate a new random 16-character string
50 function session_generate_key() {
51         $character_set = "abcdefghijklmnopqrstuvwqyzABCDEFGHIJKLMNOPQRSTUVWQYZ0123456789";
52     $id = "                ";
53
54         # PHP 4.2.0 and up seed the random number generator for you.
55         # Lets hope that it seeds with something harder to guess than the clock.
56     for($i = 0; $i < 16; ++$i) {
57         $id{$i} = $character_set{mt_rand(0, 61)};
58     }
59
60     return $id;
61 }
62
63 # track this user with a session cookie (ie a cookie that goes away when the
64 # user closes the browser). The timestamp is how long to track the session in
65 # the database. Defaults to one day.
66 function session_new($length = 86400) {
67         $session_key = session_generate_key();
68
69         db_insert('wfpl_sessions', 'session_key,length', $session_key, $length);
70         $GLOBALS['session_id'] = db_auto_id();
71         $GLOBALS['session_key'] = $session_key;
72         $_REQUEST['session_key'] = $session_key; #just in case someone calls session_exists() after session_new()
73         session_touch($length);
74         return $GLOBALS['session_key'];
75 }
76
77 # call to renew the timeout for the session.
78 # assumes there's a session. call session_init() if you'd like one auto-create one if not found.
79 function session_touch($length = false) {
80         if(!$length) {
81                 $length = db_get_value('wfpl_sessions', 'length', 'where id=%i', $GLOBALS['session_id']);
82         }
83         $expires = time() + $length;
84
85         header('Set-Cookie: session_key=' . $GLOBALS['session_key']);
86
87         db_update('wfpl_sessions', 'expires', $expires, 'where id=%i', $GLOBALS['session_id']);
88 }
89
90 # delete the current session
91 function kill_session() {
92         if(!session_exists()) {
93             return;
94         }
95         _kill_session($GLOBALS['session_id']);
96 }
97
98 # for internal use. use kill_session() above
99 function _kill_session($id) {
100         db_delete('wfpl_session_data', 'where session_id=%i', $id);
101         db_delete('wfpl_sessions', 'where id=%i', $id);
102 }
103
104 # delete expired sessions from database
105 function session_purge_old() {
106         $now = time();
107         $expired_sessions = db_get_column('wfpl_sessions', 'id', 'where expires < %i', $now);
108         if($expired_sessions) foreach($expired_sessions as $expired_session) {
109                 _kill_session($expired_session);
110         }
111 }
112
113 # return true if a session exists
114 function session_exists() {
115         if(!isset($_REQUEST['session_key'])) {
116                 return false;
117         }
118
119         if(isset($GLOBALS['session_id'])) {
120                 return true;
121         }
122
123         $session_key = ereg_replace('[^a-zA-Z0-9]', '', $_REQUEST['session_key']);
124
125         if(!strlen($session_key) == 16) {
126                 return false;
127         }
128
129         $GLOBALS['session_key'] = $session_key;
130
131         session_purge_old();
132         $id = db_get_value('wfpl_sessions', 'id', 'where session_key=%"', $session_key);
133         if($id === false) {
134                 return false;
135         }
136
137         $GLOBALS['session_id'] = $id;
138         return true;
139 }
140
141 # return username if a session exists and is authenticated
142 function session_exists_and_authed() {
143         if(!session_exists()) {
144                 return false;
145         }
146
147         return session_get('auth_username');
148 }
149
150
151 # find existing session, or make one
152 function init_session() {
153         if(!session_exists()) {
154                 session_new();
155         }
156 }
157
158 # save a variable into the session
159 function session_set($name, $value) {
160         session_clear($name);
161         db_insert('wfpl_session_data', 'session_id,name,value', $GLOBALS['session_id'], $name, $value);
162 }
163
164 # remove variable from the session
165 function session_clear($name) {
166         db_delete('wfpl_session_data', 'where session_id=%i && name=%"', $GLOBALS['session_id'], $name);
167 }
168
169 # get a variable into the session
170 function session_get($name) {
171         return db_get_value('wfpl_session_data', 'value', 'where session_id=%i && name=%"', $GLOBALS['session_id'], $name);
172 }
173
174 ?>