| 1 |
<?php |
| 2 |
|
| 3 |
if (!defined('WEBTOTEM_INIT') || WEBTOTEM_INIT !== true) { |
| 4 |
if (!headers_sent()) { |
| 5 |
header('HTTP/1.1 403 Forbidden'); |
| 6 |
} |
| 7 |
die("Protected By WebTotem!"); |
| 8 |
} |
| 9 |
/** |
| 10 |
* WebTotem Cache class for Wordpress. |
| 11 |
*/ |
| 12 |
class WebTotemCache { |
| 13 |
|
| 14 |
const WTOTEM_CACHE_STORAGE_TIME = 3; // cache storage time in minutes |
| 15 |
/** |
| 16 |
* Save multiple some data to cache. |
| 17 |
* |
| 18 |
* @param array $data |
| 19 |
* Array of data. |
| 20 |
* @param string $host_id |
| 21 |
* The data belongs to this host. |
| 22 |
* @param string $storage_time |
| 23 |
* Cache storage time in minutes. |
| 24 |
* |
| 25 |
* @return bool |
| 26 |
* Returns TRUE after saving the data. |
| 27 |
*/ |
| 28 |
public static function setData(array $data, $host_id, $storage_time = self::WTOTEM_CACHE_STORAGE_TIME) { |
| 29 |
|
| 30 |
$cache = json_decode(WebTotemOption::getOption('cache'), true) ?: []; |
| 31 |
|
| 32 |
foreach ($data as $key => $value){ |
| 33 |
$expired = time() + ( $storage_time * 60 ); |
| 34 |
$cache[$host_id][$key] = ['data' => $value, 'expired' => $expired]; |
| 35 |
} |
| 36 |
|
| 37 |
WebTotemOption::setOptions(['cache' => $cache]); |
| 38 |
|
| 39 |
return TRUE; |
| 40 |
} |
| 41 |
|
| 42 |
/** |
| 43 |
* Get data from cache. |
| 44 |
* |
| 45 |
* @param string $key |
| 46 |
* Data key. |
| 47 |
* @param string $host_id |
| 48 |
* The data belongs to this host. |
| 49 |
* |
| 50 |
* @return array |
| 51 |
* Returns saved data by key. |
| 52 |
*/ |
| 53 |
public static function getdata($key, $host_id) { |
| 54 |
|
| 55 |
$cache = json_decode(WebTotemOption::getOption('cache'), true) ?: []; |
| 56 |
if(array_key_exists($host_id, $cache) and |
| 57 |
array_key_exists($key, $cache[$host_id]) and |
| 58 |
$cache[$host_id][$key]['expired'] > time()) { |
| 59 |
return [ |
| 60 |
'data' => $cache[$host_id][$key]['data'], |
| 61 |
'remained' => $cache[$host_id][$key]['expired'] - time(), |
| 62 |
]; |
| 63 |
} else { |
| 64 |
return []; |
| 65 |
} |
| 66 |
|
| 67 |
} |
| 68 |
|
| 69 |
} |
| 70 |
|