Projet

Général

Profil

Paste
Télécharger (11,1 ko) Statistiques
| Branche: | Révision:

root / drupal7 / sites / all / modules / views / plugins / views_plugin_cache.inc @ 5d12d676

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
  /**
22
   * Contains all data that should be written/read from cache.
23
   */
24
  public $storage = array();
25

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

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

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

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

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

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

    
83
  /**
84
   * Save data to the cache.
85
   *
86
   * A plugin should override this to provide specialized caching behavior.
87
   */
88
  public function cache_set($type) {
89
    switch ($type) {
90
      case 'query':
91
        // Not supported currently, but this is certainly where we'd put it.
92
        break;
93

    
94
      case 'results':
95
        $data = array(
96
          'result' => $this->view->result,
97
          'total_rows' => isset($this->view->total_rows) ? $this->view->total_rows : 0,
98
          'current_page' => $this->view->get_current_page(),
99
        );
100
        cache_set($this->get_results_key(), $data, $this->table, $this->cache_set_expire($type));
101
        break;
102

    
103
      case 'output':
104
        $this->gather_headers();
105
        $this->storage['output'] = $this->view->display_handler->output;
106
        cache_set($this->get_output_key(), $this->storage, $this->table, $this->cache_set_expire($type));
107
        break;
108
    }
109
  }
110

    
111
  /**
112
   * Retrieve data from the cache.
113
   *
114
   * A plugin should override this to provide specialized caching behavior.
115
   */
116
  public function cache_get($type) {
117
    $cutoff = $this->cache_expire($type);
118
    switch ($type) {
119
      case 'query':
120
        // Not supported currently, but this is certainly where we'd put it.
121
        return FALSE;
122

    
123
      case 'results':
124
        // Values to set: $view->result, $view->total_rows, $view->execute_time,
125
        // $view->current_page.
126
        if ($cache = cache_get($this->get_results_key(), $this->table)) {
127
          if (!$cutoff || $cache->created > $cutoff) {
128
            $this->view->result = $cache->data['result'];
129
            $this->view->total_rows = $cache->data['total_rows'];
130
            $this->view->set_current_page($cache->data['current_page']);
131
            $this->view->execute_time = 0;
132
            return TRUE;
133
          }
134
        }
135
        return FALSE;
136

    
137
      case 'output':
138
        if ($cache = cache_get($this->get_output_key(), $this->table)) {
139
          if (!$cutoff || $cache->created > $cutoff) {
140
            $this->storage = $cache->data;
141
            $this->view->display_handler->output = $cache->data['output'];
142
            $this->restore_headers();
143
            return TRUE;
144
          }
145
        }
146
        return FALSE;
147
    }
148
  }
149

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

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

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

    
197
  /**
198
   * Gather out of band data, compare it to the start data and store the diff.
199
   */
200
  public function gather_headers() {
201
    // Simple replacement for head.
202
    if (isset($this->storage['head'])) {
203
      $this->storage['head'] = str_replace($this->storage['head'], '', drupal_add_html_head());
204
    }
205
    else {
206
      $this->storage['head'] = '';
207
    }
208

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

    
212
    // Slightly less simple for CSS.
213
    $css = drupal_add_css();
214
    $css_start = isset($this->storage['css']) ? $this->storage['css'] : array();
215
    $this->storage['css'] = $this->assetDiff($css, $css_start, $array_mapping_func);
216

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

    
224
    // Special case the settings key and get the difference of the data.
225
    $settings = isset($js['settings']['data']) ? $js['settings']['data'] : array();
226
    $settings_start = isset($js_start['settings']['data']) ? $js_start['settings']['data'] : array();
227
    $this->storage['js']['settings'] = $array_mapping_func($settings, $settings_start);
228

    
229
    // Get difference of HTTP headers.
230
    $this->storage['headers'] = $array_mapping_func(drupal_get_http_header(), $this->storage['headers']);
231
  }
232

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

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

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

    
296
  /**
297
   *
298
   */
299
  public function get_results_key() {
300
    if (!isset($this->_results_key)) {
301
      $key_data = array();
302
      foreach (array('exposed_info', 'page', 'sort', 'order', 'items_per_page', 'offset') as $key) {
303
        if (isset($_GET[$key])) {
304
          $key_data[$key] = $_GET[$key];
305
        }
306
      }
307

    
308
      $this->_results_key = $this->view->name . ':' . $this->display->id . ':results:' . $this->get_cache_key($key_data);
309
    }
310

    
311
    return $this->_results_key;
312
  }
313

    
314
  /**
315
   *
316
   */
317
  public function get_output_key() {
318
    if (!isset($this->_output_key)) {
319
      $key_data = array(
320
        'result' => $this->view->result,
321
        'theme' => $GLOBALS['theme'],
322
      );
323
      $this->_output_key = $this->view->name . ':' . $this->display->id . ':output:' . $this->get_cache_key($key_data);
324
    }
325

    
326
    return $this->_output_key;
327
  }
328

    
329
  /**
330
   * Returns cache key.
331
   *
332
   * @param array $key_data
333
   *   Additional data for cache segmentation and/or overrides for default
334
   *   segmentation.
335
   *
336
   * @return string
337
   */
338
  public function get_cache_key($key_data = array()) {
339
    global $user;
340

    
341
    $key_data += array(
342
      'roles' => array_keys($user->roles),
343
      'super-user' => $user->uid == 1,
344
    // special caching for super user.
345
      'language' => $GLOBALS['language']->language,
346
      'language_content' => $GLOBALS['language_content']->language,
347
      'base_url' => $GLOBALS['base_url'],
348
    );
349

    
350
    if (empty($key_data['build_info'])) {
351
      $build_info = $this->view->build_info;
352
      foreach (array('query', 'count_query') as $index) {
353
        // If the default query back-end is used generate SQL query strings from
354
        // the query objects.
355
        if ($build_info[$index] instanceof SelectQueryInterface) {
356
          $query = clone $build_info[$index];
357
          $query->preExecute();
358
          $key_data['build_info'][$index] = array(
359
            'sql' => (string) $query,
360
            'arguments' => $query->getArguments(),
361
          );
362
        }
363
      }
364
    }
365
    return md5(serialize($key_data));
366
  }
367

    
368
}
369

    
370
/**
371
 * @}
372
 */