/** * Invalidate all cached resources where the specified user ids were used as either the * owner or viewer id when a signed or OAuth request was made for the content by the application * identified in the security token. * @param opensocialIds Set of user ids to invalidate authenticated/signed content for * @param token identifying the calling application */ function invalidateUserResources(array $opensocialIds, SecurityToken $token) { foreach ($opensocialIds as $opensocialId) { ++self::$marker; self::$makerCache->set('marker', self::$marker); $this->invalidationEntry->set($this->getKey($opensocialId, $token), self::$marker); } }
public function get($groupName, $identifier, $function = null, $arguments = array()) { $ret = $this->cache->get($groupName, $identifier, $this->lifetime); if ($ret == false && $function != null) { $ret = call_user_func_array($function, $arguments); $this->cache->set($groupName, $identifier, $ret); } return $ret; }
/** * 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); }
/** * 获取jsticket * * @return string */ public function getTicket() { $key = 'overtrue.wechat.jsapi_ticket' . $this->appId; return $this->cache->get($key, function ($key) { $http = new Http(new AccessToken($this->appId, $this->appSecret)); $result = $http->get(self::API_TICKET); $this->cache->set($key, $result['ticket'], $result['expires_in']); return $result['ticket']; }); }
/** * 获取颜色列表 * * @return array */ public function lists() { $key = 'overtrue.wechat.colors'; return $this->cache->get($key, function ($key) { $result = $this->http->get(self::API_LIST); $this->cache->set($key, $result['colors'], 86400); // 1 day return $result['colors']; }); }
function test_flush() { $c = new Cache(); $c->set('foo', 'test', 0, 10); $c->set('bar', 'test2'); $this->assertTrue($c->flush()); // check that it also flushed dot-files for timeouts too $files = glob($c->dir . '/{,.}*', GLOB_BRACE); $this->assertEquals(count($files), 2); }
/** * Save values for a set of keys to cache * * @param array $keys list of values to save * @param int $expire expiration time * @return boolean true on success, false on failure */ protected function write(array $keys, $expire = null) { #echo "writing template to cache"; #printArray($keys); foreach ($keys as $k => $v) { $k = sha1($k); $rs = $this->Cache->set($k, $v, 0, $expire); } #$this->Cache->setMulti($keys, $expire); return true; }
/** * 获取Token * * @param bool $forceRefresh * * @return string */ public function getToken($forceRefresh = false) { $cacheKey = $this->cacheKey; $cached = $this->cache->get($cacheKey); if ($forceRefresh || !$cached) { $token = $this->getTokenFromServer(); $this->cache->set($cacheKey, $token['access_token'], $token['expires_in'] - 800); return $token['access_token']; } return $cached; }
function act_set() { $value = $_GET['value']; $cache = new Cache("group11"); $cache->set("key1", $value, "60"); return array(); }
/** * @param string $image_ * * @return \Components\Uri */ public static function uriForPath($image_) { $extension = Io::fileExtension($image_); $key = md5($image_); Cache::set($key, $image_); return Environment::uriComponents('ui', 'image', "{$key}.{$extension}"); }
public function get($id = 0, $useCache = true) { if (!$id) { $id =& $this->id; } if ($useCache && ($cache = Cache::get($id))) { return $cache; } parent::get($id, !USE_CACHE); $this->photos = array(); $i = 0; if (!is_array($this->files['photo'])) { return $this; } foreach ($this->files['photo'] as &$f) { $f->main =& Image::createThumbnail($f->name, $this->folder->config['imgWidth']); $f->thumb =& Image::createThumbnail($f->name, $this->folder->config['imgThumbWidth']); if (++$i == 1) { $f->fpthumb =& Image::createThumbnail($f->name, $this->folder->config['fpThumbWidth']); } $this->photos[] = $f; } if ($this->pub_on > 0) { Cache::set($id, $this); } return $this; }
public function beforeFilter() { $this->Auth->loginAction = array('controller' => 'users', 'action' => 'login', 'admin' => false); $this->Auth->loginRedirect = array('controller' => 'users', 'action' => 'index', 'admin' => true); $this->Auth->logoutRedirect = array('controller' => 'contents', 'action' => 'homepage', 'admin' => false, 'vendor' => false); $this->Auth->authorize = array('Controller'); $this->Auth->authenticate = array(AuthComponent::ALL => array('userModel' => 'User', 'fields' => array('username' => 'username', 'password' => 'password'), 'scope' => array('User.active' => 1)), 'Form'); if (isset($this->request->params['admin']) && $this->request->params['prefix'] == 'admin') { $this->set('authUser', $this->Auth->user()); $this->layout = 'admin'; } elseif (isset($this->request->params['vendor']) && $this->request->params['prefix'] == 'vendor') { $this->set('authUser', $this->Auth->user()); $this->layout = 'vendor'; } else { $this->Auth->allow(); $menucategories = Cache::read('menucategories'); if (!$menucategories) { $menucategories = ClassRegistry::init('Product')->find('all', array('recursive' => -1, 'contain' => array('User', 'Category'), 'fields' => array('Category.id', 'Category.name', 'Category.slug'), 'conditions' => array('User.active' => 1, 'Product.active' => 1, 'Product.category_id >' => 0, 'Category.id >' => 0), 'order' => array('Category.name' => 'ASC'), 'group' => array('Category.id'))); Cache::set(array('duration' => '+10 minutes')); Cache::write('menucategories', $menucategories); } $this->set(compact('menucategories')); $menuvendors = Cache::read('menuvendors'); if (!$menuvendors) { $menuvendors = ClassRegistry::init('User')->getVendors(); Cache::set(array('duration' => '+10 minutes')); Cache::write('menuvendors', $menuvendors); } $this->set(compact('menuvendors')); } if ($this->RequestHandler->isAjax()) { $this->layout = 'ajax'; } $this->AutoLogin->settings = array('model' => 'Member', 'username' => 'name', 'password' => 'pass', 'plugin' => '', 'controller' => 'members', 'loginAction' => 'signin', 'logoutAction' => 'signout', 'cookieName' => 'rememberMe', 'expires' => '+1 month', 'active' => true, 'redirect' => true, 'requirePrompt' => true); }
public function embed_gists($content) { $gists_regex = '/<script[^>]+src="(http:\\/\\/gist.github.com\\/[^"]+)"[^>]*><\\/script>/i'; // remove gists from multiple-post templates if (Options::get('gistextras__removefrommultiple')) { if (!in_array(URL::get_matched_rule()->name, array('display_entry', 'display_page'))) { return preg_replace($gists_regex, '', $content); } } preg_match_all($gists_regex, $content, $gists); for ($i = 0, $n = count($gists[0]); $i < $n; $i++) { if (Options::get('gistextras__cachegists')) { if (Cache::has($gists[1][$i])) { $gist = Cache::get($gists[1][$i]); } else { if ($gist = RemoteRequest::get_contents($gists[1][$i])) { $gist = $this->process_gist($gist); Cache::set($gists[1][$i], $gist, 86400); // cache for 1 day } } } else { $gist = RemoteRequest::get_contents($gists[1][$i]); $gist = $this->process_gist($gist); } // replace the script tag $content = str_replace($gists[0][$i], $gist, $content); } return $content; }
public function getCountries($data = array()) { $cache = 'countries.' . json_encode($data); $return = Cache::find($cache); if (is_array($return)) { return $return; } $sql = "SELECT * FROM PREFIX_country"; $sort_data = array('name', 'iso_code_2', 'iso_code_3'); if (isset($data['sort']) && in_array($data['sort'], $sort_data)) { $sql .= " ORDER BY " . $data['sort']; } else { $sql .= " ORDER BY name"; } if (isset($data['order']) && $data['order'] == 'DESC') { $sql .= " DESC"; } else { $sql .= " ASC"; } if (isset($data['start']) || isset($data['limit'])) { if ($data['start'] < 0) { $data['start'] = 0; } if ($data['limit'] < 1) { $data['limit'] = 20; } $sql .= " LIMIT " . (int) $data['start'] . "," . (int) $data['limit']; } $return = $this->fetchAll($sql); Cache::set($cache, $return); return $return; }
public function getWeightClasses($data = array()) { if ($data) { $sql = "SELECT * FROM " . DB_PREFIX . "weight_class wc LEFT JOIN " . DB_PREFIX . "weight_class_description wcd ON (wc.weight_class_id = wcd.weight_class_id) WHERE wcd.language_id = '" . (int) $this->config->get('config_language_id') . "'"; $sort_data = array('title', 'unit', 'value'); if (isset($data['sort']) && in_array($data['sort'], $sort_data)) { $sql .= " ORDER BY " . $data['sort']; } else { $sql .= " ORDER BY title"; } if (isset($data['order']) && $data['order'] == 'DESC') { $sql .= " DESC"; } else { $sql .= " ASC"; } if (isset($data['start']) || isset($data['limit'])) { if ($data['start'] < 0) { $data['start'] = 0; } if ($data['limit'] < 1) { $data['limit'] = 20; } $sql .= " LIMIT " . (int) $data['start'] . "," . (int) $data['limit']; } $query = $this->db->query($sql); return $query->rows; } else { $weight_class_data = Cache::find('weight_class.' . (int) $this->config->get('language_id')); if (!$weight_class_data) { $weight_class_data = $this->fetchAll("SELECT * FROM PREFIX_weight_class wc\n LEFT JOIN PREFIX_weight_class_description wcd ON (wc.weight_class_id = wcd.weight_class_id)\n WHERE wcd.language_id = '" . (int) $this->config->get('language_id') . "'"); Cache::set('weight_class.' . (int) $this->config->get('language_id'), $weight_class_data); } return $weight_class_data; } }
public function purify($html, $options = array()) { if (empty($html)) { return ''; } require_once Config::get('HTML_PURIFIER'); require_once 'HTMLPurifier.func.php'; $html = Util\toUTF8String($html); $config = \HTMLPurifier_Config::createDefault(); $config->set('AutoFormat.AutoParagraph', false); $config->set('AutoFormat.RemoveEmpty.RemoveNbsp', true); //$config->set('AutoFormat.RemoveEmpty', true);//slows down htmls parsing //$config->set('AutoFormat.RemoveSpansWithoutAttributes', true); //medium slows down htmls parsing $config->set('HTML.ForbiddenElements', array('head')); $config->set('HTML.SafeIframe', true); $config->set('HTML.TargetBlank', true); $config->set('URI.DefaultScheme', 'https'); $config->set('Attr.EnableID', true); if (!empty($options)) { foreach ($options as $k => $v) { $config->set($k, $v); } } $purifier = new \HTMLPurifier($config); // This storage is freed on error Cache::set('memory', str_repeat('*', 1024 * 1024)); register_shutdown_function(array($this, 'onScriptShutdown')); $html = $purifier->purify($html); Cache::remove('memory'); $html = str_replace('/preview/#', '#', $html); return $html; }
function action_add_template_vars($theme) { $username = Options::get('freshsurf__username'); $password = Options::get('freshsurf__password'); $count = Options::get('freshsurf__count'); if ($username != '' && $password != '') { if (Cache::has('freshsurf__' . $username)) { $response = Cache::get('freshsurf__' . $username); } else { $request = new RemoteRequest("https://{$username}:{$password}@" . self::BASE_URL . "posts/recent?count={$count}", 'GET', 20); $request->execute(); $response = $request->get_response_body(); Cache::set('freshsurf__' . $username, $response); } $delicious = @simplexml_load_string($response); if ($delicious instanceof SimpleXMLElement) { $theme->delicious = $delicious; } else { $theme->delicious = @simplexml_load_string('<posts><post href="#" description="Could not load feed from delicious. Is username/password correct?"/></posts>'); Cache::expire('freshsurf__' . $username); } } else { $theme->delicious = @simplexml_load_string('<posts></posts>'); } }
/** Retrieve from cache; or save query results to cache if not previously executed @param $query array @param $ttl int @private **/ private function cache(array $query, $ttl) { $cmd = json_encode($query, TRUE); $hash = 'mdb.' . self::hash($cmd); $cached = Cache::cached($hash); $db = (string) $this->db; $stats =& self::ref('STATS'); if ($ttl && $cached && $_SERVER['REQUEST_TIME'] - $cached < $ttl) { // Gather cached queries for profiler if (!isset($stats[$db]['cache'][$cmd])) { $stats[$db]['cache'][$cmd] = 0; } $stats[$db]['cache'][$cmd]++; // Retrieve from cache return Cache::get($hash); } else { $result = $this->exec($query); if ($ttl) { Cache::set($hash, $result, $ttl); } // Gather real queries for profiler if (!isset($stats[$db]['queries'][$cmd])) { $stats[$db]['queries'][$cmd] = 0; } $stats[$db]['queries'][$cmd]++; return $result; } }
public function action_search() { $coupons = ""; try { $coupons = unserialize(Cache::get('cache_coupons')); } catch (\CacheNotFoundException $e) { $curl = Request::forge('http://allcoupon.jp/api-v1/coupon', 'curl'); $curl->set_params(array('output' => 'json', 'apikey' => '9EBgSyRbAPmutrWE')); // this is going to be an HTTP POST $curl->set_method('get'); $curl->set_auto_format(true); $result = $curl->execute()->response(); $coupons = json_decode($result->body); Cache::set('cache_coupons', serialize($coupons), 300); } if ($area = Input::get('area')) { $coupons = array_filter($coupons, function ($v, $k) { return $v->coupon_area == Input::get('area'); }, ARRAY_FILTER_USE_BOTH); } if ($category = Input::get('category')) { $coupons = array_filter($coupons, function ($v, $k) { return $v->category_name == Input::get('category'); }, ARRAY_FILTER_USE_BOTH); } $view = Presenter::forge('home/search'); $view->set('title', $area, false); $view->set('area', $area, false); $view->set('category', $category, false); $view->set('coupons', $coupons, false); $this->template->content = $view; }
public function filter_rssblocks_update($success, $force = false) { EventLog::log('Running rrsblocks update'); $blocks = DB::get_results('SELECT b.* FROM {blocks} b WHERE b.type = ?', array('rssblock'), 'Block'); Plugins::act('get_blocks', $blocks); $success = true; foreach ($blocks as $block) { $cachename = array('rssblock', md5($block->feed_url)); if ($force || Cache::expired($cachename)) { $r = new RemoteRequest($block->feed_url); $r->set_timeout(10); $r->execute(); $feed = $r->get_response_body(); try { if (is_string($feed)) { new SimpleXMLElement($feed); // This throws an exception if the feed isn't valid Cache::set($cachename, $feed, 3600, true); } } catch (Exception $e) { $success = false; } } } Session::notice('ran rssblocks update'); return $success; }
private function update_cache() { $archives = $this->get_monthly_archives(); $class_name = strtolower(get_class($this)); Cache::set($class_name . ':list', $archives, $this->cache_expiry); $this->monthly_archives = $archives; }
/** * Dispatch a single controller. Fetch from cache (if any), execute, store cache, return output. * * @param string $controller Name of controller to execute. * @param array $params Additional parameters needed by the controller * @return string */ public function dispatchSingleController($controller, $params = array()) { $benchmark_key = 'controller_execution_time'; $this->startBench($benchmark_key); $module = Bootstrap::invokeController($controller); $module->setParams(array_merge($this->getParams(), $params)); $module->preDispatch(); $cached_content = $module->grabCache(); $class_name = get_class($module); if (false !== $cached_content) { $module_content = $cached_content; } else { $cache_key = $module->parseCache(); if (false !== $cache_key) { $module->addToDebug('name', $cache_key['name'], 'Cache properties'); $module->addToDebug('expiration', $cache_key['expiration'], 'Cache properties'); } $module_content = $module->execute(); } $cache_key = $module->parseCache(); if (false !== $cache_key) { $this->cache->set($cache_key['name'], $module_content, $cache_key['expiration']); } $module->postDispatch(); $this->stopBench($benchmark_key, "{$class_name}: TOTAL module execution"); return $module_content; }
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); }
public function test_has_group() { Cache::expire(array('*', 'bar'), 'glob'); $this->assertFalse(Cache::has_group('foo'), 'The cache has a group that was explicitly expired.'); Cache::set(array('foo', 'bar'), 'a value'); $this->assertTrue(Cache::has_group('foo'), 'The cache does not have a group that was explicitly set.'); }
/** * 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; }
function getWeather($loc, $units = 'metric', $lang = 'en', $appid = '', $cachetime = 0) { $url = "http://api.openweathermap.org/data/2.5/weather?q=" . $loc . "&appid=" . $appid . "&lang=" . $lang . "&units=" . $units . "&mode=xml"; $cached = Cache::get('curweather' . md5($url)); $now = new DateTime(); if (!is_null($cached)) { $cdate = get_pconfig(local_user(), 'curweather', 'last'); $cached = unserialize($cached); if ($cdate + $cachetime > $now->getTimestamp()) { return $cached; } } try { $res = new SimpleXMLElement(fetch_url($url)); } catch (Exception $e) { info(t('Error fetching weather data.\\nError was: ' . $e->getMessage())); return false; } if ((string) $res->temperature['unit'] === 'metric') { $tunit = '°C'; $wunit = 'm/s'; } else { $tunit = '°F'; $wunit = 'mph'; } if (trim((string) $res->weather['value']) == trim((string) $res->clouds['name'])) { $desc = (string) $res->clouds['name']; } else { $desc = (string) $res->weather['value'] . ', ' . (string) $res->clouds['name']; } $r = array('city' => (string) $res->city['name'][0], 'country' => (string) $res->city->country[0], 'lat' => (string) $res->city->coord['lat'], 'lon' => (string) $res->city->coord['lon'], 'temperature' => (string) $res->temperature['value'][0] . $tunit, 'pressure' => (string) $res->pressure['value'] . (string) $res->pressure['unit'], 'humidity' => (string) $res->humidity['value'] . (string) $res->humidity['unit'], 'descripion' => $desc, 'wind' => (string) $res->wind->speed['name'] . ' (' . (string) $res->wind->speed['value'] . $wunit . ')', 'update' => (string) $res->lastupdate['value'], 'icon' => (string) $res->weather['icon']); set_pconfig(local_user(), 'curweather', 'last', $now->getTimestamp()); Cache::set('curweather' . md5($url), serialize($r), CACHE_HOUR); return $r; }
public function details($params){ //Set top carousel $carousel = $this->db->getGroupsCarouselDetails($params['detail']); parent::set('carouselImage', $carousel); parent::set('carouselFolder', 'accomodation'); parent::set('carouselAction', 'winter'); parent::set('carouselPage', 'accomodation_id'); //Main table if(!Cache::get(array('key' => 'accType'.$params['group']))){ $output = $this->db->getAccType($params); Cache::set(array('key' => 'accType'.$params['group'], 'data' => $output)); }else $output = Cache::get(array('key' => 'accType'.$params['group'])); parent::set('accType', $output); //Accomodation if(!Cache::get(array('key' => 'oneAccom'.$params['detail']))){ $output = $this->db->getOneAcc($params); Cache::set(array('key' => 'oneAccom'.$params['detail'], 'data' => $output)); }else $output = Cache::get(array('key' => 'oneAccom'.$params['detail'])); parent::set('accom', $output); //Active page parent::set('active', 'zimovanja'); //Params parent::set('params', $params); parent::set('front', $this->db->getDescriptionAndKeywords('accomodations', $params['detail'])); }
/** * Gets killmails. * * @param $parameters an array of parameters to fetch mails for * @param $allTime gets all mails from the beginning of time or not * * @return array */ public static function getKills($parameters = array(), $allTime = true, $includeKillDetails = true) { global $mdb; $hashKey = 'Kills::getKills:' . serialize($parameters); $result = Cache::get($hashKey); //if ($result != null) return $result; $kills = MongoFilter::getKills($parameters); if ($includeKillDetails == false) { return $kills; } $details = []; foreach ($kills as $kill) { $killID = (int) $kill['killID']; $killHashKey = "killDetail:{$killID}"; $killmail = Cache::get($killHashKey); if ($killmail == null) { $killmail = $mdb->findDoc('killmails', ['killID' => $killID, 'cacheTime' => 3600]); Info::addInfo($killmail); $killmail['victim'] = $killmail['involved'][0]; $killmail['victim']['killID'] = $killID; foreach ($killmail['involved'] as $inv) { if (@$inv['finalBlow'] === true) { $killmail['finalBlow'] = $inv; } } $killmail['finalBlow']['killID'] = $killID; unset($killmail['_id']); Cache::set($killHashKey, $killmail, 3600); } $details[$killID] = $killmail; } Cache::set($hashKey, $details, 60); return $details; }
public function testSetNoToString() { $object = new CacheTestNoToSTring(); $cache = new Cache(); $this->setExpectedException('PHPUnit_Framework_Error'); $cache->set($object, 'broken'); }
function afterLayout() { if (Configure::read('Cache.disable') || Configure::read('ViewMemcache.disable')) { return true; } try { if (!empty($this->_View->viewVars['enableViewMemcache'])) { if (isset($this->_View->viewVars['viewMemcacheDuration'])) { // CakeLog::write('debug', "ViewMemCache: duration override: {$this->_View->viewVars['viewMemcacheDuration']}"); @Cache::set(array('duration' => $this->_View->viewVars['viewMemcacheDuration'], null, 'view_memcache')); //'+30 days' or seconds } if (!isset($this->_View->viewVars['viewMemcacheNoFooter'])) { //CakeLog::write('debug', "ViewMemCache: footer disabled"); $this->cacheFooter = "\n<!-- ViewCached"; if ($this->gzipContent) { $this->cacheFooter .= ' gzipped'; } $this->cacheFooter .= ' ' . date('r') . ' -->'; } if ($this->gzipContent && empty($this->_View->viewVars['viewMemcacheDisableGzip'])) { //CakeLog::write('debug', "ViewMemCache: gzipping ".$this->request->here."\n\n".var_export($this->request,true)."\n\n".var_export($_SERVER,true)); @Cache::write($this->request->here, gzencode($this->_View->output . $this->cacheFooter, $this->compressLevel), 'view_memcache'); } else { //CakeLog::write('debug', "ViewMemCache: NOT gzipping "); @Cache::write($this->request->here, $this->_View->output . $this->cacheFooter, 'view_memcache'); } } } catch (Exception $e) { //do nothing } return true; }