CacheHelper.php 9.4 KB

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