/** * Stops and saves the cache. * @param array dependencies * @return void */ public function end(array $dp = NULL) { if ($this->cache === NULL) { throw new InvalidStateException('Output cache has already been saved.'); } $this->cache->save($this->key, ob_get_flush(), (array) $dp + (array) $this->dependencies); $this->cache = NULL; }
/** * @covers Phossa\Config\Env\Environment::save() * @covers Phossa\Config\Env\Environment::get() * @covers Phossa\Config\Env\Environment::clear() */ public function testSave() { $data = ['db' => ['dsn' => 'bingo']]; $this->object->save($data); $this->assertEquals($data, $this->object->get()); $this->object->clear(); $this->assertFalse($this->object->get()); }
/** * Creates accessor for instances of given class. * @param string $class * @return Accessor */ public function create($class) { $name = $this->naming->deriveClassName($class); $namespaced = $this->naming->getNamespace() . '\\' . $name; if (class_exists($namespaced) || $this->cache && $this->cache->load($name)) { return new $namespaced(); } $definition = $this->generator->generate($class); if ($this->cache) { $this->cache->save($name, $definition); } eval($definition); return new $namespaced(); }
/** * Fetch data. * * @param string $path * @param array $params * @param string $tag * @param int $cacheLifetime * @param bool $forceFetch * @return array|mixed */ public function fetchData($path, $params = [], $tag = '', $cacheLifetime = 0, $forceFetch = false) { // Set default values. $this->code = 200; $this->message = ''; $fetch = true; $data = Cache::load($this->prefix, $path, $params, $cacheLifetime); if (!$forceFetch && count($data) > 0) { $fetch = false; } if ($fetch) { // Build and request data. $this->url = $this->buildUrl($path, $params); try { $client = new \GuzzleHttp\Client(); $result = $client->get($this->url); if ($result->getStatusCode() == 200) { $data = json_decode($result->getBody(), true); } } catch (\Exception $e) { $this->code = $e->getCode(); $this->message = $e->getMessage(); } // Save cache. if ($cacheLifetime > 0) { Cache::save($this->prefix, $path, $params, $data); } } // Extract on tag. if ($tag != '' && isset($data[$tag])) { $data = $data[$tag]; } return $data; }
/** * Renders template to output. * @return void */ public function render() { if ($this->file == NULL) { // intentionally == throw new InvalidStateException("Template file name was not specified."); } $this->__set('template', $this); $shortName = str_replace(Environment::getVariable('appDir'), '', $this->file); $cache = new Cache($this->getCacheStorage(), 'Nette.Template'); $key = trim(strtr($shortName, '\\/@', '.._'), '.') . '-' . md5($this->file); $cached = $content = $cache[$key]; if ($content === NULL) { if (!$this->getFilters()) { $this->onPrepareFilters($this); } if (!$this->getFilters()) { LimitedScope::load($this->file, $this->getParams()); return; } $content = $this->compile(file_get_contents($this->file), "file …{$shortName}"); $cache->save($key, $content, array(Cache::FILES => $this->file, Cache::EXPIRE => self::$cacheExpire)); $cache->release(); $cached = $cache[$key]; } if ($cached !== NULL && self::$cacheStorage instanceof TemplateCacheStorage) { LimitedScope::load($cached['file'], $this->getParams()); fclose($cached['handle']); } else { LimitedScope::evaluate($content, $this->getParams()); } }
/** * Renders template to output. * @return void */ public function render() { if ($this->file == NULL) { // intentionally == throw new InvalidStateException("Template file name was not specified."); } $cache = new Cache($storage = $this->getCacheStorage(), 'Nette.FileTemplate'); if ($storage instanceof PhpFileStorage) { $storage->hint = str_replace(dirname(dirname($this->file)), '', $this->file); } $cached = $compiled = $cache->load($this->file); if ($compiled === NULL) { try { $compiled = "<?php\n\n// source file: {$this->file}\n\n?>" . $this->compile(); } catch (TemplateException $e) { $e->setSourceFile($this->file); throw $e; } $cache->save($this->file, $compiled, array(Cache::FILES => $this->file, Cache::CONSTS => 'Framework::REVISION')); $cached = $cache->load($this->file); } if ($cached !== NULL && $storage instanceof PhpFileStorage) { LimitedScope::load($cached['file'], $this->getParameters()); } else { LimitedScope::evaluate($compiled, $this->getParameters()); } }
public function loadFromID($id, $loadmeta = true, $loadelements = true) { // Loads content with given ID $cachekey = "content:id:" . $id; $content = Cache::load($cachekey); if (!isset($content['id'])) { // No cache found, load from database $sql = new SqlManager(); // ...here server and language (both coming from controller if available) should be included! $sql->setQuery("SELECT * FROM content WHERE id={{id}}"); $sql->bindParam("{{id}}", $id, "int"); $content = $sql->result(); if (!isset($content['id'])) { throw new Exception("No content for ID '{$id}' found!"); return false; } $this->id = $content['id']; $this->data = $content; // Load other content data as well if ($loadmeta) { $this->data['meta'] = $this->loadMeta(); } if ($loadelements) { $this->data['elements'] = $this->loadElements(); } // Save cache for later Cache::save($cachekey, $this->data); Cache::save("content:url:" . $this->data['url'], $this->data); } return true; }
public function processCache($params) { if ($this->getOption("cacheEnabled")) { // check the database for cache $c = new Cache($this); $cacheId = $this->getCacheId($params); // check whether cache is valid, and if so, retrieve content // from the cache. Content is loaded into the cache with // this call. if ($c->isValid($cacheId)) { // parse cache content back from string to suitable object with // deformatCacheContent method different for every request type $this->setResult(true, $this->deformatCacheContent($c->getContent())); } else { // execute request like it would if there was no cache $this->parseRequest($params); // format result into string for db storage $cacheContent = $this->formatCacheContent($this->result); // save formatted result to cache $c->save($cacheId, $cacheContent); } } else { // caching is not enabled, just parse the request $this->parseRequest($params); } }
public function load() { // Load config // Try from cache $cachekey = "config"; if ($this->user) { $cachekey .= ":" . $this->user; } $this->config = Cache::load("config"); if (!is_array($this->config) || $this->get('cache.active') != 1) { // Load config from database $sql = new SqlManager(); if (!is_null($this->user)) { $sql->setQuery("SELECT * FROM config WHERE user_id = {{user}}"); $sql->bindParam("{{user}}", $this->user); } else { $sql->setQuery("SELECT * FROM config WHERE user_id IS NULL"); } $sql->execute(); $this->config = array(); while ($row = $sql->fetch()) { $this->config[$row['name']] = $row['value']; } if (!isset($this->config['cache.active']) || $this->config['cache.active'] != 1) { // If cache is deactivated, clear possible cache file Cache::clear($cachekey); } else { // If cache is activeated, save config for later use Cache::save($cachekey, $this->config); } } }
private function _verifySign($domain, $text, $sign) { include_once KFL_DIR . '/Libs/Cache.class.php'; $filename = $domain . ".txt"; $cache = new Cache(86400 * 300, 0); $cache->setCacheStore("file"); // or memcache $cache->setCacheDir(APP_TEMP_DIR); $cache->setCacheFile($filename); if ($cache->isCached()) { $client = unserialize($cache->fetch()); } else { require_once 'ClientModel.class.php'; $ClientModel = new ClientModel(); $client = $ClientModel->getClientByName($domain); if ($client) { $cache->save(serialize($client)); } else { return false; } } $this->_private_key = $client['private_key']; if (hmac($this->_private_key, $text, 'sha1') == $sign) { return true; } else { return false; } }
public function testSaveWithTTL() { $value = 'a string value'; $redis = $this->getMockBuilder('\\Redis')->getMock(); $redis->expects($this->once())->method('setex')->with('prefix:key', 200, serialize($value))->willReturn(true); $cache = new Cache($redis, 'prefix'); $this->assertTrue($cache->save('key', $value, 200)); }
/** * Modify and cache application response * * @param \Magento\Framework\App\Response\Http $response * @return void */ public function process(\Magento\Framework\App\Response\Http $response) { if (preg_match('/public.*s-maxage=(\\d+)/', $response->getHeader('Cache-Control')['value'], $matches)) { $maxAge = $matches[1]; $response->setNoCacheHeaders(); if ($response->getHttpResponseCode() == 200 && ($this->request->isGet() || $this->request->isHead())) { $tagsHeader = $response->getHeader('X-Magento-Tags'); $tags = $tagsHeader ? explode(',', $tagsHeader['value']) : array(); $response->clearHeader('Set-Cookie'); $response->clearHeader('X-Magento-Tags'); if (!headers_sent()) { header_remove('Set-Cookie'); } $this->cache->save(serialize($response), $this->identifier->getValue(), $tags, $maxAge); } } }
/** * @param string $key * @param mixed $val * @return Cache */ public static function setObject($key, $val) { $cache = new Cache(); $cache->id = $key; $cache->daten = serialize($val); $cache->datum = new CDbExpression('NOW()'); $cache->save(); return $cache; }
public static function getTree($name, $levels = 1) { $cachekey = "assortment:tree:" . $name; $assortment = Cache::load($cachekey); if (!is_array($assortment)) { $assortment = self::load($name, null, 0, $levels); Cache::save($cachekey, $assortment); } return $assortment; }
/** * Acquire the key or refresh a lock. * * @param string $key Key that should fit the lock when refreshing the lock. * @return string|false */ public function acquire($key = null) { if ($this->getKey() && $key != $this->getKey()) { return false; } if (!isset($key)) { $key = md5(microtime()); } $this->info = array('timestamp' => strftime('%Y-%m-%d %T'), 'key' => $key); if (class_exists('Q\\Auth', false) && Auth::i()->isLoggedIn()) { $this->info['user'] = Auth::i()->user()->getUsername(); $this->info['user_fullname'] = Auth::i()->user()->getFullaname(); } if (!$this->store instanceof Cache) { $this->store = Cache::with($this->store); } $this->store->save('lock:' . $this->name, $this->info, $this->timeout); return $key; }
/** * Callback for output handling. * * @param string|array $buffer * @param int $flags * @return string|array */ public function callback($buffer, $flags) { if (is_array($buffer)) { $this->data = $buffer; } else { $marker = Output::curMarker(); if ($marker !== null) { if (!is_array($this->data)) { $this->data = isset($this->data) ? array(Output::$defaultMarker => $this->data) : array(); } $this->data[$marker] = $this->data; } else { $this->data .= $buffer; } } if ($flags & PHP_OUTPUT_HANDLER_END) { $this->cache->save(static::makeKey(), $this->data); } return false; }
protected function setupHooks() { if (Environment::isProduction() && isset($this->cache['hooks'])) { $this->hooks = $this->cache['hooks']; } else { $this->hooks = new SiteHooks(); foreach ($this->modules as $module) { $module->setupHooks($this->hooks); } $this->cache->save('hooks', $this->hooks); } }
/** * Loads a HTTP resource. * * @param string $url * @param array $parameters * * @return array */ public function loadResource($url, $parameters) { $signature = $this->createSignature($url, $parameters); if ($this->cache->contains($signature)) { return $this->cache->fetch($signature); } $parameters['format'] = 'json'; $parameters['api_key'] = $this->config->getApiKey(); $url = $this->config->getApiEndpoint() . $this->buildQueryUrl($url, $parameters); $response = $this->guzzle->request('GET', $url); $body = $this->processResponse($response); $this->cache->save($signature, $body['results']); return $body['results']; }
/** * Process entry */ public function process($mobid) { header('Content-type:image/png'); header('Cache-Control: max-age=' . Cache::$time . ', public'); Cache::setFilename($mobid . ".png"); $content = ""; // Load the cache file ? if (Cache::get($content)) { die($content); } // Render and cache $this->render($mobid); Cache::save(); }
/** * Renders template to output. * @return void */ public function render() { $cache = new Cache($storage = $this->getCacheStorage(), 'Nette.Template'); $cached = $compiled = $cache->load($this->source); if ($compiled === NULL) { $compiled = $this->compile(); $cache->save($this->source, $compiled, array(Cache::CONSTS => 'Framework::REVISION')); $cached = $cache->load($this->source); } if ($cached !== NULL && $storage instanceof PhpFileStorage) { LimitedScope::load($cached['file'], $this->getParameters()); } else { LimitedScope::evaluate($compiled, $this->getParameters()); } }
/** * Send request to OSM server and return the response. * * @param string $url URL * @param string $method GET (default)/POST/PUT * @param string $user user (optional for read-only actions) * @param string $password password (optional for read-only actions) * @param string $body body (optional) * @param array $post_data (optional) * @param array $headers (optional) * * @access public * @return HTTP_Request2_Response * @todo Consider just returning the content? * @throws Services_OpenStreetMap_Exception If something unexpected has * happened while conversing with * the server. */ public function getResponse($url, $method = HTTP_Request2::METHOD_GET, $user = null, $password = null, $body = null, array $post_data = null, array $headers = null) { $arguments = array($url, $method, $user, $password, $body, implode(":", (array) $post_data), implode(":", (array) $headers)); $id = md5(implode(":", $arguments)); $data = $this->cache->get($id); if ($data) { $response = new HTTP_Request2_Response(); $response->setStatus(200); $response->setBody($data); return $response; } $response = parent::getResponse($url, $method, $user, $password, $body, $post_data, $headers); $this->cache->save($id, $response->getBody()); return $response; }
/** * Process entry */ public function process($pseudo) { header('Content-type:image/png'); header('Cache-Control: max-age=' . Cache::$time . ', public'); Cache::setFilename($pseudo . ".png"); $content = ""; // Load the cache file ? if (Cache::get($content)) { die($content); } // Find and render $data = $this->getPlayerData($pseudo); $this->render($data); // Save Cache::save(); }
public function display() { $this->__data = (object) $this->__data; return $this->render(); if ($this->__enable_cache) { Cache::restore_from_db(); $content = Cache::restore($this->_template, $this->_body); if ($content === null) { Cache::save($this->_template, $this->_body, $__content); echo $__content; } else { echo $content; } } else { return $__content; } }
/** * Gets a list of links * * @return \Storyblok\Client */ public function getLinks() { $version = 'published'; if ($this->editModeEnabled) { $version = 'draft'; } if ($version == 'published' && $this->cache && ($cachedItem = $this->cache->load($this->linksPath))) { $this->responseBody = (array) $cachedItem; } else { $options = array('token' => $this->apiKey, 'version' => $version); $response = $this->get($this->linksPath, $options); $this->responseBody = $response->httpResponseBody; if ($this->cache && $version == 'published') { $this->cache->save($this->responseBody, $this->linksPath); } } return $this; }
public static function loadVersions($type, $id) { $versions = Cache::load("version:" . $type . ":" . $id); if (!is_array($versions)) { $sql = new SqlManager(); $sql->setQuery("\n\t\t\t\tSELECT id, date FROM version\n\t\t\t\tWHERE object_table = '{{type}}'\n\t\t\t\t\tAND object_id = {{id}}\n\t\t\t\t\tAND draft IS NULL\n\t\t\t\tORDER BY date ASC\n\t\t\t\t"); $sql->bindParam("{{type}}", $type); $sql->bindParam("{{id}}", $id, "int"); $sql->execute(); $versions = array("_index" => array()); while ($row = $sql->fetch()) { $versions['_index'][] = $row['id']; $versions[$row['id']] = $row; } Cache::save("version:" . $type . ":" . $id, $versions); } return $versions; }
/** * Load an XRD file and caches it. * * @param string $url URL to fetch * * @return Net_WebFinger_Reaction Reaction object with XRD data * * @see loadXrd() */ protected function loadXrdCached($url) { if (!$this->cache) { return $this->loadXrd($url); } //FIXME: make $host secure, remove / and so $cacheId = 'webfinger-cache-' . str_replace(array('/', ':'), '-.-', $url); $cacheRetval = $this->cache->get($cacheId); if ($cacheRetval !== null) { //load from cache return $cacheRetval; } //no cache yet $retval = $this->loadXrd($url); //we do not implement http caching headers yet, so use default // cache lifetime settings $this->cache->save($cacheId, $retval); return $retval; }
public static function load($lang = null) { if (!$lang) { $lang = self::getLanguage(); } $cachekey = "locale:" . $lang; $locale = Cache::load($cachekey); if (!is_array($locale)) { // No cache available -> load from database $sql = new SqlManager(); $sql->setQuery("SELECT * FROM locale WHERE language = {{lang}}"); $sql->bindParam('{{lang}}', $lang, "int"); $sql->execute(); $locale = array(); while ($res = $sql->fetch()) { self::$locales[$lang][$res['code']] = $res['text']; } // Save loaded locales into cache file for later use Cache::save($cachekey, $locale); } }
/** * Renders template to output. * @return void */ public function render() { if ($this->file == NULL) { // intentionally == throw new InvalidStateException("Template file name was not specified."); } elseif (!is_file($this->file) || !is_readable($this->file)) { throw new FileNotFoundException("Missing template file '{$this->file}'."); } $this->__set('template', $this); $cache = new Cache($this->getCacheStorage(), 'Nette.Template'); $key = md5($this->file) . '.' . basename($this->file); $cached = $content = $cache[$key]; if ($content === NULL) { if (!$this->getFilters()) { $this->onPrepareFilters($this); } if (!$this->getFilters()) { /*Nette\Loaders\*/ LimitedScope::load($this->file, $this->getParams()); return; } try { $shortName = $this->file; $shortName = str_replace(Environment::getVariable('templatesDir'), "…", $shortName); } catch (Exception $foo) { } $content = $this->compile(file_get_contents($this->file), "file {$shortName}"); $cache->save($key, $content, array(Cache::FILES => $this->file, Cache::EXPIRE => self::$cacheExpire)); $cached = $cache[$key]; } if ($cached !== NULL && self::$cacheStorage instanceof TemplateCacheStorage) { /*Nette\Loaders\*/ LimitedScope::load($cached['file'], $this->getParams()); fclose($cached['handle']); } else { /*Nette\Loaders\*/ LimitedScope::evaluate($content, $this->getParams()); } }
function guild_list($TFSVersion) { $cache = new Cache('engine/cache/guildlist'); if ($cache->hasExpired()) { if ($TFSVersion != 'TFS_10') { $guilds = mysql_select_multi("SELECT `t`.`id`, `t`.`name`, `t`.`creationdata`, `motd`, (SELECT count(p.rank_id) FROM players AS p LEFT JOIN guild_ranks AS gr ON gr.id = p.rank_id WHERE gr.guild_id =`t`.`id`) AS `total` FROM `guilds` as `t` ORDER BY `t`.`name`;"); } else { $guilds = mysql_select_multi("SELECT `id`, `name`, `creationdata`, `motd`, (SELECT COUNT('guild_id') FROM `guild_membership` WHERE `guild_id`=`id`) AS `total` FROM `guilds` ORDER BY `name`;"); } // Add level data info to guilds if ($guilds !== false) { for ($i = 0; $i < count($guilds); $i++) { $guilds[$i]['level'] = get_guild_level_data($guilds[$i]['id']); } } $cache->setContent($guilds); $cache->save(); } else { $guilds = $cache->load(); } return $guilds; }
public function call() { $cacheEnabled = array_get($this->action, "cacheEnabled") && Config::item("application", "cache", true); if ($cacheEnabled && ($data = Cache::get(URI::current()))) { $headersEnd = strpos($data, "\n\n"); if ($headersEnd > 0) { $headers = explode("\n", substr($data, 0, $headersEnd)); foreach ($headers as $header) { header($header); } } $data = substr($data, $headersEnd + 2); return $data; } $response = $this->response(); if ($cacheEnabled) { $headersList = implode("\n", headers_list()); Cache::save(URI::current(), $headersList . "\n\n" . $response, array_get($this->action, "cacheExpirationTime")); } else { Cache::remove(URI::current()); } return $response; }