1<?php
2// (c) Copyright by authors of the Tiki Wiki CMS Groupware Project
3//
4// All Rights Reserved. See copyright.txt for details and a complete list of authors.
5// Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details.
6// $Id$
7
8/* from
9		http://www.spiration.co.uk/post/1333/PHP 5 sessions in mysql database with PDO db objects
10*/
11
12/**
13 *
14 */
15class Session
16{
17	public $db;
18
19	public function __destruct()
20	{
21		session_write_close();
22	}
23
24	/**
25	 * @param $path
26	 * @param $name
27	 * @return bool
28	 */
29	public function open($path, $name)
30	{
31		return true;
32	}
33
34	/**
35	 * @return bool
36	 */
37	public function close()
38	{
39		return true;
40	}
41
42	/**
43	 * @param $sesskey
44	 * @return mixed
45	 */
46	public function read($sesskey)
47	{
48		global $prefs;
49
50		$bindvars = [ $sesskey ];
51
52		if ($prefs['session_lifetime'] > 0) {
53			$qry = 'select data from sessions where sesskey = ? and expiry > ?';
54			$bindvars[] = $prefs['session_lifetime'];
55		} else {
56			$qry = 'select data from sessions where sesskey = ?';
57		}
58
59		return TikiDb::get()->getOne($qry, $bindvars) ?: '';
60	}
61
62	/**
63	 * @param $sesskey
64	 * @param $data
65	 * @return bool
66	 */
67	public function write($sesskey, $data)
68	{
69		global $prefs;
70
71		if (TikiDb::get()->getLock($sesskey)) {
72			$expiry = time() + ($prefs['session_lifetime'] * 60);
73			TikiDb::get()->query('insert into sessions (sesskey, data, expiry) values( ?, ?, ? ) on duplicate key update data=values(data), expiry=values(expiry)', [$sesskey, $data, $expiry]);
74			TikiDb::get()->releaseLock('sessions');
75			return true;
76		}
77		return false;
78	}
79
80	/**
81	 * @param $sesskey
82	 * @return bool
83	 */
84	public function destroy($sesskey)
85	{
86		$qry = 'delete from sessions where sesskey = ?';
87		TikiDb::get()->query($qry, [ $sesskey ]);
88		return true;
89	}
90
91	/**
92	 * @param $maxlifetime
93	 * @return bool
94	 */
95	public function gc($maxlifetime)
96	{
97		global $prefs;
98
99		if ($prefs['session_lifetime'] > 0) {
100			$qry = 'delete from sessions where expiry < ?';
101			TikiDb::get()->query($qry, [ time() ]);
102		}
103
104		return true;
105	}
106}
107
108$session = new Session;
109
110session_set_save_handler(
111	[$session, 'open'],
112	[$session, 'close'],
113	[$session, 'read'],
114	[$session, 'write'],
115	[$session, 'destroy'],
116	[$session, 'gc']
117);
118