sCacheDir = dirname(__FILE__).'/../../tmp/tcxml'; $this->sCacheDir = path::clean(path::real($sCacheDir)); $this->nCacheTime = $nCacheTime; $this->bLog = $bLog; $this->__putLog('Constructing on '.$sTumblrID); parent::__construct($sTumblrID,$sHTTPUserAgent); } public function __destruct() { $this->__flushCache(); $this->__putLog('Destructing'); $this->__putLog(); } protected function __apiRead($aParams = array()) { $sRequest = ''; foreach ($aParams as $k => $v) { $sRequest .= $k.'-'.$v.' '; } $this->__putLog('Requesting '.$this->sTumblrID.'.'.$sRequest); if (!$this->__cacheRead($aParams)) { parent::__apiRead($aParams); $this->__cacheWrite($aParams); } return true; } protected function __putLog($sText = '') { if (!$this->bLog) { return true; } if (!$this->oLogFile) { $this->oLogFile = fopen($this->sCacheDir.'/log.txt','a'); } $oLogFile = &$this->oLogFile; if ($sText != '') { fputs($oLogFile,'['.date('c').'] '.$sText."\n"); } else { fputs($oLogFile,"\n\n"); } //fclose($oLogFile); return true; } protected function __cacheRead($aParams = array()) { $sCacheFile = $this->__cacheFile($aParams); if (file_exists($sCacheFile)) { if (time() - filemtime($sCacheFile) <= $this->nCacheTime) { $this->aTemp = unserialize(file_get_contents($sCacheFile)); $this->__putLog('Reading from cache'); if ($this->bDebug) { $sKey = ''; foreach ($aParams as $k => $v) { $sKey .= $k.$v; } $this->aDebug[$sKey] = $this->aTemp; } return true; } else { $this->__putLog('Reading from API'); return false; } } else { $this->__putLog('Reading from API'); return false; } } protected function __cacheWrite($aParams = array()) { file_put_contents($this->__cacheFile($aParams),serialize($this->aTemp)); $this->__putLog('Writing cache'); return true; } protected function __cacheFile($aParams = array()) { $sCacheFile = $this->sTumblrID; foreach ($aParams as $k => $v) { if ($k == 'search') { $v = md5($v); } $sCacheFile .= '.'.$k.'-'.$v; } $sCacheFile .= '.inc'; $sCacheFile = $this->sCacheDir.'/'.$sCacheFile; return $sCacheFile; } protected function __flushCache() { $this->__putLog('Flushing cache'); $sCacheFiles = files::scanDir($this->sCacheDir); foreach ($sCacheFiles as $v) { $sCacheFile = $this->sCacheDir.'/'.$v; $sCacheFile = path::clean(path::real($sCacheFile)); if (is_file($sCacheFile)) { if (time() - filemtime($sCacheFile) >= $this->nCacheTime) { unlink($sCacheFile); $this->__putLog('Deleting '.$v); } } } $sCacheFiles = files::scanDir($this->sCacheDir); return true; } } ?>