/** * Builds the fetch URL, and returns the resulting as a SimpleXML Object * * @param string $url * @return SimpleXMLElement * @throws tclScraperNetworkException If the URL couldn't be fetched */ protected function fetch() { $this->requestUrl = $this->baseURL; if (count($this->params) > 0) { foreach ($this->params as $key => $value) { $URIComponents[] = "{$key}=" . urlencode($value); } $this->requestUrl .= '?' . implode('&', $URIComponents); } try { $cache = ezcCacheManager::getCache('scrapers'); } catch (Exception $e) { throw $e; } $cacheId = md5($this->requestUrl); if (($this->responseBody = $cache->restore($cacheId)) === false) { set_error_handler(array($this, 'phpFileGetContentsErrorHandler')); $this->responseBody = @file_get_contents($this->requestUrl, 0, stream_context_create(array('http' => array('timeout' => 5)))); restore_error_handler(); $this->responseHeaders = $http_response_header; if ($this->HTTPStatus() != self::HTTP_OK) { throw new tclScraperHTTPException($this->requestUrl, $this->responseHeaders); } $cache->store($cacheId, $this->responseBody); } $doc = new DOMDocument(); $doc->strictErrorChecking = FALSE; if (@$doc->loadHTML($this->responseBody) === false) { throw new tclScraperHTMLException($this->requestUrl, $this->responseBody); } $doc = simplexml_import_dom($doc); return $doc; }
/** * Extract REST routes from APC cache. * Cache is generated if needed * @return array The route objects */ protected function getCachedRoutes() { $ttl = (int)eZINI::instance( 'rest.ini' )->variable( 'CacheSettings', 'RouteApcCacheTTL' ); if( self::$isRouteCacheCreated === false ) { $options = array( 'ttl' => $ttl ); ezcCacheManager::createCache( self::ROUTE_CACHE_ID, self::ROUTE_CACHE_PATH, 'ezpRestCacheStorageApcCluster', $options ); self::$isRouteCacheCreated = true; } $cache = ezcCacheManager::getCache( self::ROUTE_CACHE_ID ); $cacheKey = self::ROUTE_CACHE_KEY . '_' . ezpRestPrefixFilterInterface::getApiProviderName(); if( ( $prefixedRoutes = $cache->restore( $cacheKey ) ) === false ) { try { $prefixedRoutes = $this->doCreateRoutes(); $cache->store( $cacheKey, $prefixedRoutes ); } catch( Exception $e ) { // Sometimes APC can miss a write. No big deal, just log it. // Cache will be regenerated next time ezpRestDebug::getInstance()->log( $e->getMessage(), ezcLog::ERROR ); } } return $prefixedRoutes; }
/** * Builds the fetch URL, and returns the resulting as a SimpleXML Object * * @param string $url An URL to use. Will fallback to $requestUrl if not given. * * @return SimpleXMLElement * @throws tclScraperNetworkException If the URL couldn't be fetched */ protected function fetch( $url = null, $handler = 'parseFromHTMLToXML' ) { $this->requestUrl = $url !== null ? $url : $this->baseURL; if ( count( $this->params ) > 0 ) { foreach( $this->params as $key => $value ) $URIComponents[] = "$key=" . urlencode( $value ); $this->requestUrl .= '?' . implode( '&', $URIComponents ); } if ( self::$isCacheEnabled ) { try { $cache = ezcCacheManager::getCache( 'scrapers' ); } catch( Exception $e ) { throw $e; } $cacheId = md5( $this->requestUrl ); } if ( !self::$isCacheEnabled || !( $this->responseBody = $cache->restore( $cacheId ) ) ) { set_error_handler( array( $this, 'phpFileGetContentsErrorHandler' ) ); $this->responseBody = @file_get_contents( $this->requestUrl, 0, stream_context_create( array( 'http' => array( 'timeout' => 5 ) ) ) ); restore_error_handler(); $this->responseHeaders = $http_response_header; if( $this->HTTPStatus() != self::HTTP_OK ) throw new MkvManagerScraperHTTPException( $this->requestUrl, $this->responseHeaders ); if ( self::$isCacheEnabled) $cache->store( $cacheId, $this->responseBody ); } else { error_log( 'restored from cache' ); } return $this->$handler(); }
<?php require_once 'tutorial_autoload.php'; $options = array('ttl' => 30, 'host' => 'localhost', 'port' => 11211); ezcCacheManager::createCache('memcache', 'memcache', 'ezcCacheStorageMemcachePlain', $options); $myId = 'unique_id_1'; $mySecondId = 'id_2'; $cache = ezcCacheManager::getCache('memcache'); if (($dataOfFirstItem = $cache->restore($myId)) === false) { $dataOfFirstItem = "Plain cache stored on " . date('Y-m-d, H:i:s'); $cache->store($myId, $dataOfFirstItem); } if (($dataOfSecondItem = $cache->restore($mySecondId)) === false) { $dataOfSecondItem = "Plain cache 2 stored on " . date('Y-m-d, H:i:s'); $cache->store($mySecondId, $dataOfSecondItem); } var_dump($dataOfFirstItem, $dataOfSecondItem);
public function testCacheBackendSingleConnection() { $options = array('host' => 'localhost', 'port' => 11211, 'ttl' => 10); ezcCacheManager::createCache('cache-a', null, 'ezcCacheStorageMemcachePlain', $options); ezcCacheManager::createCache('cache-b', null, 'ezcCacheStorageMemcachePlain', $options); $storageA = ezcCacheManager::getCache('cache-a'); $storageA->reset(); $storageB = ezcCacheManager::getCache('cache-b'); $storageA->reset(); $backendA = $this->readAttribute($storageA, 'backend'); $backendB = $this->readAttribute($storageB, 'backend'); $memcacheA = $this->readAttribute($backendA, 'memcache'); $memcacheB = $this->readAttribute($backendB, 'memcache'); $this->assertSame($memcacheA, $memcacheB); unset($storageA); unset($storageA); }
public function testNoBubbleUpAgain() { $stack = ezcCacheManager::getCache(__CLASS__); $data = $this->testDataArray; // Stop bubbling up again $stack->options->bubbleUpOnRestore = false; // Restore item id_2 from 3rd level without bubbling $this->assertEquals($data[1][1], $stack->restore($data[1][0], $data[1][2])); // Restore item id_7 from 2nd level without bubbling $this->assertEquals('id_7_content', $stack->restore('id_7')); $metaData = ezcCacheStackTestConfigurator::$metaStorage->restoreMetaData()->getState(); $this->assertEquals(array('replacementData' => array('id_9' => 7, 'id_3' => 7, 'id_5' => 6, 'id_4' => 6, 'id_2' => 7, 'id_1' => 9, 'id_8' => 8, 'id_7' => 9, 'id_6' => 9), 'storageData' => array('memory_storage' => array('id_6' => true, 'id_8' => true, 'id_9' => true, 'id_1' => true, 'id_3' => true), 'array_storage' => array('id_1' => true, 'id_6' => true, 'id_7' => true, 'id_8' => true, 'id_9' => true, 'id_3' => true), 'eval_array_storage' => array('id_4' => true, 'id_5' => true, 'id_1' => true, 'id_2' => true, 'id_3' => true, 'id_6' => true, 'id_7' => true, 'id_8' => true, 'id_9' => true))), $metaData); }
$layergroupHighlight = null; if ($table == 'tmp') { $enableCache = false; $layergroupHighlight = 'g_tmp'; $idValue = session_id(); } else { $enableCache = true; $layergroupHighlight = "g_{$table}"; } $fileId = $idValue . '_' . $fileDimensions; // set cache attributes $cacheAttributes = array('layer' => $table, 'lang' => $languages[$lang], 'id' => $idValue); $cadastreIntersection = false; $bufferExtent = false; ezcCacheManager::createCache('mappreview', R3_CACHE_DIR . 'mappreview/', 'ezcCacheStorageFilePlain', array('ttl' => 5 * 24 * 60 * 60)); $cache = ezcCacheManager::getCache('mappreview'); if (!$enableCache || ($imageContent = $cache->restore($fileId, $cacheAttributes)) === false) { list($size, $split) = explode('-', $fileDimensions); list($x, $y) = explode('x', $size); $size = array((int) $x, (int) $y); list($unitDimensions, $format) = explode('.', $split); $unitDimensions = explode('x', $unitDimensions); try { switch ($table) { case 'foto': $tableName = 'document_data'; break; default: $tableName = $table; break; }
/** * @group restApplicationCache * @group restClusterCache * @group restCache */ public function testManageCache() { $cacheOptions = array('ttl' => 2); $cacheID = 'test_id'; $cacheKey = 'myUniqueCacheKey'; $cacheLocation = 'myLocation'; $data = array('foo' => 'bar', 'baz' => 123, 'boolean' => true); ezcCacheManager::createCache($cacheID, $cacheLocation, 'ezpRestCacheStorageClusterObject', $cacheOptions); $cache = ezcCacheManager::getCache($cacheID); $cacheContent = $cache->restore($cacheKey); // Should be false as we didn't write anything yet self::assertFalse($cacheContent, 'Cache should be empty before generation'); // Remaining lifetime should be 0 as cache does not exist yet self::assertSame(0, $cache->getRemainingLifetime($cacheKey)); // Store the cache $cache->store($cacheID, $data); $cacheContent = $cache->restore($cacheKey); self::assertSame($data, $cacheContent, 'Invalid cache retrieval !'); // Now check if it is present in the cluster $cacheFullLocation = eZSys::cacheDirectory() . '/rest/' . $cacheLocation; $cacheFile = $cacheKey . '-.cache'; self::assertTrue(eZClusterFileHandler::instance()->fileExists($cacheFullLocation . '/' . $cacheFile), 'REST cache file has not been written in the cluster'); self::assertSame(1, $cache->countDataItems($cacheKey)); self::assertGreaterThan(0, $cache->getRemainingLifetime($cacheKey), 'Invalid remaining lifetime for REST cache'); $cache->delete($cacheKey); // Test file deletion self::assertFalse(eZClusterFileHandler::instance()->fileExists($cacheFullLocation . '/' . $cacheFile), 'REST cache file has not been deleted from the cluster'); }
public function testGetCacheDelayedInit2() { testDelayedInitCacheManager::$tmpDir = $this->createTempDir(__CLASS__); ezcBaseInit::setCallback('ezcInitCacheManager', 'testDelayedInitCacheManager'); $cache = ezcCacheManager::getCache('simple'); self::assertSame('.cache', $cache->options->extension); }
/** * Override to add the "requestedResponseGroups" variable for every REST requests * * @see lib/ezc/MvcTools/src/interfaces/ezcMvcController::createResult() */ public function createResult() { $debug = ezpRestDebug::getInstance(); $debug->startTimer('GeneratingRestResult', 'RestController'); if (!self::$isCacheCreated) { ezcCacheManager::createCache(self::CACHE_ID, $this->getCacheLocation(), 'ezpRestCacheStorageClusterObject', array('ttl' => $this->getActionTTL())); self::$isCacheCreated = true; } $cache = ezcCacheManager::getCache(self::CACHE_ID); $controllerCacheId = $this->generateCacheId(); $isCacheEnabled = $this->isCacheEnabled(); // Try to restore application cache. // If expired or not yet available, generate it and store it $cache->isCacheEnabled = $isCacheEnabled; if (($res = $cache->restore($controllerCacheId)) === false) { try { $debug->log('Generating cache', ezcLog::DEBUG); $debug->switchTimer('GeneratingCache', 'GeneratingRestResult'); $res = parent::createResult(); $resGroups = $this->getResponseGroups(); if (!empty($resGroups)) { $res->variables['requestedResponseGroups'] = $resGroups; } if ($res instanceof ezpRestMvcResult) { $res->responseGroups = $resGroups; } if ($isCacheEnabled) { $cache->store($controllerCacheId, $res); } $debug->stopTimer('GeneratingCache'); } catch (Exception $e) { $debug->log('Exception caught, aborting cache generation', ezcLog::DEBUG); if ($isCacheEnabled) { $cache->abortCacheGeneration(); } throw $e; } } // Add debug infos to output if debug is enabled $debug->stopTimer('GeneratingRestResult'); if (ezpRestDebug::isDebugEnabled()) { $res->variables['debug'] = $debug->getReport(); } return $res; }
// Specify any number of attributes to identify the cache item you want // to store. This attributes can be used later to perform operations // on a set of cache items, that share a common attribute. $attributes = array('node' => 2, 'area' => 'admin', 'lang' => 'en-GB'); // This function is not part of the Cache package. You have to define // unique IDs for your cache items yourself. $id = getUniqueId(); // Initialize the data variable you want to restore $data = ''; // Check if data is available in the cache. The restore method returns // the cached data, if available, or bool false. if (($data = $cache->restore($id, $attributes)) === false) { // The cache item we tried to restore does not exist, so we have to // generate the data. $data = array('This is some data', 'and some more data.'); // For testing we echo something here... echo "No cache data found. Generated some.\n" . var_export($data, true) . "\n"; // Now we store the data in the cache. It will be available through // restore, next time the code is reached $cache->store($id, $data, $attributes); } else { // We found cache data. Let's echo the information. echo "Cache data found.\n" . var_export($data, true) . "\n"; } // In some other place you can access the second defined cache. $cache = ezcCacheManager::getCache('template'); // Here we are removing cache items. We do not specify an ID (which would // have meant to delete 1 specific cache item), but only an array of // attributes. This will result in all cache items to be deleted, that // have this attribute assigned. $cache->delete(null, array('node' => 5));
<?php require 'ezc-setup.php'; @mkdir('/tmp/temp-location'); ezcCacheManager::createCache('identifier', '/tmp/temp-location', 'ezcCacheStorageFileEvalArray', array('ttl' => 30)); $cache = ezcCacheManager::getCache('identifier'); $myId = 'unique_id_1'; if (($data = $cache->restore($myId)) === false) { $data = "Plain cache stored on " . date('Y-m-d, H:i:s'); $cache->store($myId, $data); } echo $data;
<?php require_once 'tutorial_autoload.php'; $optionsPlain = array('ttl' => 30); $optionsArray = array('ttl' => 45); ezcCacheManager::createCache('plain', '/tmp/cache/plain', 'ezcCacheStorageFilePlain', $optionsPlain); ezcCacheManager::createCache('array', '/tmp/cache/array', 'ezcCacheStorageFileArray', $optionsArray); $myId = 'unique_id_2'; $cache = ezcCacheManager::getCache('plain'); if (($plainData = $cache->restore($myId)) === false) { $plainData = "Plain cache stored on " . date('Y-m-d, H:m:s'); $cache->store($myId, $plainData); sleep(2); } echo "Plain cache data:\n"; var_dump($plainData); $cache = ezcCacheManager::getCache('array'); if (($arrayData = $cache->restore($myId)) === false) { $arrayData = array($plainData, "Array cache stored on " . date('Y-m-d, H:m:s'), true, 23); $cache->store($myId, $arrayData); } echo "Array cache data:\n"; var_dump($arrayData);
public function testCacheManagerLocationEmpty() { $options = array('ttl' => 10); ezcCacheManager::createCache('cache', null, 'ezcCacheStorageApcPlain', $options); $storage = ezcCacheManager::getCache('cache'); $storage->reset(); $storage->store('key', 'data'); $this->assertEquals('data', $storage->restore('key')); }
public function testCacheManagerLocationEmpty() { $options = array('ttl' => 10); ezcCacheManager::createCache('memory', null, 'ezcCacheStorageFileApcArray', $options); try { $storage = ezcCacheManager::getCache('memory'); $this->fail("Expected exception was not thrown"); } catch (ezcBaseFilePermissionException $e) { $this->assertEquals("The file '/' can not be opened for writing. (Cache location is not a directory.)", $e->getMessage()); } }
<?php require_once 'tutorial_autoload.php'; $options = array('ttl' => 30); ezcCacheManager::createCache('apc', 'apc', 'ezcCacheStorageApcPlain', $options); $myId = 'unique_id_1'; $mySecondId = 'id_2'; $cache = ezcCacheManager::getCache('apc'); if (($dataOfFirstItem = $cache->restore($myId)) === false) { $dataOfFirstItem = "Plain cache stored on " . date('Y-m-d, H:i:s'); $cache->store($myId, $dataOfFirstItem); } if (($dataOfSecondItem = $cache->restore($mySecondId)) === false) { $dataOfSecondItem = "Plain cache 2 stored on " . date('Y-m-d, H:i:s'); $cache->store($mySecondId, $dataOfSecondItem); } var_dump($dataOfFirstItem, $dataOfSecondItem);
<?php require_once 'tutorial_autoload.php'; $options = array('ttl' => 30); ezcCacheManager::createCache('simple', '/tmp/cache/plain', 'ezcCacheStorageFilePlain', $options); $myId = 'unique_id_1'; $mySecondId = 'id_2'; $cache = ezcCacheManager::getCache('simple'); if (($dataOfFirstItem = $cache->restore($myId)) === false) { $dataOfFirstItem = "Plain cache stored on " . date('Y-m-d, H:i:s'); $cache->store($myId, $dataOfFirstItem); } if (($dataOfSecondItem = $cache->restore($mySecondId)) === false) { $dataOfSecondItem = "Plain cache 2 stored on " . date('Y-m-d, H:i:s'); $cache->store($mySecondId, $dataOfSecondItem); } var_dump($dataOfFirstItem, $dataOfSecondItem);
<?php require_once 'tutorial_autoload.php'; class myCustomConfigurator implements ezcCacheStackConfigurator { public static function configure(ezcCacheStack $stack) { // ... create your storages here or fetch from manager... $stack->pushStorage(new ezcCacheStackStorageConfiguration('file', $fileStorage, 1000000, 0.5)); $stack->pushStorage(new ezcCacheStackStorageConfiguration('apc', $apcStorage, 1000, 0.3)); } } $stackOptions = array('bubbleUpOnRestore' => true, 'configurator' => 'myCustomConfigurator'); $stack = new ezcCacheStack('stack'); ezcCacheManager::createCache('stack', 'stack', 'ezcCacheStack', $stackOptions); // ... somewhere else... $stack = ezcCacheManager::getCache('stack');