public function testSetNoToString()
 {
     $object = new CacheTestNoToSTring();
     $cache = new Cache();
     $this->setExpectedException('PHPUnit_Framework_Error');
     $cache->set($object, 'broken');
 }
Example #2
0
 public function parseDir($dir)
 {
     if (!$dir) {
         return;
     }
     $cache = new Cache($dir);
     $settings = [];
     if (false && $cache->isBuilt()) {
         $settings = $cache->get();
     } else {
         /**
          * @T00D00
          * We need to parse config directory recursively.
          * defaults.php and env.php needs to be taken differently (as root namespace).
          */
         $files = ["defaults" => $dir . 'config' . path('ds') . "defaults.php", "database" => $dir . 'config' . path('ds') . "database.php", "router" => $dir . 'config' . path('ds') . "router.php", "env" => $dir . 'config' . path('ds') . "env.php"];
         foreach ($files as $key => $file) {
             $content = is_file($file) ? require $file : [];
             if (in_array($key, ['defaults', 'env'])) {
                 $settings = $this->merge($settings, $content);
             } else {
                 $settings[$key] = $content;
             }
         }
     }
     $this->data = $this->merge($this->data, $settings);
 }
Example #3
0
 public function act_getUserList()
 {
     $list_english_id = addslashes($_GET['englishId']);
     $list_english_id = trim($list_english_id);
     if ($list_english_id === '') {
         self::$errCode = '5506';
         self::$errMsg = 'Mail englishId is null,please input again!';
         return array();
     } else {
         $cacheName = md5("rss_name_list");
         $memc_obj = new Cache(C('CACHEGROUP'));
         $rssNameInfo = $memc_obj->get_extral($cacheName);
         if (!empty($rssNameInfo)) {
             return unserialize($rssNameInfo);
         } else {
             $getData = new MailApiModel();
             $getUserList = $getData->checkPower($list_english_id);
             $rssNameInfo = $this->checkReturnData($getUserList, array());
             $isok = $memc_obj->set_extral($cacheName, serialize($rssNameInfo), 14400);
             if (!$isok) {
                 self::$errCode = 0;
                 self::$errMsg = 'memcache缓存出错!';
             }
             self::$errCode = mailApiModel::$errCode;
             self::$errMsg = mailApiModel::$errMsg;
             return $rssNameInfo;
         }
     }
 }
Example #4
0
 /**
  * Method to create a nonce, either from a service call (when the caller type is a website) or from the Warehouse
  * (when the caller type is an Indicia user.
  */
 public static function create_nonce($type, $website_id)
 {
     $nonce = sha1(time() . ':' . rand() . $_SERVER['REMOTE_ADDR'] . ':' . kohana::config('indicia.private_key'));
     $cache = new Cache();
     $cache->set($nonce, $website_id, $type, Kohana::config('indicia.nonce_life'));
     return $nonce;
 }
 public function renderFile()
 {
     //Send Content-Type
     $sCharset = Settings::getSetting('encoding', 'browser', 'utf-8');
     if ($this->sType === ResourceIncluder::RESOURCE_TYPE_CSS) {
         header("Content-Type: text/css;charset={$sCharset}");
     } else {
         if ($this->sType === ResourceIncluder::RESOURCE_TYPE_JS) {
             header("Content-Type: text/javascript;charset={$sCharset}");
         }
     }
     //Find consolidated resources
     $aKeys = array();
     while (Manager::hasNextPathItem()) {
         $aKeys[] = Manager::usePath();
     }
     $sKey = 'consolidated-output-' . $this->sType . '-' . implode('|', $aKeys);
     $oCachingStrategy = clone CachingStrategy::fromConfig('file');
     $oCache = new Cache($sKey, 'resource', $oCachingStrategy);
     $oItemCachingStrategy = clone $oCachingStrategy;
     $oItemCachingStrategy->init(array('key_encode' => null));
     $oCache->sendCacheControlHeaders();
     if (!$oCache->entryExists(false)) {
         foreach ($aKeys as $sItemKey) {
             $oItemCache = new Cache($sItemKey, DIRNAME_PRELOAD, $oItemCachingStrategy);
             if (!$oItemCache->entryExists(false)) {
                 throw new Exception("Consolidated resource {$sItemKey} does not exist.");
             }
             $oCache->setContents($oItemCache->getContentsAsString() . "\n", false, true);
         }
     }
     $oCache->sendCacheControlHeaders();
     $oCache->passContents(true);
 }
Example #6
0
 /**
  * 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());
     }
 }
Example #7
0
 public function cachedFrontend($bIsPreview = false)
 {
     $oCacheKey = $this->cacheKey();
     $oCache = null;
     if ($oCacheKey !== null && !$bIsPreview) {
         $sPrefix = 'frontend_module_' . $this->getModuleName() . '_' . ($this->oLanguageObject ? $this->oLanguageObject->getPKString() : 'data_' . $this->oData);
         $oCache = new Cache($oCacheKey->render($sPrefix), DIRNAME_FULL_PAGE);
         $bIsCached = $oCache->entryExists();
         $bIsOutdated = false;
         if ($bIsCached) {
             if ($this->oLanguageObject) {
                 $bIsOutdated = $oCache->isOlderThan($this->oLanguageObject);
             }
             if (!$bIsOutdated) {
                 return $oCache->getContentsAsString();
             }
         }
     }
     $sResult = $this->renderFrontend();
     if ($sResult instanceof Template) {
         $sResult = $sResult->render();
     }
     if ($oCache) {
         $oCache->setContents($sResult);
     }
     return $sResult;
 }
Example #8
0
 /**
  * Returns the value of a view ane merges the config with any data passed to it
  *
  * @param   string        name of view
  * @param   boolean|array optional array of data to pass to the view
  * @param   string        file extension
  * @param   boolean|int   lifetime of cache. if set to true it will use the default
  *                            cache from the pages config or use an int if it is passed one
  * @return  string        contents of view or cache file
  */
 public static function view($view, $config = FALSE, $type = FALSE, $lifetime = FALSE)
 {
     $page = Pages::instance();
     // Setup caching and return the cache file it it works
     if ($lifetime) {
         $cache = new Cache();
         $cache_name = $page->getCacheIdForView($view . $type . serialize($data));
         if ($output = $cache->get($cache_name)) {
             return $output;
         }
     }
     // Load the view
     $view = new View($view, $config, $type);
     $output = $view->render();
     // Convert to markdown automatically
     if ($type == 'markdown' || $type == 'mdown' || $type == 'md') {
         $output = markdown::to_html($output);
     }
     // Store into cache
     if ($lifetime) {
         // Setup lifetime
         if ($lifetime === TRUE) {
             $lifetime = $page->cache_lifetime;
         } else {
             $lifetime = (int) $lifetime;
         }
         // Store the cache
         $cache->set($cache_name, $output, NULL, $lifetime);
     }
     return $output;
 }
Example #9
0
 protected function setUrlToCache()
 {
     $url = $this->findUrlFromDB();
     $cache = new \Cache(['path' => __DIR__ . '/../runtime/redirectCache/', 'name' => 'default', 'extension' => '.cache']);
     $cache->store($this->currentUrl, $url);
     return $url;
 }
 function indexAction()
 {
     /* @var $model CidadesModel */
     $model = newModel('CidadesModel');
     /* @var $v CidadeVO */
     $start = microtime(true);
     $estado = url_parans(0) ? url_parans(0) : inputPost('estado');
     $cidade = url_parans(1) ? url_parans(1) : inputPost('cidade');
     if ($estado > 0 or preg_match('/^[A-Z]{2}$/i', $estado)) {
         $cache = new Cache('cidades.' . $estado, 60);
         if (!($options = $cache->getContent())) {
             $cidades = $model->getCidades($estado);
             if (count($cidades)) {
                 $options = formOption('-- Selecione a cidade --', '');
             } else {
                 $options = formOption('-- Selecione o estado --', '');
             }
             foreach ($cidades as $v) {
                 $options .= formOption($v->getTitle(), $v->getId(), false);
             }
             # Salvando cache
             $cache->setContent($options);
         }
         echo preg_replace(['/(value="' . preg_quote($cidade) . '")/', '/>(' . preg_quote($cidade) . ')</'], ['$1 selected=""', 'selected="" >$1<'], $options);
     }
     $end = microtime(true);
     echo "\n\n<!-- " . number_format(($end - $start) * 1000, 5, ',', '.') . "ms --> Buscou por {$cidade}";
     exit;
 }
 /**
  * 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());
     }
 }
Example #12
0
function osc_latestTweets($num = 5)
{
    require_once osc_lib_path() . 'osclass/classes/Cache.php';
    $cache = new Cache('admin-twitter', 900);
    if ($cache->check()) {
        return $cache->retrieve();
    }
    $list = array();
    $content = osc_file_get_contents('https://twitter.com/statuses/user_timeline/osclass.rss');
    if ($content) {
        $xml = simplexml_load_string($content);
        if (isset($xml->error)) {
            return $list;
        }
        $count = 0;
        foreach ($xml->channel->item as $item) {
            $list[] = array('link' => strval($item->link), 'title' => strval($item->title), 'pubDate' => strval($item->pubDate));
            $count++;
            if ($count == $num) {
                break;
            }
        }
    }
    $cache->store($list);
    return $list;
}
Example #13
0
 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);
     }
 }
Example #14
0
 public function common($params)
 {
     $Register = Register::getInstance();
     $output = '';
     if (!strpos($params, '{{ users_rating }}')) {
         return $params;
     }
     $Cache = new Cache();
     $Cache->lifeTime = 600;
     if ($Cache->check('pl_users_rating')) {
         $users = $Cache->read('pl_users_rating');
         $users = json_decode($users, true);
     } else {
         $users = $this->DB->select('users', DB_ALL, array('order' => '`rating` DESC', 'limit' => $this->limit));
         //$users = $this->DB->query($sql);
         $Cache->write(json_encode($users), 'pl_users_rating', array());
     }
     if (!empty($users)) {
         foreach ($users as $key => $user) {
             $link = get_link($user['name'], getProfileUrl($user['id']));
             $ava = file_exists(ROOT . '/sys/avatars/' . $user['id'] . '.jpg') ? get_url('/sys/avatars/' . $user['id'] . '.jpg') : get_url('/sys/img/noavatar.png');
             $output .= sprintf($this->wrap, $ava, $link, $user['rating'], $user['posts']);
         }
     }
     $output .= '<div class="etopu">' . get_link('Весь рейтинг', '/users/index?order=rating') . '</div>';
     return str_replace('{{ users_rating }}', $output, $params);
 }
Example #15
0
 public function actSendList()
 {
     $is_new = isset($_REQUEST["is_new"]) ? $_REQUEST["is_new"] : 0;
     if (!in_array($is_new, array(0, 1))) {
         self::$errCode = 10000;
         self::$errMsg = "更新参数非法!";
         return false;
     }
     $cacheName = md5("notice_name_list");
     $memc_obj = new Cache(C('CACHEGROUP'));
     $noticeNameInfo = $memc_obj->get_extral($cacheName);
     if (!empty($noticeNameInfo) && empty($is_new)) {
         return unserialize($noticeNameInfo);
     } else {
         $noticeNameInfo = NoticeApiModel::showNameList();
         self::$errCode = NoticeApiModel::$errCode;
         self::$errMsg = NoticeApiModel::$errMsg;
         $isok = $memc_obj->set_extral($cacheName, serialize($noticeNameInfo), 14400);
         if (!$isok) {
             self::$errCode = 0;
             self::$errMsg = 'memcache缓存出错!';
             //return false;
         }
         return $noticeNameInfo;
     }
 }
Example #16
0
 /**
  * Loads all the static strings from either the cache or the ini files. Note that ini files in modules are not verified for outdatedness, so if they were updated, just clear all the caches or hard reload a page
  * This method should not be called directly from outsite TranslationPeer except for testing and debugging purposes
  */
 public static function getStaticStrings($sLanguageId)
 {
     if (!isset(self::$STATIC_STRINGS[$sLanguageId])) {
         $oCache = new Cache($sLanguageId, DIRNAME_LANG);
         $aLanguageFiles = ResourceFinder::create()->addPath(DIRNAME_LANG, "{$sLanguageId}.ini")->all()->baseFirst()->find();
         if ($oCache->entryExists() && !$oCache->isOutdated($aLanguageFiles)) {
             self::$STATIC_STRINGS[$sLanguageId] = $oCache->getContentsAsVariable();
         } else {
             self::$STATIC_STRINGS[$sLanguageId] = array();
             //Get default strings
             foreach ($aLanguageFiles as $sLanguageFile) {
                 self::$STATIC_STRINGS[$sLanguageId] = array_merge(self::$STATIC_STRINGS[$sLanguageId], parse_ini_file($sLanguageFile));
             }
             //Get strings for modules
             foreach (ResourceFinder::create()->addExpression(DIRNAME_MODULES, ResourceFinder::ANY_NAME_OR_TYPE_PATTERN, ResourceFinder::ANY_NAME_OR_TYPE_PATTERN, DIRNAME_LANG, "{$sLanguageId}.ini")->all()->baseFirst()->find() as $sLanguageFile) {
                 self::$STATIC_STRINGS[$sLanguageId] = array_merge(self::$STATIC_STRINGS[$sLanguageId], parse_ini_file($sLanguageFile));
             }
             //Fix string encoding
             foreach (self::$STATIC_STRINGS[$sLanguageId] as $sStringKey => $sValue) {
                 self::$STATIC_STRINGS[$sLanguageId][$sStringKey] = StringUtil::encodeForDbFromFile($sValue);
             }
             $oCache->setContents(self::$STATIC_STRINGS[$sLanguageId]);
         }
     }
     return self::$STATIC_STRINGS[$sLanguageId];
 }
Example #17
0
 public function validate(Validation $array, $save = FALSE)
 {
     // uses PHP trim() to remove whitespace from beginning and end of all fields before validation
     $array->pre_filter('trim');
     // merge unvalidated fields, in case the subclass has set any.
     if (!isset($this->unvalidatedFields)) {
         $this->unvalidatedFields = array();
     }
     $this->unvalidatedFields = array_merge($this->unvalidatedFields, array('validation_rules', 'public', 'multi_value', 'deleted'));
     $array->add_rules('caption', 'required');
     $array->add_rules('data_type', 'required');
     if (array_key_exists('data_type', $array->as_array()) && $array['data_type'] == 'L') {
         if (empty($array['termlist_id'])) {
             $array->add_rules('termlist_id', 'required');
         } else {
             array_push($this->unvalidatedFields, 'termlist_id');
         }
     }
     $array->add_rules('system_function', 'length[1,30]');
     $parent_valid = parent::validate($array, $save);
     // clean up cached required fields in case validation rules have changed
     $cache = Cache::instance();
     $cache->delete_tag('required-fields');
     if ($save && $parent_valid) {
         // clear the cache used for attribute datatype and validation rules since the attribute has changed
         $cache = new Cache();
         // Type is the object name with _attribute stripped from the end
         $type = substr($this->object_name, 0, strlen($this->object_name) - 10);
         $cache->delete('attrInfo_' . $type . '_' . $this->id);
     }
     return $save && $parent_valid;
 }
 public static function addEntry($bID, $commentText, $name, $email, $approved, $cID, $uID = 0, $timestamp = null)
 {
     $txt = Loader::helper('text');
     $db = Loader::db();
     $query = "INSERT INTO btGuestBookEntries (bID, cID, uID, user_name, user_email, commentText, approved, entryDate) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
     $v = array($bID, $cID, intval($uID), $txt->sanitize($name), $txt->sanitize($email), $txt->sanitize($commentText), $approved, $timestamp);
     $res = $db->query($query, $v);
     $number = 1;
     //stupid cache stuff
     $ca = new Cache();
     $db = Loader::db();
     $count = $ca->get('GuestBookCount', $cID . "-" . $bID);
     if ($count && $number) {
         $count += $number;
     } else {
         $q = 'SELECT count(bID) as count
 FROM btGuestBookEntries
 WHERE bID = ?
 AND cID = ?
 AND approved=1';
         $v = array($bID, $cID);
         $rs = $db->query($q, $v);
         $row = $rs->FetchRow();
         $count = $row['count'];
     }
     $ca->set('GuestBookCount', $cID . "-" . $bID, $count);
 }
Example #19
0
 /**
  * @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());
 }
Example #20
0
 public function encodedKey(Cache $oCache)
 {
     $sKey = $oCache->getKey();
     if ($this->key_encode) {
         $sKey = call_user_func($this->key_encode, $sKey);
     }
     return $sKey;
 }
Example #21
0
 public function testPing()
 {
     $this->assertEquals('+PONG', $this->cache->X()->ping());
     $count = 1000;
     while ($count--) {
         $this->assertEquals('+PONG', $this->cache->X()->ping());
     }
 }
Example #22
0
 public function after()
 {
     parent::after();
     if ($this->cache === TRUE && $this->request->status === 200 && $this->session->user->manage_dash_mods === null) {
         $cache = new Cache($this->cache_config);
         $cache->set($this->request->uri . ' :: ' . $this->session->group, $this->request->response, $this->cache_tag, $this->cache_lifetime);
     }
 }
Example #23
0
 /**
  * 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;
 }
 /**
  * @see system_list_reset()
  */
 function systemListReset()
 {
     $this->drupalStatic->resetKey('system_list');
     $this->drupalStatic->resetKey('system_rebuild_module_data');
     $this->drupalStatic->resetKey('list_themes');
     $this->cache->cacheClearAll('bootstrap_modules', 'cache_bootstrap');
     $this->cache->cacheClearAll('system_list', 'cache_bootstrap');
 }
Example #25
0
 /**
  * @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;
 }
 function initInstance()
 {
     //instance conf
     $instanceCache = new Cache($this->initer['db'], $this->initer['log']);
     $this->initer['cacheisallowed'] = $instanceCache->checkcacheisallowed();
     //set instance before return
     $this->setInstance($instanceCache);
     return $cache = $instanceCache->cacheselected;
 }
Example #27
0
 /**
  * Parse a given file for defintions of classes, traits and interfaces
  *
  * @param SourceFile $source file to process
  *
  * @return ParseResult
  */
 public function parse(SourceFile $source)
 {
     if ($this->cache->hasResult($source)) {
         return $this->cache->getResult($source);
     }
     $result = $this->parser->parse($source);
     $this->cache->addResult($source, $result);
     return $result;
 }
Example #28
0
 /**
  * Take a project key and return the properties
  *
  * @param string $identifier
  * @return array
  */
 public function project($identifier)
 {
     if (!$this->cache->has($identifier)) {
         $html = $this->fetch($identifier);
         $project = $this->parse($html);
         $this->cache->set($identifier, $project, $this->expiry);
     }
     return $this->cache->get($identifier);
 }
Example #29
0
 function __construct($location = NULL)
 {
     parent::__construct();
     $this->globalModel = array();
     $cache = new Cache();
     $cache->checkCacheFile(array(__CACHE__ . '/action' => array('listener' => 'dirExists', 'callback' => array($this, 'buildCache'))));
     $this->location = $location;
     $this->isFile = false;
 }
Example #30
0
 /**
  * remove deleted files in $path from the cache
  *
  * @param string $path
  */
 public function cleanFolder($path)
 {
     $cachedContent = $this->cache->getFolderContents($path);
     foreach ($cachedContent as $entry) {
         if (!$this->storage->file_exists($entry['path'])) {
             $this->cache->remove($entry['path']);
         }
     }
 }