root/trunk/trax/vendor/trax/session.php

Revision 327, 14.0 KB (checked in by john, 2 years ago)

AR changed the count on paginated queries, added session_cookie_domain to the Trax class

  • Property svn:keywords set to Id
Line 
1<?php
2/**
3 *  File containing the Session class
4 *
5 *  (PHP 5)
6 *
7 *  @package PHPonTrax
8 *  @version $Id$
9 *  @copyright (c) 2005 John Peterson
10 *
11 *  Permission is hereby granted, free of charge, to any person obtaining
12 *  a copy of this software and associated documentation files (the
13 *  "Software"), to deal in the Software without restriction, including
14 *  without limitation the rights to use, copy, modify, merge, publish,
15 *  distribute, sublicense, and/or sell copies of the Software, and to
16 *  permit persons to whom the Software is furnished to do so, subject to
17 *  the following conditions:
18 *
19 *  The above copyright notice and this permission notice shall be
20 *  included in all copies or substantial portions of the Software.
21 *
22 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
23 *  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
24 *  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
25 *  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
26 *  LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
27 *  OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
28 *  WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
29 */
30
31/**
32 *  Keep track of state of the client's session with the server
33 *
34 *  Since there is no continuous connection between the client and the
35 *  web server, there must be some way to carry information forward
36 *  from one page to the next.  PHP does this with a global array variable
37 *  {@link http://www.php.net/manual/en/reserved.variables.php#reserved.variables.session $_SESSION}
38 *  which is automatically restored from an area of the server's hard disk
39 *  indicated by the contents of a cookie stored on the client's computer.
40 *  This class is a static class with convenience methods for accessing the
41 *  contents of $_SESSION.
42 *   @tutorial PHPonTrax/Session.cls
43 */
44class Session {
45
46    /**
47     *  Name of the session (used as cookie name).
48     */
49    const TRAX_SESSION_NAME = "TRAXSESSID";
50
51    /**
52     *  Lifetime in seconds of cookie or, if 0, until browser is restarted.
53     */
54    const TRAX_SESSION_LIFETIME = "0";
55
56    /**
57     *  After this number of minutes, stored data will be seen as
58     *  'garbage' and cleaned up by the garbage collection process.
59     */
60    const TRAX_SESSION_MAXLIFETIME_MINUTES = "20";
61
62    /**
63     *  IP Address of client
64     *  @var string
65     */
66    private static $ip = null;
67
68    /**
69     *  User Agent (OS, Browser, etc) of client
70     *  @var string
71     */
72    private static $user_agent = null;
73
74    /**
75     *  Session started
76     *  @var boolean
77     */
78    private static $started = false; 
79
80    /**
81     *  Session ID
82     *  @var string
83     */
84    public static $id = null;
85
86    /**
87     *  Setup basic session information
88     *
89     *  Fetch the contents from a specified element of
90     *  {@link http://www.php.net/manual/en/reserved.variables.php#reserved.variables.session $_SESSION}
91     *  @uses Trax::$session_name
92     *  @uses Trax::$session_lifetime
93     *  @uses Trax::$session_maxlifetime_minutes
94     */
95    function init() {
96        Trax::$session_name = Trax::$session_name ? Trax::$session_name : self::TRAX_SESSION_NAME;
97        Trax::$session_lifetime = Trax::$session_lifetime ? Trax::$session_lifetime : self::TRAX_SESSION_LIFETIME;
98        Trax::$session_maxlifetime_minutes = Trax::$session_maxlifetime_minutes ? Trax::$session_maxlifetime_minutes : self::TRAX_SESSION_MAXLIFETIME_MINUTES;
99       
100        # set the session default for this app
101        ini_set('session.name', Trax::$session_name);
102        ini_set('session.use_cookies', 1);     
103        if(Trax::$session_cookie_domain) {
104            ini_set('session.cookie_domain',  Trax::$session_cookie_domain); 
105        }       
106        ini_set('session.cookie_lifetime', Trax::$session_lifetime);
107        ini_set('session.gc_probability', 1);
108        ini_set('session.gc_maxlifetime', Trax::$session_maxlifetime_minutes * 60);
109        ini_set('session.use_trans_sid', 0);
110        ini_set('session.auto_start', 0);
111
112        if(Trax::$session_store == 'active_record_store') {
113            ini_set('session.save_handler', 'user');
114            include_once("session/active_record_store.php");
115            $session_class_name = Trax::$session_class_name ? Trax::$session_class_name : 'ActiveRecordStore'; 
116            $ar_session = new $session_class_name;         
117            session_set_save_handler(               
118                array(&$ar_session, 'open'),
119                array(&$ar_session, 'close'),
120                array(&$ar_session, 'read'),
121                array(&$ar_session, 'write'),
122                array(&$ar_session, 'destroy'),
123                array(&$ar_session, 'gc')                   
124            );             
125        } else {
126            # file store
127            ini_set('session.save_handler', 'files');
128            if(Trax::$session_save_path) {
129                ini_set('session.save_path', Trax::$session_save_path);
130            }               
131        }       
132    }
133   
134    /**
135     *  Get a session variable
136     *
137     *  Fetch the contents from a specified element of
138     *  {@link http://www.php.net/manual/en/reserved.variables.php#reserved.variables.session $_SESSION}
139     *  @param mixed $key Key to identify one particular session variable
140     *                    of potentially many for this session
141     *  @return mixed Content of the session variable with the specified
142     *                key if the variable exists; otherwise null.
143     *  @uses get_hash()
144     *  @uses is_valid_host()
145     */
146    function get($key) {
147        if(self::is_valid_host()) {
148            return $_SESSION[self::get_hash()][$key];
149        }
150        return null;
151    }
152
153    /**
154     *  Set a session variable
155     *
156     *  Store a value in a specified element of
157     *  {@link http://www.php.net/manual/en/reserved.variables.php#reserved.variables.session $_SESSION}
158     *  @param mixed $key Key to identify one particular session variable
159     *                    of potentially many for this session
160     *  @param string $value Value to store in the session variable
161     *                       identified by $key 
162     *  @uses get_hash()
163     *  @uses is_valid_host()
164     * 
165     */
166    function set($key, $value) {
167        if(self::is_valid_host()) {
168            $_SESSION[self::get_hash()][$key] = $value;
169        }
170     }
171
172    /**
173     *  Test whether the user host is as expected for this session
174     *
175     *  Compare the REMOTE_ADDR and HTTP_USER_AGENT elements of
176     *  {@link http://www.php.net/manual/en/reserved.variables.php#reserved.variables.server $_SERVER}
177     *  to the expected values for this session.
178     *  @uses $ip
179     *  @uses is_aol_host()
180     *  @uses $user_agent
181     *  @return boolean
182     *          <ul>
183     *            <li>true =>  User host is as expected</li>
184     *            <li>false => User host NOT as expected</li>
185     *          </ul>
186     */
187    function is_valid_host() {
188        if(($_SERVER['REMOTE_ADDR'] == self::$ip || self::is_aol_host()) &&
189           $_SERVER['HTTP_USER_AGENT'] == self::$user_agent) {
190            return true;
191        }
192        return false;
193    }
194
195    /**
196     *  Test whether the client is an AOL user
197     *
198     *  Check whether the domain name of the client's IP ends in
199     *  "proxy.aol.com" or the client's user agent name includes "AOL"
200     *  @return boolean
201     *          <ul>
202     *            <li>true =>  Client is on AOL</li>
203     *            <li>false => Client from some other ISP</li>
204     *          </ul>
205     */
206    function is_aol_host() {
207        if(isset($_SERVER['REMOTE_ADDR']) && ereg("proxy\.aol\.com$", gethostbyaddr($_SERVER['REMOTE_ADDR'])) ||
208           stristr($_SERVER['HTTP_USER_AGENT'], "AOL")) {
209            return true;
210        }
211        return false;
212    }
213
214    /**
215     *  Get key that uniquely identifies this session
216     *
217     *  Calculate a unique session key based on the session ID and
218     *  user agent, plus the user's IP address if not on AOL.
219     *  @uses is_aol_host()
220     *  @uses md5()
221     *  @uses session_id()
222     */
223    function get_hash() {
224        $key = session_id().$_SERVER['HTTP_USER_AGENT'];
225        if(!self::is_aol_host()) {
226            $key .= $_SERVER['REMOTE_ADDR'];
227        }
228        // error_log('get_hash() returns '.md5($key));
229        return md5($key);
230    }
231
232    /**
233     *  Alias to Session::start()
234     *
235     *  @uses start()
236     */
237    function start() {
238        self::start_session();
239    }
240
241    /**
242     *  Start or continue a session
243     *
244     *  @uses ini_set()
245     *  @uses $ip
246     *  @uses is_valid_host()
247     *  @uses session_id()
248     *  @uses session_start()
249     *  @uses $user_agent
250     */
251    function start_session() {
252           
253        if(!self::$started) {
254   
255            self::init();
256
257            header('P3P: CP="NOI ADM DEV PSAi COM NAV OUR OTRo STP IND DEM"');
258   
259            self::$ip = $_SERVER['REMOTE_ADDR'];
260            self::$user_agent = $_SERVER['HTTP_USER_AGENT'];
261   
262            if(self::is_valid_host() && array_key_exists('sess_id',$_REQUEST)) {
263                session_id($_REQUEST['sess_id']);
264            }
265   
266            session_cache_limiter("must-revalidate");
267            session_start();
268            self::$id = session_id();
269            self::$started = true;
270            $hash = self::get_hash();
271            if(!isset($_SESSION[$hash])) {
272                $_SESSION[self::get_hash()] = array();
273            }
274        }               
275    }
276
277    /**
278     *  Alias to Session::destroy_session()
279     *
280     *  @uses destroy_session()
281     */
282    function destroy() {
283        return self::destroy_session();
284    }
285
286    /**
287     *  Destroy the user's session
288     *
289     *  Destroy all data registered to a session
290     *
291     *  @uses session_destroy()
292     */
293    function destroy_session() {
294        session_destroy();
295        #self::init();
296    }
297
298    /**
299     *  Free all session variables currently registered
300     *
301     *  @uses get_hash()
302     *  @uses session_unset()
303     */
304    function unset_session() {
305        $_SESSION[self::get_hash()] = array();
306    }
307
308    /**
309     *  Unset a session variable
310     *
311     *  Unset the variable in
312     *  {@link http://www.php.net/manual/en/reserved.variables.php#reserved.variables.session $_SESSION}
313     *  identified by key $key
314     *  @uses get_hash()
315     *  @uses is_valid_host()
316     */
317    function unset_var($key) {
318         // error_log('Session::unset_var("'.$key.'")');
319        if(self::is_valid_host()) {
320            // error_log('before unsetting SESSION='.var_export($_SESSION,true));
321            unset($_SESSION[self::get_hash()][$key]);
322            // error_log('after unsetting SESSION='.var_export($_SESSION,true));
323        }
324    }
325
326    /**
327     *  Test whether a session variable is defined in $_SESSION
328     *
329     *  Check the
330     *  {@link http://www.php.net/manual/en/reserved.variables.php#reserved.variables.session $_SESSION}
331     *  array for the existance of a variable identified by $key
332     *  @param mixed $key Key to identify one particular session variable
333     *                    of potentially many for this session
334     *  @return boolean
335     *          <ul>
336     *            <li>true =>  The specified session variable is
337     *                         defined.</li>
338     *            <li>false => The specified session variable is
339     *                         not defined.</li>
340     *          </ul>
341     *  @uses get_hash()
342     *  @uses is_valid_host()
343     */
344    function isset_var($key) {
345        if(self::is_valid_host()) {
346            if(isset($_SESSION[self::get_hash()][$key])) {
347                return true;   
348            }
349        }
350        return false;
351    }
352
353    /**
354     *  Test whether there is a flash message to be shown
355     *
356     *  Check whether the
357     *  {@link http://www.php.net/manual/en/reserved.variables.php#reserved.variables.session $_SESSION}
358     *  array for this session contains a
359     *  flash message to be shown to the user.
360     *  @param mixed $key Key to identify one particular flash message
361     *                    of potentially many for this session
362     *  @return boolean
363     *          <ul>
364     *            <li>true =>  A flash message is present</li>
365     *            <li>false => No flash message is present</li>
366     *          </ul>
367     *  @uses get_hash()
368     *  @uses is_valid_host()
369     */
370    function isset_flash($key) {
371        if(self::is_valid_host()) {
372            $hash = self::get_hash();
373            if(isset($_SESSION[$hash]['flash'][$key])) {
374                return true;
375            }
376            #if(array_key_exists($hash, $_SESSION)
377            #   && array_key_exists('flash', $_SESSION[$hash])
378            #   && array_key_exists($key, $_SESSION[$hash]['flash'])) {
379            #    return true;   
380            #}
381        }
382        return false;
383    }
384
385    /**
386     *  Get or set a flash message
387     *
388     *  A flash message is a message that will appear prominently on
389     *  the next screen to be sent to the user. Flash
390     *  messages are intended to be shown to the user once then erased.
391     *  They are stored in the
392     *  {@link http://www.php.net/manual/en/reserved.variables.php#reserved.variables.session $_SESSION}
393     *  array for the user's session.
394     *
395     *  @param mixed $key Key to identify one particular flash message
396     *                    of potentially many for this session
397     *  @param string $value Content of the flash message if present
398     *  @return mixed Content of the flash message with the specified
399     *                key if $value is null; otherwise null.
400     *  @uses get_hash()
401     *  @uses is_valid_host()
402     */
403    function flash($key, $value = null) {
404        if(self::is_valid_host()) {
405            $hash = self::get_hash();
406            if($value) {
407                $_SESSION[$hash]['flash'][$key] = $value;
408            } else {
409                $value = $_SESSION[$hash]['flash'][$key];
410                unset($_SESSION[$hash]['flash'][$key]);
411                return $value;
412            }
413        }
414    }
415
416    /**
417     *  Debugging function to see what's in the session
418     *
419     *  Does a dump of the session to log file and optionally to screen
420     *
421     *  @param boolean $screen Display dump to screen
422     */
423    function debug($screen = false) {
424        $msg = "Session::debug() => ".print_r($_SESSION, true);
425        error_log($msg);
426        if($screen) {
427            echo "<p><pre>".$msg."</pre></p>";
428        }
429    }
430}
431
432// -- set Emacs parameters --
433// Local variables:
434// tab-width: 4
435// c-basic-offset: 4
436// c-hanging-comment-ender-p: nil
437// indent-tabs-mode: nil
438// End:
439?>
Note: See TracBrowser for help on using the browser.