CacheHelper.php 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  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-2011, 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-2011, 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. * Parses the view file and stores content for cache file building.
  52. *
  53. * @param string $viewFile
  54. * @return void
  55. */
  56. public function afterRender($viewFile) {
  57. $caching = (($this->_View->cacheAction != false)) && (Configure::read('Cache.check') === true);
  58. if ($caching) {
  59. $this->_View->output = $this->cache($viewFile, $this->_View->output, false);
  60. }
  61. }
  62. /**
  63. * Parses the layout file and stores content for cache file building.
  64. *
  65. * @param string $layoutFile
  66. * @return void
  67. */
  68. public function afterLayout($layoutFile) {
  69. $caching = (($this->_View->cacheAction != false)) && (Configure::read('Cache.check') === true);
  70. if ($caching) {
  71. $this->_View->output = $this->cache($layoutFile, $this->_View->output, true);
  72. }
  73. $this->_View->output = preg_replace('/<!--\/?nocache-->/', '', $this->_View->output);
  74. }
  75. /**
  76. * Main method used to cache a view
  77. *
  78. * @param string $file File to cache
  79. * @param string $out output to cache
  80. * @param boolean $cache Whether or not a cache file should be written.
  81. * @return string view ouput
  82. */
  83. public function cache($file, $out, $cache = false) {
  84. $cacheTime = 0;
  85. $useCallbacks = false;
  86. $cacheAction = $this->_View->cacheAction;
  87. if (is_array($cacheAction)) {
  88. $keys = array_keys($cacheAction);
  89. $index = null;
  90. foreach ($keys as $action) {
  91. if ($action == $this->request->params['action']) {
  92. $index = $action;
  93. break;
  94. }
  95. }
  96. if (!isset($index) && $this->request->params['action'] == 'index') {
  97. $index = 'index';
  98. }
  99. $options = $cacheAction;
  100. if (isset($cacheAction[$index])) {
  101. if (is_array($cacheAction[$index])) {
  102. $options = array_merge(array('duration' => 0, 'callbacks' => false), $cacheAction[$index]);
  103. } else {
  104. $cacheTime = $cacheAction[$index];
  105. }
  106. }
  107. if (isset($options['duration'])) {
  108. $cacheTime = $options['duration'];
  109. }
  110. if (isset($options['callbacks'])) {
  111. $useCallbacks = $options['callbacks'];
  112. }
  113. } else {
  114. $cacheTime = $cacheAction;
  115. }
  116. if ($cacheTime != '' && $cacheTime > 0) {
  117. $out = preg_replace_callback('/<!--nocache-->/', array($this, '_replaceSection'), $out);
  118. $this->_parseFile($file, $out);
  119. if ($cache === true) {
  120. $cached = $this->_parseOutput($out);
  121. $this->_writeFile($cached, $cacheTime, $useCallbacks);
  122. $out = $this->_stripTags($out);
  123. }
  124. return $out;
  125. } else {
  126. return $out;
  127. }
  128. }
  129. /**
  130. * Parse file searching for no cache tags
  131. *
  132. * @param string $file The filename that needs to be parsed.
  133. * @param string $cache The cached content
  134. * @return void
  135. */
  136. protected function _parseFile($file, $cache) {
  137. if (is_file($file)) {
  138. $file = file_get_contents($file);
  139. } elseif ($file = fileExistsInPath($file)) {
  140. $file = file_get_contents($file);
  141. }
  142. preg_match_all('/(<!--nocache:\d{3}-->(?<=<!--nocache:\d{3}-->)[\\s\\S]*?(?=<!--\/nocache-->)<!--\/nocache-->)/i', $cache, $outputResult, PREG_PATTERN_ORDER);
  143. preg_match_all('/(?<=<!--nocache-->)([\\s\\S]*?)(?=<!--\/nocache-->)/i', $file, $fileResult, PREG_PATTERN_ORDER);
  144. $fileResult = $fileResult[0];
  145. $outputResult = $outputResult[0];
  146. if (!empty($this->_replace)) {
  147. foreach ($outputResult as $i => $element) {
  148. $index = array_search($element, $this->_match);
  149. if ($index !== false) {
  150. unset($outputResult[$i]);
  151. }
  152. }
  153. $outputResult = array_values($outputResult);
  154. }
  155. if (!empty($fileResult)) {
  156. $i = 0;
  157. foreach ($fileResult as $cacheBlock) {
  158. if (isset($outputResult[$i])) {
  159. $this->_replace[] = $cacheBlock;
  160. $this->_match[] = $outputResult[$i];
  161. }
  162. $i++;
  163. }
  164. }
  165. }
  166. /**
  167. * Munges the output from a view with cache tags, and numbers the sections.
  168. * This helps solve issues with empty/duplicate content.
  169. *
  170. * @return string The content with cake:nocache tags replaced.
  171. */
  172. protected function _replaceSection() {
  173. $this->_counter += 1;
  174. return sprintf('<!--nocache:%03d-->', $this->_counter);
  175. }
  176. /**
  177. * Strip cake:nocache tags from a string. Since View::render()
  178. * only removes un-numbered nocache tags, remove all the numbered ones.
  179. * This is the complement to _replaceSection.
  180. *
  181. * @param string $content String to remove tags from.
  182. * @return string String with tags removed.
  183. */
  184. protected function _stripTags($content) {
  185. return preg_replace('#<!--/?nocache(\:\d{3})?-->#', '', $content);
  186. }
  187. /**
  188. * Parse the output and replace cache tags
  189. *
  190. * @param string $cache Output to replace content in.
  191. * @return string with all replacements made to <!--nocache--><!--nocache-->
  192. */
  193. protected function _parseOutput($cache) {
  194. $count = 0;
  195. if (!empty($this->_match)) {
  196. foreach ($this->_match as $found) {
  197. $original = $cache;
  198. $length = strlen($found);
  199. $position = 0;
  200. for ($i = 1; $i <= 1; $i++) {
  201. $position = strpos($cache, $found, $position);
  202. if ($position !== false) {
  203. $cache = substr($original, 0, $position);
  204. $cache .= $this->_replace[$count];
  205. $cache .= substr($original, $position + $length);
  206. } else {
  207. break;
  208. }
  209. }
  210. $count++;
  211. }
  212. return $cache;
  213. }
  214. return $cache;
  215. }
  216. /**
  217. * Write a cached version of the file
  218. *
  219. * @param string $content view content to write to a cache file.
  220. * @param string $timestamp Duration to set for cache file.
  221. * @param boolean $useCallbacks
  222. * @return boolean success of caching view.
  223. */
  224. protected function _writeFile($content, $timestamp, $useCallbacks = false) {
  225. $now = time();
  226. if (is_numeric($timestamp)) {
  227. $cacheTime = $now + $timestamp;
  228. } else {
  229. $cacheTime = strtotime($timestamp, $now);
  230. }
  231. $path = $this->request->here();
  232. if ($path == '/') {
  233. $path = 'home';
  234. }
  235. $cache = strtolower(Inflector::slug($path));
  236. if (empty($cache)) {
  237. return;
  238. }
  239. $cache = $cache . '.php';
  240. $file = '<!--cachetime:' . $cacheTime . '--><?php';
  241. if (empty($this->_View->plugin)) {
  242. $file .= '
  243. App::import(\'Controller\', \'' . $this->_View->name. '\');
  244. ';
  245. } else {
  246. $file .= '
  247. App::import(\'Controller\', \'' . $this->_View->plugin . '.' . $this->_View->name. '\');
  248. ';
  249. }
  250. $file .= '$controller = new ' . $this->_View->name . 'Controller();
  251. $controller->plugin = $this->plugin = \'' . $this->_View->plugin . '\';
  252. $controller->helpers = $this->helpers = unserialize(\'' . serialize($this->_View->helpers) . '\');
  253. $controller->layout = $this->layout = \'' . $this->_View->layout. '\';
  254. $controller->request = $this->request = unserialize(\'' . str_replace("'", "\\'", serialize($this->request)) . '\');
  255. $controller->theme = $this->theme = \'' . $this->_View->theme . '\';
  256. $controller->viewVars = $this->viewVars = unserialize(base64_decode(\'' . base64_encode(serialize($this->_View->viewVars)) . '\'));
  257. Router::setRequestInfo($controller->request);';
  258. if ($useCallbacks == true) {
  259. $file .= '
  260. $controller->constructClasses();
  261. $controller->startupProcess();';
  262. }
  263. $file .= '
  264. $this->loadHelpers();
  265. extract($this->viewVars, EXTR_SKIP);
  266. ?>';
  267. $content = preg_replace("/(<\\?xml)/", "<?php echo '$1';?>",$content);
  268. $file .= $content;
  269. return cache('views' . DS . $cache, $file, $timestamp);
  270. }
  271. }