-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttp_request_cache.module
More file actions
89 lines (72 loc) · 2.47 KB
/
http_request_cache.module
File metadata and controls
89 lines (72 loc) · 2.47 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
<?php
/**
* @file
* http_request_cache.module
*
* Shows how to create a wrapper around drupal_http_request() that implements
* both static and database caching. It also adds a hook to allow modules the
* ability to adjust if something gets cached.
*/
/**
* Custom drupal_http_request() wrapper that implements caching.
*
* @see drupal_http_request()
*/
function http_request_cache_http_request($url, array $options = array()) {
$args = func_get_args();
$key = __FUNCTION__ . serialize($args);
$cid = hash('sha512', drupal_get_hash_salt() . $key);
print_r($cid);
// Skip POST requests no matter what.
$is_cacheable = empty($options['method']) || drupal_strtoupper($options['method']) != 'POST';
// Allow modules to adjust cacheable status.
if ($is_cacheable) {
$context = array(
'url' => $url,
'options' => $options,
);
drupal_alter('http_request_is_cacheable', $is_cacheable, $context);
}
$result = NULL;
if ($is_cacheable) {
$result = &drupal_static($cid);
// See if we have a static cached result so we can avoid the db completely.
if (!empty($result)) {
return $result;
}
// Check for a cached version of this request in the db.
elseif($cache = cache_get($cid, 'cache_page')) {
// Assign to our static cache before returning result.
$result = $cache->data;
return $result;
}
}
// We need to remove our drupal_http_request() override so it doesn't result
// in an infinite recursion scenario. We then need to restore our custom
// setting after the call is complete.
global $conf;
$original_function = $conf['drupal_http_request_function'];
$conf['drupal_http_request_function'] = FALSE;
$result = call_user_func_array('drupal_http_request', $args);
$conf['drupal_http_request_function'] = $original_function;
if ($is_cacheable) {
// Be sure to save this request so we can avoid it in the future.
cache_set($cid, $result, 'cache_page');
}
return $result;
}
/**
* Implements hook_init().
*/
function http_request_cache_init() {
// Use our custom function only after the module is loaded.
global $conf;
$conf['drupal_http_request_function'] = 'http_request_cache_http_request';
}
/**
* Implements hook_http_request_is_cacheable_alter().
*/
function http_request_cache_http_request_is_cacheable_alter(&$is_cacheable, $context) {
// Try and limit to only Solr requests to minimize possible issues.
$is_cacheable &= strpos($context['url'], '/solr/') !== FALSE;
}