CacheHelper.php 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  5. *
  6. * Licensed under The MIT License
  7. * For full copyright and license information, please see the LICENSE.txt
  8. * Redistributions of files must retain the above copyright notice.
  9. *
  10. * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  11. * @link http://cakephp.org CakePHP(tm) Project
  12. * @package Cake.View.Helper
  13. * @since CakePHP(tm) v 1.0.0.2277
  14. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  15. */
  16. App::uses('AppHelper', 'View/Helper');
  17. /**
  18. * CacheHelper helps create full page view caching.
  19. *
  20. * When using CacheHelper you don't call any of its methods, they are all automatically
  21. * called by View, and use the $cacheAction settings set in the controller.
  22. *
  23. * @package Cake.View.Helper
  24. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/cache.html
  25. * @deprecated This class will be removed in 3.0. You should use a separate response cache
  26. * like Varnish instead.
  27. */
  28. class CacheHelper extends AppHelper {
  29. /**
  30. * Array of strings replaced in cached views.
  31. * The strings are found between `<!--nocache--><!--/nocache-->` in views
  32. *
  33. * @var array
  34. */
  35. protected $_replace = array();
  36. /**
  37. * Array of string that are replace with there var replace above.
  38. * The strings are any content inside `<!--nocache--><!--/nocache-->` and includes the tags in views
  39. *
  40. * @var array
  41. */
  42. protected $_match = array();
  43. /**
  44. * Counter used for counting nocache section tags.
  45. *
  46. * @var int
  47. */
  48. protected $_counter = 0;
  49. /**
  50. * Is CacheHelper enabled? should files + output be parsed.
  51. *
  52. * @return bool
  53. */
  54. protected function _enabled() {
  55. return $this->_View->cacheAction && (Configure::read('Cache.check') === true);
  56. }
  57. /**
  58. * Parses the view file and stores content for cache file building.
  59. *
  60. * @param string $viewFile View file name.
  61. * @param string $output The output for the file.
  62. * @return string Updated content.
  63. */
  64. public function afterRenderFile($viewFile, $output) {
  65. if ($this->_enabled()) {
  66. return $this->_parseContent($viewFile, $output);
  67. }
  68. }
  69. /**
  70. * Parses the layout file and stores content for cache file building.
  71. *
  72. * @param string $layoutFile Layout file name.
  73. * @return void
  74. */
  75. public function afterLayout($layoutFile) {
  76. if ($this->_enabled()) {
  77. $this->_View->output = $this->cache($layoutFile, $this->_View->output);
  78. }
  79. $this->_View->output = preg_replace('/<!--\/?nocache-->/', '', $this->_View->output);
  80. }
  81. /**
  82. * Parse a file + output. Matches nocache tags between the current output and the current file
  83. * stores a reference of the file, so the generated can be swapped back with the file contents when
  84. * writing the cache file.
  85. *
  86. * @param string $file The filename to process.
  87. * @param string $out The output for the file.
  88. * @return string Updated content.
  89. */
  90. protected function _parseContent($file, $out) {
  91. $out = preg_replace_callback('/<!--nocache-->/', array($this, '_replaceSection'), $out);
  92. $this->_parseFile($file, $out);
  93. return $out;
  94. }
  95. /**
  96. * Main method used to cache a view
  97. *
  98. * @param string $file File to cache
  99. * @param string $out output to cache
  100. * @return string view output
  101. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/cache.html
  102. * @throws Exception If debug mode is enabled and writing to cache file fails.
  103. */
  104. public function cache($file, $out) {
  105. $cacheTime = 0;
  106. $useCallbacks = false;
  107. $cacheAction = $this->_View->cacheAction;
  108. if (is_array($cacheAction)) {
  109. $keys = array_keys($cacheAction);
  110. $index = null;
  111. foreach ($keys as $action) {
  112. if ($action === $this->request->params['action']) {
  113. $index = $action;
  114. break;
  115. }
  116. }
  117. if (!isset($index) && $this->request->params['action'] === 'index') {
  118. $index = 'index';
  119. }
  120. $options = $cacheAction;
  121. if (isset($cacheAction[$index])) {
  122. if (is_array($cacheAction[$index])) {
  123. $options = $cacheAction[$index] + array('duration' => 0, 'callbacks' => false);
  124. } else {
  125. $cacheTime = $cacheAction[$index];
  126. }
  127. }
  128. if (isset($options['duration'])) {
  129. $cacheTime = $options['duration'];
  130. }
  131. if (isset($options['callbacks'])) {
  132. $useCallbacks = $options['callbacks'];
  133. }
  134. } else {
  135. $cacheTime = $cacheAction;
  136. }
  137. if ($cacheTime && $cacheTime > 0) {
  138. $cached = $this->_parseOutput($out);
  139. try {
  140. $this->_writeFile($cached, $cacheTime, $useCallbacks);
  141. } catch (Exception $e) {
  142. if (Configure::read('debug')) {
  143. throw $e;
  144. }
  145. $message = __d(
  146. 'cake_dev',
  147. 'Unable to write view cache file: "%s" for "%s"',
  148. $e->getMessage(),
  149. $this->request->here
  150. );
  151. $this->log($message, 'error');
  152. }
  153. $out = $this->_stripTags($out);
  154. }
  155. return $out;
  156. }
  157. /**
  158. * Parse file searching for no cache tags
  159. *
  160. * @param string $file The filename that needs to be parsed.
  161. * @param string $cache The cached content
  162. * @return void
  163. */
  164. protected function _parseFile($file, $cache) {
  165. if (is_file($file)) {
  166. $file = file_get_contents($file);
  167. } elseif ($file = fileExistsInPath($file)) {
  168. $file = file_get_contents($file);
  169. }
  170. preg_match_all('/(<!--nocache:\d{3}-->(?<=<!--nocache:\d{3}-->)[\\s\\S]*?(?=<!--\/nocache-->)<!--\/nocache-->)/i', $cache, $outputResult, PREG_PATTERN_ORDER);
  171. preg_match_all('/(?<=<!--nocache-->)([\\s\\S]*?)(?=<!--\/nocache-->)/i', $file, $fileResult, PREG_PATTERN_ORDER);
  172. $fileResult = $fileResult[0];
  173. $outputResult = $outputResult[0];
  174. if (!empty($this->_replace)) {
  175. foreach ($outputResult as $i => $element) {
  176. $index = array_search($element, $this->_match);
  177. if ($index !== false) {
  178. unset($outputResult[$i]);
  179. }
  180. }
  181. $outputResult = array_values($outputResult);
  182. }
  183. if (!empty($fileResult)) {
  184. $i = 0;
  185. foreach ($fileResult as $cacheBlock) {
  186. if (isset($outputResult[$i])) {
  187. $this->_replace[] = $cacheBlock;
  188. $this->_match[] = $outputResult[$i];
  189. }
  190. $i++;
  191. }
  192. }
  193. }
  194. /**
  195. * Munges the output from a view with cache tags, and numbers the sections.
  196. * This helps solve issues with empty/duplicate content.
  197. *
  198. * @return string The content with cake:nocache tags replaced.
  199. */
  200. protected function _replaceSection() {
  201. $this->_counter += 1;
  202. return sprintf('<!--nocache:%03d-->', $this->_counter);
  203. }
  204. /**
  205. * Strip cake:nocache tags from a string. Since View::render()
  206. * only removes un-numbered nocache tags, remove all the numbered ones.
  207. * This is the complement to _replaceSection.
  208. *
  209. * @param string $content String to remove tags from.
  210. * @return string String with tags removed.
  211. */
  212. protected function _stripTags($content) {
  213. return preg_replace('#<!--/?nocache(\:\d{3})?-->#', '', $content);
  214. }
  215. /**
  216. * Parse the output and replace cache tags
  217. *
  218. * @param string $cache Output to replace content in.
  219. * @return string with all replacements made to <!--nocache--><!--nocache-->
  220. */
  221. protected function _parseOutput($cache) {
  222. $count = 0;
  223. if (!empty($this->_match)) {
  224. foreach ($this->_match as $found) {
  225. $original = $cache;
  226. $length = strlen($found);
  227. $position = 0;
  228. for ($i = 1; $i <= 1; $i++) {
  229. $position = strpos($cache, $found, $position);
  230. if ($position !== false) {
  231. $cache = substr($original, 0, $position);
  232. $cache .= $this->_replace[$count];
  233. $cache .= substr($original, $position + $length);
  234. } else {
  235. break;
  236. }
  237. }
  238. $count++;
  239. }
  240. return $cache;
  241. }
  242. return $cache;
  243. }
  244. /**
  245. * Write a cached version of the file
  246. *
  247. * @param string $content view content to write to a cache file.
  248. * @param string $timestamp Duration to set for cache file.
  249. * @param bool $useCallbacks Whether to include statements in cached file which
  250. * run callbacks.
  251. * @return bool success of caching view.
  252. */
  253. protected function _writeFile($content, $timestamp, $useCallbacks = false) {
  254. $now = time();
  255. if (is_numeric($timestamp)) {
  256. $cacheTime = $now + $timestamp;
  257. } else {
  258. $cacheTime = strtotime($timestamp, $now);
  259. }
  260. $path = $this->request->here();
  261. if ($path === '/') {
  262. $path = 'home';
  263. }
  264. $prefix = Configure::read('Cache.viewPrefix');
  265. if ($prefix) {
  266. $path = $prefix . '_' . $path;
  267. }
  268. $cache = strtolower(Inflector::slug($path));
  269. if (empty($cache)) {
  270. return;
  271. }
  272. $cache = $cache . '.php';
  273. $file = '<!--cachetime:' . $cacheTime . '--><?php';
  274. if (empty($this->_View->plugin)) {
  275. $file .= "
  276. App::uses('{$this->_View->name}Controller', 'Controller');
  277. ";
  278. } else {
  279. $file .= "
  280. App::uses('{$this->_View->plugin}AppController', '{$this->_View->plugin}.Controller');
  281. App::uses('{$this->_View->name}Controller', '{$this->_View->plugin}.Controller');
  282. ";
  283. }
  284. $file .= '
  285. $request = unserialize(base64_decode(\'' . base64_encode(serialize($this->request)) . '\'));
  286. $response->type(\'' . $this->_View->response->type() . '\');
  287. $controller = new ' . $this->_View->name . 'Controller($request, $response);
  288. $controller->plugin = $this->plugin = \'' . $this->_View->plugin . '\';
  289. $controller->helpers = $this->helpers = unserialize(base64_decode(\'' . base64_encode(serialize($this->_View->helpers)) . '\'));
  290. $controller->layout = $this->layout = \'' . $this->_View->layout . '\';
  291. $controller->theme = $this->theme = \'' . $this->_View->theme . '\';
  292. $controller->viewVars = unserialize(base64_decode(\'' . base64_encode(serialize($this->_View->viewVars)) . '\'));
  293. Router::setRequestInfo($controller->request);
  294. $this->request = $request;';
  295. if ($useCallbacks) {
  296. $file .= '
  297. $controller->constructClasses();
  298. $controller->startupProcess();';
  299. }
  300. $file .= '
  301. $this->viewVars = $controller->viewVars;
  302. $this->loadHelpers();
  303. extract($this->viewVars, EXTR_SKIP);
  304. ?>';
  305. $content = preg_replace("/(<\\?xml)/", "<?php echo '$1'; ?>", $content);
  306. $file .= $content;
  307. return cache('views' . DS . $cache, $file, $timestamp);
  308. }
  309. }