CacheHelper.php 9.5 KB

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