forked from robots/4dayforecast
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cache.php
112 lines (87 loc) · 2.96 KB
/
cache.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
101
102
103
104
105
106
107
108
109
110
111
112
<?php
class Cache {
private $_data = array();
private $_filename;
private $_timeout;
function __construct ($filename, $timeout = 240) {
$this->_filename = $filename;
$this->_timeout = $timeout;
}
public function get_key($key) {
if (file_exists($this->_filename)) {
$fp = fopen($this->_filename, "r");
if ($fp) {
if (flock($fp, LOCK_SH)) {
$contents = stream_get_contents($fp);
$this->_data = unserialize($contents);
flock($fp, LOCK_UN);
}
fclose($fp);
}
if (is_null($this->_data)) {
return null;
}
}
if (array_key_exists($key, $this->_data)) {
$data = $this->_data[$key];
if (time() - $data['ts'] > 0) {
return null;
}
return $data['data'];
}
return null;
}
public function unset_key($key) {
$ret = false;
$fp = fopen($this->_filename, "c+");
if (flock($fp, LOCK_EX)) {
fseek($fp, 0);
$contents = stream_get_contents($fp);
$this->_data = unserialize($contents);
if (is_array($this->_data)) {
unset($this->_data[$key]);
ftruncate($fp, 0);
fseek($fp, 0);
fwrite($fp, serialize($this->_data));
fflush($fp);
}
flock($fp, LOCK_UN);
$ret = true;
} else {
$ret = false;
}
fclose($fp);
return $ret;
}
public function set_key($key, $data) {
$ret = false;
$fp = fopen($this->_filename, "c+");
if (flock($fp, LOCK_EX)) {
$contents = stream_get_contents($fp);
$this->_data = unserialize($contents);
if (!is_array($this->_data)) {
$this->_data = array();
}
// timeout \in (1*timeout, 2.5*timeout) hours
$timeout = $this->_timeout;
//$timeout *= mt_rand(10, 25) / 10;
$timeout *= 60;
$timeout += time();
$this->_data[$key] = array('ts' => $timeout, 'data' => $data);
ftruncate($fp, 0);
fseek($fp, 0);
fwrite($fp, serialize($this->_data));
fflush($fp);
flock($fp, LOCK_UN);
$ret = true;
} else {
$ret = false;
}
fclose($fp);
return $ret;
}
public static function clear($key) {
@unlink($this->_filename);
}
}
?>