/** * Минификация яваскриптов * * @return void */ public function jsAction() { $this->_response->setHeader('Content-Type', 'text/javascript', true); if (isset($this->_params['files'])) { $files = explode(',', $this->_params['files']); foreach ($files as $key => $file) { $file = $this->_jsdir . trim($file) . '.js'; if (file_exists($file)) { $files[$key] = $file; } } if (!empty($files)) { $cacheid = 'minify_js_' . md5(implode(',', $files)); $this->_cache->setMasterFiles($files); if ($this->_cache->test($cacheid)) { $this->_response->setBody($this->_cache->load($cacheid)); } else { require_once 'Phorm/Plugin/jsmin.php'; $str = ''; foreach ($files as $file) { $str .= file_get_contents($file) . PHP_EOL; } $js = JSMin::minify($str); $this->_cache->save($js, $cacheid); $this->_response->setBody($js); } } } }
/** * * @param string|array $data * @param string $id * @return \ZendT_Cache */ public function set($data, $id = '') { if ($id == '') { $id = $this->_id; } if ($id == '') { throw new ZendT_Exception('Favor informar o id do cache!'); } $data = serialize($data); $this->_cache->save($data, $id); return $this; }
/** Perform a curl request based on url provided * @access public * @param string $method * @param array $params * @return type */ public function get($method, $params) { $url = $this->createUrl($method, $params); if (!$this->_cache->test(md5($url))) { $config = array('adapter' => 'Zend_Http_Client_Adapter_Curl', 'curloptions' => array(CURLOPT_POST => true, CURLOPT_USERAGENT => $_SERVER["HTTP_USER_AGENT"], CURLOPT_FOLLOWLOCATION => true, CURLOPT_RETURNTRANSFER => true, CURLOPT_LOW_SPEED_TIME => 1)); $client = new Zend_Http_Client($url, $config); $response = $client->request(); $data = $response->getBody(); $this->_cache->save($data); } else { $data = $this->_cache->load(md5($url)); } return Zend_Json_Decoder::decode($data, Zend_Json::TYPE_OBJECT); }
/** Get data from the endpoint * @access protected * @return string */ protected function getData() { $key = md5($this->_uri); if (!$this->_cache->test($key)) { $graph = new EasyRdf_Graph(self::URI . $this->_uri . self::SUFFIX); $graph->load(); $data = $graph->resource(self::URI . $this->_uri); $this->_cache->save($data); } else { $data = $this->_cache->load($key); } EasyRdf_Namespace::set('dcterms', 'http://purl.org/dc/terms/'); EasyRdf_Namespace::set('pleiades', 'http://pleiades.stoa.org/places/vocab#'); return $data; }
/** * Connects to the API and logs in * * @param string $rest_url * @param string $username * @param string $password * @param string $md5_password * @return boolean */ function connect($rest_url = null, $username = null, $password = null, $md5_password = true) { if ($this->cache && ($this->session = $this->cache->load('suiteSession'))) { $this->logged_in = TRUE; } if (!$this->logged_in) { if (!is_null($rest_url)) { $this->rest_url = $rest_url; } if (!is_null($username)) { $this->username = $username; } if (!is_null($password)) { $this->password = $password; } $this->logged_in = FALSE; if ($this->login($md5_password)) { $this->logged_in = TRUE; if ($this->cache) { $this->cache->save($this->session, 'suiteSession'); } } } return $this->logged_in; }
/** Get the data for a postcode * @access public * @param string $postcode * @return array * @throws Pas_Geo_Exception */ public function getData($postcode) { if ($this->_validator->isValid($postcode)) { $postcode = str_replace(' ', '', $postcode); } else { throw new Pas_Geo_Exception('Invalid postcode sent'); } $key = md5($postcode); if (!$this->_cache->test($key)) { $response = $this->_get($postcode); $this->_cache->save($response); } else { $response = $this->_cache->load($key); } $geo = json_decode($response); return array('lat' => $geo->wgs84_lat, 'lon' => $geo->wgs84_lon); }
/** * Save Table Names Cache * * Saves the current value of $_tableNames into the cache. * * @return void */ protected function _saveTableNamesCache() { if (!$this->_cache) { return; } // store table list for 12 hours $this->_cache->save($this->_tableNames, 'rsc_simpledb_tablenames', array(), 43200); }
/** * Metodo que faz limpeza do Cache (Memcached ou Filesystem) * das duas instancias de cache do MPE: cache_FS e cache_acl * * Como chamar via admim: * * http://[mpe-dominio]/cache/clean-all-caches * * @author esilva * * @param Zend_Cache $cache */ public function cleanAllCachesAction(Zend_Cache $cache = null) { $this->_helper->layout()->disableLayout(); $this->_helper->viewRenderer->setNoRender(); $this->cache = Zend_Registry::get('cache_FS'); $this->cache2 = Zend_Registry::get('cache_acl'); echo "<br>Inserindo conteudo no Cache (Memcached ou Filesystem) <br><br>"; $this->cache->save('conteudo variavel teste eh este!!', 'teste'); $testando = $this->cache->load('teste'); $this->cache2->save('conteudo variavel testeAcl eh este!!', 'testeAcl'); $testandoAcl = $this->cache2->load('testeAcl'); sleep(1); echo ""; var_dump('teste_var (cache): ', $testando); var_dump('teste_var_acl (cache): ', $testandoAcl); echo "<br><BR>LIMPANDO CACHE!!!<br><BR>"; // clean all records $this->cache->clean(Zend_Cache::CLEANING_MODE_ALL); $this->cache2->clean(Zend_Cache::CLEANING_MODE_ALL); // clean only outdated $this->cache->clean(Zend_Cache::CLEANING_MODE_OLD); $this->cache2->clean(Zend_Cache::CLEANING_MODE_OLD); sleep(2); echo "<br> [Verificação da limpeza do cache]<Br><BR>"; $testando = $this->cache->load('teste'); $testando2 = $this->cache->load('teste2'); $testando3 = $this->cache->load('teste3'); $testandoAcl = $this->cache2->load('testeAcl'); //recupera do cache if ($testando == false) { echo "variavel [teste] não mais existe<br>"; echo "variavel [teste2] não mais existe<br>"; echo "variavel [teste3] não mais existe<br>"; echo "variavel [testeAcl] não mais existe<br>"; } else { echo "variavel [teste] existe no cache: "; echo "teste: " . $testando . "<br>"; echo "variavel [teste2] existe no cache: "; echo "teste2: " . $testando2 . "<br>"; echo "variavel [teste3] existe no cache: "; echo "teste3: " . $testando3 . "<br>"; echo "variavel [testeAcl] existe no cache: "; echo "testeAcl: " . $testandoAcl . "<br>"; } }
/** Fetch pairs from the model * @access public * @param string $sql * @param array $bind * @return array */ public function fetchPairs($sql, $bind = array()) { $id = md5($sql); if (!$this->_cache->test($id) || !$this->cache_result) { $result = parent::fetchPairs($sql, $bind); $this->_cache->save($result); return $result; } else { return $this->_cache->load($id); } }
/** Fetch one result * @access public * @param array $where * @param string $order * @return Object */ public function fetchRow($where = null, $order = null) { $id = md5($where->__toString()); if (!$this->_cache->test($id) || !$this->cache_result) { $result = parent::fetchRow($where, $order); $this->_cache->save($result); return $result; } else { return $this->_cache->load($id); } }
/** * Push an element onto the end of the queue * * @param mixed $message message to send to the queue * @param string $name queue name * @return Zend_Queue_Message */ public function send($message, $name = null) { if ($name !== null) { $this->setActiveQueue($name); } else { $name = $this->getActiveQueue(); } $data = array('message_id' => md5(uniqid(rand(), true)), 'handle' => null, 'body' => $message, 'md5' => md5($message)); $this->_cache->save($data, $data['message_id'], array($name)); $config = array('queue' => $this, 'data' => $data); Zend_Loader::loadClass($this->_msgClass); return new $this->_msgClass($config); }
/** * Save data to the cache * * @param mixed $data The data to be saved, if data fails is_string() check, then it will be serialized. * You then must unserialize it when it is retrieved from cache or call the load method * like so: $cache->load('cacheId', true); * @param string $id Cache id (if not set, the last cache id will be used) * @return boolean * @throws coding_exception */ public function save($data, $id = null) { if ($this->cache === false) { return true; } try { if (!is_string($data)) { $data = serialize($data); } return $this->cache->save($data, $id); } catch (Zend_Cache_Exception $e) { throw new coding_exception('Zend Cache Error: ' . $e->getMessage()); } }
/** * method for set cache value with specific life time * * @param string $key the key in the cache container * @param mixed $value the value in the cache container * if automatic_serialization is not set (set by default), require to be a string * @param string $prefix the prefix used for grouping * @param int $lifetime if != false, set a specific lifetime for this cache record (null => infinite lifetime) * * @return mixed the value in the cache for the key */ public function set($key, $value, $prefix = null, $lifetime = false) { if (!is_null($prefix)) { $prevPrefix = $this->addPrefix($prefix); } $saveStatus = $this->cache->save($value, $key, array(), $lifetime); if (!is_null($prefix)) { // revert to the default prefix $this->setPrefix($prevPrefix); } if ($saveStatus !== FALSE) { return $value; } return FALSE; }
/** Reverse geocode for woeid and other data * @param float $lat * @param float $lon * @return array|boolean */ public function reverseGeoCode($lat, $lon) { if (!is_null($lat) && !is_null($lon)) { $key = 'geocode' . md5($lat . $lon); if (!($place = $this->_cache->load($key))) { $yql = 'SELECT * FROM geo.placefinder where text="' . $lat . ',' . $lon . '" and gflags="R"'; // $yql = 'SELECT * FROM xml WHERE url="http://where.yahooapis.com/geocode?location=' . $lat . '+' . $lon // . '&gflags=R&appid=' . $this->_appID . '"'; $place = $this->_oauth->execute($yql, $this->_accessToken, $this->_accessSecret, $this->_accessExpiry, $this->_handle); $this->_cache->save($place); } else { $place = $this->_cache->load($key); } if (sizeof($place) > 0) { $place = $this->_parser->parseGeocoded($place); return $place; } else { return false; } } else { return false; } }
/** * Tests if the password appears on a (weak) password list. The list should * be a simpe newline separated list of (lowercase) passwords. * * @param string $parameter Filename of the password list, relative to APPLICATION_PATH * @param string $password The password */ protected function inPasswordList($parameter, $password) { if (empty($parameter)) { return; } if ($this->cache) { $passwordList = $this->cache->load('weakpasswordlist'); } if (empty($passwordList)) { $filename = __DIR__ . '/../../../docs/' . ltrim($parameter, '/'); if (!file_exists($filename)) { throw new \Gems_Exception("Unable to load password list '{$filename}'"); } $passwordList = explode("\n", file_get_contents($filename)); if ($this->cache) { $this->cache->save($passwordList, 'weakpasswordlist'); } } if (null === $password) { $this->_addError($this->translate->_('should not appear in the list of common passwords')); } elseif (in_array(strtolower($password), $passwordList)) { $this->_addError($this->translate->_('appears in the list of common passwords')); } }
/** * Returns PHPTAL output - either from a render or from the cache. * * @param string|array $template The name of the template to render or * an array with the ('src') src for a template * and a ('name') name to help identify the * template in error messages. * * @return string */ public function render($template) { // Check we are fully configured and initialised. if ($this->_engine == null) { throw new \Zend_View_Exception('PHPTAL is not defined', $this); } // If a cache has been setup and content is available, return it if ($this->_zendPageCacheContent != false) { return $this->_zendPageCacheContent; } // Setup the script locations based on the view's script paths $this->_engine->setTemplateRepository($this->getScriptPaths()); // Do this at this point rather than in the constructor because we don't // know what the template repositories are going to be at that point. $this->_engine->addSourceResolver(new PharResolver($this->getScriptPaths())); // Assign all the variables set here through to the PHPTAL engine. foreach ($this->getVars() as $key => $value) { $this->_engine->set($key, $value); } if (!is_array($template)) { $this->_engine->setTemplate($this->_convertTemplateName($template)); } else { $this->_engine->setSource($template['src'], $template['name']); } // Setup a collection of standard variable available in the view $this->_engine->set('doctype', $this->doctype()); $this->_engine->set('headTitle', $this->headTitle()); $this->_engine->set('headScript', $this->headScript()); $this->_engine->set('headLink', $this->headLink()); $this->_engine->set('headMeta', $this->headMeta()); $this->_engine->set('headStyle', $this->headStyle()); $this->productionMode = 'production' == APPLICATION_ENV; // If perging of the tal template cache is enabled // find all template cache files and delete them if ($this->_purgeCacheBeforeRender) { $cacheFolder = $this->_engine->getPhpCodeDestination(); if (is_dir($cacheFolder)) { foreach (new \DirectoryIterator($cacheFolder) as $cacheItem) { if (strncmp($cacheItem->getFilename(), 'tpl_', 4) != 0 || $cacheItem->isdir()) { continue; } @unlink($cacheItem->getPathname()); } } } // if a layout is being used and nothing has already overloaded the viewContent, // register the content as viewContent, otherwise set it to empty if (!isset($this->viewContent)) { if ($this->getHelperPath('layout') != false && $this->layout()->isEnabled()) { $this->_engine->set('viewContent', $this->layout()->content); } else { $this->viewContent = ''; } } if (!$this->_preFiltersRegistered) { // Strip html comments and compress un-needed whitespace $this->_engine->addPreFilter(new \PHPTAL_PreFilter_StripComments()); if ($this->_compressWhitespace == true) { $this->_engine->addPreFilter(new \PHPTAL_PreFilter_Compress()); } $this->_preFiltersRegistered = true; } try { $result = $this->_engine->execute(); } catch (\PHPTAL_TemplateException $e) { // If the exception is a root PHPTAL_TemplateException // rather than a subclass of this exception and xdebug is enabled, // it will have already been picked up by xdebug, if enabled, and // should be shown like any other php error. // Any subclass of PHPTAL_TemplateException can be handled by // the phptal internal exception handler as it gives a useful // error output if (get_class($e) == 'PHPTAL_TemplateException' && function_exists('xdebug_is_enabled') && xdebug_is_enabled()) { exit; } throw $e; } // If the page needed to be rendered but was configured to // cache then cache the result of the render. if ($this->_zendPageCache instanceof \Zend_Cache_Core) { $this->_zendPageCache->save($result, $this->_zendPageCacheKey, array(), $this->_zendPageCacheDuration); } return $result; }
/** * Return the Translate class. * * If don't exists, try to create it. * * @param string|Zend_Locale $locale Locale/Language to set. * * @return Phprojekt_Language An instance of Phprojekt_Language. */ public function getTranslate($locale = null) { if (null === $locale) { $locale = Phprojekt_User_User::getSetting("language", $this->_config->language); } if (!($translate = $this->_cache->load('Phprojekt_getTranslate_' . $locale))) { $translate = new Phprojekt_Language($locale); $this->_cache->save($translate, 'Phprojekt_getTranslate_' . $locale, array('Language')); } return $translate; }
/** * Returns PHPTAL output - either from a render or from the cache. * * @param string|array $template The name of the template to render or * an array with the ('src') src for a template * and a ('name') name to help identify the * template in error messages. * * @return string */ public function render($template) { $this->_checkLoaded(); if ($this->_zendPageCacheContent != false) { return $this->_zendPageCacheContent; } if (!is_array($template)) { //conversion of template names from '-' split to camel-case $templateParts = explode('-', $template); $firstPart = array_shift($templateParts); foreach ($templateParts as &$currentPart) { $currentPart = ucfirst($currentPart); } $template = $firstPart . implode('', $templateParts); $this->_engine->setTemplate($template); } else { $this->_engine->setSource($template['src'], $template['name']); } $this->productionMode = 'production' == APPLICATION_ENV; $this->_engine->set('doctype', $this->doctype()); $this->_engine->set('headTitle', $this->headTitle()); $this->_engine->set('headScript', $this->headScript()); $this->_engine->set('headLink', $this->headLink()); $this->_engine->set('headMeta', $this->headMeta()); $this->_engine->set('headStyle', $this->headStyle()); if ($this->_purgeCacheBeforeRender) { $cacheFolder = $this->_engine->getPhpCodeDestination(); if (is_dir($cacheFolder)) { foreach (new DirectoryIterator($cacheFolder) as $cacheItem) { if (strncmp($cacheItem->getFilename(), 'tpl_', 4) != 0 || $cacheItem->isdir()) { continue; } @unlink($cacheItem->getPathname()); } } } // if a layout is being used and nothing has already overloaded the viewContent, // register the content as viewContent, otherwise set it to empty if (!isset($this->viewContent)) { if ($this->getHelperPath('layout') != false && $this->layout()->isEnabled()) { $this->_engine->set('viewContent', $this->layout()->content); } else { $this->viewContent = ''; } } // Strip html comments and compress un-needed whitespace $this->_engine->addPreFilter(new PHPTAL_PreFilter_StripComments()); if ($this->_compressWhitespace == true) { $this->_engine->addPreFilter(new PHPTAL_PreFilter_Compress()); } try { $result = $this->_engine->execute(); } catch (PHPTAL_TemplateException $e) { // If the exception is a root PHPTAL_TemplateException // rather than a subclass of this exception and xdebug is enabled, // it will have already been picked up by xdebug, if enabled, and // should be shown like any other php error. // Any subclass of PHPTAL_TemplateException can be handled by // the phptal internal exception handler as it gives a useful // error output if (get_class($e) == 'PHPTAL_TemplateException' && function_exists('xdebug_is_enabled') && xdebug_is_enabled()) { exit; } throw $e; } if ($this->_zendPageCache instanceof Zend_Cache_Core) { $this->_zendPageCache->save($result, $this->_zendPageCacheKey, array(), $this->_zendPageCacheDuration); } return $result; }
/** * Module view helper. * * Returns an OntoWiki module either rendered or from cache. * * Fetches the module from the module registry and renders it into the * window template. If a rendering exists in the local module cache it * is used instead. * * @param string $moduleName * @param array $moduleOptions An associative array or and instance of * Zend_config with module options. * The following keys can be used: * enabled – whether the module is enabled or disabled * title – the module window's title * caching – whether the module should be cached * priority – priority of the module in the module contexts * lower number means higher priority * classes – string of css classes for the module window * id – a css id for the module window * * @return string */ public function module($moduleName, $renderOptions = null, $context = OntoWiki_Module_Registry::DEFAULT_CONTEXT) { $moduleRegistry = OntoWiki_Module_Registry::getInstance(); // allow old-style array config if (is_array($renderOptions)) { $renderOptions = new Zend_Config($renderOptions); } // get default options from the registry $defaultModuleOptions = $moduleRegistry->getModuleConfig($moduleName); if ($defaultModuleOptions == null) { $moduleOptions = $renderOptions; } else { if ($renderOptions != null) { $moduleOptions = $defaultModuleOptions->merge($renderOptions); } else { $moduleOptions = $defaultModuleOptions; } } $cssClasses = isset($moduleOptions->classes) ? $moduleOptions->classes : ''; $cssId = isset($moduleOptions->id) ? $moduleOptions->id : ''; $module = $moduleRegistry->getModule($moduleName, $context); // no module found if (null == $module) { return ''; } $module->setOptions($moduleOptions); if ($module->shouldShow()) { // init module view if (null == $this->_moduleView) { $this->_moduleView = clone $this; } $this->_moduleView->clearVars(); // query module's title $this->_moduleView->title = $module->getTitle(); // does the module have a message // TODO: allow multiple messages if (method_exists($module, 'getMessage')) { if ($message = $module->getMessage()) { $this->_moduleView->messages = array($message); } } // does the module have a menu? if (method_exists($module, 'getMenu')) { $menu = $module->getMenu(); $this->_moduleView->menu = $menu->toArray(false, false); } // does the module have a context menu? if (method_exists($module, 'getContextMenu')) { $contextMenu = $module->getContextMenu(); if ($contextMenu instanceof OntoWiki_Menu) { $contextMenu = $contextMenu->toArray(); } $this->_moduleView->contextmenu = $contextMenu; } // is caching enabled if ($this->_moduleCache && $module->allowCaching()) { // get cache id $cacheId = md5($module->getCacheId() . $cssClasses . $this->_config->languages->locale); // cache hit? if (!($moduleContent = $this->_moduleCache->load($cacheId))) { // render (expensive) contents $pre = microtime(true); $moduleContent = $module->getContents(); $post = (microtime(true) - $pre) * 1000; // $this->_owApp->logger->info("Rendering module '$moduleName': $post ms (cache miss)"); // save to cache $this->_moduleCache->save($moduleContent, $cacheId, array('module', $moduleName), $module->getCacheLivetime()); } } else { // caching disabled $pre = microtime(true); $moduleContent = $module->getContents(); $post = (microtime(true) - $pre) * 1000; // $this->_owApp->logger->info("Rendering module '$moduleName': $post ms (caching disabled)"); } // implement tabs if (is_array($moduleContent)) { // TODO: tabs $navigation = array(); $content = array(); $i = 0; foreach ($moduleContent as $key => $content) { $navigation[$key] = array('active' => $i++ == 0 ? 'active' : '', 'url' => '#' . $key, 'name' => $this->_($key)); } $this->_moduleView->navigation = $navigation; $this->_moduleView->content = $moduleContent; } else { if (is_string($moduleContent)) { $this->_moduleView->content = $moduleContent; } } // set variables $this->_moduleView->cssClasses = $cssClasses; $this->_moduleView->cssId = $cssId; if (isset($moduleOptions->noChrome) && (bool) $moduleOptions->noChrome) { // render without window chrome $moduleWindow = $this->_moduleView->render('partials/module.phtml'); } else { // render with window chrome $moduleWindow = $this->_moduleView->render('partials/window.phtml'); } return $moduleWindow; } }