1 <?php # vim:ts=2:sw=2:et:
2 /* For licensing and copyright terms, see the file named LICENSE */
5 function mtrack_cache_maintain()
7 $cachedir = MTrackConfig::get('core', 'vardir') . '/cmdcache';
8 $max_cache_life = MTrackConfig::get('core', 'max_cache_life');
9 if (!$max_cache_life) {
10 $max_cache_life = 14 * 86400;
12 foreach (scandir($cachedir) as $name) {
13 $filename = "$cachedir/$name";
14 if (!is_file($filename)) {
17 $st = stat($filename);
18 if ($st['mtime'] + $max_cache_life < time()) {
24 /* walks the cache; loads each element and examines the keys.
25 * if the key prefix matches $key, that element is removed */
26 function mtrack_cache_blow_matching($key)
28 $cachedir = MTrackConfig::get('core', 'vardir') . '/cmdcache';
29 foreach (scandir($cachedir) as $name) {
30 $filename = "$cachedir/$name";
31 if (!is_file($filename)) {
34 $fp = @fopen($filename, 'r');
39 $data = unserialize(stream_get_contents($fp));
44 foreach ($key as $i => $element) {
45 if ($data->key[$i] != $element) {
51 unlink("$cachedir/$name");
56 function mtrack_cache_blow($key)
58 $cachedir = MTrackConfig::get('core', 'vardir') . '/cmdcache';
59 foreach (scandir($cachedir) as $name) {
60 if (!is_file($name)) {
63 $fp = @fopen("$cachedir/$name", 'r');
68 $data = unserialize(stream_get_contents($fp));
72 if ($key == $data->key) {
73 unlink("$cachedir/$name");
78 function mtrack_cache($func, $args, $cache_life = 300, $key = null)
80 $cachedir = MTrackConfig::get('core', 'vardir') . '/cmdcache';
81 if (!is_dir($cachedir)) {
85 $fkey = var_export($args, true);
88 $fkey = var_export($key, true);
90 if (is_string($func)) {
93 $fkey = var_export($func, true) . $fkey;
96 $cachefile = $cachedir . '/' . sha1($fkey);
99 for ($i = 0; $i < 10; $i++) {
100 $fp = @fopen($cachefile, 'r+');
105 if ($st['size'] == 0) {
106 /* not valid to have 0 size; we're likely racing with the
113 if ($st['mtime'] + $cache_life < time()) {
114 /* no longer current; we'll make it current */
117 /* we have exclusive access; someone else may have
118 * made it current in the meantime */
120 if ($st['mtime'] + $cache_life >= time()) {
126 /* we're going to create it */
127 $fp = @fopen($cachefile, 'x+');
139 $result = call_user_func_array($func, $args);
140 $data = new stdclass;
142 $data->res = $result;
143 fwrite($fp, serialize($data));
148 $data = unserialize(stream_get_contents($fp));
152 /* if we didn't get a file pointer, just run the command */
153 return call_user_func_array($func, $args);