1 <?php
2 /**
3 * DatabaseSessionHandler.php
4 *
5 * @author Elvyrra SAS
6 * @license http://rem.mit-license.org/ MIT
7 */
8
9 namespace Hawk;
10
11 /**
12 * This class implements SessionHandlerInterface to define a session engine base on database
13 *
14 * @package SessionHandlers
15 */
16 class DatabaseSessionHandler implements \SessionHandlerInterface{
17 /**
18 * The DB instance used to get and set data
19 *
20 * @var DB
21 */
22 private $db,
23
24 /**
25 * The name of the table containing the sessions
26 */
27 $table;
28
29 /**
30 * Close the session
31 */
32 public function close(){
33 return true;
34 }
35
36 /**
37 * Destroy the session
38 *
39 * @param string $sessionId The session id, corresponding to the session cookie
40 */
41 public function destroy($sessionId){
42 // Clean expired sessions
43 $this->gc(0);
44
45 return !!$this->db->delete($this->table, 'id = :id', array('id' => $sessionId));
46 }
47
48 /**
49 * Clean expired sessions
50 *
51 * @param int $maxlifetime The session lifetime (not used)
52 */
53 public function gc($maxlifetime){
54 if(!$maxlifetime) {
55 $maxlifetime = max(App::conf()->get('session.lifetime'), ini_get('session.gc_maxlifetime'));
56 }
57 return !! $this->db->delete($this->table, ':lifetime AND mtime + :lifetime < UNIX_TIMESTAMP()', array('lifetime' => $maxlifetime));
58 }
59
60
61 /**
62 * Open a new session
63 *
64 * @param string $savePath Not used
65 * @param string $name The session name (defaulty 'PHPSESSID')
66 */
67 public function open($savePath, $name){
68 $this->db = App::db();
69 $this->table = DB::getFullTablename('Session');
70
71 // Update the session mtime
72 if(App::request()->getCookies($name)) {
73 $this->db->update($this->table, new DBExample(array('id' => App::request()->getCookies($name))), array('mtime' => time()));
74 }
75
76 // Clean expired sessions
77 $this->gc(0);
78 }
79
80
81 /**
82 * Read data of a session
83 *
84 * @param string $sessionId The session id, corresponding to the session cookie
85 *
86 * @return string The session data, serialized
87 */
88 public function read($sessionId){
89 $line = $this->db->select(
90 array(
91 'from' => $this->table,
92 'where' => 'id = :id',
93 'binds' => array('id' => $sessionId),
94 'one' => true
95 )
96 );
97
98 return $line['data'];
99 }
100
101
102 /**
103 * Write data on the session
104 *
105 * @param string $sessionId The session id, corresponding to the session cookie
106 * @param string $data The data session to write, serialized
107 */
108 public function write($sessionId, $data){
109 $sql = 'REPLACE INTO ' . $this->table . ' (id, data, mtime) VALUES (:id, :data, UNIX_TIMESTAMP())';
110 return $this->db->query(
111 $sql, array(
112 'id' => $sessionId,
113 'data' => $data,
114 )
115 );
116 }
117 }