Beispiel #1
3
 public function afterDispatch(Event $event, Request $request, Response $response)
 {
     if (Configure::read('debug') || !isset($request->params['cache']) || $request->params['cache'] !== true) {
         return;
     }
     unset($request->params['cache']);
     $cacheKey = $this->_getCacheKey($request);
     if ($cacheKey !== false) {
         $content = $response->body();
         Cache::write($cacheKey, $content, 'wasabi/cms/pages');
     }
 }
Beispiel #2
0
 /**
  * Get all options
  *
  * @param bool $force Force
  * @return array|mixed
  */
 public static function getAll($force = false)
 {
     if ($force === true || self::$_config['cache'] === false || self::$_config['cache'] === true && !Cache::read(self::$_config['cache_name'])) {
         $options = self::$_table->find('all');
         $optionsArray = [];
         foreach ($options as $v) {
             $value = $v->{self::$_config['column_value']};
             $setting = Settings::getSetting($v->{self::$_config['column_key']});
             if (!is_null($setting)) {
                 switch ($setting['type']) {
                     case 'boolean':
                         $value = boolval($value);
                         break;
                     case 'integer':
                         $value = intval($value);
                         break;
                     case 'float':
                         $value = floatval($value);
                         break;
                 }
             }
             $optionsArray[$v->{self::$_config['column_key']}] = $value;
         }
         if (self::$_config['cache'] === true) {
             Cache::write(self::$_config['cache_name'], $optionsArray, self::$_config['cache_config']);
         }
         return $optionsArray;
     }
     return Cache::read(self::$_config['cache_name']);
 }
 /**
  * Prepares some variables used in "default.ctp" layout, such as skin color to use,
  * pending comments counter, etc.
  *
  * @return array Associative array
  */
 function backendLayoutVars()
 {
     $layoutOptions = [];
     $skin = theme()->settings('skin');
     $boxClass = 'success';
     $pendingComments = Cache::read('pending_comments', 'pending_comments');
     if ($pendingComments === false) {
         $pendingComments = TableRegistry::get('Comment.Comments')->find()->where(['Comments.status' => 'pending', 'Comments.table_alias' => 'contents'])->count();
         Cache::write('pending_comments', $pendingComments, 'pending_comments');
     }
     $pendingComments = !$pendingComments ? '' : $pendingComments;
     if (strpos($skin, 'blue') !== false || strpos($skin, 'black') !== false) {
         $boxClass = 'info';
     } elseif (strpos($skin, 'green') !== false) {
         $boxClass = 'success';
     } elseif (strpos($skin, 'red') !== false || strpos($skin, 'purple') !== false) {
         $boxClass = 'danger';
     } elseif (strpos($skin, 'yellow') !== false) {
         $boxClass = 'warning';
     }
     if (theme()->settings('fixed_layout')) {
         $layoutOptions[] = 'fixed';
     }
     if (theme()->settings('boxed_layout')) {
         $layoutOptions[] = 'layout-boxed';
     }
     if (theme()->settings('collapsed_sidebar')) {
         $layoutOptions[] = 'sidebar-collapse';
     }
     return compact('skin', 'layoutOptions', 'boxClass', 'pendingComments');
 }
 /**
  * Establishes a connection to the salesforce server
  *
  * @param array $config configuration to be used for creating connection
  * @return bool true on success
  */
 protected function _connect(array $config)
 {
     $this->config = $config;
     if (empty($this->config['my_wsdl'])) {
         throw new \ErrorException("A WSDL needs to be provided");
     } else {
         $wsdl = CONFIG . DS . $this->config['my_wsdl'];
     }
     $mySforceConnection = new \SforceEnterpriseClient();
     $mySoapClient = $mySforceConnection->createConnection($wsdl);
     $sflogin = (array) Cache::read('salesforce_login', 'salesforce');
     if (!empty($sflogin['sessionId'])) {
         $mySforceConnection->setSessionHeader($sflogin['sessionId']);
         $mySforceConnection->setEndPoint($sflogin['serverUrl']);
     } else {
         try {
             $mylogin = $mySforceConnection->login($this->config['username'], $this->config['password']);
             $sflogin = array('sessionId' => $mylogin->sessionId, 'serverUrl' => $mylogin->serverUrl);
             Cache::write('salesforce_login', $sflogin, 'salesforce');
         } catch (Exception $e) {
             $this->log("Error logging into salesforce - Salesforce down?");
             $this->log("Username: "******"Password: " . $this->config['password']);
         }
     }
     $this->client = $mySforceConnection;
     $this->connected = true;
     return $this->connected;
 }
 public function index()
 {
     if (($books = Cache::read('exlibrisBooksIndex')) === false) {
         $books = $this->Books->find('all')->contain('Publishers')->all();
         Cache::write('exlibrisBooksIndex', $books);
     }
     $this->set('books', $books);
     $this->set('_serialize', ['books']);
 }
Beispiel #6
0
 /**
  * Write the data into the Cache with the passed key.
  *
  * @param int|object|string $data The data to save in the Cache.
  * @param string $key The key to save the data.
  *
  * @return bool
  */
 protected function _writeCache($data, $key)
 {
     if (empty($data) || empty($key)) {
         return true;
     }
     $result = Cache::write($key, $data, 'statistics');
     if ($result) {
         return true;
     }
     return false;
 }
 /**
  * Internal method to get the latest photos
  * @param int $limit Limit
  * @return array
  * @uses MeInstagram\Utility\Instagram::recent()
  */
 protected function _latest($limit = 15)
 {
     //Tries to get data from the cache
     $photos = Cache::read($cache = sprintf('latest_%s', $limit), 'instagram');
     //If the data are not available from the cache
     if (empty($photos)) {
         list($photos) = Instagram::recent(null, $limit);
         Cache::write($cache, $photos, 'instagram');
     }
     return $photos;
 }
 public function view($slug)
 {
     $pagina = Cache::read('pagina_view_' . $slug);
     if ($pagina === false) {
         $pagina = $this->Paginas->getPaginaBySlug($slug);
         Cache::write('pagina_view_' . $slug, $pagina);
     }
     if (!$pagina) {
         throw new NotFoundException();
     }
     $this->set(compact('pagina'));
 }
Beispiel #9
0
 /**
  * Write user failed login.
  *
  * @param Controller $controller
  * @return void
  */
 protected function _writeFailedLogin(Controller $controller)
 {
     $cacheConfig = 'auth';
     if ($controller->request->param('prefix') == 'admin') {
         $cacheConfig .= '_admin';
     }
     $cacheName = 'failed_' . $controller->request->data('username');
     $cacheValue = (int) Cache::read($cacheName, $cacheConfig);
     $cookieVal = $controller->Cookie->read('fail.auth');
     $controller->Cookie->config(['expires' => '+300 seconds']);
     $controller->Cookie->write('fail.auth', (int) $cookieVal + 1);
     Cache::write($cacheName, (int) $cacheValue + 1, $cacheConfig);
 }
 /**
  * Renders the login form.
  *
  * @return \Cake\Network\Response|null
  */
 public function login()
 {
     $this->loadModel('User.Users');
     $this->viewBuilder()->layout('login');
     if ($this->request->is('post')) {
         $loginBlocking = plugin('User')->settings('failed_login_attempts') && plugin('User')->settings('failed_login_attempts_block_seconds');
         $continue = true;
         if ($loginBlocking) {
             Cache::config('users_login', ['duration' => '+' . plugin('User')->settings('failed_login_attempts_block_seconds') . ' seconds', 'path' => CACHE, 'engine' => 'File', 'prefix' => 'qa_', 'groups' => ['acl']]);
             $cacheName = 'login_failed_' . env('REMOTE_ADDR');
             $cache = Cache::read($cacheName, 'users_login');
             if ($cache && $cache['attempts'] >= plugin('User')->settings('failed_login_attempts')) {
                 $blockTime = (int) plugin('User')->settings('failed_login_attempts_block_seconds');
                 $this->Flash->warning(__d('user', 'You have reached the maximum number of login attempts. Try again in {0} minutes.', $blockTime / 60));
                 $continue = false;
             }
         }
         if ($continue) {
             $user = $this->Auth->identify();
             if ($user) {
                 $this->Auth->setUser($user);
                 if (!empty($user['id'])) {
                     try {
                         $user = $this->Users->get($user['id']);
                         if ($user) {
                             $this->Users->touch($user, 'Users.login');
                             $this->Users->save($user);
                         }
                     } catch (\Exception $e) {
                         // invalid user
                     }
                 }
                 return $this->redirect($this->Auth->redirectUrl());
             } else {
                 if ($loginBlocking && isset($cache) && isset($cacheName)) {
                     $cacheStruct = ['attempts' => 0, 'last_attempt' => 0, 'ip' => '', 'request_log' => []];
                     $cache = array_merge($cacheStruct, $cache);
                     $cache['attempts'] += 1;
                     $cache['last_attempt'] = time();
                     $cache['ip'] = env('REMOTE_ADDR');
                     $cache['request_log'][] = ['data' => $this->request->data, 'time' => time()];
                     Cache::write($cacheName, $cache, 'users_login');
                 }
                 $this->Flash->danger(__d('user', 'Username or password is incorrect.'));
             }
         }
     }
     $user = $this->Users->newEntity();
     $this->title(__d('user', 'Login'));
     $this->set(compact('user'));
 }
Beispiel #11
0
 /**
  * {@inheritDoc}
  *
  */
 public function describe($name, array $options = [])
 {
     $options += ['forceRefresh' => false];
     $cacheConfig = $this->cacheMetadata();
     $cacheKey = $this->cacheKey($name);
     if (!empty($cacheConfig) && !$options['forceRefresh']) {
         $cached = Cache::read($cacheKey, $cacheConfig);
         if ($cached !== false) {
             return $cached;
         }
     }
     $table = parent::describe($name, $options);
     if (!empty($cacheConfig)) {
         Cache::write($cacheKey, $table, $cacheConfig);
     }
     return $table;
 }
 /**
  * Returns a application access token.
  *
  * @return string|bool The access token or false in case of a failure
  */
 public function accessToken()
 {
     $cacheKey = 'twitter-' . $this->config('name') . '-token';
     if (Cache::read($cacheKey) !== false) {
         return Cache::read($cacheKey);
     }
     $bearerToken = $this->bearerToken();
     if (!$bearerToken) {
         return false;
     }
     $client = new Client(['headers' => ['Authorization' => 'Basic ' . $bearerToken], 'host' => 'api.twitter.com', 'scheme' => 'https']);
     $response = $client->post('/oauth2/token', ['grant_type' => 'client_credentials']);
     if (!$response->isOk() || !$response->json['token_type']) {
         return false;
     }
     Cache::write($cacheKey, $response->json['access_token']);
     return $response->json['access_token'];
 }
 /**
  * Returns a list of Controller names found in /src/Controller/Api.
  *
  * @return array List holding sorted Controller names
  */
 public static function getApiControllers()
 {
     $cached = Cache::read('api_controllers');
     if ($cached) {
         return $cached;
     }
     $dir = new Folder(APP . 'Controller' . DS . Inflector::camelize(Configure::read('App++.Api.prefix')));
     $controllerFiles = $dir->find('.*Controller\\.php');
     if (!$controllerFiles) {
         return false;
     }
     $result = [];
     foreach ($controllerFiles as $controllerFile) {
         $result[] = substr($controllerFile, 0, strlen($controllerFile) - 14);
     }
     sort($result);
     Cache::write('api_controllers', $result);
     return $result;
 }
 public function main()
 {
     //Cache::clear(false);
     foreach ($this->Incidents->filterTimes as $filter_string => $filter) {
         foreach ($this->Incidents->summarizableFields as $field) {
             $this->out("processing " . $filter_string . ":" . $field);
             $entriesWithCount = $this->Reports->getRelatedByField($field, 25, false, false, $filter["limit"]);
             $entriesWithCount = json_encode($entriesWithCount);
             Cache::write($field . '_' . $filter_string, $entriesWithCount);
         }
         $query = array('group' => 'grouped_by', 'order' => 'Incidents.created');
         if (isset($filter["limit"])) {
             $query["conditions"] = array('Incidents.created >=' => $filter["limit"]);
         }
         $downloadStats = $this->Incidents->find('all', $query);
         $downloadStats->select(['grouped_by' => $filter["group"], 'date' => "DATE_FORMAT(Incidents.created, '%a %b %d %Y %T')", 'count' => $downloadStats->func()->count('*')]);
         $downloadStats = json_encode($downloadStats->toArray());
         Cache::write('downloadStats_' . $filter_string, $downloadStats);
     }
 }
 protected function _icons()
 {
     $useCache = true;
     if (!empty($this->request->params['named']['reset'])) {
         $useCache = false;
     }
     if ($useCache && ($iconNames = Cache::read('country_icon_names')) !== false) {
         $this->Flash->info('Cache Used');
         return $iconNames;
     }
     $handle = new Folder($this->imageFolder);
     $icons = $handle->read(true, true);
     $iconNames = [];
     foreach ($icons[1] as $icon) {
         # only use files (not folders)
         $iconNames[] = strtoupper(extractPathInfo('filename', $icon));
     }
     Cache::write('country_icon_names', $iconNames);
     return $iconNames;
 }
 public static function loadListeners()
 {
     $eventManager = EventManager::instance();
     $cached = Cache::read('EventHandlers', 'default');
     if ($cached === false) {
         $eventHandlers = Configure::read('EventHandlers');
         $validKeys = array('eventKey' => null, 'options' => array());
         $cached = array();
         if (!empty($eventHandlers) && is_array($eventHandlers)) {
             foreach ($eventHandlers as $eventHandler => $eventOptions) {
                 $eventKey = null;
                 if (is_numeric($eventHandler)) {
                     $eventHandler = $eventOptions;
                     $eventOptions = array();
                 }
                 list($plugin, $class) = pluginSplit($eventHandler);
                 if (!empty($eventOptions)) {
                     extract(array_intersect_key($eventOptions, $validKeys));
                 }
                 if (isset($eventOptions['options']['className'])) {
                     list($plugin, $class) = pluginSplit($eventOptions['options']['className']);
                 }
                 if (class_exists('\\' . $plugin . '\\Event\\' . $class)) {
                     $cached[] = compact('plugin', 'class', 'eventKey', 'eventOptions');
                 } else {
                     Log::error(__d('croogo', 'EventHandler %s not found in plugin %s', $class, $plugin));
                 }
             }
             Cache::write('EventHandlers', $cached, 'default');
         }
     }
     foreach ($cached as $cache) {
         extract($cache);
         if (Plugin::loaded($plugin)) {
             $settings = isset($eventOptions['options']) ? $eventOptions['options'] : array();
             $namespace = '\\' . $plugin . '\\Event\\' . $class;
             $listener = new $namespace($settings);
             $eventManager->on($listener, $eventKey, $eventOptions);
         }
     }
 }
Beispiel #17
0
 protected function initData()
 {
     $menus = \Cake\Cache\Cache::read('admin_menus');
     if ($menus === false) {
         $Menu = \Cake\ORM\TableRegistry::get('cwp_menu');
         $menus = $Menu->find()->hydrate(false)->where('status = 1')->orderDesc('rank')->toArray();
         $menus = \Admin\Utils\Util::getMenu($menus);
         \Cake\Cache\Cache::write('admin_menus', $menus);
     }
     $this->_menus = $menus;
     $controller = strtolower($this->request->param('controller'));
     $action = strtolower($this->request->param('action'));
     $url = '/admin/' . $controller . '/' . $action;
     $this->_url = $url;
     $active = null;
     foreach ($menus as $value) {
         if (isset($value['child'])) {
             foreach ($value['child'] as $sub_menu) {
                 if ($sub_menu['node'] == $url) {
                     $this->_pageTitle = $sub_menu['name'];
                     $this->_breadFirst = ['name' => $value['name'], 'node' => $value['node']];
                     $this->_breadSecond = ['name' => $sub_menu['name'], 'node' => $sub_menu['node']];
                     break;
                 }
                 if (isset($sub_menu['child'])) {
                     foreach ($sub_menu['child'] as $v) {
                         if ($v['node'] == $url) {
                             $active = $sub_menu['node'];
                             $this->_active = $active;
                             $this->_pageTitle = $v['name'];
                             $this->_breadFirst = ['name' => $value['name'], 'node' => $value['node']];
                             $this->_breadSecond = ['name' => $sub_menu['name'], 'node' => $sub_menu['node']];
                         }
                     }
                 }
             }
         }
     }
 }
 /**
  * Authorizes current logged in user, if user belongs to the "administrator"
  * he/she is automatically authorized.
  *
  * @param array $user Active user data
  * @param \Cake\Network\Request $request Request instance
  * @return bool True if user is can access this request
  */
 public function authorize($user, Request $request)
 {
     if ($request->is('userAdmin')) {
         return true;
     }
     $user = user();
     $path = $this->requestPath($request);
     $cacheKey = 'permissions_' . intval($user->id);
     $permissions = Cache::read($cacheKey, 'permissions');
     if ($permissions === false) {
         $permissions = [];
         Cache::write($cacheKey, [], 'permissions');
     }
     if (!isset($permissions[$path])) {
         $allowed = $user->isAllowed($path);
         $permissions[$path] = $allowed;
         Cache::write($cacheKey, $permissions, 'permissions');
     } else {
         $allowed = $permissions[$path];
     }
     return $allowed;
 }
 public function stats()
 {
     $filter = $this->_getTimeFilter();
     $relatedEntries = array();
     $filter_string = $this->request->query('filter');
     if (!$filter_string) {
         $filter_string = "all_time";
     }
     $entriesWithCount = array();
     //Cache::clear(false);
     foreach (TableRegistry::get('Incidents')->summarizableFields as $field) {
         if (($entriesWithCount = Cache::read($field . '_' . $filter_string)) === false) {
             $entriesWithCount = TableRegistry::get('Reports')->getRelatedByField($field, 25, false, false, $filter["limit"]);
             $entriesWithCount = json_encode($entriesWithCount);
             Cache::write($field . '_' . $filter_string, $entriesWithCount);
         }
         $relatedEntries[$field] = json_decode($entriesWithCount, TRUE);
     }
     $this->set("related_entries", $relatedEntries);
     $this->set('columns', TableRegistry::get('Incidents')->summarizableFields);
     $this->set('filter_times', TableRegistry::get('Incidents')->filterTimes);
     $this->set('selected_filter', $this->request->query('filter'));
     $query = array('group' => 'grouped_by', 'order' => 'Incidents.created');
     if (isset($filter["limit"])) {
         $query["conditions"] = array('Incidents.created >=' => $filter["limit"]);
     }
     TableRegistry::get('Incidents')->recursive = -1;
     $downloadStats = array();
     if (($downloadStats = Cache::read('downloadStats_' . $filter_string)) === false) {
         $downloadStats = TableRegistry::get('Incidents')->find('all', $query);
         $downloadStats->select(['grouped_by' => $filter["group"], 'date' => "DATE_FORMAT(Incidents.created, '%a %b %d %Y %T')", 'count' => $downloadStats->func()->count('*')]);
         $downloadStats = json_encode($downloadStats->toArray());
         Cache::write('downloadStats_' . $filter_string, $downloadStats);
     }
     $this->set('download_stats', json_decode($downloadStats, TRUE));
 }
 /**
  * @param ComponentRegistry $registry The controller for this request.
  * @param array $config An array of config. This class does not use any config.
  */
 public function __construct(ComponentRegistry $registry, array $config = [])
 {
     parent::__construct($registry, $config);
     if (!file_exists(CONFIG . $this->config('hierarchyFile'))) {
         throw new Exception(sprintf("Provided hierarchy config file %s doesn't exist.", $this->config('hierarchyFile')));
     }
     if (!file_exists(CONFIG . $this->config('aclFile'))) {
         throw new Exception(sprintf("Provided ACL config file %s doesn't exist.", $this->config('aclFile')));
     }
     // caching
     $hierarchyModified = filemtime(CONFIG . $this->config('hierarchyFile'));
     $aclModified = filemtime(CONFIG . $this->config('aclFile'));
     $lastModified = $hierarchyModified > $aclModified ? $hierarchyModified : $aclModified;
     if (Cache::read('hierarchy_auth_build_time') < $lastModified) {
         $this->_hierarchy = $this->_getHierarchy();
         $this->_acl = $this->_getAcl();
         Cache::write('hierarchy_auth_cache', ['acl' => $this->_acl, 'hierarchy' => $this->_hierarchy]);
         Cache::write('hierarchy_auth_build_time', time());
     } else {
         $cache = Cache::read('hierarchy_auth_cache');
         $this->_hierarchy = $cache['hierarchy'];
         $this->_acl = $cache['acl'];
     }
 }
 /**
  * Test clearing a cache group
  *
  * @return void
  */
 public function testGroupClear()
 {
     Cache::config('memcached_groups', ['engine' => 'Memcached', 'duration' => 3600, 'groups' => ['group_a', 'group_b']]);
     $this->assertTrue(Cache::write('test_groups', 'value', 'memcached_groups'));
     $this->assertTrue(Cache::clearGroup('group_a', 'memcached_groups'));
     $this->assertFalse(Cache::read('test_groups', 'memcached_groups'));
     $this->assertTrue(Cache::write('test_groups', 'value2', 'memcached_groups'));
     $this->assertTrue(Cache::clearGroup('group_b', 'memcached_groups'));
     $this->assertFalse(Cache::read('test_groups', 'memcached_groups'));
 }
 /**
  * Sets to cache the timestamp of the next record to be published.
  * This value can be used to check if the cache is valid
  * @return void
  * @uses $cache
  */
 public function setNextToBePublished()
 {
     $next = $this->find()->select('created')->where([sprintf('%s.active', $this->alias()) => true, sprintf('%s.created >', $this->alias()) => new Time()])->order([sprintf('%s.created', $this->alias()) => 'ASC'])->first();
     $next = empty($next->created) ? false : $next->created->toUnixString();
     Cache::write('next_to_be_published', $next, $this->cache);
 }
Beispiel #23
0
 /**
  * Helper function called on write for cache sessions.
  *
  * @param int $id ID that uniquely identifies session in database
  * @param mixed $data The value of the data to be saved.
  * @return bool True for successful write, false otherwise.
  */
 public function write($id, $data)
 {
     return Cache::write($id, $data, $this->_options['config']);
 }
 /**
  * Prepares the given threaded list of terms.
  *
  * @param array $terms Threaded list of terms
  * @param \Cake\Datasource\EntityInterface $block The block
  */
 public static function termsForBlock($terms, $block)
 {
     foreach ($terms as $term) {
         $title = $term->name;
         if (!empty($block->settings['show_counters'])) {
             $countCacheKey = "t{$term->id}";
             $count = (string) Cache::read($countCacheKey, 'terms_count');
             if ($count == '') {
                 $count = (int) TableRegistry::get('Taxonomy.EntitiesTerms')->find()->where(['EntitiesTerms.term_id' => $term->id])->count();
                 Cache::write($countCacheKey, $count, 'terms_count');
             }
             $title .= " ({$count})";
         }
         $term->set('title', $title);
         $term->set('url', "/find/term:{$term->slug}");
         if (!empty($term->children)) {
             $term->set('expanded', true);
             static::termsForBlock($term->children, $block);
         }
     }
 }
Beispiel #25
0
 /**
  * Used to write runtime configuration into Cache. Stored runtime configuration can be
  * restored using `Configure::restore()`. These methods can be used to enable configuration managers
  * frontends, or other GUI type interfaces for configuration.
  *
  * @param string $name The storage name for the saved configuration.
  * @param string $cacheConfig The cache configuration to save into. Defaults to 'default'
  * @param array $data Either an array of data to store, or leave empty to store all values.
  * @return bool Success
  */
 public static function store($name, $cacheConfig = 'default', $data = null)
 {
     if ($data === null) {
         $data = static::$_values;
     }
     return Cache::write($name, $data, $cacheConfig);
 }
 /**
  * Returns the targeted field names for all configured formatter, live and
  * normal caching.
  *
  * If a formatter cannot be found, it will silently be removed from the list.
  *
  * @return array
  */
 protected function formatters()
 {
     if ($this->loaded === false) {
         $useCache = $this->useCache();
         $cacheKey = $this->cacheKey();
         $cache = true === $useCache ? Cache::read($cacheKey) : false;
         if (false === $cache) {
             $cache = [];
             foreach ((array) $this->config('formatters') as $callback => $conditions) {
                 $tokens = preg_split('/::/', $callback);
                 if (method_exists($tokens[0], $tokens[1])) {
                     $cache[$callback] = $this->fieldsByConditions($conditions);
                 }
             }
             if (true === $useCache) {
                 Cache::write($cacheKey, $cache);
             }
         }
         $this->cache = $cache;
         $this->loaded = true;
     }
     return $this->cache;
 }
Beispiel #27
0
 /**
  * Create a cached block of view logic.
  *
  * This allows you to cache a block of view output into the cache
  * defined in `elementCache`.
  *
  * This method will attempt to read the cache first. If the cache
  * is empty, the $block will be run and the output stored.
  *
  * @param callable $block The block of code that you want to cache the output of.
  * @param array $options The options defining the cache key etc.
  * @return string The rendered content.
  * @throws \RuntimeException When $options is lacking a 'key' option.
  */
 public function cache(callable $block, array $options = [])
 {
     $options += ['key' => '', 'config' => $this->elementCache];
     if (empty($options['key'])) {
         throw new RuntimeException('Cannot cache content with an empty key');
     }
     $result = Cache::read($options['key'], $options['config']);
     if ($result) {
         return $result;
     }
     ob_start();
     $block();
     $result = ob_get_clean();
     Cache::write($options['key'], $result, $options['config']);
     return $result;
 }
Beispiel #28
0
 /**
  * Method that returns posts tags urls
  * @return array
  * @uses MeCms\Utility\SitemapBuilder::parse()
  */
 public static function postsTags()
 {
     $table = TableRegistry::get('MeCms.Tags');
     $url = Cache::read('sitemap', $table->cache);
     if ($url) {
         return $url;
     }
     $tags = $table->find('all')->select(['tag', 'modified'])->order(['tag' => 'ASC'])->where(['post_count >' => 0]);
     if ($tags->isEmpty()) {
         return [];
     }
     $latest = $table->find()->select(['modified'])->order(['modified' => 'DESC'])->firstOrFail();
     //Adds the tags index
     $url[] = self::parse(['_name' => 'postsTags'], ['lastmod' => $latest->modified]);
     //Adds all tags
     $url = am($url, array_map(function ($tag) {
         return self::parse(['_name' => 'postsTag', $tag->slug], ['lastmod' => $tag->modified]);
     }, $tags->toArray()));
     Cache::write('sitemap', $url, $table->cache);
     return $url;
 }
Beispiel #29
0
 /**
  * Test clearing a cache group
  *
  * @return void
  */
 public function testGroupClear()
 {
     Cache::config('apc_groups', array('engine' => 'Apc', 'duration' => 0, 'groups' => array('group_a', 'group_b'), 'prefix' => 'test_'));
     $this->assertTrue(Cache::write('test_groups', 'value', 'apc_groups'));
     $this->assertTrue(Cache::clearGroup('group_a', 'apc_groups'));
     $this->assertFalse(Cache::read('test_groups', 'apc_groups'));
     $this->assertTrue(Cache::write('test_groups', 'value2', 'apc_groups'));
     $this->assertTrue(Cache::clearGroup('group_b', 'apc_groups'));
     $this->assertFalse(Cache::read('test_groups', 'apc_groups'));
 }
Beispiel #30
0
 /**
  * @return Array 2d heading and values
  */
 public function getOfficialIsoList()
 {
     $this->HtmlDom = new HtmlDom();
     if (!($res = Cache::read('lov_gov_iso_list'))) {
         $res = file_get_contents('http://www.loc.gov/standards/iso639-2/php/code_list.php');
         $res = $this->HtmlDom->domFromString($res);
         Cache::write('lov_gov_iso_list', $res);
     }
     foreach ($res->find('table') as $element) {
         $languageArray = $element->plaintext;
         $languageArray = explode(TB . TB, $languageArray);
         array_shift($languageArray);
         $max = count($languageArray);
         $languageArray[$max - 1] = array_shift(explode(' ', $languageArray[$max - 1]));
         foreach ($languageArray as $key => $val) {
             $languageArray[$key] = trim(str_replace(["&lt;", "&gt;", '&amp;', '&#039;', '&quot;', '&nbsp;'], ["<", ">", '&', '\'', '"', ' '], $val));
         }
         $languages = [];
         for ($i = 0; $i < $max; $i = $i + 4) {
             $iso3 = $languageArray[$i];
             if (isset($languages[$iso3])) {
                 continue;
             }
             $iso2 = $languageArray[$i + 1];
             if (strpos($iso3, '(') !== false) {
                 $iso3array = explode(NL, $iso3);
                 foreach ($iso3array as $key => $val) {
                     if (strpos($val, '(T)') === false) {
                         continue;
                     }
                     $iso3 = trim(array_shift(explode('(', $val)));
                 }
             }
             $languages[$iso3] = ['iso3' => $iso3, 'iso2' => $iso2, 'ori_name' => $languageArray[$i + 2]];
         }
         $heading = ['ISO 639-2 Code (alpha3)', 'ISO 639-1 Code (alpha2)', 'English name of Language'];
         break;
     }
     return ['heading' => $heading, 'values' => $languages];
 }