CacheHelper.php 9.8 KB

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