2
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
4
* Serialize Class definition
10
* @author Jeff Stys <jeff.stys@nasa.gov>
11
* @license http://www.mozilla.org/MPL/MPL-1.1.html Mozilla Public License 1.1
12
* @link http://launchpad.net/helioviewer.org
15
* Provides reading, writing, and invalidating Serilized cache files.
18
* @package Helioviewer
19
* @author Jeff Stys <jeff.stys@nasa.gov>
20
* @license http://www.mozilla.org/MPL/MPL-1.1.html Mozilla Public License 1.1
21
* @link http://launchpad.net/helioviewer.org
23
class Helper_Serialize {
34
public function __construct($subPath, $filename, $maxAgeSec=86000) {
35
$this->_path = HV_CACHE_DIR.'/'.$subPath;
36
$this->_filename = $filename;
37
$this->_maxAgeSec = $maxAgeSec;
39
// Verify that cache directory exists
40
if ( !@file_exists($this->_path) ) {
41
if ( !@mkdir($this->_path, 0777, true) ) {
49
* Read cache file from disk and return un-serialized data structure.
50
* Optionally invalidate cache file if older than _maxAgeSec.
52
* @return array on success, boolean false on error
54
public function readCache($verifyAge=true) {
56
// Optionally invalidate cache if _maxAgeSec has been exceeded
57
if ( $verifyAge === true ) {
59
clearstatcache(true, $this->_path.'/'.$this->_filename);
60
$timestamp = @filemtime($this->_path.'/'.$this->_filename);
62
if ( $timestamp === false ||
63
(microtime(true)-(float)$timestamp) > (float)$this->_maxAgeSec ) {
65
@unlink($this->_path.'/'.$this->_filename);
70
// Read serialized data from cache file
71
$serialized = @file_get_contents($this->_path.'/'.$this->_filename);
73
if ( $serialized === false ) {
74
@unlink($this->_path.'/'.$this->_filename);
79
$data = unserialize($serialized);
80
if ( $data === null ) {
81
@unlink($this->_path.'/'.$this->_filename);
89
* Write serialized data to cache file.
90
* Optionally that caching succeeded by immediately reading in cached data
91
* and attempting to un-serialize it.
95
public function writeCache($data, $verify=false) {
97
$serialized = serialize($data);
98
if ( $serialized === false ) {
103
// Write data to a temporary file first
104
$temp_filename = md5($serialized).'_'.microtime(true);
106
$fh = @fopen($this->_path.'/'.$temp_filename, 'w');
107
if ( $fh === false ) {
110
if ( !@fwrite($fh, $serialized) ) {
112
@unlink($this->_path.'/'.$temp_filename);
117
// Move temporary file into permanent location
118
if ( !@rename($this->_path.'/'.$temp_filename, $this->_path.'/'.$this->_filename) ) {
120
@unlink($this->_path.'/'.$temp_filename);
123
clearstatcache(true, $this->_path.'/'.$this->_filename);
125
// Optionally verify that cache file was written and installed
126
// successfully by explicitly reading it back from disk and checking
127
// that it the data it contains can be un-serialized.
128
if ( $verify === true ) {
129
if ( $this->readCache($verifyAge=false) === false ) {
b'\\ No newline at end of file'