CacheHelper.php 7.5 KB

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