Projet

Général

Profil

Paste
Télécharger (10,9 ko) Statistiques
| Branche: | Révision:

root / drupal7 / sites / all / modules / views / plugins / views_plugin_cache.inc @ 7547bb19

1
<?php
2

    
3
/**
4
 * @file
5
 * Definition of views_plugin_cache.
6
 */
7

    
8
/**
9
 * @defgroup views_cache_plugins Views cache plugins
10
 * @{
11
 * @todo.
12
 *
13
 * @see hook_views_plugins()
14
 */
15

    
16
/**
17
 * The base plugin to handle caching.
18
 */
19
class views_plugin_cache extends views_plugin {
20
  /**
21
   * Contains all data that should be written/read from cache.
22
   */
23
  var $storage = array();
24

    
25
  /**
26
   * What table to store data in.
27
   */
28
  var $table = 'cache_views_data';
29

    
30
  /**
31
   * Initialize the plugin.
32
   *
33
   * @param $view
34
   *   The view object.
35
   * @param $display
36
   *   The display handler.
37
   */
38
  function init(&$view, &$display) {
39
    $this->view = &$view;
40
    $this->display = &$display;
41

    
42
    if (is_object($display->handler)) {
43
      $options = $display->handler->get_option('cache');
44
      // Overlay incoming options on top of defaults
45
      $this->unpack_options($this->options, $options);
46
    }
47
  }
48

    
49
  /**
50
   * Return a string to display as the clickable title for the
51
   * access control.
52
   */
53
  function summary_title() {
54
    return t('Unknown');
55
  }
56

    
57
  /**
58
   * Determine the expiration time of the cache type, or NULL if no expire.
59
   *
60
   * Plugins must override this to implement expiration.
61
   *
62
   * @param $type
63
   *   The cache type, either 'query', 'result' or 'output'.
64
   */
65
   function cache_expire($type) { }
66

    
67
   /**
68
    * Determine expiration time in the cache table of the cache type
69
    * or CACHE_PERMANENT if item shouldn't be removed automatically from cache.
70
    *
71
    * Plugins must override this to implement expiration in the cache table.
72
    *
73
    * @param $type
74
    *   The cache type, either 'query', 'result' or 'output'.
75
    */
76
  function cache_set_expire($type) {
77
    return CACHE_PERMANENT;
78
  }
79

    
80

    
81
  /**
82
   * Save data to the cache.
83
   *
84
   * A plugin should override this to provide specialized caching behavior.
85
   */
86
  function cache_set($type) {
87
    switch ($type) {
88
      case 'query':
89
        // Not supported currently, but this is certainly where we'd put it.
90
        break;
91
      case 'results':
92
        $data = array(
93
          'result' => $this->view->result,
94
          'total_rows' => isset($this->view->total_rows) ? $this->view->total_rows : 0,
95
          'current_page' => $this->view->get_current_page(),
96
        );
97
        cache_set($this->get_results_key(), $data, $this->table, $this->cache_set_expire($type));
98
        break;
99
      case 'output':
100
        $this->gather_headers();
101
        $this->storage['output'] = $this->view->display_handler->output;
102
        cache_set($this->get_output_key(), $this->storage, $this->table, $this->cache_set_expire($type));
103
        break;
104
    }
105
  }
106

    
107

    
108
  /**
109
   * Retrieve data from the cache.
110
   *
111
   * A plugin should override this to provide specialized caching behavior.
112
   */
113
  function cache_get($type) {
114
    $cutoff = $this->cache_expire($type);
115
    switch ($type) {
116
      case 'query':
117
        // Not supported currently, but this is certainly where we'd put it.
118
        return FALSE;
119
      case 'results':
120
        // Values to set: $view->result, $view->total_rows, $view->execute_time,
121
        // $view->current_page.
122
        if ($cache = cache_get($this->get_results_key(), $this->table)) {
123
          if (!$cutoff || $cache->created > $cutoff) {
124
            $this->view->result = $cache->data['result'];
125
            $this->view->total_rows = $cache->data['total_rows'];
126
            $this->view->set_current_page($cache->data['current_page']);
127
            $this->view->execute_time = 0;
128
            return TRUE;
129
          }
130
        }
131
        return FALSE;
132
      case 'output':
133
        if ($cache = cache_get($this->get_output_key(), $this->table)) {
134
          if (!$cutoff || $cache->created > $cutoff) {
135
            $this->storage = $cache->data;
136
            $this->view->display_handler->output = $cache->data['output'];
137
            $this->restore_headers();
138
            return TRUE;
139
          }
140
        }
141
        return FALSE;
142
    }
143
  }
144

    
145
  /**
146
   * Clear out cached data for a view.
147
   *
148
   * We're just going to nuke anything related to the view, regardless of display,
149
   * to be sure that we catch everything. Maybe that's a bad idea.
150
   */
151
  function cache_flush() {
152
    cache_clear_all($this->view->name . ':', $this->table, TRUE);
153
  }
154

    
155
  /**
156
   * Post process any rendered data.
157
   *
158
   * This can be valuable to be able to cache a view and still have some level of
159
   * dynamic output. In an ideal world, the actual output will include HTML
160
   * comment based tokens, and then the post process can replace those tokens.
161
   *
162
   * Example usage. If it is known that the view is a node view and that the
163
   * primary field will be a nid, you can do something like this:
164
   *
165
   * <!--post-FIELD-NID-->
166
   *
167
   * And then in the post render, create an array with the text that should
168
   * go there:
169
   *
170
   * strtr($output, array('<!--post-FIELD-1-->', 'output for FIELD of nid 1');
171
   *
172
   * All of the cached result data will be available in $view->result, as well,
173
   * so all ids used in the query should be discoverable.
174
   */
175
  function post_render(&$output) { }
176

    
177
  /**
178
   * Start caching javascript, css and other out of band info.
179
   *
180
   * This takes a snapshot of the current system state so that we don't
181
   * duplicate it. Later on, when gather_headers() is run, this information
182
   * will be removed so that we don't hold onto it.
183
   */
184
  function cache_start() {
185
    $this->storage['head'] = drupal_add_html_head();
186
    $this->storage['css'] = drupal_add_css();
187
    $this->storage['js'] = drupal_add_js();
188
    $this->storage['headers'] = drupal_get_http_header();
189
  }
190

    
191
  /**
192
   * Gather out of band data, compare it to what we started with and store the difference.
193
   */
194
  function gather_headers() {
195
    // Simple replacement for head
196
    if (isset($this->storage['head'])) {
197
      $this->storage['head'] = str_replace($this->storage['head'], '', drupal_add_html_head());
198
    }
199
    else {
200
      $this->storage['head'] = '';
201
    }
202

    
203
    // Check if the advanced mapping function of D 7.23 is available.
204
    $array_mapping_func = function_exists('drupal_array_diff_assoc_recursive') ? 'drupal_array_diff_assoc_recursive' : 'array_diff_assoc';
205

    
206
    // Slightly less simple for CSS:
207
    $css = drupal_add_css();
208
    $css_start = isset($this->storage['css']) ? $this->storage['css'] : array();
209
    $this->storage['css'] = $this->assetDiff($css, $css_start, $array_mapping_func);
210

    
211
    // Get javascript after/before views renders.
212
    $js = drupal_add_js();
213
    $js_start = isset($this->storage['js']) ? $this->storage['js'] : array();
214
    // If there are any differences between the old and the new javascript then
215
    // store them to be added later.
216
    $this->storage['js'] = $this->assetDiff($js, $js_start, $array_mapping_func);
217

    
218
    // Special case the settings key and get the difference of the data.
219
    $settings = isset($js['settings']['data']) ? $js['settings']['data'] : array();
220
    $settings_start = isset($js_start['settings']['data']) ? $js_start['settings']['data'] : array();
221
    $this->storage['js']['settings'] = $array_mapping_func($settings, $settings_start);
222

    
223
    // Get difference of HTTP headers.
224
    $this->storage['headers'] = $array_mapping_func(drupal_get_http_header(), $this->storage['headers']);
225
  }
226

    
227
  /**
228
   * Computes the differences between two JS/CSS asset arrays.
229
   *
230
   * @param array $assets
231
   *   The current asset array.
232
   * @param array $start_assets
233
   *   The original asset array.
234
   * @param string $diff_function
235
   *   The function that should be used for computing the diff.
236
   *
237
   * @return array
238
   *   A CSS or JS asset array that contains all entries that are new/different
239
   *   in $assets.
240
   */
241
  protected function assetDiff(array $assets, array $start_assets, $diff_function) {
242
    $diff = $diff_function($assets, $start_assets);
243

    
244
    // Cleanup the resulting array since drupal_array_diff_assoc_recursive() can
245
    // leave half populated arrays behind.
246
    foreach ($diff as $key => $entry) {
247
      // If only the weight was different we can remove this entry.
248
      if (count($entry) == 1 && isset($entry['weight'])) {
249
        unset($diff[$key]);
250
      }
251
      // If there are other differences we override with the latest entry.
252
      elseif ($entry != $assets[$key]) {
253
        $diff[$key] = $assets[$key];
254
      }
255
    }
256
    return $diff;
257
  }
258

    
259
  /**
260
   * Restore out of band data saved to cache. Copied from Panels.
261
   */
262
  function restore_headers() {
263
    if (!empty($this->storage['head'])) {
264
      drupal_add_html_head($this->storage['head']);
265
    }
266
    if (!empty($this->storage['css'])) {
267
      foreach ($this->storage['css'] as $args) {
268
        drupal_add_css($args['data'], $args);
269
      }
270
    }
271
    if (!empty($this->storage['js'])) {
272
      foreach ($this->storage['js'] as $key => $args) {
273
        if ($key !== 'settings') {
274
          drupal_add_js($args['data'], $args);
275
        }
276
        else {
277
          foreach ($args as $setting) {
278
            drupal_add_js($setting, 'setting');
279
          }
280
        }
281
      }
282
    }
283
    if (!empty($this->storage['headers'])) {
284
      foreach ($this->storage['headers'] as $name => $value) {
285
        drupal_add_http_header($name, $value);
286
      }
287
    }
288
  }
289

    
290
  function get_results_key() {
291
    if (!isset($this->_results_key)) {
292
      $key_data = array();
293
      foreach (array('exposed_info', 'page', 'sort', 'order', 'items_per_page', 'offset') as $key) {
294
        if (isset($_GET[$key])) {
295
          $key_data[$key] = $_GET[$key];
296
        }
297
      }
298

    
299
      $this->_results_key = $this->view->name . ':' . $this->display->id . ':results:' . $this->get_cache_key($key_data);
300
    }
301

    
302
    return $this->_results_key;
303
  }
304

    
305
  function get_output_key() {
306
    if (!isset($this->_output_key)) {
307
      $key_data = array(
308
        'result' => $this->view->result,
309
        'theme' => $GLOBALS['theme'],
310
      );
311
      $this->_output_key = $this->view->name . ':' . $this->display->id . ':output:' . $this->get_cache_key($key_data);
312
    }
313

    
314
    return $this->_output_key;
315
  }
316

    
317
  /**
318
   * Returns cache key.
319
   *
320
   * @param array $key_data
321
   *   Additional data for cache segmentation and/or overrides for default
322
   *   segmentation.
323
   *
324
   * @return string
325
   */
326
  function get_cache_key($key_data = array()) {
327
    global $user;
328

    
329
    $key_data += array(
330
      'roles' => array_keys($user->roles),
331
      'super-user' => $user->uid == 1, // special caching for super user.
332
      'language' => $GLOBALS['language']->language,
333
      'base_url' => $GLOBALS['base_url'],
334
    );
335

    
336
    if (empty($key_data['build_info'])) {
337
      $build_info = $this->view->build_info;
338
      foreach (array('query','count_query') as $index) {
339
        // If the default query back-end is used generate SQL query strings from
340
        // the query objects.
341
        if ($build_info[$index] instanceof SelectQueryInterface) {
342
          $query = clone $build_info[$index];
343
          $query->preExecute();
344
          $key_data['build_info'][$index] = array(
345
            'sql' => (string) $query,
346
            'arguments' => $query->getArguments(),
347
          );
348
        }
349
      }
350
    }
351
    $key = md5(serialize($key_data));
352
    return $key;
353
  }
354
}
355

    
356
/**
357
 * @}
358
 */