From fa1198d7f76dbc9c8367d6ea3a8263ead99a34e1 Mon Sep 17 00:00:00 2001 From: aricwatson Date: Tue, 13 Oct 2015 14:03:58 -0400 Subject: [PATCH 01/18] Added disableEsiInjection update to changelog Forgot to update changelog when this was merged in. --- CHANGELOG.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index cb1ac3a99..09c912622 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -419,4 +419,5 @@ Magento CE 1.8+ or EE 1.13+, see [these instructions](https://github.com/nexcess * [#945] Send unmodified url to the backend server (@thampe) * [#885] Add maintenance mode that will allow debug_ips through to visit the site, all other users get the landing page (@craigcarnell) * [#955] Include theme specific handles to ESI data (@LyndonHook) - * [#972] Fixed bug with wrong return value of ->getSkinUrl() (@ceckoslab) + * [#972] Fixed bug with wrong return value of ->getSkinUrl() (@ceckoslab) + * [#951] Added 'disableEsiInjection' ESI policy option. From 2cbfb6a3730bd279280c5ac7ac6e70c5b2f2338e Mon Sep 17 00:00:00 2001 From: mbalparda Date: Thu, 15 Oct 2015 09:39:30 -0300 Subject: [PATCH 02/18] refs Added Scrutinizer. --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 1a9d5d59a..54c8dcfa5 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,6 @@ # [Nexcess.net](https://www.nexcess.net/) Turpentine Extension for Magento [![Build Status](https://travis-ci.org/nexcess/magento-turpentine.png?branch=master,devel)](https://travis-ci.org/nexcess/magento-turpentine) +[![Scrutinizer](https://scrutinizer-ci.com/g/nexcess/magento-turpentine/badges/quality-score.png?b=master)](https://scrutinizer-ci.com/g/nexcess/magento-turpentine/) Turpentine is a full page cache extension for [Magento](https://www.magentocommerce.com/) that works with [Varnish](https://www.varnish-cache.org/), a very fast caching reverse-proxy. By From f944c8ed44a436d0828fd2b136255c7b696ff241 Mon Sep 17 00:00:00 2001 From: Scrutinizer Auto-Fixer Date: Thu, 15 Oct 2015 13:11:14 +0000 Subject: [PATCH 03/18] Scrutinizer Auto-Fixes This commit consists of patches automatically generated for this project on https://scrutinizer-ci.com --- .../Turpentine/Block/Adminhtml/Cache/Grid.php | 8 +- .../Turpentine/Block/Core/Messages.php | 130 +++--- .../Turpentine/Block/Management.php | 10 +- .../Turpentine/Block/Poll/ActivePoll.php | 4 +- .../Turpentine/Block/Product/Compared.php | 2 +- .../Turpentine/Block/Product/Viewed.php | 2 +- .../Nexcessnet/Turpentine/Helper/Ban.php | 24 +- .../Nexcessnet/Turpentine/Helper/Cron.php | 124 +++--- .../Nexcessnet/Turpentine/Helper/Data.php | 180 ++++---- .../Nexcessnet/Turpentine/Helper/Debug.php | 197 +++++---- .../Nexcessnet/Turpentine/Helper/Esi.php | 139 +++--- .../Nexcessnet/Turpentine/Helper/Varnish.php | 66 +-- .../Model/Config/Select/StripWhitespace.php | 6 +- .../Model/Config/Select/Version.php | 2 +- .../Turpentine/Model/Core/Session.php | 6 +- .../Turpentine/Model/Dummy/Request.php | 175 ++++---- .../Turpentine/Model/Observer/Ban.php | 230 +++++----- .../Turpentine/Model/Observer/Cron.php | 42 +- .../Turpentine/Model/Observer/Debug.php | 12 +- .../Turpentine/Model/Observer/Esi.php | 270 ++++++------ .../Turpentine/Model/Observer/Varnish.php | 70 +-- .../Model/PageCache/Container/Notices.php | 4 +- .../Nexcessnet/Turpentine/Model/Session.php | 37 +- .../Turpentine/Model/Shim/Mage/Core/App.php | 74 ++-- .../Model/Shim/Mage/Core/Config.php | 4 +- .../Model/Shim/Mage/Core/Layout.php | 16 +- .../Turpentine/Model/Varnish/Admin.php | 68 +-- .../Turpentine/Model/Varnish/Admin/Socket.php | 221 +++++----- .../Model/Varnish/Configurator/Abstract.php | 404 +++++++++--------- .../Model/Varnish/Configurator/Version2.php | 2 +- .../Model/Varnish/Configurator/Version3.php | 14 +- .../Model/Varnish/Configurator/Version4.php | 2 +- .../controllers/Adminhtml/CacheController.php | 12 +- .../Turpentine/controllers/EsiController.php | 220 +++++----- .../Varnish/ManagementController.php | 120 +++--- contrib/tools/esi-decoder.php | 40 +- util/varnishadm.php | 22 +- 37 files changed, 1479 insertions(+), 1480 deletions(-) diff --git a/app/code/community/Nexcessnet/Turpentine/Block/Adminhtml/Cache/Grid.php b/app/code/community/Nexcessnet/Turpentine/Block/Adminhtml/Cache/Grid.php index 07a045dcc..d25bb7b78 100644 --- a/app/code/community/Nexcessnet/Turpentine/Block/Adminhtml/Cache/Grid.php +++ b/app/code/community/Nexcessnet/Turpentine/Block/Adminhtml/Cache/Grid.php @@ -19,20 +19,20 @@ protected function _prepareCollection() $fullPageEnabled = false; foreach ($collection as $key=>$item) { - if($item->getStatus()==1 && ($item->getId()=='turpentine_pages' || $item->getId()=='turpentine_esi_blocks')) + if ($item->getStatus() == 1 && ($item->getId() == 'turpentine_pages' || $item->getId() == 'turpentine_esi_blocks')) { $turpentineEnabled = true; } - if($item->getStatus()==1 && $item->getId()=='full_page') + if ($item->getStatus() == 1 && $item->getId() == 'full_page') { $fullPageEnabled = true; } } - if($turpentineEnabled) + if ($turpentineEnabled) { $collection->removeItemByKey('full_page'); } - if($fullPageEnabled) + if ($fullPageEnabled) { $collection->removeItemByKey('turpentine_pages'); $collection->removeItemByKey('turpentine_esi_blocks'); diff --git a/app/code/community/Nexcessnet/Turpentine/Block/Core/Messages.php b/app/code/community/Nexcessnet/Turpentine/Block/Core/Messages.php index b09ecd45a..d330623e4 100644 --- a/app/code/community/Nexcessnet/Turpentine/Block/Core/Messages.php +++ b/app/code/community/Nexcessnet/Turpentine/Block/Core/Messages.php @@ -25,13 +25,13 @@ class Nexcessnet_Turpentine_Block_Core_Messages extends Mage_Core_Block_Messages * can't use null because that is the default so no way to tell between * the default and not actually calling it */ - const NO_SINGLE_RENDER_TYPE = -1; + const NO_SINGLE_RENDER_TYPE = -1; /** * Hold the message type to call getHtml with * @var mixed */ - protected $_singleRenderType = null; + protected $_singleRenderType = null; /** * Sentinel to check if the toHtml method was skipped (getGroupedHtml was @@ -41,7 +41,7 @@ class Nexcessnet_Turpentine_Block_Core_Messages extends Mage_Core_Block_Messages * * @var boolean */ - protected $_directCall = false; + protected $_directCall = false; /** * List of session types to load messages from for the "messages" block. @@ -65,10 +65,10 @@ class Nexcessnet_Turpentine_Block_Core_Messages extends Mage_Core_Block_Messages * * @var array */ - protected $_usedStorageTypes = array( 'core/session' ); + protected $_usedStorageTypes = array('core/session'); public function _prepareLayout() { - if( $this->_fixMessages() ) { + if ($this->_fixMessages()) { /* do nothing */ return $this; } else { @@ -82,11 +82,11 @@ public function _prepareLayout() { * @param Mage_Core_Model_Message_Collection $messages * @return Mage_Core_Block_Messages */ - public function setMessages( Mage_Core_Model_Message_Collection $messages ) { - if( $this->_fixMessages() ) { - $this->_saveMessages( $messages->getItems() ); + public function setMessages(Mage_Core_Model_Message_Collection $messages) { + if ($this->_fixMessages()) { + $this->_saveMessages($messages->getItems()); } else { - parent::setMessages( $messages ); + parent::setMessages($messages); } return $this; } @@ -97,11 +97,11 @@ public function setMessages( Mage_Core_Model_Message_Collection $messages ) { * @param Mage_Core_Model_Message_Collection $messages * @return Mage_Core_Block_Messages */ - public function addMessages( Mage_Core_Model_Message_Collection $messages ) { - if( $this->_fixMessages() ) { - $this->_saveMessages( $messages->getItems() ); + public function addMessages(Mage_Core_Model_Message_Collection $messages) { + if ($this->_fixMessages()) { + $this->_saveMessages($messages->getItems()); } else { - parent::addMessages( $messages ); + parent::addMessages($messages); } return $this; } @@ -112,11 +112,11 @@ public function addMessages( Mage_Core_Model_Message_Collection $messages ) { * @param Mage_Core_Model_Message_Abstract $message * @return Mage_Core_Block_Messages */ - public function addMessage( Mage_Core_Model_Message_Abstract $message ) { - if( $this->_fixMessages() ) { - $this->_saveMessages( array( $message ) ); + public function addMessage(Mage_Core_Model_Message_Abstract $message) { + if ($this->_fixMessages()) { + $this->_saveMessages(array($message)); } else { - parent::addMessage( $message ); + parent::addMessage($message); } return $this; } @@ -125,12 +125,11 @@ public function addMessage( Mage_Core_Model_Message_Abstract $message ) { * Override this in case some dumb layout decides to use it instead of the * standard toHtml stuff * - * @param mixed $type=self::NO_SINGLE_RENDER_TYPE * @return string */ - public function getHtml( $type=self::NO_SINGLE_RENDER_TYPE ) { + public function getHtml($type = self::NO_SINGLE_RENDER_TYPE) { $this->_singleRenderType = $type; - return $this->_handleDirectCall( 'getHtml' )->toHtml(); + return $this->_handleDirectCall('getHtml')->toHtml(); } /** @@ -140,7 +139,7 @@ public function getHtml( $type=self::NO_SINGLE_RENDER_TYPE ) { * @return string */ public function getGroupedHtml() { - return $this->_handleDirectCall( 'getGroupedHtml' )->toHtml(); + return $this->_handleDirectCall('getGroupedHtml')->toHtml(); } /** @@ -150,37 +149,38 @@ public function getGroupedHtml() { * * @param string $type */ - public function addStorageType( $type ) { + public function addStorageType($type) { $this->_usedStorageTypes[] = $type; } /** * Load layout options * - * @return null + * @param string $methodCalled + * @return Nexcessnet_Turpentine_Block_Core_Messages */ - protected function _handleDirectCall( $methodCalled ) { + protected function _handleDirectCall($methodCalled) { // this doesn't actually do anything because _real_toHtml() won't be // called in this request context (unless the flash message isn't // actually supposed to be ajax/esi'd in) $this->_directCall = $methodCalled; - if( $this->_fixMessages() ) { + if ($this->_fixMessages()) { $layout = $this->getLayout(); - $layoutUpdate = $layout->getUpdate()->load( 'default' ); - if( Mage::app()->useCache( 'layout' ) ) { + $layoutUpdate = $layout->getUpdate()->load('default'); + if (Mage::app()->useCache('layout')) { // this is skipped in the layout update load() if the "layout" // cache is enabled, which seems to cause the esi layout stuff // to not load, so we manually do it here - foreach( $layoutUpdate->getHandles() as $handle ) { - $layoutUpdate->merge( $handle ); + foreach ($layoutUpdate->getHandles() as $handle) { + $layoutUpdate->merge($handle); } } $layout->generateXml(); - $layoutShim = Mage::getSingleton( 'turpentine/shim_mage_core_layout' ); - foreach( $layout->getNode()->xpath( - sprintf( '//reference[@name=\'%s\']/action', - $this->getNameInLayout() ) ) as $node ) { - $layoutShim->shim_generateAction( $node ); + $layoutShim = Mage::getSingleton('turpentine/shim_mage_core_layout'); + foreach ($layout->getNode()->xpath( + sprintf('//reference[@name=\'%s\']/action', + $this->getNameInLayout()) ) as $node) { + $layoutShim->shim_generateAction($node); } } return $this; @@ -192,13 +192,13 @@ protected function _handleDirectCall( $methodCalled ) { * @return string */ protected function _toHtml() { - if( $this->_fixMessages() ) { - if( $this->_shouldUseInjection() ) { + if ($this->_fixMessages()) { + if ($this->_shouldUseInjection()) { $html = $this->renderView(); } else { $this->_loadMessages(); $this->_loadSavedMessages(); - if ( count($this->getMessages()) ) { + if (count($this->getMessages())) { $html = $this->_real_toHtml(); } else { // Prevent returning an empty
    @@ -219,7 +219,7 @@ protected function _toHtml() { */ protected function _hasInjectOptions() { return $this->getEsiOptions() && - Mage::helper( 'turpentine/esi' )->shouldResponseUseEsi(); + Mage::helper('turpentine/esi')->shouldResponseUseEsi(); } /** @@ -241,7 +241,7 @@ protected function _shouldUseInjection() { * @return boolean */ protected function _hasTemplateSet() { - return (bool)$this->getTemplate(); + return (bool) $this->getTemplate(); } /** @@ -249,10 +249,10 @@ protected function _hasTemplateSet() { * * @return null */ - protected function _saveMessages( $messages ) { - if( $this->_fixMessages() && !$this->_isEsiRequest() ) { - Mage::getSingleton( 'turpentine/session' ) - ->saveMessages( $this->getNameInLayout(), $messages ); + protected function _saveMessages($messages) { + if ($this->_fixMessages() && ! $this->_isEsiRequest()) { + Mage::getSingleton('turpentine/session') + ->saveMessages($this->getNameInLayout(), $messages); } } @@ -262,14 +262,14 @@ protected function _saveMessages( $messages ) { * @return null */ protected function _loadMessages() { - if( $this->getNameInLayout() == 'messages' ) { - foreach( $this->_messageStorageTypes as $type ) { - $storage = sprintf( '%s/session', $type ); - $this->addStorageType( $storage ); - $this->_loadMessagesFromStorage( $storage ); + if ($this->getNameInLayout() == 'messages') { + foreach ($this->_messageStorageTypes as $type) { + $storage = sprintf('%s/session', $type); + $this->addStorageType($storage); + $this->_loadMessagesFromStorage($storage); } } else { - $this->_loadMessagesFromStorage( 'core/session' ); + $this->_loadMessagesFromStorage('core/session'); } } @@ -279,9 +279,9 @@ protected function _loadMessages() { * @return null */ protected function _loadSavedMessages() { - $session = Mage::getSingleton( 'turpentine/session' ); - foreach( $session->loadMessages( $this->getNameInLayout() ) as $msg ) { - parent::addMessage( $msg ); + $session = Mage::getSingleton('turpentine/session'); + foreach ($session->loadMessages($this->getNameInLayout()) as $msg) { + parent::addMessage($msg); } $this->_clearMessages(); } @@ -292,10 +292,10 @@ protected function _loadSavedMessages() { * @param string $type * @return null */ - protected function _loadMessagesFromStorage( $type ) { - foreach( Mage::getSingleton( $type ) - ->getMessages( true )->getItems() as $msg ) { - parent::addMessage( $msg ); + protected function _loadMessagesFromStorage($type) { + foreach (Mage::getSingleton($type) + ->getMessages(true)->getItems() as $msg) { + parent::addMessage($msg); } } @@ -305,8 +305,8 @@ protected function _loadMessagesFromStorage( $type ) { * @return null */ protected function _clearMessages() { - Mage::getSingleton( 'turpentine/session' ) - ->clearMessages( $this->getNameInLayout() ); + Mage::getSingleton('turpentine/session') + ->clearMessages($this->getNameInLayout()); } /** @@ -315,8 +315,8 @@ protected function _clearMessages() { * @return string */ protected function _real_toHtml() { - if( !$this->_directCall ) { - switch( $this->getNameInLayout() ) { + if ( ! $this->_directCall) { + switch ($this->getNameInLayout()) { case 'global_messages': $this->_directCall = 'getHtml'; break; @@ -326,9 +326,9 @@ protected function _real_toHtml() { break; } } - switch( $this->_directCall ) { + switch ($this->_directCall) { case 'getHtml': - $html = parent::getHtml( $this->_singleRenderType ); + $html = parent::getHtml($this->_singleRenderType); $this->_singleRenderType = self::NO_SINGLE_RENDER_TYPE; break; case 'getGroupedHtml': @@ -346,7 +346,7 @@ protected function _real_toHtml() { * @return bool */ protected function _fixMessages() { - return Mage::helper( 'turpentine/esi' )->shouldFixFlashMessages(); + return Mage::helper('turpentine/esi')->shouldFixFlashMessages(); } /** @@ -358,7 +358,7 @@ protected function _fixMessages() { * @return boolean */ protected function _isEsiRequest() { - return is_a( Mage::app()->getRequest(), - 'Nexcessnet_Turpentine_Model_Dummy_Request' ); + return is_a(Mage::app()->getRequest(), + 'Nexcessnet_Turpentine_Model_Dummy_Request'); } } diff --git a/app/code/community/Nexcessnet/Turpentine/Block/Management.php b/app/code/community/Nexcessnet/Turpentine/Block/Management.php index 34a1452f0..ff66045b4 100644 --- a/app/code/community/Nexcessnet/Turpentine/Block/Management.php +++ b/app/code/community/Nexcessnet/Turpentine/Block/Management.php @@ -34,7 +34,7 @@ public function __construct() { * @return string */ public function getFlushAllUrl() { - return $this->getUrl( '*/varnish_management/flushAll' ); + return $this->getUrl('*/varnish_management/flushAll'); } /** @@ -43,7 +43,7 @@ public function getFlushAllUrl() { * @return string */ public function getFlushPartialUrl() { - return $this->getUrl( '*/varnish_management/flushPartial' ); + return $this->getUrl('*/varnish_management/flushPartial'); } /** @@ -52,7 +52,7 @@ public function getFlushPartialUrl() { * @return string */ public function getFlushContentTypeUrl() { - return $this->getUrl( '*/varnish_management/flushContentType' ); + return $this->getUrl('*/varnish_management/flushContentType'); } /** @@ -61,7 +61,7 @@ public function getFlushContentTypeUrl() { * @return string */ public function getApplyConfigUrl() { - return $this->getUrl( '*/varnish_management/applyConfig' ); + return $this->getUrl('*/varnish_management/applyConfig'); } /** @@ -88,7 +88,7 @@ public function getGetConfigUrl() { * @param string $type * @return string */ - public function getSwitchNavigationUrl( $type ) { + public function getSwitchNavigationUrl($type) { return $this->getUrl('*/varnish_management/switchNavigation', array('type' => $type)); } } diff --git a/app/code/community/Nexcessnet/Turpentine/Block/Poll/ActivePoll.php b/app/code/community/Nexcessnet/Turpentine/Block/Poll/ActivePoll.php index 8e66ba08a..e4f9810f7 100644 --- a/app/code/community/Nexcessnet/Turpentine/Block/Poll/ActivePoll.php +++ b/app/code/community/Nexcessnet/Turpentine/Block/Poll/ActivePoll.php @@ -24,8 +24,8 @@ class Nexcessnet_Turpentine_Block_Poll_Activepoll extends Mage_Poll_Block_Active public function setTemplate($template) { $this->_template = $template; - $this->setPollTemplate('turpentine/ajax.phtml', 'poll' ); - $this->setPollTemplate('turpentine/ajax.phtml', 'results' ); + $this->setPollTemplate('turpentine/ajax.phtml', 'poll'); + $this->setPollTemplate('turpentine/ajax.phtml', 'results'); return $this; } } diff --git a/app/code/community/Nexcessnet/Turpentine/Block/Product/Compared.php b/app/code/community/Nexcessnet/Turpentine/Block/Product/Compared.php index 12ec356c9..76201db74 100644 --- a/app/code/community/Nexcessnet/Turpentine/Block/Product/Compared.php +++ b/app/code/community/Nexcessnet/Turpentine/Block/Product/Compared.php @@ -23,7 +23,7 @@ class Nexcessnet_Turpentine_Block_Product_Compared extends Mage_Reports_Block_Pr protected function _toHtml() { - if (!$this->getCount()) { + if ( ! $this->getCount()) { return $this->renderView(); } diff --git a/app/code/community/Nexcessnet/Turpentine/Block/Product/Viewed.php b/app/code/community/Nexcessnet/Turpentine/Block/Product/Viewed.php index 9561243e1..bc9e228d3 100644 --- a/app/code/community/Nexcessnet/Turpentine/Block/Product/Viewed.php +++ b/app/code/community/Nexcessnet/Turpentine/Block/Product/Viewed.php @@ -23,7 +23,7 @@ class Nexcessnet_Turpentine_Block_Product_Viewed extends Mage_Reports_Block_Prod protected function _toHtml() { - if (!$this->getCount()) { + if ( ! $this->getCount()) { return $this->renderView(); } $this->setRecentlyViewedProducts($this->getItemsCollection()); diff --git a/app/code/community/Nexcessnet/Turpentine/Helper/Ban.php b/app/code/community/Nexcessnet/Turpentine/Helper/Ban.php index a468ebc44..fabcb3549 100644 --- a/app/code/community/Nexcessnet/Turpentine/Helper/Ban.php +++ b/app/code/community/Nexcessnet/Turpentine/Helper/Ban.php @@ -27,20 +27,20 @@ class Nexcessnet_Turpentine_Helper_Ban extends Mage_Core_Helper_Abstract { * @param Mage_Catalog_Model_Product $product * @return string */ - public function getProductBanRegex( $product ) { + public function getProductBanRegex($product) { $urlPatterns = array(); - foreach( $this->getParentProducts( $product ) as $parentProduct ) { - if ( $parentProduct->getUrlKey() ) { + foreach ($this->getParentProducts($product) as $parentProduct) { + if ($parentProduct->getUrlKey()) { $urlPatterns[] = $parentProduct->getUrlKey(); } } - if ( $product->getUrlKey() ) { + if ($product->getUrlKey()) { $urlPatterns[] = $product->getUrlKey(); } - if ( empty($urlPatterns) ) { + if (empty($urlPatterns)) { $urlPatterns[] = "##_NEVER_MATCH_##"; } - $pattern = sprintf( '(?:%s)', implode( '|', $urlPatterns ) ); + $pattern = sprintf('(?:%s)', implode('|', $urlPatterns)); return $pattern; } @@ -50,13 +50,13 @@ public function getProductBanRegex( $product ) { * @param Mage_Catalog_Model_Product $childProduct * @return array */ - public function getParentProducts( $childProduct ) { + public function getParentProducts($childProduct) { $parentProducts = array(); - foreach( array( 'configurable', 'grouped' ) as $pType ) { - foreach( Mage::getModel( 'catalog/product_type_' . $pType ) - ->getParentIdsByChild( $childProduct->getId() ) as $parentId ) { - $parentProducts[] = Mage::getModel( 'catalog/product' ) - ->load( $parentId ); + foreach (array('configurable', 'grouped') as $pType) { + foreach (Mage::getModel('catalog/product_type_'.$pType) + ->getParentIdsByChild($childProduct->getId()) as $parentId) { + $parentProducts[] = Mage::getModel('catalog/product') + ->load($parentId); } } return $parentProducts; diff --git a/app/code/community/Nexcessnet/Turpentine/Helper/Cron.php b/app/code/community/Nexcessnet/Turpentine/Helper/Cron.php index 9489edb6a..6c30a5be6 100644 --- a/app/code/community/Nexcessnet/Turpentine/Helper/Cron.php +++ b/app/code/community/Nexcessnet/Turpentine/Helper/Cron.php @@ -51,7 +51,7 @@ public function getRunTime() { * @return int */ public function getAllowedRunTime() { - return (int)ini_get( 'max_execution_time' ); + return (int) ini_get('max_execution_time'); } /** @@ -61,8 +61,8 @@ public function getAllowedRunTime() { * @param string $url * @return bool */ - public function addUrlToCrawlerQueue( $url ) { - return $this->addUrlsToCrawlerQueue( array( $url ) ); + public function addUrlToCrawlerQueue($url) { + return $this->addUrlsToCrawlerQueue(array($url)); } /** @@ -72,18 +72,18 @@ public function addUrlToCrawlerQueue( $url ) { * @param array $urls * @return int */ - public function addUrlsToCrawlerQueue( array $urls ) { + public function addUrlsToCrawlerQueue(array $urls) { // TODO: remove this debug message - if( $this->getCrawlerDebugEnabled() ) { - foreach( $urls as $url ) { - Mage::helper( 'turpentine/debug' )->log( + if ($this->getCrawlerDebugEnabled()) { + foreach ($urls as $url) { + Mage::helper('turpentine/debug')->log( 'Adding URL to queue: %s', $url ); } } $oldQueue = $this->_readUrlQueue(); - $newQueue = array_unique( array_merge( $oldQueue, $urls ) ); - $this->_writeUrlQueue( $newQueue ); - $diff = count( $newQueue ) - count( $oldQueue ); + $newQueue = array_unique(array_merge($oldQueue, $urls)); + $this->_writeUrlQueue($newQueue); + $diff = count($newQueue) - count($oldQueue); return $diff; } @@ -94,8 +94,8 @@ public function addUrlsToCrawlerQueue( array $urls ) { */ public function getNextUrl() { $urls = $this->_readUrlQueue(); - $nextUrl = array_shift( $urls ); - $this->_writeUrlQueue( $urls ); + $nextUrl = array_shift($urls); + $this->_writeUrlQueue($urls); return $nextUrl; } @@ -114,15 +114,15 @@ public function getUrlQueue() { * @return Varien_Http_Client */ public function getCrawlerClient() { - if( is_null( $this->_crawlerClient ) ) { - $this->_crawlerClient = new Varien_Http_Client( null, array( + if (is_null($this->_crawlerClient)) { + $this->_crawlerClient = new Varien_Http_Client(null, array( 'useragent' => sprintf( 'Nexcessnet_Turpentine/%s Magento/%s Varien_Http_Client', - Mage::helper( 'turpentine/data' )->getVersion(), + Mage::helper('turpentine/data')->getVersion(), Mage::getVersion() ), 'keepalive' => true, - ) ); - $this->_crawlerClient->setCookie( 'frontend', 'crawler-session' ); + )); + $this->_crawlerClient->setCookie('frontend', 'crawler-session'); } return $this->_crawlerClient; } @@ -133,7 +133,7 @@ public function getCrawlerClient() { * @return bool */ public function getCrawlerEnabled() { - return Mage::getStoreConfig( 'turpentine_varnish/general/crawler_enable' ); + return Mage::getStoreConfig('turpentine_varnish/general/crawler_enable'); } /** @@ -142,7 +142,7 @@ public function getCrawlerEnabled() { * @return bool */ public function getCrawlerDebugEnabled() { - return Mage::getStoreConfig( 'turpentine_varnish/general/crawler_debug' ); + return Mage::getStoreConfig('turpentine_varnish/general/crawler_debug'); } /** @@ -157,31 +157,31 @@ public function getAllUrls() { Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH, Mage_Catalog_Model_Product_Visibility::VISIBILITY_IN_CATALOG, ); - foreach( Mage::app()->getStores() as $storeId => $store ) { - Mage::app()->setCurrentStore( $store ); - $baseUrl = $store->getBaseUrl( Mage_Core_Model_Store::URL_TYPE_LINK ); + foreach (Mage::app()->getStores() as $storeId => $store) { + Mage::app()->setCurrentStore($store); + $baseUrl = $store->getBaseUrl(Mage_Core_Model_Store::URL_TYPE_LINK); $urls[] = $baseUrl; - foreach( Mage::getModel( 'catalog/category' ) - ->getCollection( $storeId ) + foreach (Mage::getModel('catalog/category') + ->getCollection($storeId) ->addIsActiveFilter() - as $cat ) { + as $cat) { $urls[] = $cat->getUrl(); - foreach( $cat->getProductCollection( $storeId ) - ->addUrlRewrite( $cat->getId() ) - ->addAttributeToFilter( 'visibility', $visibility ) - as $prod ) { + foreach ($cat->getProductCollection($storeId) + ->addUrlRewrite($cat->getId()) + ->addAttributeToFilter('visibility', $visibility) + as $prod) { $urls[] = $prod->getProductUrl(); } } $sitemap = (Mage::getConfig()->getNode('modules/MageWorx_XSitemap') !== FALSE) ? 'xsitemap/cms_page' : 'sitemap/cms_page'; - foreach( Mage::getResourceModel( $sitemap ) - ->getCollection( $storeId ) as $item ) { - $urls[] = $baseUrl . $item->getUrl(); + foreach (Mage::getResourceModel($sitemap) + ->getCollection($storeId) as $item) { + $urls[] = $baseUrl.$item->getUrl(); } } - Mage::app()->setCurrentStore( $origStore ); - return array_unique( $urls ); + Mage::app()->setCurrentStore($origStore); + return array_unique($urls); } /** @@ -190,23 +190,23 @@ public function getAllUrls() { * @param Mage_Catalog_Model_Product $product * @return int */ - public function addProductToCrawlerQueue( $product ) { + public function addProductToCrawlerQueue($product) { $productUrls = array(); $origStore = Mage::app()->getStore(); - foreach( Mage::app()->getStores() as $storeId => $store ) { - Mage::app()->setCurrentStore( $store ); + foreach (Mage::app()->getStores() as $storeId => $store) { + Mage::app()->setCurrentStore($store); $baseUrl = $store->getBaseUrl( Mage_Core_Model_Store::URL_TYPE_LINK ); $productUrls[] = $product->getProductUrl(); - foreach( $product->getCategoryIds() as $catId ) { - $cat = Mage::getModel( 'catalog/category' )->load( $catId ); - $productUrls[] = rtrim( $baseUrl, '/' ) . '/' . - ltrim( $product->getUrlModel() - ->getUrlPath( $product, $cat ), '/' ); + foreach ($product->getCategoryIds() as $catId) { + $cat = Mage::getModel('catalog/category')->load($catId); + $productUrls[] = rtrim($baseUrl, '/').'/'. + ltrim($product->getUrlModel() + ->getUrlPath($product, $cat), '/'); } } - Mage::app()->setCurrentStore( $origStore ); - return $this->addUrlsToCrawlerQueue( $productUrls ); + Mage::app()->setCurrentStore($origStore); + return $this->addUrlsToCrawlerQueue($productUrls); } /** @@ -215,15 +215,15 @@ public function addProductToCrawlerQueue( $product ) { * @param Mage_Catalog_Model_Category $category * @return int */ - public function addCategoryToCrawlerQueue( $category ) { + public function addCategoryToCrawlerQueue($category) { $catUrls = array(); $origStore = Mage::app()->getStore(); - foreach( Mage::app()->getStores() as $storeId => $store ) { - Mage::app()->setCurrentStore( $store ); + foreach (Mage::app()->getStores() as $storeId => $store) { + Mage::app()->setCurrentStore($store); $catUrls[] = $category->getUrl(); } - Mage::app()->setCurrentStore( $origStore ); - return $this->addUrlsToCrawlerQueue( $catUrls ); + Mage::app()->setCurrentStore($origStore); + return $this->addUrlsToCrawlerQueue($catUrls); } /** @@ -232,18 +232,18 @@ public function addCategoryToCrawlerQueue( $category ) { * @param int $cmsPageId * @return int */ - public function addCmsPageToCrawlerQueue( $cmsPageId ) { - $page = Mage::getModel( 'cms/page' )->load( $cmsPageId ); + public function addCmsPageToCrawlerQueue($cmsPageId) { + $page = Mage::getModel('cms/page')->load($cmsPageId); $pageUrls = array(); $origStore = Mage::app()->getStore(); - foreach( Mage::app()->getStores() as $storeId => $store ) { - Mage::app()->setCurrentStore( $store ); - $page->setStoreId( $storeId ); - $pageUrls[] = Mage::getUrl( null, - array( '_direct' => $page->getIdentifier() ) ); + foreach (Mage::app()->getStores() as $storeId => $store) { + Mage::app()->setCurrentStore($store); + $page->setStoreId($storeId); + $pageUrls[] = Mage::getUrl(null, + array('_direct' => $page->getIdentifier())); } - Mage::app()->setCurrentStore( $origStore ); - return $this->addUrlsToCrawlerQueue( $pageUrls ); + Mage::app()->setCurrentStore($origStore); + return $this->addUrlsToCrawlerQueue($pageUrls); } /** @@ -253,8 +253,8 @@ public function addCmsPageToCrawlerQueue( $cmsPageId ) { */ protected function _readUrlQueue() { $readQueue = @unserialize( - Mage::app()->loadCache( self::CRAWLER_URLS_CACHE_ID ) ); - if( !is_array( $readQueue ) ) { + Mage::app()->loadCache(self::CRAWLER_URLS_CACHE_ID) ); + if ( ! is_array($readQueue)) { // This is the first time the queue has been read since the last // cache flush (or the queue is corrupt) // Returning an empty array here would be the proper behavior, @@ -271,8 +271,8 @@ protected function _readUrlQueue() { * @param array $urls * @return null */ - protected function _writeUrlQueue( array $urls ) { + protected function _writeUrlQueue(array $urls) { return Mage::app()->saveCache( - serialize( $urls ), self::CRAWLER_URLS_CACHE_ID ); + serialize($urls), self::CRAWLER_URLS_CACHE_ID ); } } diff --git a/app/code/community/Nexcessnet/Turpentine/Helper/Data.php b/app/code/community/Nexcessnet/Turpentine/Helper/Data.php index e9220fb2f..2f5b1ad63 100644 --- a/app/code/community/Nexcessnet/Turpentine/Helper/Data.php +++ b/app/code/community/Nexcessnet/Turpentine/Helper/Data.php @@ -25,7 +25,7 @@ class Nexcessnet_Turpentine_Helper_Data extends Mage_Core_Helper_Abstract { * Contains a newly generated v4 uuid whenever read, possibly not available * on all kernels */ - const UUID_SOURCE = '/proc/sys/kernel/random/uuid'; + const UUID_SOURCE = '/proc/sys/kernel/random/uuid'; /** * Compression level for serialization compression @@ -38,21 +38,21 @@ class Nexcessnet_Turpentine_Helper_Data extends Mage_Core_Helper_Abstract { /** * Hash algorithm to use in various cryptographic methods */ - const HASH_ALGORITHM = 'sha256'; + const HASH_ALGORITHM = 'sha256'; /** * Cookie name for the Varnish bypass * * @var string */ - const BYPASS_COOKIE_NAME = 'varnish_bypass'; + const BYPASS_COOKIE_NAME = 'varnish_bypass'; /** * encryption singleton thing * * @var Mage_Core_Model_Encryption */ - protected $_crypt = null; + protected $_crypt = null; /** * Like built-in explode() but applies trim to each exploded element and @@ -62,9 +62,9 @@ class Nexcessnet_Turpentine_Helper_Data extends Mage_Core_Helper_Abstract { * @param string $data [description] * @return array */ - public function cleanExplode( $token, $data ) { - return array_filter( array_map( 'trim', - explode( $token, trim( $data ) ) ) ); + public function cleanExplode($token, $data) { + return array_filter(array_map('trim', + explode($token, trim($data)))); } /** @@ -73,32 +73,32 @@ public function cleanExplode( $token, $data ) { * @return string */ public function generateUuid() { - if( is_readable( self::UUID_SOURCE ) ) { - $uuid = trim( file_get_contents( self::UUID_SOURCE ) ); - } elseif( function_exists( 'mt_rand' ) ) { + if (is_readable(self::UUID_SOURCE)) { + $uuid = trim(file_get_contents(self::UUID_SOURCE)); + } elseif (function_exists('mt_rand')) { /** * Taken from stackoverflow answer, possibly not the fastest or * strictly standards compliant * @link http://stackoverflow.com/a/2040279 */ - $uuid = sprintf( '%04x%04x-%04x-%04x-%04x-%04x%04x%04x', + $uuid = sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x', // 32 bits for "time_low" - mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ), + mt_rand(0, 0xffff), mt_rand(0, 0xffff), // 16 bits for "time_mid" - mt_rand( 0, 0xffff ), + mt_rand(0, 0xffff), // 16 bits for "time_hi_and_version", // four most significant bits holds version number 4 - mt_rand( 0, 0x0fff ) | 0x4000, + mt_rand(0, 0x0fff) | 0x4000, // 16 bits, 8 bits for "clk_seq_hi_res", // 8 bits for "clk_seq_low", // two most significant bits holds zero and one for variant DCE1.1 - mt_rand( 0, 0x3fff ) | 0x8000, + mt_rand(0, 0x3fff) | 0x8000, // 48 bits for "node" - mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ) + mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff) ); } else { // chosen by dice roll, guaranteed to be random @@ -114,7 +114,7 @@ public function generateUuid() { */ public function getVersion() { return Mage::getConfig() - ->getModuleConfig( 'Nexcessnet_Turpentine' )->version; + ->getModuleConfig('Nexcessnet_Turpentine')->version; } /** @@ -127,11 +127,11 @@ public function getVersion() { * @param string $str * @return string */ - public function urlBase64Encode( $str ) { + public function urlBase64Encode($str) { return str_replace( - array( '/', '+' ), - array( '.', '-' ), - base64_encode( $str ) ); + array('/', '+'), + array('.', '-'), + base64_encode($str) ); } /** @@ -140,11 +140,11 @@ public function urlBase64Encode( $str ) { * @param string $str * @return string */ - public function urlBase64Decode( $str ) { + public function urlBase64Decode($str) { return base64_decode( str_replace( - array( '.', '-' ), - array( '/', '+' ), + array('.', '-'), + array('/', '+'), $str ) ); } @@ -157,14 +157,14 @@ public function urlBase64Decode( $str ) { * @param mixed $data * @return string */ - public function freeze( $data ) { - Varien_Profiler::start( 'turpentine::helper::data::freeze' ); + public function freeze($data) { + Varien_Profiler::start('turpentine::helper::data::freeze'); $frozenData = $this->urlBase64Encode( $this->_getCrypt()->encrypt( gzdeflate( - serialize( $data ), + serialize($data), self::COMPRESSION_LEVEL ) ) ); - Varien_Profiler::stop( 'turpentine::helper::data::freeze' ); + Varien_Profiler::stop('turpentine::helper::data::freeze'); return $frozenData; } @@ -174,13 +174,13 @@ public function freeze( $data ) { * @param string $data * @return mixed */ - public function thaw( $data ) { - Varien_Profiler::start( 'turpentine::helper::data::thaw' ); + public function thaw($data) { + Varien_Profiler::start('turpentine::helper::data::thaw'); $thawedData = unserialize( gzinflate( $this->_getCrypt()->decrypt( - $this->urlBase64Decode( $data ) ) ) ); - Varien_Profiler::stop( 'turpentine::helper::data::thaw' ); + $this->urlBase64Decode($data) ) ) ); + Varien_Profiler::stop('turpentine::helper::data::thaw'); return $thawedData; } @@ -190,9 +190,9 @@ public function thaw( $data ) { * @param string $data * @return string */ - public function secureHash( $data ) { + public function secureHash($data) { $salt = $this->_getCryptKey(); - return hash( self::HASH_ALGORITHM, sprintf( '%s:%s', $salt, $data ) ); + return hash(self::HASH_ALGORITHM, sprintf('%s:%s', $salt, $data)); } /** @@ -201,8 +201,8 @@ public function secureHash( $data ) { * @param string $data * @return string */ - public function getHmac( $data ) { - return hash_hmac( self::HASH_ALGORITHM, $data, $this->_getCryptKey() ); + public function getHmac($data) { + return hash_hmac(self::HASH_ALGORITHM, $data, $this->_getCryptKey()); } /** @@ -211,8 +211,8 @@ public function getHmac( $data ) { * @param array $key * @return string */ - public function getCacheKeyHash( $key ) { - return sha1( implode( '|', array_values( $key ) ) ); + public function getCacheKeyHash($key) { + return sha1(implode('|', array_values($key))); } /** @@ -221,8 +221,8 @@ public function getCacheKeyHash( $key ) { * @param Mage_Core_Model_Layout_Element $blockNode * @return array */ - public function getChildBlockNames( $blockNode ) { - return array_unique( $this->_getChildBlockNames( $blockNode ) ); + public function getChildBlockNames($blockNode) { + return array_unique($this->_getChildBlockNames($blockNode)); } /** @@ -231,12 +231,12 @@ public function getChildBlockNames( $blockNode ) { * @param string|object $model * @return string */ - public function getModelName( $model ) { - if( is_object( $model ) ) { - $model = get_class( $model ); + public function getModelName($model) { + if (is_object($model)) { + $model = get_class($model); } - return strtolower( preg_replace( - '~^[^_]+_([^_]+)_Model_(.+)$~', '$1/$2', $model ) ); + return strtolower(preg_replace( + '~^[^_]+_([^_]+)_Model_(.+)$~', '$1/$2', $model )); } /** @@ -245,7 +245,7 @@ public function getModelName( $model ) { * @return bool */ public function useFlashMessagesFix() { - return (bool)Mage::getStoreConfig( + return (bool) Mage::getStoreConfig( 'turpentine_varnish/general/ajax_messages' ); } @@ -256,7 +256,7 @@ public function useFlashMessagesFix() { * @return bool */ public function useProductListToolbarFix() { - return (bool)Mage::getStoreConfig( + return (bool) Mage::getStoreConfig( 'turpentine_varnish/general/fix_product_toolbar' ); } @@ -266,7 +266,7 @@ public function useProductListToolbarFix() { * @return bool */ public function getAutoApplyOnSave() { - return (bool)Mage::getStoreConfig( + return (bool) Mage::getStoreConfig( 'turpentine_varnish/general/auto_apply_on_save' ); } @@ -280,31 +280,31 @@ public function getVclFix() { 'turpentine_varnish/general/vcl_fix' ); } - /** - * Get config value specifying when to strip VCL whitespaces - * - * @return string - */ - public function getStripVclWhitespace() { - return Mage::getStoreConfig( - 'turpentine_varnish/general/strip_vcl_whitespace' ); - } - - /** - * Check if VCL whitespaces should be stripped for the given action - * - * @param string $action can be either "apply", "save" or "download" - * @return bool - */ - public function shouldStripVclWhitespace($action) { - $configValue = $this->getStripVclWhitespace(); - if ( $configValue==='always' ) { - return true; - } elseif ( $configValue==='apply' && $action==='apply' ) { - return true; - } - return false; - } + /** + * Get config value specifying when to strip VCL whitespaces + * + * @return string + */ + public function getStripVclWhitespace() { + return Mage::getStoreConfig( + 'turpentine_varnish/general/strip_vcl_whitespace' ); + } + + /** + * Check if VCL whitespaces should be stripped for the given action + * + * @param string $action can be either "apply", "save" or "download" + * @return bool + */ + public function shouldStripVclWhitespace($action) { + $configValue = $this->getStripVclWhitespace(); + if ( $configValue==='always' ) { + return true; + } elseif ( $configValue==='apply' && $action==='apply' ) { + return true; + } + return false; + } /** * Get the cookie name for the Varnish bypass @@ -321,19 +321,19 @@ public function getBypassCookieName() { * @param Mage_Core_Model_Layout_Element $blockNode * @return array */ - protected function _getChildBlockNames( $blockNode ) { - Varien_Profiler::start( 'turpentine::helper::data::_getChildBlockNames' ); - if( $blockNode instanceof Mage_Core_Model_Layout_Element ) { - $blockNames = array( (string)$blockNode['name'] ); - foreach( $blockNode->xpath( './block | ./reference' ) as $childBlockNode ) { - $blockNames = array_merge( $blockNames, - $this->_getChildBlockNames( $childBlockNode ) ); - if( $this->getLayout() instanceof Varien_Simplexml_Config ) { - foreach( $this->getLayout()->getNode()->xpath( sprintf( - '//reference[@name=\'%s\']', (string)$childBlockNode['name'] ) ) - as $childBlockLayoutNode ) { - $blockNames = array_merge( $blockNames, - $this->_getChildBlockNames( $childBlockLayoutNode ) ); + protected function _getChildBlockNames($blockNode) { + Varien_Profiler::start('turpentine::helper::data::_getChildBlockNames'); + if ($blockNode instanceof Mage_Core_Model_Layout_Element) { + $blockNames = array((string) $blockNode['name']); + foreach ($blockNode->xpath('./block | ./reference') as $childBlockNode) { + $blockNames = array_merge($blockNames, + $this->_getChildBlockNames($childBlockNode)); + if ($this->getLayout() instanceof Varien_Simplexml_Config) { + foreach ($this->getLayout()->getNode()->xpath(sprintf( + '//reference[@name=\'%s\']', (string) $childBlockNode['name'] )) + as $childBlockLayoutNode) { + $blockNames = array_merge($blockNames, + $this->_getChildBlockNames($childBlockLayoutNode)); } } @@ -341,7 +341,7 @@ protected function _getChildBlockNames( $blockNode ) { } else { $blockNames = array(); } - Varien_Profiler::stop( 'turpentine::helper::data::_getChildBlockNames' ); + Varien_Profiler::stop('turpentine::helper::data::_getChildBlockNames'); return $blockNames; } @@ -354,9 +354,9 @@ protected function _getChildBlockNames( $blockNode ) { * @return Mage_Core_Model_Encryption */ protected function _getCrypt() { - if( is_null( $this->_crypt ) ) { + if (is_null($this->_crypt)) { $this->_crypt = Varien_Crypt::factory() - ->init( $this->_getCryptKey() ); + ->init($this->_getCryptKey()); } return $this->_crypt; } @@ -367,6 +367,6 @@ protected function _getCrypt() { * @return string */ protected function _getCryptKey() { - return (string)Mage::getConfig()->getNode( 'global/crypt/key' ); + return (string) Mage::getConfig()->getNode('global/crypt/key'); } } diff --git a/app/code/community/Nexcessnet/Turpentine/Helper/Debug.php b/app/code/community/Nexcessnet/Turpentine/Helper/Debug.php index 0a62ca8fe..4fbb7ed61 100644 --- a/app/code/community/Nexcessnet/Turpentine/Helper/Debug.php +++ b/app/code/community/Nexcessnet/Turpentine/Helper/Debug.php @@ -26,13 +26,13 @@ class Nexcessnet_Turpentine_Helper_Debug extends Mage_Core_Helper_Abstract { * @param $message * @return string */ - public function logError( $message ) + public function logError($message) { - if ( func_num_args() > 1 ) { - $message = $this->_prepareLogMessage( func_get_args() ); + if (func_num_args() > 1) { + $message = $this->_prepareLogMessage(func_get_args()); } - return $this->_log( Zend_Log::ERR, $message ); + return $this->_log(Zend_Log::ERR, $message); } /** @@ -41,13 +41,13 @@ public function logError( $message ) * @param $message * @return string */ - public function logWarn( $message ) + public function logWarn($message) { - if ( func_num_args() > 1 ) { - $message = $this->_prepareLogMessage( func_get_args() ); + if (func_num_args() > 1) { + $message = $this->_prepareLogMessage(func_get_args()); } - return $this->_log( Zend_Log::WARN, $message ); + return $this->_log(Zend_Log::WARN, $message); } /** @@ -56,13 +56,13 @@ public function logWarn( $message ) * @param $message * @return string */ - public function logNotice( $message ) + public function logNotice($message) { - if ( func_num_args() > 1 ) { - $message = $this->_prepareLogMessage( func_get_args() ); + if (func_num_args() > 1) { + $message = $this->_prepareLogMessage(func_get_args()); } - return $this->_log( Zend_Log::NOTICE, $message ); + return $this->_log(Zend_Log::NOTICE, $message); } /** @@ -71,13 +71,13 @@ public function logNotice( $message ) * @param $message * @return string */ - public function logInfo( $message ) + public function logInfo($message) { - if ( func_num_args() > 1 ) { - $message = $this->_prepareLogMessage( func_get_args() ); + if (func_num_args() > 1) { + $message = $this->_prepareLogMessage(func_get_args()); } - return $this->_log( Zend_Log::INFO, $message ); + return $this->_log(Zend_Log::INFO, $message); } /** @@ -86,17 +86,17 @@ public function logInfo( $message ) * @param $message * @return string */ - public function logDebug( $message ) + public function logDebug($message) { - if( ! Mage::helper( 'turpentine/varnish' )->getVarnishDebugEnabled() ) { + if ( ! Mage::helper('turpentine/varnish')->getVarnishDebugEnabled()) { return; } - if ( func_num_args() > 1 ) { - $message = $this->_prepareLogMessage( func_get_args() ); + if (func_num_args() > 1) { + $message = $this->_prepareLogMessage(func_get_args()); } - return $this->_log( Zend_Log::DEBUG, $message ); + return $this->_log(Zend_Log::DEBUG, $message); } /** @@ -105,16 +105,16 @@ public function logDebug( $message ) * @param array $args * @return string */ - protected function _prepareLogMessage( array $args ) + protected function _prepareLogMessage(array $args) { $pattern = $args[0]; - $substitutes = array_slice( $args, 1 ); + $substitutes = array_slice($args, 1); - if ( ! $this->_validatePattern( $pattern, $substitutes ) ) { + if ( ! $this->_validatePattern($pattern, $substitutes)) { return $pattern; } - return vsprintf( $pattern, $substitutes ); + return vsprintf($pattern, $substitutes); } /** @@ -128,7 +128,7 @@ protected function _prepareLogMessage( array $args ) * @param array $arguments * @return bool */ - protected function _validatePattern( $pattern, $arguments ) + protected function _validatePattern($pattern, $arguments) { return true; } @@ -138,12 +138,12 @@ protected function _validatePattern( $pattern, $arguments ) * * @param mixed $value */ - public function dump( $value ) { - Mage::register( 'turpentine_nocache_flag', true, true ); - $this->logValue( $value ); - echo '
    ' . PHP_EOL;
    -        var_dump( $value );
    -        echo '
    ' . PHP_EOL; + public function dump($value) { + Mage::register('turpentine_nocache_flag', true, true); + $this->logValue($value); + echo '
    '.PHP_EOL;
    +        var_dump($value);
    +        echo '
    '.PHP_EOL; } /** @@ -153,52 +153,51 @@ public function dump( $value ) { * @param mixed ... * @return null */ - public function log( $message ) { + public function log($message) { $args = func_get_args(); - return call_user_func_array( array( $this, 'logDebug' ), $args ); + return call_user_func_array(array($this, 'logDebug'), $args); } /** * Log a backtrace, can pass a already generated backtrace to use * - * @param array $backTrace=null + * @param array $backTrace * @return null */ - public function logBackTrace( $backTrace=null ) { - if( is_null( $backTrace ) ) { + public function logBackTrace($backTrace = null) { + if (is_null($backTrace)) { $backTrace = debug_backtrace(); - array_shift( $backTrace ); + array_shift($backTrace); } - $btuuid = Mage::helper( 'turpentine/data' )->generateUuid(); - $this->log( 'TRACEBACK: START ** %s **', $btuuid ); - $this->log( 'TRACEBACK: URL: %s', $_SERVER['REQUEST_URI'] ); - for( $i=0; $i < count($backTrace); $i++ ) { + $btuuid = Mage::helper('turpentine/data')->generateUuid(); + $this->log('TRACEBACK: START ** %s **', $btuuid); + $this->log('TRACEBACK: URL: %s', $_SERVER['REQUEST_URI']); + for ($i = 0; $i < count($backTrace); $i++) { $line = $backTrace[$i]; - $this->log( 'TRACEBACK: #%02d: %s:%d', - $i, $line['file'], $line['line'] ); - $this->log( 'TRACEBACK: ==> %s%s%s(%s)', - (is_object( @$line['object'] ) ? - get_class( $line['object'] ) : @$line['class'] ), + $this->log('TRACEBACK: #%02d: %s:%d', + $i, $line['file'], $line['line']); + $this->log('TRACEBACK: ==> %s%s%s(%s)', + (is_object(@$line['object']) ? + get_class($line['object']) : @$line['class']), @$line['type'], $line['function'], - $this->_backtrace_formatArgs( $line['args'] ) ); + $this->_backtrace_formatArgs($line['args'])); } - $this->log( 'TRACEBACK: END ** %s **', $btuuid ); + $this->log('TRACEBACK: END ** %s **', $btuuid); } /** * Like var_dump to the log * * @param mixed $value - * @param string $name=null * @return null */ - public function logValue( $value, $name=null ) { - if( is_null( $name ) ) { + public function logValue($value, $name = null) { + if (is_null($name)) { $name = 'VALUE'; } - $this->log( '%s => %s', $name, - $this->_backtrace_formatArgsHelper( $value ) ); + $this->log('%s => %s', $name, + $this->_backtrace_formatArgsHelper($value)); } /** @@ -208,40 +207,40 @@ public function logValue( $value, $name=null ) { * @param string $message * @return string */ - protected function _log( $level, $message ) { - $message = 'TURPENTINE: ' . $message; - Mage::log( $message, $level, $this->_getLogFileName() ); + protected function _log($level, $message) { + $message = 'TURPENTINE: '.$message; + Mage::log($message, $level, $this->_getLogFileName()); return $message; } - /** - * Get the name of the log file to use - * @return string - */ - protected function _getLogFileName() { - if ( $this->useCustomLogFile() ) { - return $this->getCustomLogFileName(); - } - return ''; - } + /** + * Get the name of the log file to use + * @return string + */ + protected function _getLogFileName() { + if ( $this->useCustomLogFile() ) { + return $this->getCustomLogFileName(); + } + return ''; + } - /** - * Check if custom log file should be used - * @return bool - */ - public function useCustomLogFile() { - return Mage::getStoreConfigFlag( - 'turpentine_varnish/logging/use_custom_log_file' ); - } + /** + * Check if custom log file should be used + * @return bool + */ + public function useCustomLogFile() { + return Mage::getStoreConfigFlag( + 'turpentine_varnish/logging/use_custom_log_file' ); + } - /** - * Get custom log file name - * @return string - */ - public function getCustomLogFileName() { - return (string)Mage::getStoreConfig( - 'turpentine_varnish/logging/custom_log_file_name' ); - } + /** + * Get custom log file name + * @return string + */ + public function getCustomLogFileName() { + return (string)Mage::getStoreConfig( + 'turpentine_varnish/logging/custom_log_file_name' ); + } /** * Format a list of function arguments for the backtrace @@ -249,10 +248,10 @@ public function getCustomLogFileName() { * @param array $args * @return string */ - protected function _backtrace_formatArgs( $args ) { - return implode( ', ', + protected function _backtrace_formatArgs($args) { + return implode(', ', array_map( - array( $this, '_backtrace_formatArgsHelper' ), + array($this, '_backtrace_formatArgsHelper'), $args ) ); @@ -264,25 +263,25 @@ protected function _backtrace_formatArgs( $args ) { * @param mixed $arg * @return null */ - protected function _backtrace_formatArgsHelper( $arg ) { + protected function _backtrace_formatArgsHelper($arg) { $value = $arg; - if( is_object( $arg ) ) { - $value = sprintf( 'OBJECT(%s)', get_class( $arg ) ); - } elseif( is_resource( $arg ) ) { + if (is_object($arg)) { + $value = sprintf('OBJECT(%s)', get_class($arg)); + } elseif (is_resource($arg)) { $value = 'RESOURCE'; - } elseif( is_array( $arg ) ) { + } elseif (is_array($arg)) { $value = 'ARRAY[%s](%s)'; $c = array(); - foreach( $arg as $k => $v ) { - $c[] = sprintf( '%s => %s', $k, - $this->_backtrace_formatArgsHelper( $v ) ); + foreach ($arg as $k => $v) { + $c[] = sprintf('%s => %s', $k, + $this->_backtrace_formatArgsHelper($v)); } - $value = sprintf( $value, count( $arg ), implode( ', ', $c ) ); - } elseif( is_string( $arg ) ) { - $value = sprintf( '\'%s\'', $arg ); - } elseif( is_bool( $arg ) ) { + $value = sprintf($value, count($arg), implode(', ', $c)); + } elseif (is_string($arg)) { + $value = sprintf('\'%s\'', $arg); + } elseif (is_bool($arg)) { $value = $arg ? 'TRUE' : 'FALSE'; - } elseif( is_null( $arg ) ) { + } elseif (is_null($arg)) { $value = 'NULL'; } return $value; diff --git a/app/code/community/Nexcessnet/Turpentine/Helper/Esi.php b/app/code/community/Nexcessnet/Turpentine/Helper/Esi.php index 6e150f44b..00250a122 100644 --- a/app/code/community/Nexcessnet/Turpentine/Helper/Esi.php +++ b/app/code/community/Nexcessnet/Turpentine/Helper/Esi.php @@ -41,7 +41,7 @@ class Nexcessnet_Turpentine_Helper_Esi extends Mage_Core_Helper_Abstract { * @return bool */ public function getEsiEnabled() { - return Mage::app()->useCache( $this->getMageCacheName() ); + return Mage::app()->useCache($this->getMageCacheName()); } /** @@ -50,7 +50,7 @@ public function getEsiEnabled() { * @return bool */ public function shouldResponseUseEsi() { - return Mage::helper( 'turpentine/varnish' )->shouldResponseUseVarnish() && + return Mage::helper('turpentine/varnish')->shouldResponseUseVarnish() && $this->getEsiEnabled(); } @@ -60,8 +60,8 @@ public function shouldResponseUseEsi() { * @return null */ public function ensureEsiEnabled() { - if( !$this->shouldResponseUseEsi() ) { - Mage::throwException( 'ESI includes are not enabled' ); + if ( ! $this->shouldResponseUseEsi()) { + Mage::throwException('ESI includes are not enabled'); } } @@ -119,14 +119,14 @@ public function getEsiHmacParam() { return self::ESI_HMAC_PARAM; } - /** - * Get referrer param - * - * @return string - */ - public function getEsiReferrerParam() { - return Mage_Core_Controller_Varien_Action::PARAM_NAME_BASE64_URL; - } + /** + * Get referrer param + * + * @return string + */ + public function getEsiReferrerParam() { + return Mage_Core_Controller_Varien_Action::PARAM_NAME_BASE64_URL; + } /** * Get whether ESI debugging is enabled or not @@ -134,7 +134,7 @@ public function getEsiReferrerParam() { * @return bool */ public function getEsiDebugEnabled() { - return Mage::helper( 'turpentine/varnish' ) + return Mage::helper('turpentine/varnish') ->getVarnishDebugEnabled(); } @@ -144,7 +144,7 @@ public function getEsiDebugEnabled() { * @return bool */ public function getEsiBlockLogEnabled() { - return (bool)Mage::getStoreConfig( + return (bool) Mage::getStoreConfig( 'turpentine_varnish/general/block_debug' ); } @@ -154,7 +154,7 @@ public function getEsiBlockLogEnabled() { * @return bool */ public function shouldFixFlashMessages() { - return Mage::helper( 'turpentine/data' )->useFlashMessagesFix() && + return Mage::helper('turpentine/data')->useFlashMessagesFix() && Mage::app()->getStore()->getCode() !== 'admin'; } @@ -164,7 +164,7 @@ public function shouldFixFlashMessages() { * @return string */ public function getDummyUrl() { - return Mage::getUrl( 'checkout/cart' ); + return Mage::getUrl('checkout/cart'); } /** @@ -174,11 +174,10 @@ public function getDummyUrl() { * turpentine/esi/getBlock while rendering ESI blocks. Not perfect, but may * be good enough * - * @param string $url=null * @return Mage_Core_Controller_Request_Http */ - public function getDummyRequest( $url=null ) { - if( $url === null ) { + public function getDummyRequest($url = null) { + if ($url === null) { $url = $this->getDummyUrl(); } $request = Mage::getModel('turpentine/dummy_request', $url); @@ -198,7 +197,7 @@ public function getMageCacheName() { /** * Get the list of cache clear events to include with every ESI block * - * @return array + * @return string[] */ public function getDefaultCacheClearEvents() { $events = array( @@ -211,19 +210,19 @@ public function getDefaultCacheClearEvents() { /** * Get the list of events that should cause the ESI cache to be cleared * - * @return array + * @return string[] */ public function getCacheClearEvents() { - Varien_Profiler::start( 'turpentine::helper::esi::getCacheClearEvents' ); + Varien_Profiler::start('turpentine::helper::esi::getCacheClearEvents'); $cacheKey = $this->getCacheClearEventsCacheKey(); - $events = @unserialize( Mage::app()->loadCache( $cacheKey ) ); - if( is_null( $events ) || $events === false ) { + $events = @unserialize(Mage::app()->loadCache($cacheKey)); + if (is_null($events) || $events === false) { $events = $this->_loadEsiCacheClearEvents(); - Mage::app()->saveCache( serialize( $events ), $cacheKey, - array( 'LAYOUT_GENERAL_CACHE_TAG' ) ); + Mage::app()->saveCache(serialize($events), $cacheKey, + array('LAYOUT_GENERAL_CACHE_TAG')); } - Varien_Profiler::stop( 'turpentine::helper::esi::getCacheClearEvents' ); - return array_merge( $this->getDefaultCacheClearEvents(), $events ); + Varien_Profiler::stop('turpentine::helper::esi::getCacheClearEvents'); + return array_merge($this->getDefaultCacheClearEvents(), $events); } /** @@ -232,7 +231,7 @@ public function getCacheClearEvents() { * @return string */ public function getDefaultEsiTtl() { - return trim( Mage::getStoreConfig( 'web/cookie/cookie_lifetime' ) ); + return trim(Mage::getStoreConfig('web/cookie/cookie_lifetime')); } /** @@ -242,18 +241,18 @@ public function getDefaultEsiTtl() { * * @return string */ - public function getCorsOrigin( $url=null ) { - if( is_null( $url ) ) { + public function getCorsOrigin($url = null) { + if (is_null($url)) { $baseUrl = Mage::getBaseUrl(); } else { $baseUrl = $url; } - $path = parse_url( $baseUrl, PHP_URL_PATH ); - $domain = parse_url( $baseUrl, PHP_URL_HOST ); + $path = parse_url($baseUrl, PHP_URL_PATH); + $domain = parse_url($baseUrl, PHP_URL_HOST); // there has to be a better way to just strip the path off - return substr( $baseUrl, 0, - strpos( $baseUrl, $path, - strpos( $baseUrl, $domain ) ) ); + return substr($baseUrl, 0, + strpos($baseUrl, $path, + strpos($baseUrl, $domain))); } /** @@ -264,23 +263,23 @@ public function getCorsOrigin( $url=null ) { * @return Mage_Core_Model_Layout_Element|SimpleXMLElement */ public function getLayoutXml() { - Varien_Profiler::start( 'turpentine::helper::esi::getLayoutXml' ); - if( is_null( $this->_layoutXml ) ) { - if( $useCache = Mage::app()->useCache( 'layout' ) ) { + Varien_Profiler::start('turpentine::helper::esi::getLayoutXml'); + if (is_null($this->_layoutXml)) { + if ($useCache = Mage::app()->useCache('layout')) { $cacheKey = $this->getFileLayoutUpdatesXmlCacheKey(); $this->_layoutXml = simplexml_load_string( - Mage::app()->loadCache( $cacheKey ) ); + Mage::app()->loadCache($cacheKey) ); } // this check is redundant if the layout cache is disabled - if( !$this->_layoutXml ) { + if ( ! $this->_layoutXml) { $this->_layoutXml = $this->_loadLayoutXml(); - if( $useCache ) { - Mage::app()->saveCache( $this->_layoutXml->asXML(), - $cacheKey, array( 'LAYOUT_GENERAL_CACHE_TAG' ) ); + if ($useCache) { + Mage::app()->saveCache($this->_layoutXml->asXML(), + $cacheKey, array('LAYOUT_GENERAL_CACHE_TAG')); } } } - Varien_Profiler::stop( 'turpentine::helper::esi::getLayoutXml' ); + Varien_Profiler::stop('turpentine::helper::esi::getLayoutXml'); return $this->_layoutXml; } @@ -291,14 +290,14 @@ public function getLayoutXml() { */ public function getCacheClearEventsCacheKey() { $design = Mage::getDesign(); - return Mage::helper( 'turpentine/data' ) - ->getCacheKeyHash( array( + return Mage::helper('turpentine/data') + ->getCacheKeyHash(array( 'FILE_LAYOUT_ESI_CACHE_EVENTS', $design->getArea(), $design->getPackageName(), - $design->getTheme( 'layout' ), + $design->getTheme('layout'), Mage::app()->getStore()->getId(), - ) ); + )); } /** @@ -308,14 +307,14 @@ public function getCacheClearEventsCacheKey() { */ public function getFileLayoutUpdatesXmlCacheKey() { $design = Mage::getDesign(); - return Mage::helper( 'turpentine/data' ) - ->getCacheKeyHash( array( + return Mage::helper('turpentine/data') + ->getCacheKeyHash(array( 'FILE_LAYOUT_UPDATES_XML', $design->getArea(), $design->getPackageName(), - $design->getTheme( 'layout' ), + $design->getTheme('layout'), Mage::app()->getStore()->getId(), - ) ); + )); } /** @@ -327,8 +326,8 @@ public function getFileLayoutUpdatesXmlCacheKey() { * @param string $url url to pull content from * @return string */ - public function buildEsiIncludeFragment( $url ) { - return sprintf( '', $url ); + public function buildEsiIncludeFragment($url) { + return sprintf('', $url); } /** @@ -341,8 +340,8 @@ public function buildEsiIncludeFragment( $url ) { * @param string $content content to be removed * @return string */ - public function buildEsiRemoveFragment( $content ) { - return sprintf( '%s', $content ); + public function buildEsiRemoveFragment($content) { + return sprintf('%s', $content); } /** @@ -357,9 +356,9 @@ public function getFormKeyEsiUrl() { $this->getEsiScopeParam() => 'global', $this->getEsiCacheTypeParam() => 'private', ); - $esiUrl = Mage::getUrl( 'turpentine/esi/getFormKey', $urlOptions ); + $esiUrl = Mage::getUrl('turpentine/esi/getFormKey', $urlOptions); // setting [web/unsecure/base_url] can be https://... but ESI can never be HTTPS - $esiUrl = preg_replace( '|^https://|i', 'http://', $esiUrl ); + $esiUrl = preg_replace('|^https://|i', 'http://', $esiUrl); return $esiUrl; } @@ -369,19 +368,19 @@ public function getFormKeyEsiUrl() { * @return array */ protected function _loadEsiCacheClearEvents() { - Varien_Profiler::start( 'turpentine::helper::esi::_loadEsiCacheClearEvents' ); + Varien_Profiler::start('turpentine::helper::esi::_loadEsiCacheClearEvents'); $layoutXml = $this->getLayoutXml(); $events = $layoutXml->xpath( '//action[@method=\'setEsiOptions\']/params/flush_events/*' ); - if( $events ) { - $events = array_unique( array_map( - create_function( '$e', - 'return (string)$e->getName();' ), - $events ) ); + if ($events) { + $events = array_unique(array_map( + create_function('$e', + 'return (string)$e->getName();'), + $events )); } else { $events = array(); } - Varien_Profiler::stop( 'turpentine::helper::esi::_loadEsiCacheClearEvents' ); + Varien_Profiler::stop('turpentine::helper::esi::_loadEsiCacheClearEvents'); return $events; } @@ -391,16 +390,16 @@ protected function _loadEsiCacheClearEvents() { * @return Mage_Core_Model_Layout_Element */ protected function _loadLayoutXml() { - Varien_Profiler::start( 'turpentine::helper::esi::_loadLayoutXml' ); + Varien_Profiler::start('turpentine::helper::esi::_loadLayoutXml'); $design = Mage::getDesign(); - $layoutXml = Mage::getSingleton( 'core/layout' ) + $layoutXml = Mage::getSingleton('core/layout') ->getUpdate() ->getFileLayoutUpdatesXml( $design->getArea(), $design->getPackageName(), - $design->getTheme( 'layout' ), + $design->getTheme('layout'), Mage::app()->getStore()->getId() ); - Varien_Profiler::stop( 'turpentine::helper::esi::_loadLayoutXml' ); + Varien_Profiler::stop('turpentine::helper::esi::_loadLayoutXml'); return $layoutXml; } } diff --git a/app/code/community/Nexcessnet/Turpentine/Helper/Varnish.php b/app/code/community/Nexcessnet/Turpentine/Helper/Varnish.php index 7ef95c207..80f5fbde5 100644 --- a/app/code/community/Nexcessnet/Turpentine/Helper/Varnish.php +++ b/app/code/community/Nexcessnet/Turpentine/Helper/Varnish.php @@ -21,7 +21,7 @@ class Nexcessnet_Turpentine_Helper_Varnish extends Mage_Core_Helper_Abstract { - const MAGE_CACHE_NAME = 'turpentine_pages'; + const MAGE_CACHE_NAME = 'turpentine_pages'; /** * Get whether Varnish caching is enabled or not @@ -29,7 +29,7 @@ class Nexcessnet_Turpentine_Helper_Varnish extends Mage_Core_Helper_Abstract { * @return bool */ public function getVarnishEnabled() { - return Mage::app()->useCache( $this->getMageCacheName() ); + return Mage::app()->useCache($this->getMageCacheName()); } /** @@ -38,7 +38,7 @@ public function getVarnishEnabled() { * @return bool */ public function getVarnishDebugEnabled() { - return (bool)Mage::getStoreConfig( + return (bool) Mage::getStoreConfig( 'turpentine_varnish/general/varnish_debug' ); } @@ -50,7 +50,7 @@ public function getVarnishDebugEnabled() { */ public function isRequestFromVarnish() { return $this->getSecretHandshake() == - Mage::app()->getRequest()->getHeader( 'X-Turpentine-Secret-Handshake' ); + Mage::app()->getRequest()->getHeader('X-Turpentine-Secret-Handshake'); } /** @@ -89,18 +89,18 @@ public function getSecretHandshake() { * * @param string $host [description] * @param string|int $port [description] - * @param string $secretKey=null [description] - * @param string $version=null [description] + * @param string $secretKey [description] + * @param string $version [description] * @return Nexcessnet_Turpentine_Model_Varnish_Admin_Socket */ - public function getSocket( $host, $port, $secretKey=null, $version=null ) { - $socket = Mage::getModel( 'turpentine/varnish_admin_socket', - array( 'host' => $host, 'port' => $port ) ); - if( $secretKey ) { - $socket->setAuthSecret( $secretKey ); + public function getSocket($host, $port, $secretKey = null, $version = null) { + $socket = Mage::getModel('turpentine/varnish_admin_socket', + array('host' => $host, 'port' => $port)); + if ($secretKey) { + $socket->setAuthSecret($secretKey); } - if( $version ) { - $socket->setVersion( $version ); + if ($version) { + $socket->setVersion($version); } return $socket; } @@ -112,17 +112,17 @@ public function getSocket( $host, $port, $secretKey=null, $version=null ) { */ public function getSockets() { $sockets = array(); - $servers = Mage::helper( 'turpentine/data' )->cleanExplode( PHP_EOL, - Mage::getStoreConfig( 'turpentine_varnish/servers/server_list' ) ); - $key = str_replace( '\n', PHP_EOL, - Mage::getStoreConfig( 'turpentine_varnish/servers/auth_key' ) ); - $version = Mage::getStoreConfig( 'turpentine_varnish/servers/version' ); - if( $version == 'auto' ) { + $servers = Mage::helper('turpentine/data')->cleanExplode(PHP_EOL, + Mage::getStoreConfig('turpentine_varnish/servers/server_list')); + $key = str_replace('\n', PHP_EOL, + Mage::getStoreConfig('turpentine_varnish/servers/auth_key')); + $version = Mage::getStoreConfig('turpentine_varnish/servers/version'); + if ($version == 'auto') { $version = null; } - foreach( $servers as $server ) { - $parts = explode( ':', $server ); - $sockets[] = $this->getSocket( $parts[0], $parts[1], $key, $version ); + foreach ($servers as $server) { + $parts = explode(':', $server); + $sockets[] = $this->getSocket($parts[0], $parts[1], $key, $version); } return $sockets; } @@ -142,7 +142,7 @@ public function getMageCacheName() { * @return string */ public function getDefaultTtl() { - return Mage::getStoreConfig( 'turpentine_vcl/ttls/default_ttl' ); + return Mage::getStoreConfig('turpentine_vcl/ttls/default_ttl'); } /** @@ -152,7 +152,7 @@ public function getDefaultTtl() { * @return bool */ public function shouldFixProductListToolbar() { - return Mage::helper( 'turpentine/data' )->useProductListToolbarFix() && + return Mage::helper('turpentine/data')->useProductListToolbarFix() && Mage::app()->getStore()->getCode() !== 'admin'; } @@ -162,8 +162,8 @@ public function shouldFixProductListToolbar() { * @return boolean */ public function isBypassEnabled() { - $cookieName = Mage::helper( 'turpentine/data' )->getBypassCookieName(); - $cookieValue = Mage::getModel( 'core/cookie' )->get( $cookieName ); + $cookieName = Mage::helper('turpentine/data')->getBypassCookieName(); + $cookieValue = Mage::getModel('core/cookie')->get($cookieName); return $cookieValue === $this->getSecretHandshake(); } @@ -180,7 +180,7 @@ public function shouldDisplayNotice() { public function getFormKeyFixupActionsList() { $data = Mage::getStoreConfig( 'turpentine_varnish/miscellaneous/formkey_fixup_actions' ); - $actions = array_filter( explode( PHP_EOL, trim( $data ) ) ); + $actions = array_filter(explode(PHP_EOL, trim($data))); return $actions; } @@ -196,21 +196,21 @@ public function getFormKeyFixupActionsList() { public function csrfFixupNeeded() { $result = false; $isEnterprise = false; // ce - if( method_exists( 'Mage', 'getEdition' ) ) { - if( Mage::getEdition() === Mage::EDITION_ENTERPRISE ) { + if (method_exists('Mage', 'getEdition')) { + if (Mage::getEdition() === Mage::EDITION_ENTERPRISE) { $isEnterprise = true; } } else { - if( Mage::getConfig()->getModuleConfig( 'Enterprise_Enterprise' ) ) { + if (Mage::getConfig()->getModuleConfig('Enterprise_Enterprise')) { $isEnterprise = true; } } - if( $isEnterprise ) { - if( version_compare( Mage::getVersion(), '1.13', '>=' ) ) { + if ($isEnterprise) { + if (version_compare(Mage::getVersion(), '1.13', '>=')) { $result = true; } } else { - if( version_compare( Mage::getVersion(), '1.8', '>=' ) ) { + if (version_compare(Mage::getVersion(), '1.8', '>=')) { $result = true; } } diff --git a/app/code/community/Nexcessnet/Turpentine/Model/Config/Select/StripWhitespace.php b/app/code/community/Nexcessnet/Turpentine/Model/Config/Select/StripWhitespace.php index 4aa1889fc..be5876151 100644 --- a/app/code/community/Nexcessnet/Turpentine/Model/Config/Select/StripWhitespace.php +++ b/app/code/community/Nexcessnet/Turpentine/Model/Config/Select/StripWhitespace.php @@ -23,9 +23,9 @@ class Nexcessnet_Turpentine_Model_Config_Select_stripWhitespace { public function toOptionArray() { $helper = Mage::helper('turpentine'); return array( - array( 'value' => 'always', 'label' => $helper->__( 'Always' ) ), - array( 'value' => 'apply', 'label' => $helper->__( 'Only when applying directly to Varnish' ) ), - array( 'value' => 'never', 'label' => $helper->__( 'Never' ) ), + array('value' => 'always', 'label' => $helper->__('Always')), + array('value' => 'apply', 'label' => $helper->__('Only when applying directly to Varnish')), + array('value' => 'never', 'label' => $helper->__('Never')), ); } } \ No newline at end of file diff --git a/app/code/community/Nexcessnet/Turpentine/Model/Config/Select/Version.php b/app/code/community/Nexcessnet/Turpentine/Model/Config/Select/Version.php index 3bdce45a0..df21d3600 100644 --- a/app/code/community/Nexcessnet/Turpentine/Model/Config/Select/Version.php +++ b/app/code/community/Nexcessnet/Turpentine/Model/Config/Select/Version.php @@ -25,7 +25,7 @@ public function toOptionArray() { return array( array( 'value' => '2.1', 'label' => $helper->__( '2.1.x' ) ), array( 'value' => '3.0', 'label' => $helper->__( '3.0.x' ) ), - array( 'value' => '4.0', 'label' => $helper->__( '4.0.x' ) ), + array( 'value' => '4.0', 'label' => $helper->__( '4.0.x' ) ), array( 'value' => 'auto', 'label' => $helper->__( 'Auto' ) ), ); } diff --git a/app/code/community/Nexcessnet/Turpentine/Model/Core/Session.php b/app/code/community/Nexcessnet/Turpentine/Model/Core/Session.php index 7b2afa444..63aa888ed 100644 --- a/app/code/community/Nexcessnet/Turpentine/Model/Core/Session.php +++ b/app/code/community/Nexcessnet/Turpentine/Model/Core/Session.php @@ -20,7 +20,7 @@ */ class Nexcessnet_Turpentine_Model_Core_Session extends Mage_Core_Model_Session { - public function __construct($data=array()) + public function __construct($data = array()) { $name = isset($data['name']) ? $data['name'] : null; $this->init('core', $name); @@ -34,7 +34,7 @@ public function __construct($data=array()) public function getFormKey() { if (Mage::registry('replace_form_key') && - !Mage::app()->getRequest()->getParam('form_key', false)) { + ! Mage::app()->getRequest()->getParam('form_key', false)) { // flag request for ESI processing Mage::register('turpentine_esi_flag', true, true); return '{{form_key_esi_placeholder}}'; @@ -45,7 +45,7 @@ public function getFormKey() public function real_getFormKey() { - if (!$this->getData('_form_key')) { + if ( ! $this->getData('_form_key')) { $this->setData('_form_key', Mage::helper('core')->getRandomString(16)); } return $this->getData('_form_key'); diff --git a/app/code/community/Nexcessnet/Turpentine/Model/Dummy/Request.php b/app/code/community/Nexcessnet/Turpentine/Model/Dummy/Request.php index 52f6d7344..ebfd40013 100644 --- a/app/code/community/Nexcessnet/Turpentine/Model/Dummy/Request.php +++ b/app/code/community/Nexcessnet/Turpentine/Model/Dummy/Request.php @@ -37,18 +37,18 @@ class Nexcessnet_Turpentine_Model_Dummy_Request extends * @return void * @throws Zend_Controller_Request_Exception when invalid URI passed */ - public function __construct( $uri=null ) { + public function __construct($uri = null) { $this->_initFakeSuperGlobals(); - $this->_fixupFakeSuperGlobals( $uri ); + $this->_fixupFakeSuperGlobals($uri); try { - parent::__construct( $uri ); - } catch( Exception $e ) { - Mage::helper( 'turpentine/debug' ) - ->logError( 'Bad URI given to dummy request: ' . $uri ); - Mage::helper( 'turpentine/debug' ) + parent::__construct($uri); + } catch (Exception $e) { + Mage::helper('turpentine/debug') + ->logError('Bad URI given to dummy request: '.$uri); + Mage::helper('turpentine/debug') ->logBackTrace(); - Mage::logException( $e ); - if( Mage::helper( 'turpentine/esi' )->getEsiDebugEnabled() ) { + Mage::logException($e); + if (Mage::helper('turpentine/esi')->getEsiDebugEnabled()) { throw $e; } } @@ -62,23 +62,23 @@ public function __construct( $uri=null ) { * @param string $key * @return mixed */ - public function __get( $key ) { - switch( true ) { - case isset( $this->_params[$key] ): + public function __get($key) { + switch (true) { + case isset($this->_params[$key]): return $this->_params[$key]; - case isset( $this->GET[$key] ): + case isset($this->GET[$key]): return $this->GET[$key]; - case isset( $this->POST[$key] ): + case isset($this->POST[$key]): return $this->POST[$key]; - case isset( $_COOKIE[$key] ): + case isset($_COOKIE[$key]): return $_COOKIE[$key]; case ($key == 'REQUEST_URI'): return $this->getRequestUri(); case ($key == 'PATH_INFO'): return $this->getPathInfo(); - case isset( $this->SERVER[$key] ): + case isset($this->SERVER[$key]): return $this->SERVER[$key]; - case isset( $this->ENV[$key] ): + case isset($this->ENV[$key]): return $this->ENV[$key]; default: return null; @@ -91,19 +91,19 @@ public function __get( $key ) { * @param string $key * @return boolean */ - public function __isset( $key ) { + public function __isset($key) { switch (true) { - case isset( $this->_params[$key] ): + case isset($this->_params[$key]): return true; - case isset( $this->GET[$key] ): + case isset($this->GET[$key]): return true; - case isset( $this->POST[$key] ): + case isset($this->POST[$key]): return true; - case isset( $_COOKIE[$key] ): + case isset($_COOKIE[$key]): return true; - case isset( $this->SERVER[$key] ): + case isset($this->SERVER[$key]): return true; - case isset( $this->ENV[$key] ): + case isset($this->ENV[$key]): return true; default: return false; @@ -117,8 +117,8 @@ public function __isset( $key ) { * @param null|mixed $value * @return Zend_Controller_Request_Http */ - public function setQuery( $spec, $value=null ) { - if ((null === $value) && !is_array($spec)) { + public function setQuery($spec, $value = null) { + if ((null === $value) && ! is_array($spec)) { #require_once 'Zend/Controller/Exception.php'; throw new Zend_Controller_Exception('Invalid value passed to setQuery(); must be either array of values or key/value pair'); } @@ -142,11 +142,11 @@ public function setQuery( $spec, $value=null ) { * @param mixed $default Default value to use if key not found * @return mixed Returns null if key does not exist */ - public function getQuery( $key=null, $default=null ) { - if( null === $key ) { + public function getQuery($key = null, $default = null) { + if (null === $key) { return $this->GET; } - return ( isset( $this->GET[$key] ) ) ? $this->GET[$key] : $default; + return (isset($this->GET[$key])) ? $this->GET[$key] : $default; } /** @@ -159,7 +159,7 @@ public function getQuery( $key=null, $default=null ) { * @param mixed $default Default value to use if key not found * @return mixed Returns null if key does not exist */ - public function getPost( $key=null, $default=null ) { + public function getPost($key = null, $default = null) { if (null === $key) { return $this->POST; } @@ -176,7 +176,7 @@ public function getPost( $key=null, $default=null ) { * @param mixed $default Default value to use if key not found * @return mixed Returns null if key does not exist */ - public function getServer( $key=null, $default=null ) { + public function getServer($key = null, $default = null) { if (null === $key) { return $this->SERVER; } @@ -193,7 +193,7 @@ public function getServer( $key=null, $default=null ) { * @param mixed $default Default value to use if key not found * @return mixed Returns null if key does not exist */ - public function getEnv( $key=null, $default=null ) { + public function getEnv($key = null, $default = null) { if (null === $key) { return $this->ENV; } @@ -210,14 +210,14 @@ public function getEnv( $key=null, $default=null ) { * @return string|false HTTP header value, or false if not found * @throws Zend_Controller_Request_Exception */ - public function getHeader( $header ) { + public function getHeader($header) { if (empty($header)) { #require_once 'Zend/Controller/Request/Exception.php'; throw new Zend_Controller_Request_Exception('An HTTP header name is required'); } // Try to get it from the $_SERVER array first - $temp = 'HTTP_' . strtoupper(str_replace('-', '_', $header)); + $temp = 'HTTP_'.strtoupper(str_replace('-', '_', $header)); if (isset($this->SERVER[$temp])) { return $this->SERVER[$temp]; } @@ -249,7 +249,7 @@ public function getHeader( $header ) { * @param string $requestUri * @return Zend_Controller_Request_Http */ - public function setRequestUri( $requestUri=null ) { + public function setRequestUri($requestUri = null) { if ($requestUri === null) { if (isset($this->SERVER['HTTP_X_REWRITE_URL'])) { // check this first so IIS will catch $requestUri = $this->SERVER['HTTP_X_REWRITE_URL']; @@ -264,19 +264,19 @@ public function setRequestUri( $requestUri=null ) { } elseif (isset($this->SERVER['REQUEST_URI'])) { $requestUri = $this->SERVER['REQUEST_URI']; // Http proxy reqs setup request uri with scheme and host [and port] + the url path, only use url path - $schemeAndHttpHost = $this->getScheme() . '://' . $this->getHttpHost(); + $schemeAndHttpHost = $this->getScheme().'://'.$this->getHttpHost(); if (strpos($requestUri, $schemeAndHttpHost) === 0) { $requestUri = substr($requestUri, strlen($schemeAndHttpHost)); } } elseif (isset($this->SERVER['ORIG_PATH_INFO'])) { // IIS 5.0, PHP as CGI $requestUri = $this->SERVER['ORIG_PATH_INFO']; - if (!empty($this->SERVER['QUERY_STRING'])) { - $requestUri .= '?' . $this->SERVER['QUERY_STRING']; + if ( ! empty($this->SERVER['QUERY_STRING'])) { + $requestUri .= '?'.$this->SERVER['QUERY_STRING']; } } else { return $this; } - } elseif (!is_string($requestUri)) { + } elseif ( ! is_string($requestUri)) { return $this; } else { // Set GET items, if available @@ -312,8 +312,8 @@ public function setRequestUri( $requestUri=null ) { * @param mixed $baseUrl * @return Zend_Controller_Request_Http */ - public function setBaseUrl( $baseUrl=null ) { - if ((null !== $baseUrl) && !is_string($baseUrl)) { + public function setBaseUrl($baseUrl = null) { + if ((null !== $baseUrl) && ! is_string($baseUrl)) { return $this; } @@ -338,7 +338,7 @@ public function setBaseUrl( $baseUrl=null ) { $baseUrl = ''; do { $seg = $segs[$index]; - $baseUrl = '/' . $seg . $baseUrl; + $baseUrl = '/'.$seg.$baseUrl; ++$index; } while (($last > $index) && (false !== ($pos = strpos($path, $baseUrl))) && (0 != $pos)); } @@ -364,7 +364,7 @@ public function setBaseUrl( $baseUrl=null ) { } $basename = basename($baseUrl); - if (empty($basename) || !strpos($truncatedRequestUri, $basename)) { + if (empty($basename) || ! strpos($truncatedRequestUri, $basename)) { // no match whatsoever; set it blank $this->_baseUrl = ''; return $this; @@ -390,7 +390,7 @@ public function setBaseUrl( $baseUrl=null ) { * @param string|null $basePath * @return Zend_Controller_Request_Http */ - public function setBasePath( $basePath=null ) { + public function setBasePath($basePath = null) { if ($basePath === null) { $filename = (isset($this->SERVER['SCRIPT_FILENAME'])) ? basename($this->SERVER['SCRIPT_FILENAME']) @@ -430,7 +430,7 @@ public function setBasePath( $basePath=null ) { * @param mixed $default Default value to use if key not found * @return mixed */ - public function getParam( $key, $default=null ) { + public function getParam($key, $default = null) { $keyName = (null !== ($alias = $this->getAlias($key))) ? $alias : $key; $paramSources = $this->getParamSources(); @@ -478,8 +478,8 @@ public function getParams() { * @param bool $trimPort * @return string */ - public function getHttpHost( $trimPort=true ) { - if (!isset($this->SERVER['HTTP_HOST'])) { + public function getHttpHost($trimPort = true) { + if ( ! isset($this->SERVER['HTTP_HOST'])) { return false; } if ($trimPort) { @@ -497,11 +497,10 @@ public function getHttpHost( $trimPort=true ) { * * @return Mage_Core_Controller_Request_Http */ - public function setPost( $key, $value=null ) { + public function setPost($key, $value = null) { if (is_array($key)) { $this->POST = $key; - } - else { + } else { $this->POST[$key] = $value; } return $this; @@ -525,30 +524,30 @@ protected function _initFakeSuperGlobals() { * @param string $uri * @return null */ - protected function _fixupFakeSuperGlobals( $uri ) { + protected function _fixupFakeSuperGlobals($uri) { $uri = str_replace('|', urlencode('|'), $uri); - $parsedUrl = parse_url( $uri ); + $parsedUrl = parse_url($uri); - if ( isset($parsedUrl['path']) ) { + if (isset($parsedUrl['path'])) { $this->SERVER['REQUEST_URI'] = $parsedUrl['path']; } - if( isset( $parsedUrl['query'] ) && $parsedUrl['query'] ) { + if (isset($parsedUrl['query']) && $parsedUrl['query']) { $this->SERVER['QUERY_STRING'] = $parsedUrl['query']; - $this->SERVER['REQUEST_URI'] .= '?' . $this->SERVER['QUERY_STRING']; + $this->SERVER['REQUEST_URI'] .= '?'.$this->SERVER['QUERY_STRING']; } else { $this->SERVER['QUERY_STRING'] = null; } - parse_str( $this->SERVER['QUERY_STRING'], $this->GET ); - if( isset( $this->SERVER['SCRIPT_URI'] ) ) { - $start = strpos( $this->SERVER['SCRIPT_URI'], '/', 9 ); - $sub = substr( $this->SERVER['SCRIPT_URI'], $start ); + parse_str($this->SERVER['QUERY_STRING'], $this->GET); + if (isset($this->SERVER['SCRIPT_URI'])) { + $start = strpos($this->SERVER['SCRIPT_URI'], '/', 9); + $sub = substr($this->SERVER['SCRIPT_URI'], $start); $this->SERVER['SCRIPT_URI'] = substr( - $this->SERVER['SCRIPT_URI'], 0, $start ) . + $this->SERVER['SCRIPT_URI'], 0, $start ). @str_replace( $this->SERVER['SCRIPT_URL'], $parsedUrl['path'], - $sub, $c=1 ); + $sub, $c = 1 ); } - if( isset( $this->SERVER['SCRIPT_URL'] ) ) { + if (isset($this->SERVER['SCRIPT_URL'])) { $this->SERVER['SCRIPT_URL'] = $parsedUrl['path']; } } @@ -563,14 +562,14 @@ protected function _fixupFakeSuperGlobals( $uri ) { * @return null */ public function fakeRouterDispatch() { - if( $this->_cmsRouterMatch() ) { - Mage::helper( 'turpentine/debug' )->logDebug( 'Matched router: cms' ); - } elseif( $this->_standardRouterMatch() ) { - Mage::helper( 'turpentine/debug' )->logDebug( 'Matched router: standard' ); - } elseif( $this->_defaultRouterMatch() ) { - Mage::helper( 'turpentine/debug' )->logDebug( 'Matched router: default' ); + if ($this->_cmsRouterMatch()) { + Mage::helper('turpentine/debug')->logDebug('Matched router: cms'); + } elseif ($this->_standardRouterMatch()) { + Mage::helper('turpentine/debug')->logDebug('Matched router: standard'); + } elseif ($this->_defaultRouterMatch()) { + Mage::helper('turpentine/debug')->logDebug('Matched router: default'); } else { - Mage::helper( 'turpentine/debug' )->logDebug( 'No router match' ); + Mage::helper('turpentine/debug')->logDebug('No router match'); } } @@ -586,7 +585,7 @@ protected function _defaultRouterMatch() { $actionName = isset($noRoute[2]) ? $noRoute[2] : 'index'; if (Mage::app()->getStore()->isAdmin()) { - $adminFrontName = (string)Mage::getConfig()->getNode('admin/routers/adminhtml/args/frontName'); + $adminFrontName = (string) Mage::getConfig()->getNode('admin/routers/adminhtml/args/frontName'); if ($adminFrontName != $moduleName) { $moduleName = 'core'; $controllerName = 'index'; @@ -608,7 +607,7 @@ protected function _defaultRouterMatch() { * @return bool */ protected function _standardRouterMatch() { - $router = Mage::app()->getFrontController()->getRouter( 'standard' ); + $router = Mage::app()->getFrontController()->getRouter('standard'); // $router->fetchDefault(); @@ -626,14 +625,14 @@ protected function _standardRouterMatch() { if ($this->getModuleName()) { $module = $this->getModuleName(); } else { - if (!empty($p[0])) { + if ( ! empty($p[0])) { $module = $p[0]; } else { $module = $router->getFront()->getDefault('module'); $this->setAlias(Mage_Core_Model_Url_Rewrite::REWRITE_REQUEST_PATH_ALIAS, ''); } } - if (!$module) { + if ( ! $module) { if (Mage::app()->getStore()->isAdmin()) { $module = 'admin'; } else { @@ -661,7 +660,7 @@ protected function _standardRouterMatch() { if ($this->getControllerName()) { $controller = $this->getControllerName(); } else { - if (!empty($p[1])) { + if ( ! empty($p[1])) { $controller = $p[1]; } else { $controller = $front->getDefault('controller'); @@ -677,7 +676,7 @@ protected function _standardRouterMatch() { if ($this->getActionName()) { $action = $this->getActionName(); } else { - $action = !empty($p[2]) ? $p[2] : $front->getDefault('action'); + $action = ! empty($p[2]) ? $p[2] : $front->getDefault('action'); } } @@ -685,21 +684,21 @@ protected function _standardRouterMatch() { // $router->_checkShouldBeSecure($this, '/'.$module.'/'.$controller.'/'.$action); // $controllerClassName = $router->_validateControllerClassName($realModule, $controller); - $controllerClassName = $router->getControllerClassName( $realModule, $controller ); - if (!$controllerClassName) { + $controllerClassName = $router->getControllerClassName($realModule, $controller); + if ( ! $controllerClassName) { continue; } else { - $controllerFileName = $router->getControllerFileName( $realModule, $controller ); - if( !$router->validateControllerFileName( $controllerFileName ) ) { + $controllerFileName = $router->getControllerFileName($realModule, $controller); + if ( ! $router->validateControllerFileName($controllerFileName)) { return false; } - if (!class_exists($controllerClassName, false)) { - if (!file_exists($controllerFileName)) { + if ( ! class_exists($controllerClassName, false)) { + if ( ! file_exists($controllerFileName)) { return false; } include_once $controllerFileName; - if (!class_exists($controllerClassName, false)) { + if ( ! class_exists($controllerClassName, false)) { throw Mage::exception('Mage_Core', Mage::helper('core')->__('Controller file was loaded but class does not exist')); } } @@ -708,7 +707,7 @@ protected function _standardRouterMatch() { // instantiate controller class $controllerInstance = Mage::getControllerInstance($controllerClassName, $this, $front->getResponse()); - if (!$controllerInstance->hasAction($action)) { + if ( ! $controllerInstance->hasAction($action)) { continue; } @@ -719,7 +718,7 @@ protected function _standardRouterMatch() { /** * if we did not found any suitable */ - if (!$found) { + if ( ! $found) { /* if ($router->_noRouteShouldBeApplied()) { $controller = 'index'; @@ -752,7 +751,7 @@ protected function _standardRouterMatch() { // set parameters from pathinfo for ($i = 3, $l = sizeof($p); $i < $l; $i += 2) { - $this->setParam($p[$i], isset($p[$i+1]) ? urldecode($p[$i+1]) : ''); + $this->setParam($p[$i], isset($p[$i + 1]) ? urldecode($p[$i + 1]) : ''); } // dispatch action @@ -768,7 +767,7 @@ protected function _standardRouterMatch() { * @return bool */ protected function _cmsRouterMatch() { - $router = Mage::app()->getFrontController()->getRouter( 'cms' ); + $router = Mage::app()->getFrontController()->getRouter('cms'); $identifier = trim($this->getPathInfo(), '/'); @@ -790,13 +789,13 @@ protected function _cmsRouterMatch() { return true; } - if (!$condition->getContinue()) { + if ( ! $condition->getContinue()) { return false; } $page = Mage::getModel('cms/page'); $pageId = $page->checkIdentifier($identifier, Mage::app()->getStore()->getId()); - if (!$pageId) { + if ( ! $pageId) { return false; } diff --git a/app/code/community/Nexcessnet/Turpentine/Model/Observer/Ban.php b/app/code/community/Nexcessnet/Turpentine/Model/Observer/Ban.php index 5bfd8a13c..843f90043 100644 --- a/app/code/community/Nexcessnet/Turpentine/Model/Observer/Ban.php +++ b/app/code/community/Nexcessnet/Turpentine/Model/Observer/Ban.php @@ -29,12 +29,12 @@ class Nexcessnet_Turpentine_Model_Observer_Ban extends Varien_Event_Observer { * Cache the varnish admin object * @var Nexcessnet_Turpentine_Model_Varnish_Admin */ - protected $_varnishAdmin = null; + protected $_varnishAdmin = null; /** * Flag to prevent doing the ESI cache clear more than once per request * @var boolean */ - protected $_esiClearFlag = array(); + protected $_esiClearFlag = array(); /** * Clear the ESI block cache for a specific client @@ -46,23 +46,23 @@ class Nexcessnet_Turpentine_Model_Observer_Ban extends Varien_Event_Observer { * @param Varien_Object $eventObject * @return null */ - public function banClientEsiCache( $eventObject ) { + public function banClientEsiCache($eventObject) { $eventName = $eventObject->getEvent()->getName(); - if( Mage::helper( 'turpentine/esi' )->getEsiEnabled() && - !in_array( $eventName, $this->_esiClearFlag ) ) { - $sessionId = Mage::app()->getRequest()->getCookie( 'frontend' ); - if( $sessionId ) { + if (Mage::helper('turpentine/esi')->getEsiEnabled() && + ! in_array($eventName, $this->_esiClearFlag)) { + $sessionId = Mage::app()->getRequest()->getCookie('frontend'); + if ($sessionId) { $result = $this->_getVarnishAdmin()->flushExpression( 'obj.http.X-Varnish-Session', '==', $sessionId, '&&', 'obj.http.X-Turpentine-Flush-Events', '~', $eventName ); - Mage::dispatchEvent( 'turpentine_ban_client_esi_cache', $result ); - if( $this->_checkResult( $result ) ) { - Mage::helper( 'turpentine/debug' ) - ->logDebug( 'Cleared ESI cache for client (%s) on event: %s', - $sessionId, $eventName ); + Mage::dispatchEvent('turpentine_ban_client_esi_cache', $result); + if ($this->_checkResult($result)) { + Mage::helper('turpentine/debug') + ->logDebug('Cleared ESI cache for client (%s) on event: %s', + $sessionId, $eventName); } else { - Mage::helper( 'turpentine/debug' ) + Mage::helper('turpentine/debug') ->logWarn( 'Failed to clear Varnish ESI cache for client: %s', $sessionId ); @@ -81,20 +81,20 @@ public function banClientEsiCache( $eventObject ) { * @param Varien_Object $eventObject * @return null */ - public function banProductPageCache( $eventObject ) { - if( Mage::helper( 'turpentine/varnish' )->getVarnishEnabled() ) { - $banHelper = Mage::helper( 'turpentine/ban' ); + public function banProductPageCache($eventObject) { + if (Mage::helper('turpentine/varnish')->getVarnishEnabled()) { + $banHelper = Mage::helper('turpentine/ban'); $product = $eventObject->getProduct(); - $urlPattern = $banHelper->getProductBanRegex( $product ); - $result = $this->_getVarnishAdmin()->flushUrl( $urlPattern ); - Mage::dispatchEvent( 'turpentine_ban_product_cache', $result ); - $cronHelper = Mage::helper( 'turpentine/cron' ); - if( $this->_checkResult( $result ) && - $cronHelper->getCrawlerEnabled() ) { - $cronHelper->addProductToCrawlerQueue( $product ); - foreach( $banHelper->getParentProducts( $product ) - as $parentProduct ) { - $cronHelper->addProductToCrawlerQueue( $parentProduct ); + $urlPattern = $banHelper->getProductBanRegex($product); + $result = $this->_getVarnishAdmin()->flushUrl($urlPattern); + Mage::dispatchEvent('turpentine_ban_product_cache', $result); + $cronHelper = Mage::helper('turpentine/cron'); + if ($this->_checkResult($result) && + $cronHelper->getCrawlerEnabled()) { + $cronHelper->addProductToCrawlerQueue($product); + foreach ($banHelper->getParentProducts($product) + as $parentProduct) { + $cronHelper->addProductToCrawlerQueue($parentProduct); } } } @@ -109,27 +109,27 @@ public function banProductPageCache( $eventObject ) { * @param Varien_Object $eventObject * @return null */ - public function banProductPageCacheCheckStock( $eventObject ) { - if( Mage::helper( 'turpentine/varnish' )->getVarnishEnabled() ) { + public function banProductPageCacheCheckStock($eventObject) { + if (Mage::helper('turpentine/varnish')->getVarnishEnabled()) { $item = $eventObject->getItem(); - if( $item->getStockStatusChangedAutomatically() || - ( $item->getOriginalInventoryQty() <= 0 && + if ($item->getStockStatusChangedAutomatically() || + ($item->getOriginalInventoryQty() <= 0 && $item->getQty() > 0 && - $item->getQtyCorrection() > 0 ) ) { - $banHelper = Mage::helper( 'turpentine/ban' ); - $cronHelper = Mage::helper( 'turpentine/cron' ); - $product = Mage::getModel( 'catalog/product' ) - ->load( $item->getProductId() ); - $urlPattern = $banHelper->getProductBanRegex( $product ); - $result = $this->_getVarnishAdmin()->flushUrl( $urlPattern ); - Mage::dispatchEvent( 'turpentine_ban_product_cache_check_stock', - $result ); - if( $this->_checkResult( $result ) && - $cronHelper->getCrawlerEnabled() ) { - $cronHelper->addProductToCrawlerQueue( $product ); - foreach( $banHelper->getParentProducts( $product ) - as $parentProduct ) { - $cronHelper->addProductToCrawlerQueue( $parentProduct ); + $item->getQtyCorrection() > 0)) { + $banHelper = Mage::helper('turpentine/ban'); + $cronHelper = Mage::helper('turpentine/cron'); + $product = Mage::getModel('catalog/product') + ->load($item->getProductId()); + $urlPattern = $banHelper->getProductBanRegex($product); + $result = $this->_getVarnishAdmin()->flushUrl($urlPattern); + Mage::dispatchEvent('turpentine_ban_product_cache_check_stock', + $result); + if ($this->_checkResult($result) && + $cronHelper->getCrawlerEnabled()) { + $cronHelper->addProductToCrawlerQueue($product); + foreach ($banHelper->getParentProducts($product) + as $parentProduct) { + $cronHelper->addProductToCrawlerQueue($parentProduct); } } } @@ -145,15 +145,15 @@ public function banProductPageCacheCheckStock( $eventObject ) { * @param Varien_Object $eventObject * @return null */ - public function banCategoryCache( $eventObject ) { - if( Mage::helper( 'turpentine/varnish' )->getVarnishEnabled() ) { + public function banCategoryCache($eventObject) { + if (Mage::helper('turpentine/varnish')->getVarnishEnabled()) { $category = $eventObject->getCategory(); - $result = $this->_getVarnishAdmin()->flushUrl( $category->getUrlKey() ); - Mage::dispatchEvent( 'turpentine_ban_category_cache', $result ); - $cronHelper = Mage::helper( 'turpentine/cron' ); - if( $this->_checkResult( $result ) && - $cronHelper->getCrawlerEnabled() ) { - $cronHelper->addCategoryToCrawlerQueue( $category ); + $result = $this->_getVarnishAdmin()->flushUrl($category->getUrlKey()); + Mage::dispatchEvent('turpentine_ban_category_cache', $result); + $cronHelper = Mage::helper('turpentine/cron'); + if ($this->_checkResult($result) && + $cronHelper->getCrawlerEnabled()) { + $cronHelper->addCategoryToCrawlerQueue($category); } } } @@ -168,11 +168,11 @@ public function banCategoryCache( $eventObject ) { * @param Varien_Object $eventObject * @return null */ - public function banMediaCache( $eventObject ) { - if( Mage::helper( 'turpentine/varnish' )->getVarnishEnabled() ) { - $result = $this->_getVarnishAdmin()->flushUrl( 'media/(?:js|css)/' ); - Mage::dispatchEvent( 'turpentine_ban_media_cache', $result ); - $this->_checkResult( $result ); + public function banMediaCache($eventObject) { + if (Mage::helper('turpentine/varnish')->getVarnishEnabled()) { + $result = $this->_getVarnishAdmin()->flushUrl('media/(?:js|css)/'); + Mage::dispatchEvent('turpentine_ban_media_cache', $result); + $this->_checkResult($result); } } @@ -186,12 +186,12 @@ public function banMediaCache( $eventObject ) { * @param Varien_Object $eventObject * @return null */ - public function banCatalogImagesCache( $eventObject ) { - if( Mage::helper( 'turpentine/varnish' )->getVarnishEnabled() ) { + public function banCatalogImagesCache($eventObject) { + if (Mage::helper('turpentine/varnish')->getVarnishEnabled()) { $result = $this->_getVarnishAdmin()->flushUrl( 'media/catalog/product/cache/' ); - Mage::dispatchEvent( 'turpentine_ban_catalog_images_cache', $result ); - $this->_checkResult( $result ); + Mage::dispatchEvent('turpentine_ban_catalog_images_cache', $result); + $this->_checkResult($result); } } @@ -204,15 +204,15 @@ public function banCatalogImagesCache( $eventObject ) { * @param Varien_Object $eventObject * @return null */ - public function banCmsPageCache( $eventObject ) { - if( Mage::helper( 'turpentine/varnish' )->getVarnishEnabled() ) { + public function banCmsPageCache($eventObject) { + if (Mage::helper('turpentine/varnish')->getVarnishEnabled()) { $pageId = $eventObject->getDataObject()->getIdentifier(); - $result = $this->_getVarnishAdmin()->flushUrl( $pageId . '(?:\.html?)?$' ); - Mage::dispatchEvent( 'turpentine_ban_cms_page_cache', $result ); - $cronHelper = Mage::helper( 'turpentine/cron' ); - if( $this->_checkResult( $result ) && - $cronHelper->getCrawlerEnabled() ) { - $cronHelper->addCmsPageToCrawlerQueue( $pageId ); + $result = $this->_getVarnishAdmin()->flushUrl($pageId.'(?:\.html?)?$'); + Mage::dispatchEvent('turpentine_ban_cms_page_cache', $result); + $cronHelper = Mage::helper('turpentine/cron'); + if ($this->_checkResult($result) && + $cronHelper->getCrawlerEnabled()) { + $cronHelper->addCmsPageToCrawlerQueue($pageId); } } } @@ -226,21 +226,21 @@ public function banCmsPageCache( $eventObject ) { * @return null */ public function banCmsPageRevisionCache($eventObject) { - if ( Mage::helper( 'turpentine/varnish' )->getVarnishEnabled() ) { + if (Mage::helper('turpentine/varnish')->getVarnishEnabled()) { $pageId = $eventObject->getDataObject()->getPageId(); - $page = Mage::getModel( 'cms/page' )->load( $pageId ); + $page = Mage::getModel('cms/page')->load($pageId); // Don't do anything if the page isn't found. - if( !$page ) { + if ( ! $page) { return; } $pageIdentifier = $page->getIdentifier(); - $result = $this->_getVarnishAdmin()->flushUrl( $pageIdentifier . '(?:\.html?)?$' ); - Mage::dispatchEvent( 'turpentine_ban_cms_page_cache', $result ); - $cronHelper = Mage::helper( 'turpentine/cron' ); - if( $this->_checkResult( $result ) && - $cronHelper->getCrawlerEnabled() ) { - $cronHelper->addCmsPageToCrawlerQueue( $pageIdentifier ); + $result = $this->_getVarnishAdmin()->flushUrl($pageIdentifier.'(?:\.html?)?$'); + Mage::dispatchEvent('turpentine_ban_cms_page_cache', $result); + $cronHelper = Mage::helper('turpentine/cron'); + if ($this->_checkResult($result) && + $cronHelper->getCrawlerEnabled()) { + $cronHelper->addCmsPageToCrawlerQueue($pageIdentifier); } } } @@ -256,11 +256,11 @@ public function banCmsPageRevisionCache($eventObject) { * @param Varien_Object $eventObject * @return null */ - public function banAllCache( $eventObject ) { - if( Mage::helper( 'turpentine/varnish' )->getVarnishEnabled() ) { + public function banAllCache($eventObject) { + if (Mage::helper('turpentine/varnish')->getVarnishEnabled()) { $result = $this->_getVarnishAdmin()->flushAll(); - Mage::dispatchEvent( 'turpentine_ban_all_cache', $result ); - $this->_checkResult( $result ); + Mage::dispatchEvent('turpentine_ban_all_cache', $result); + $this->_checkResult($result); } } @@ -273,20 +273,20 @@ public function banAllCache( $eventObject ) { * @param Varien_Object $eventObject * @return null */ - public function banCacheType( $eventObject ) { - switch( $eventObject->getType() ) { + public function banCacheType($eventObject) { + switch ($eventObject->getType()) { //note this is the name of the container xml tag in config.xml, // **NOT** the cache tag name - case Mage::helper( 'turpentine/esi' )->getMageCacheName(): - if( Mage::helper( 'turpentine/esi' )->getEsiEnabled() ) { + case Mage::helper('turpentine/esi')->getMageCacheName(): + if (Mage::helper('turpentine/esi')->getEsiEnabled()) { $result = $this->_getVarnishAdmin()->flushUrl( '/turpentine/esi/getBlock/' ); - Mage::dispatchEvent( 'turpentine_ban_esi_cache', $result ); - $this->_checkResult( $result ); + Mage::dispatchEvent('turpentine_ban_esi_cache', $result); + $this->_checkResult($result); } break; - case Mage::helper( 'turpentine/varnish' )->getMageCacheName(): - $this->banAllCache( $eventObject ); + case Mage::helper('turpentine/varnish')->getMageCacheName(): + $this->banAllCache($eventObject); break; } } @@ -297,7 +297,7 @@ public function banCacheType( $eventObject ) { * @param Varien_Object $eventObject * @return bool */ - public function banProductReview( $eventObject ) { + public function banProductReview($eventObject) { $patterns = array(); /* @var $review \Mage_Review_Model_Review*/ $review = $eventObject->getObject(); @@ -305,30 +305,30 @@ public function banProductReview( $eventObject ) { /* @var $productCollection \Mage_Review_Model_Resource_Review_Product_Collection*/ $productCollection = $review->getProductCollection(); - $products = $productCollection->addEntityFilter((int)$review->getEntityPkValue())->getItems(); + $products = $productCollection->addEntityFilter((int) $review->getEntityPkValue())->getItems(); - $productIds = array_unique( array_map( - create_function( '$p', 'return $p->getEntityId();' ), - $products ) ); - $patterns[] = sprintf( '/review/product/list/id/(?:%s)/category/', - implode( '|', array_unique( $productIds ) ) ); - $patterns[] = sprintf( '/review/product/view/id/%d/', - $review->getEntityId() ); + $productIds = array_unique(array_map( + create_function('$p', 'return $p->getEntityId();'), + $products )); + $patterns[] = sprintf('/review/product/list/id/(?:%s)/category/', + implode('|', array_unique($productIds))); + $patterns[] = sprintf('/review/product/view/id/%d/', + $review->getEntityId()); $productPatterns = array(); - foreach ( $products as $p ) { - $urlKey = $p->getUrlModel()->formatUrlKey( $p->getName() ); - if ( $urlKey ) { + foreach ($products as $p) { + $urlKey = $p->getUrlModel()->formatUrlKey($p->getName()); + if ($urlKey) { $productPatterns[] = $urlKey; } } - if ( !empty($productPatterns) ) { - $productPatterns = array_unique( $productPatterns ); - $patterns[] = sprintf( '(?:%s)', implode( '|', $productPatterns ) ); + if ( ! empty($productPatterns)) { + $productPatterns = array_unique($productPatterns); + $patterns[] = sprintf('(?:%s)', implode('|', $productPatterns)); } - $urlPattern = implode( '|', $patterns ); + $urlPattern = implode('|', $patterns); - $result = $this->_getVarnishAdmin()->flushUrl( $urlPattern ); - return $this->_checkResult( $result ); + $result = $this->_getVarnishAdmin()->flushUrl($urlPattern); + return $this->_checkResult($result); } /** @@ -337,11 +337,11 @@ public function banProductReview( $eventObject ) { * @param array $result stored as $socketName => $result * @return bool */ - protected function _checkResult( $result ) { + protected function _checkResult($result) { $rvalue = true; - foreach( $result as $socketName => $value ) { - if( $value !== true ) { - Mage::helper( 'turpentine/debug' )->logWarn( + foreach ($result as $socketName => $value) { + if ($value !== true) { + Mage::helper('turpentine/debug')->logWarn( 'Error in Varnish action result for server [%s]: %s', $socketName, $value ); $rvalue = false; @@ -356,8 +356,8 @@ protected function _checkResult( $result ) { * @return Nexcessnet_Turpentine_Model_Varnish_Admin */ protected function _getVarnishAdmin() { - if( is_null( $this->_varnishAdmin ) ) { - $this->_varnishAdmin = Mage::getModel( 'turpentine/varnish_admin' ); + if (is_null($this->_varnishAdmin)) { + $this->_varnishAdmin = Mage::getModel('turpentine/varnish_admin'); } return $this->_varnishAdmin; } diff --git a/app/code/community/Nexcessnet/Turpentine/Model/Observer/Cron.php b/app/code/community/Nexcessnet/Turpentine/Model/Observer/Cron.php index 2b80fbfe6..5542cfca7 100644 --- a/app/code/community/Nexcessnet/Turpentine/Model/Observer/Cron.php +++ b/app/code/community/Nexcessnet/Turpentine/Model/Observer/Cron.php @@ -26,14 +26,14 @@ class Nexcessnet_Turpentine_Model_Observer_Cron extends Varien_Event_Observer { * * @var int */ - const MAX_CRAWL_TIME = 300; + const MAX_CRAWL_TIME = 300; /** * Amount of time of execution time to leave for other cron processes * * @var int */ - const EXEC_TIME_BUFFER = 15; + const EXEC_TIME_BUFFER = 15; /** * Crawl available URLs in the queue until we get close to max_execution_time @@ -42,19 +42,19 @@ class Nexcessnet_Turpentine_Model_Observer_Cron extends Varien_Event_Observer { * @param Varien_Object $eventObject * @return null */ - public function crawlUrls( $eventObject ) { - $helper = Mage::helper( 'turpentine/cron' ); - if( $helper->getCrawlerEnabled() ) { + public function crawlUrls($eventObject) { + $helper = Mage::helper('turpentine/cron'); + if ($helper->getCrawlerEnabled()) { $maxRunTime = $helper->getAllowedRunTime(); - if( $maxRunTime === 0 ) { + if ($maxRunTime === 0) { $maxRunTime = self::MAX_CRAWL_TIME; } // just in case we have a silly short max_execution_time - $maxRunTime = abs( $maxRunTime - self::EXEC_TIME_BUFFER ); - while( ( $helper->getRunTime() < $maxRunTime ) && - $url = $helper->getNextUrl() ) { - if( !$this->_crawlUrl( $url ) ) { - Mage::helper( 'turpentine/debug' )->logWarn( + $maxRunTime = abs($maxRunTime - self::EXEC_TIME_BUFFER); + while (($helper->getRunTime() < $maxRunTime) && + $url = $helper->getNextUrl()) { + if ( ! $this->_crawlUrl($url)) { + Mage::helper('turpentine/debug')->logWarn( 'Failed to crawl URL: %s', $url ); } } @@ -67,10 +67,10 @@ public function crawlUrls( $eventObject ) { * @param Varien_Object $eventObject * @return null */ - public function queueAllUrls( $eventObject ) { - $helper = Mage::helper( 'turpentine/cron' ); - if( $helper->getCrawlerEnabled() ) { - $helper->addUrlsToCrawlerQueue( $helper->getAllUrls() ); + public function queueAllUrls($eventObject) { + $helper = Mage::helper('turpentine/cron'); + if ($helper->getCrawlerEnabled()) { + $helper->addUrlsToCrawlerQueue($helper->getAllUrls()); } } @@ -80,14 +80,14 @@ public function queueAllUrls( $eventObject ) { * @param string $url * @return bool */ - protected function _crawlUrl( $url ) { - $client = Mage::helper( 'turpentine/cron' )->getCrawlerClient(); - $client->setUri( $url ); - Mage::helper( 'turpentine/debug' )->logDebug( 'Crawling URL: %s', $url ); + protected function _crawlUrl($url) { + $client = Mage::helper('turpentine/cron')->getCrawlerClient(); + $client->setUri($url); + Mage::helper('turpentine/debug')->logDebug('Crawling URL: %s', $url); try { $response = $client->request(); - } catch( Exception $e ) { - Mage::helper( 'turpentine/debug' )->logWarn( + } catch (Exception $e) { + Mage::helper('turpentine/debug')->logWarn( 'Error crawling URL (%s): %s', $url, $e->getMessage() ); return false; diff --git a/app/code/community/Nexcessnet/Turpentine/Model/Observer/Debug.php b/app/code/community/Nexcessnet/Turpentine/Model/Observer/Debug.php index 03bca7f02..0b5d154c0 100644 --- a/app/code/community/Nexcessnet/Turpentine/Model/Observer/Debug.php +++ b/app/code/community/Nexcessnet/Turpentine/Model/Observer/Debug.php @@ -27,9 +27,9 @@ class Nexcessnet_Turpentine_Model_Observer_Debug extends Varien_Event_Observer { * @param Varien_Object $eventObject * @return null */ - public function logEvent( $eventObject ) { - Mage::helper( 'turpentine/debug' )->log( 'EVENT: %s', - $eventObject->getEvent()->getName() ); + public function logEvent($eventObject) { + Mage::helper('turpentine/debug')->log('EVENT: %s', + $eventObject->getEvent()->getName()); } /** @@ -38,8 +38,8 @@ public function logEvent( $eventObject ) { * @param Varien_Object $eventObject * @return null */ - public function logBackTrace( $eventObject ) { - $this->logEvent( $eventObject ); - Mage::helper( 'turpentine/debug' )->logBackTrace(); + public function logBackTrace($eventObject) { + $this->logEvent($eventObject); + Mage::helper('turpentine/debug')->logBackTrace(); } } diff --git a/app/code/community/Nexcessnet/Turpentine/Model/Observer/Esi.php b/app/code/community/Nexcessnet/Turpentine/Model/Observer/Esi.php index 5124e706e..800cfb486 100644 --- a/app/code/community/Nexcessnet/Turpentine/Model/Observer/Esi.php +++ b/app/code/community/Nexcessnet/Turpentine/Model/Observer/Esi.php @@ -28,7 +28,7 @@ class Nexcessnet_Turpentine_Model_Observer_Esi extends Varien_Event_Observer { * @param Varien_Object $eventObject * @return null */ - public function setCustomerGroupCookie( $eventObject ) { + public function setCustomerGroupCookie($eventObject) { $customer = $eventObject->getCustomer(); $cookie = Mage::getSingleton('core/cookie'); if (Mage::getStoreConfig('persistent/options/enabled')) { @@ -46,7 +46,7 @@ public function setCustomerGroupCookie( $eventObject ) { * @param Varien_Object $eventObject * @return null */ - public function removeCustomerGroupCookie( $eventObject ) { + public function removeCustomerGroupCookie($eventObject) { Mage::getSingleton('core/cookie')->delete('customer_group'); } @@ -58,14 +58,14 @@ public function removeCustomerGroupCookie( $eventObject ) { * @param Varien_Object $eventObject * @return null */ - public function setFlagHeaders( $eventObject ) { + 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( + 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' ) ); + (Mage::registry('turpentine_esi_flag') ? '1' : '0') ); } } @@ -81,14 +81,14 @@ public function setFlagHeaders( $eventObject ) { * @param Varien_Object $eventObject * @return null */ - public function checkCacheFlag( $eventObject ) { - if( Mage::helper( 'turpentine/varnish' )->shouldResponseUseVarnish() ) { + 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 ); + 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 } } @@ -104,29 +104,29 @@ public function checkCacheFlag( $eventObject ) { * @param Varien_Object $eventObject * @return null */ - public function checkRedirectUrl( $eventObject ) { - $esiHelper = Mage::helper( 'turpentine/esi' ); + public function checkRedirectUrl($eventObject) { + $esiHelper = Mage::helper('turpentine/esi'); $url = $eventObject->getTransport()->getUrl(); - $referer = Mage::helper( 'core/http' )->getHttpReferer(); + $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 ) ) { + $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 ); + $eventObject->getTransport()->setUrl($newUrl); } - if( $eventObject->getTransport()->getUrl() != $url ) { - Mage::helper( 'turpentine/debug' )->logDebug( + if ($eventObject->getTransport()->getUrl() != $url) { + Mage::helper('turpentine/debug')->logDebug( 'Detected redirect to ESI URL, changing: %s => %s', $url, $eventObject->getTransport()->getUrl() ); } @@ -138,16 +138,16 @@ public function checkRedirectUrl( $eventObject ) { * @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' ); + 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' ); + Varien_Profiler::stop('turpentine::observer::esi::loadCacheClearEvents'); } /** @@ -160,13 +160,13 @@ public function loadCacheClearEvents( $eventObject ) { * @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' ); + 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'); } } @@ -177,14 +177,14 @@ public function addMessagesBlockRewrite( $eventObject ) { * @param Varien_Object $eventObject * @return null */ - public function setReplaceFormKeyFlag( $eventObject ) { - $esiHelper = Mage::helper( 'turpentine/esi' ); - $varnishHelper = Mage::helper( 'turpentine/varnish' ); + public function setReplaceFormKeyFlag($eventObject) { + $esiHelper = Mage::helper('turpentine/esi'); + $varnishHelper = Mage::helper('turpentine/varnish'); $request = Mage::app()->getRequest(); - if( $esiHelper->shouldResponseUseEsi() && + if ($esiHelper->shouldResponseUseEsi() && $varnishHelper->csrfFixupNeeded() && - !$request->isPost() ) { - Mage::register( 'replace_form_key', true ); + ! $request->isPost()) { + Mage::register('replace_form_key', true); } } @@ -194,16 +194,16 @@ public function setReplaceFormKeyFlag( $eventObject ) { * @param Varien_Object $eventObject * @return null */ - public function replaceFormKeyPlaceholder( $eventObject ) { - if( Mage::registry( 'replace_form_key' ) ) { - $esiHelper = Mage::helper( 'turpentine/esi' ); + 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}}', + $responseBody = str_replace('{{form_key_esi_placeholder}}', $esiHelper->buildEsiIncludeFragment( $esiHelper->getFormKeyEsiUrl() ), - $responseBody ); - $response->setBody( $responseBody ); + $responseBody); + $response->setBody($responseBody); } } @@ -217,35 +217,35 @@ public function replaceFormKeyPlaceholder( $eventObject ) { * @param Varien_Object $eventObject * @return null */ - public function injectEsi( $eventObject ) { + 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() ) { + $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() ); } - if( $esiHelper->shouldResponseUseEsi() && + if ($esiHelper->shouldResponseUseEsi() && $blockObject instanceof Mage_Core_Block_Template && - $esiOptions = $blockObject->getEsiOptions() ) { + $esiOptions = $blockObject->getEsiOptions()) { if ((isset($esiOptions['disableEsiInjection'])) && ($esiOptions['disableEsiInjection'] == 1)) { return; } - if( Mage::app()->getStore()->getCode() == 'admin' ) { + 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() ); + } elseif ($esiHelper->getEsiBlockLogEnabled()) { + $debugHelper->logInfo('Block check passed, injecting block: %s', + $blockObject->getNameInLayout() ? $blockObject->getNameInLayout() : $blockObject->getModuleName()); } - Varien_Profiler::start( 'turpentine::observer::esi::injectEsi' ); + Varien_Profiler::start('turpentine::observer::esi::injectEsi'); $ttlParam = $esiHelper->getEsiTtlParam(); $cacheTypeParam = $esiHelper->getEsiCacheTypeParam(); $dataParam = $esiHelper->getEsiDataParam(); @@ -286,7 +286,7 @@ public function injectEsi( $eventObject ) { } if( $esiOptions[$scopeParam] == 'page' ) { $urlOptions[$referrerParam] = Mage::helper('core')->urlEncode( - Mage::getUrl('*/*/*', array('_use_rewrite' => true, '_current' => true)) + Mage::getUrl('*/*/*', array('_use_rewrite' => true, '_current' => true)) ); } @@ -317,65 +317,65 @@ public function injectEsi( $eventObject ) { * @param array $esiOptions * @return Varien_Object */ - protected function _getEsiData( $blockObject, $esiOptions ) { - Varien_Profiler::start( 'turpentine::observer::esi::_getEsiData' ); - $esiHelper = Mage::helper( 'turpentine/esi' ); + 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->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( + $esiData->setStoreId(Mage::app()->getStore()->getId()); + $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'] ) ) ); + array_keys($esiOptions['flush_events']) )); } else { $esiData->setFlushEvents( $esiHelper->getDefaultCacheClearEvents() ); } } - if( $esiOptions[$scopeParam] == 'page' ) { - $esiData->setParentUrl( Mage::app()->getRequest()->getRequestString() ); + if ($esiOptions[$scopeParam] == 'page') { + $esiData->setParentUrl(Mage::app()->getRequest()->getRequestString()); } - if( is_array( $esiOptions['dummy_blocks'] ) ) { + if (is_array($esiOptions['dummy_blocks'])) { $dummyBlocks = array(); - foreach( $esiOptions['dummy_blocks'] as $key => $value ) { - $dummyBlocks[] = ( empty($value) && !is_numeric($key) ) ? $key : $value; + foreach ($esiOptions['dummy_blocks'] as $key => $value) { + $dummyBlocks[] = (empty($value) && ! is_numeric($key)) ? $key : $value; } - $esiData->setDummyBlocks( $dummyBlocks ); + $esiData->setDummyBlocks($dummyBlocks); } else { - Mage::helper( 'turpentine/debug' )->logWarn( + 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 ) { + 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 ); + $this->_getComplexRegistryData($options, $value); } else { $simpleRegistry[$key] = $value; } } } } else { - Mage::helper( 'turpentine/debug' )->logWarn( + 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' ); + $esiData->setSimpleRegistry($simpleRegistry); + $esiData->setComplexRegistry($complexRegistry); + Varien_Profiler::stop('turpentine::observer::esi::_getEsiData'); return $esiData; } @@ -399,35 +399,35 @@ protected function _getEsiData( $blockObject, $esiOptions ) { * @param Mage_Core_Block_Template $block * @return array */ - protected function _getBlockLayoutHandles( $block ) { - Varien_Profiler::start( 'turpentine::observer::esi::_getBlockLayoutHandles' ); + protected function _getBlockLayoutHandles($block) { + Varien_Profiler::start('turpentine::observer::esi::_getBlockLayoutHandles'); $layout = $block->getLayout(); - $layoutXml = Mage::helper( 'turpentine/esi' )->getLayoutXml(); + $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 = current( $layout->getNode()->xpath( sprintf( + $blockNode = current($layout->getNode()->xpath(sprintf( '//block[@name=\'%s\']', - $block->getNameInLayout() ) ) ); - $childBlocks = Mage::helper( 'turpentine/data' ) - ->getChildBlockNames( $blockNode ); - foreach( $childBlocks as $blockName ) { - foreach( $layout->getUpdate()->getHandles() as $handle ) { + $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 ) ) ) ) { + if ($handle !== '' && (strpos($handle, 'THEME') === 0 || + $layoutXml->xpath(sprintf( + '//%s//*[@name=\'%s\']', $handle, $blockName )))) { $activeHandles[] = $handle; } } } - if( !$activeHandles ) { + if ( ! $activeHandles) { $activeHandles[] = 'default'; } - Varien_Profiler::stop( 'turpentine::observer::esi::_getBlockLayoutHandles' ); - return array_unique( $activeHandles ); + Varien_Profiler::stop('turpentine::observer::esi::_getBlockLayoutHandles'); + return array_unique($activeHandles); } /** @@ -435,8 +435,8 @@ protected function _getBlockLayoutHandles( $block ) { * * @return array */ - protected function _getDefaultEsiOptions( $options ) { - $esiHelper = Mage::helper( 'turpentine/esi' ); + protected function _getDefaultEsiOptions($options) { + $esiHelper = Mage::helper('turpentine/esi'); $ttlParam = $esiHelper->getEsiTtlParam(); $methodParam = $esiHelper->getEsiMethodParam(); $cacheTypeParam = $esiHelper->getEsiCacheTypeParam(); @@ -447,12 +447,12 @@ protected function _getDefaultEsiOptions( $options ) { 'dummy_blocks' => array(), 'registry_keys' => array(), ); - $options = array_merge( $defaults, $options ); + $options = array_merge($defaults, $options); // set the default TTL - if( !isset( $options[$ttlParam] ) ) { - if( $options[$cacheTypeParam] == 'private' || $options[$cacheTypeParam] == 'customer_group' ) { - switch( $options[$methodParam] ) { + if ( ! isset($options[$ttlParam])) { + if ($options[$cacheTypeParam] == 'private' || $options[$cacheTypeParam] == 'customer_group') { + switch ($options[$methodParam]) { case 'ajax': $options[$ttlParam] = '0'; break; @@ -463,7 +463,7 @@ protected function _getDefaultEsiOptions( $options ) { break; } } else { - $options[$ttlParam] = Mage::helper( 'turpentine/varnish' ) + $options[$ttlParam] = Mage::helper('turpentine/varnish') ->getDefaultTtl(); } } @@ -478,12 +478,12 @@ protected function _getDefaultEsiOptions( $options ) { * @param mixed $value * @return array */ - protected function _getComplexRegistryData( $valueOptions, $value ) { + protected function _getComplexRegistryData($valueOptions, $value) { $idMethod = @$valueOptions['id_method'] ? $valueOptions['id_method'] : 'getId'; $model = @$valueOptions['model'] ? - $valueOptions['model'] : Mage::helper( 'turpentine/data' ) - ->getModelName( $value ); + $valueOptions['model'] : Mage::helper('turpentine/data') + ->getModelName($value); $data = array( 'model' => $model, 'id' => $value->{$idMethod}(), @@ -498,11 +498,11 @@ protected function _getComplexRegistryData( $valueOptions, $value ) { * @param string $uencUrl * @return string */ - protected function _fixupUencUrl( $uencUrl ) { - $esiHelper = Mage::helper( 'turpentine/esi' ); + 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 ); + if ($corsOrigin != $esiHelper->getCorsOrigin($uencUrl)) { + return $corsOrigin.parse_url($uencUrl, PHP_URL_PATH); } else { return $uencUrl; } @@ -514,8 +514,8 @@ protected function _fixupUencUrl( $uencUrl ) { * @param string $url * @return bool */ - protected function _checkIsNotEsiUrl( $url ) { - return $url && !preg_match( '~/turpentine/esi/getBlock/~', $url ); + protected function _checkIsNotEsiUrl($url) { + return $url && ! preg_match('~/turpentine/esi/getBlock/~', $url); } /** @@ -524,18 +524,18 @@ protected function _checkIsNotEsiUrl( $url ) { * @param string $url * @return bool */ - protected function _checkIsEsiUrl( $url ) { - return !$this->_checkIsNotEsiUrl( $url ); + 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') { + 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())); } } public function hookToControllerActionPostDispatch($observer) { - if($observer->getEvent()->getControllerAction()->getFullActionName() == 'checkout_cart_add') { + if ($observer->getEvent()->getControllerAction()->getFullActionName() == 'checkout_cart_add') { Mage::dispatchEvent("add_to_cart_after", array('request' => $observer->getControllerAction()->getRequest())); } } diff --git a/app/code/community/Nexcessnet/Turpentine/Model/Observer/Varnish.php b/app/code/community/Nexcessnet/Turpentine/Model/Observer/Varnish.php index d2b2d8a9b..d1e9067c1 100644 --- a/app/code/community/Nexcessnet/Turpentine/Model/Observer/Varnish.php +++ b/app/code/community/Nexcessnet/Turpentine/Model/Observer/Varnish.php @@ -28,15 +28,15 @@ class Nexcessnet_Turpentine_Model_Observer_Varnish extends Varien_Event_Observer * @param mixed $eventObject * @return null */ - public function setCacheFlagHeader( $eventObject ) { + public function setCacheFlagHeader($eventObject) { $response = $eventObject->getResponse(); - if( Mage::helper( 'turpentine/varnish' )->shouldResponseUseVarnish() ) { - $response->setHeader( 'X-Turpentine-Cache', - Mage::registry( 'turpentine_nocache_flag' ) ? '0' : '1' ); - if( Mage::helper( 'turpentine/varnish' )->getVarnishDebugEnabled() ) { - Mage::helper( 'turpentine/debug' )->logDebug( - 'Set Varnish cache flag header to: ' . - ( Mage::registry( 'turpentine_nocache_flag' ) ? '0' : '1' ) ); + if (Mage::helper('turpentine/varnish')->shouldResponseUseVarnish()) { + $response->setHeader('X-Turpentine-Cache', + Mage::registry('turpentine_nocache_flag') ? '0' : '1'); + if (Mage::helper('turpentine/varnish')->getVarnishDebugEnabled()) { + Mage::helper('turpentine/debug')->logDebug( + 'Set Varnish cache flag header to: '. + (Mage::registry('turpentine_nocache_flag') ? '0' : '1') ); } } } @@ -47,11 +47,11 @@ public function setCacheFlagHeader( $eventObject ) { * @param Varien_Object $eventObject * @return null */ - public function addProductListToolbarRewrite( $eventObject ) { - if( Mage::helper( 'turpentine/varnish' )->shouldFixProductListToolbar() ) { - Mage::getSingleton( 'turpentine/shim_mage_core_app' ) - ->shim_addClassRewrite( 'block', 'catalog', 'product_list_toolbar', - 'Nexcessnet_Turpentine_Block_Catalog_Product_List_Toolbar' ); + public function addProductListToolbarRewrite($eventObject) { + if (Mage::helper('turpentine/varnish')->shouldFixProductListToolbar()) { + Mage::getSingleton('turpentine/shim_mage_core_app') + ->shim_addClassRewrite('block', 'catalog', 'product_list_toolbar', + 'Nexcessnet_Turpentine_Block_Catalog_Product_List_Toolbar'); } } @@ -61,33 +61,33 @@ public function addProductListToolbarRewrite( $eventObject ) { * @param mixed $eventObject * @return null */ - public function adminSystemConfigChangedSection( $eventObject ) { - if( Mage::helper( 'turpentine/varnish' )->getVarnishEnabled() && - Mage::helper( 'turpentine/data' )->getAutoApplyOnSave() ) { - $result = Mage::getModel( 'turpentine/varnish_admin' )->applyConfig(); - $session = Mage::getSingleton( 'core/session' ); - foreach( $result as $name => $value ) { - if( $value === true ) { - $session->addSuccess( Mage::helper( 'turpentine/data' ) - ->__( 'VCL successfully applied to: ' . $name ) ); + public function adminSystemConfigChangedSection($eventObject) { + if (Mage::helper('turpentine/varnish')->getVarnishEnabled() && + Mage::helper('turpentine/data')->getAutoApplyOnSave()) { + $result = Mage::getModel('turpentine/varnish_admin')->applyConfig(); + $session = Mage::getSingleton('core/session'); + foreach ($result as $name => $value) { + if ($value === true) { + $session->addSuccess(Mage::helper('turpentine/data') + ->__('VCL successfully applied to: '.$name)); } else { - $session->addError( Mage::helper( 'turpentine/data' ) - ->__( sprintf( 'Failed to apply the VCL to %s: %s', - $name, $value ) ) ); + $session->addError(Mage::helper('turpentine/data') + ->__(sprintf('Failed to apply the VCL to %s: %s', + $name, $value))); } } - $cfgr = Mage::getModel( 'turpentine/varnish_admin' )->getConfigurator(); - if( is_null( $cfgr ) ) { - $session->addError( Mage::helper( 'turpentine/data' ) - ->__( 'Failed to load configurator' ) ); + $cfgr = Mage::getModel('turpentine/varnish_admin')->getConfigurator(); + if (is_null($cfgr)) { + $session->addError(Mage::helper('turpentine/data') + ->__('Failed to load configurator')); } else { - $result = $cfgr->save( $cfgr->generate() ); - if( $result[0] ) { - $session->addSuccess( Mage::helper('turpentine/data' ) - ->__( 'The VCL file has been saved.' ) ); + $result = $cfgr->save($cfgr->generate()); + if ($result[0]) { + $session->addSuccess(Mage::helper('turpentine/data') + ->__('The VCL file has been saved.')); } else { - $session->addError( Mage::helper('turpentine/data' ) - ->__( 'Failed to save the VCL file: ' . $result[1]['message'] ) ); + $session->addError(Mage::helper('turpentine/data') + ->__('Failed to save the VCL file: '.$result[1]['message'])); } } } diff --git a/app/code/community/Nexcessnet/Turpentine/Model/PageCache/Container/Notices.php b/app/code/community/Nexcessnet/Turpentine/Model/PageCache/Container/Notices.php index 670aac48f..f5643e069 100644 --- a/app/code/community/Nexcessnet/Turpentine/Model/PageCache/Container/Notices.php +++ b/app/code/community/Nexcessnet/Turpentine/Model/PageCache/Container/Notices.php @@ -28,7 +28,7 @@ class Nexcessnet_Turpentine_Model_PageCache_Container_Notices * @param string $content * @return boolean */ - public function applyWithoutApp( &$content ) { + public function applyWithoutApp(&$content) { return false; } @@ -39,7 +39,7 @@ public function applyWithoutApp( &$content ) { */ protected function _renderBlock() { $block = new Nexcessnet_Turpentine_Block_Notices(); - $block->setTemplate( 'turpentine/notices.phtml' ); + $block->setTemplate('turpentine/notices.phtml'); return $block->toHtml(); } diff --git a/app/code/community/Nexcessnet/Turpentine/Model/Session.php b/app/code/community/Nexcessnet/Turpentine/Model/Session.php index 3886f8e68..c1b15b219 100644 --- a/app/code/community/Nexcessnet/Turpentine/Model/Session.php +++ b/app/code/community/Nexcessnet/Turpentine/Model/Session.php @@ -22,12 +22,12 @@ class Nexcessnet_Turpentine_Model_Session extends Mage_Core_Model_Session_Abstract { protected $_namespace = 'turpentine'; - public function __construct( $data=array() ) { - $sessionName = isset( $data['name'] ) ? $data['name'] : null; - $this->init( $this->_namespace, $sessionName ); + public function __construct($data = array()) { + $sessionName = isset($data['name']) ? $data['name'] : null; + $this->init($this->_namespace, $sessionName); Mage::dispatchEvent( - sprintf( '%s_session_init', $this->_namespace ), - array( sprintf( '%s_session', $this->_namespace ) => $this ) ); + sprintf('%s_session_init', $this->_namespace), + array(sprintf('%s_session', $this->_namespace) => $this) ); } /** @@ -37,11 +37,11 @@ public function __construct( $data=array() ) { * @param array $messages * @return null */ - public function saveMessages( $blockName, $messages ) { + public function saveMessages($blockName, $messages) { $allMessages = $this->getMessages(); $allMessages[$blockName] = array_merge( - $this->loadMessages( $blockName ), $messages ); - $this->setMessages( $allMessages ); + $this->loadMessages($blockName), $messages ); + $this->setMessages($allMessages); } /** @@ -50,9 +50,9 @@ public function saveMessages( $blockName, $messages ) { * @param string $blockName * @return array */ - public function loadMessages( $blockName ) { + public function loadMessages($blockName) { $messages = $this->getMessages(); - if( is_array( @$messages[$blockName] ) ) { + if (is_array(@$messages[$blockName])) { return $messages[$blockName]; } else { return array(); @@ -65,21 +65,20 @@ public function loadMessages( $blockName ) { * @param string $blockName * @return null */ - public function clearMessages( $blockName ) { + public function clearMessages($blockName) { $messages = $this->getMessages(); - unset( $messages[$blockName] ); - $this->setMessages( $messages ); + unset($messages[$blockName]); + $this->setMessages($messages); } /** * Retrieve the stored messages * - * @param boolean $clear=false * @return array */ - public function getMessages( $clear=false ) { - $messages = $this->getData( 'messages' ); - if( !is_array( $messages ) ) { + public function getMessages($clear = false) { + $messages = $this->getData('messages'); + if ( ! is_array($messages)) { $messages = array(); } return $messages; @@ -90,7 +89,7 @@ public function getMessages( $clear=false ) { * * @param array $messages */ - public function setMessages( $messages ) { - $this->setData( 'messages', $messages ); + public function setMessages($messages) { + $this->setData('messages', $messages); } } diff --git a/app/code/community/Nexcessnet/Turpentine/Model/Shim/Mage/Core/App.php b/app/code/community/Nexcessnet/Turpentine/Model/Shim/Mage/Core/App.php index c5898af95..07f1b67e4 100644 --- a/app/code/community/Nexcessnet/Turpentine/Model/Shim/Mage/Core/App.php +++ b/app/code/community/Nexcessnet/Turpentine/Model/Shim/Mage/Core/App.php @@ -35,9 +35,9 @@ class Nexcessnet_Turpentine_Model_Shim_Mage_Core_App extends Mage_Core_Model_App */ public function shim_setRequest(Mage_Core_Controller_Request_Http $request) { $app = $this->_shim_getApp(); - if( method_exists( $app, 'setRequest' ) ) { + if (method_exists($app, 'setRequest')) { // use the real setRequest if it's available - $app->setRequest( $request ); + $app->setRequest($request); } else { $app->_request = $request; } @@ -55,12 +55,12 @@ public function shim_setRequest(Mage_Core_Controller_Request_Http $request) { * @param string $method name of the method to call * @return Nexcessnet_Turpentine_Model_Shim_Mage_Core_App */ - public function shim_addEventObserver( $area, $eventName, $obsName, - $type=null, $class=null, $method=null ) { + public function shim_addEventObserver($area, $eventName, $obsName, + $type = null, $class = null, $method = null) { $eventConfig = new Varien_Simplexml_Config(); - $eventConfig->loadDom( $this->_shim_getEventDom( - $area, $eventName, $obsName, $type, $class, $method ) ); - $this->_shim_getConfig()->extend( $eventConfig, true ); + $eventConfig->loadDom($this->_shim_getEventDom( + $area, $eventName, $obsName, $type, $class, $method )); + $this->_shim_getConfig()->extend($eventConfig, true); // this wouldn't work if PHP had a sane object model $this->_shim_getApp()->_events[$area][$eventName] = null; /* clear the event area cache because by the time this gets executed all events have already been @@ -78,12 +78,12 @@ public function shim_addEventObserver( $area, $eventName, $obsName, * @param string $rewriteTarget full class name to rewrite to * @return Nexcessnet_Turpentine_Model_Shim_Mage_Core_App */ - public function shim_addClassRewrite( $type, $module, $class, - $rewriteTarget ) { + public function shim_addClassRewrite($type, $module, $class, + $rewriteTarget) { $rewriteConfig = new Varien_Simplexml_Config(); - $rewriteConfig->loadDom( $this->_shim_getRewriteDom( - $type, $module, $class, $rewriteTarget ) ); - $this->_shim_getConfig()->extend( $rewriteConfig, true ); + $rewriteConfig->loadDom($this->_shim_getRewriteDom( + $type, $module, $class, $rewriteTarget )); + $this->_shim_getConfig()->extend($rewriteConfig, true); $this->_shim_getConfigShim()->shim_setClassNameCache( $type, $module, $class, $rewriteTarget ); return $this; @@ -100,25 +100,25 @@ public function shim_addClassRewrite( $type, $module, $class, * @param string $method * @return DOMDocument */ - protected function _shim_getEventDom( $area, $eventName, $obsName, - $type=null, $class=null, $method=null ) { - $dom = new DOMDocument( '1.0' ); - $config = $dom->createElement( 'config' ); + protected function _shim_getEventDom($area, $eventName, $obsName, + $type = null, $class = null, $method = null) { + $dom = new DOMDocument('1.0'); + $config = $dom->createElement('config'); $observers = $config - ->appendChild( $dom->createElement( $area ) ) - ->appendChild( $dom->createElement( 'events' ) ) - ->appendChild( $dom->createElement( $eventName ) ) - ->appendChild( $dom->createElement( 'observers' ) ); - $observer = $dom->createElement( $obsName ); - if( $class && $method ) { - if( $type ) { - $observer->appendChild( $dom->createElement( 'type', $type ) ); + ->appendChild($dom->createElement($area)) + ->appendChild($dom->createElement('events')) + ->appendChild($dom->createElement($eventName)) + ->appendChild($dom->createElement('observers')); + $observer = $dom->createElement($obsName); + if ($class && $method) { + if ($type) { + $observer->appendChild($dom->createElement('type', $type)); } - $observer->appendChild( $dom->createElement( 'class', $class ) ); - $observer->appendChild( $dom->createElement( 'method', $method ) ); + $observer->appendChild($dom->createElement('class', $class)); + $observer->appendChild($dom->createElement('method', $method)); } - $observers->appendChild( $observer ); - $dom->appendChild( $config ); + $observers->appendChild($observer); + $dom->appendChild($config); return $dom; } @@ -131,14 +131,14 @@ protected function _shim_getEventDom( $area, $eventName, $obsName, * @param string $className full class name to rewrite to * @return DOMDocument */ - protected function _shim_getRewriteDom( $groupType, $group, $class, $className ) { - $dom = new DOMDocument( '1.0' ); - $dom->appendChild( $dom->createElement( 'config' ) ) - ->appendChild( $dom->createElement( 'global' ) ) - ->appendChild( $dom->createElement( $groupType . 's' ) ) - ->appendChild( $dom->createElement( $group ) ) - ->appendChild( $dom->createElement( 'rewrite' ) ) - ->appendChild( $dom->createElement( $class, $className ) ); + protected function _shim_getRewriteDom($groupType, $group, $class, $className) { + $dom = new DOMDocument('1.0'); + $dom->appendChild($dom->createElement('config')) + ->appendChild($dom->createElement('global')) + ->appendChild($dom->createElement($groupType.'s')) + ->appendChild($dom->createElement($group)) + ->appendChild($dom->createElement('rewrite')) + ->appendChild($dom->createElement($class, $className)); return $dom; } @@ -166,6 +166,6 @@ protected function _shim_getConfig() { * @return Nexcessnet_Turpentine_Model_Shim_Mage_Core_Config */ protected function _shim_getConfigShim() { - return Mage::getModel( 'turpentine/shim_mage_core_config' ); + return Mage::getModel('turpentine/shim_mage_core_config'); } } diff --git a/app/code/community/Nexcessnet/Turpentine/Model/Shim/Mage/Core/Config.php b/app/code/community/Nexcessnet/Turpentine/Model/Shim/Mage/Core/Config.php index 6c7394076..d3a25d0c9 100644 --- a/app/code/community/Nexcessnet/Turpentine/Model/Shim/Mage/Core/Config.php +++ b/app/code/community/Nexcessnet/Turpentine/Model/Shim/Mage/Core/Config.php @@ -31,7 +31,7 @@ class Nexcessnet_Turpentine_Model_Shim_Mage_Core_Config extends Mage_Core_Model_ * @param string $className full class name to rewrite to * @return string */ - public function shim_setClassNameCache( $groupType, $group, $class, $className ) { + public function shim_setClassNameCache($groupType, $group, $class, $className) { $config = Mage::getConfig(); $prevValue = @$config->_classNameCache[$groupType][$group][$class]; $config->_classNameCache[$groupType][$group][$class] = $className; @@ -45,7 +45,7 @@ public function shim_setClassNameCache( $groupType, $group, $class, $className ) * @param $area string The config area to clear (e.g. 'global') */ public function unsetEventAreaCache($area) { - if(version_compare(Mage::getVersion(),'1.11.0', '>=') // enterprise + if (version_compare(Mage::getVersion(), '1.11.0', '>=') // enterprise || version_compare(Mage::getVersion(), '1.6.0', '>=')) // community unset($this->_eventAreas[$area]); } diff --git a/app/code/community/Nexcessnet/Turpentine/Model/Shim/Mage/Core/Layout.php b/app/code/community/Nexcessnet/Turpentine/Model/Shim/Mage/Core/Layout.php index 99417c2a5..f45bfc5d8 100644 --- a/app/code/community/Nexcessnet/Turpentine/Model/Shim/Mage/Core/Layout.php +++ b/app/code/community/Nexcessnet/Turpentine/Model/Shim/Mage/Core/Layout.php @@ -26,13 +26,13 @@ class Nexcessnet_Turpentine_Model_Shim_Mage_Core_Layout extends Mage_Core_Model_ * @param Mage_Core_Model_Layout_Element $blockNode * @return null */ - public function shim_generateFullBlock( $blockNode ) { + public function shim_generateFullBlock($blockNode) { $layout = $this->_shim_getLayout(); - if( !( $parent = $blockNode->getParent() ) ) { + if ( ! ($parent = $blockNode->getParent())) { $parent = new Varien_Object(); } - $layout->_generateBlock( $blockNode, $parent ); - return $layout->generateBlocks( $blockNode ); + $layout->_generateBlock($blockNode, $parent); + return $layout->generateBlocks($blockNode); } /** @@ -41,11 +41,11 @@ public function shim_generateFullBlock( $blockNode ) { * @param Mage_Core_Model_Layout_Element $node * @return Mage_Core_Model_Layout */ - public function shim_generateAction( $node ) { - if( !( $parentNode = $node->getParent() ) ) { + public function shim_generateAction($node) { + if ( ! ($parentNode = $node->getParent())) { $parentNode = new Varien_Object(); } - return $this->_shim_getLayout()->_generateAction( $node, $parentNode ); + return $this->_shim_getLayout()->_generateAction($node, $parentNode); } /** @@ -54,6 +54,6 @@ public function shim_generateAction( $node ) { * @return Mage_Core_Model_Layout */ protected function _shim_getLayout() { - return Mage::getSingleton( 'core/layout' ); + return Mage::getSingleton('core/layout'); } } diff --git a/app/code/community/Nexcessnet/Turpentine/Model/Varnish/Admin.php b/app/code/community/Nexcessnet/Turpentine/Model/Varnish/Admin.php index a26f5105e..1543ed66d 100644 --- a/app/code/community/Nexcessnet/Turpentine/Model/Varnish/Admin.php +++ b/app/code/community/Nexcessnet/Turpentine/Model/Varnish/Admin.php @@ -30,7 +30,7 @@ class Nexcessnet_Turpentine_Model_Varnish_Admin { * @return bool */ public function flushAll() { - return $this->flushUrl( '.*' ); + return $this->flushUrl('.*'); } /** @@ -39,15 +39,15 @@ public function flushAll() { * @param string $subPattern regex to match against URLs * @return bool */ - public function flushUrl( $subPattern ) { + public function flushUrl($subPattern) { $result = array(); - foreach( Mage::helper( 'turpentine/varnish' )->getSockets() as $socket ) { + foreach (Mage::helper('turpentine/varnish')->getSockets() as $socket) { $socketName = $socket->getConnectionString(); try { // We don't use "ban_url" here, because we want to do lurker friendly bans. // Lurker friendly bans get cleaned up, so they don't slow down Varnish. - $socket->ban( 'obj.http.X-Varnish-URL', '~', $subPattern ); - } catch( Mage_Core_Exception $e ) { + $socket->ban('obj.http.X-Varnish-URL', '~', $subPattern); + } catch (Mage_Core_Exception $e) { $result[$socketName] = $e->getMessage(); continue; } @@ -65,11 +65,11 @@ public function flushUrl( $subPattern ) { public function flushExpression() { $args = func_get_args(); $result = array(); - foreach( Mage::helper( 'turpentine/varnish' )->getSockets() as $socket ) { + foreach (Mage::helper('turpentine/varnish')->getSockets() as $socket) { $socketName = $socket->getConnectionString(); try { - call_user_func_array( array( $socket, 'ban' ), $args ); - } catch( Mage_Core_Exception $e ) { + call_user_func_array(array($socket, 'ban'), $args); + } catch (Mage_Core_Exception $e) { $result[$socketName] = $e->getMessage(); continue; } @@ -84,7 +84,7 @@ public function flushExpression() { * @param string $contentType * @return array */ - public function flushContentType( $contentType ) { + public function flushContentType($contentType) { return $this->flushExpression( 'obj.http.Content-Type', '~', $contentType ); } @@ -96,7 +96,7 @@ public function flushContentType( $contentType ) { */ public function applyConfig() { $result = array(); - $helper = Mage::helper( 'turpentine' ); + $helper = Mage::helper( 'turpentine' ); foreach( Mage::helper( 'turpentine/varnish' )->getSockets() as $socket ) { $cfgr = Nexcessnet_Turpentine_Model_Varnish_Configurator_Abstract::getFromSocket( $socket ); $socketName = $socket->getConnectionString(); @@ -127,50 +127,50 @@ public function applyConfig() { * @return Nexcessnet_Turpentine_Model_Varnish_Configurator_Abstract */ public function getConfigurator() { - $sockets = Mage::helper( 'turpentine/varnish' )->getSockets(); - $cfgr = Nexcessnet_Turpentine_Model_Varnish_Configurator_Abstract::getFromSocket( $sockets[0] ); + $sockets = Mage::helper('turpentine/varnish')->getSockets(); + $cfgr = Nexcessnet_Turpentine_Model_Varnish_Configurator_Abstract::getFromSocket($sockets[0]); return $cfgr; } - protected function _testEsiSyntaxParam( $socket ) { - $session = Mage::getSingleton( 'adminhtml/session' ); - $helper = Mage::helper( 'turpentine/varnish' ); + protected function _testEsiSyntaxParam($socket) { + $session = Mage::getSingleton('adminhtml/session'); + $helper = Mage::helper('turpentine/varnish'); $result = false; - if( $helper->csrfFixupNeeded() ) { - if ( $socket->getVersion()==='4.0' ) { + if ($helper->csrfFixupNeeded()) { + if ($socket->getVersion() === '4.0') { $paramName = 'feature'; - $value = $socket->param_show( $paramName ); + $value = $socket->param_show($paramName); $value = explode("\n", $value['text']); - if ( isset($value[1]) && strpos($value[1], '+esi_ignore_other_elements')!==false ) { + if (isset($value[1]) && strpos($value[1], '+esi_ignore_other_elements') !== false) { $result = true; } else { - $session->addWarning( 'Varnish feature param is ' . - 'not set correctly, please see these instructions ' . - 'to fix this warning.' ); + $session->addWarning('Varnish feature param is '. + 'not set correctly, please see these instructions '. + 'to fix this warning.'); } } else { $paramName = 'esi_syntax'; - $value = $socket->param_show( $paramName ); - if( preg_match( '~(\d)\s+\[bitmap\]~', $value['text'], $match ) ) { - $value = hexdec( $match[1] ); - if( $value & self::MASK_ESI_SYNTAX ) { //bitwise intentional + $value = $socket->param_show($paramName); + if (preg_match('~(\d)\s+\[bitmap\]~', $value['text'], $match)) { + $value = hexdec($match[1]); + if ($value & self::MASK_ESI_SYNTAX) { //bitwise intentional // setting is correct, all is fine $result = true; } else { - $session->addWarning( 'Varnish esi_syntax param is ' . - 'not set correctly, please see these instructions ' . - 'to fix this warning.' ); + $session->addWarning('Varnish esi_syntax param is '. + 'not set correctly, please see these instructions '. + 'to fix this warning.'); } } } - if ( $result===false ) { + if ($result === false) { // error - Mage::helper( 'turpentine/debug' )->logWarn( - sprintf('Failed to parse param.show output to check %s value', $paramName ) ); + Mage::helper('turpentine/debug')->logWarn( + sprintf('Failed to parse param.show output to check %s value', $paramName) ); $result = true; } } else { diff --git a/app/code/community/Nexcessnet/Turpentine/Model/Varnish/Admin/Socket.php b/app/code/community/Nexcessnet/Turpentine/Model/Varnish/Admin/Socket.php index 68b9540ea..acca508dc 100644 --- a/app/code/community/Nexcessnet/Turpentine/Model/Varnish/Admin/Socket.php +++ b/app/code/community/Nexcessnet/Turpentine/Model/Varnish/Admin/Socket.php @@ -82,7 +82,7 @@ class Nexcessnet_Turpentine_Model_Varnish_Admin_Socket { // varnish default, can only be changed at Varnish startup time // if data to write is over this limit the actual run-time limit is checked // and used - const CLI_CMD_LENGTH_LIMIT = 8192; + const CLI_CMD_LENGTH_LIMIT = 8192; /** * Regexp to detect the varnish version number @@ -93,7 +93,7 @@ class Nexcessnet_Turpentine_Model_Varnish_Admin_Socket { /** * VCL config versions, should match config select values */ - static protected $_VERSIONS = array( '2.1', '3.0', '4.0' ); + static protected $_VERSIONS = array('2.1', '3.0', '4.0'); /** * Varnish socket connection @@ -108,23 +108,23 @@ class Nexcessnet_Turpentine_Model_Varnish_Admin_Socket { protected $_timeout = 5; protected $_version = null; //auto-detect - public function __construct( array $options=array() ) { - foreach( $options as $key => $value ) { - switch( $key ) { + public function __construct(array $options = array()) { + foreach ($options as $key => $value) { + switch ($key) { case 'host': - $this->setHost( $value ); + $this->setHost($value); break; case 'port': - $this->setPort( $value ); + $this->setPort($value); break; case 'auth_secret': - $this->setAuthSecret( $value ); + $this->setAuthSecret($value); break; case 'timeout': - $this->setTimeout( $value ); + $this->setTimeout($value); break; case 'version': - $this->setVersion( $value ); + $this->setVersion($value); break; default: break; @@ -157,10 +157,10 @@ public function __construct( array $options=array() ) { * @param array $args method args * @return array */ - public function __call( $name, $args ) { - array_unshift( $args, self::CODE_OK ); - array_unshift( $args, $this->_translateCommandMethod( $name ) ); - return call_user_func_array( array( $this, '_command' ), $args ); + public function __call($name, $args) { + array_unshift($args, self::CODE_OK); + array_unshift($args, $this->_translateCommandMethod($name)); + return call_user_func_array(array($this, '_command'), $args); } /** @@ -169,7 +169,7 @@ public function __call( $name, $args ) { * @return string */ public function getConnectionString() { - return sprintf( '%s:%d', $this->getHost(), $this->getPort() ); + return sprintf('%s:%d', $this->getHost(), $this->getPort()); } /** @@ -186,7 +186,7 @@ public function getHost() { * * @param string $host hostname or ip */ - public function setHost( $host ) { + public function setHost($host) { $this->_close(); $this->_host = $host; return $this; @@ -206,9 +206,9 @@ public function getPort() { * * @param int $port */ - public function setPort( $port ) { + public function setPort($port) { $this->_close(); - $this->_port = (int)$port; + $this->_port = (int) $port; return $this; } @@ -217,7 +217,7 @@ public function setPort( $port ) { * * @param string $authSecret */ - public function setAuthSecret( $authSecret=null ) { + public function setAuthSecret($authSecret = null) { $this->_authSecret = $authSecret; return $this; } @@ -227,10 +227,10 @@ public function setAuthSecret( $authSecret=null ) { * * @param int $timeout */ - public function setTimeout( $timeout ) { - $this->_timeout = (int)$timeout; - if( !is_null( $this->_varnishConn ) ) { - stream_set_timeout( $this->_varnishConn, $this->_timeout ); + public function setTimeout($timeout) { + $this->_timeout = (int) $timeout; + if ( ! is_null($this->_varnishConn)) { + stream_set_timeout($this->_varnishConn, $this->_timeout); } return $this; } @@ -240,11 +240,11 @@ public function setTimeout( $timeout ) { * * @param string $version version from $_VERSIONS */ - public function setVersion( $version ) { - if( in_array( $version, self::$_VERSIONS ) ) { + public function setVersion($version) { + if (in_array($version, self::$_VERSIONS)) { $this->_version = $version; } else { - Mage::throwException( 'Unsupported Varnish version: ' . $version ); + Mage::throwException('Unsupported Varnish version: '.$version); } } @@ -254,7 +254,7 @@ public function setVersion( $version ) { * @return boolean */ public function isConnected() { - return !is_null( $this->_varnishConn ); + return ! is_null($this->_varnishConn); } /** @@ -263,7 +263,7 @@ public function isConnected() { * @return string */ public function getVersion() { - if ( !$this->isConnected() ) { + if ( ! $this->isConnected()) { $this->_connect(); } return $this->_version; @@ -273,7 +273,7 @@ public function getVersion() { * Stop the Varnish instance */ public function quit() { - $this->_command( 'quit', self::CODE_CLOSE ); + $this->_command('quit', self::CODE_CLOSE); $this->_close(); } @@ -283,8 +283,8 @@ public function quit() { * @return boolean */ public function status() { - $response = $this->_command( 'status' ); - if( !preg_match( '~Child in state (\w+)~', $response['text'], $match ) ) { + $response = $this->_command('status'); + if ( ! preg_match('~Child in state (\w+)~', $response['text'], $match)) { return false; } else { return $match[1] === 'running'; @@ -297,8 +297,8 @@ public function status() { * @return $this */ public function stop() { - if( $this->status() ) { - $this->_command( 'stop' ); + if ($this->status()) { + $this->_command('stop'); } return $this; } @@ -309,40 +309,40 @@ public function stop() { * @return $this */ public function start() { - $this->_command( 'start' ); + $this->_command('start'); return $this; } /** * Establish a connection to the configured Varnish instance * - * @return array + * @return boolean */ protected function _connect() { - $this->_varnishConn = fsockopen( $this->_host, $this->_port, $errno, - $errstr, $this->_timeout ); - if( !is_resource( $this->_varnishConn ) ) { - Mage::throwException( sprintf( + $this->_varnishConn = fsockopen($this->_host, $this->_port, $errno, + $errstr, $this->_timeout); + if ( ! is_resource($this->_varnishConn)) { + Mage::throwException(sprintf( 'Failed to connect to Varnish on [%s:%d]: (%d) %s', - $this->_host, $this->_port, $errno, $errstr ) ); + $this->_host, $this->_port, $errno, $errstr )); } - stream_set_blocking( $this->_varnishConn, 1 ); - stream_set_timeout( $this->_varnishConn, $this->_timeout ); + stream_set_blocking($this->_varnishConn, 1); + stream_set_timeout($this->_varnishConn, $this->_timeout); //varnish 2.0 doesn't spit out a banner on connection, this will need //to be changed if 2.0 support is ever added $banner = $this->_read(); - if( $banner['code'] === self::CODE_AUTH ) { - $challenge = substr( $banner['text'], 0, 32 ); - $response = hash( 'sha256', sprintf( "%s\n%s%s\n", $challenge, - $this->_authSecret, $challenge ) ); - $banner = $this->_command( 'auth', self::CODE_OK, $response ); + if ($banner['code'] === self::CODE_AUTH) { + $challenge = substr($banner['text'], 0, 32); + $response = hash('sha256', sprintf("%s\n%s%s\n", $challenge, + $this->_authSecret, $challenge)); + $banner = $this->_command('auth', self::CODE_OK, $response); } - if( $banner['code'] !== self::CODE_OK ) { - Mage::throwException( 'Varnish admin authentication failed: ' . - $banner['text'] ); + if ($banner['code'] !== self::CODE_OK) { + Mage::throwException('Varnish admin authentication failed: '. + $banner['text']); } if ($this->_version == null) { // If autodetecting @@ -352,23 +352,26 @@ protected function _connect() { return $this->isConnected(); } + /** + * @param string $bannerText + */ protected function _determineVersion($bannerText) { $bannerText = array_filter(explode("\n", $bannerText)); - if ( count($bannerText)<6 ) { + if (count($bannerText) < 6) { // Varnish 2.0 does not spit out a banner on connect Mage::throwException('Varnish versions before 2.1 are not supported'); } - if ( count($bannerText)<7 ) { + if (count($bannerText) < 7) { // Varnish before 3.0.4 does not spit out a version number - $resp = $this->_write( 'help' )->_read(); - if( strpos( $resp['text'], 'ban.url' ) !== false ) { + $resp = $this->_write('help')->_read(); + if (strpos($resp['text'], 'ban.url') !== false) { // Varnish versions 3.0 through 3.0.3 do not return a version banner. // To differentiate between 2.1 and 3.0, we check the existence of the ban.url command. return '3.0'; } return '2.1'; - } elseif ( preg_match(self::REGEXP_VARNISH_VERSION, $bannerText[4], $matches)===1 ) { - return $matches['vmajor'] . '.' . $matches['vminor']; + } elseif (preg_match(self::REGEXP_VARNISH_VERSION, $bannerText[4], $matches) === 1) { + return $matches['vmajor'].'.'.$matches['vminor']; } else { Mage::throwException('Unable to detect varnish version'); } @@ -380,8 +383,8 @@ protected function _determineVersion($bannerText) { * @return $this */ protected function _close() { - if( $this->isConnected() ) { - fclose( $this->_varnishConn ); + if ($this->isConnected()) { + fclose($this->_varnishConn); $this->_varnishConn = null; } return $this; @@ -393,39 +396,39 @@ protected function _close() { * @param string $data data to write * @return $this */ - protected function _write( $data ) { - if( is_null( $this->_varnishConn ) ) { + protected function _write($data) { + if (is_null($this->_varnishConn)) { $this->_connect(); } - $data = rtrim( $data ) . PHP_EOL; - $dataLength = strlen( $data ); - if( $dataLength >= self::CLI_CMD_LENGTH_LIMIT ) { - $cliBufferResponse = $this->param_show( 'cli_buffer' ); + $data = rtrim($data).PHP_EOL; + $dataLength = strlen($data); + if ($dataLength >= self::CLI_CMD_LENGTH_LIMIT) { + $cliBufferResponse = $this->param_show('cli_buffer'); $regexp = '~^cli_buffer\s+(\d+)\s+\[bytes\]~'; - if ( $this->getVersion()==='4.0' ) { + if ($this->getVersion() === '4.0') { // Varnish4 supports "16k" style notation $regexp = '~^cli_buffer\s+Value is:\s+(\d+)([k|m|g]{1})?\s+\[bytes\]~'; } - if( preg_match( $regexp, $cliBufferResponse['text'], $match ) ) { - $realLimit = (int)$match[1]; - if ( isset($match[2]) ) { - $factors = array('k'=>1,'m'=>2,'g'=>3); + if (preg_match($regexp, $cliBufferResponse['text'], $match)) { + $realLimit = (int) $match[1]; + if (isset($match[2])) { + $factors = array('k'=>1, 'm'=>2, 'g'=>3); $realLimit *= pow(1024, $factors[$match[2]]); } } else { - Mage::helper( 'turpentine/debug' )->logWarn( + Mage::helper('turpentine/debug')->logWarn( 'Failed to determine Varnish cli_buffer limit, using default' ); $realLimit = self::CLI_CMD_LENGTH_LIMIT; } - if( $dataLength >= $realLimit ) { - Mage::throwException( sprintf( + if ($dataLength >= $realLimit) { + Mage::throwException(sprintf( 'Varnish data to write over length limit by %d characters', - $dataLength - $realLimit ) ); + $dataLength - $realLimit )); } } - if( ( $byteCount = fwrite( $this->_varnishConn, $data ) ) !== $dataLength ) { - Mage::throwException( sprintf( 'Varnish socket write error: %d != %d', - $byteCount, $dataLength ) ); + if (($byteCount = fwrite($this->_varnishConn, $data)) !== $dataLength) { + Mage::throwException(sprintf('Varnish socket write error: %d != %d', + $byteCount, $dataLength)); } return $this; } @@ -438,29 +441,29 @@ protected function _write( $data ) { protected function _read() { $code = null; $len = -1; - while( !feof( $this->_varnishConn ) ) { - $response = fgets( $this->_varnishConn, self::READ_CHUNK_SIZE ); - if( empty( $response ) ) { - $streamMeta = stream_get_meta_data( $this->_varnishConn ); - if( $streamMeta['timed_out'] ) { - Mage::throwException( 'Varnish admin socket timeout' ); + while ( ! feof($this->_varnishConn)) { + $response = fgets($this->_varnishConn, self::READ_CHUNK_SIZE); + if (empty($response)) { + $streamMeta = stream_get_meta_data($this->_varnishConn); + if ($streamMeta['timed_out']) { + Mage::throwException('Varnish admin socket timeout'); } } - if( preg_match( '~^(\d{3}) (\d+)~', $response, $match ) ) { - $code = (int)$match[1]; - $len = (int)$match[2]; + if (preg_match('~^(\d{3}) (\d+)~', $response, $match)) { + $code = (int) $match[1]; + $len = (int) $match[2]; break; } } - if( is_null( $code ) ) { - Mage::throwException( 'Failed to read response code from Varnish' ); + if (is_null($code)) { + Mage::throwException('Failed to read response code from Varnish'); } else { - $response = array( 'code' => $code, 'text' => '' ); - while( !feof( $this->_varnishConn ) && - strlen( $response['text'] ) < $len ) { - $response['text'] .= fgets( $this->_varnishConn, - self::READ_CHUNK_SIZE ); + $response = array('code' => $code, 'text' => ''); + while ( ! feof($this->_varnishConn) && + strlen($response['text']) < $len) { + $response['text'] .= fgets($this->_varnishConn, + self::READ_CHUNK_SIZE); } return $response; } @@ -469,32 +472,32 @@ protected function _read() { /** * [_command description] * @param string $verb command name - * @param integer $okCode=200 code that indicates command was successful + * @param integer $okCode code that indicates command was successful * @param string ... command args * @return array */ - protected function _command( $verb, $okCode=200 ) { + protected function _command($verb, $okCode = 200) { $params = func_get_args(); //remove $verb - array_shift( $params ); + array_shift($params); //remove $okCode (if it exists) - array_shift( $params ); + array_shift($params); $cleanedParams = array(); - foreach( $params as $param ) { - $cp = addcslashes( $param, "\"\\" ); - $cp = str_replace( PHP_EOL, '\n', $cp ); - $cleanedParams[] = sprintf( '"%s"', $cp ); + foreach ($params as $param) { + $cp = addcslashes($param, "\"\\"); + $cp = str_replace(PHP_EOL, '\n', $cp); + $cleanedParams[] = sprintf('"%s"', $cp); } - $data = implode( ' ', array_merge( - array( sprintf( '"%s"', $verb ) ), - $cleanedParams ) ); - $response = $this->_write( $data )->_read(); - if( $response['code'] !== $okCode && !is_null( $okCode ) ) { - Mage::helper( 'turpentine/debug' )->logDebug( + $data = implode(' ', array_merge( + array(sprintf('"%s"', $verb)), + $cleanedParams )); + $response = $this->_write($data)->_read(); + if ($response['code'] !== $okCode && ! is_null($okCode)) { + Mage::helper('turpentine/debug')->logDebug( 'Error on Varnish command: %s', $data ); - Mage::throwException( sprintf( + Mage::throwException(sprintf( "Got unexpected response code from Varnish: %d\n%s", - $response['code'], $response['text'] ) ); + $response['code'], $response['text'] )); } else { return $response; } @@ -512,7 +515,7 @@ protected function _translateCommandMethod( $verb ) { case '2.1': $command = str_replace( 'ban', 'purge', $command ); break; - case '4.0': + case '4.0': case '3.0': $command = str_replace( 'purge', 'ban', $command ); break; diff --git a/app/code/community/Nexcessnet/Turpentine/Model/Varnish/Configurator/Abstract.php b/app/code/community/Nexcessnet/Turpentine/Model/Varnish/Configurator/Abstract.php index 393e00d04..c4808ef47 100644 --- a/app/code/community/Nexcessnet/Turpentine/Model/Varnish/Configurator/Abstract.php +++ b/app/code/community/Nexcessnet/Turpentine/Model/Varnish/Configurator/Abstract.php @@ -21,7 +21,7 @@ abstract class Nexcessnet_Turpentine_Model_Varnish_Configurator_Abstract { - const VCL_CUSTOM_C_CODE_FILE = 'uuid.c'; + const VCL_CUSTOM_C_CODE_FILE = 'uuid.c'; /** * Get the correct version of a configurator from a socket @@ -29,31 +29,31 @@ abstract class Nexcessnet_Turpentine_Model_Varnish_Configurator_Abstract { * @param Nexcessnet_Turpentine_Model_Varnish_Admin_Socket $socket * @return Nexcessnet_Turpentine_Model_Varnish_Configurator_Abstract */ - static public function getFromSocket( $socket ) { + static public function getFromSocket($socket) { try { $version = $socket->getVersion(); - } catch( Mage_Core_Exception $e ) { - Mage::getSingleton( 'core/session' ) - ->addError( 'Error determining Varnish version: ' . - $e->getMessage() ); + } catch (Mage_Core_Exception $e) { + Mage::getSingleton('core/session') + ->addError('Error determining Varnish version: '. + $e->getMessage()); return null; } - switch( $version ) { + switch ($version) { case '4.0': return Mage::getModel( 'turpentine/varnish_configurator_version4', - array( 'socket' => $socket ) ); + array('socket' => $socket) ); case '3.0': return Mage::getModel( 'turpentine/varnish_configurator_version3', - array( 'socket' => $socket ) ); + array('socket' => $socket) ); case '2.1': return Mage::getModel( 'turpentine/varnish_configurator_version2', - array( 'socket' => $socket ) ); + array('socket' => $socket) ); default: - Mage::throwException( 'Unsupported Varnish version' ); + Mage::throwException('Unsupported Varnish version'); } } @@ -72,11 +72,11 @@ static public function getFromSocket( $socket ) { 'vcl_template' => null, ); - public function __construct( $options=array() ) { - $this->_options = array_merge( $this->_options, $options ); + public function __construct($options = array()) { + $this->_options = array_merge($this->_options, $options); } - abstract public function generate($doClean=true); + abstract public function generate($doClean = true); // abstract protected function _getTemplateVars(); /** @@ -85,22 +85,22 @@ abstract public function generate($doClean=true); * @param string $generatedConfig config generated by @generate * @return null */ - public function save( $generatedConfig ) { + public function save($generatedConfig) { $filename = $this->_getVclFilename(); - $dir = dirname( $filename ); - if( !is_dir( $dir ) ) { + $dir = dirname($filename); + if ( ! is_dir($dir)) { // this umask is probably redundant, but just in case... - if( !mkdir( $dir, 0777 & ~umask(), true ) ) { + if ( ! mkdir($dir, 0777 & ~umask(), true)) { $err = error_get_last(); - return array( false, $err ); + return array(false, $err); } } - if( strlen( $generatedConfig ) !== - file_put_contents( $filename, $generatedConfig ) ) { + if (strlen($generatedConfig) !== + file_put_contents($filename, $generatedConfig)) { $err = error_get_last(); - return array( false, $err ); + return array(false, $err); } - return array( true, null ); + return array(true, null); } /** @@ -109,9 +109,9 @@ public function save( $generatedConfig ) { * @param string $baseFilename * @return string */ - protected function _getVclTemplateFilename( $baseFilename ) { - $extensionDir = Mage::getModuleDir( '', 'Nexcessnet_Turpentine' ); - return sprintf( '%s/misc/%s', $extensionDir, $baseFilename ); + protected function _getVclTemplateFilename($baseFilename) { + $extensionDir = Mage::getModuleDir('', 'Nexcessnet_Turpentine'); + return sprintf('%s/misc/%s', $extensionDir, $baseFilename); } /** @@ -121,8 +121,8 @@ protected function _getVclTemplateFilename( $baseFilename ) { */ protected function _getVclFilename() { return $this->_formatTemplate( - Mage::getStoreConfig( 'turpentine_varnish/servers/config_file' ), - array( 'root_dir' => Mage::getBaseDir() ) ); + Mage::getStoreConfig('turpentine_varnish/servers/config_file'), + array('root_dir' => Mage::getBaseDir()) ); } /** @@ -132,8 +132,8 @@ protected function _getVclFilename() { */ protected function _getCustomIncludeFilename() { return $this->_formatTemplate( - Mage::getStoreConfig( 'turpentine_varnish/servers/custom_include_file' ), - array( 'root_dir' => Mage::getBaseDir() ) ); + Mage::getStoreConfig('turpentine_varnish/servers/custom_include_file'), + array('root_dir' => Mage::getBaseDir()) ); } /** @@ -144,13 +144,13 @@ protected function _getCustomIncludeFilename() { * @param array $vars array of key => value replacements * @return string */ - protected function _formatTemplate( $template, array $vars ) { - $needles = array_map( create_function( '$k', 'return "{{".$k."}}";' ), - array_keys( $vars ) ); - $replacements = array_values( $vars ); + protected function _formatTemplate($template, array $vars) { + $needles = array_map(create_function('$k', 'return "{{".$k."}}";'), + array_keys($vars)); + $replacements = array_values($vars); // do replacements, then delete unused template vars - return preg_replace( '~{{[^}]+}}~', '', - str_replace( $needles, $replacements, $template ) ); + return preg_replace('~{{[^}]+}}~', '', + str_replace($needles, $replacements, $template)); } /** @@ -159,8 +159,8 @@ protected function _formatTemplate( $template, array $vars ) { * @param string $subroutine subroutine name * @return string */ - protected function _vcl_call( $subroutine ) { - return sprintf( 'call %s;', $subroutine ); + protected function _vcl_call($subroutine) { + return sprintf('call %s;', $subroutine); } /** @@ -172,10 +172,10 @@ protected function _vcl_call( $subroutine ) { * @return string */ protected function _getAdminFrontname() { - if( Mage::getStoreConfig( 'admin/url/use_custom_path' ) ) { - return Mage::getStoreConfig( 'admin/url/custom_path' ); + if (Mage::getStoreConfig('admin/url/use_custom_path')) { + return Mage::getStoreConfig('admin/url/custom_path'); } else { - return (string)Mage::getConfig()->getNode( + return (string) Mage::getConfig()->getNode( 'admin/routers/adminhtml/args/frontName' ); } } @@ -186,14 +186,14 @@ protected function _getAdminFrontname() { * @return string */ protected function _getNormalizeHostTarget() { - $configHost = trim( Mage::getStoreConfig( - 'turpentine_vcl/normalization/host_target' ) ); - if( $configHost ) { + $configHost = trim(Mage::getStoreConfig( + 'turpentine_vcl/normalization/host_target' )); + if ($configHost) { return $configHost; } else { - $baseUrl = parse_url( Mage::getBaseUrl() ); - if( isset( $baseUrl['port'] ) ) { - return sprintf( '%s:%d', $baseUrl['host'], $baseUrl['port'] ); + $baseUrl = parse_url(Mage::getBaseUrl()); + if (isset($baseUrl['port'])) { + return sprintf('%s:%d', $baseUrl['host'], $baseUrl['port']); } else { return $baseUrl['host']; } @@ -210,11 +210,11 @@ protected function _getNormalizeHostTarget() { */ public function getAllowedHostsRegex() { $hosts = array(); - foreach( Mage::app()->getStores() as $store ) { - $hosts[] = parse_url( $store->getBaseUrl( Mage_Core_Model_Store::URL_TYPE_WEB , false ), PHP_URL_HOST ); + foreach (Mage::app()->getStores() as $store) { + $hosts[] = parse_url($store->getBaseUrl(Mage_Core_Model_Store::URL_TYPE_WEB, false), PHP_URL_HOST); } - $hosts = array_values(array_unique( $hosts )); + $hosts = array_values(array_unique($hosts)); $pattern = '('.implode('|', array_map("preg_quote", $hosts)).')'; return $pattern; @@ -232,8 +232,8 @@ protected function _vcl_sub_allowed_hosts_regex() { return (pass); } EOS; - return $this->_formatTemplate( $tpl, array( - 'allowed_hosts_regex' => $this->getAllowedHostsRegex() ) ); + return $this->_formatTemplate($tpl, array( + 'allowed_hosts_regex' => $this->getAllowedHostsRegex() )); } /** @@ -246,9 +246,9 @@ protected function _vcl_sub_allowed_hosts_regex() { */ public function getBaseUrlPathRegex() { $pattern = '^(%s)(?:(?:index|litespeed)\\.php/)?'; - return sprintf( $pattern, implode( '|', - array_map( create_function( '$x', 'return preg_quote($x,"|");' ), - $this->_getBaseUrlPaths() ) ) ); + return sprintf($pattern, implode('|', + array_map(create_function('$x', 'return preg_quote($x,"|");'), + $this->_getBaseUrlPaths()))); } /** @@ -258,22 +258,22 @@ public function getBaseUrlPathRegex() { */ protected function _getBaseUrlPaths() { $paths = array(); - $linkTypes = array( Mage_Core_Model_Store::URL_TYPE_LINK, + $linkTypes = array(Mage_Core_Model_Store::URL_TYPE_LINK, Mage_Core_Model_Store::URL_TYPE_JS, Mage_Core_Model_Store::URL_TYPE_SKIN, - Mage_Core_Model_Store::URL_TYPE_MEDIA ); - foreach( Mage::app()->getStores() as $store ) { - foreach( $linkTypes as $linkType ) { - $paths[] = parse_url( $store->getBaseUrl( $linkType , false ), - PHP_URL_PATH ); - $paths[] = parse_url( $store->getBaseUrl( $linkType , true ), - PHP_URL_PATH ); + Mage_Core_Model_Store::URL_TYPE_MEDIA); + foreach (Mage::app()->getStores() as $store) { + foreach ($linkTypes as $linkType) { + $paths[] = parse_url($store->getBaseUrl($linkType, false), + PHP_URL_PATH); + $paths[] = parse_url($store->getBaseUrl($linkType, true), + PHP_URL_PATH); } } - $paths = array_unique( $paths ); - usort( $paths, create_function( '$a, $b', - 'return strlen( $b ) - strlen( $a );' ) ); - return array_values( $paths ); + $paths = array_unique($paths); + usort($paths, create_function('$a, $b', + 'return strlen( $b ) - strlen( $a );')); + return array_values($paths); } /** @@ -283,9 +283,9 @@ protected function _getBaseUrlPaths() { * @return string */ protected function _getUrlExcludes() { - $urls = Mage::getStoreConfig( 'turpentine_vcl/urls/url_blacklist' ); - return implode( '|', array_merge( array( $this->_getAdminFrontname(), 'api' ), - Mage::helper( 'turpentine/data' )->cleanExplode( PHP_EOL, $urls ) ) ); + $urls = Mage::getStoreConfig('turpentine_vcl/urls/url_blacklist'); + return implode('|', array_merge(array($this->_getAdminFrontname(), 'api'), + Mage::helper('turpentine/data')->cleanExplode(PHP_EOL, $urls))); } /** @@ -294,7 +294,7 @@ protected function _getUrlExcludes() { * @return string */ protected function _getDefaultTtl() { - return Mage::helper( 'turpentine/varnish' )->getDefaultTtl(); + return Mage::helper('turpentine/varnish')->getDefaultTtl(); } /** @@ -303,18 +303,18 @@ protected function _getDefaultTtl() { * @return string */ protected function _getDefaultBackend() { - $timeout = Mage::getStoreConfig( 'turpentine_vcl/backend/frontend_timeout' ); + $timeout = Mage::getStoreConfig('turpentine_vcl/backend/frontend_timeout'); $default_options = array( - 'first_byte_timeout' => $timeout . 's', - 'between_bytes_timeout' => $timeout . 's', + 'first_byte_timeout' => $timeout.'s', + 'between_bytes_timeout' => $timeout.'s', ); - if ( Mage::getStoreConfig( 'turpentine_vcl/backend/load_balancing' ) != 'no' ) { - return $this->_vcl_director( 'default', $default_options ); + if (Mage::getStoreConfig('turpentine_vcl/backend/load_balancing') != 'no') { + return $this->_vcl_director('default', $default_options); } else { - return $this->_vcl_backend( 'default', - Mage::getStoreConfig( 'turpentine_vcl/backend/backend_host' ), - Mage::getStoreConfig( 'turpentine_vcl/backend/backend_port' ), - $default_options ); + return $this->_vcl_backend('default', + Mage::getStoreConfig('turpentine_vcl/backend/backend_host'), + Mage::getStoreConfig('turpentine_vcl/backend/backend_port'), + $default_options); } } @@ -324,18 +324,18 @@ protected function _getDefaultBackend() { * @return string */ protected function _getAdminBackend() { - $timeout = Mage::getStoreConfig( 'turpentine_vcl/backend/admin_timeout' ); + $timeout = Mage::getStoreConfig('turpentine_vcl/backend/admin_timeout'); $admin_options = array( - 'first_byte_timeout' => $timeout . 's', - 'between_bytes_timeout' => $timeout . 's', + 'first_byte_timeout' => $timeout.'s', + 'between_bytes_timeout' => $timeout.'s', ); - if ( Mage::getStoreConfig( 'turpentine_vcl/backend/load_balancing' ) != 'no' ) { - return $this->_vcl_director( 'admin', $admin_options ); + if (Mage::getStoreConfig('turpentine_vcl/backend/load_balancing') != 'no') { + return $this->_vcl_director('admin', $admin_options); } else { - return $this->_vcl_backend( 'admin', - Mage::getStoreConfig( 'turpentine_vcl/backend/backend_host' ), - Mage::getStoreConfig( 'turpentine_vcl/backend/backend_port' ), - $admin_options ); + return $this->_vcl_backend('admin', + Mage::getStoreConfig('turpentine_vcl/backend/backend_host'), + Mage::getStoreConfig('turpentine_vcl/backend/backend_port'), + $admin_options); } } @@ -348,7 +348,7 @@ protected function _getAdminBackend() { * @return string */ protected function _getGracePeriod() { - return Mage::getStoreConfig( 'turpentine_vcl/ttls/grace_period' ); + return Mage::getStoreConfig('turpentine_vcl/ttls/grace_period'); } /** @@ -357,7 +357,7 @@ protected function _getGracePeriod() { * @return string */ protected function _getEnableDebugHeaders() { - return Mage::getStoreConfig( 'turpentine_varnish/general/varnish_debug' ) + return Mage::getStoreConfig('turpentine_varnish/general/varnish_debug') ? 'true' : 'false'; } @@ -367,16 +367,16 @@ protected function _getEnableDebugHeaders() { * @return string */ protected function _getGetParamExcludes() { - return implode( '|', Mage::helper( 'turpentine/data' )->cleanExplode( ',', - Mage::getStoreConfig( 'turpentine_vcl/params/get_params' ) ) ); + return implode('|', Mage::helper('turpentine/data')->cleanExplode(',', + Mage::getStoreConfig('turpentine_vcl/params/get_params'))); } protected function _getIgnoreGetParameters() { /** @var Nexcessnet_Turpentine_Helper_Data $helper */ $helper = Mage::helper('turpentine'); - $ignoredParameters = $helper->cleanExplode(',', Mage::getStoreConfig( 'turpentine_vcl/params/ignore_get_params')); - return implode( '|', $ignoredParameters); + $ignoredParameters = $helper->cleanExplode(',', Mage::getStoreConfig('turpentine_vcl/params/ignore_get_params')); + return implode('|', $ignoredParameters); } /** @@ -393,7 +393,7 @@ protected function _sendUnModifiedUrlToBackend() * @return string */ protected function _getGenerateSessionStart() { - return Mage::getStoreConfig( 'turpentine_varnish/general/vcl_fix' ) + return Mage::getStoreConfig('turpentine_varnish/general/vcl_fix') ? '/* -- REMOVED' : ''; } @@ -403,7 +403,7 @@ protected function _getGenerateSessionStart() { * @return string */ protected function _getGenerateSessionEnd() { - return Mage::getStoreConfig( 'turpentine_varnish/general/vcl_fix' ) + return Mage::getStoreConfig('turpentine_varnish/general/vcl_fix') ? '-- */' : ''; } @@ -414,7 +414,7 @@ protected function _getGenerateSessionEnd() { * @return string */ protected function _getGenerateSession() { - return Mage::getStoreConfigFlag( 'turpentine_varnish/general/vcl_fix' ) + return Mage::getStoreConfigFlag('turpentine_varnish/general/vcl_fix') ? 'return (pipe);' : 'call generate_session;'; } @@ -425,7 +425,7 @@ protected function _getGenerateSession() { * @return string */ protected function _getGenerateSessionExpires() { - return Mage::getStoreConfig( 'turpentine_varnish/general/vcl_fix' ) + return Mage::getStoreConfig('turpentine_varnish/general/vcl_fix') ? '# call generate_session_expires' : 'call generate_session_expires;'; } @@ -435,7 +435,7 @@ protected function _getGenerateSessionExpires() { * @return string */ protected function _getForceCacheStatic() { - return Mage::getStoreConfig( 'turpentine_vcl/static/force_static' ) + return Mage::getStoreConfig('turpentine_vcl/static/force_static') ? 'true' : 'false'; } @@ -445,8 +445,8 @@ protected function _getForceCacheStatic() { * @return string */ protected function _getStaticExtensions() { - return implode( '|', Mage::helper( 'turpentine/data' )->cleanExplode( ',', - Mage::getStoreConfig( 'turpentine_vcl/static/exts' ) ) ); + return implode('|', Mage::helper('turpentine/data')->cleanExplode(',', + Mage::getStoreConfig('turpentine_vcl/static/exts'))); } /** @@ -455,7 +455,7 @@ protected function _getStaticExtensions() { * @return string */ protected function _getStaticTtl() { - return Mage::getStoreConfig( 'turpentine_vcl/ttls/static_ttl' ); + return Mage::getStoreConfig('turpentine_vcl/ttls/static_ttl'); } /** @@ -465,22 +465,22 @@ protected function _getStaticTtl() { */ protected function _getUrlTtls() { $str = array(); - $configTtls = Mage::helper( 'turpentine/data' )->cleanExplode( PHP_EOL, - Mage::getStoreConfig( 'turpentine_vcl/ttls/url_ttls' ) ); + $configTtls = Mage::helper('turpentine/data')->cleanExplode(PHP_EOL, + Mage::getStoreConfig('turpentine_vcl/ttls/url_ttls')); $ttls = array(); - foreach( $configTtls as $line ) { - $ttls[] = explode( ',', trim( $line ) ); + foreach ($configTtls as $line) { + $ttls[] = explode(',', trim($line)); } - foreach( $ttls as $ttl ) { - $str[] = sprintf( 'if (bereq.url ~ "%s%s") { set beresp.ttl = %ds; }', - $this->getBaseUrlPathRegex(), $ttl[0], $ttl[1] ); + foreach ($ttls as $ttl) { + $str[] = sprintf('if (bereq.url ~ "%s%s") { set beresp.ttl = %ds; }', + $this->getBaseUrlPathRegex(), $ttl[0], $ttl[1]); } - $str = implode( ' else ', $str ); - if( $str ) { - $str .= sprintf( ' else { set beresp.ttl = %ds; }', - $this->_getDefaultTtl() ); + $str = implode(' else ', $str); + if ($str) { + $str .= sprintf(' else { set beresp.ttl = %ds; }', + $this->_getDefaultTtl()); } else { - $str = sprintf( 'set beresp.ttl = %ds;', $this->_getDefaultTtl() ); + $str = sprintf('set beresp.ttl = %ds;', $this->_getDefaultTtl()); } return $str; } @@ -491,7 +491,7 @@ protected function _getUrlTtls() { * @return string */ protected function _getEnableCaching() { - return Mage::helper( 'turpentine/varnish' )->getVarnishEnabled() ? + return Mage::helper('turpentine/varnish')->getVarnishEnabled() ? 'true' : 'false'; } @@ -501,8 +501,8 @@ protected function _getEnableCaching() { * @return array */ protected function _getDebugIps() { - return Mage::helper( 'turpentine/data' )->cleanExplode( ',', - Mage::getStoreConfig( 'dev/restrict/allow_ips' ) ); + return Mage::helper('turpentine/data')->cleanExplode(',', + Mage::getStoreConfig('dev/restrict/allow_ips')); } /** @@ -511,8 +511,8 @@ protected function _getDebugIps() { * @return array */ protected function _getCrawlerIps() { - return Mage::helper( 'turpentine/data' )->cleanExplode( ',', - Mage::getStoreConfig( 'turpentine_vcl/backend/crawlers' ) ); + return Mage::helper('turpentine/data')->cleanExplode(',', + Mage::getStoreConfig('turpentine_vcl/backend/crawlers')); } /** @@ -521,10 +521,10 @@ protected function _getCrawlerIps() { * @return string */ protected function _getCrawlerUserAgents() { - return implode( '|', Mage::helper( 'turpentine/data' ) - ->cleanExplode( ',', + return implode('|', Mage::helper('turpentine/data') + ->cleanExplode(',', Mage::getStoreConfig( - 'turpentine_vcl/backend/crawler_user_agents' ) ) ); + 'turpentine_vcl/backend/crawler_user_agents' ))); } /** @@ -535,7 +535,7 @@ protected function _getCrawlerUserAgents() { * @return string */ protected function _getLruFactor() { - return Mage::getStoreConfig( 'turpentine_vcl/ttls/lru_factor' ); + return Mage::getStoreConfig('turpentine_vcl/ttls/lru_factor'); } /** @@ -548,19 +548,19 @@ protected function _getLruFactor() { */ protected function _getAdvancedSessionValidationTargets() { $validation = array(); - if( Mage::getStoreConfig( 'web/session/use_remote_addr' ) ) { + if (Mage::getStoreConfig('web/session/use_remote_addr')) { $validation[] = 'client.ip'; } - if( Mage::getStoreConfig( 'web/session/use_http_via' ) ) { + if (Mage::getStoreConfig('web/session/use_http_via')) { $validation[] = 'req.http.Via'; } - if( Mage::getStoreConfig( 'web/session/use_http_x_forwarded_for' ) ) { + if (Mage::getStoreConfig('web/session/use_http_x_forwarded_for')) { $validation[] = 'req.http.X-Forwarded-For'; } - if( Mage::getStoreConfig( + if (Mage::getStoreConfig( 'web/session/use_http_user_agent' ) && - !Mage::getStoreConfig( - 'turpentine_vcl/normalization/user_agent' ) ) { + ! Mage::getStoreConfig( + 'turpentine_vcl/normalization/user_agent' )) { $validation[] = 'req.http.User-Agent'; } return $validation; @@ -572,12 +572,12 @@ protected function _getAdvancedSessionValidationTargets() { * @param string $dirtyVcl generated vcl * @return string */ - protected function _cleanVcl( $dirtyVcl ) { - return implode( PHP_EOL, + protected function _cleanVcl($dirtyVcl) { + return implode(PHP_EOL, array_filter( - Mage::helper( 'turpentine/data' ) - ->cleanExplode( PHP_EOL, $dirtyVcl ), - array( $this, '_cleanVclHelper' ) + Mage::helper('turpentine/data') + ->cleanExplode(PHP_EOL, $dirtyVcl), + array($this, '_cleanVclHelper') ) ); } @@ -588,11 +588,11 @@ protected function _cleanVcl( $dirtyVcl ) { * @param string $line * @return bool */ - protected function _cleanVclHelper( $line ) { + protected function _cleanVclHelper($line) { return $line && - ( ( substr( $line, 0, 1 ) != '#' && - substr( $line, 0, 2 ) != '//' ) || - substr( $line, 0, 8 ) == '#include' ); + ((substr($line, 0, 1) != '#' && + substr($line, 0, 2) != '//') || + substr($line, 0, 8) == '#include'); } /** @@ -604,7 +604,7 @@ protected function _cleanVclHelper( $line ) { * @param array $options options * @return string */ - protected function _vcl_backend( $name, $host, $port, $options=array() ) { + protected function _vcl_backend($name, $host, $port, $options = array()) { $tpl = << $port, 'name' => $name, ); - $str = $this->_formatTemplate( $tpl, $vars ); - foreach( $options as $key => $value ) { - $str .= sprintf( ' .%s = %s;', $key, $value ) . PHP_EOL; + $str = $this->_formatTemplate($tpl, $vars); + foreach ($options as $key => $value) { + $str .= sprintf(' .%s = %s;', $key, $value).PHP_EOL; } - $str .= '}' . PHP_EOL; + $str .= '}'.PHP_EOL; return $str; } @@ -631,33 +631,33 @@ protected function _vcl_backend( $name, $host, $port, $options=array() ) { * @param array $backendOptions options for each backend * @return string */ - protected function _vcl_director( $name, $backendOptions ) { + protected function _vcl_director($name, $backendOptions) { $tpl = <<cleanExplode( PHP_EOL, - Mage::getStoreConfig( 'turpentine_vcl/backend/backend_nodes_admin' ) ); - $probeUrl = Mage::getStoreConfig( 'turpentine_vcl/backend/backend_probe_url_admin' ); + if ('admin' == $name && 'yes_admin' == Mage::getStoreConfig('turpentine_vcl/backend/load_balancing')) { + $backendNodes = Mage::helper('turpentine/data')->cleanExplode(PHP_EOL, + Mage::getStoreConfig('turpentine_vcl/backend/backend_nodes_admin')); + $probeUrl = Mage::getStoreConfig('turpentine_vcl/backend/backend_probe_url_admin'); } else { - $backendNodes = Mage::helper( 'turpentine/data' )->cleanExplode( PHP_EOL, - Mage::getStoreConfig( 'turpentine_vcl/backend/backend_nodes' ) ); - $probeUrl = Mage::getStoreConfig( 'turpentine_vcl/backend/backend_probe_url' ); + $backendNodes = Mage::helper('turpentine/data')->cleanExplode(PHP_EOL, + Mage::getStoreConfig('turpentine_vcl/backend/backend_nodes')); + $probeUrl = Mage::getStoreConfig('turpentine_vcl/backend/backend_probe_url'); } $backends = ''; - foreach ( $backendNodes as $backendNode ) { - $parts = explode( ':', $backendNode, 2 ); - $host = ( empty($parts[0]) ) ? '127.0.0.1' : $parts[0]; - $port = ( empty($parts[1]) ) ? '80' : $parts[1]; - $backends .= $this->_vcl_director_backend( $host, $port, $probeUrl, $backendOptions ); + foreach ($backendNodes as $backendNode) { + $parts = explode(':', $backendNode, 2); + $host = (empty($parts[0])) ? '127.0.0.1' : $parts[0]; + $port = (empty($parts[1])) ? '80' : $parts[1]; + $backends .= $this->_vcl_director_backend($host, $port, $probeUrl, $backendOptions); } $vars = array( 'name' => $name, 'backends' => $backends ); - return $this->_formatTemplate( $tpl, $vars ); + return $this->_formatTemplate($tpl, $vars); } /** @@ -669,7 +669,7 @@ protected function _vcl_director( $name, $backendOptions ) { * @param array $options extra options for backend * @return string */ - protected function _vcl_director_backend( $host, $port, $probeUrl='', $options=array() ) { + protected function _vcl_director_backend($host, $port, $probeUrl = '', $options = array()) { $tpl = << $port, 'probe' => '' ); - if ( !empty( $probeUrl ) ) { - $vars['probe'] = $this->_vcl_get_probe( $probeUrl ); + if ( ! empty($probeUrl)) { + $vars['probe'] = $this->_vcl_get_probe($probeUrl); } - $str = $this->_formatTemplate( $tpl, $vars ); - foreach( $options as $key => $value ) { - $str .= sprintf( ' .%s = %s;', $key, $value ) . PHP_EOL; + $str = $this->_formatTemplate($tpl, $vars); + foreach ($options as $key => $value) { + $str .= sprintf(' .%s = %s;', $key, $value).PHP_EOL; } $str .= << $urlParts['host'], 'probe_path' => $urlParts['path'] ); - return $this->_formatTemplate( $tpl, $vars ); + return $this->_formatTemplate($tpl, $vars); } } @@ -732,18 +732,18 @@ protected function _vcl_get_probe( $probeUrl ) { * @param array $hosts list of hosts to add to the ACL * @return string */ - protected function _vcl_acl( $name, array $hosts ) { + protected function _vcl_acl($name, array $hosts) { $tpl = << $name, - 'hosts' => implode( "\n ", array_map( $fmtHost, $hosts ) ), + 'hosts' => implode("\n ", array_map($fmtHost, $hosts)), ); - return $this->_formatTemplate( $tpl, $vars ); + return $this->_formatTemplate($tpl, $vars); } /** @@ -809,8 +809,8 @@ protected function _vcl_sub_normalize_host() { set req.http.Host = "{{normalize_host_target}}"; EOS; - return $this->_formatTemplate( $tpl, array( - 'normalize_host_target' => $this->_getNormalizeHostTarget() ) ); + return $this->_formatTemplate($tpl, array( + 'normalize_host_target' => $this->_getNormalizeHostTarget() )); } /** @@ -819,8 +819,8 @@ protected function _vcl_sub_normalize_host() { * @return string */ protected function _getNormalizeCookieTarget() { - return trim( Mage::getStoreConfig( - 'turpentine_vcl/normalization/cookie_target' ) ); + return trim(Mage::getStoreConfig( + 'turpentine_vcl/normalization/cookie_target' )); } /** @@ -829,8 +829,8 @@ protected function _getNormalizeCookieTarget() { * @return string */ protected function _getNormalizeCookieRegex() { - return trim( Mage::getStoreConfig( - 'turpentine_vcl/normalization/cookie_regex' ) ); + return trim(Mage::getStoreConfig( + 'turpentine_vcl/normalization/cookie_regex' )); } /** @@ -839,11 +839,11 @@ protected function _getNormalizeCookieRegex() { * @return string */ protected function _vcl_sub_maintenance_allowed_ips() { - if((! $this->_getDebugIps()) || ! Mage::getStoreConfig( 'turpentine_vcl/maintenance/custom_vcl_synth' ) ) { + if (( ! $this->_getDebugIps()) || ! Mage::getStoreConfig('turpentine_vcl/maintenance/custom_vcl_synth')) { return false; } - switch(Mage::getStoreConfig( 'turpentine_varnish/servers/version' )) { + switch (Mage::getStoreConfig('turpentine_varnish/servers/version')) { case 4.0: $tpl = <<_formatTemplate( $tpl, array( - 'debug_ips' => Mage::getStoreConfig( 'dev/restrict/allow_ips' ) ) ); + return $this->_formatTemplate($tpl, array( + 'debug_ips' => Mage::getStoreConfig('dev/restrict/allow_ips') )); } /** @@ -884,7 +884,7 @@ protected function _vcl_sub_maintenance_allowed_ips() { */ protected function _vcl_sub_synth() { - if ((!$this->_getDebugIps()) || !Mage::getStoreConfig('turpentine_vcl/maintenance/custom_vcl_synth')) { + if (( ! $this->_getDebugIps()) || ! Mage::getStoreConfig('turpentine_vcl/maintenance/custom_vcl_synth')) { return false; } @@ -950,46 +950,46 @@ protected function _getTemplateVars() { 'static_ttl' => $this->_getStaticTtl(), 'url_ttls' => $this->_getUrlTtls(), 'enable_caching' => $this->_getEnableCaching(), - 'crawler_acl' => $this->_vcl_acl( 'crawler_acl', - $this->_getCrawlerIps() ), + 'crawler_acl' => $this->_vcl_acl('crawler_acl', + $this->_getCrawlerIps()), 'esi_cache_type_param' => - Mage::helper( 'turpentine/esi' )->getEsiCacheTypeParam(), + Mage::helper('turpentine/esi')->getEsiCacheTypeParam(), 'esi_method_param' => - Mage::helper( 'turpentine/esi' )->getEsiMethodParam(), - 'esi_ttl_param' => Mage::helper( 'turpentine/esi' )->getEsiTtlParam(), - 'secret_handshake' => Mage::helper( 'turpentine/varnish' ) + Mage::helper('turpentine/esi')->getEsiMethodParam(), + 'esi_ttl_param' => Mage::helper('turpentine/esi')->getEsiTtlParam(), + 'secret_handshake' => Mage::helper('turpentine/varnish') ->getSecretHandshake(), 'crawler_user_agent_regex' => $this->_getCrawlerUserAgents(), // 'lru_factor' => $this->_getLruFactor(), - 'debug_acl' => $this->_vcl_acl( 'debug_acl', - $this->_getDebugIps() ), + 'debug_acl' => $this->_vcl_acl('debug_acl', + $this->_getDebugIps()), 'custom_c_code' => file_get_contents( - $this->_getVclTemplateFilename( self::VCL_CUSTOM_C_CODE_FILE ) ), - 'esi_private_ttl' => Mage::helper( 'turpentine/esi' ) + $this->_getVclTemplateFilename(self::VCL_CUSTOM_C_CODE_FILE) ), + 'esi_private_ttl' => Mage::helper('turpentine/esi') ->getDefaultEsiTtl(), ); - if( (bool)Mage::getStoreConfig( 'turpentine_vcl/urls/bypass_cache_store_url') ) { + if ((bool) Mage::getStoreConfig('turpentine_vcl/urls/bypass_cache_store_url')) { $vars['allowed_hosts'] = $this->_vcl_sub_allowed_hosts_regex(); } - if( Mage::getStoreConfig( 'turpentine_vcl/normalization/encoding' ) ) { + if (Mage::getStoreConfig('turpentine_vcl/normalization/encoding')) { $vars['normalize_encoding'] = $this->_vcl_sub_normalize_encoding(); } - if( Mage::getStoreConfig( 'turpentine_vcl/normalization/user_agent' ) ) { + if (Mage::getStoreConfig('turpentine_vcl/normalization/user_agent')) { $vars['normalize_user_agent'] = $this->_vcl_sub_normalize_user_agent(); } - if( Mage::getStoreConfig( 'turpentine_vcl/normalization/host' ) ) { + if (Mage::getStoreConfig('turpentine_vcl/normalization/host')) { $vars['normalize_host'] = $this->_vcl_sub_normalize_host(); } - if( Mage::getStoreConfig( 'turpentine_vcl/normalization/cookie_regex' ) ) { + if (Mage::getStoreConfig('turpentine_vcl/normalization/cookie_regex')) { $vars['normalize_cookie_regex'] = $this->_getNormalizeCookieRegex(); } - if( Mage::getStoreConfig( 'turpentine_vcl/normalization/cookie_target' ) ) { + if (Mage::getStoreConfig('turpentine_vcl/normalization/cookie_target')) { $vars['normalize_cookie_target'] = $this->_getNormalizeCookieTarget(); } - if( Mage::getStoreConfig( 'turpentine_vcl/maintenance/enable' ) ) { + if (Mage::getStoreConfig('turpentine_vcl/maintenance/enable')) { // in vcl_recv set the allowed IPs otherwise load the vcl_error (v3)/vcl_synth (v4) $vars['maintenance_allowed_ips'] = $this->_vcl_sub_maintenance_allowed_ips(); // set the vcl_error from Magento database @@ -997,8 +997,8 @@ protected function _getTemplateVars() { } $customIncludeFile = $this->_getCustomIncludeFilename(); - if( is_readable( $customIncludeFile ) ) { - $vars['custom_vcl_include'] = file_get_contents( $customIncludeFile ); + if (is_readable($customIncludeFile)) { + $vars['custom_vcl_include'] = file_get_contents($customIncludeFile); } return $vars; diff --git a/app/code/community/Nexcessnet/Turpentine/Model/Varnish/Configurator/Version2.php b/app/code/community/Nexcessnet/Turpentine/Model/Varnish/Configurator/Version2.php index 2ac5e2e62..4b9136473 100644 --- a/app/code/community/Nexcessnet/Turpentine/Model/Varnish/Configurator/Version2.php +++ b/app/code/community/Nexcessnet/Turpentine/Model/Varnish/Configurator/Version2.php @@ -34,7 +34,7 @@ public function generate($doClean=true) { $tplFile = $this->_getVclTemplateFilename( self::VCL_TEMPLATE_FILE ); $vcl = $this->_formatTemplate( file_get_contents( $tplFile ), $this->_getTemplateVars() ); - return $doClean ? $this->_cleanVcl( $vcl ) : $vcl; + return $doClean ? $this->_cleanVcl( $vcl ) : $vcl; } protected function _getAdvancedSessionValidation() { diff --git a/app/code/community/Nexcessnet/Turpentine/Model/Varnish/Configurator/Version3.php b/app/code/community/Nexcessnet/Turpentine/Model/Varnish/Configurator/Version3.php index be6c7a382..745ec6076 100644 --- a/app/code/community/Nexcessnet/Turpentine/Model/Varnish/Configurator/Version3.php +++ b/app/code/community/Nexcessnet/Turpentine/Model/Varnish/Configurator/Version3.php @@ -30,17 +30,17 @@ class Nexcessnet_Turpentine_Model_Varnish_Configurator_Version3 * @param bool $doClean if true, VCL will be cleaned (whitespaces stripped, etc.) * @return string */ - public function generate($doClean=true) { - $tplFile = $this->_getVclTemplateFilename( self::VCL_TEMPLATE_FILE ); - $vcl = $this->_formatTemplate( file_get_contents( $tplFile ), - $this->_getTemplateVars() ); - return $doClean ? $this->_cleanVcl( $vcl ) : $vcl; + public function generate($doClean = true) { + $tplFile = $this->_getVclTemplateFilename(self::VCL_TEMPLATE_FILE); + $vcl = $this->_formatTemplate(file_get_contents($tplFile), + $this->_getTemplateVars()); + return $doClean ? $this->_cleanVcl($vcl) : $vcl; } protected function _getAdvancedSessionValidation() { $validation = ''; - foreach( $this->_getAdvancedSessionValidationTargets() as $target ) { - $validation .= sprintf( 'hash_data(%s);' . PHP_EOL, $target ); + foreach ($this->_getAdvancedSessionValidationTargets() as $target) { + $validation .= sprintf('hash_data(%s);'.PHP_EOL, $target); } return $validation; } diff --git a/app/code/community/Nexcessnet/Turpentine/Model/Varnish/Configurator/Version4.php b/app/code/community/Nexcessnet/Turpentine/Model/Varnish/Configurator/Version4.php index 6b5fe55d1..08641fa24 100644 --- a/app/code/community/Nexcessnet/Turpentine/Model/Varnish/Configurator/Version4.php +++ b/app/code/community/Nexcessnet/Turpentine/Model/Varnish/Configurator/Version4.php @@ -37,7 +37,7 @@ public function generate($doClean=true) { return $doClean ? $this->_cleanVcl( $vcl ) : $vcl; } - // TODO: Check this + // TODO: Check this protected function _getAdvancedSessionValidation() { $validation = ''; foreach( $this->_getAdvancedSessionValidationTargets() as $target ) { diff --git a/app/code/community/Nexcessnet/Turpentine/controllers/Adminhtml/CacheController.php b/app/code/community/Nexcessnet/Turpentine/controllers/Adminhtml/CacheController.php index 74ca7cfce..5161fb5b3 100644 --- a/app/code/community/Nexcessnet/Turpentine/controllers/Adminhtml/CacheController.php +++ b/app/code/community/Nexcessnet/Turpentine/controllers/Adminhtml/CacheController.php @@ -1,8 +1,8 @@ addSuccess(Mage::helper('adminhtml')->__("Full page cache has been disabled since Varnish cache is enabled.")); + Mage::getSingleton('core/session')->addSuccess(Mage::helper('adminhtml')->__("Full page cache has been disabled since Varnish cache is enabled.")); } else if ($allTypes['full_page']==1) { - Mage::getSingleton('core/session')->addSuccess(Mage::helper('adminhtml')->__("Turpentine cache has been disabled since Full Page cache is enabled.")); - } + Mage::getSingleton('core/session')->addSuccess(Mage::helper('adminhtml')->__("Turpentine cache has been disabled since Full Page cache is enabled.")); + } // disable FPC when Varnish cache is enabled. Mage::app()->saveUseCache($allTypes); $this->_getSession()->addSuccess(Mage::helper('adminhtml')->__("%s cache type(s) enabled.", $updatedTypes)); diff --git a/app/code/community/Nexcessnet/Turpentine/controllers/EsiController.php b/app/code/community/Nexcessnet/Turpentine/controllers/EsiController.php index 8d2521bba..fb66776ab 100644 --- a/app/code/community/Nexcessnet/Turpentine/controllers/EsiController.php +++ b/app/code/community/Nexcessnet/Turpentine/controllers/EsiController.php @@ -27,7 +27,7 @@ class Nexcessnet_Turpentine_EsiController extends Mage_Core_Controller_Front_Act * @return null */ public function indexAction() { - $this->getResponse()->setRedirect( Mage::getBaseUrl() ); + $this->getResponse()->setRedirect(Mage::getBaseUrl()); } /** @@ -38,16 +38,16 @@ public function indexAction() { public function getFormKeyAction() { $resp = $this->getResponse(); $resp->setBody( - Mage::getSingleton( 'core/session' )->real_getFormKey() ); - $resp->setHeader( 'X-Turpentine-Cache', '1' ); - $resp->setHeader( 'X-Turpentine-Flush-Events', - implode( ',', Mage::helper( 'turpentine/esi' ) - ->getDefaultCacheClearEvents() ) ); - $resp->setHeader( 'X-Turpentine-Block', 'form_key' ); - Mage::register( 'turpentine_nocache_flag', false, true ); + Mage::getSingleton('core/session')->real_getFormKey() ); + $resp->setHeader('X-Turpentine-Cache', '1'); + $resp->setHeader('X-Turpentine-Flush-Events', + implode(',', Mage::helper('turpentine/esi') + ->getDefaultCacheClearEvents())); + $resp->setHeader('X-Turpentine-Block', 'form_key'); + Mage::register('turpentine_nocache_flag', false, true); - Mage::helper( 'turpentine/debug' )->logDebug( 'Generated form_key: %s', - $resp->getBody() ); + Mage::helper('turpentine/debug')->logDebug('Generated form_key: %s', + $resp->getBody()); } /** @@ -58,89 +58,89 @@ public function getFormKeyAction() { public function getBlockAction() { $resp = $this->getResponse(); $cacheFlag = false; - if( Mage::helper( 'turpentine/esi' )->shouldResponseUseEsi() ) { + if (Mage::helper('turpentine/esi')->shouldResponseUseEsi()) { $req = $this->getRequest(); - $esiHelper = Mage::helper( 'turpentine/esi' ); - $dataHelper = Mage::helper( 'turpentine/data' ); - $debugHelper = Mage::helper( 'turpentine/debug' ); - $esiDataHmac = $req->getParam( $esiHelper->getEsiHmacParam() ); - $esiDataParamValue = $req->getParam( $esiHelper->getEsiDataParam() ); - if( $esiDataHmac !== ( $hmac = $dataHelper->getHmac( $esiDataParamValue ) ) ) { - $debugHelper->logWarn( 'ESI data HMAC mismatch, expected (%s) but received (%s)', - $hmac, $esiDataHmac ); - $resp->setHttpResponseCode( 500 ); - $resp->setBody( 'ESI data is not valid' ); - } elseif( !( $esiDataArray = $dataHelper->thaw( $esiDataParamValue ) ) ) { - $debugHelper->logWarn( 'Invalid ESI data in URL: %s', - $esiDataParamValue ); - $resp->setHttpResponseCode( 500 ); - $resp->setBody( 'ESI data is not valid' ); - } elseif( !$esiHelper->getEsiDebugEnabled() && + $esiHelper = Mage::helper('turpentine/esi'); + $dataHelper = Mage::helper('turpentine/data'); + $debugHelper = Mage::helper('turpentine/debug'); + $esiDataHmac = $req->getParam($esiHelper->getEsiHmacParam()); + $esiDataParamValue = $req->getParam($esiHelper->getEsiDataParam()); + if ($esiDataHmac !== ($hmac = $dataHelper->getHmac($esiDataParamValue))) { + $debugHelper->logWarn('ESI data HMAC mismatch, expected (%s) but received (%s)', + $hmac, $esiDataHmac); + $resp->setHttpResponseCode(500); + $resp->setBody('ESI data is not valid'); + } elseif ( ! ($esiDataArray = $dataHelper->thaw($esiDataParamValue))) { + $debugHelper->logWarn('Invalid ESI data in URL: %s', + $esiDataParamValue); + $resp->setHttpResponseCode(500); + $resp->setBody('ESI data is not valid'); + } elseif ( ! $esiHelper->getEsiDebugEnabled() && $esiDataArray['esi_method'] !== - $req->getParam( $esiHelper->getEsiMethodParam() ) ) { - $resp->setHttpResponseCode( 403 ); - $resp->setBody( 'ESI method mismatch' ); - $debugHelper->logWarn( 'Blocking change of ESI method: %s -> %s', + $req->getParam($esiHelper->getEsiMethodParam())) { + $resp->setHttpResponseCode(403); + $resp->setBody('ESI method mismatch'); + $debugHelper->logWarn('Blocking change of ESI method: %s -> %s', $esiDataArray['esi_method'], - $req->getParam( $esiHelper->getEsiMethodParam() ) ); + $req->getParam($esiHelper->getEsiMethodParam())); } else { - $esiData = new Varien_Object( $esiDataArray ); + $esiData = new Varien_Object($esiDataArray); $origRequest = Mage::app()->getRequest(); Mage::app()->setCurrentStore( - Mage::app()->getStore( $esiData->getStoreId() ) ); - $appShim = Mage::getModel( 'turpentine/shim_mage_core_app' ); - if( $referer = $this->_getRefererUrl() ) { - $referer = htmlspecialchars_decode( $referer ); - $dummyRequest = Mage::helper( 'turpentine/esi' ) - ->getDummyRequest( $referer ); + Mage::app()->getStore($esiData->getStoreId()) ); + $appShim = Mage::getModel('turpentine/shim_mage_core_app'); + if ($referer = $this->_getRefererUrl()) { + $referer = htmlspecialchars_decode($referer); + $dummyRequest = Mage::helper('turpentine/esi') + ->getDummyRequest($referer); } else { - $dummyRequest = Mage::helper( 'turpentine/esi' ) + $dummyRequest = Mage::helper('turpentine/esi') ->getDummyRequest(); } - $appShim->shim_setRequest( $dummyRequest ); - $block = $this->_getEsiBlock( $esiData ); - if( $block ) { + $appShim->shim_setRequest($dummyRequest); + $block = $this->_getEsiBlock($esiData); + if ($block) { $blockEsiOptions = $block->getEsiOptions(); - $block->setEsiOptions( false ); - $resp->setBody( $block->toHtml() ); - if( (int)$req->getParam( $esiHelper->getEsiTtlParam() ) > 0 ) { + $block->setEsiOptions(false); + $resp->setBody($block->toHtml()); + if ((int) $req->getParam($esiHelper->getEsiTtlParam()) > 0) { $cacheFlag = true; - if ( isset( $blockEsiOptions['only_cache_if'] ) ) { - switch ( $blockEsiOptions['only_cache_if'] ) { + if (isset($blockEsiOptions['only_cache_if'])) { + switch ($blockEsiOptions['only_cache_if']) { case 'empty': - $cacheFlag = ( '' === $resp->getBody() ); + $cacheFlag = ('' === $resp->getBody()); break; case 'no_text': - $cacheFlag = ( '' === trim( strip_tags( $resp->getBody() ) ) ); + $cacheFlag = ('' === trim(strip_tags($resp->getBody()))); break; default: $cacheFlag = false; } } } - if( $esiData->getEsiMethod() == 'ajax' ) { - $resp->setHeader( 'Access-Control-Allow-Origin', - $esiHelper->getCorsOrigin() ); + if ($esiData->getEsiMethod() == 'ajax') { + $resp->setHeader('Access-Control-Allow-Origin', + $esiHelper->getCorsOrigin()); } - if( !is_null( $flushEvents = $esiData->getFlushEvents() ) ) { - $resp->setHeader( 'X-Turpentine-Flush-Events', - implode( ',', $flushEvents ) ); + if ( ! is_null($flushEvents = $esiData->getFlushEvents())) { + $resp->setHeader('X-Turpentine-Flush-Events', + implode(',', $flushEvents)); } - if( $esiHelper->getEsiDebugEnabled() ) { - $resp->setHeader( 'X-Turpentine-Block', - $block->getNameInLayout() ); + if ($esiHelper->getEsiDebugEnabled()) { + $resp->setHeader('X-Turpentine-Block', + $block->getNameInLayout()); } } else { - $resp->setHttpResponseCode( 404 ); - $resp->setBody( 'ESI block not found' ); + $resp->setHttpResponseCode(404); + $resp->setBody('ESI block not found'); } - $appShim->shim_setRequest( $origRequest ); + $appShim->shim_setRequest($origRequest); } } else { - $resp->setHttpResponseCode( 403 ); - $resp->setBody( 'ESI includes are not enabled' ); + $resp->setHttpResponseCode(403); + $resp->setBody('ESI includes are not enabled'); } - Mage::register( 'turpentine_nocache_flag', !$cacheFlag, true ); + Mage::register('turpentine_nocache_flag', ! $cacheFlag, true); } /** @@ -152,10 +152,10 @@ public function getBlockAction() { * @return null */ public function postDispatch() { - $flag = $this->getFlag( '', self::FLAG_NO_START_SESSION ); - $this->setFlag( '', self::FLAG_NO_START_SESSION, true ); + $flag = $this->getFlag('', self::FLAG_NO_START_SESSION); + $this->setFlag('', self::FLAG_NO_START_SESSION, true); parent::postDispatch(); - $this->setFlag( '', self::FLAG_NO_START_SESSION, $flag ); + $this->setFlag('', self::FLAG_NO_START_SESSION, $flag); } /** @@ -164,25 +164,25 @@ public function postDispatch() { * @param Varien_Object $esiData * @return Mage_Core_Block_Template|null */ - protected function _getEsiBlock( $esiData ) { + protected function _getEsiBlock($esiData) { $block = null; - Varien_Profiler::start( 'turpentine::controller::esi::_getEsiBlock' ); - foreach( $esiData->getSimpleRegistry() as $key => $value ) { - Mage::register( $key, $value, true ); + Varien_Profiler::start('turpentine::controller::esi::_getEsiBlock'); + foreach ($esiData->getSimpleRegistry() as $key => $value) { + Mage::register($key, $value, true); } - foreach( $esiData->getComplexRegistry() as $key => $data ) { - $value = Mage::getModel( $data['model'] ); - if( !is_object( $value ) ) { - Mage::helper( 'turpentine/debug' )->logWarn( + foreach ($esiData->getComplexRegistry() as $key => $data) { + $value = Mage::getModel($data['model']); + if ( ! is_object($value)) { + Mage::helper('turpentine/debug')->logWarn( 'Failed to register key/model: %s as %s(%s)', $key, $data['model'], $data['id'] ); continue; } else { - $value->load( $data['id'] ); - Mage::register( $key, $value, true ); + $value->load($data['id']); + Mage::register($key, $value, true); } } - $layout = Mage::getSingleton( 'core/layout' ); + $layout = Mage::getSingleton('core/layout'); // dispatch event for adding handles to layout update Mage::dispatchEvent( @@ -191,13 +191,13 @@ protected function _getEsiBlock( $esiData ) { ); $layoutUpdate = $layout->getUpdate(); - $layoutUpdate->load( $this->_swapCustomerHandles( - $esiData->getLayoutHandles() ) ); - foreach( $esiData->getDummyBlocks() as $blockName ) { - $layout->createBlock( 'Mage_Core_Block_Template', $blockName ); + $layoutUpdate->load($this->_swapCustomerHandles( + $esiData->getLayoutHandles() )); + foreach ($esiData->getDummyBlocks() as $blockName) { + $layout->createBlock('Mage_Core_Block_Template', $blockName); } - if(!$this->getFlag('', self::FLAG_NO_DISPATCH_BLOCK_EVENT)) { + if ( ! $this->getFlag('', self::FLAG_NO_DISPATCH_BLOCK_EVENT)) { Mage::dispatchEvent( 'controller_action_layout_generate_xml_before', array('action'=>$this, 'layout'=>$layout) @@ -206,33 +206,33 @@ protected function _getEsiBlock( $esiData ) { $layout->generateXml(); /** @var Nexcessnet_Turpentine_Helper_Data $turpentineHelper */ - $turpentineHelper = Mage::helper( 'turpentine/data' ) - ->setLayout( $layout ); + $turpentineHelper = Mage::helper('turpentine/data') + ->setLayout($layout); - $blockNode = current( $layout->getNode()->xpath( - sprintf('//block[@name=\'%s\']',$esiData->getNameInLayout()) - ) ); + $blockNode = current($layout->getNode()->xpath( + sprintf('//block[@name=\'%s\']', $esiData->getNameInLayout()) + )); - if( ! ($blockNode instanceof Mage_Core_Model_Layout_Element) ) { - Mage::helper( 'turpentine/debug' )->logWarn( + if ( ! ($blockNode instanceof Mage_Core_Model_Layout_Element)) { + Mage::helper('turpentine/debug')->logWarn( 'No block node found with @name="%s"', $esiData->getNameInLayout() ); return null; } - $nodesToGenerate = $turpentineHelper->getChildBlockNames( $blockNode ); - Mage::getModel( 'turpentine/shim_mage_core_layout' ) - ->shim_generateFullBlock( $blockNode ); + $nodesToGenerate = $turpentineHelper->getChildBlockNames($blockNode); + Mage::getModel('turpentine/shim_mage_core_layout') + ->shim_generateFullBlock($blockNode); //find addional blocks that aren't defined in the but via - $referenceNodes = $layout->getNode()->xpath( sprintf( + $referenceNodes = $layout->getNode()->xpath(sprintf( '//reference[@name=\'%s\']', - $esiData->getNameInLayout() ) ); + $esiData->getNameInLayout() )); if ($referenceNodes) { foreach ($referenceNodes as $referenceNode) { if ($referenceNode instanceof Mage_Core_Model_Layout_Element) { $referencesToGenerate = $turpentineHelper - ->getChildBlockNames( $referenceNode ); + ->getChildBlockNames($referenceNode); $nodesToGenerate = array_merge($nodesToGenerate, $referencesToGenerate); } @@ -240,22 +240,22 @@ protected function _getEsiBlock( $esiData ) { } // dispatch event for adding xml layout elements - if(!$this->getFlag('', self::FLAG_NO_DISPATCH_BLOCK_EVENT)) { + if ( ! $this->getFlag('', self::FLAG_NO_DISPATCH_BLOCK_EVENT)) { Mage::dispatchEvent( 'controller_action_layout_generate_blocks_before', array('action'=>$this, 'layout'=>$layout) ); } - foreach( array_unique($nodesToGenerate) as $nodeName ) { - foreach( $layout->getNode()->xpath( sprintf( - '//reference[@name=\'%s\']', $nodeName ) ) as $node ) { - $layout->generateBlocks( $node ); + foreach (array_unique($nodesToGenerate) as $nodeName) { + foreach ($layout->getNode()->xpath(sprintf( + '//reference[@name=\'%s\']', $nodeName )) as $node) { + $layout->generateBlocks($node); } } - $block = $layout->getBlock( $esiData->getNameInLayout() ); + $block = $layout->getBlock($esiData->getNameInLayout()); - if(!$this->getFlag('', self::FLAG_NO_DISPATCH_BLOCK_EVENT)) { + if ( ! $this->getFlag('', self::FLAG_NO_DISPATCH_BLOCK_EVENT)) { Mage::dispatchEvent( 'controller_action_layout_generate_blocks_after', array('action'=>$this, 'layout'=>$layout) @@ -263,7 +263,7 @@ protected function _getEsiBlock( $esiData ) { } $this->_isLayoutLoaded = true; - Varien_Profiler::stop( 'turpentine::controller::esi::_getEsiBlock' ); + Varien_Profiler::stop('turpentine::controller::esi::_getEsiBlock'); return $block; } @@ -277,13 +277,13 @@ protected function _getEsiBlock( $esiData ) { * @param array $handles * @return array */ - protected function _swapCustomerHandles( $handles ) { - if( Mage::helper( 'customer' )->isLoggedIn() ) { - $replacement = array( 'customer_logged_out', 'customer_logged_in' ); + protected function _swapCustomerHandles($handles) { + if (Mage::helper('customer')->isLoggedIn()) { + $replacement = array('customer_logged_out', 'customer_logged_in'); } else { - $replacement = array( 'customer_logged_in', 'customer_logged_out' ); + $replacement = array('customer_logged_in', 'customer_logged_out'); } - if( ( $pos = array_search( $replacement[0], $handles ) ) !== false ) { + if (($pos = array_search($replacement[0], $handles)) !== false) { $handles[$pos] = $replacement[1]; } return $handles; diff --git a/app/code/community/Nexcessnet/Turpentine/controllers/Varnish/ManagementController.php b/app/code/community/Nexcessnet/Turpentine/controllers/Varnish/ManagementController.php index 1db2b4d5a..a5bbd7e65 100644 --- a/app/code/community/Nexcessnet/Turpentine/controllers/Varnish/ManagementController.php +++ b/app/code/community/Nexcessnet/Turpentine/controllers/Varnish/ManagementController.php @@ -44,20 +44,20 @@ public function indexAction() { * @return null */ public function flushAllAction() { - Mage::dispatchEvent( 'turpentine_varnish_flush_all' ); - $result = Mage::getModel( 'turpentine/varnish_admin' )->flushAll(); - foreach( $result as $name => $value ) { - if( $value === true ) { + Mage::dispatchEvent('turpentine_varnish_flush_all'); + $result = Mage::getModel('turpentine/varnish_admin')->flushAll(); + foreach ($result as $name => $value) { + if ($value === true) { $this->_getSession() - ->addSuccess( Mage::helper( 'turpentine/data' ) - ->__( 'Flushed Varnish cache for: ' ) . $name ); + ->addSuccess(Mage::helper('turpentine/data') + ->__('Flushed Varnish cache for: ').$name); } else { $this->_getSession() - ->addError( Mage::helper( 'turpentine/data' ) - ->__( 'Error flushing Varnish cache on: ' ) . $name ); + ->addError(Mage::helper('turpentine/data') + ->__('Error flushing Varnish cache on: ').$name); } } - $this->_redirect( '*/cache' ); + $this->_redirect('*/cache'); } /** @@ -68,27 +68,27 @@ public function flushAllAction() { */ public function flushPartialAction() { $postData = $this->getRequest()->getPost(); - if( !isset( $postData['pattern'] ) ) { - $this->_getSession()->addError( $this->__( 'Missing URL post data' ) ); + if ( ! isset($postData['pattern'])) { + $this->_getSession()->addError($this->__('Missing URL post data')); } else { $pattern = $postData['pattern']; - Mage::dispatchEvent( 'turpentine_varnish_flush_partial', - array( 'pattern' => $pattern ) ); - $result = Mage::getModel( 'turpentine/varnish_admin' ) - ->flushUrl( $pattern ); - foreach( $result as $name => $value ) { - if( $value === true ) { + Mage::dispatchEvent('turpentine_varnish_flush_partial', + array('pattern' => $pattern)); + $result = Mage::getModel('turpentine/varnish_admin') + ->flushUrl($pattern); + foreach ($result as $name => $value) { + if ($value === true) { $this->_getSession() - ->addSuccess( Mage::helper( 'turpentine/data' ) - ->__( 'Flushed matching URLs for: ' ) . $name ); + ->addSuccess(Mage::helper('turpentine/data') + ->__('Flushed matching URLs for: ').$name); } else { $this->_getSession() - ->addError( Mage::helper( 'turpentine/data' ) - ->__( 'Error flushing matching URLs on: ' ) . $name ); + ->addError(Mage::helper('turpentine/data') + ->__('Error flushing matching URLs on: ').$name); } } } - $this->_redirect( '*/cache' ); + $this->_redirect('*/cache'); } /** @@ -98,23 +98,23 @@ public function flushPartialAction() { */ public function flushContentTypeAction() { $postData = $this->getRequest()->getPost(); - if( !isset( $postData['ctype'] ) ) { - $this->_getSession()->addError( $this->__( 'Missing URL post data' ) ); + if ( ! isset($postData['ctype'])) { + $this->_getSession()->addError($this->__('Missing URL post data')); } else { $ctype = $postData['ctype']; - Mage::dispatchEvent( 'turpentine_varnish_flush_content_type', - array( 'ctype' => $ctype ) ); - $result = Mage::getModel( 'turpentine/varnish_admin' ) - ->flushContentType( $ctype ); - foreach( $result as $name => $value ) { - if( $value === true ) { + Mage::dispatchEvent('turpentine_varnish_flush_content_type', + array('ctype' => $ctype)); + $result = Mage::getModel('turpentine/varnish_admin') + ->flushContentType($ctype); + foreach ($result as $name => $value) { + if ($value === true) { $this->_getSession() - ->addSuccess( Mage::helper( 'turpentine/data' ) - ->__( 'Flushed matching content-types for: ' ) . $name ); + ->addSuccess(Mage::helper('turpentine/data') + ->__('Flushed matching content-types for: ').$name); } else { $this->_getSession() - ->addError( Mage::helper( 'turpentine/data' ) - ->__( 'Error flushing matching content-types on: ' ) . $name ); + ->addError(Mage::helper('turpentine/data') + ->__('Error flushing matching content-types on: ').$name); } } } @@ -127,18 +127,18 @@ public function flushContentTypeAction() { * @return null */ public function applyConfigAction() { - Mage::dispatchEvent( 'turpentine_varnish_apply_config' ); - $result = Mage::getModel( 'turpentine/varnish_admin' )->applyConfig(); - foreach( $result as $name => $value ) { - if( $value === true ) { + Mage::dispatchEvent('turpentine_varnish_apply_config'); + $result = Mage::getModel('turpentine/varnish_admin')->applyConfig(); + foreach ($result as $name => $value) { + if ($value === true) { $this->_getSession() - ->addSuccess( Mage::helper( 'turpentine' ) - ->__( 'VCL successfully applied to ' . $name ) ); + ->addSuccess(Mage::helper('turpentine') + ->__('VCL successfully applied to '.$name)); } else { $this->_getSession() - ->addError( Mage::helper( 'turpentine' ) - ->__( sprintf( 'Failed to apply the VCL to %s: %s', - $name, $value ) ) ); + ->addError(Mage::helper('turpentine') + ->__(sprintf('Failed to apply the VCL to %s: %s', + $name, $value))); } } $this->_redirect('*/cache'); @@ -158,7 +158,7 @@ public function saveConfigAction() { Mage::dispatchEvent( 'turpentine_varnish_save_config', array( 'cfgr' => $cfgr ) ); $result = $cfgr->save( $cfgr->generate( - Mage::helper('turpentine')->shouldStripVclWhitespace('save') ) ); + Mage::helper('turpentine')->shouldStripVclWhitespace('save') ) ); if( $result[0] ) { $this->_getSession() ->addSuccess( Mage::helper('turpentine') @@ -185,7 +185,7 @@ public function getConfigAction() { $this->_redirect( '*/cache' ); } else { $vcl = $cfgr->generate( - Mage::helper( 'turpentine' )->shouldStripVclWhitespace('download') ); + Mage::helper( 'turpentine' )->shouldStripVclWhitespace('download') ); $this->getResponse() ->setHttpResponseCode( 200 ) ->setHeader( 'Content-Type', 'text/plain', true ) @@ -203,39 +203,39 @@ public function getConfigAction() { * @return void */ public function switchNavigationAction() { - $type = $this->getRequest()->get( 'type' ); - if( is_null( $type ) ) { - $this->_redirect( 'noRoute' ); + $type = $this->getRequest()->get('type'); + if (is_null($type)) { + $this->_redirect('noRoute'); return; } - $cookieName = Mage::helper( 'turpentine' )->getBypassCookieName(); - $cookieModel = Mage::getModel( 'core/cookie' ); - $adminSession = Mage::getSingleton( 'adminhtml/session' ); + $cookieName = Mage::helper('turpentine')->getBypassCookieName(); + $cookieModel = Mage::getModel('core/cookie'); + $adminSession = Mage::getSingleton('adminhtml/session'); - switch( $type ) { + switch ($type) { case 'default': $cookieModel->set( $cookieName, - Mage::helper( 'turpentine/varnish' )->getSecretHandshake(), + Mage::helper('turpentine/varnish')->getSecretHandshake(), null, // period null, // path null, // domain false, // secure true ); // httponly - $adminSession->addSuccess( Mage::helper( 'turpentine/data' ) - ->__( 'The Varnish bypass cookie has been successfully added.' ) ); + $adminSession->addSuccess(Mage::helper('turpentine/data') + ->__('The Varnish bypass cookie has been successfully added.')); break; case 'varnish': - $cookieModel->delete( $cookieName ); - $adminSession->addSuccess( Mage::helper( 'turpentine/data' ) - ->__( 'The Varnish bypass cookie has been successfully removed.' ) ); + $cookieModel->delete($cookieName); + $adminSession->addSuccess(Mage::helper('turpentine/data') + ->__('The Varnish bypass cookie has been successfully removed.')); break; default: - $adminSession->addError( Mage::helper( 'turpentine/data' ) - ->__( 'The given navigation type is not supported!' ) ); + $adminSession->addError(Mage::helper('turpentine/data') + ->__('The given navigation type is not supported!')); break; } diff --git a/contrib/tools/esi-decoder.php b/contrib/tools/esi-decoder.php index 7e066ac20..20ae29055 100644 --- a/contrib/tools/esi-decoder.php +++ b/contrib/tools/esi-decoder.php @@ -1,31 +1,31 @@ @@ -79,9 +79,9 @@ $esiDataArray = $dataHelper->thaw( $processData ); $showContentUrl = Mage::getUrl( 'turpentine/esi/getBlock', array( 'method' => 'esi', - 'ttl' => 0, - 'hmac' => $dataHelper->getHmac( $processData ), - 'data' => $processData ) ); + 'ttl' => 0, + 'hmac' => $dataHelper->getHmac( $processData ), + 'data' => $processData ) ); ?>
    =  DATA  =
    diff --git a/util/varnishadm.php b/util/varnishadm.php index 535f61cf5..efa39c383 100755 --- a/util/varnishadm.php +++ b/util/varnishadm.php @@ -20,7 +20,7 @@ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ -require_once( dirname( $_SERVER['argv'][0] ) . '/abstract.php' ); +require_once(dirname($_SERVER['argv'][0]).'/abstract.php'); class Turpentine_Shell_Varnishadm extends Mage_Shell_Abstract { /** @@ -30,16 +30,16 @@ class Turpentine_Shell_Varnishadm extends Mage_Shell_Abstract { */ protected function _parseArgs() { $this->_args = array_slice( - array_filter( $_SERVER['argv'], - create_function( '$e', - 'return $e != \'--\';' ) ), + array_filter($_SERVER['argv'], + create_function('$e', + 'return $e != \'--\';')), 1 ); return $this; } protected function _write() { $args = func_get_args(); - return call_user_func_array( 'printf', $args ); + return call_user_func_array('printf', $args); } /** @@ -48,13 +48,13 @@ protected function _write() { * @return null */ public function run() { - $command = str_replace( '.', '_', $this->_args[0] ); - $params = array_slice( $this->_args, 1 ); - foreach( Mage::helper( 'turpentine/varnish' )->getSockets() as $socket ) { - $response = call_user_func_array( array( $socket, $command ), $params ); - $this->_write( "=== Result from server [%s]: %d ===\n%s\n", + $command = str_replace('.', '_', $this->_args[0]); + $params = array_slice($this->_args, 1); + foreach (Mage::helper('turpentine/varnish')->getSockets() as $socket) { + $response = call_user_func_array(array($socket, $command), $params); + $this->_write("=== Result from server [%s]: %d ===\n%s\n", $socket->getConnectionString(), $response['code'], - $response['text'] ); + $response['text']); } } From e419a546dc81982d30142acd6c1283eaf9dbb438 Mon Sep 17 00:00:00 2001 From: Scrutinizer Auto-Fixer Date: Thu, 15 Oct 2015 13:25:05 +0000 Subject: [PATCH 04/18] Scrutinizer Auto-Fixes This commit consists of patches automatically generated for this project on https://scrutinizer-ci.com --- .../Nexcessnet/Turpentine/Helper/Data.php | 4 +- .../Nexcessnet/Turpentine/Helper/Debug.php | 4 +- .../Model/Config/Select/Version.php | 8 ++-- .../Turpentine/Model/Observer/Esi.php | 44 +++++++++--------- .../Model/Shim/Mage/Core/Config.php | 4 +- .../Turpentine/Model/Varnish/Admin.php | 24 +++++----- .../Turpentine/Model/Varnish/Admin/Socket.php | 14 +++--- .../Model/Varnish/Configurator/Version2.php | 14 +++--- .../Model/Varnish/Configurator/Version4.php | 14 +++--- .../controllers/Adminhtml/CacheController.php | 4 +- .../Varnish/ManagementController.php | 46 +++++++++---------- contrib/tools/esi-decoder.php | 28 +++++------ 12 files changed, 105 insertions(+), 103 deletions(-) diff --git a/app/code/community/Nexcessnet/Turpentine/Helper/Data.php b/app/code/community/Nexcessnet/Turpentine/Helper/Data.php index 2f5b1ad63..040252c15 100644 --- a/app/code/community/Nexcessnet/Turpentine/Helper/Data.php +++ b/app/code/community/Nexcessnet/Turpentine/Helper/Data.php @@ -298,9 +298,9 @@ public function getStripVclWhitespace() { */ public function shouldStripVclWhitespace($action) { $configValue = $this->getStripVclWhitespace(); - if ( $configValue==='always' ) { + if ($configValue === 'always') { return true; - } elseif ( $configValue==='apply' && $action==='apply' ) { + } elseif ($configValue === 'apply' && $action === 'apply') { return true; } return false; diff --git a/app/code/community/Nexcessnet/Turpentine/Helper/Debug.php b/app/code/community/Nexcessnet/Turpentine/Helper/Debug.php index 4fbb7ed61..102120dd5 100644 --- a/app/code/community/Nexcessnet/Turpentine/Helper/Debug.php +++ b/app/code/community/Nexcessnet/Turpentine/Helper/Debug.php @@ -218,7 +218,7 @@ protected function _log($level, $message) { * @return string */ protected function _getLogFileName() { - if ( $this->useCustomLogFile() ) { + if ($this->useCustomLogFile()) { return $this->getCustomLogFileName(); } return ''; @@ -238,7 +238,7 @@ public function useCustomLogFile() { * @return string */ public function getCustomLogFileName() { - return (string)Mage::getStoreConfig( + return (string) Mage::getStoreConfig( 'turpentine_varnish/logging/custom_log_file_name' ); } diff --git a/app/code/community/Nexcessnet/Turpentine/Model/Config/Select/Version.php b/app/code/community/Nexcessnet/Turpentine/Model/Config/Select/Version.php index df21d3600..e88251213 100644 --- a/app/code/community/Nexcessnet/Turpentine/Model/Config/Select/Version.php +++ b/app/code/community/Nexcessnet/Turpentine/Model/Config/Select/Version.php @@ -23,10 +23,10 @@ class Nexcessnet_Turpentine_Model_Config_Select_Version { public function toOptionArray() { $helper = Mage::helper('turpentine'); return array( - array( 'value' => '2.1', 'label' => $helper->__( '2.1.x' ) ), - array( 'value' => '3.0', 'label' => $helper->__( '3.0.x' ) ), - array( 'value' => '4.0', 'label' => $helper->__( '4.0.x' ) ), - array( 'value' => 'auto', 'label' => $helper->__( 'Auto' ) ), + array('value' => '2.1', 'label' => $helper->__('2.1.x')), + array('value' => '3.0', 'label' => $helper->__('3.0.x')), + array('value' => '4.0', 'label' => $helper->__('4.0.x')), + array('value' => 'auto', 'label' => $helper->__('Auto')), ); } } \ No newline at end of file diff --git a/app/code/community/Nexcessnet/Turpentine/Model/Observer/Esi.php b/app/code/community/Nexcessnet/Turpentine/Model/Observer/Esi.php index 800cfb486..1e37fc8a9 100644 --- a/app/code/community/Nexcessnet/Turpentine/Model/Observer/Esi.php +++ b/app/code/community/Nexcessnet/Turpentine/Model/Observer/Esi.php @@ -254,59 +254,59 @@ public function injectEsi($eventObject) { $scopeParam = $esiHelper->getEsiScopeParam(); $referrerParam = $esiHelper->getEsiReferrerParam(); - $esiOptions = $this->_getDefaultEsiOptions( $esiOptions ); + $esiOptions = $this->_getDefaultEsiOptions($esiOptions); // change the block's template to the stripped down ESI template - switch( $esiOptions[$methodParam] ) { + switch ($esiOptions[$methodParam]) { case 'ajax': - $blockObject->setTemplate( 'turpentine/ajax.phtml' ); + $blockObject->setTemplate('turpentine/ajax.phtml'); break; case 'esi': default: - $blockObject->setTemplate( 'turpentine/esi.phtml' ); + $blockObject->setTemplate('turpentine/esi.phtml'); // flag request for ESI processing - Mage::register( 'turpentine_esi_flag', true, true ); + 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 ); + $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 ), + $hmacParam => $dataHelper->getHmac($frozenData), $dataParam => $frozenData, ); - if( $esiOptions[$methodParam] == 'ajax' ) { + if ($esiOptions[$methodParam] == 'ajax') { $urlOptions['_secure'] = Mage::app()->getStore() ->isCurrentlySecure(); } - if( $esiOptions[$scopeParam] == 'page' ) { - $urlOptions[$referrerParam] = Mage::helper('core')->urlEncode( + if ($esiOptions[$scopeParam] == 'page') { + $urlOptions[$referrerParam] = Mage::helper('core')->urlEncode( Mage::getUrl('*/*/*', array('_use_rewrite' => true, '_current' => true)) ); } - $esiUrl = Mage::getUrl( 'turpentine/esi/getBlock', $urlOptions ); - if( $esiOptions[$methodParam] == 'esi' ) { + $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 ); + $esiUrl = preg_replace('|^https://|i', 'http://', $esiUrl); } - $blockObject->setEsiUrl( $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 ); + foreach (array('lifetime', 'tags', 'key') as $dataKey) { + $blockObject->unsetData('cache_'.$dataKey); } - if( strlen( $esiUrl ) > 2047 ) { - Mage::helper( 'turpentine/debug' )->logWarn( + if (strlen($esiUrl) > 2047) { + Mage::helper('turpentine/debug')->logWarn( 'ESI url is probably too long (%d > 2047 characters): %s', - strlen( $esiUrl ), $esiUrl ); + strlen($esiUrl), $esiUrl ); } - Varien_Profiler::stop( 'turpentine::observer::esi::injectEsi' ); + Varien_Profiler::stop('turpentine::observer::esi::injectEsi'); } // else handle the block like normal and cache it inline with the page } diff --git a/app/code/community/Nexcessnet/Turpentine/Model/Shim/Mage/Core/Config.php b/app/code/community/Nexcessnet/Turpentine/Model/Shim/Mage/Core/Config.php index d3a25d0c9..eee96bfd9 100644 --- a/app/code/community/Nexcessnet/Turpentine/Model/Shim/Mage/Core/Config.php +++ b/app/code/community/Nexcessnet/Turpentine/Model/Shim/Mage/Core/Config.php @@ -46,8 +46,10 @@ public function shim_setClassNameCache($groupType, $group, $class, $className) { */ public function unsetEventAreaCache($area) { if (version_compare(Mage::getVersion(), '1.11.0', '>=') // enterprise - || version_compare(Mage::getVersion(), '1.6.0', '>=')) // community + || version_compare(Mage::getVersion(), '1.6.0', '>=')) { + // community unset($this->_eventAreas[$area]); + } } } diff --git a/app/code/community/Nexcessnet/Turpentine/Model/Varnish/Admin.php b/app/code/community/Nexcessnet/Turpentine/Model/Varnish/Admin.php index 1543ed66d..6dbb2115d 100644 --- a/app/code/community/Nexcessnet/Turpentine/Model/Varnish/Admin.php +++ b/app/code/community/Nexcessnet/Turpentine/Model/Varnish/Admin.php @@ -96,22 +96,22 @@ public function flushContentType($contentType) { */ public function applyConfig() { $result = array(); - $helper = Mage::helper( 'turpentine' ); - foreach( Mage::helper( 'turpentine/varnish' )->getSockets() as $socket ) { - $cfgr = Nexcessnet_Turpentine_Model_Varnish_Configurator_Abstract::getFromSocket( $socket ); + $helper = Mage::helper('turpentine'); + foreach (Mage::helper('turpentine/varnish')->getSockets() as $socket) { + $cfgr = Nexcessnet_Turpentine_Model_Varnish_Configurator_Abstract::getFromSocket($socket); $socketName = $socket->getConnectionString(); - if( is_null( $cfgr ) ) { + if (is_null($cfgr)) { $result[$socketName] = 'Failed to load configurator'; } else { - $vcl = $cfgr->generate( $helper->shouldStripVclWhitespace('apply') ); - $vclName = Mage::helper( 'turpentine/data' ) - ->secureHash( microtime() ); + $vcl = $cfgr->generate($helper->shouldStripVclWhitespace('apply')); + $vclName = Mage::helper('turpentine/data') + ->secureHash(microtime()); try { - $this->_testEsiSyntaxParam( $socket ); - $socket->vcl_inline( $vclName, $vcl ); - sleep( 1 ); //this is probably not really needed - $socket->vcl_use( $vclName ); - } catch( Mage_Core_Exception $e ) { + $this->_testEsiSyntaxParam($socket); + $socket->vcl_inline($vclName, $vcl); + sleep(1); //this is probably not really needed + $socket->vcl_use($vclName); + } catch (Mage_Core_Exception $e) { $result[$socketName] = $e->getMessage(); continue; } diff --git a/app/code/community/Nexcessnet/Turpentine/Model/Varnish/Admin/Socket.php b/app/code/community/Nexcessnet/Turpentine/Model/Varnish/Admin/Socket.php index acca508dc..4c6e14b48 100644 --- a/app/code/community/Nexcessnet/Turpentine/Model/Varnish/Admin/Socket.php +++ b/app/code/community/Nexcessnet/Turpentine/Model/Varnish/Admin/Socket.php @@ -509,19 +509,19 @@ protected function _command($verb, $okCode = 200) { * @param string $verb command to check * @return string */ - protected function _translateCommandMethod( $verb ) { - $command = str_replace( '_', '.', $verb ); - switch( $this->getVersion() ) { + protected function _translateCommandMethod($verb) { + $command = str_replace('_', '.', $verb); + switch ($this->getVersion()) { case '2.1': - $command = str_replace( 'ban', 'purge', $command ); + $command = str_replace('ban', 'purge', $command); break; case '4.0': case '3.0': - $command = str_replace( 'purge', 'ban', $command ); + $command = str_replace('purge', 'ban', $command); break; default: - Mage::throwException( 'Unrecognized Varnish version: ' . - $this->_version ); + Mage::throwException('Unrecognized Varnish version: '. + $this->_version); } return $command; } diff --git a/app/code/community/Nexcessnet/Turpentine/Model/Varnish/Configurator/Version2.php b/app/code/community/Nexcessnet/Turpentine/Model/Varnish/Configurator/Version2.php index 4b9136473..170153981 100644 --- a/app/code/community/Nexcessnet/Turpentine/Model/Varnish/Configurator/Version2.php +++ b/app/code/community/Nexcessnet/Turpentine/Model/Varnish/Configurator/Version2.php @@ -30,17 +30,17 @@ class Nexcessnet_Turpentine_Model_Varnish_Configurator_Version2 * @param bool $doClean if true, VCL will be cleaned (whitespaces stripped, etc.) * @return string */ - public function generate($doClean=true) { - $tplFile = $this->_getVclTemplateFilename( self::VCL_TEMPLATE_FILE ); - $vcl = $this->_formatTemplate( file_get_contents( $tplFile ), - $this->_getTemplateVars() ); - return $doClean ? $this->_cleanVcl( $vcl ) : $vcl; + public function generate($doClean = true) { + $tplFile = $this->_getVclTemplateFilename(self::VCL_TEMPLATE_FILE); + $vcl = $this->_formatTemplate(file_get_contents($tplFile), + $this->_getTemplateVars()); + return $doClean ? $this->_cleanVcl($vcl) : $vcl; } protected function _getAdvancedSessionValidation() { $validation = ''; - foreach( $this->_getAdvancedSessionValidationTargets() as $target ) { - $validation .= sprintf( 'set req.hash += %s;' . PHP_EOL, $target ); + foreach ($this->_getAdvancedSessionValidationTargets() as $target) { + $validation .= sprintf('set req.hash += %s;'.PHP_EOL, $target); } return $validation; } diff --git a/app/code/community/Nexcessnet/Turpentine/Model/Varnish/Configurator/Version4.php b/app/code/community/Nexcessnet/Turpentine/Model/Varnish/Configurator/Version4.php index 08641fa24..273c09f1a 100644 --- a/app/code/community/Nexcessnet/Turpentine/Model/Varnish/Configurator/Version4.php +++ b/app/code/community/Nexcessnet/Turpentine/Model/Varnish/Configurator/Version4.php @@ -30,18 +30,18 @@ class Nexcessnet_Turpentine_Model_Varnish_Configurator_Version4 * @param bool $doClean if true, VCL will be cleaned (whitespaces stripped, etc.) * @return string */ - public function generate($doClean=true) { - $tplFile = $this->_getVclTemplateFilename( self::VCL_TEMPLATE_FILE ); - $vcl = $this->_formatTemplate( file_get_contents( $tplFile ), - $this->_getTemplateVars() ); - return $doClean ? $this->_cleanVcl( $vcl ) : $vcl; + public function generate($doClean = true) { + $tplFile = $this->_getVclTemplateFilename(self::VCL_TEMPLATE_FILE); + $vcl = $this->_formatTemplate(file_get_contents($tplFile), + $this->_getTemplateVars()); + return $doClean ? $this->_cleanVcl($vcl) : $vcl; } // TODO: Check this protected function _getAdvancedSessionValidation() { $validation = ''; - foreach( $this->_getAdvancedSessionValidationTargets() as $target ) { - $validation .= sprintf( 'hash_data(%s);' . PHP_EOL, $target ); + foreach ($this->_getAdvancedSessionValidationTargets() as $target) { + $validation .= sprintf('hash_data(%s);'.PHP_EOL, $target); } return $validation; } diff --git a/app/code/community/Nexcessnet/Turpentine/controllers/Adminhtml/CacheController.php b/app/code/community/Nexcessnet/Turpentine/controllers/Adminhtml/CacheController.php index 5161fb5b3..561e4c930 100644 --- a/app/code/community/Nexcessnet/Turpentine/controllers/Adminhtml/CacheController.php +++ b/app/code/community/Nexcessnet/Turpentine/controllers/Adminhtml/CacheController.php @@ -26,11 +26,11 @@ public function massEnableAction() } if ($updatedTypes > 0) { // disable FPC when Varnish cache is enabled: - if($allTypes['turpentine_pages']==1 || $allTypes['turpentine_esi_blocks']==1) + if ($allTypes['turpentine_pages'] == 1 || $allTypes['turpentine_esi_blocks'] == 1) { $allTypes['full_page'] = 0; Mage::getSingleton('core/session')->addSuccess(Mage::helper('adminhtml')->__("Full page cache has been disabled since Varnish cache is enabled.")); - } else if ($allTypes['full_page']==1) { + } else if ($allTypes['full_page'] == 1) { Mage::getSingleton('core/session')->addSuccess(Mage::helper('adminhtml')->__("Turpentine cache has been disabled since Full Page cache is enabled.")); } // disable FPC when Varnish cache is enabled. diff --git a/app/code/community/Nexcessnet/Turpentine/controllers/Varnish/ManagementController.php b/app/code/community/Nexcessnet/Turpentine/controllers/Varnish/ManagementController.php index a5bbd7e65..0472d4e62 100644 --- a/app/code/community/Nexcessnet/Turpentine/controllers/Varnish/ManagementController.php +++ b/app/code/community/Nexcessnet/Turpentine/controllers/Varnish/ManagementController.php @@ -150,23 +150,23 @@ public function applyConfigAction() { * @return null */ public function saveConfigAction() { - $cfgr = Mage::getModel( 'turpentine/varnish_admin' )->getConfigurator(); - if( is_null( $cfgr ) ) { + $cfgr = Mage::getModel('turpentine/varnish_admin')->getConfigurator(); + if (is_null($cfgr)) { $this->_getSession()->addError( - $this->__( 'Failed to load configurator' ) ); + $this->__('Failed to load configurator') ); } else { - Mage::dispatchEvent( 'turpentine_varnish_save_config', - array( 'cfgr' => $cfgr ) ); - $result = $cfgr->save( $cfgr->generate( - Mage::helper('turpentine')->shouldStripVclWhitespace('save') ) ); - if( $result[0] ) { + Mage::dispatchEvent('turpentine_varnish_save_config', + array('cfgr' => $cfgr)); + $result = $cfgr->save($cfgr->generate( + Mage::helper('turpentine')->shouldStripVclWhitespace('save') )); + if ($result[0]) { $this->_getSession() - ->addSuccess( Mage::helper('turpentine') - ->__('The VCL file has been saved.' ) ); + ->addSuccess(Mage::helper('turpentine') + ->__('The VCL file has been saved.')); } else { $this->_getSession() - ->addError( Mage::helper('turpentine') - ->__('Failed to save the VCL file: ' . $result[1]['message'] ) ); + ->addError(Mage::helper('turpentine') + ->__('Failed to save the VCL file: '.$result[1]['message'])); } } $this->_redirect('*/cache'); @@ -178,21 +178,21 @@ public function saveConfigAction() { * @return $this */ public function getConfigAction() { - $cfgr = Mage::getModel( 'turpentine/varnish_admin' ) + $cfgr = Mage::getModel('turpentine/varnish_admin') ->getConfigurator(); - if( is_null( $cfgr ) ) { - $this->_getSession()->addError( $this->__( 'Failed to load configurator' ) ); - $this->_redirect( '*/cache' ); + if (is_null($cfgr)) { + $this->_getSession()->addError($this->__('Failed to load configurator')); + $this->_redirect('*/cache'); } else { $vcl = $cfgr->generate( - Mage::helper( 'turpentine' )->shouldStripVclWhitespace('download') ); + Mage::helper('turpentine')->shouldStripVclWhitespace('download') ); $this->getResponse() - ->setHttpResponseCode( 200 ) - ->setHeader( 'Content-Type', 'text/plain', true ) - ->setHeader( 'Content-Length', strlen( $vcl ) ) - ->setHeader( 'Content-Disposition', - 'attachment; filename=default.vcl' ) - ->setBody( $vcl ); + ->setHttpResponseCode(200) + ->setHeader('Content-Type', 'text/plain', true) + ->setHeader('Content-Length', strlen($vcl)) + ->setHeader('Content-Disposition', + 'attachment; filename=default.vcl') + ->setBody($vcl); return $this; } } diff --git a/contrib/tools/esi-decoder.php b/contrib/tools/esi-decoder.php index 20ae29055..cf2bb6685 100644 --- a/contrib/tools/esi-decoder.php +++ b/contrib/tools/esi-decoder.php @@ -68,33 +68,33 @@
    getEsiDataParam(), '|' ); - if ( preg_match('|'.$dataPreg.'/([\w\.\-]+=*)|', $data, $matches) ) { + $esiHelper = Mage::helper('turpentine/esi'); + $dataPreg = preg_quote($esiHelper->getEsiDataParam(), '|'); + if (preg_match('|'.$dataPreg.'/([\w\.\-]+=*)|', $data, $matches)) { $processData = $matches[1]; } - $dataHelper = Mage::helper( 'turpentine/data' ); - $esiDataArray = $dataHelper->thaw( $processData ); - $showContentUrl = Mage::getUrl( 'turpentine/esi/getBlock', - array( 'method' => 'esi', + $dataHelper = Mage::helper('turpentine/data'); + $esiDataArray = $dataHelper->thaw($processData); + $showContentUrl = Mage::getUrl('turpentine/esi/getBlock', + array('method' => 'esi', 'ttl' => 0, - 'hmac' => $dataHelper->getHmac( $processData ), - 'data' => $processData ) ); + 'hmac' => $dataHelper->getHmac($processData), + 'data' => $processData)); ?>
    =  DATA  =
    -
    +
    getEsiReferrerParam(), '|' ); - if ( preg_match('|'.$refPreg.'/([\w\.\-]+),*|', $data, $matches) ): + $refPreg = preg_quote($esiHelper->getEsiReferrerParam(), '|'); + if (preg_match('|'.$refPreg.'/([\w\.\-]+),*|', $data, $matches)): $processData = $matches[1]; ?>
    =  REFERRER  =
    -
    urlBase64Decode( $processData ) ); ?>
    +
    urlBase64Decode($processData)); ?>
    Date: Thu, 5 Nov 2015 16:41:50 +0000 Subject: [PATCH 05/18] Invalidating cms pages with url enging with slash Invalidating cms pages with url enging with slash. Like: http://domain.com/about-us/ --- app/code/community/Nexcessnet/Turpentine/Model/Observer/Ban.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/code/community/Nexcessnet/Turpentine/Model/Observer/Ban.php b/app/code/community/Nexcessnet/Turpentine/Model/Observer/Ban.php index 843f90043..420c61e5b 100644 --- a/app/code/community/Nexcessnet/Turpentine/Model/Observer/Ban.php +++ b/app/code/community/Nexcessnet/Turpentine/Model/Observer/Ban.php @@ -235,7 +235,7 @@ public function banCmsPageRevisionCache($eventObject) { return; } $pageIdentifier = $page->getIdentifier(); - $result = $this->_getVarnishAdmin()->flushUrl($pageIdentifier.'(?:\.html?)?$'); + $result = $this->_getVarnishAdmin()->flushUrl($pageIdentifier.'(?:\.html?)?/?$'); Mage::dispatchEvent('turpentine_ban_cms_page_cache', $result); $cronHelper = Mage::helper('turpentine/cron'); if ($this->_checkResult($result) && From 97b3fb9609b7ab287f181bac4f9cb8af57e2d2d0 Mon Sep 17 00:00:00 2001 From: Sergey Ivashchenko Date: Thu, 5 Nov 2015 16:45:34 +0000 Subject: [PATCH 06/18] Update Ban.php --- .../community/Nexcessnet/Turpentine/Model/Observer/Ban.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/app/code/community/Nexcessnet/Turpentine/Model/Observer/Ban.php b/app/code/community/Nexcessnet/Turpentine/Model/Observer/Ban.php index 420c61e5b..83ff52ceb 100644 --- a/app/code/community/Nexcessnet/Turpentine/Model/Observer/Ban.php +++ b/app/code/community/Nexcessnet/Turpentine/Model/Observer/Ban.php @@ -207,7 +207,7 @@ public function banCatalogImagesCache($eventObject) { public function banCmsPageCache($eventObject) { if (Mage::helper('turpentine/varnish')->getVarnishEnabled()) { $pageId = $eventObject->getDataObject()->getIdentifier(); - $result = $this->_getVarnishAdmin()->flushUrl($pageId.'(?:\.html?)?$'); + $result = $this->_getVarnishAdmin()->flushUrl($pageId.'(?:\.html?)?\/?$'); Mage::dispatchEvent('turpentine_ban_cms_page_cache', $result); $cronHelper = Mage::helper('turpentine/cron'); if ($this->_checkResult($result) && @@ -235,7 +235,7 @@ public function banCmsPageRevisionCache($eventObject) { return; } $pageIdentifier = $page->getIdentifier(); - $result = $this->_getVarnishAdmin()->flushUrl($pageIdentifier.'(?:\.html?)?/?$'); + $result = $this->_getVarnishAdmin()->flushUrl($pageIdentifier.'(?:\.html?)?$'); Mage::dispatchEvent('turpentine_ban_cms_page_cache', $result); $cronHelper = Mage::helper('turpentine/cron'); if ($this->_checkResult($result) && From 13a7988b3b0fe7262289cd7456ff7626c321e58c Mon Sep 17 00:00:00 2001 From: mbalparda Date: Tue, 10 Nov 2015 16:46:06 -0300 Subject: [PATCH 07/18] refs Added PRs to CHANGELOG.md and bump version. --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 09c912622..b85a8142b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -421,3 +421,4 @@ Magento CE 1.8+ or EE 1.13+, see [these instructions](https://github.com/nexcess * [#955] Include theme specific handles to ESI data (@LyndonHook) * [#972] Fixed bug with wrong return value of ->getSkinUrl() (@ceckoslab) * [#951] Added 'disableEsiInjection' ESI policy option. + * [#1005 ] Invalidating cms pages with url enging with slash. (@sivaschenko) From 8a788e86f1c632a64e15f7df73c121147162f1b5 Mon Sep 17 00:00:00 2001 From: Paul Partington Date: Wed, 18 Nov 2015 12:27:36 +0000 Subject: [PATCH 08/18] Add the form key to wishlist submit to prevent 403 errors. --- .../Turpentine/Model/Observer/Esi.php | 17 +++++++++++++++++ .../Nexcessnet/Turpentine/etc/config.xml | 8 ++++++++ 2 files changed, 25 insertions(+) diff --git a/app/code/community/Nexcessnet/Turpentine/Model/Observer/Esi.php b/app/code/community/Nexcessnet/Turpentine/Model/Observer/Esi.php index 5124e706e..805ea0baa 100644 --- a/app/code/community/Nexcessnet/Turpentine/Model/Observer/Esi.php +++ b/app/code/community/Nexcessnet/Turpentine/Model/Observer/Esi.php @@ -532,6 +532,9 @@ 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) { @@ -552,4 +555,18 @@ 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; + } } diff --git a/app/code/community/Nexcessnet/Turpentine/etc/config.xml b/app/code/community/Nexcessnet/Turpentine/etc/config.xml index a9fc7eec1..5e814f690 100644 --- a/app/code/community/Nexcessnet/Turpentine/etc/config.xml +++ b/app/code/community/Nexcessnet/Turpentine/etc/config.xml @@ -468,6 +468,14 @@ + + + + turpentine/observer_esi + >hookToAddToWishlistBefore + + + From ae50f395597326fa800ff7ed9930432ed7111604 Mon Sep 17 00:00:00 2001 From: Aric Watson Date: Tue, 1 Dec 2015 13:49:09 -0500 Subject: [PATCH 09/18] Added search results flush event to resolve Issue #938 --- app/design/frontend/base/default/layout/turpentine_esi.xml | 1 + 1 file changed, 1 insertion(+) diff --git a/app/design/frontend/base/default/layout/turpentine_esi.xml b/app/design/frontend/base/default/layout/turpentine_esi.xml index f44357b68..276137966 100644 --- a/app/design/frontend/base/default/layout/turpentine_esi.xml +++ b/app/design/frontend/base/default/layout/turpentine_esi.xml @@ -44,6 +44,7 @@ + From 3e3bb425967526c0ea7870f19e7236bdcf8fabf3 Mon Sep 17 00:00:00 2001 From: Jeroen Vermeulen Date: Tue, 1 Dec 2015 21:51:42 +0100 Subject: [PATCH 10/18] Improved helper function getModelName() It did not work in case an extension used in config.xml: MyPackage_MyExtension_Model Because then the class guessed by getModelName($product) is: `myextension/product` while it should be `mygroupname/product`. I made the function check if the guess is a valid model. If not: the right value is quite hard to look up, so I decided to return `MyPackage_MyExtension_Model_Product` in this example. --- .../Nexcessnet/Turpentine/Helper/Data.php | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) diff --git a/app/code/community/Nexcessnet/Turpentine/Helper/Data.php b/app/code/community/Nexcessnet/Turpentine/Helper/Data.php index 040252c15..6515feee9 100644 --- a/app/code/community/Nexcessnet/Turpentine/Helper/Data.php +++ b/app/code/community/Nexcessnet/Turpentine/Helper/Data.php @@ -231,12 +231,20 @@ public function getChildBlockNames($blockNode) { * @param string|object $model * @return string */ - public function getModelName($model) { - if (is_object($model)) { - $model = get_class($model); + public function getModelName( $model ) { + if( is_object( $model ) ) { + $model = get_class( $model ); } - return strtolower(preg_replace( - '~^[^_]+_([^_]+)_Model_(.+)$~', '$1/$2', $model )); + // This guess may work if the extension uses its lowercased name as model group name. + $result = strtolower( preg_replace( + '~^[^_]+_([^_]+)_Model_(.+)$~', '$1/$2', $model ) ); + // This check is not expensive because the answer should come from Magento's classNameCache + $checkModel = Mage::getConfig()->getModelClassName($result); + if ( 'Mage_' == substr($checkModel,0,5) && !class_exists($result) ) { + // Fallback to full model name. + $result = $model; + } + return $result; } /** From f57f39ca539ccb73b5bbf7b7dea49d1a3d7b1d86 Mon Sep 17 00:00:00 2001 From: Simon Sprankel Date: Mon, 7 Dec 2015 14:23:13 +0100 Subject: [PATCH 11/18] prime checkout and light checkout compatibility --- .../base/default/layout/turpentine_esi.xml | 120 ++++++++++++++++++ 1 file changed, 120 insertions(+) diff --git a/app/design/frontend/base/default/layout/turpentine_esi.xml b/app/design/frontend/base/default/layout/turpentine_esi.xml index 276137966..d8c18dae4 100644 --- a/app/design/frontend/base/default/layout/turpentine_esi.xml +++ b/app/design/frontend/base/default/layout/turpentine_esi.xml @@ -283,6 +283,126 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + From 23f49fab3433abf53fb05fec0400e3bbc148cd5e Mon Sep 17 00:00:00 2001 From: Jeroen Vermeulen Date: Mon, 14 Dec 2015 00:10:23 +0100 Subject: [PATCH 12/18] "Use Simple Hash" option for static files When enabled: Always serve the same version of a static file. Ignore domain, cookies and browser version. Saves memory and lowers cache misses. Thanks to @toonvd for the idea of this improvement. Improved some use of booleans in Varnish version 2.1 config --- .../Model/Varnish/Configurator/Abstract.php | 11 +++++++++++ .../Nexcessnet/Turpentine/etc/config.xml | 1 + .../Nexcessnet/Turpentine/etc/system.xml | 13 +++++++++++++ .../Nexcessnet/Turpentine/misc/version-2.vcl | 19 ++++++++++++++++--- .../Nexcessnet/Turpentine/misc/version-3.vcl | 11 +++++++++++ .../Nexcessnet/Turpentine/misc/version-4.vcl | 11 +++++++++++ 6 files changed, 63 insertions(+), 3 deletions(-) diff --git a/app/code/community/Nexcessnet/Turpentine/Model/Varnish/Configurator/Abstract.php b/app/code/community/Nexcessnet/Turpentine/Model/Varnish/Configurator/Abstract.php index c4808ef47..86805aea8 100644 --- a/app/code/community/Nexcessnet/Turpentine/Model/Varnish/Configurator/Abstract.php +++ b/app/code/community/Nexcessnet/Turpentine/Model/Varnish/Configurator/Abstract.php @@ -439,6 +439,16 @@ protected function _getForceCacheStatic() { ? 'true' : 'false'; } + /** + * Get the Force Static Caching option + * + * @return string + */ + protected function _getSimpleHashStatic() { + return Mage::getStoreConfig('turpentine_vcl/static/simple_hash') + ? 'true' : 'false'; + } + /** * Format the list of static cache extensions * @@ -942,6 +952,7 @@ protected function _getTemplateVars() { 'debug_headers' => $this->_getEnableDebugHeaders(), 'grace_period' => $this->_getGracePeriod(), 'force_cache_static' => $this->_getForceCacheStatic(), + 'simple_hash_static' => $this->_getSimpleHashStatic(), 'generate_session_expires' => $this->_getGenerateSessionExpires(), 'generate_session' => $this->_getGenerateSession(), 'generate_session_start' => $this->_getGenerateSessionStart(), diff --git a/app/code/community/Nexcessnet/Turpentine/etc/config.xml b/app/code/community/Nexcessnet/Turpentine/etc/config.xml index 5e814f690..9f15c241f 100644 --- a/app/code/community/Nexcessnet/Turpentine/etc/config.xml +++ b/app/code/community/Nexcessnet/Turpentine/etc/config.xml @@ -85,6 +85,7 @@ 1 css,js,jpe?g,png,gif,ico,swf + 1 diff --git a/app/code/community/Nexcessnet/Turpentine/etc/system.xml b/app/code/community/Nexcessnet/Turpentine/etc/system.xml index 396871326..fcbaf2c17 100644 --- a/app/code/community/Nexcessnet/Turpentine/etc/system.xml +++ b/app/code/community/Nexcessnet/Turpentine/etc/system.xml @@ -587,6 +587,19 @@ 0 0 + + + Always serve the same version of a static file. Ignore domain, cookies and browser version. Saves memory and lowers cache misses. + + 1 + + select + turpentine/config_select_toggle + 30 + 1 + 0 + 0 + diff --git a/app/code/community/Nexcessnet/Turpentine/misc/version-2.vcl b/app/code/community/Nexcessnet/Turpentine/misc/version-2.vcl index 5fa385f5d..d581be09e 100644 --- a/app/code/community/Nexcessnet/Turpentine/misc/version-2.vcl +++ b/app/code/community/Nexcessnet/Turpentine/misc/version-2.vcl @@ -100,9 +100,11 @@ sub vcl_recv { } # varnish 2.1 doesn't support bare booleans so we have to add these - # as headers to the req so they've available throught the VCL + # as headers to the req so they've available through the VCL set req.http.X-Opt-Enable-Caching = "{{enable_caching}}"; set req.http.X-Opt-Force-Static-Caching = "{{force_cache_static}}"; + set req.http.X-Opt-Simple-Hash-Static = "{{simple_hash_static}}"; + set req.http.X-Opt-Enable-Get-Ignored = "{{enable_get_ignored}}"; set req.http.X-Opt-Enable-Get-Excludes = "{{enable_get_excludes}}"; set req.http.X-Opt-Send-Unmodified-Url = "{{send_unmodified_url}}"; @@ -186,6 +188,7 @@ sub vcl_recv { # don't need cookies for static assets remove req.http.Cookie; remove req.http.X-Varnish-Faked-Session; + set req.http.X-Varnish-Static = "1"; return (lookup); } # this doesn't need a enable_url_excludes because we can be reasonably @@ -202,7 +205,7 @@ sub vcl_recv { req.url ~ "(?:[?&](?:{{get_param_excludes}})(?=[&=]|$))") { return (pass); } - if ({{enable_get_ignored}} && req.url ~ "[?&]({{get_param_ignored}})=") { + if (req.http.X-Opt-Enable-Get-Ignored == "true" && req.url ~ "[?&]({{get_param_ignored}})=") { # Strip out ignored GET related parameters set req.url = regsuball(req.url, "(?:(\?)?|&)(?:{{get_param_ignored}})=[^&]+", "\1"); set req.url = regsuball(req.url, "(?:(\?)&|\?$)", "\1"); @@ -234,8 +237,18 @@ sub vcl_pipe { # } sub vcl_hash { + # For static files we keep the hash simple and don't add the domain. + # This saves memory when a static file is used on multiple domains. + if (req.http.X-Opt-Simple-Hash-Static == "true" && req.http.X-Varnish-Static) { + set req.hash += req.url; + if (req.http.Accept-Encoding) { + # make sure we give back the right encoding + set req.hash += req.http.Accept-Encoding; + } + return (hash); + } - if({{send_unmodified_url}} && req.http.X-Varnish-Cache-Url) { + if(req.http.X-Opt-Send-Unmodified-Url == "true" && req.http.X-Varnish-Cache-Url) { set req.hash += req.http.X-Varnish-Cache-Url; } else { set req.hash += req.url; diff --git a/app/code/community/Nexcessnet/Turpentine/misc/version-3.vcl b/app/code/community/Nexcessnet/Turpentine/misc/version-3.vcl index 115c1887f..10219981e 100644 --- a/app/code/community/Nexcessnet/Turpentine/misc/version-3.vcl +++ b/app/code/community/Nexcessnet/Turpentine/misc/version-3.vcl @@ -185,6 +185,7 @@ sub vcl_recv { # don't need cookies for static assets unset req.http.Cookie; unset req.http.X-Varnish-Faked-Session; + set req.http.X-Varnish-Static = 1; return (lookup); } # this doesn't need a enable_url_excludes because we can be reasonably @@ -233,6 +234,16 @@ sub vcl_pipe { # } sub vcl_hash { + # For static files we keep the hash simple and don't add the domain. + # This saves memory when a static file is used on multiple domains. + if ({{simple_hash_static}} && req.http.X-Varnish-Static) { + hash_data(req.url); + if (req.http.Accept-Encoding) { + # make sure we give back the right encoding + hash_data(req.http.Accept-Encoding); + } + return (hash); + } if({{send_unmodified_url}} && req.http.X-Varnish-Cache-Url) { hash_data(req.http.X-Varnish-Cache-Url); diff --git a/app/code/community/Nexcessnet/Turpentine/misc/version-4.vcl b/app/code/community/Nexcessnet/Turpentine/misc/version-4.vcl index ca782c605..874bd65e1 100644 --- a/app/code/community/Nexcessnet/Turpentine/misc/version-4.vcl +++ b/app/code/community/Nexcessnet/Turpentine/misc/version-4.vcl @@ -183,6 +183,7 @@ sub vcl_recv { # don't need cookies for static assets unset req.http.Cookie; unset req.http.X-Varnish-Faked-Session; + set req.http.X-Varnish-Static = 1; return (hash); } # this doesn't need a enable_url_excludes because we can be reasonably @@ -237,6 +238,16 @@ sub vcl_pipe { # } sub vcl_hash { + # For static files we keep the hash simple and don't add the domain. + # This saves memory when a static file is used on multiple domains. + if ({{simple_hash_static}} && req.http.X-Varnish-Static) { + hash_data(req.url); + if (req.http.Accept-Encoding) { + # make sure we give back the right encoding + hash_data(req.http.Accept-Encoding); + } + return (lookup); + } if({{send_unmodified_url}} && req.http.X-Varnish-Cache-Url) { hash_data(req.http.X-Varnish-Cache-Url); From 9f4178cfaabc9079f1557f41a08124d6857d8d8d Mon Sep 17 00:00:00 2001 From: Aric Watson Date: Thu, 17 Dec 2015 15:17:52 -0500 Subject: [PATCH 13/18] Moved the custom include vcl to bottom Custom included VCL is now included at the bottom of the generated VCL --- .../community/Nexcessnet/Turpentine/misc/version-3.vcl | 9 +++++---- .../community/Nexcessnet/Turpentine/misc/version-4.vcl | 8 ++++---- 2 files changed, 9 insertions(+), 8 deletions(-) diff --git a/app/code/community/Nexcessnet/Turpentine/misc/version-3.vcl b/app/code/community/Nexcessnet/Turpentine/misc/version-3.vcl index 115c1887f..57aa03a04 100644 --- a/app/code/community/Nexcessnet/Turpentine/misc/version-3.vcl +++ b/app/code/community/Nexcessnet/Turpentine/misc/version-3.vcl @@ -28,10 +28,6 @@ C{ import std; -## Custom VCL Logic - -{{custom_vcl_include}} - ## Backends {{default_backend}} @@ -423,3 +419,8 @@ sub vcl_deliver { unset resp.http.X-Varnish-Set-Cookie; } } + +## Custom VCL Logic + +{{custom_vcl_include}} + diff --git a/app/code/community/Nexcessnet/Turpentine/misc/version-4.vcl b/app/code/community/Nexcessnet/Turpentine/misc/version-4.vcl index ca782c605..4c07d7f9e 100644 --- a/app/code/community/Nexcessnet/Turpentine/misc/version-4.vcl +++ b/app/code/community/Nexcessnet/Turpentine/misc/version-4.vcl @@ -29,10 +29,6 @@ C{ import std; -## Custom VCL Logic - -{{custom_vcl_include}} - ## Backends {{default_backend}} @@ -424,3 +420,7 @@ sub vcl_deliver { unset resp.http.X-Varnish-Set-Cookie; } } + +## Custom VCL Logic + +{{custom_vcl_include}} From fdc1d16ac3658efec2bb17adda6e38155a82d3bd Mon Sep 17 00:00:00 2001 From: miguelbalparda Date: Wed, 30 Dec 2015 10:55:45 -0300 Subject: [PATCH 14/18] refs Added PRs to CHANGELOG.md. --- CHANGELOG.md | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b85a8142b..5965578fe 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -421,4 +421,9 @@ Magento CE 1.8+ or EE 1.13+, see [these instructions](https://github.com/nexcess * [#955] Include theme specific handles to ESI data (@LyndonHook) * [#972] Fixed bug with wrong return value of ->getSkinUrl() (@ceckoslab) * [#951] Added 'disableEsiInjection' ESI policy option. - * [#1005 ] Invalidating cms pages with url enging with slash. (@sivaschenko) + * [#1005] Invalidating cms pages with url enging with slash. (@sivaschenko) + * [#1020] Add the form key to wishlist submit to prevent 403 errors. (@paulpartington) + * [#1036] Prime Checkout and Light Checkout Compatibility. (@sprankhub) + * [#1050] Use Simple Hash" option for static files. (@jeroenvermeulen) + * [#1031] Improved helper function getModelName(). (@jeroenvermeulen) + From d1de03f71da5a58a7225327b6be88d3e1f19cf37 Mon Sep 17 00:00:00 2001 From: Aric Watson Date: Tue, 5 Jan 2016 18:03:30 -0500 Subject: [PATCH 15/18] Added ESI policy for cookie notice block --- .../frontend/base/default/layout/turpentine_esi.xml | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/app/design/frontend/base/default/layout/turpentine_esi.xml b/app/design/frontend/base/default/layout/turpentine_esi.xml index d8c18dae4..9cd985aad 100644 --- a/app/design/frontend/base/default/layout/turpentine_esi.xml +++ b/app/design/frontend/base/default/layout/turpentine_esi.xml @@ -138,6 +138,16 @@ + + + + + private + no_text + + + + From d5dc273b011d8eb58627670d75c5bc8e48f49104 Mon Sep 17 00:00:00 2001 From: Jeroen Vermeulen Date: Wed, 6 Jan 2016 17:36:42 +0100 Subject: [PATCH 16/18] Fix for crawler lock problem with CM_RedisSession Turpentine sets the fake cookie 'frontend=crawler-session' when a crawler is detected. This causes lock problems with Cm_RedisSession, because all crawler hits are requesting the same session lock. Cm_RedisSession provides the define CM_REDISSESSION_LOCKING_ENABLED to overrule if locking should be enabled. I added an 'controller_front_init_before' event listener to set this define if the fake session cookie exists. --- .../Turpentine/Model/Observer/Varnish.php | 16 ++++++++++++++++ .../Nexcessnet/Turpentine/etc/config.xml | 4 ++++ 2 files changed, 20 insertions(+) diff --git a/app/code/community/Nexcessnet/Turpentine/Model/Observer/Varnish.php b/app/code/community/Nexcessnet/Turpentine/Model/Observer/Varnish.php index d1e9067c1..be6ecb3cc 100644 --- a/app/code/community/Nexcessnet/Turpentine/Model/Observer/Varnish.php +++ b/app/code/community/Nexcessnet/Turpentine/Model/Observer/Varnish.php @@ -55,6 +55,22 @@ public function addProductListToolbarRewrite($eventObject) { } } + /** + * Turpentine sets the fake cookie 'frontend=crawler-session' when a crawler is detected. + * This causes lock problems with Cm_RedisSession, because all crawler hits are requesting the same session lock. + * Cm_RedisSession provides the define CM_REDISSESSION_LOCKING_ENABLED to overrule if locking should be enabled. + * + * @param $eventObject + * @return null + */ + public function fixCmRedisSessionLocks($eventObject) { + if (Mage::helper('core')->isModuleEnabled('Cm_RedisSession')) { + if (!empty($_COOKIE['frontend']) && 'crawler-session' == $_COOKIE['frontend']) { + define('CM_REDISSESSION_LOCKING_ENABLED', false); + } + } + } + /** * Re-apply and save Varnish configuration on config change * diff --git a/app/code/community/Nexcessnet/Turpentine/etc/config.xml b/app/code/community/Nexcessnet/Turpentine/etc/config.xml index 9f15c241f..23ed88e1f 100644 --- a/app/code/community/Nexcessnet/Turpentine/etc/config.xml +++ b/app/code/community/Nexcessnet/Turpentine/etc/config.xml @@ -302,6 +302,10 @@ turpentine/observer_varnish addProductListToolbarRewrite + + turpentine/observer_varnish + fixCmRedisSessionLocks + turpentine/observer_esi setReplaceFormKeyFlag From abb5b946efc2bd9c8a1740da183ea55fb3a984ef Mon Sep 17 00:00:00 2001 From: miguelbalparda Date: Thu, 14 Jan 2016 10:49:50 -0300 Subject: [PATCH 17/18] refs Added PRs to CHANGELOG.md and bump version. --- CHANGELOG.md | 7 ++++++- app/code/community/Nexcessnet/Turpentine/etc/config.xml | 2 +- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5965578fe..91bd16ed6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -420,10 +420,15 @@ Magento CE 1.8+ or EE 1.13+, see [these instructions](https://github.com/nexcess * [#885] Add maintenance mode that will allow debug_ips through to visit the site, all other users get the landing page (@craigcarnell) * [#955] Include theme specific handles to ESI data (@LyndonHook) * [#972] Fixed bug with wrong return value of ->getSkinUrl() (@ceckoslab) + +### RELEASE-0.6.7 * [#951] Added 'disableEsiInjection' ESI policy option. * [#1005] Invalidating cms pages with url enging with slash. (@sivaschenko) * [#1020] Add the form key to wishlist submit to prevent 403 errors. (@paulpartington) - * [#1036] Prime Checkout and Light Checkout Compatibility. (@sprankhub) + * [#1036] Prime Checkout and Light Checkout Compatibility. (@sprankhub) * [#1050] Use Simple Hash" option for static files. (@jeroenvermeulen) * [#1031] Improved helper function getModelName(). (@jeroenvermeulen) + * [#1066] Fix for crawler lock problem with CM_RedisSession. (@jeroenvermeulen) +### RELEASE-0.6.8 + * [#1065] Added ESI policy for cookie notice block. (@aricwatson) diff --git a/app/code/community/Nexcessnet/Turpentine/etc/config.xml b/app/code/community/Nexcessnet/Turpentine/etc/config.xml index 23ed88e1f..e13b425d6 100644 --- a/app/code/community/Nexcessnet/Turpentine/etc/config.xml +++ b/app/code/community/Nexcessnet/Turpentine/etc/config.xml @@ -20,7 +20,7 @@ - 0.6.7 + 0.6.8 From e7a32446e3514c8efc742b2ad14ce1ba8660ced3 Mon Sep 17 00:00:00 2001 From: Scrutinizer Auto-Fixer Date: Thu, 14 Jan 2016 14:02:00 +0000 Subject: [PATCH 18/18] Scrutinizer Auto-Fixes This commit consists of patches automatically generated for this project on https://scrutinizer-ci.com --- .../community/Nexcessnet/Turpentine/Helper/Data.php | 12 ++++++------ .../Nexcessnet/Turpentine/Model/Observer/Varnish.php | 2 +- .../controllers/Adminhtml/CacheController.php | 6 +++--- 3 files changed, 10 insertions(+), 10 deletions(-) diff --git a/app/code/community/Nexcessnet/Turpentine/Helper/Data.php b/app/code/community/Nexcessnet/Turpentine/Helper/Data.php index 6515feee9..a357b7a47 100644 --- a/app/code/community/Nexcessnet/Turpentine/Helper/Data.php +++ b/app/code/community/Nexcessnet/Turpentine/Helper/Data.php @@ -231,16 +231,16 @@ public function getChildBlockNames($blockNode) { * @param string|object $model * @return string */ - public function getModelName( $model ) { - if( is_object( $model ) ) { - $model = get_class( $model ); + public function getModelName($model) { + if (is_object($model)) { + $model = get_class($model); } // This guess may work if the extension uses its lowercased name as model group name. - $result = strtolower( preg_replace( - '~^[^_]+_([^_]+)_Model_(.+)$~', '$1/$2', $model ) ); + $result = strtolower(preg_replace( + '~^[^_]+_([^_]+)_Model_(.+)$~', '$1/$2', $model )); // This check is not expensive because the answer should come from Magento's classNameCache $checkModel = Mage::getConfig()->getModelClassName($result); - if ( 'Mage_' == substr($checkModel,0,5) && !class_exists($result) ) { + if ('Mage_' == substr($checkModel, 0, 5) && ! class_exists($result)) { // Fallback to full model name. $result = $model; } diff --git a/app/code/community/Nexcessnet/Turpentine/Model/Observer/Varnish.php b/app/code/community/Nexcessnet/Turpentine/Model/Observer/Varnish.php index be6ecb3cc..7eb51c4e3 100644 --- a/app/code/community/Nexcessnet/Turpentine/Model/Observer/Varnish.php +++ b/app/code/community/Nexcessnet/Turpentine/Model/Observer/Varnish.php @@ -65,7 +65,7 @@ public function addProductListToolbarRewrite($eventObject) { */ public function fixCmRedisSessionLocks($eventObject) { if (Mage::helper('core')->isModuleEnabled('Cm_RedisSession')) { - if (!empty($_COOKIE['frontend']) && 'crawler-session' == $_COOKIE['frontend']) { + if ( ! empty($_COOKIE['frontend']) && 'crawler-session' == $_COOKIE['frontend']) { define('CM_REDISSESSION_LOCKING_ENABLED', false); } } diff --git a/app/code/community/Nexcessnet/Turpentine/controllers/Adminhtml/CacheController.php b/app/code/community/Nexcessnet/Turpentine/controllers/Adminhtml/CacheController.php index 561e4c930..9beb94935 100644 --- a/app/code/community/Nexcessnet/Turpentine/controllers/Adminhtml/CacheController.php +++ b/app/code/community/Nexcessnet/Turpentine/controllers/Adminhtml/CacheController.php @@ -1,8 +1,8 @@