CacheHelper.php 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  1. <?php
  2. /**
  3. * CacheHelper helps create full page view caching.
  4. *
  5. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  6. * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  7. *
  8. * Licensed under The MIT License
  9. * For full copyright and license information, please see the LICENSE.txt
  10. * Redistributions of files must retain the above copyright notice.
  11. *
  12. * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  13. * @link http://cakephp.org CakePHP(tm) Project
  14. * @package Cake.View.Helper
  15. * @since CakePHP(tm) v 1.0.0.2277
  16. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  17. */
  18. App::uses('AppHelper', 'View/Helper');
  19. /**
  20. * CacheHelper helps create full page view caching.
  21. *
  22. * When using CacheHelper you don't call any of its methods, they are all automatically
  23. * called by View, and use the $cacheAction settings set in the controller.
  24. *
  25. * @package Cake.View.Helper
  26. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/cache.html
  27. */
  28. class CacheHelper extends AppHelper {
  29. /**
  30. * Array of strings replaced in cached views.
  31. * The strings are found between `<!--nocache--><!--/nocache-->` in views
  32. *
  33. * @var array
  34. */
  35. protected $_replace = array();
  36. /**
  37. * Array of string that are replace with there var replace above.
  38. * The strings are any content inside `<!--nocache--><!--/nocache-->` and includes the tags in views
  39. *
  40. * @var array
  41. */
  42. protected $_match = array();
  43. /**
  44. * Counter used for counting nocache section tags.
  45. *
  46. * @var int
  47. */
  48. protected $_counter = 0;
  49. /**
  50. * Is CacheHelper enabled? should files + output be parsed.
  51. *
  52. * @return bool
  53. */
  54. protected function _enabled() {
  55. return $this->_View->cacheAction && (Configure::read('Cache.check') === true);
  56. }
  57. /**
  58. * Parses the view file and stores content for cache file building.
  59. *
  60. * @param string $viewFile View file name.
  61. * @param string $output The output for the file.
  62. * @return string Updated content.
  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 Layout file name.
  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 output
  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 = $cacheAction[$index] + array('duration' => 0, 'callbacks' => false);
  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 bool $useCallbacks Whether to include statements in cached file which
  246. * run callbacks.
  247. * @return bool 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. }