CacheHelper.php 9.5 KB

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