/** * Check if the last two parts of the FQDN are whitelisted. * * @param string Host to check if it is whitelisted * @access protected * @return boolean True if the host is whitelisted */ function isDoubleCcTld($fqdn) { // 30 Days should be way enough $options = array('lifeTime' => '2592000', 'automaticSerialization' => true); $id = md5($this->doubleCcTldFile); $cache = new Cache_Lite($options); if ($data = $cache->get($id)) { // Cache hit } else { // Cache miss $http = new HTTP_Request($this->doubleCcTldFile); if (!PEAR::isError($http->sendRequest())) { $data = $http->getResponseBody(); } $data = explode("\n", $data); $data = array_flip($data); $cache->save($data, $id); } // if if (array_key_exists($fqdn, $data)) { return true; } else { return false; } // if }
/** * Retrieves data from cache, if it's there. If it is, but it's expired, * it performs a conditional GET to see if the data is updated. If it * isn't, it down updates the modification time of the cache file and * returns the data. If the cache is not there, or the remote file has been * modified, it is downloaded and cached. * * @param string URL of remote file to retrieve * @param int Length of time to cache file locally before asking the server * if it changed. * @return string File contents */ function retrieveFile($url, $cacheLength, $cacheDir) { $cacheID = md5($url); $cache = new Cache_Lite(array("cacheDir" => $cacheDir, "lifeTime" => $cacheLength)); if ($data = $cache->get($cacheID)) { return $data; } else { // we need to perform a request, so include HTTP_Request include_once 'HTTP/Request.php'; // HTTP_Request has moronic redirect "handling", turn that off (Alexey Borzov) $req = new HTTP_Request($url, array('allowRedirects' => false)); // if $cache->get($cacheID) found the file, but it was expired, // $cache->_file will exist if (isset($cache->_file) && file_exists($cache->_file)) { $req->addHeader('If-Modified-Since', gmdate("D, d M Y H:i:s", filemtime($cache->_file)) . " GMT"); } $req->sendRequest(); if (!($req->getResponseCode() == 304)) { // data is changed, so save it to cache $data = $req->getResponseBody(); $cache->save($data, $cacheID); return $data; } else { // retrieve the data, since the first time we did this failed if ($data = $cache->get($cacheID, 'default', true)) { return $data; } } } Services_ExchangeRates::raiseError("Unable to retrieve file {$url} (unknown reason)", SERVICES_EXCHANGERATES_ERROR_RETRIEVAL_FAILED); return false; }
/** * versionCheck - Get the most current version of nterchange and cache the result. * * @return array Information about the newest version of nterchange. **/ function versionCheck() { require_once 'Cache/Lite.php'; $options = array('cacheDir' => CACHE_DIR . '/ntercache/', 'lifeTime' => $this->check_version_interval); $cache = new Cache_Lite($options); $yaml = $cache->get($this->cache_name, $this->cache_group); if (empty($yaml)) { include_once 'HTTP/Request.php'; $req = new HTTP_Request($this->check_version_url); if (!PEAR::isError($req->sendRequest())) { $yaml = $req->getResponseBody(); $cached = $cache->save($yaml, $this->cache_name, $this->cache_group); if ($cached == true) { NDebug::debug('Version check - data is from the web and is now cached.', N_DEBUGTYPE_INFO); } else { NDebug::debug('Version check - data is from the web and is NOT cached.', N_DEBUGTYPE_INFO); } } } else { NDebug::debug('Version check - data is from the cache.', N_DEBUGTYPE_INFO); } require_once 'vendor/spyc.php'; $newest_version_info = @Spyc::YAMLLoad($yaml); return $newest_version_info; }
function transaction($sql) { global $response, $apiKey, $data, $basePath; $parsedSQL = SqlParser::ParseString($sql)->getArray(); //$tokens = SqlParser::Tokenize($sql, true); if (strpos($sql, ';') !== false) { $response['success'] = false; $response['message'] = "You can't use ';'. Use the bulk transaction API instead"; } elseif (strpos($sql, '--') !== false) { $response['success'] = false; $response['message'] = "SQL comments '--' are not allowed"; } elseif ($parsedSQL['drop']) { $response['success'] = false; $response['message'] = "DROP is not allowed through the API"; } elseif ($parsedSQL['alter']) { $response['success'] = false; $response['message'] = "ALTER is not allowed through the API"; } elseif ($parsedSQL['create']) { $response['success'] = false; $response['message'] = "CREATE is not allowed through the API"; } elseif ($parsedSQL['update'] || $parsedSQL['insert'] || $parsedSQL['delete']) { if ($apiKey == $_REQUEST['key'] || $apiKey == false) { $api = new sqlapi(); $response = $api->transaction($_REQUEST['q']); } else { $response['success'] = false; $response['message'] = "Not the right key!"; } } elseif ($parsedSQL['select']) { parse_str(urldecode($_SERVER['QUERY_STRING']), $args); $id = $args['q']; if (!$args['lifetime']) { $args['lifetime'] = 0; } $options = array('cacheDir' => "{$basePath}/tmp/", 'lifeTime' => $args['lifetime']); $Cache_Lite = new Cache_Lite($options); if ($data = $Cache_Lite->get($id)) { //echo "cached"; } else { ob_start(); if ($_REQUEST['srs']) { $srs = $_REQUEST['srs']; } else { $srs = "900913"; } $api = new sqlapi($srs); $api->execQuery("set client_encoding='UTF8'", "PDO"); $response = $api->sql($_REQUEST['q']); echo json_encode($response); // Cache script $data = ob_get_contents(); $Cache_Lite->save($data, $id); ob_get_clean(); } } else { $response['success'] = false; $response['message'] = "Check your SQL. Could not recognise it as either SELECT, INSERT, UPDATE or DELETE"; } return $response; }
private static function minify($arrFilter) { $strOutput = ""; if (is_dir($GLOBALS["_PATHS"]['js'])) { //*** Directory exists. foreach ($arrFilter as $strFilter) { $strFile = $GLOBALS["_PATHS"]['js'] . $strFilter . ".js"; if (is_file($strFile)) { $strOutput .= @file_get_contents($strFile) . "\n"; } } } //*** Minify the Javascript and cache the result. $strHash = md5(implode(",", $arrFilter)); $objCache = new \Cache_Lite($GLOBALS["_CONF"]["cache"]); $strReturn = $objCache->get($strHash, "js"); if ($strReturn) { $strOutput = $strReturn; } else { if ($GLOBALS["_CONF"]["cache"]["caching"]) { $strOutput = \JSMin::minify($strOutput); } $objCache->save($strOutput, $strHash, "js"); } return $strOutput; }
public function getData() { $Cache_Lite = new Cache_Lite(parent::getCacheOptions()); $url = sprintf('https://readitlaterlist.com/v2/get?username=%s&password=%s&apikey=%s&count=%s&format=json', $this->config['username'], $this->config['password'], $this->config['apikey'], $this->config['total']); $id = $url; if ($data = $Cache_Lite->get($id)) { $data = json_decode($data); } else { $Cache_Lite->get($id); PubwichLog::log(2, Pubwich::_('Rebuilding cache for a Readitlater')); PubwichLog::log(2, $this->url); $data = file_get_contents($url); $data = json_decode($data); foreach ($data->list as $item) { // Default value $item->title = parse_url($item->url, PHP_URL_HOST); // If check page title if (!empty($this->config['getTitle'])) { $file = @fopen($item->url, "r"); if ($file) { $text = fread($file, 1024 * 3); if (preg_match('/<title>(.*?)<\\/title>/is', $text, $found)) { $item->title = $found[1]; } } } } // Write cache $cacheWrite = $Cache_Lite->save(json_encode($data)); } return $data->list; }
function HandleDownloadStat() { require_once "Http_Cache.php"; Http_Cache::setExpires(4 * 60 * 60); require_once "Cache/Lite.php"; print " "; $options = array("cacheDir" => "../tmpcache/", "lifeTime" => 4 * 60 * 60); $cacheLite = new Cache_Lite($options); if ($data = $cacheLite->get("downloadStat")) { print $data; } else { require_once "TreeUtils.php"; require_once "RubricsData.php"; $rubrics = new RubricsData(); ob_start(); list($days1, $days2) = $rubrics->getDayNums(true); print ' <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3c.org/TR/1999/REC-html401-19991224/loose.dtd"> <html><head><title>Статистика скачиваний</title> <meta http-equiv="content-type" content="text/html; charset=windows-1251"> <meta name="description" content=""> <meta name="keywords" content=""> <link type="text/css" rel="stylesheet" href="styles/style.css"> </head> <body><div id="container" class="stats"><div id="page"> <div id="content"> <div id="header"> <a href="./categs.html">Категории</a> | <a href="./tasks.html">Журнал обновлений</a> | <a href="./stat.html"><b>Статистика скачиваний</b></a></div> <div id="main_content"> <h1>Статистика скачиваний</h1> <strong style="font-size: 11px;">Обновление статистики производится ежедневно после 06.00, 12.00, 16.00, 20.00, 00.00 часов.</strong> <br><br><br> <p>Количество скаченных компаний, вчера - ' . $days1 . '</p> <p>Количество скаченных компаний, сегодня - ' . $days2 . '</p> <br><br> <table> <thead> <thead> <tr><th>Номер</th><th>Название</th><th>Количество<br>скачанных</th><th>Количество в источнике</th><td>Осталось,<br>%</td><td>Email</td><td>Email,<br>%</td><td>Разница</td><td>Последнее обновление</td></tr> </thead> <tbody> '; processRubrics($rubrics); print ' </tbody> </table> </div> </div></div></div><div id="footer"></div> </body></html> '; $data = ob_get_contents(); ob_end_clean(); $cacheLite->save($data); } }
public function CacheDelete($mode = TRUE) { $cacheoptions = array('automaticCleaningFactor' => '100', 'cacheDir' => dirname(__FILE__) . '/nicocache/cache/'); $CacheLite = new Cache_Lite($cacheoptions); if ($mode) { $flag = $CacheLite->clean(); } else { $flag = $CacheLite->clean(FALSE, 'old'); } return $flag; }
private function get_file($type) { include_once 'Cache_Lite/Lite.php'; $db = Input::getPath()->part(5); $baseLayer = Input::get("baselayer"); $layers = Input::get("layers"); $center = Input::get("center"); $zoom = Input::get("zoom"); $size = Input::get("size"); $sizeArr = explode("x", Input::get("size")); $bbox = Input::get("bbox"); $sql = Input::get("sql"); $id = $db . "_" . $baseLayer . "_" . $layers . "_" . $center . "_" . $zoom . "_" . $size . "_" . $bbox . "_" . $sql; $lifetime = Input::get('lifetime') ?: 0; $options = array('cacheDir' => \app\conf\App::$param['path'] . "app/tmp/", 'lifeTime' => $lifetime); $Cache_Lite = new \Cache_Lite($options); if ($data = $Cache_Lite->get($id)) { //echo "Cached"; } else { ob_start(); $fileName = md5(time() . rand(10000, 99999) . microtime()); $file = \app\conf\App::$param["path"] . "/app/tmp/_" . $fileName . "." . $type; $cmd = "wkhtmltoimage " . "--height {$sizeArr[1]} --disable-smart-width --width {$sizeArr[0]} --quality 90 --javascript-delay 1000 " . "\"" . "http://127.0.0.1" . "/api/v1/staticmap/html/{$db}?baselayer={$baseLayer}&layers={$layers}¢er={$center}&zoom={$zoom}&size={$size}&bbox={$bbox}&sql={$sql}\" " . $file; //die($cmd); exec($cmd); switch ($type) { case "png": $res = imagecreatefrompng($file); break; case "jpg": $res = imagecreatefromjpeg($file); break; } if (!$res) { $response['success'] = false; $response['message'] = "Could not create image"; $response['code'] = 406; header("HTTP/1.0 {$response['code']} " . \app\inc\Util::httpCodeText($response['code'])); echo \app\inc\Response::toJson($response); exit; } header('Content-type: image/png'); imageAlphaBlending($res, true); imageSaveAlpha($res, true); imagepng($res); // Cache script $data = ob_get_contents(); $Cache_Lite->save($data, $id); ob_get_clean(); } header("Content-type: image/png"); echo $data; exit; }
public function getPage($pageID, $apply_shortcodes = false) { $options = array('caching' => true, 'cacheDir' => APP_ROOT . 'app/' . APP_NAME . '/cache/', 'lifeTime' => 3600, 'fileNameProtection' => true); $cache = new Cache_Lite($options); $cacheName = 'wptool' . self::$wp_root . $pageID . '_' . $apply_shortcodes; if ($_cachedData = $cache->get($cacheName)) { return unserialize($_cachedData); } $c = self::_fetchPage($pageID, $apply_shortcodes); $cache->save(serialize($c)); return $c; }
function getCachedContent($url, $anonfunction) { $options = array('lifeTime' => 86400, 'pearErrorMode' => CACHE_LITE_ERROR_DIE); $cache = new Cache_Lite($options); if ($data = $cache->get($url)) { return $data; } else { // No valid cache found (you have to make and save the page) $data = $anonfunction; $cache->save($data); return $data; } }
/** * This is a warpper for Cache_Lite::remove(), since it generates * strict warnings. * * @param mixed $key The key to remove from cache * * @return result of Cache_Lite::remove(), without the strict warnings */ protected function removeFromCache($key) { $current = error_reporting(); error_reporting($current & ~E_STRICT); $this->cache->remove($key); error_reporting($current); }
/** * Constructor * * $options is an assoc. To have a look at availables options, * see the constructor of the Cache_Lite class in 'Cache_Lite.php' * * Comparing to Cache_Lite constructor, there is another option : * $options = array( * (...) see Cache_Lite constructor * 'defaultGroup' => default cache group for function caching (string) * ); * * @param array $options options * @access public */ function __construct($options = array(NULL)) { if (isset($options['defaultGroup'])) { $this->_defaultGroup = $options['defaultGroup']; } parent::__construct($options); }
function _list_output() { $sm = vivvo_lite_site::get_instance(); $content_template = $this->load_template($this->_template_root . 'content.xml'); require_once VIVVO_FS_FRAMEWORK . '/PEAR/Lite.php'; $options = array('cacheDir' => VIVVO_FS_ROOT . 'cache/', 'lifeTime' => 600); $cache_manager = new Cache_Lite($options); $web_stat = $cache_manager->get('web_statistics', 'admin'); if (empty($web_stat)) { $web_stat = $this->web_statistics(); $cache_manager->save($web_stat, 'web_statistics', 'admin'); } $system_stat = $cache_manager->get('system_statistics', 'admin'); if (empty($system_stat)) { $system_stat = $this->system_statistics(); $cache_manager->save($system_stat, 'system_statistics', 'admin'); } $today_stat = $cache_manager->get('today_statistics', 'admin'); if (empty($today_stat)) { $today_stat = $this->today_statistics(); $cache_manager->save($today_stat, 'today_statistics', 'admin'); } $signup_stat = $cache_manager->get('signup_statistics', 'admin'); if (empty($signup_stat)) { $signup_stat = $this->signup_statistics(); $cache_manager->save($signup_stat, 'signup_statistics', 'admin'); } $content_template->assign('web_statistics', $web_stat); $content_template->assign('system_statistics', $system_stat); $content_template->assign('today_statistics', $today_stat); $content_template->assign('signup_statistics', $signup_stat); $log_file = VIVVO_FS_ROOT . VIVVO_FS_FILES_DIR . 'logs/' . date('Y') . '-' . date('m') . '.txt'; $handle = @fopen($log_file, "r"); if ($handle) { $i = 0; while (!feof($handle) && $i < 10) { $buffer .= str_replace(',', ', ', str_replace('"', '', fgets($handle, 4096))); $i++; } fclose($handle); $content_template->assign('activity_log', strval($buffer)); } else { $content_template->assign('activity_log', strval('')); } $content_template->assign('activity_log_link', strval(VIVVO_URL . VIVVO_FS_ADMIN_DIR . 'download.php?file=' . VIVVO_FS_FILES_DIR . 'logs/' . date('Y') . '-' . date('m') . '.txt')); return $content_template; }
/** * Overrides Cache_Lite save() method. * * @access public * * @param string $data Data to put in cache (can be another type than strings * if automaticSerialization is on). * @param string $id (optional) Cache id. * @param string $group (optional) Name of the cache group. * * @return boolean True if no problem (else : false or a PEAR_Error object). */ public function save($data, $id = NULL, $group = 'default') { $result = parent::save($data, $id, $group); // Change the permissions on the cache file, so users other than the web server // user can manage the file. chmod($this->_file, 0664); return $result; }
/** * Sets options for Cache_Lite based on the needs of the current method. * Options set include the subdirectory to be used, and the expiration. * * @param string $key The sub-directory of the cacheDir * @param string $expire The cache lifetime (expire) to be used * * @return void */ protected function setOptions($key, $expire = null) { $cacheDir = $this->options['cacheDir'] . '/oauth/'; $cacheDir .= rtrim($key, '/') . '/'; $this->ensureDirectoryExists($cacheDir); $this->cache->setOption('cacheDir', $cacheDir); $this->cache->setOption('lifeTime', $expire); }
public function delete() { global $config; if ($config['cache']['disable']) { return false; } return parent::remove($this->cache_id, $this->cache_group); }
function get($id) { $mtime = $this->dbmtime(); $this->_setFileName($id, 'default'); if ($mtime < $this->lastModified()) { return parent::get($id); } else { return false; } }
/** * Test if a cache is available and (if yes) return it * * @param string $id cache id * @param string $group name of the cache group * @return string data of the cache (or false if no cache available) * @access public */ function get($id, $group = 'default') { if ($data = parent::get($id, $group, true)) { if ($filemtime = $this->lastModified()) { if ($filemtime > $this->_masterFile_mtime) { return $data; } } } return false; }
function clean_usericoncache($user) { if ($user instanceof steam_user) { $user->delete_value("OBJ_ICON"); $icon = $user->get_attribute("OBJ_ICON"); clean_iconcache($icon); // Clean Icon data from cache require_once "Cache/Lite.php"; $cache = new Cache_Lite(array("cacheDir" => PATH_CACHE)); $cache->clean($user->get_name()); // Clean profile data from cache $cache = get_cache_function($user->get_name(), 86400); $cache->drop("lms_steam::user_get_profile", $user->get_name()); // TODO: In Menu "Your Desktop" some Icon data comes from lms_user // stored in session => delete/refresh this value in session here $portal = $GLOBALS["portal"]; $steam_user = $portal->get_user(); $steam_user->init_attributes(); } }
/** * Constructor * * $options is an assoc. To have a look at availables options, * see the constructor of the Cache_Lite class in 'Cache_Lite.php' * * Comparing to Cache_Lite constructor, there is another option : * $options = array( * (...) see Cache_Lite constructor * 'debugCacheLiteFunction' => (bool) debug the caching process, * 'defaultGroup' => default cache group for function caching (string), * 'dontCacheWhenTheOutputContainsNOCACHE' => (bool) don't cache when the function output contains "NOCACHE", * 'dontCacheWhenTheResultIsFalse' => (bool) don't cache when the function result is false, * 'dontCacheWhenTheResultIsNull' => (bool don't cache when the function result is null * ); * * @param array $options options * @access public */ function __construct($options = array(NULL)) { $availableOptions = array('debugCacheLiteFunction', 'defaultGroup', 'dontCacheWhenTheOutputContainsNOCACHE', 'dontCacheWhenTheResultIsFalse', 'dontCacheWhenTheResultIsNull'); while (list($name, $value) = each($options)) { if (in_array($name, $availableOptions)) { $property = '_' . $name; $this->{$property} = $value; } } reset($options); parent::__construct($options); }
protected function generateOptions() { $AuthOptions = PEAR::getStaticProperty('m_office', 'options'); $userOpt = $AuthOptions['auth']; $opt = array('all' => PEAR::getStaticProperty('Module', 'global')); $options = array('caching' => MODE == 'developpement' ? false : true, 'cacheDir' => $opt['all']['cacheDir'] . '/config/' . ($userOpt ? User::getInstance('office')->getId() . '/' : ''), 'lifeTime' => null, 'fileNameProtection' => false, 'automaticSerialization' => true); $optcache = new Cache_Lite($options); if (!($moduleopt = $optcache->get($this->_modulename))) { if (@(include_once $this->_path . $this->_modulename . '.conf.php')) { if (!is_array($config)) { $config = array(); } $moduleopt = MArray::array_merge_recursive_unique($opt, $config); } else { $moduleopt = $opt; } $useropt = Mreg::get('authHelper')->getPrivilegesForModule(User::getInstance('office'), $this->_modulename); $moduleopt = MArray::array_merge_recursive_unique($moduleopt, $useropt); $optcache->save($moduleopt); } return $moduleopt; }
function _retrieveFile($url, $cacheLength, $cacheDir) { $cacheID = md5($url); $cache = new Cache_Lite(array("cacheDir" => $cacheDir, "lifeTime" => $cacheLength)); if ($data = $cache->get($cacheID)) { return $data; } else { $fp = fopen($url, 'r'); $data = stream_get_contents($fp); if (strlen($data) > 10) { // data is changed, so save it to cache $cache->save($data, $cacheID); return $data; } else { // retrieve the data, since the first time we did this failed if ($data = $cache->get($cacheID, 'default', true)) { return $data; } } } Services_ExchangeRates::raiseError("Unable to retrieve file {$url} (unknown reason)", SERVICES_EXCHANGERATES_ERROR_RETRIEVAL_FAILED); return false; }
/** * Response controller. * * @param integer $cache_lifetime * @param boolean $respond_to_conditional_request * @param string $format (rss1|rss2) * @return void */ public function getFeed($cache_lifetime = 0, $respond_to_conditional_request = true, $format = 'rss2', $format_output = false) { $cache_lifetime = (int) $cache_lifetime; $use_cache = !empty($this->cacheDir) and $cache_lifetime > 0; if ($use_cache) { $cache = new Cache_Lite(array('cacheDir' => $this->cacheDir, 'lifeTime' => $cache_lifetime)); $cache_id = $_SERVER['REQUEST_URI']; if ($respond_to_conditional_request) { $this->emulateLastModified($cache_id, $cache_lifetime); } } if (!$use_cache or false === ($feed = $cache->get($cache_id))) { $this->analyze(); $doc = $this->buildFeed($format, $format_output); $feed = $doc->saveXML(); if ($use_cache) { $cache->save($feed, $cache_id); } } header('Content-Type: application/xml;charset=UTF-8'); echo $feed; exit; }
/** * Create full directory structure, Ripped straight from the Smarty Template engine. * Version: 2.3.0 * Copyright: 2001,2002 ispi of Lincoln, Inc. * * @param string $dir Full directory. * @access private */ function _create_dir_structure($dir) { if (!@file_exists($dir)) { $dir_parts = preg_split('![\\/]+!', $dir, -1, PREG_SPLIT_NO_EMPTY); $new_dir = $dir[0] == DIR_SEP ? DIR_SEP : ''; foreach ($dir_parts as $dir_part) { $new_dir .= $dir_part; if (!file_exists($new_dir) && !mkdir($new_dir, 0771)) { Cache_Lite::raiseError('Cache_Lite : problem creating directory \\"$dir\\" !', -3); return false; } $new_dir .= DIR_SEP; } } }
/** * Create full directory structure, Ripped straight from the Smarty Template engine. * Version: 2.3.0 * Copyright: 2001,2002 ispi of Lincoln, Inc. * * @param string $dir Full directory. * @access private */ function _create_dir_structure($dir) { $dir = str_replace("\"", "", $dir); //Windows doesn't allow quotes in dir names like Linux does. if (!@file_exists($dir)) { $dir_parts = preg_split('![\\/]+!', $dir, -1, PREG_SPLIT_NO_EMPTY); $new_dir = $dir[0] == DIR_SEP ? DIR_SEP : ''; foreach ($dir_parts as $dir_part) { $new_dir .= $dir_part; if (!file_exists($new_dir) && !mkdir($new_dir, 0771)) { Cache_Lite::raiseError('Cache_Lite : problem creating directory \\"$dir\\" !', -3); return false; } $new_dir .= DIR_SEP; } } }
/** * Parses the data files of the map. * * @access public * @return array */ function parse() { foreach ($this->dataFiles as $dataFile => $color) { $cacheID = md5($dataFile . '_' . $color); $lineSet = false; if (is_object($this->cache) && ($lineSet = $this->cache->get($cacheID, 'Image_GIS'))) { $lineSet = unserialize($lineSet); } if ($lineSet === false) { $lineSet = $this->parseFile($dataFile, $color); if (is_object($this->cache)) { $this->cache->save(serialize($lineSet), $cacheID, 'Image_GIS'); } } $this->lineSets[] = $lineSet; } return $this->lineSets; }
/** * [@param Cache_Lite $Cache_Lite] * @return void */ public function buildCache($Cache_Lite = null) { PubwichLog::log(2, sprintf(Pubwich::_('Rebuilding the cache for %s service'), get_class($this))); $url = $this->getURL(); if (!$Cache_Lite) { $Cache_Lite = new Cache_Lite($this->cache_options); $Cache_Lite->get($this->cache_id); } $content = FileFetcher::get($url, $this->http_headers); if ($content !== false) { $cacheWrite = $Cache_Lite->save($content); if (PEAR::isError($cacheWrite)) { /*var_dump( $cacheWrite->getMessage() );*/ } libxml_use_internal_errors(true); $this->data = call_user_func($this->callback_function, $content); } else { $this->data = false; } }
/** * Garbage collect expired cache data * * @return boolean * * @since 11.1 */ public function gc() { $result = true; static::$CacheLiteInstance->setOption('automaticCleaningFactor', 1); static::$CacheLiteInstance->setOption('hashedDirectoryLevel', 1); $success1 = static::$CacheLiteInstance->_cleanDir($this->_root . '/', false, 'old'); if (!($dh = opendir($this->_root . '/'))) { return false; } while ($file = readdir($dh)) { if ($file != '.' && $file != '..' && $file != '.svn') { $file2 = $this->_root . '/' . $file; if (is_dir($file2)) { $result = $result && static::$CacheLiteInstance->_cleanDir($file2 . '/', false, 'old'); } } } $success = $success1 && $result; return $success; }
/** * Save some data in a cache file * * @param string $data data to put in cache (can be another type than strings if automaticSerialization is on) * @param string $id cache id * @param string $group name of the cache group * @param int $lifetime The time in seconds that this entry should live. Defaults to the lifetime * set by the constructor. * @return boolean true if no problem (else : false or a PEAR_Error object) * @access public */ function save($data, $id = NULL, $group = 'default', $lifetime = null) { $res = parent::save($data, $id, $group); if ($res === true) { if ($lifetime == null) { $lifetime = $this->_bufferedLifetime; } if ($lifetime == null) { $lifetime = $this->_lifeTime; } $res = $this->_setLastModified(time() + $lifetime); if (is_object($res)) { // $res is a PEAR_Error object if (!$this->_errorHandlingAPIBreak) { return false; // we return false (old API) } } } return $res; }