views_plugin_cache.inc 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  1. <?php
  2. /**
  3. * @file
  4. * Definition of views_plugin_cache.
  5. */
  6. /**
  7. * @defgroup views_cache_plugins Views cache plugins
  8. * @{
  9. * @todo.
  10. *
  11. * @see hook_views_plugins()
  12. */
  13. /**
  14. * The base plugin to handle caching.
  15. */
  16. class views_plugin_cache extends views_plugin {
  17. /**
  18. * Contains all data that should be written/read from cache.
  19. */
  20. var $storage = array();
  21. /**
  22. * What table to store data in.
  23. */
  24. var $table = 'cache_views_data';
  25. /**
  26. * Initialize the plugin.
  27. *
  28. * @param $view
  29. * The view object.
  30. * @param $display
  31. * The display handler.
  32. */
  33. function init(&$view, &$display) {
  34. $this->view = &$view;
  35. $this->display = &$display;
  36. if (is_object($display->handler)) {
  37. $options = $display->handler->get_option('cache');
  38. // Overlay incoming options on top of defaults
  39. $this->unpack_options($this->options, $options);
  40. }
  41. }
  42. /**
  43. * Return a string to display as the clickable title for the
  44. * access control.
  45. */
  46. function summary_title() {
  47. return t('Unknown');
  48. }
  49. /**
  50. * Determine the expiration time of the cache type, or NULL if no expire.
  51. *
  52. * Plugins must override this to implement expiration.
  53. *
  54. * @param $type
  55. * The cache type, either 'query', 'result' or 'output'.
  56. */
  57. function cache_expire($type) { }
  58. /**
  59. * Determine expiration time in the cache table of the cache type
  60. * or CACHE_PERMANENT if item shouldn't be removed automatically from cache.
  61. *
  62. * Plugins must override this to implement expiration in the cache table.
  63. *
  64. * @param $type
  65. * The cache type, either 'query', 'result' or 'output'.
  66. */
  67. function cache_set_expire($type) {
  68. return CACHE_PERMANENT;
  69. }
  70. /**
  71. * Save data to the cache.
  72. *
  73. * A plugin should override this to provide specialized caching behavior.
  74. */
  75. function cache_set($type) {
  76. switch ($type) {
  77. case 'query':
  78. // Not supported currently, but this is certainly where we'd put it.
  79. break;
  80. case 'results':
  81. $data = array(
  82. 'result' => $this->view->result,
  83. 'total_rows' => isset($this->view->total_rows) ? $this->view->total_rows : 0,
  84. 'current_page' => $this->view->get_current_page(),
  85. );
  86. cache_set($this->get_results_key(), $data, $this->table, $this->cache_set_expire($type));
  87. break;
  88. case 'output':
  89. $this->gather_headers();
  90. $this->storage['output'] = $this->view->display_handler->output;
  91. cache_set($this->get_output_key(), $this->storage, $this->table, $this->cache_set_expire($type));
  92. break;
  93. }
  94. }
  95. /**
  96. * Retrieve data from the cache.
  97. *
  98. * A plugin should override this to provide specialized caching behavior.
  99. */
  100. function cache_get($type) {
  101. $cutoff = $this->cache_expire($type);
  102. switch ($type) {
  103. case 'query':
  104. // Not supported currently, but this is certainly where we'd put it.
  105. return FALSE;
  106. case 'results':
  107. // Values to set: $view->result, $view->total_rows, $view->execute_time,
  108. // $view->current_page.
  109. if ($cache = cache_get($this->get_results_key(), $this->table)) {
  110. if (!$cutoff || $cache->created > $cutoff) {
  111. $this->view->result = $cache->data['result'];
  112. $this->view->total_rows = $cache->data['total_rows'];
  113. $this->view->set_current_page($cache->data['current_page']);
  114. $this->view->execute_time = 0;
  115. return TRUE;
  116. }
  117. }
  118. return FALSE;
  119. case 'output':
  120. if ($cache = cache_get($this->get_output_key(), $this->table)) {
  121. if (!$cutoff || $cache->created > $cutoff) {
  122. $this->storage = $cache->data;
  123. $this->view->display_handler->output = $cache->data['output'];
  124. $this->restore_headers();
  125. return TRUE;
  126. }
  127. }
  128. return FALSE;
  129. }
  130. }
  131. /**
  132. * Clear out cached data for a view.
  133. *
  134. * We're just going to nuke anything related to the view, regardless of display,
  135. * to be sure that we catch everything. Maybe that's a bad idea.
  136. */
  137. function cache_flush() {
  138. cache_clear_all($this->view->name . ':', $this->table, TRUE);
  139. }
  140. /**
  141. * Post process any rendered data.
  142. *
  143. * This can be valuable to be able to cache a view and still have some level of
  144. * dynamic output. In an ideal world, the actual output will include HTML
  145. * comment based tokens, and then the post process can replace those tokens.
  146. *
  147. * Example usage. If it is known that the view is a node view and that the
  148. * primary field will be a nid, you can do something like this:
  149. *
  150. * <!--post-FIELD-NID-->
  151. *
  152. * And then in the post render, create an array with the text that should
  153. * go there:
  154. *
  155. * strtr($output, array('<!--post-FIELD-1-->', 'output for FIELD of nid 1');
  156. *
  157. * All of the cached result data will be available in $view->result, as well,
  158. * so all ids used in the query should be discoverable.
  159. */
  160. function post_render(&$output) { }
  161. /**
  162. * Start caching javascript, css and other out of band info.
  163. *
  164. * This takes a snapshot of the current system state so that we don't
  165. * duplicate it. Later on, when gather_headers() is run, this information
  166. * will be removed so that we don't hold onto it.
  167. */
  168. function cache_start() {
  169. $this->storage['head'] = drupal_add_html_head();
  170. $this->storage['css'] = drupal_add_css();
  171. $this->storage['js'] = drupal_add_js();
  172. $this->storage['headers'] = drupal_get_http_header();
  173. }
  174. /**
  175. * Gather out of band data, compare it to what we started with and store the difference.
  176. */
  177. function gather_headers() {
  178. // Simple replacement for head
  179. if (isset($this->storage['head'])) {
  180. $this->storage['head'] = str_replace($this->storage['head'], '', drupal_add_html_head());
  181. }
  182. else {
  183. $this->storage['head'] = '';
  184. }
  185. // Check if the advanced mapping function of D 7.23 is available.
  186. $array_mapping_func = function_exists('drupal_array_diff_assoc_recursive') ? 'drupal_array_diff_assoc_recursive' : 'array_diff_assoc';
  187. // Slightly less simple for CSS:
  188. $css = drupal_add_css();
  189. $css_start = isset($this->storage['css']) ? $this->storage['css'] : array();
  190. $this->storage['css'] = $this->assetDiff($css, $css_start, $array_mapping_func);
  191. // Get javascript after/before views renders.
  192. $js = drupal_add_js();
  193. $js_start = isset($this->storage['js']) ? $this->storage['js'] : array();
  194. // If there are any differences between the old and the new javascript then
  195. // store them to be added later.
  196. $this->storage['js'] = $this->assetDiff($js, $js_start, $array_mapping_func);
  197. // Special case the settings key and get the difference of the data.
  198. $settings = isset($js['settings']['data']) ? $js['settings']['data'] : array();
  199. $settings_start = isset($js_start['settings']['data']) ? $js_start['settings']['data'] : array();
  200. $this->storage['js']['settings'] = $array_mapping_func($settings, $settings_start);
  201. // Get difference of HTTP headers.
  202. $this->storage['headers'] = $array_mapping_func(drupal_get_http_header(), $this->storage['headers']);
  203. }
  204. /**
  205. * Computes the differences between two JS/CSS asset arrays.
  206. *
  207. * @param array $assets
  208. * The current asset array.
  209. * @param array $start_assets
  210. * The original asset array.
  211. * @param string $diff_function
  212. * The function that should be used for computing the diff.
  213. *
  214. * @return array
  215. * A CSS or JS asset array that contains all entries that are new/different
  216. * in $assets.
  217. */
  218. protected function assetDiff(array $assets, array $start_assets, $diff_function) {
  219. $diff = $diff_function($assets, $start_assets);
  220. // Cleanup the resulting array since drupal_array_diff_assoc_recursive() can
  221. // leave half populated arrays behind.
  222. foreach ($diff as $key => $entry) {
  223. // If only the weight was different we can remove this entry.
  224. if (count($entry) == 1 && isset($entry['weight'])) {
  225. unset($diff[$key]);
  226. }
  227. // If there are other differences we override with the latest entry.
  228. elseif ($entry != $assets[$key]) {
  229. $diff[$key] = $assets[$key];
  230. }
  231. }
  232. return $diff;
  233. }
  234. /**
  235. * Restore out of band data saved to cache. Copied from Panels.
  236. */
  237. function restore_headers() {
  238. if (!empty($this->storage['head'])) {
  239. drupal_add_html_head($this->storage['head']);
  240. }
  241. if (!empty($this->storage['css'])) {
  242. foreach ($this->storage['css'] as $args) {
  243. drupal_add_css($args['data'], $args);
  244. }
  245. }
  246. if (!empty($this->storage['js'])) {
  247. foreach ($this->storage['js'] as $key => $args) {
  248. if ($key !== 'settings') {
  249. drupal_add_js($args['data'], $args);
  250. }
  251. else {
  252. foreach ($args as $setting) {
  253. drupal_add_js($setting, 'setting');
  254. }
  255. }
  256. }
  257. }
  258. if (!empty($this->storage['headers'])) {
  259. foreach ($this->storage['headers'] as $name => $value) {
  260. drupal_add_http_header($name, $value);
  261. }
  262. }
  263. }
  264. function get_results_key() {
  265. if (!isset($this->_results_key)) {
  266. $key_data = array();
  267. foreach (array('exposed_info', 'page', 'sort', 'order', 'items_per_page', 'offset') as $key) {
  268. if (isset($_GET[$key])) {
  269. $key_data[$key] = $_GET[$key];
  270. }
  271. }
  272. $this->_results_key = $this->view->name . ':' . $this->display->id . ':results:' . $this->get_cache_key($key_data);
  273. }
  274. return $this->_results_key;
  275. }
  276. function get_output_key() {
  277. if (!isset($this->_output_key)) {
  278. $key_data = array(
  279. 'result' => $this->view->result,
  280. 'theme' => $GLOBALS['theme'],
  281. );
  282. $this->_output_key = $this->view->name . ':' . $this->display->id . ':output:' . $this->get_cache_key($key_data);
  283. }
  284. return $this->_output_key;
  285. }
  286. /**
  287. * Returns cache key.
  288. *
  289. * @param array $key_data
  290. * Additional data for cache segmentation and/or overrides for default
  291. * segmentation.
  292. *
  293. * @return string
  294. */
  295. function get_cache_key($key_data = array()) {
  296. global $user;
  297. $key_data += array(
  298. 'roles' => array_keys($user->roles),
  299. 'super-user' => $user->uid == 1, // special caching for super user.
  300. 'language' => $GLOBALS['language']->language,
  301. 'base_url' => $GLOBALS['base_url'],
  302. );
  303. if (empty($key_data['build_info'])) {
  304. $build_info = $this->view->build_info;
  305. foreach (array('query','count_query') as $index) {
  306. // If the default query back-end is used generate SQL query strings from
  307. // the query objects.
  308. if ($build_info[$index] instanceof SelectQueryInterface) {
  309. $query = clone $build_info[$index];
  310. $query->preExecute();
  311. $key_data['build_info'][$index] = array(
  312. 'sql' => (string) $query,
  313. 'arguments' => $query->getArguments(),
  314. );
  315. }
  316. }
  317. }
  318. $key = md5(serialize($key_data));
  319. return $key;
  320. }
  321. }
  322. /**
  323. * @}
  324. */