/** * Render the cell. * * @param string|null $template Custom template name to render. If not provided (null), the last * value will be used. This value is automatically set by `CellTrait::cell()`. * @return string The rendered cell. * @throws \Cake\View\Exception\MissingCellViewException When a MissingTemplateException is raised during rendering. */ public function render($template = null) { $cache = []; if ($this->_cache) { $cache = $this->_cacheConfig($this->action); } $render = function () use($template) { if ($template !== null && strpos($template, '/') === false && strpos($template, '.') === false) { $template = Inflector::underscore($template); } if ($template === null) { $template = $this->template; } $builder = $this->viewBuilder(); $builder->layout(false); $builder->template($template); $className = substr(strrchr(get_class($this), "\\"), 1); $name = substr($className, 0, -4); $builder->templatePath('Cell' . DS . $name); try { $reflect = new ReflectionMethod($this, $this->action); $reflect->invokeArgs($this, $this->args); } catch (ReflectionException $e) { throw new BadMethodCallException(sprintf('Class %s does not have a "%s" method.', get_class($this), $this->action)); } $this->View = $this->createView(); try { return $this->View->render($template); } catch (MissingTemplateException $e) { throw new MissingCellViewException(['file' => $template, 'name' => $name]); } }; if ($cache) { return Cache::remember($cache['key'], $render, $cache['config']); } return $render(); }
/** * {{@inheritDoc}} */ public function check($aro, $aco, $action = "*") { $key = $this->_getCacheKey($aro, $aco, $action); $permission = Cache::remember($key, function () use($aro, $aco, $action) { return $this->Permission->check($aro, $aco, $action) === true ? 'true' : 'false'; }, $this->_cacheConfig); return $permission === 'true'; }
/** * Get the Notice of the chat. * * @return string */ public function getNotice() { $defaultNotice = __d('chat', 'Welcome on <strong>{0}</strong> ! :heart:', Configure::read('Site.name')); $notice = Cache::remember('notice', function () use($defaultNotice) { $config = HTMLPurifier_Config::createDefault(); $config->loadArray(Configure::read('HtmlPurifier.Chat.notice')); $HTMLPurifier = new HTMLPurifier($config); return $HTMLPurifier->purify($defaultNotice); }, 'chat'); return $notice; }
/** * Find all permissions for a specific $groupId. * * @param array|string $groupId A single group id or an array of group ids. * @return array|mixed */ public function findAllForGroup($groupId) { if (!$groupId) { return []; } if (!is_array($groupId)) { $groupId = [$groupId]; } $cacheKey = join('_', $groupId); $permissions = Cache::remember($cacheKey, function () use($groupId) { return $this->find('list', ['keyField' => 'path', 'valueField' => 'allowed'])->where(['group_id IN' => $groupId, 'allowed >' => 0])->order('allowed DESC')->hydrate(false)->toArray(); }, 'wasabi/core/group_permissions'); return $permissions; }
/** * Loads all settings from db and triggers the event 'Settings.afterLoad' * that can be listened to by plugins to further modify the settings. * * Structure: * ---------- * Array( * 'PluginName|ScopeName' => Array( * 'key1' => 'value1', * ... * ), * ... * ) * * Access via: * ----------- * Configure::read('Settings.ScopeName.key1'); * * @return array */ protected function _loadSettings() { $settings = Cache::remember('settings', function () { /** @var SettingsTable $Settings */ $Settings = $this->loadModel('Wasabi/Core.Settings'); return $Settings->getAllKeyValues(); }, 'wasabi/core/longterm'); $event = new Event('Settings.afterLoad', $settings); $this->eventManager()->dispatch($event); if ($event->result !== null) { $settings = $event->result; } Configure::write('Settings', $settings); }
/** * Index page. * * @return \Cake\Network\Response */ public function index() { $this->loadModel('ForumCategories'); $categories = $this->ForumCategories->find('threaded')->contain(['LastPost', 'LastPost.Users' => function ($q) { return $q->find('short'); }, 'LastPost.ForumThreads' => function ($q) { return $q->select(['id', 'title']); }])->order(['ForumCategories.lft' => 'ASC']); $statistics = []; $statistics['TotalPosts'] = Cache::remember('statisticsTotalPosts', function () { $this->eventManager()->attach(new Statistics()); $event = new Event('Model.ForumPosts.new'); $this->eventManager()->dispatch($event); return $event->result; }, 'forum'); $statistics['TotalThreads'] = Cache::remember('statisticsTotalThreads', function () { $this->eventManager()->attach(new Statistics()); $event = new Event('Model.ForumThreads.new'); $this->eventManager()->dispatch($event); return $event->result; }, 'forum'); $statistics['TotalPostsLikes'] = Cache::remember('statisticsTotalPostsLikes', function () { $this->eventManager()->attach(new Statistics()); $event = new Event('Model.ForumPostsLikes.update'); $this->eventManager()->dispatch($event); return $event->result; }, 'forum'); $statistics['Users'] = Cache::remember('statisticsUsers', function () { $this->eventManager()->attach(new Statistics()); $event = new Event('Model.Users.register'); $this->eventManager()->dispatch($event); return $event->result; }, 'forum'); $statistics['Groups'] = Cache::remember('statisticsGroups', function () { $this->eventManager()->attach(new Statistics()); $event = new Event('Model.Groups.update'); $this->eventManager()->dispatch($event); return $event->result; }, 'forum'); $online = $this->SessionsActivity->getOnlineUsers(); if ($this->Auth->User('id')) { foreach ($categories as $category) { $this->eventManager()->attach(new Reader()); $read = new Event('Reader.Category', $this, ['user_id' => $this->Auth->User('id'), 'category' => $category, 'descendants' => $category->children]); $this->eventManager()->dispatch($read); } } $this->set(compact('categories', 'statistics', 'online')); }
/** * Check if a URL array matches this route instance. * * If the URL matches the route parameters and settings, then * return a generated string URL. If the URL doesn't match the route parameters, false will be returned. * This method handles the reverse routing or conversion of URL arrays into string URLs. * * @param array $url An array of parameters to check matching with. * @param array $context An array of the current request context. * Contains information such as the current host, scheme, port, base * directory and other url params. * @return string|false Either a string URL for the parameters if they match or false. */ public function match(array $url, array $context = []) { unset($url['action'], $url['plugin']); $cacheKey = md5(serialize($url)); $route = Cache::remember($cacheKey, function () use($url, $context) { $routesMatchEvent = new Event('Wasabi.Routes.match', $this, [$url, $context]); EventManager::instance()->dispatch($routesMatchEvent); if (empty($routesMatchEvent->result)) { return false; } return $routesMatchEvent->result; }, 'wasabi/core/routes'); if ($route === false) { return false; } return $context['_base'] . $route; }
/** * Gets a translator from the registry by package for a locale. * * @param string $name The translator package to retrieve. * @param string $locale The locale to use; if empty, uses the default * locale. * @return \Aura\Intl\TranslatorInterface A translator object. * @throws \Aura\Intl\Exception If no translator with that name could be found * for the given locale. */ public function get($name, $locale = null) { if (!$name) { return null; } if ($locale === null) { $locale = $this->getLocale(); } if (!isset($this->registry[$name][$locale])) { $key = "translations.{$name}.{$locale}"; $translator = Cache::remember($key, function () use($name, $locale) { try { return parent::get($name, $locale); } catch (\Aura\Intl\Exception $e) { } if (!isset($this->_loaders[$name])) { $this->registerLoader($name, $this->_partialLoader()); } return $this->_getFromLoader($name, $locale); }, '_cake_core_'); return $this->registry[$name][$locale] = $translator; } return $this->registry[$name][$locale]; }
/** * Render the cell. * * @param string|null $template Custom template name to render. If not provided (null), the last * value will be used. This value is automatically set by `CellTrait::cell()`. * @return string The rendered cell. * @throws \Cake\View\Exception\MissingCellViewException When a MissingTemplateException is raised during rendering. */ public function render($template = null) { $cache = []; if ($this->_cache) { $cache = $this->_cacheConfig($this->action); } $render = function () use($template) { try { $reflect = new ReflectionMethod($this, $this->action); $reflect->invokeArgs($this, $this->args); } catch (ReflectionException $e) { throw new BadMethodCallException(sprintf('Class %s does not have a "%s" method.', get_class($this), $this->action)); } $builder = $this->viewBuilder(); if ($template !== null && strpos($template, '/') === false && strpos($template, '.') === false) { $template = Inflector::underscore($template); } if ($template === null) { $template = $builder->template() ?: $this->template; } $builder->layout(false)->template($template); $className = get_class($this); $namePrefix = '\\View\\Cell\\'; $name = substr($className, strpos($className, $namePrefix) + strlen($namePrefix)); $name = substr($name, 0, -4); if (!$builder->templatePath()) { $builder->templatePath('Cell' . DIRECTORY_SEPARATOR . str_replace('\\', DIRECTORY_SEPARATOR, $name)); } $this->View = $this->createView(); try { return $this->View->render($template); } catch (MissingTemplateException $e) { throw new MissingCellViewException(['file' => $template, 'name' => $name]); } }; if ($cache) { return Cache::remember($cache['key'], $render, $cache['config']); } return $render(); }
/** * test remember method. * * @return void */ public function testRemember() { $this->_configCache(); $counter = 0; $cacher = function () use($counter) { return 'This is some data ' . $counter; }; $expected = 'This is some data 0'; $result = Cache::remember('test_key', $cacher, 'tests'); $this->assertEquals($expected, $result); $counter = 1; $result = Cache::remember('test_key', $cacher, 'tests'); $this->assertEquals($expected, $result); }
/** * Index page. * * @return void */ public function home() { if (Configure::read('Analytics.enabled') === true) { $httpAdapter = new CurlHttpAdapter(); $client = new Client(Configure::read('Analytics.client_id'), Configure::read('Analytics.private_key'), $httpAdapter); $service = new Service($client); $statistics = Cache::remember('statistics', function () use($service) { $statistics = new Query(Configure::read('Analytics.profile_id')); $statistics->setStartDate(new \DateTime(Configure::read('Analytics.start_date')))->setEndDate(new \DateTime())->setMetrics(array('ga:visits', 'ga:visitors', 'ga:pageviews', 'ga:pageviewsPerVisit', 'ga:avgtimeOnSite', 'ga:visitBounceRate', 'ga:percentNewVisits')); return $service->query($statistics); }, 'analytics'); $browsers = Cache::remember('browsers', function () use($service) { $browsers = new Query(Configure::read('Analytics.profile_id')); $browsers->setStartDate(new \DateTime(Configure::read('Analytics.start_date')))->setEndDate(new \DateTime())->setDimensions(array('ga:browser'))->setMetrics(array('ga:pageviews'))->setSorts(array('ga:pageviews'))->setFilters(array('ga:browser==Chrome,ga:browser==Firefox,ga:browser==Internet Explorer,ga:browser==Safari,ga:browser==Opera')); return $service->query($browsers); }, 'analytics'); $continents = Cache::remember('continents', function () use($service) { $continentsRows = new Query(Configure::read('Analytics.profile_id')); $continentsRows->setStartDate(new \DateTime(Configure::read('Analytics.start_date')))->setEndDate(new \DateTime())->setDimensions(array('ga:continent'))->setMetrics(array('ga:visitors'))->setSorts(array('ga:visitors'))->setFilters(array('ga:continent==Africa,ga:continent==Americas,ga:continent==Asia,ga:continent==Europe,ga:continent==Oceania')); $continentsRows = $service->query($continentsRows); $color = new Color("1abc9c"); $light = 1; $continents = []; foreach (array_reverse($continentsRows->getRows()) as $continentRow) { $continent = []; $continent['label'] = $continentRow[0]; $continent['data'] = $continentRow[1]; $continent['color'] = '#' . $color->lighten($light); array_push($continents, $continent); $light += 10; } return $continents; }, 'analytics'); $graphVisitors = Cache::remember('graphVisitors', function () use($service) { $graphVisitors = new Query(Configure::read('Analytics.profile_id')); $graphVisitors->setStartDate(new \DateTime('-7 days'))->setEndDate(new \DateTime())->setDimensions(array('ga:date'))->setMetrics(array('ga:visits', 'ga:pageviews'))->setSorts(array('ga:date')); return $service->query($graphVisitors); }, 'analytics'); $this->set(compact('statistics', 'browsers', 'continents', 'graphVisitors')); } $this->loadModel('Users'); //UsersGraph $usersGraphCount = $this->Users->find('all')->select(['date' => 'DATE_FORMAT(created,\'%d-%m-%Y\')', 'count' => 'COUNT(id)'])->group('DATE(created)')->order(['date' => 'desc'])->where(['UNIX_TIMESTAMP(DATE(created)) >' => (new \DateTime('-8 days'))->getTimestamp()])->toArray(); $usersGraph = array(); //Fill the new array with the date of the 8 past days and give them the value 0. for ($i = 0; $i < 8; $i++) { $date = new \DateTime("{$i} days ago"); $usersGraph[$date->format('d-m-Y')] = 0; } //Foreach value that we got in the database, parse the array by the key date, //and if the key exist, attribute the new value. foreach ($usersGraphCount as $user) { $usersGraph[$user->date] = intval($user->count); } $usersGraph = array_reverse($usersGraph); $usersCount = Number::format($this->Users->find()->count()); $this->loadModel('BlogArticles'); $articlesCount = Number::format($this->BlogArticles->find()->count()); $this->loadModel('BlogArticlesComments'); $commentsCount = Number::format($this->BlogArticlesComments->find()->count()); $this->loadModel('BlogCategories'); $categoriesCount = Number::format($this->BlogCategories->find()->count()); $this->set(compact('usersCount', 'articlesCount', 'commentsCount', 'categoriesCount', 'usersGraph')); }
/** * Get Uri Datas * * @param string $uri The Uri we want to get infos * @return Cake\ORM\Entity */ public function getUriDatas($uri = null) { if ($uri === null) { $uri = $this->request->here; } $uriDatas = Cache::remember('uri_' . md5($uri), function () use($uri) { $SeoUris = TableRegistry::get('Seo.SeoUris'); return $SeoUris->findByUri($uri)->find('approved')->first(); }, 'seo'); return $uriDatas; }
/** * Get By Uri * * Find and return a full SeoUri Entity * * @param string $uri the Uri to find * @param bool $approved filter on approved flag * @return \Cake\ORM\Entity */ public function getByUri($uri, $approved = true) { return Cache::remember('uri_' . md5($uri), function () use($uri, $approved) { $data = $this->findByUri($uri)->contain(['SeoTitles', 'SeoCanonicals', 'SeoMetaTags']); if ($approved) { $data->find('approved'); } return $data->first(); }, 'seo'); }
/** * Read cache * * @return array All saved key value pairs */ protected function _cache() { $keyField = $this->config('fields.key'); $queryBuilder = $this->_queryBuilder(); return Cache::remember('key_value_pairs_' . $this->_table->table(), function () use($queryBuilder, $keyField) { return $queryBuilder->combine($keyField, function ($entity) { return $entity; })->toArray(); }, $this->config('cacheConfig')); }
/** * Load and setup all languages. * * @param null $langId If set, then the language with id = $langId will be set as the content language. * @param bool|false $backend If true also initializes all backend languages * @return void */ public static function loadLanguages($langId = null, $backend = false) { // Configure all available frontend and backend languages. $languages = Cache::remember('languages', function () { /** @var LanguagesTable $Languages */ $Languages = TableRegistry::get('Wasabi/Core.Languages'); $langs = $Languages->find('allFrontendBackend')->all(); return ['frontend' => array_values($Languages->filterFrontend($langs)->toArray()), 'backend' => array_values($Languages->filterBackend($langs)->toArray())]; }, 'wasabi/core/longterm'); Configure::write('languages', $languages); if ($backend === true) { // Backend $request = Router::getRequest(); // Setup the users backend language. $backendLanguage = $languages['backend'][0]; if ($request->session()->check('Auth.User.language_id')) { $backendLanguageId = $request->session()->read('Auth.User.language_id'); if ($backendLanguageId !== null) { foreach ($languages['backend'] as $lang) { if ($lang->id === $backendLanguageId) { $backendLanguage = $lang; break; } } } } // Setup the users content language. $contentLanguage = $languages['frontend'][0]; if ($request->session()->check('contentLanguageId')) { $contentLanguageId = $request->session()->read('contentLanguageId'); foreach ($languages['frontend'] as $lang) { if ($lang->id === $contentLanguageId) { $contentLanguage = $lang; break; } } } Configure::write('contentLanguage', $contentLanguage); Configure::write('backendLanguage', $backendLanguage); I18n::locale($backendLanguage->iso2); } else { // Frontend if ($langId !== null) { foreach ($languages['frontend'] as $frontendLanguage) { if ($frontendLanguage->id === $langId) { Configure::write('contentLanguage', $frontendLanguage); I18n::locale($frontendLanguage->iso2); break; } } } else { Configure::write('contentLanguage', $languages['frontend'][0]); I18n::locale($languages['frontend'][0]->iso2); } } }
/** * Determine the path for a given url array. * * @param array $url The url parameters. * @return string */ public function getPathFromUrl($url) { $cacheKey = md5(serialize($url)); return Cache::remember($cacheKey, function () use($url) { $plugin = 'App'; $action = 'index'; $parsedUrl = !is_array($url) ? Router::parse($url) : $url; if (isset($parsedUrl['plugin']) && !empty($parsedUrl['plugin'])) { $plugin = $parsedUrl['plugin']; } $controller = $parsedUrl['controller']; if (isset($parsedUrl['action']) && $parsedUrl['action'] !== '') { $action = $parsedUrl['action']; } return $plugin . '.' . $controller . '.' . $action; }, 'wasabi/core/guardian_paths'); }