protected function _read() { $settingsFile = CONFIGS . DS . 'settings.php'; include $settingsFile; if (!isset($settings)) { trigger_error(sprintf(__('Missing settings file[%s] or $settings could not be found', true), $settingsFile)); return array(); } $records = $this->find('all'); foreach ($records as $record) { switch ($record['Setting']['name']) { case 'per_page_options': $settings[$record['Setting']['name']] = explode(',', $record['Setting']['value']); break; case 'issue_list_default_columns': $settings[$record['Setting']['name']] = Spyc::YAMLLoad($record['Setting']['value']); // array_slice(array_map('trim',explode('- ',$v['Setting']['value'])),1); break; default: $settings[$record['Setting']['name']] = $record['Setting']['value']; } } Cache::write(self::$__cacheKey, $settings); return $settings; }
/** * admin_index * * @param id integer aco id, when null, the root ACO is used * @return void */ public function admin_index($id = null, $level = null) { $this->set('title_for_layout', __('Permissions')); if ($id == null) { $root = $this->AclAco->node('controllers'); $root = $root[0]; } else { $root = $this->AclAco->read(null, $id); } if ($level !== null) { $level++; } $acos = $this->AclAco->getChildren($root['Aco']['id']); $roles = $this->Role->find('list'); $this->set(compact('acos', 'roles', 'level')); $aros = $this->AclAro->getRoles($roles); if ($this->RequestHandler->ext == 'json') { $options = array_intersect_key($this->request->query, array('perms' => null, 'urls' => null)); $cacheName = 'permissions_aco_' . $root['Aco']['id']; $permissions = Cache::read($cacheName, 'permissions'); if ($permissions === false) { $permissions = $this->AclPermission->format($acos, $aros, $options); Cache::write($cacheName, $permissions, 'permissions'); } } else { $permissions = array(); } $this->set(compact('aros', 'permissions')); }
function lookup(&$model, $title, $field = 'id', $create = true) { $ret = null; if (($ret = Cache::read("{$model->alias}.lookup.{$title}")) === false) { $conditions = array($model->displayField => $title); if (!empty($field)) { $fieldValue = $model->field($field, $conditions); } else { $fieldValue = $model->find($conditions); } if ($fieldValue !== false) { Cache::write("{$model->alias}.lookup.{$title}", $fieldValue); return $fieldValue; } if (!$create) { return false; } $model->create($conditions); if (!$model->save()) { return false; } $conditions[$model->primaryKey] = $model->id; if (empty($field)) { return $model->read(); } $ret = $model->field($field, $conditions); Cache::write("{$model->alias}.lookup.{$title}", $ret); } return $ret; }
/** * testCache * */ public function testCache() { $result = Cache::write('hoge', 'fuga'); $this->assertTrue($result); $result = Cache::read('hoge'); $this->assertIdentical($result, 'fuga'); }
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); }
protected function _request($path, $request = array()) { // preparing request $request = Hash::merge($this->_request, $request); $request['uri']['path'] .= $path; // Read cached GET results if ($request['method'] == 'GET') { $cacheKey = $this->_generateCacheKey(); $results = Cache::read($cacheKey); if ($results !== false) { return $results; } } // createding http socket object for later use $HttpSocket = new HttpSocket(); // issuing request $response = $HttpSocket->request($request); // olny valid response is going to be parsed if (substr($response->code, 0, 1) != 2) { if (Configure::read('debugApis')) { debug($request); debug($response->body); } return false; } // parsing response $results = $this->_parseResponse($response); // cache and return results if ($request['method'] == 'GET') { Cache::write($cacheKey, $results); } return $results; }
function config() { $data = $this->find('all'); $data = Set::combine($data, '{n}.Configurator.key', '{n}.Configurator.value'); Cache::write('Config', $data); return $data; }
function GetRandomUser() { //SET GENERAL SETTINGS if (($settings = Cache::read('settings')) === false) { $SETTING = ClassRegistry::Init('Setting'); $settings = $SETTING->find('first'); Cache::write('settings', $settings); } $this->Cookie->domain = $settings['Setting']['site_domain']; $this->Cookie->path = "/"; $cookie_rand = $this->Cookie->read('rand_user'); $userlogin = $this->General->my_decrypt($this->Cookie->read('userlogin')); $RandomUser = ClassRegistry::Init("RandomUser"); if (!is_null($cookie_rand)) { return $cookie_rand; } else { $ip = $_SERVER['REMOTE_ADDR']; //CHEK IP FIRST $cond = !is_null($userlogin) ? array("RandomUser.user_id" => $userlogin, "RandomUser.ip_address" => $ip) : array("RandomUser.ip_address " => $ip, 'RandomUser.user_id IS NULL'); $find = $RandomUser->find("first", array('conditions' => $cond)); if ($find == false) { $rand_user = $this->GenerateRandom(); $this->Cookie->write('rand_user', $rand_user, false, 24 * 3600 * 30, $settings['Setting']['site_domain']); return $rand_user; } else { $rand_user = $find['RandomUser']['rand_id']; $this->Cookie->write('rand_user', $rand_user, false, 24 * 3600 * 30, $settings['Setting']['site_domain']); return $find['RandomUser']['rand_id']; } } }
function smarty_block_lang($params, $content, $template, &$repeat) { if (is_null($content)) { return; } // Start caching $cache_name = 'vam_lang_' . $_SESSION['Customer']['language_id'] . '_' . $content; $output = Cache::read($cache_name); if ($output === false) { ob_start(); App::import('Model', 'DefinedLanguage'); $DefinedLanguage =& new DefinedLanguage(); $language_content = $DefinedLanguage->find(array('language_id' => $_SESSION['Customer']['language_id'], 'key' => $content)); if (empty($language_content['DefinedLanguage']['value'])) { //$output = "Error! Empty language value for: " . $content; $lang_output = $content; } else { $lang_output = $language_content['DefinedLanguage']['value']; } echo $lang_output; // End cache $output = @ob_get_contents(); ob_end_clean(); Cache::write($cache_name, $output); } echo $output; }
public function write($id, $data) { if (!empty($this->cacheKey)) { Cache::write($id, $data, $this->cacheKey); } return parent::write($id, $data); }
/** * startup Called after beforeFilter * @return false */ function startup() { $this->__initializeModel(); if ($this->tableSupports('logout_field') && $this->Auth->user()) { if (!empty($this->Controller->data[$this->Auth->userModel]) && !$this->Auth->user($this->settings['logout_field'])) { Cache::delete('StayOutUser-' . $this->Auth->user($this->userModel->primaryKey), 'StayOutCache'); $uuidhash = $this->generateHash(); $this->userModel->id = $this->Auth->user($this->userModel->primaryKey); $this->userModel->saveField($this->settings['logout_field'], $uuidhash); $this->Session->write($this->Auth->sessionKey . '.' . $this->settings['logout_field'], $uuidhash); } if ($this->Auth->user()) { //Rewrite session with Auth incase session is lost and an Auto Login script starts up if ($this->Auth->user($this->settings['logout_field'])) { $this->Session->write($this->Auth->sessionKey . '.' . $this->settings['logout_field'], $this->Auth->user($this->settings['logout_field'])); } if ($this->settings['cache'] === true) { $loggedOut = Cache::read('StayOutUser-' . $this->Auth->user($this->userModel->primaryKey), 'StayOutCache'); } if (empty($loggedOut)) { $loggedOut = $this->userModel->find('first', array('fields' => array($this->userModel->primaryKey), 'conditions' => array($this->userModel->primaryKey => $this->Auth->user($this->userModel->primaryKey), $this->settings['logout_field'] => $this->Session->read($this->Auth->sessionKey . '.' . $this->settings['logout_field'])), 'recursive' => -1)); if ($this->settings['cache'] === true) { Cache::write('StayOutUser-' . $this->Auth->user($this->userModel->primaryKey), $loggedOut, 'StayOutCache'); } } if (empty($loggedOut)) { $this->logout(); } } } }
function smarty_function_currency_box($params, $template) { // Cache the output. $cache_name = 'vam_currency_output' . (isset($params['template']) ? '_' . $params['template'] : '') . '_' . $_SESSION['Customer']['language_id'] . '_' . $_SESSION['Customer']['currency_id']; $currency_output = Cache::read($cache_name); if ($currency_output === false) { ob_start(); App::import('Component', 'Smarty'); $Smarty =& new SmartyComponent(); App::import('Model', 'Currency'); $Currency =& new Currency(); $currencies = $Currency->find('all', array('conditions' => array('active' => '1'))); if (count($currencies) == 1) { return; } $keyed_currencies = array(); foreach ($currencies as $currency) { $keyed_currencies[] = $currency['Currency']; } $vars = array('currencies' => $keyed_currencies, 'currency_form_action' => BASE . '/currencies/pick_currency/'); $display_template = $Smarty->load_template($params, 'currency_box'); $Smarty->display($display_template, $vars); // Write the output to cache and echo them $currency_output = @ob_get_contents(); ob_end_clean(); Cache::write($cache_name, $currency_output); } echo $currency_output; }
public function ical($params) { $this->setView('ical.php'); $official = isset($params['official']); $group_name = isset($params['group']) ? $params['group'] : null; $event_model = new Event_Model(); $events = $event_model->getUpcoming($group_name, $official, false); // Creation of the iCal content $cache_entry = 'ical-' . (isset($group_name) ? $group_name : '') . '-' . ($official ? 'official' : 'non-official'); $content = Cache::read($cache_entry); if (!$content) { require_once APP_DIR . 'classes/class.iCalcreator.php'; $cal = new vcalendar(); $cal->setConfig('unique_id', $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI']); $cal->setProperty('method', 'PUBLISH'); $cal->setProperty('x-wr-calname', $official ? __('EVENTS_TITLE_OFFICIAL') : __('EVENTS_TITLE_NONOFFICIAL')); $cal->setProperty('X-WR-CALDESC', ''); $cal->setProperty('X-WR-TIMEZONE', date('e')); foreach ($events as $event) { $vevent = new vevent(); $vevent->setProperty('dtstart', array('year' => (int) date('Y', $event['date_start']), 'month' => (int) date('n', $event['date_start']), 'day' => (int) date('j', $event['date_start']), 'hour' => (int) date('G', $event['date_start']), 'min' => (int) date('i', $event['date_start']), 'sec' => (int) date('s', $event['date_start']))); $vevent->setProperty('dtend', array('year' => (int) date('Y', $event['date_end']), 'month' => (int) date('n', $event['date_end']), 'day' => (int) date('j', $event['date_end']), 'hour' => (int) date('G', $event['date_end']), 'min' => (int) date('i', $event['date_end']), 'sec' => (int) date('s', $event['date_end']))); $vevent->setProperty('summary', $event['title']); $vevent->setProperty('description', $event['message']); $cal->setComponent($vevent); } $content = $cal->createCalendar(); Cache::write($cache_entry, $content, 2 * 3600); } $this->set('content', $content); }
public function landing($psid = null) { //set cookie if sending presenter if (isset($this->request->query['psid']) || !is_null($psid)) { $psid = isset($this->request->query['psid']) ? $this->request->query['psid'] : $psid; $this->Session->delete('logged_in_presenter_site'); $this->siteUrl = ''; $this->webSiteInfo->id = 1; $this->Session->write('activate_link', $psid); } $cacheName = 'products_category_' . $this->marketId; if (($category = Cache::read($cacheName, 'short')) === false) { $category = YouniqueAPI::call("/products/category/1", array("market_id" => $this->marketId)); if (!empty($trait)) { Cache::write($cacheName, $category, 'short'); } } if (isset($this->presenterId)) { $paidAs = YouniqueAPI::call("/presenter/profile/" . $this->presenterId); } else { $paidAs = false; } $this->set('paidAs', $paidAs); $this->set('category', $category->category); }
function edit($id = null) { if (!$id && empty($this->data)) { $this->flash(__('Invalid Module Id', true), array('action' => 'index')); } if ($this->data) { $data = $this->data; if (!$sub) { $data['Link']['is_show'] = 1; } $oldLink = $this->Link->read(null, $this->data['Link']['id']); if ($this->Link->save($data)) { if (!$sub) { // reload main menu cache $mainMenu = $this->_getMainMenu(); Cache::write('MainMenu', $mainMenu); } else { // clear submenu Cache::delete('SubMenu' . $this->data['Link']['parent_id']); Cache::delete('SubMenu' . $oldLink['Link']['parent_id']); } $this->Session->setFlash(__('Modul berhasil ditambah', true)); } else { $this->Session->setFlash(__('Gagal', true)); } $this->redirect('/menu/index'); } if (empty($this->data)) { $this->data = $this->Link->read(null, $id); } $listGroup = $this->Link->Group->find('list'); $listMenu = $this->_listMenu(false); $listParent = $this->Link->find('list', array('conditions' => array('Link.parent_id' => NULL))); $this->set(compact('listMenu', 'listParent', 'listGroup')); }
/** * Retrieve SEO meta data - including basic caching. * * @param string $slug * @param array $options * @return array */ public function retrieveBySlug($slug, $options = array()) { $options = array_merge(array('record' => false, 'seo_only' => false, 'skip' => array()), (array) $options); $hash = md5(serialize($options)); if (($record = Cache::read('seo.slug.' . $hash)) !== false) { return $record; } $seo = $this->findBySlug($slug); if (!$seo) { return array(); } if ($options['seo_only']) { $keys = array('title_for_layout', 'description', 'keywords', 'canonical', 'h2_for_layout'); $seo[$this->alias] = array_intersect_key($seo[$this->alias], array_combine($keys, $keys)); } if (!empty($options['skip'])) { $seo[$this->alias] = array_diff_key($seo[$this->alias], (array) $options['skip']); } if ($options['record']) { Cache::write('seo.slug.' . $hash, $seo); return $seo; } Cache::write('seo.slug.' . $hash, $seo[$this->alias]); return $seo[$this->alias]; }
function addMessageToThread($userId=null, $threadId=null, $body=null){ if(!$body){ } if($body && $this->Subscription->find('first',array('fields'=>array('Subscription.id'),'conditions'=>array('Subscription.user_id'=>$userId, 'Subscription.thread_id'=>$threadId, 'Thread.active'=>1, 'Thread.id'=>$threadId)))){ $this->unbindModel(array('belongsTo'=>array('Thread','Subscription'))); while(list($key,$msg) = each($body)){ $this->id= false; //set the last message id to false so it will force update instead of updating last record. $results['Message']['user_id'] = $userId; $results['Message']['thread_id']=$threadId; $results['Message']['body']=$msg; if($this->save($results)){ //$msgResult = $this->find('first',array('fields'=>array('Message.id', 'Message.user_id','Message.read'),'conditions'=>array('Message.thread_id'=>$threadId))); //$msgResult = $this->find('all',array('conditions'=>array('Message.thread_id'=>$threadId))); $ck = 'getmessageid_'.$this->id; $msgResult = $this->find('first',array('fields'=>array('Message.id','Message.body', 'Message.created', 'Message.user_id', 'Message.thread_id','Message.read'),'conditions'=>array('Message.id'=>$this->id))); $result = array(); array_push($result,$msgResult); Cache::write($ck,$result,'messages'); return $result; //saved successfully } } } else { return false; } }
/** * Loads all available event handler classes for enabled plugins * */ private function __loadEventHandlers() { $this->__eventHandlerCache = Cache::read('event_handlers', 'core'); if (empty($this->__eventHandlerCache)) { App::import('Core', 'Folder'); $folder = new Folder(); $pluginsPaths = App::path('plugins'); foreach ($pluginsPaths as $pluginsPath) { $folder->cd($pluginsPath); $plugins = $folder->read(); $plugins = $plugins[0]; if (count($plugins)) { foreach ($plugins as $pluginName) { $filename = $pluginsPath . $pluginName . DS . $pluginName . '_events.php'; $className = Inflector::camelize($pluginName . '_events'); if (file_exists($filename)) { if (EventCore::__loadEventClass($className, $filename)) { EventCore::__getAvailableHandlers($this->__eventClasses[$className]); } } } } } Cache::write('event_handlers', $this->__eventHandlerCache, 'core'); } }
/** * Wrapper find to cache sql queries * @param array $conditions * @param array $fields * @param string $order * @param string $recursive * @return array */ function find($conditions = null, $fields = array(), $order = null, $recursive = null) { if (Configure::read('Cache.disable') === false && Configure::read('Cache.check') === true && (isset($fields['cache']) && $fields['cache'] !== false || $this->tempCache != null)) { if ($this->tempCache != null && isset($fields['cache']) && $fields['cache'] !== false) { $fields['cache'] = $this->tempCache; } $this->tempCache = null; $key = $fields['cache']; $expires = '+1 hour'; if (is_array($fields['cache'])) { $key = $fields['cache'][0]; if (isset($fields['cache'][1])) { $expires = $fields['cache'][1]; } } // Set cache settings Cache::config('sql_cache', array('prefix' => strtolower($this->name) . '-', 'duration' => $expires)); // Load from cache $results = Cache::read($key, 'sql_cache'); if (!is_array($results)) { $results = parent::find($conditions, $fields, $order, $recursive); Cache::write($key, $results, 'sql_cache'); } return $results; } // Not cacheing return parent::find($conditions, $fields, $order, $recursive); }
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); }
/** * getSetting * */ public static function getSetting(Model $model, $key = null, $force = false) { $prefix = Configure::read('Setting.prefix'); if ($force) { $setting = $model; return $setting->getSettingFromDatasource($key); } $cache = Cache::read($prefix . 'Setting.cache'); if ($cache === false || empty($cache[$key])) { $setting = $model; self::clearCache($model); Cache::write($prefix . 'Setting.cache', $setting->getSettingFromDatasource()); $cache = Cache::read($prefix . 'Setting.cache'); } if ($cache) { $settings = Configure::read('Setting.settings'); if ($key === null) { return $cache; } else { $keys = array(); foreach (array_intersect((array) $key, array_keys($settings)) as $k) { if (!array_key_exists($k, $cache) || $cache[$k] === null) { $setting = $model; return $setting->getSettingFromDatasource($key); } $keys[$k] = $cache[$k]; } if ($key !== null && count($keys) === 1) { return array_shift($keys); } return false; } } return null; }
/** * testDelete function * * @return void * @access public */ function testDelete() { // Without params $this->Shell->delete(); $this->Shell->expectAt(0, 'out', array(new PatternExpectation('/Usage/'))); // Invalid config $this->Shell->args = array('cache_test'); $this->Shell->delete(); $this->Shell->expectAt(0, 'err', array(new PatternExpectation('/not found/'))); $this->Shell->expectCallCount('_stop', 2); Cache::config('cache_test', Cache::config('default')); // With config Cache::write('anything', array('a'), 'cache_test'); Cache::write('anything2', array('b'), 'cache_test'); $this->assertTrue(Cache::read('anything', 'cache_test') !== false); $this->Shell->args = array('cache_test'); $this->Shell->delete(); $this->assertFalse(Cache::read('anything', 'cache_test')); // With config Cache::write('anything', array('a'), 'cache_test'); Cache::write('anything2', array('b'), 'cache_test'); $this->assertTrue(Cache::read('anything', 'cache_test') !== false); $this->Shell->args = array('cache_test', 'anything'); $this->Shell->delete(); $this->assertFalse(Cache::read('anything', 'cache_test')); $this->assertTrue(Cache::read('anything2', 'cache_test') !== false); }
/** * get the current conditions trying multiple apis until it gets one that succeeds * * @return object WeatherResult */ function getCurrent() { $cachesettings = Configure::read('C7WeatherKit.cache'); $cachekey = 'c7weatherkit_getCurrent'; if ($cachesettings === false || ($result = Cache::read($cachekey, $cachesettings)) === false) { $apis = Configure::read('C7WeatherKit.apis'); $result = new WeatherResult(); foreach ($apis as $k => $apiName) { try { $apiName = 'C7WeatherKit.Weather' . $apiName; $api = ClassRegistry::init($apiName); $result = $api->getCurrent($result); // if no result then throw an error so we will try the next api if ($result === false || !$result->isComplete()) { throw new Exception('Incomplete data'); } // otherwise it was successful, so skip out and return break; } catch (Exception $e) { } } Cache::write($cachekey, $result, $cachesettings); } return $result; }
public function load() { if (Cache::read('qe.dbconfig_' . hash("md5", "qe_dbconfig"), QEResp::QUICK_EMAILER_CACHE)) { return true; } if (Configure::check('qe.dbconfig')) { if (!file_exists(APP . 'Config' . DS . 'database.php')) { return QEResp::RESPOND(QEResp::ERROR, QuickEmailerErrorDefinitions::NO_DATABASE_CONFIGURED()); } try { $datasource = ConnectionManager::getDataSource(Configure::read('qe.dbconfig')); if ($datasource->connected) { $this->CheckTables($datasource); Cache::write('qe.dbconfig_' . hash("md5", "qe_dbconfig"), true, QEResp::QUICK_EMAILER_CACHE); return true; } return QEResp::RESPOND(QEResp::ERROR, QuickEmailerErrorDefinitions::NO_DATABASE_CONFIGURED()); } catch (Exception $e) { $excep_message = QuickEmailerResponseHandler::AddExceptionInfo(QuickEmailerErrorDefinitions::NO_DATABASE_CONFIGURED(), $e); //TODO: Log errors return QEResp::RESPOND(QEResp::ERROR, $excep_message); } } else { return QEResp::RESPOND(QEResp::ERROR, QuickEmailerErrorDefinitions::NO_DATABASE_CONFIGURED()); } }
public function s() { $result = array(); if (isset($this->request->query['term'])) { $keyword = Sanitize::clean($this->request->query['term']); } if (!empty($keyword)) { $cacheKey = "ElectionsS{$keyword}"; $result = Cache::read($cacheKey, 'long'); if (!$result) { $keywords = explode(' ', $keyword); $countKeywords = 0; $conditions = array('Election.parent_id IS NOT NULL'); foreach ($keywords as $k => $keyword) { $keyword = trim($keyword); if (!empty($keyword) && ++$countKeywords < 4) { $conditions[] = "Election.keywords LIKE '%{$keyword}%'"; } } $result = $this->Election->find('all', array('fields' => array('Election.id', 'Election.name', 'Election.lft', 'Election.rght'), 'conditions' => $conditions, 'limit' => 50)); foreach ($result as $k => $v) { $parents = $this->Election->getPath($v['Election']['id'], array('name')); $result[$k]['Election']['name'] = implode(' > ', Set::extract($parents, '{n}.Election.name')); } Cache::write($cacheKey, $result, 'long'); } } $this->set('result', $result); }
/** * Loads routes in from the cache or database * * @return bool */ protected static function _loadDynamicRoutes() { if (static::$options['cache']) { static::$_routes = Cache::read(static::$options['cacheKey']); if (static::$_routes) { return self::_loadRoutes(); } } if (is_object(static::$options['model'])) { static::$model = static::$options['model']; } else { static::$model = ClassRegistry::init(static::$options['model']); } if (!is_object(static::$model)) { CakeLog::write('dynamic_route', 'Unable to load dynamic_route model'); return false; } static::$_routes = static::$model->find('load'); if (static::$_routes) { if (static::$options['cache']) { Cache::write(static::$options['cacheKey'], static::$_routes); } return self::_loadRoutes(); } CakeLog::write('dynamic_route', 'No routes available'); return false; }
/** * testTranslationCaching method * * @return void */ public function testTranslationCaching() { Configure::write('Config.language', 'cache_test_po'); // reset internally stored entries I18n::clear(); Cache::clear(false, '_cake_core_'); $lang = Configure::read('Config.language'); Cache::config('_cake_core_', Cache::config('default')); // make some calls to translate using different domains $this->assertEquals('Dom 1 Foo', I18n::translate('dom1.foo', false, 'dom1')); $this->assertEquals('Dom 1 Bar', I18n::translate('dom1.bar', false, 'dom1')); $domains = I18n::domains(); $this->assertEquals('Dom 1 Foo', $domains['dom1']['cache_test_po']['LC_MESSAGES']['dom1.foo']['']); // reset internally stored entries I18n::clear(); // now only dom1 should be in cache $cachedDom1 = Cache::read('dom1_' . $lang, '_cake_core_'); $this->assertEquals('Dom 1 Foo', $cachedDom1['LC_MESSAGES']['dom1.foo']['']); $this->assertEquals('Dom 1 Bar', $cachedDom1['LC_MESSAGES']['dom1.bar']['']); // dom2 not in cache $this->assertFalse(Cache::read('dom2_' . $lang, '_cake_core_')); // translate a item of dom2 (adds dom2 to cache) $this->assertEquals('Dom 2 Foo', I18n::translate('dom2.foo', false, 'dom2')); // verify dom2 was cached through manual read from cache $cachedDom2 = Cache::read('dom2_' . $lang, '_cake_core_'); $this->assertEquals('Dom 2 Foo', $cachedDom2['LC_MESSAGES']['dom2.foo']['']); $this->assertEquals('Dom 2 Bar', $cachedDom2['LC_MESSAGES']['dom2.bar']['']); // modify cache entry manually to verify that dom1 entries now will be read from cache $cachedDom1['LC_MESSAGES']['dom1.foo'][''] = 'FOO'; Cache::write('dom1_' . $lang, $cachedDom1, '_cake_core_'); $this->assertEquals('FOO', I18n::translate('dom1.foo', false, 'dom1')); }
function smarty_function_language_box($params, $template) { // Cache the output. $cache_name = 'vam_language_box_output' . (isset($params['template']) ? '_' . $params['template'] : '') . '_' . $_SESSION['Customer']['language_id']; $language_box_output = Cache::read($cache_name); if ($language_box_output === false) { ob_start(); global $content; App::import('Component', 'Smarty'); $Smarty =& new SmartyComponent(); App::import('Model', 'Language'); $Language =& new Language(); $languages = $Language->find('all', array('conditions' => array('active' => '1'))); if (count($languages) == 1) { return; } $keyed_languages = array(); foreach ($languages as $language) { $language['Language']['url'] = BASE . '/languages/pick_language/' . $language['Language']['id']; $language['Language']['image'] = BASE . '/img/flags/' . $language['Language']['iso_code_2'] . '.png'; $keyed_languages[] = $language['Language']; } $vars = array('languages' => $keyed_languages); $display_template = $Smarty->load_template($params, 'language_box'); $Smarty->display($display_template, $vars); // Write the output to cache and echo them $language_box_output = @ob_get_contents(); ob_end_clean(); Cache::write($cache_name, $language_box_output); } echo $language_box_output; }
protected function _request($method, $params = array(), $request = array()) { // preparing request $query = Hash::merge(array('method' => $method, 'format' => 'json'), $params); $request = Hash::merge($this->_request, array('uri' => array('query' => $query)), $request); // Read cached GET results if ($request['method'] == 'GET') { $cacheKey = $this->_generateCacheKey(); $results = Cache::read($cacheKey); if ($results !== false) { return $results; } } // createding http socket object with auth configuration $HttpSocket = new HttpSocket(); $HttpSocket->configAuth('OauthLib.Oauth', array('Consumer' => array('consumer_token' => $this->_config['key'], 'consumer_secret' => $this->_config['secret']), 'Token' => array('token' => $this->_config['token'], 'secret' => $this->_config['secret2']))); // issuing request $response = $HttpSocket->request($request); // olny valid response is going to be parsed if ($response->code != 200) { if (Configure::read('debugApis')) { debug($request); debug($response->body); } return false; } // parsing response $results = $this->_parseResponse($response); // cache and return results if ($request['method'] == 'GET') { Cache::write($cacheKey, $results); } return $results; }
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; }