forked from anchorcms/anchor-cms
/
session.php
100 lines (81 loc) · 2.5 KB
/
session.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
<?php defined('IN_CMS') or die('No direct access allowed.');
/*
This will handle our native sessions for now
but provides somes flexibility in the future
if we decide to use other methods for
session management
*/
class Session {
private static $id, $data = array();
private static function gc() {
// dont run gc on every request
if(mt_rand(1, 100) <= 10) {
$sql = 'delete from sessions where date < ?';
$expire = time() - Config::get('session.expire', 86400);
Db::query($sql, array(date(DATE_ISO8601, $expire)));
}
}
public static function regenerate() {
$new = Str::random(32);
Db::update('sessions', array('id' => $new), array('id' => static::$id));
static::$id = $new;
}
public static function start() {
// run gc
static::gc();
// get session id
$name = Config::get('session.name', 'anchorcms');
static::$id = Cookie::get($name);
if(static::$id === false) {
Log::info('Session cookie not found: ' . $name);
static::$id = Str::random(32);
}
// load session data
$sql = "select data from sessions where id = ? and ip = ? and ua = ? limit 1";
$args = array(static::$id, Input::ip_address(), Input::user_agent());
if($session = Db::row($sql, $args)) {
static::$data = unserialize($session->data);
} else {
// Session not found regenerate ID
static::$id = Str::random(32);
Db::insert('sessions', array(
'id' => static::$id,
'date' => date(DATE_ISO8601),
'ip' => Input::ip_address(),
'ua' => Input::user_agent(),
'data' => serialize(static::$data)
));
}
}
public static function end() {
// cookie details
$name = Config::get('session.name', 'anchorcms');
$expire = time() + Config::get('session.expire', 86400);
$path = Config::get('session.path', '/');
$domain = Config::get('session.domain', '');
// update db session
Db::update('sessions', array(
'date' => date(DATE_ISO8601),
'ip' => Input::ip_address(),
'ua' => Input::user_agent(),
'data' => serialize(static::$data)
), array(
'id' => static::$id
));
// create cookie with ID
if(!Cookie::write($name, static::$id, $expire, $path, $domain)) {
Log::error('Could not write session cookie: ' . static::$id);
}
}
public static function get($key, $default = false) {
return isset(static::$data[$key]) ? static::$data[$key] : $default;
}
public static function set($key, $value) {
static::$data[$key] = $value;
}
public static function forget($key) {
if(isset(static::$data[$key])) {
unset(static::$data[$key]);
}
}
}