-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathblockcache_stale.module
executable file
·398 lines (356 loc) · 13.9 KB
/
blockcache_stale.module
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
<?php
// $Id: blockcache_stale.module,v 1.1.2.6 2010/08/05 08:03:29 yhahn Exp $
/**
* Implements hook_init().
* Load all dependencies from composer (at least Guzzle)
*/
function blockcache_stale_init() {
require __DIR__ . '/vendor/autoload.php';
}
/**
* Implements hook_context_plugins().
* This is a ctools plugins hook.
*
* It declares that the site should use this class of context reaction block
* The only means of this class (in compareason of context_blockcache_alter_reaction_block's one
* is to call blockcache_stale_block_render_blocks instead of default drupal core block module.
*/
function blockcache_stale_context_plugins() {
return array(
'blockcache_stale_reaction_block' => array(
'handler' => array(
'path' => drupal_get_path('module', 'blockcache_stale') . '/plugins',
'file' => 'blockcache_stale_reaction_block.inc',
'class' => 'blockcache_stale_reaction_block',
'parent' => 'context_blockcache_alter_reaction_block',
),
),
);
}
/**
* Implements hook_context_registry_alter().
*/
function blockcache_stale_context_registry_alter(&$registry) {
if (isset($registry['reactions']['block'])) {
$registry['reactions']['block']['plugin'] = 'blockcache_stale_reaction_block';
}
}
/**
* Call zeromq to clear specifics blocs on one page
*
* @param array $bid array of block id to be cleaed on the $page
* @param string $page the concerned relative url page
*/
function blockcache_stale_clear_blocks($bid, $page) {
$params = array(
'session_id' => uniqid(),
'blocks' => $bid,
'page' => $page
);
blockcache_stale_zmq_ping('clear-blocks', $params);
}
/**
* Call zeromq to clear specifics pages
*
* @param array $pages array of pages to be cleared
*/
function blockcache_stale_clear_page($pages) {
$params = array(
'session_id' => uniqid(),
'pages' => $pages
);
blockcache_stale_zmq_ping('clear-pages', $params);
}
function blockcache_stale_zmq_ping($action, $params) {
static $daemon_url;
$actions = func_get_args();
$msg = $actions[0];
$actions[0] = 'from:drupal/msg:' . $msg;
$actions[1] = '' . serialize($params);
$ctx = new ZMQContext();
$socket = new ZMQSocket($ctx, ZMQ::SOCKET_PUSH);
if (empty($daemon_url)) {
$daemon_url = variable_get('blockcache_stale_zmq_connect_url', 'tcp://localhost:1234');
}
$socket->connect($daemon_url);
$socket->sendMulti($actions);
watchdog('blockcache_stale', 'ping clear block: %msg', array('%msg' => $msg), WATCHDOG_NOTICE, $link = NULL);
echo $action;
}
function blockcache_stale_regenerate_blocks($params = array()) {
// build the url
$url = url(
$params['page'],
array(
'absolute' => true,
'query' => array(
'blockcache_stale_block' => $params['blocks'], // it's an array
'blockcache_stale_session_id' => $params['session_id'],
)
)
);
$start = microtime(TRUE);
$client = new Guzzle\Http\Client($url);
$response = $client->head()->send();
printf(
"%s %s: %s — blocks: %s (in %ss)\n",
$response->getStatusCode(),
$response->getReasonPhrase(),
$params['page'],
implode(', ', $params['blocks']),
round(microtime(TRUE) - $start, 2)
);
}
function blockcache_stale_regenerate_page($params = array()) {
foreach ($params['pages'] as $page) {
if (is_array($page)) {
// handle specifics blocks in pages
foreach($page as $block) {
$block['session_id'] = $params['session_id'];
blockcache_stale_regenerate_blocks($block);
}
continue;
}
$url = url(
$page,
array(
'absolute' => true,
'query' => array(
'blockcache_stale_page' => 1,
'blockcache_stale_session_id' => $params['session_id'],
)
)
);
$start = microtime(TRUE);
$client = new Guzzle\Http\Client($url);
$response = $client->head()->send();
printf("%s %s: %s (in %ss)\n", $response->getStatusCode(), $response->getReasonPhrase(), $page, round(microtime(TRUE) - $start, 2));
}
}
/**
* Render the content and subject for a set of blocks.
* **OVERRIDE** by bjaillot for:
* - never reset cache, but instead regenerate it
* - set cache to be CACHE_PERMANENT instead of CACHE_TEMPORARY
*
* @param $region_blocks
* An array of block objects such as returned for one region by _block_load_blocks().
*
* @return
* An array of visible blocks as expected by drupal_render().
*/
function blockcache_stale_block_render_blocks($region_blocks) {
if ($_SERVER['REQUEST_METHOD'] != 'HEAD' && !(isset($_GET['blockcache_stale_block']) || isset($_GET['blockcache_stale_page']))) { //TODO check this condition
// use default render block if not in condition of blockcache_stale
return blockcache_stale_original_block_render_blocks($region_blocks);
}
// Block caching is not compatible with node access modules. We also
// preserve the submission of forms in blocks, by fetching from cache only
// if the request method is 'GET' (or 'HEAD').
$cacheable = !count(module_implements('node_grants')) && ($_SERVER['REQUEST_METHOD'] == 'GET' || $_SERVER['REQUEST_METHOD'] == 'HEAD');
foreach ($region_blocks as $key => $block) {
// Render the block content if it has not been created already.
if (_blockcache_stale_is_useful_to_regenerate_cache($key, $block)) {
// Erase the block from the static array - we'll put it back if it has
// content.
unset($region_blocks[$key]);
// Try fetching the block from cache.
if ($cacheable && ($cid = blockcache_stale_block_get_cache_id($block))) {
$array = module_invoke($block->module, 'block_view', $block->delta);
// Allow modules to modify the block before it is viewed, via either
// hook_block_view_alter() or hook_block_view_MODULE_DELTA_alter().
drupal_alter(array('block_view', "block_view_{$block->module}_{$block->delta}"), $array, $block);
if (isset($cid)) {
cache_set($cid, $array, 'cache_block', CACHE_PERMANENT);
}
}
}
}
return array(); //$region_blocks; // we don't care about returning anything
}
/**
* Decide whether or not a block is supposed to be regenerated
*
* @param string $key the block_id
* @param object $block the block object
* @return boolean is the block supposed to be regenerated
*/
function _blockcache_stale_is_useful_to_regenerate_cache($key, $block) {
// already generated block or no cache at all, skip the block
if (isset($block->content) || $block->cache < 1) {
return false;
}
// a not demanded block, skip it
if (isset($_GET['blockcache_stale_block']) && !in_array($key, $_GET['blockcache_stale_block'])) {
return false;
}
// for global block, ensure that they are setted exactly one time in a session of multiple page
if ($block->cache == 1) {
$session_id = $_GET['blockcache_stale_session_id'];
// TODO using variables is BAD for performance! => use a direct cache_get / cache_set?
$blocks_already_generated = variable_get('blockcache_stale_' . $session_id, array());
if (isset($blocks_already_generated[$key])) {
// watchdog('blockcache_stale', 'block already_generated: %msg', array('%msg' => print_r($blocks_already_generated, true)), WATCHDOG_NOTICE, $link = NULL);
return false;
}
$blocks_already_generated[$key] = true;
variable_set('blockcache_stale_' . $session_id, $blocks_already_generated);
}
return true;
}
/**
* Render the content and subject for a set of blocks.
* **OVERRIDE** by bjaillot for:
* - use custom _block_get_cache_id
* - set cache to be CACHE_PERMANENT instead of CACHE_TEMPORARY
*
* @param $region_blocks
* An array of block objects such as returned for one region by _block_load_blocks().
*
* @return
* An array of visible blocks as expected by drupal_render().
*/
function blockcache_stale_original_block_render_blocks($region_blocks) {
// Block caching is not compatible with node access modules. We also
// preserve the submission of forms in blocks, by fetching from cache only
// if the request method is 'GET' (or 'HEAD').
$cacheable = !count(module_implements('node_grants')) && ($_SERVER['REQUEST_METHOD'] == 'GET' || $_SERVER['REQUEST_METHOD'] == 'HEAD');
foreach ($region_blocks as $key => $block) {
// Render the block content if it has not been created already.
if (!isset($block->content)) {
// Erase the block from the static array - we'll put it back if it has
// content.
unset($region_blocks[$key]);
// Try fetching the block from cache.
// if ($cacheable && ($cid = _block_get_cache_id($block)) && ($cache = cache_get($cid, 'cache_block'))) { // CHANGED
if ($cacheable && ($cid = blockcache_stale_block_get_cache_id($block)) && ($cache = cache_get($cid, 'cache_block'))) {
$array = $cache->data;
}
else {
$array = module_invoke($block->module, 'block_view', $block->delta);
// Allow modules to modify the block before it is viewed, via either
// hook_block_view_alter() or hook_block_view_MODULE_DELTA_alter().
drupal_alter(array('block_view', "block_view_{$block->module}_{$block->delta}"), $array, $block);
if (isset($cid)) {
// cache_set($cid, $array, 'cache_block', CACHE_TEMPORARY); // ORIGINAL
cache_set($cid, $array, 'cache_block', CACHE_PERMANENT); // CHANGED
}
}
if (isset($array) && is_array($array)) {
foreach ($array as $k => $v) {
$block->$k = $v;
}
}
if (isset($block->content) && $block->content) {
// Normalize to the drupal_render() structure.
if (is_string($block->content)) {
$block->content = array('#markup' => $block->content);
}
// Override default block title if a custom display title is present.
if ($block->title) {
// Check plain here to allow module generated titles to keep any
// markup.
$block->subject = $block->title == '<none>' ? '' : check_plain($block->title);
}
if (!isset($block->subject)) {
$block->subject = '';
}
$region_blocks["{$block->module}_{$block->delta}"] = $block;
}
}
}
return $region_blocks;
}
/**
* Assemble the cache_id to use for a given block.
*
* The cache_id string reflects the viewing context for the current block
* instance, obtained by concatenating the relevant context information
* (user, page, ...) according to the block's cache settings (BLOCK_CACHE_*
* constants). Two block instances can use the same cached content when
* they share the same cache_id.
*
* Theme and language contexts are automatically differentiated.
*
* @param $block
* @return
* The string used as cache_id for the block.
*/
function blockcache_stale_block_get_cache_id($block) {
global $user;
// User 1 being out of the regular 'roles define permissions' schema,
// it brings too many chances of having unwanted output get in the cache
// and later be served to other users. We therefore exclude user 1 from
// block caching.
if (variable_get('block_cache', FALSE) && !in_array($block->cache, array(DRUPAL_NO_CACHE, DRUPAL_CACHE_CUSTOM)) && $user->uid != 1) {
// Start with common sub-patterns: block identification, theme, language.
$cid_parts[] = $block->module;
$cid_parts[] = $block->delta;
$drupal_cid_parts = drupal_render_cid_parts($block->cache);
$cid_parts = array_merge($cid_parts, $drupal_cid_parts);
$string_cid_parts = implode(':', $cid_parts);
// remove blockcache_stale tokens
$string_cid_parts = preg_replace('/[\?\&]*blockcache_stale_(?:block|page|session_id)(?:%5B[0-9]*%5D)?=(?:.*)/', '', $string_cid_parts);
return $string_cid_parts;
}
}
/**
* Implements hook_form_alter().
*
* Change node_form_submit callback just to override
* the block and page cache clearing after each node
* form submit
*
* @see http://drupalcode.org/project/performance_hacks.git/blob/HEAD:/performance_hacks.module
*/
function blockcache_stale_form_alter(&$form, $form_state, $form_id) {
if (!empty($form['#node_edit_form'])) {
$node_form_submit = array_search('node_form_submit', $form['actions']['submit']['#submit']);
if ($node_form_submit !== FALSE) {
$form['actions']['submit']['#submit'][$node_form_submit] = 'blockcache_stale_node_form_submit';
}
}
}
/**
* Exact copy of node_form_submit, except for cache clearing.
* Do not clear block and page cache because we are overriding
* by daemon script.
* This way, cache are never deleted, but they are overriden
* by the daemon script so cache is always existing and perfectly
* up to date.
*
* The only change with the original node_form_submit is the last
* line commented
*
* @see http://drupalcode.org/project/performance_hacks.git/blob/HEAD:/performance_hacks.module
*/
function blockcache_stale_node_form_submit($form, &$form_state) {
$node = node_form_submit_build_node($form, $form_state);
$insert = empty($node->nid);
node_save($node);
$node_link = l(t('view'), 'node/' . $node->nid);
$watchdog_args = array('@type' => $node->type, '%title' => $node->title);
$t_args = array('@type' => node_type_get_name($node), '%title' => $node->title);
if ($insert) {
watchdog('content', '@type: added %title.', $watchdog_args, WATCHDOG_NOTICE, $node_link);
drupal_set_message(t('@type %title has been created.', $t_args));
}
else {
watchdog('content', '@type: updated %title.', $watchdog_args, WATCHDOG_NOTICE, $node_link);
drupal_set_message(t('@type %title has been updated.', $t_args));
}
if ($node->nid) {
$form_state['values']['nid'] = $node->nid;
$form_state['nid'] = $node->nid;
$form_state['redirect'] = 'node/' . $node->nid;
}
else {
// In the unlikely case something went wrong on save, the node will be
// rebuilt and node form redisplayed the same way as in preview.
drupal_set_message(t('The post could not be saved.'), 'error');
$form_state['rebuild'] = TRUE;
}
// Only change from Drupal core - try to keep this updated.
// Clear the page and block caches.
//cache_clear_all();
}