CacheHelper.php 7.4 KB

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