sfViewCacheManager.class.php 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908
  1. <?php
  2. /*
  3. * This file is part of the symfony package.
  4. * (c) 2004-2006 Fabien Potencier <fabien.potencier@symfony-project.com>
  5. *
  6. * For the full copyright and license information, please view the LICENSE
  7. * file that was distributed with this source code.
  8. */
  9. /**
  10. * Cache class to cache the HTML results for actions and templates.
  11. *
  12. * This class uses a sfCache instance implementation to store cache.
  13. *
  14. * To disable all caching, you can set the [sf_cache] constant to false.
  15. *
  16. * @package symfony
  17. * @subpackage view
  18. * @author Fabien Potencier <fabien.potencier@symfony-project.com>
  19. * @version SVN: $Id: sfViewCacheManager.class.php 19850 2009-07-03 14:58:22Z FabianLange $
  20. */
  21. class sfViewCacheManager
  22. {
  23. protected
  24. $cache = null,
  25. $cacheConfig = array(),
  26. $context = null,
  27. $dispatcher = null,
  28. $controller = null,
  29. $routing = null,
  30. $loaded = array();
  31. /**
  32. * Class constructor.
  33. *
  34. * @see initialize()
  35. */
  36. public function __construct($context, sfCache $cache)
  37. {
  38. $this->initialize($context, $cache);
  39. }
  40. /**
  41. * Initializes the cache manager.
  42. *
  43. * @param sfContext $context Current application context
  44. * @param sfCache $cache An sfCache instance
  45. */
  46. public function initialize($context, sfCache $cache)
  47. {
  48. $this->context = $context;
  49. $this->dispatcher = $context->getEventDispatcher();
  50. $this->controller = $context->getController();
  51. // empty configuration
  52. $this->cacheConfig = array();
  53. // cache instance
  54. $this->cache = $cache;
  55. // routing instance
  56. $this->routing = $context->getRouting();
  57. }
  58. /**
  59. * Retrieves the current cache context.
  60. *
  61. * @return sfContext The sfContext instance
  62. */
  63. public function getContext()
  64. {
  65. return $this->context;
  66. }
  67. /**
  68. * Retrieves the current cache object.
  69. *
  70. * @return sfCache The current cache object
  71. */
  72. public function getCache()
  73. {
  74. return $this->cache;
  75. }
  76. /**
  77. * Generates a unique cache key for an internal URI.
  78. * This cache key can be used by any of the cache engines as a unique identifier to a cached resource
  79. *
  80. * Basically, the cache key generated for the following internal URI:
  81. * module/action?key1=value1&key2=value2
  82. * Looks like:
  83. * /localhost/all/module/action/key1/value1/key2/value2
  84. *
  85. * @param string $internalUri The internal unified resource identifier
  86. * Accepts rules formatted like 'module/action?key1=value1&key2=value2'
  87. * Does not accept rules starting with a route name, except for '@sf_cache_partial'
  88. * @param string $hostName The host name
  89. * Optional - defaults to the current host name bu default
  90. * @param string $vary The vary headers, separated by |, or "all" for all vary headers
  91. * Defaults to 'all'
  92. * @param string $contextualPrefix The contextual prefix for contextual partials.
  93. * Defaults to 'currentModule/currentAction/currentPAram1/currentvalue1'
  94. * Used only by the sfViewCacheManager::remove() method
  95. *
  96. * @return string The cache key
  97. * If some of the parameters contained wildcards (* or **), the generated key will also have wildcards
  98. */
  99. public function generateCacheKey($internalUri, $hostName = '', $vary = '', $contextualPrefix = '')
  100. {
  101. if ($callable = sfConfig::get('sf_cache_namespace_callable'))
  102. {
  103. if (!is_callable($callable))
  104. {
  105. throw new sfException(sprintf('"%s" cannot be called as a function.', var_export($callable, true)));
  106. }
  107. return call_user_func($callable, $internalUri, $hostName, $vary, $contextualPrefix);
  108. }
  109. if (strpos($internalUri, '@') === 0 && strpos($internalUri, '@sf_cache_partial') === false)
  110. {
  111. throw new sfException('A cache key cannot be generated for an internal URI using the @rule syntax');
  112. }
  113. $cacheKey = '';
  114. if ($this->isContextual($internalUri))
  115. {
  116. // Contextual partial
  117. if (!$contextualPrefix)
  118. {
  119. list($route_name, $params) = $this->controller->convertUrlStringToParameters($this->routing->getCurrentInternalUri());
  120. $cacheKey = $this->convertParametersToKey($params);
  121. }
  122. else
  123. {
  124. $cacheKey = $contextualPrefix;
  125. }
  126. list($route_name, $params) = $this->controller->convertUrlStringToParameters($internalUri);
  127. $cacheKey .= sprintf('/%s/%s/%s', $params['module'], $params['action'], isset($params['sf_cache_key']) ? $params['sf_cache_key'] : '');
  128. }
  129. else
  130. {
  131. // Regular action or non-contextual partial
  132. list($route_name, $params) = $this->controller->convertUrlStringToParameters($internalUri);
  133. if ($route_name == 'sf_cache_partial')
  134. {
  135. $cacheKey = 'sf_cache_partial/';
  136. }
  137. $cacheKey .= $this->convertParametersToKey($params);
  138. }
  139. // prefix with vary headers
  140. if (!$vary)
  141. {
  142. $varyHeaders = $this->getVary($internalUri);
  143. if ($varyHeaders)
  144. {
  145. sort($varyHeaders);
  146. $request = $this->context->getRequest();
  147. $vary = '';
  148. foreach ($varyHeaders as $header)
  149. {
  150. $vary .= $request->getHttpHeader($header).'|';
  151. }
  152. $vary = $vary;
  153. }
  154. else
  155. {
  156. $vary = 'all';
  157. }
  158. }
  159. // prefix with hostname
  160. if (!$hostName)
  161. {
  162. $request = $this->context->getRequest();
  163. $hostName = $request->getHost();
  164. }
  165. $hostName = preg_replace('/[^a-z0-9\*]/i', '_', $hostName);
  166. $hostName = strtolower(preg_replace('/_+/', '_', $hostName));
  167. $cacheKey = sprintf('/%s/%s/%s', $hostName, $vary, $cacheKey);
  168. // replace multiple /
  169. $cacheKey = preg_replace('#/+#', '/', $cacheKey);
  170. return $cacheKey;
  171. }
  172. /**
  173. * Transforms an associative array of parameters from an URI into a unique key
  174. *
  175. * @param array $params Associative array of parameters from the URI (including, at least, module and action)
  176. *
  177. * @return string Unique key
  178. */
  179. protected function convertParametersToKey($params)
  180. {
  181. if(!isset($params['module']) || !isset($params['action']))
  182. {
  183. throw new sfException('A cache key must contain both a module and an action parameter');
  184. }
  185. $module = $params['module'];
  186. unset($params['module']);
  187. $action = $params['action'];
  188. unset($params['action']);
  189. ksort($params);
  190. $cacheKey = sprintf('%s/%s', $module, $action);
  191. foreach ($params as $key => $value)
  192. {
  193. $cacheKey .= sprintf('/%s/%s', $key, $value);
  194. }
  195. return $cacheKey;
  196. }
  197. /**
  198. * Adds a cache to the manager.
  199. *
  200. * @param string $moduleName Module name
  201. * @param string $actionName Action name
  202. * @param array $options Options for the cache
  203. */
  204. public function addCache($moduleName, $actionName, $options = array())
  205. {
  206. // normalize vary headers
  207. if (isset($options['vary']))
  208. {
  209. foreach ($options['vary'] as $key => $name)
  210. {
  211. $options['vary'][$key] = strtr(strtolower($name), '_', '-');
  212. }
  213. }
  214. $options['lifeTime'] = isset($options['lifeTime']) ? $options['lifeTime'] : 0;
  215. if (!isset($this->cacheConfig[$moduleName]))
  216. {
  217. $this->cacheConfig[$moduleName] = array();
  218. }
  219. $this->cacheConfig[$moduleName][$actionName] = array(
  220. 'withLayout' => isset($options['withLayout']) ? $options['withLayout'] : false,
  221. 'lifeTime' => $options['lifeTime'],
  222. 'clientLifeTime' => isset($options['clientLifeTime']) ? $options['clientLifeTime'] : $options['lifeTime'],
  223. 'contextual' => isset($options['contextual']) ? $options['contextual'] : false,
  224. 'vary' => isset($options['vary']) ? $options['vary'] : array(),
  225. );
  226. }
  227. /**
  228. * Registers configuration options for the cache.
  229. *
  230. * @param string $moduleName Module name
  231. */
  232. public function registerConfiguration($moduleName)
  233. {
  234. if (!isset($this->loaded[$moduleName]))
  235. {
  236. require($this->context->getConfigCache()->checkConfig('modules/'.$moduleName.'/config/cache.yml'));
  237. $this->loaded[$moduleName] = true;
  238. }
  239. }
  240. /**
  241. * Retrieves the layout from the cache option list.
  242. *
  243. * @param string $internalUri Internal uniform resource identifier
  244. *
  245. * @return bool true, if have layout otherwise false
  246. */
  247. public function withLayout($internalUri)
  248. {
  249. return $this->getCacheConfig($internalUri, 'withLayout', false);
  250. }
  251. /**
  252. * Retrieves lifetime from the cache option list.
  253. *
  254. * @param string $internalUri Internal uniform resource identifier
  255. *
  256. * @return int LifeTime
  257. */
  258. public function getLifeTime($internalUri)
  259. {
  260. return $this->getCacheConfig($internalUri, 'lifeTime', 0);
  261. }
  262. /**
  263. * Retrieves client lifetime from the cache option list
  264. *
  265. * @param string $internalUri Internal uniform resource identifier
  266. *
  267. * @return int Client lifetime
  268. */
  269. public function getClientLifeTime($internalUri)
  270. {
  271. return $this->getCacheConfig($internalUri, 'clientLifeTime', 0);
  272. }
  273. /**
  274. * Retrieves contextual option from the cache option list.
  275. *
  276. * @param string $internalUri Internal uniform resource identifier
  277. *
  278. * @return boolean true, if is contextual otherwise false
  279. */
  280. public function isContextual($internalUri)
  281. {
  282. return $this->getCacheConfig($internalUri, 'contextual', false);
  283. }
  284. /**
  285. * Retrieves vary option from the cache option list.
  286. *
  287. * @param string $internalUri Internal uniform resource identifier
  288. *
  289. * @return array Vary options for the cache
  290. */
  291. public function getVary($internalUri)
  292. {
  293. return $this->getCacheConfig($internalUri, 'vary', array());
  294. }
  295. /**
  296. * Gets a config option from the cache.
  297. *
  298. * @param string $internalUri Internal uniform resource identifier
  299. * @param string $key Option name
  300. * @param string $defaultValue Default value of the option
  301. *
  302. * @return mixed Value of the option
  303. */
  304. protected function getCacheConfig($internalUri, $key, $defaultValue = null)
  305. {
  306. list($route_name, $params) = $this->controller->convertUrlStringToParameters($internalUri);
  307. $this->registerConfiguration($params['module']);
  308. $value = $defaultValue;
  309. if (isset($this->cacheConfig[$params['module']][$params['action']][$key]))
  310. {
  311. $value = $this->cacheConfig[$params['module']][$params['action']][$key];
  312. }
  313. else if (isset($this->cacheConfig[$params['module']]['DEFAULT'][$key]))
  314. {
  315. $value = $this->cacheConfig[$params['module']]['DEFAULT'][$key];
  316. }
  317. return $value;
  318. }
  319. /**
  320. * Returns true if the current content is cacheable.
  321. *
  322. * Possible break in backward compatibility: If the sf_lazy_cache_key
  323. * setting is turned on in settings.yml, this method is not used when
  324. * initially checking a partial's cacheability.
  325. *
  326. * @see sfPartialView, isActionCacheable()
  327. *
  328. * @param string $internalUri Internal uniform resource identifier
  329. *
  330. * @return bool true, if the content is cacheable otherwise false
  331. */
  332. public function isCacheable($internalUri)
  333. {
  334. if (count($_GET) || count($_POST))
  335. {
  336. return false;
  337. }
  338. list($route_name, $params) = $this->controller->convertUrlStringToParameters($internalUri);
  339. $this->registerConfiguration($params['module']);
  340. if (isset($this->cacheConfig[$params['module']][$params['action']]))
  341. {
  342. return ($this->cacheConfig[$params['module']][$params['action']]['lifeTime'] > 0);
  343. }
  344. else if (isset($this->cacheConfig[$params['module']]['DEFAULT']))
  345. {
  346. return ($this->cacheConfig[$params['module']]['DEFAULT']['lifeTime'] > 0);
  347. }
  348. return false;
  349. }
  350. /**
  351. * Returns true if the action is cacheable.
  352. *
  353. * @param string $moduleName A module name
  354. * @param string $actionName An action or partial template name
  355. *
  356. * @return boolean True if the action is cacheable
  357. *
  358. * @see isCacheable()
  359. */
  360. public function isActionCacheable($moduleName, $actionName)
  361. {
  362. if (count($_GET) || count($_POST))
  363. {
  364. return false;
  365. }
  366. $this->registerConfiguration($moduleName);
  367. if (isset($this->cacheConfig[$moduleName][$actionName]))
  368. {
  369. return $this->cacheConfig[$moduleName][$actionName]['lifeTime'] > 0;
  370. }
  371. else if (isset($this->cacheConfig[$moduleName]['DEFAULT']))
  372. {
  373. return $this->cacheConfig[$moduleName]['DEFAULT']['lifeTime'] > 0;
  374. }
  375. return false;
  376. }
  377. /**
  378. * Retrieves content in the cache.
  379. *
  380. * @param string $internalUri Internal uniform resource identifier
  381. *
  382. * @return string The content in the cache
  383. */
  384. public function get($internalUri)
  385. {
  386. // no cache or no cache set for this action
  387. if (!$this->isCacheable($internalUri) || $this->ignore())
  388. {
  389. return null;
  390. }
  391. $retval = $this->cache->get($this->generateCacheKey($internalUri));
  392. if (sfConfig::get('sf_logging_enabled'))
  393. {
  394. $this->dispatcher->notify(new sfEvent($this, 'application.log', array(sprintf('Cache for "%s" %s', $internalUri, $retval !== null ? 'exists' : 'does not exist'))));
  395. }
  396. return $retval;
  397. }
  398. /**
  399. * Returns true if there is a cache.
  400. *
  401. * @param string $internalUri Internal uniform resource identifier
  402. *
  403. * @return bool true, if there is a cache otherwise false
  404. */
  405. public function has($internalUri)
  406. {
  407. if (!$this->isCacheable($internalUri) || $this->ignore())
  408. {
  409. return null;
  410. }
  411. return $this->cache->has($this->generateCacheKey($internalUri));
  412. }
  413. /**
  414. * Ignores the cache functionality.
  415. *
  416. * @return bool true, if the cache is ignore otherwise false
  417. */
  418. protected function ignore()
  419. {
  420. // ignore cache parameter? (only available in debug mode)
  421. if (sfConfig::get('sf_debug') && $this->context->getRequest()->getAttribute('_sf_ignore_cache'))
  422. {
  423. if (sfConfig::get('sf_logging_enabled'))
  424. {
  425. $this->dispatcher->notify(new sfEvent($this, 'application.log', array('Discard cache')));
  426. }
  427. return true;
  428. }
  429. return false;
  430. }
  431. /**
  432. * Sets the cache content.
  433. *
  434. * @param string $data Data to put in the cache
  435. * @param string $internalUri Internal uniform resource identifier
  436. *
  437. * @return boolean true, if the data get set successfully otherwise false
  438. */
  439. public function set($data, $internalUri)
  440. {
  441. if (!$this->isCacheable($internalUri))
  442. {
  443. return false;
  444. }
  445. try
  446. {
  447. $ret = $this->cache->set($this->generateCacheKey($internalUri), $data, $this->getLifeTime($internalUri));
  448. }
  449. catch (Exception $e)
  450. {
  451. return false;
  452. }
  453. if (sfConfig::get('sf_logging_enabled'))
  454. {
  455. $this->dispatcher->notify(new sfEvent($this, 'application.log', array(sprintf('Save cache for "%s"', $internalUri))));
  456. }
  457. return true;
  458. }
  459. /**
  460. * Removes the content in the cache.
  461. *
  462. * @param string $internalUri Internal uniform resource identifier
  463. * @param string $hostName The host name
  464. * @param string $vary The vary headers, separated by |, or "all" for all vary headers
  465. * @param string $contextualPrefix The removal prefix for contextual partials. Defaults to '**' (all actions, all params)
  466. *
  467. * @return bool true, if the remove happened, false otherwise
  468. */
  469. public function remove($internalUri, $hostName = '', $vary = '', $contextualPrefix = '**')
  470. {
  471. if (sfConfig::get('sf_logging_enabled'))
  472. {
  473. $this->dispatcher->notify(new sfEvent($this, 'application.log', array(sprintf('Remove cache for "%s"', $internalUri))));
  474. }
  475. $cacheKey = $this->generateCacheKey($internalUri, $hostName, $vary, $contextualPrefix);
  476. if(strpos($cacheKey, '*'))
  477. {
  478. return $this->cache->removePattern($cacheKey);
  479. }
  480. elseif ($this->cache->has($cacheKey))
  481. {
  482. return $this->cache->remove($cacheKey);
  483. }
  484. }
  485. /**
  486. * Retrieves the last modified time.
  487. *
  488. * @param string $internalUri Internal uniform resource identifier
  489. *
  490. * @return int The last modified datetime
  491. */
  492. public function getLastModified($internalUri)
  493. {
  494. if (!$this->isCacheable($internalUri))
  495. {
  496. return 0;
  497. }
  498. return $this->cache->getLastModified($this->generateCacheKey($internalUri));
  499. }
  500. /**
  501. * Retrieves the timeout.
  502. *
  503. * @param string $internalUri Internal uniform resource identifier
  504. *
  505. * @return int The timeout datetime
  506. */
  507. public function getTimeout($internalUri)
  508. {
  509. if (!$this->isCacheable($internalUri))
  510. {
  511. return 0;
  512. }
  513. return $this->cache->getTimeout($this->generateCacheKey($internalUri));
  514. }
  515. /**
  516. * Starts the fragment cache.
  517. *
  518. * @param string $name Unique fragment name
  519. * @param string $lifeTime Life time for the cache
  520. * @param string $clientLifeTime Client life time for the cache
  521. * @param array $vary Vary options for the cache
  522. *
  523. * @return bool true, if success otherwise false
  524. */
  525. public function start($name, $lifeTime, $clientLifeTime = null, $vary = array())
  526. {
  527. $internalUri = $this->routing->getCurrentInternalUri();
  528. if (!$clientLifeTime)
  529. {
  530. $clientLifeTime = $lifeTime;
  531. }
  532. // add cache config to cache manager
  533. list($route_name, $params) = $this->controller->convertUrlStringToParameters($internalUri);
  534. $this->addCache($params['module'], $params['action'], array('withLayout' => false, 'lifeTime' => $lifeTime, 'clientLifeTime' => $clientLifeTime, 'vary' => $vary));
  535. // get data from cache if available
  536. $data = $this->get($internalUri.(strpos($internalUri, '?') ? '&' : '?').'_sf_cache_key='.$name);
  537. if ($data !== null)
  538. {
  539. return $data;
  540. }
  541. else
  542. {
  543. ob_start();
  544. ob_implicit_flush(0);
  545. return null;
  546. }
  547. }
  548. /**
  549. * Stops the fragment cache.
  550. *
  551. * @param string $name Unique fragment name
  552. *
  553. * @return bool true, if success otherwise false
  554. */
  555. public function stop($name)
  556. {
  557. $data = ob_get_clean();
  558. // save content to cache
  559. $internalUri = $this->routing->getCurrentInternalUri();
  560. try
  561. {
  562. $this->set($data, $internalUri.(strpos($internalUri, '?') ? '&' : '?').'_sf_cache_key='.$name);
  563. }
  564. catch (Exception $e)
  565. {
  566. }
  567. return $data;
  568. }
  569. /**
  570. * Computes the cache key based on the passed parameters.
  571. *
  572. * @param array $parameters An array of parameters
  573. */
  574. public function computeCacheKey(array $parameters)
  575. {
  576. if (isset($parameters['sf_cache_key']))
  577. {
  578. return $parameters['sf_cache_key'];
  579. }
  580. if (sfConfig::get('sf_logging_enabled'))
  581. {
  582. $this->dispatcher->notify(new sfEvent($this, 'application.log', array('Generate cache key')));
  583. }
  584. return md5(serialize($parameters));
  585. }
  586. /**
  587. * Checks that the supplied parameters include a cache key.
  588. *
  589. * If no 'sf_cache_key' parameter is present one is added to the array as
  590. * it is passed by reference.
  591. *
  592. * @param array $parameters An array of parameters
  593. *
  594. * @return string The cache key
  595. */
  596. public function checkCacheKey(array & $parameters)
  597. {
  598. $parameters['sf_cache_key'] = $this->computeCacheKey($parameters);
  599. return $parameters['sf_cache_key'];
  600. }
  601. /**
  602. * Computes a partial internal URI.
  603. *
  604. * @param string $module The module name
  605. * @param string $action The action name
  606. * @param string $cacheKey The cache key
  607. *
  608. * @return string The internal URI
  609. */
  610. public function getPartialUri($module, $action, $cacheKey)
  611. {
  612. return sprintf('@sf_cache_partial?module=%s&action=%s&sf_cache_key=%s', $module, $action, $cacheKey);
  613. }
  614. /**
  615. * Returns whether a partial template is in the cache.
  616. *
  617. * @param string $module The module name
  618. * @param string $action The action name
  619. * @param string $cacheKey The cache key
  620. *
  621. * @return bool true if a partial is in the cache, false otherwise
  622. */
  623. public function hasPartialCache($module, $action, $cacheKey)
  624. {
  625. return $this->has($this->getPartialUri($module, $action, $cacheKey));
  626. }
  627. /**
  628. * Gets a partial template from the cache.
  629. *
  630. * @param string $module The module name
  631. * @param string $action The action name
  632. * @param string $cacheKey The cache key
  633. *
  634. * @return string The cache content
  635. */
  636. public function getPartialCache($module, $action, $cacheKey)
  637. {
  638. $uri = $this->getPartialUri($module, $action, $cacheKey);
  639. if (!$this->isCacheable($uri))
  640. {
  641. return null;
  642. }
  643. // retrieve content from cache
  644. $cache = $this->get($uri);
  645. if (is_null($cache))
  646. {
  647. return null;
  648. }
  649. $cache = unserialize($cache);
  650. $content = $cache['content'];
  651. $this->context->getResponse()->merge($cache['response']);
  652. if (sfConfig::get('sf_web_debug'))
  653. {
  654. $content = $this->dispatcher->filter(new sfEvent($this, 'view.cache.filter_content', array('response' => $this->context->getResponse(), 'uri' => $uri, 'new' => false)), $content)->getReturnValue();
  655. }
  656. return $content;
  657. }
  658. /**
  659. * Sets an action template in the cache.
  660. *
  661. * @param string $module The module name
  662. * @param string $action The action name
  663. * @param string $cacheKey The cache key
  664. * @param string $content The content to cache
  665. *
  666. * @return string The cached content
  667. */
  668. public function setPartialCache($module, $action, $cacheKey, $content)
  669. {
  670. $uri = $this->getPartialUri($module, $action, $cacheKey);
  671. if (!$this->isCacheable($uri))
  672. {
  673. return $content;
  674. }
  675. $saved = $this->set(serialize(array('content' => $content, 'response' => $this->context->getResponse())), $uri);
  676. if ($saved && sfConfig::get('sf_web_debug'))
  677. {
  678. $content = $this->dispatcher->filter(new sfEvent($this, 'view.cache.filter_content', array('response' => $this->context->getResponse(), 'uri' => $uri, 'new' => true)), $content)->getReturnValue();
  679. }
  680. return $content;
  681. }
  682. /**
  683. * Returns whether an action template is in the cache.
  684. *
  685. * @param string $uri The internal URI
  686. *
  687. * @return bool true if an action is in the cache, false otherwise
  688. */
  689. public function hasActionCache($uri)
  690. {
  691. return $this->has($uri) && !$this->withLayout($uri);
  692. }
  693. /**
  694. * Gets an action template from the cache.
  695. *
  696. * @param string $uri The internal URI
  697. *
  698. * @return array An array composed of the cached content and the view attribute holder
  699. */
  700. public function getActionCache($uri)
  701. {
  702. if (!$this->isCacheable($uri) || $this->withLayout($uri))
  703. {
  704. return null;
  705. }
  706. // retrieve content from cache
  707. $cache = $this->get($uri);
  708. if (is_null($cache))
  709. {
  710. return null;
  711. }
  712. $cache = unserialize($cache);
  713. $content = $cache['content'];
  714. $cache['response']->setEventDispatcher($this->dispatcher);
  715. $this->context->getResponse()->copyProperties($cache['response']);
  716. if (sfConfig::get('sf_web_debug'))
  717. {
  718. $content = $this->dispatcher->filter(new sfEvent($this, 'view.cache.filter_content', array('response' => $this->context->getResponse(), 'uri' => $uri, 'new' => false)), $content)->getReturnValue();
  719. }
  720. return array($content, $cache['decoratorTemplate']);
  721. }
  722. /**
  723. * Sets an action template in the cache.
  724. *
  725. * @param string $uri The internal URI
  726. * @param string $content The content to cache
  727. * @param string $decoratorTemplate The view attribute holder to cache
  728. *
  729. * @return string The cached content
  730. */
  731. public function setActionCache($uri, $content, $decoratorTemplate)
  732. {
  733. if (!$this->isCacheable($uri) || $this->withLayout($uri))
  734. {
  735. return $content;
  736. }
  737. $saved = $this->set(serialize(array('content' => $content, 'decoratorTemplate' => $decoratorTemplate, 'response' => $this->context->getResponse())), $uri);
  738. if ($saved && sfConfig::get('sf_web_debug'))
  739. {
  740. $content = $this->dispatcher->filter(new sfEvent($this, 'view.cache.filter_content', array('response' => $this->context->getResponse(), 'uri' => $uri, 'new' => true)), $content)->getReturnValue();
  741. }
  742. return $content;
  743. }
  744. /**
  745. * Sets a page in the cache.
  746. *
  747. * @param string $uri The internal URI
  748. */
  749. public function setPageCache($uri)
  750. {
  751. if (sfView::RENDER_CLIENT != $this->controller->getRenderMode())
  752. {
  753. return;
  754. }
  755. // save content in cache
  756. $saved = $this->set(serialize($this->context->getResponse()), $uri);
  757. if ($saved && sfConfig::get('sf_web_debug'))
  758. {
  759. $content = $this->dispatcher->filter(new sfEvent($this, 'view.cache.filter_content', array('response' => $this->context->getResponse(), 'uri' => $uri, 'new' => true)), $this->context->getResponse()->getContent())->getReturnValue();
  760. $this->context->getResponse()->setContent($content);
  761. }
  762. }
  763. /**
  764. * Gets a page from the cache.
  765. *
  766. * @param string $uri The internal URI
  767. *
  768. * @return string The cached page
  769. */
  770. public function getPageCache($uri)
  771. {
  772. $retval = $this->get($uri);
  773. if (is_null($retval))
  774. {
  775. return false;
  776. }
  777. $cachedResponse = unserialize($retval);
  778. $cachedResponse->setEventDispatcher($this->dispatcher);
  779. if (sfView::RENDER_VAR == $this->controller->getRenderMode())
  780. {
  781. $this->controller->getActionStack()->getLastEntry()->setPresentation($cachedResponse->getContent());
  782. $this->response->setContent('');
  783. }
  784. else
  785. {
  786. $this->context->setResponse($cachedResponse);
  787. if (sfConfig::get('sf_web_debug'))
  788. {
  789. $content = $this->dispatcher->filter(new sfEvent($this, 'view.cache.filter_content', array('response' => $this->context->getResponse(), 'uri' => $uri, 'new' => false)), $this->context->getResponse()->getContent())->getReturnValue();
  790. $this->context->getResponse()->setContent($content);
  791. }
  792. }
  793. return true;
  794. }
  795. }