コード例 #1
0
 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'];
         }
     }
 }
コード例 #2
0
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;
}
コード例 #3
0
 /**
  * beforeRender callback function
  *
  * @return array contents for panel
  **/
 public function beforeRender(Controller $controller)
 {
     $cacheKey = $controller->Toolbar->cacheKey;
     $toolbarHistory = Cache::read($cacheKey, 'debug_kit');
     $historyStates = array();
     if (is_array($toolbarHistory) && !empty($toolbarHistory)) {
         $prefix = array();
         if (!empty($controller->request->params['prefix'])) {
             $prefix[$controller->request->params['prefix']] = false;
         }
         foreach ($toolbarHistory as $i => $state) {
             if (!isset($state['request']['content']['url'])) {
                 continue;
             }
             $title = $state['request']['content']['url'];
             $query = @$state['request']['content']['query'];
             if (isset($query['url'])) {
                 unset($query['url']);
             }
             if (!empty($query)) {
                 $title .= '?' . urldecode(http_build_query($query));
             }
             $historyStates[] = array('title' => $title, 'url' => array_merge($prefix, array('plugin' => 'debug_kit', 'controller' => 'toolbar_access', 'action' => 'history_state', $i + 1)));
         }
     }
     if (count($historyStates) >= $this->history) {
         array_pop($historyStates);
     }
     return $historyStates;
 }
コード例 #4
0
 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);
 }
コード例 #5
0
 /**
  * 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'));
 }
コード例 #6
0
ファイル: SystemControlTest.php プロジェクト: k1low/setting
 /**
  * testCache
  *
  */
 public function testCache()
 {
     $result = Cache::write('hoge', 'fuga');
     $this->assertTrue($result);
     $result = Cache::read('hoge');
     $this->assertIdentical($result, 'fuga');
 }
 /**
  * admin_index
  * 
  * @return void
  */
 public function admin_index()
 {
     $settingLang = Cache::read('settings', "admin");
     $this->User->locale = $settingLang[0]['Setting']['value'];
     $this->paginate['User']['order'] = 'User.id Desc';
     $this->set('users', $this->paginate('User'));
 }
コード例 #8
0
 /**
  * Get the cache key config if we have cache setup
  * @param string key
  * @return mixed boolean false or 
  */
 public static function readCache($key)
 {
     if (self::getConfig('cache')) {
         return Cache::read($key, 'queue');
     }
     return false;
 }
コード例 #9
0
ファイル: index.php プロジェクト: VictorSproot/AtomXCMS-2
 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);
 }
コード例 #10
0
ファイル: Meta.php プロジェクト: simaostephanie/cakephp-seo
 /**
  * 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];
 }
コード例 #11
0
ファイル: events.php プロジェクト: rchavik/infinitas
 /**
  * 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');
     }
 }
コード例 #12
0
 /**
  * Builds an URL array based on a preset.
  *
  * @param array $data Data for the URL params.
  * @param string $identifier
  * @param array $options
  * @throws RuntimeException
  * @throws InvalidArgumentException
  * @return array
  */
 public static function url($data, $identifier, $options = array())
 {
     if (self::$_cacheConfig !== false) {
         $cacheKey = md5(serialize($data) . serialize($options)) . $identifier;
         $url = Cache::read($cacheKey, self::$_cacheConfig);
         if (!empty($url)) {
             return $url;
         }
     }
     if (is_string($identifier)) {
         $preset = self::getTemplate($identifier);
     } elseif (is_array($identifier)) {
         $preset = $identifier;
     } else {
         throw new \InvalidArgumentException(__d('bz_utils', 'Must be string or array!'));
     }
     $url = self::_buildUrlArray($data, $preset);
     if (isset($options['string']) && $options['string'] === true) {
         $fullBase = isset($options['fullBase']) && $options['fullBase'] === true;
         $url = Router::url($url, $fullBase);
         if (self::$_cacheConfig !== false) {
             Cache::write($cacheKey, $url, self::$_cacheConfig);
         }
         return $url;
     }
     if (self::$_cacheConfig !== false) {
         Cache::write($cacheKey, $url, self::$_cacheConfig);
     }
     return $url;
 }
コード例 #13
0
ファイル: block.lang.php プロジェクト: risnandar/testing
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;
}
コード例 #14
0
 /**
  * Find all defined callbacks in the app or other plugins
  *
  * @param undefined $cached
  * @return void
  * @access public
  */
 public function load()
 {
     $cached = Cache::read('_plugin_callbacks_', '_cake_models_');
     if ($cached !== false) {
         $this->settings = $cached;
         return $cached;
     }
     App::import('Folder');
     $Folder = new Folder($this->path . 'plugins');
     $folders = current($Folder->ls());
     $files = array();
     foreach ($folders as $folder) {
         if ($Folder->cd($this->path . 'models' . DS . 'callbacks')) {
             $files = $Folder->findRecursive('([a-z_]+)_' . $folder . '.php');
         }
         $files = array_flip($files);
         foreach ($folders as $_folder) {
             if ($Folder->cd($this->path . 'plugins' . DS . $_folder . DS . 'models' . DS . 'callbacks')) {
                 $files = array_merge($files, array_flip($Folder->findRecursive('([a-z_]+)_' . $folder . '.php')));
             }
         }
         foreach (array_keys($files) as $k => $file) {
             if (!preg_match_all('/models\\/callbacks\\/([a-z_]+)_' . $folder . '\\.php/i', $file, $matches)) {
                 continue;
             }
             $plugin = current($matches[1]);
             if (empty($plugin)) {
                 $plugin = 'app';
             }
             $callbackName = Inflector::camelize(sprintf('%s_%s', $plugin, $folder));
             $this->settings[$folder][$plugin] = $callbackName;
         }
     }
     Cache::write('_plugin_callbacks_', $this->settings, '_cake_models_');
 }
コード例 #15
0
ファイル: SettableBehavior.php プロジェクト: k1low/setting
 /**
  * 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;
 }
コード例 #16
0
ファイル: cache_shell.test.php プロジェクト: sams/cache
 /**
  * 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);
 }
コード例 #17
0
 function svn_test($prop = null, $prop2 = 0)
 {
     Configure::write('debug', 1);
     exit('===OK===');
     if ($prop == 'global_check') {
         echo '<br/><b>=========================Test Memcache (example - slider):</b><br/>';
         print_r(Cache::read('slides', 'full_time'));
         echo '<br/><b>=========================Test Session (example - user):</b><br/>';
         print_r($_SESSION['loggedUser']);
         echo '<br/><b>=========================Test Master/Slave (example - store_offers):</b><br/>';
         $StoreOffer = ClassRegistry::init("StoreOffer");
         /*
         if (!$prop2) {
         $StoreOffer->create();
         $StoreOffer->save(array('name' => 'Test is OK'));
         $prop2 = $StoreOffer->getLastInsertID();
         echo "<br/><b>Last ID</b>: " . $prop2;
         }
         */
         //sleep(5);
         //$StoreOffer->setDataSource('slave1');
         //unset($_SESSION['database']['master_switched']);
         echo "<br/><b>Saved Record Slave</b>:<br/>";
         Configure::write('Database.use_master', 0);
         print_r($StoreOffer->read(null, 242));
         echo "<br/><b>Saved Record Master</b>:<br/>";
         Configure::write('Database.use_master', 1);
         print_r($StoreOffer->read(null, 242));
         //$StoreOffer->delete($id);
     }
     exit;
 }
コード例 #18
0
 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());
     }
 }
コード例 #19
0
 /**
  * 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;
 }
コード例 #20
0
 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;
 }
コード例 #21
0
 /**
  * should be called in beforeRender()
  * 
  */
 public static function init(View $View)
 {
     $params = $View->request->params;
     if (Configure::read('UrlCache.pageFiles')) {
         $cachePageKey = '_misc';
         if (is_object($View)) {
             $path = $View->request->here;
             if ($path == '/') {
                 $path = 'uc_homepage';
             } else {
                 $path = strtolower(Inflector::slug($path));
             }
             if (empty($path)) {
                 $path = 'uc_error';
             }
             $cachePageKey = '_' . $path;
         }
         self::$cachePageKey = self::$cacheKey . $cachePageKey;
         self::$cachePage = Cache::read(self::$cachePageKey, '_cake_core_');
     }
     self::$cache = Cache::read(self::$cacheKey, '_cake_core_');
     # still old "prefix true/false" syntax?
     if (Configure::read('UrlCache.verbosePrefixes')) {
         unset(self::$paramFields[3]);
         self::$paramFields = array_merge(self::$paramFields, (array) Configure::read('Routing.prefixes'));
     }
     self::$extras = array_intersect_key($params, array_combine(self::$paramFields, self::$paramFields));
     $defaults = array();
     foreach (self::$paramFields as $field) {
         $defaults[$field] = '';
     }
     self::$extras = array_merge($defaults, self::$extras);
 }
コード例 #22
0
 /**
  * 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;
 }
コード例 #23
0
 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);
 }
コード例 #24
0
ファイル: BcCacheBehavior.php プロジェクト: kenz/basercms
 /**
  * キャッシュ処理
  * 
  * @param Model $model
  * @param int $expire
  * @param string $method
  * @args mixed
  * @return mixed
  * @access public
  */
 public function readCache(Model $model, $expire, $type, $query = array())
 {
     static $cacheData = array();
     // キャッシュキー
     $tableName = $model->tablePrefix . $model->table;
     $cachekey = $tableName . '_' . $type . '_' . $expire . '_' . md5(serialize($query));
     // 変数キャッシュの場合
     if (!$expire) {
         if (isset($cacheData[$cachekey])) {
             return $cacheData[$cachekey];
         }
         if (!($db = ConnectionManager::getDataSource($model->useDbConfig))) {
             return false;
         }
         $results = $db->read($model, $query);
         $cacheData[$cachekey] = $results;
         return $results;
     }
     $this->changeCachePath($model->tablePrefix . $model->table);
     // サーバーキャッシュの場合
     $results = Cache::read($cachekey, '_cake_data_');
     if ($results !== false) {
         if ($results == "{false}") {
             $results = false;
         }
         return $results;
     }
     if (!($db = ConnectionManager::getDataSource($model->useDbConfig))) {
         return false;
     }
     $results = $db->read($model, $query);
     Cache::write($cachekey, $results === false ? "{false}" : $results, '_cake_data_');
     return $results;
 }
コード例 #25
0
ファイル: MarkdownHelper.php プロジェクト: k1low/yamd
 /**
  * loadFile
  *
  */
 public function loadFile($markdownFile, $viewVars = array())
 {
     $exts = $this->_getExtensions();
     $language = Configure::read('Config.language');
     $catalog = $this->l10n->catalog($language);
     if (!empty($catalog['locale'])) {
         $lang = $catalog['locale'];
     } elseif (!empty($catalog['localeFallback'])) {
         $lang = $catalog['localeFallback'];
     } else {
         $lang = 'eng';
     }
     $cacheKey = $markdownFile . '.' . $lang;
     if (Configure::read('debug') == 0 && Cache::read($cacheKey, $this->settings['cacheConfig'])) {
         return Cache::read($cacheKey, $this->settings['cacheConfig']);
     }
     foreach ($exts as $ext) {
         $filePath = $this->settings['markdownFilePath'] . $lang . DS . $markdownFile . $ext;
         if (file_exists($filePath)) {
             return $this->__loadFile($filePath, $cacheKey, $viewVars);
         }
         $filePath = $this->settings['markdownFilePath'] . $markdownFile . $ext;
         if (file_exists($filePath)) {
             return $this->__loadFile($filePath, $cacheKey, $viewVars);
         }
     }
 }
コード例 #26
0
 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;
 }
コード例 #27
0
ファイル: NewController.php プロジェクト: kodiary/hamroawaz
 function index()
 {
     if (!($cachedate = Cache::read('cached_date'))) {
         Cache::delete('cached_date');
     }
     $current = strtotime(date('Y-m-d G:i:s'));
     $checktime = strtotime(date('Y-m-d G:i:s', mktime(10, 0, 0, date("m"), date("d"), date("Y"))));
     $dateObject = new DateTime(date('Y-m-d G:i:s'));
     $today = $dateObject->format('Y-m-d');
     $yesterday = date("Y-m-d", mktime(0, 0, 0, date("m"), date("d") - 1, date("Y")));
     $this->set('title', 'HamroAwaz');
     $this->loadModel('Categorymanager');
     $this->loadModel('Newsmanager');
     $qcat = $this->Categorymanager->find('all');
     $this->set('cat', $qcat);
     if ($checktime >= $current) {
         $arr['conditions'] = array('created_date' => $yesterday);
         $slider = $this->Newsmanager->find('all', $arr);
         $this->set('slider', $slider);
         $q = $this->Newsmanager->find('all', array('conditions' => array('created_date' => $yesterday, 'is_headline' => 1), 'order' => array('id' => 'DESC'), 'limit' => 5));
         // debug($q);die();
         $this->set('val', $q);
     }
     if ($checktime < $current) {
         $arr['conditions'] = array('created_date' => $today);
         $slider = $this->Newsmanager->find('all', $arr);
         $this->set('slider', $slider);
         //die('lalustine');
         $q = $this->Newsmanager->find('all', array('conditions' => array('created_date' => $today, 'is_headline' => 1), 'order' => array('id' => 'DESC'), 'limit' => 5));
         $this->set('val', $q);
     }
 }
コード例 #28
0
ファイル: app_model.php プロジェクト: gersonjnr/portabilis
 /**
  * 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);
 }
コード例 #29
0
ファイル: I18nTest.php プロジェクト: kuradakis/cakephp-ex
 /**
  * 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'));
 }
コード例 #30
0
ファイル: StayOutComponent.php プロジェクト: voidet/stay_out
 /**
  * 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();
             }
         }
     }
 }