PageRenderTime 25ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/Cake/View/Helper/CacheHelper.php

https://github.com/suzuki/candycane
PHP | 321 lines | 181 code | 28 blank | 112 comment | 35 complexity | dd26e90ab43a423bbc595be7db89980f MD5 | raw file
  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-2012, 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-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
  14. * @link http://cakephp.org CakePHP(tm) Project
  15. * @package Cake.View.Helper
  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.View.Helper
  27. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/cache.html
  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. * Counter used for counting nocache section tags.
  46. *
  47. * @var integer
  48. */
  49. protected $_counter = 0;
  50. /**
  51. * Is CacheHelper enabled? should files + output be parsed.
  52. *
  53. * @return boolean
  54. */
  55. protected function _enabled() {
  56. return (($this->_View->cacheAction != false)) && (Configure::read('Cache.check') === true);
  57. }
  58. /**
  59. * Parses the view file and stores content for cache file building.
  60. *
  61. * @param string $viewFile
  62. * @return void
  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
  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 ouput
  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 = array_merge(array('duration' => 0, 'callbacks' => false), $cacheAction[$index]);
  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. $this->_writeFile($cached, $cacheTime, $useCallbacks);
  139. $out = $this->_stripTags($out);
  140. }
  141. return $out;
  142. }
  143. /**
  144. * Parse file searching for no cache tags
  145. *
  146. * @param string $file The filename that needs to be parsed.
  147. * @param string $cache The cached content
  148. * @return void
  149. */
  150. protected function _parseFile($file, $cache) {
  151. if (is_file($file)) {
  152. $file = file_get_contents($file);
  153. } elseif ($file = fileExistsInPath($file)) {
  154. $file = file_get_contents($file);
  155. }
  156. preg_match_all('/(<!--nocache:\d{3}-->(?<=<!--nocache:\d{3}-->)[\\s\\S]*?(?=<!--\/nocache-->)<!--\/nocache-->)/i', $cache, $outputResult, PREG_PATTERN_ORDER);
  157. preg_match_all('/(?<=<!--nocache-->)([\\s\\S]*?)(?=<!--\/nocache-->)/i', $file, $fileResult, PREG_PATTERN_ORDER);
  158. $fileResult = $fileResult[0];
  159. $outputResult = $outputResult[0];
  160. if (!empty($this->_replace)) {
  161. foreach ($outputResult as $i => $element) {
  162. $index = array_search($element, $this->_match);
  163. if ($index !== false) {
  164. unset($outputResult[$i]);
  165. }
  166. }
  167. $outputResult = array_values($outputResult);
  168. }
  169. if (!empty($fileResult)) {
  170. $i = 0;
  171. foreach ($fileResult as $cacheBlock) {
  172. if (isset($outputResult[$i])) {
  173. $this->_replace[] = $cacheBlock;
  174. $this->_match[] = $outputResult[$i];
  175. }
  176. $i++;
  177. }
  178. }
  179. }
  180. /**
  181. * Munges the output from a view with cache tags, and numbers the sections.
  182. * This helps solve issues with empty/duplicate content.
  183. *
  184. * @return string The content with cake:nocache tags replaced.
  185. */
  186. protected function _replaceSection() {
  187. $this->_counter += 1;
  188. return sprintf('<!--nocache:%03d-->', $this->_counter);
  189. }
  190. /**
  191. * Strip cake:nocache tags from a string. Since View::render()
  192. * only removes un-numbered nocache tags, remove all the numbered ones.
  193. * This is the complement to _replaceSection.
  194. *
  195. * @param string $content String to remove tags from.
  196. * @return string String with tags removed.
  197. */
  198. protected function _stripTags($content) {
  199. return preg_replace('#<!--/?nocache(\:\d{3})?-->#', '', $content);
  200. }
  201. /**
  202. * Parse the output and replace cache tags
  203. *
  204. * @param string $cache Output to replace content in.
  205. * @return string with all replacements made to <!--nocache--><!--nocache-->
  206. */
  207. protected function _parseOutput($cache) {
  208. $count = 0;
  209. if (!empty($this->_match)) {
  210. foreach ($this->_match as $found) {
  211. $original = $cache;
  212. $length = strlen($found);
  213. $position = 0;
  214. for ($i = 1; $i <= 1; $i++) {
  215. $position = strpos($cache, $found, $position);
  216. if ($position !== false) {
  217. $cache = substr($original, 0, $position);
  218. $cache .= $this->_replace[$count];
  219. $cache .= substr($original, $position + $length);
  220. } else {
  221. break;
  222. }
  223. }
  224. $count++;
  225. }
  226. return $cache;
  227. }
  228. return $cache;
  229. }
  230. /**
  231. * Write a cached version of the file
  232. *
  233. * @param string $content view content to write to a cache file.
  234. * @param string $timestamp Duration to set for cache file.
  235. * @param boolean $useCallbacks
  236. * @return boolean success of caching view.
  237. */
  238. protected function _writeFile($content, $timestamp, $useCallbacks = false) {
  239. $now = time();
  240. if (is_numeric($timestamp)) {
  241. $cacheTime = $now + $timestamp;
  242. } else {
  243. $cacheTime = strtotime($timestamp, $now);
  244. }
  245. $path = $this->request->here();
  246. if ($path == '/') {
  247. $path = 'home';
  248. }
  249. $cache = strtolower(Inflector::slug($path));
  250. if (empty($cache)) {
  251. return;
  252. }
  253. $cache = $cache . '.php';
  254. $file = '<!--cachetime:' . $cacheTime . '--><?php';
  255. if (empty($this->_View->plugin)) {
  256. $file .= "
  257. App::uses('{$this->_View->name}Controller', 'Controller');
  258. ";
  259. } else {
  260. $file .= "
  261. App::uses('{$this->_View->plugin}AppController', '{$this->_View->plugin}.Controller');
  262. App::uses('{$this->_View->name}Controller', '{$this->_View->plugin}.Controller');
  263. ";
  264. }
  265. $file .= '
  266. $request = unserialize(\'' . str_replace("'", "\\'", serialize($this->request)) . '\');
  267. $response = new CakeResponse(array("charset" => Configure::read("App.encoding")));
  268. $controller = new ' . $this->_View->name . 'Controller($request, $response);
  269. $controller->plugin = $this->plugin = \'' . $this->_View->plugin . '\';
  270. $controller->helpers = $this->helpers = unserialize(base64_decode(\'' . base64_encode(serialize($this->_View->helpers)) . '\'));
  271. $controller->layout = $this->layout = \'' . $this->_View->layout . '\';
  272. $controller->theme = $this->theme = \'' . $this->_View->theme . '\';
  273. $controller->viewVars = unserialize(base64_decode(\'' . base64_encode(serialize($this->_View->viewVars)) . '\'));
  274. Router::setRequestInfo($controller->request);
  275. $this->request = $request;';
  276. if ($useCallbacks == true) {
  277. $file .= '
  278. $controller->constructClasses();
  279. $controller->startupProcess();';
  280. }
  281. $file .= '
  282. $this->viewVars = $controller->viewVars;
  283. $this->loadHelpers();
  284. extract($this->viewVars, EXTR_SKIP);
  285. ?>';
  286. $content = preg_replace("/(<\\?xml)/", "<?php echo '$1';?>", $content);
  287. $file .= $content;
  288. return cache('views' . DS . $cache, $file, $timestamp);
  289. }
  290. }