-
Notifications
You must be signed in to change notification settings - Fork 0
/
homecards-localcache.php
68 lines (67 loc) · 2.58 KB
/
homecards-localcache.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
<?php
function hc_set($key, $data, $timeoutSecs) {
$key .= $_SESSION['mls'];
if ( defined("HC_CACHE_MODE") ) { $cacheMode = HC_CACHE_MODE; } else { define("HC_CACHE_MODE", "transient"); $cacheMode = "transient";}
if ( !isset($timeoutSecs)) { $timeoutSecs = 60*60*12; }
$expireTime = time() + $timeoutSecs;
if ($cacheMode == 'file' ) {
// check for null $data - clean file
if ( $data == null ) {
return unlink($tmpfname);
} else {
// we have data to cache to file
$tmpfname = tempnam("/tmp", "hc_cache_" . $key . '.tmp');
$handle = fopen($tmpfname, "w");
fwrite($handle, $data);
fclose($handle);
}
} else if ($cacheMode == 'globals' || $cacheMode == 'memory' || $cacheMode == 'php' ) {
// PER-SCRIPT-REQUEST VALUE CACHE - PREVENTS REPETITIVE OR RECURSIVE DATA CALLS TO THE HC PROXY SERVER
// check for a delete request
if ( $data == null ) {
$GLOBALS[$key] = null;
return false;
}
$GLOBALS[$key] = $data;
$GLOBALS[$key . "_exptime"] = $expireTime;
} else if ($cacheMode == 'transient' || $cacheMode == 'db' || $cacheMode == 'wp' ) {
// This is probably the best bet to be compatible with 3rd party caching layers (like redis or mongoDB )
// check for a delete request
if ( $data == null ) {
return delete_transient($key);
} else {
// We gots data to push
set_transient($key, $data, $timeoutSecs);
}
}
}
function hc_get($key, $defaultValue = '') {
$key .= $_SESSION['mls'];
if ( defined("HC_CACHE_MODE") ) { $cacheMode = HC_CACHE_MODE; } else { define("HC_CACHE_MODE", "transient"); $cacheMode = "transient";}
if ($cacheMode == 'file' ) {
$tmpfname = tempnam("/tmp", "hc_cache_" . $key . '.tmp');
if ( file_exists($tmpfname) ) {
$handle = fopen($tmpfname, "r");
$contents = fread($handle, filesize($tmpfname));
fclose($handle);
//unlink($tmpfname);
return $contents;
}
} else if ($cacheMode == 'globals' || $cacheMode == 'memory' || $cacheMode == 'php' ) {
if (isset($GLOBALS[$key . "_exptime"])) {$expireTime = $GLOBALS[$key . "_exptime"];} else { $expireTime = time() + 60*60*1; }
if (time() > $expireTime) { /* Expired Data, clear it out!!! */
$GLOBALS[$key] = null;
return $defaultValue;
}
if ( isset($GLOBALS[$key]) ) { return $GLOBALS[$key]; }
return $defaultValue;
} else if ($cacheMode == 'transient' || $cacheMode == 'db' || $cacheMode == 'wp' ) {
if ( false === ( $value = get_transient( $key ) ) ) {
// this code runs when there is no valid transient set
return $defaultValue;
} else {
return $value;
}
}
return $defaultValue;
}