-
Notifications
You must be signed in to change notification settings - Fork 253
/
Copy pathEsi.php
585 lines (548 loc) · 23.9 KB
/
Esi.php
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
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
<?php
/**
* Nexcess.net Turpentine Extension for Magento
* Copyright (C) 2012 Nexcess.net L.L.C.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
class Nexcessnet_Turpentine_Model_Observer_Esi extends Varien_Event_Observer {
/**
* Set a cookie with the customer group id when customer logs in
*
* Events: customer_login
*
* @param Varien_Object $eventObject
* @return null
*/
public function setCustomerGroupCookie($eventObject) {
$customer = $eventObject->getCustomer();
$cookie = Mage::getSingleton('core/cookie');
if (Mage::getStoreConfig('persistent/options/enabled')) {
$cookie->set('customer_group', $customer->getGroupId(), Mage::getStoreConfig('persistent/options/lifetime'));
} else {
$cookie->set('customer_group', $customer->getGroupId());
}
}
/**
* Destroy the cookie with the customer group when customer logs out
*
* Events: customer_logout
*
* @param Varien_Object $eventObject
* @return null
*/
public function removeCustomerGroupCookie($eventObject) {
Mage::getSingleton('core/cookie')->delete('customer_group');
}
/**
* Check the ESI flag and set the ESI header if needed
*
* Events: http_response_send_before
*
* @param Varien_Object $eventObject
* @return null
*/
public function setFlagHeaders($eventObject) {
$response = $eventObject->getResponse();
if (Mage::helper('turpentine/esi')->shouldResponseUseEsi()) {
$response->setHeader('X-Turpentine-Esi',
Mage::registry('turpentine_esi_flag') ? '1' : '0');
Mage::helper('turpentine/debug')->logDebug(
'Set ESI flag header to: %s',
(Mage::registry('turpentine_esi_flag') ? '1' : '0') );
}
}
/**
* Allows disabling page-caching by setting the cache flag on a controller
*
* <customer_account>
* <turpentine_cache_flag value="0" />
* </customer_account>
*
* Events: controller_action_layout_generate_blocks_after
*
* @param Varien_Object $eventObject
* @return null
*/
public function checkCacheFlag($eventObject) {
if (Mage::helper('turpentine/varnish')->shouldResponseUseVarnish()) {
$layoutXml = $eventObject->getLayout()->getUpdate()->asSimplexml();
foreach ($layoutXml->xpath('//turpentine_cache_flag') as $node) {
foreach ($node->attributes() as $attr => $value) {
if ($attr == 'value') {
if ( ! (string) $value) {
Mage::register('turpentine_nocache_flag', true, true);
return; //only need to set the flag once
}
}
}
}
}
}
/**
* On controller redirects, check the target URL and set to home page
* if it would otherwise go to a getBlock URL
*
* @param Varien_Object $eventObject
* @return null
*/
public function checkRedirectUrl($eventObject) {
$esiHelper = Mage::helper('turpentine/esi');
$url = $eventObject->getTransport()->getUrl();
$referer = Mage::helper('core/http')->getHttpReferer();
$dummyUrl = $esiHelper->getDummyUrl();
$reqUenc = Mage::helper('core')->urlDecode(
Mage::app()->getRequest()->getParam('uenc') );
if ($this->_checkIsEsiUrl($url)) {
if ($this->_checkIsNotEsiUrl($reqUenc) &&
Mage::getBaseUrl() == $url) {
$newUrl = $this->_fixupUencUrl($reqUenc);
} elseif ($this->_checkIsNotEsiUrl($referer)) {
$newUrl = $referer;
} else {
$newUrl = $dummyUrl;
}
// TODO: make sure this actually looks like a URL
$eventObject->getTransport()->setUrl($newUrl);
}
if ($eventObject->getTransport()->getUrl() != $url) {
Mage::helper('turpentine/debug')->logDebug(
'Detected redirect to ESI URL, changing: %s => %s',
$url, $eventObject->getTransport()->getUrl() );
}
}
/**
* Load the cache clear events from stored config
*
* @param Varien_Object $eventObject
* @return null
*/
public function loadCacheClearEvents($eventObject) {
Varien_Profiler::start('turpentine::observer::esi::loadCacheClearEvents');
$events = Mage::helper('turpentine/esi')->getCacheClearEvents();
$appShim = Mage::getSingleton('turpentine/shim_mage_core_app');
foreach ($events as $ccEvent) {
$appShim->shim_addEventObserver('global', $ccEvent,
'turpentine_ban_'.$ccEvent, 'singleton',
'turpentine/observer_ban', 'banClientEsiCache');
}
Varien_Profiler::stop('turpentine::observer::esi::loadCacheClearEvents');
}
/**
* Add the core/messages block rewrite if the flash message fix is enabled
*
* The core/messages block is rewritten because it doesn't use a template
* we can replace with an ESI include tag, just dumps out a block of
* hard-coded HTML and also frequently skips the toHtml method
*
* @param Varien_Object $eventObject
* @return null
*/
public function addMessagesBlockRewrite($eventObject) {
if (Mage::helper('turpentine/esi')->shouldFixFlashMessages()) {
Varien_Profiler::start('turpentine::observer::esi::addMessagesBlockRewrite');
Mage::getSingleton('turpentine/shim_mage_core_app')
->shim_addClassRewrite('block', 'core', 'messages',
'Nexcessnet_Turpentine_Block_Core_Messages');
Varien_Profiler::stop('turpentine::observer::esi::addMessagesBlockRewrite');
}
}
/**
* Check the magento version and runtime env and set the replace_form_key
* flag if needed
*
* @param Varien_Object $eventObject
* @return null
*/
public function setReplaceFormKeyFlag($eventObject) {
$esiHelper = Mage::helper('turpentine/esi');
$varnishHelper = Mage::helper('turpentine/varnish');
$request = Mage::app()->getRequest();
if ($esiHelper->shouldResponseUseEsi() &&
$varnishHelper->csrfFixupNeeded() &&
! $request->isPost()) {
Mage::register('replace_form_key', true);
}
}
/**
* Replace the form key placeholder with the ESI include fragment
*
* @param Varien_Object $eventObject
* @return null
*/
public function replaceFormKeyPlaceholder($eventObject) {
if (Mage::registry('replace_form_key')) {
$esiHelper = Mage::helper('turpentine/esi');
$response = $eventObject->getResponse();
$responseBody = $response->getBody();
$responseBody = str_replace('{{form_key_esi_placeholder}}',
$esiHelper->buildEsiIncludeFragment(
$esiHelper->getFormKeyEsiUrl() ),
$responseBody);
$response->setBody($responseBody);
}
}
/**
* Encode block data in URL then replace with ESI template
*
* @link https://github.com/nexcess/magento-turpentine/wiki/ESI_Cache_Policy
*
* Events: core_block_abstract_to_html_before
*
* @param Varien_Object $eventObject
* @return null
*/
public function injectEsi($eventObject) {
$blockObject = $eventObject->getBlock();
$dataHelper = Mage::helper('turpentine/data');
$esiHelper = Mage::helper('turpentine/esi');
$debugHelper = Mage::helper('turpentine/debug');
if ($esiHelper->getEsiBlockLogEnabled()) {
$debugHelper->logInfo(
'Checking ESI block candidate: %s',
$blockObject->getNameInLayout() ? $blockObject->getNameInLayout() : $blockObject->getModuleName() );
$debugHelper->logInfo("-- block testing: shouldResponseUseEsi = ".$esiHelper->shouldResponseUseEsi());
$debugHelper->logInfo("-- block testing: instanceof Mage_Core_Block_Template = ".$blockObject instanceof Mage_Core_Block_Template);
$debugHelper->logInfo("-- block testing: Esi Options = ".print_r($blockObject->getEsiOptions(), true));
}
if ($esiHelper->shouldResponseUseEsi() &&
$blockObject instanceof Mage_Core_Block_Template &&
$esiOptions = $blockObject->getEsiOptions()) {
if ((isset($esiOptions['disableEsiInjection'])) && ($esiOptions['disableEsiInjection'] == 1)) {
if ($esiHelper->getEsiBlockLogEnabled()) {
$debugHelper->logInfo("-- ESI Injection disabled");
}
return;
}
if (Mage::app()->getStore()->getCode() == 'admin') {
// admin blocks are not allowed to be cached for now
$debugHelper->logWarn(
'Ignoring attempt to inject adminhtml block: %s',
$blockObject->getNameInLayout() ? $blockObject->getNameInLayout() : $blockObject->getModuleName() );
return;
} elseif ($esiHelper->getEsiBlockLogEnabled()) {
$debugHelper->logInfo('Block check passed, injecting block: %s',
$blockObject->getNameInLayout() ? $blockObject->getNameInLayout() : $blockObject->getModuleName());
}
Varien_Profiler::start('turpentine::observer::esi::injectEsi');
$ttlParam = $esiHelper->getEsiTtlParam();
$cacheTypeParam = $esiHelper->getEsiCacheTypeParam();
$dataParam = $esiHelper->getEsiDataParam();
$methodParam = $esiHelper->getEsiMethodParam();
$hmacParam = $esiHelper->getEsiHmacParam();
$scopeParam = $esiHelper->getEsiScopeParam();
$referrerParam = $esiHelper->getEsiReferrerParam();
$esiOptions = $this->_getDefaultEsiOptions($esiOptions);
// change the block's template to the stripped down ESI template
switch ($esiOptions[$methodParam]) {
case 'ajax':
$blockObject->setTemplate('turpentine/ajax.phtml');
break;
case 'esi':
default:
$blockObject->setTemplate('turpentine/esi.phtml');
// flag request for ESI processing
Mage::register('turpentine_esi_flag', true, true);
}
// esi data is the data needed to regenerate the ESI'd block
$esiData = $this->_getEsiData($blockObject, $esiOptions)->toArray();
ksort($esiData);
$frozenData = $dataHelper->freeze($esiData);
$urlOptions = array(
$methodParam => $esiOptions[$methodParam],
$cacheTypeParam => $esiOptions[$cacheTypeParam],
$ttlParam => $esiOptions[$ttlParam],
$hmacParam => $dataHelper->getHmac($frozenData),
$dataParam => $frozenData,
);
if ($esiOptions[$methodParam] == 'ajax') {
$urlOptions['_secure'] = Mage::app()->getStore()
->isCurrentlySecure();
}
if ($esiOptions[$scopeParam] == 'page') {
$urlOptions[$referrerParam] = Mage::helper('core')->urlEncode(
Mage::getUrl('*/*/*', array('_use_rewrite' => true, '_current' => true))
);
}
/**
* Keep params from original url
*/
$urlOptions['_query'] = Mage::app()->getRequest()->getParams();
$esiUrl = Mage::getUrl('turpentine/esi/getBlock', $urlOptions);
if ($esiOptions[$methodParam] == 'esi') {
// setting [web/unsecure/base_url] can be https://... but ESI can never be HTTPS
$esiUrl = preg_replace('|^https://|i', 'http://', $esiUrl);
}
$blockObject->setEsiUrl($esiUrl);
// avoid caching the ESI template output to prevent the double-esi-
// include/"ESI processing not enabled" bug
foreach (array('lifetime', 'tags', 'key') as $dataKey) {
$blockObject->unsetData('cache_'.$dataKey);
}
if (strlen($esiUrl) > 2047) {
Mage::helper('turpentine/debug')->logWarn(
'ESI url is probably too long (%d > 2047 characters): %s',
strlen($esiUrl), $esiUrl );
}
Varien_Profiler::stop('turpentine::observer::esi::injectEsi');
} // else handle the block like normal and cache it inline with the page
}
/**
* Generate ESI data to be encoded in URL
*
* @param Mage_Core_Block_Template $blockObject
* @param array $esiOptions
* @return Varien_Object
*/
protected function _getEsiData($blockObject, $esiOptions) {
Varien_Profiler::start('turpentine::observer::esi::_getEsiData');
$esiHelper = Mage::helper('turpentine/esi');
$cacheTypeParam = $esiHelper->getEsiCacheTypeParam();
$scopeParam = $esiHelper->getEsiScopeParam();
$methodParam = $esiHelper->getEsiMethodParam();
$esiData = new Varien_Object();
$esiData->setStoreId(Mage::app()->getStore()->getId());
$esiData->setDesignPackage(Mage::getDesign()->getPackageName());
$esiData->setDesignTheme(Mage::getDesign()->getTheme('layout'));
$esiData->setNameInLayout($blockObject->getNameInLayout());
$esiData->setBlockType(get_class($blockObject));
$esiData->setLayoutHandles($this->_getBlockLayoutHandles($blockObject));
$esiData->setEsiMethod($esiOptions[$methodParam]);
if ($esiOptions[$cacheTypeParam] == 'private' || $esiOptions[$cacheTypeParam] == 'customer_group') {
if (is_array(@$esiOptions['flush_events'])) {
$esiData->setFlushEvents(array_merge(
$esiHelper->getDefaultCacheClearEvents(),
array_keys($esiOptions['flush_events']) ));
} else {
$esiData->setFlushEvents(
$esiHelper->getDefaultCacheClearEvents() );
}
}
if ($esiOptions[$scopeParam] == 'page') {
$esiData->setParentUrl(Mage::app()->getRequest()->getRequestString());
}
if (is_array($esiOptions['dummy_blocks'])) {
$dummyBlocks = array();
foreach ($esiOptions['dummy_blocks'] as $key => $value) {
$dummyBlocks[] = (empty($value) && ! is_numeric($key)) ? $key : $value;
}
$esiData->setDummyBlocks($dummyBlocks);
} else {
Mage::helper('turpentine/debug')->logWarn(
'Invalid dummy_blocks for block: %s',
$blockObject->getNameInLayout() );
}
$simpleRegistry = array();
$complexRegistry = array();
if (is_array($esiOptions['registry_keys'])) {
foreach ($esiOptions['registry_keys'] as $key => $options) {
$value = Mage::registry($key);
if ($value) {
if (is_object($value) &&
$value instanceof Mage_Core_Model_Abstract) {
$complexRegistry[$key] =
$this->_getComplexRegistryData($options, $value);
} else {
$simpleRegistry[$key] = $value;
}
}
}
} else {
Mage::helper('turpentine/debug')->logWarn(
'Invalid registry_keys for block: %s',
$blockObject->getNameInLayout() );
}
$esiData->setSimpleRegistry($simpleRegistry);
$esiData->setComplexRegistry($complexRegistry);
Varien_Profiler::stop('turpentine::observer::esi::_getEsiData');
return $esiData;
}
/**
* Get the active layout handles for this block and any child blocks
*
* This is probably kind of slow since it uses a bunch of xpath searches
* but this was the easiest way to get the info needed. Should be a target
* for future optimization
*
* There is an issue with encoding the used handles in the URL, if the used
* handles change (ex customer logs in), the cached version of the page will
* still have the old handles encoded in it's ESI url. This can lead to
* weirdness like the "Log in" link displaying for already logged in
* visitors on pages that were initially visited by not-logged-in visitors.
* Not sure of a solution for this yet.
*
* Above problem is currently solved by EsiController::_swapCustomerHandles()
* but it would be best to find a more general solution to this.
*
* @param Mage_Core_Block_Template $block
* @return array
*/
protected function _getBlockLayoutHandles($block) {
Varien_Profiler::start('turpentine::observer::esi::_getBlockLayoutHandles');
$layout = $block->getLayout();
$layoutXml = Mage::helper('turpentine/esi')->getLayoutXml();
$activeHandles = array();
// get the xml node representing the block we're working on (from the
// default handle probably)
$blockNode = Mage::helper('turpentine/esi')->getEsiLayoutBlockNode(
$layout, $block->getNameInLayout());
$childBlocks = Mage::helper('turpentine/data')
->getChildBlockNames($blockNode);
foreach ($childBlocks as $blockName) {
foreach ($layout->getUpdate()->getHandles() as $handle) {
// check if this handle has any block or reference tags that
// refer to this block or a child block, unless the handle name
// is blank
if ($handle !== '' && (strpos($handle, 'THEME') === 0 ||
$layoutXml->xpath(sprintf(
'//%s//*[@name=\'%s\']', $handle, $blockName )))) {
$activeHandles[] = $handle;
}
}
}
if ( ! $activeHandles) {
$activeHandles[] = 'default';
}
Varien_Profiler::stop('turpentine::observer::esi::_getBlockLayoutHandles');
return array_unique($activeHandles);
}
/**
* Get the default ESI options
*
* @return array
*/
protected function _getDefaultEsiOptions($options) {
$esiHelper = Mage::helper('turpentine/esi');
$ttlParam = $esiHelper->getEsiTtlParam();
$methodParam = $esiHelper->getEsiMethodParam();
$cacheTypeParam = $esiHelper->getEsiCacheTypeParam();
$defaults = array(
$esiHelper->getEsiMethodParam() => 'esi',
$esiHelper->getEsiScopeParam() => 'global',
$esiHelper->getEsiCacheTypeParam() => 'public',
'dummy_blocks' => array(),
'registry_keys' => array(),
);
$options = array_merge($defaults, $options);
// set the default TTL
if ( ! isset($options[$ttlParam])) {
if ($options[$cacheTypeParam] == 'private' || $options[$cacheTypeParam] == 'customer_group') {
switch ($options[$methodParam]) {
case 'ajax':
$options[$ttlParam] = '0';
break;
case 'esi':
default:
$options[$ttlParam] = $esiHelper->getDefaultEsiTtl();
break;
}
} else {
$options[$ttlParam] = Mage::helper('turpentine/varnish')
->getDefaultTtl();
}
}
return $options;
}
/**
* Get the complex registry entry data
*
* @param array $valueOptions
* @param mixed $value
* @return array
*/
protected function _getComplexRegistryData($valueOptions, $value) {
$idMethod = @$valueOptions['id_method'] ?
$valueOptions['id_method'] : 'getId';
$model = @$valueOptions['model'] ?
$valueOptions['model'] : Mage::helper('turpentine/data')
->getModelName($value);
$data = array(
'model' => $model,
'id' => $value->{$idMethod}(),
);
return $data;
}
/**
* Fix a URL to ensure it uses Magento's base URL instead of the backend
* URL
*
* @param string $uencUrl
* @return string
*/
protected function _fixupUencUrl($uencUrl) {
$esiHelper = Mage::helper('turpentine/esi');
$corsOrigin = $esiHelper->getCorsOrigin();
if ($corsOrigin != $esiHelper->getCorsOrigin($uencUrl)) {
return $corsOrigin.parse_url($uencUrl, PHP_URL_PATH);
} else {
return $uencUrl;
}
}
/**
* Check if a URL *is not* for the /turpentine/esi/getBlock/ action
*
* @param string $url
* @return bool
*/
protected function _checkIsNotEsiUrl($url) {
return $url && ! preg_match('~/turpentine/esi/getBlock/~', $url);
}
/**
* Check if a URL *is* for the /turpentine/esi/getBlock/ action
*
* @param string $url
* @return bool
*/
protected function _checkIsEsiUrl($url) {
return ! $this->_checkIsNotEsiUrl($url);
}
public function hookToControllerActionPreDispatch($observer) {
if (Mage::helper('turpentine/data')->getVclFix() == 0 && $observer->getEvent()->getControllerAction()->getFullActionName() == 'checkout_cart_add') {
Mage::dispatchEvent("add_to_cart_before", array('request' => $observer->getControllerAction()->getRequest()));
}
if ($observer->getEvent()->getControllerAction()->getFullActionName() == 'wishlist_index_index') {
Mage::dispatchEvent('wishlist_index_index_before', array('request' => $observer->getControllerAction()->getRequest()));
}
}
public function hookToControllerActionPostDispatch($observer) {
if ($observer->getEvent()->getControllerAction()->getFullActionName() == 'checkout_cart_add') {
Mage::dispatchEvent("add_to_cart_after", array('request' => $observer->getControllerAction()->getRequest()));
}
}
public function hookToAddToCartBefore($observer) {
//Mage::log("hookToAddToCartBefore-antes ".print_r($observer->getEvent()->getRequest()->getParams(),true)." will be added to cart.", null, 'carrinho.log', true);
$key = Mage::getSingleton('core/session')->getFormKey();
$observer->getEvent()->getRequest()->setParam('form_key', $key);
$request = $observer->getEvent()->getRequest()->getParams();
//Mage::log("hookToAddToCartBefore ".print_r($request,true)." will be added to cart.", null, 'carrinho.log', true);
}
public function hookToAddToCartAfter($observer) {
$request = $observer->getEvent()->getRequest()->getParams();
//Mage::log("hookToAddToCartAfter ".print_r($request,true)." is added to cart.", null, 'carrinho.log', true);
}
/**
* Set the form key on the add to wishlist request
*
* @param $observer
*
* @return Nexcessnet_Turpentine_Model_Observer_Esi
*/
public function hookToAddToWishlistBefore($observer)
{
$key = Mage::getSingleton('core/session')->getFormKey();
$observer->getEvent()->getRequest()->setParam('form_key', $key);
return $this;
}
}