Re-apply and save Varnish configuration on config change

@param  mixed $eventObject
@return null
336125
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');
            $helper = Mage::helper('turpentine');
            foreach ($result as $name => $value) {
                if ($value === true) {
                    $session->addSuccess($helper
                        ->__('VCL successfully applied to: '.$name));
                } else {
                    $session->addError($helper
                        ->__(sprintf('Failed to apply the VCL to %s: %s',
                            $name, $value)));
                }
            }
            $cfgr = Mage::getModel('turpentine/varnish_admin')->getConfigurator();
            if (is_null($cfgr)) {
                $session->addError($helper
                    ->__('Failed to load configurator'));
            } else {
                $result = $cfgr->save($cfgr->generate($helper->shouldStripVclWhitespace('save')));
                if ($result[0]) {
                    $session->addSuccess($helper
                        ->__('The VCL file has been saved.'));
                } else {
                    $session->addError($helper
                        ->__('Failed to save the VCL file: '.$result[1]['message']));
                }
            }
        }
    }
804697
public function replaceFormKeyPlaceholder($eventObject) {
        if (Mage::registry('replace_form_key')) {
            $esiHelper = Mage::helper('turpentine/esi');
            $response = $eventObject->getResponse();
            $responseBody = $response->getBody();
            $responseBody = str_replace('{{form_key_esi_placeholder}}',
                $esiHelper->buildEsiIncludeFragment(
                    $esiHelper->getFormKeyEsiUrl() ),
                $responseBody);
            $response->setBody($responseBody);
        }
    }
590379
public function afterSave(Event $event, EntityInterface $entity)
    {
        $property = $this->versionAssociation()->getProperty();
        $entity->unsetProperty($property);
    }
140391
public function addChild($clientObject)
    {
        $this->data[] = $clientObject;
        if (is_null($clientObject->parentCollection))
            $clientObject->parentCollection = $this;
    }
18832
public function checkRedirectUrl($eventObject) {
        $esiHelper = Mage::helper('turpentine/esi');
        $url = $eventObject->getTransport()->getUrl();
        $referer = Mage::helper('core/http')->getHttpReferer();
        $dummyUrl = $esiHelper->getDummyUrl();
        $reqUenc = Mage::helper('core')->urlDecode(
            Mage::app()->getRequest()->getParam('uenc') );

        if ($this->_checkIsEsiUrl($url)) {
            if ($this->_checkIsNotEsiUrl($reqUenc) &&
                    Mage::getBaseUrl() == $url) {
                $newUrl = $this->_fixupUencUrl($reqUenc);
            } elseif ($this->_checkIsNotEsiUrl($referer)) {
                $newUrl = $referer;
            } else {
                $newUrl = $dummyUrl;
            }
            // TODO: make sure this actually looks like a URL
            $eventObject->getTransport()->setUrl($newUrl);
        }

        if ($eventObject->getTransport()->getUrl() != $url) {
            Mage::helper('turpentine/debug')->logDebug(
                'Detected redirect to ESI URL, changing: %s => %s',
                $url, $eventObject->getTransport()->getUrl() );
        }
    }
1301148
private void fireEvent(int eventType, Object eventObject) {
        AgentRosterListener[] listeners;
        synchronized (this.listeners) {
            listeners = new AgentRosterListener[this.listeners.size()];
            this.listeners.toArray(listeners);
        }
        for (int i = 0; i < listeners.length; i++) {
            switch (eventType) {
                case EVENT_AGENT_ADDED:
                    listeners[i].agentAdded((EntityBareJid) eventObject);
                    break;
                case EVENT_AGENT_REMOVED:
                    listeners[i].agentRemoved((EntityBareJid) eventObject);
                    break;
                case EVENT_PRESENCE_CHANGED:
                    listeners[i].presenceChanged((Presence) eventObject);
                    break;
            }
        }
    }
1147408
public function updateMetadata(EventInterface $event) {
        $request = $event->getRequest();

        $event->getDatabase()->updateMetadata(
            $request->getUser(),
            $request->getImageIdentifier(),
            $event->getArgument('metadata')
        );

        $event->getDatabase()->setLastModifiedNow(
            $request->getUser(),
            $request->getImageIdentifier()
        );
    }
731077
public function crawlUrls($eventObject) {
        $helper = Mage::helper('turpentine/cron');
        if ($helper->getCrawlerEnabled()) {
            $maxRunTime = $helper->getAllowedRunTime();
            if ($maxRunTime === 0) {
                $maxRunTime = self::MAX_CRAWL_TIME;
            }

            $batchSize = $helper->getCrawlerBatchSize();
            $timeout = $helper->getCrawlerWaitPeriod();
            $crawlCount = 0;

            // 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(
                        'Failed to crawl URL: %s', $url );
                }

                if ($crawlCount > 0
                    && $timeout > 0
                    && $batchSize > 0
                    && $crawlCount % $batchSize == 0
                ) {
                    Mage::helper('turpentine/debug')->logDebug('Crawled '.$crawlCount.' urls, sleeping for '.$timeout.' seconds');
                    sleep($timeout);
                }
                $crawlCount++;
            }
        }
    }
155712
public function banCmsPageRevisionCache($eventObject) {
        if (Mage::helper('turpentine/varnish')->getVarnishEnabled()) {
            $pageId = $eventObject->getDataObject()->getPageId();
            $page = Mage::getModel('cms/page')->load($pageId);

            // Don't do anything if the page isn't found.
            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);
            }
        }
    }
457667
public function injectEsi($eventObject) {
        $blockObject = $eventObject->getBlock();
        $dataHelper = Mage::helper('turpentine/data');
        $esiHelper = Mage::helper('turpentine/esi');
        $debugHelper = Mage::helper('turpentine/debug');
        if ($esiHelper->getEsiBlockLogEnabled()) {
            $debugHelper->logInfo(
                'Checking ESI block candidate: %s',
                $blockObject->getNameInLayout() ? $blockObject->getNameInLayout() : $blockObject->getModuleName() );

            $debugHelper->logInfo("-- block testing: shouldResponseUseEsi = ".$esiHelper->shouldResponseUseEsi());
            $debugHelper->logInfo("-- block testing: instanceof Mage_Core_Block_Template = ".$blockObject instanceof Mage_Core_Block_Template);
            $debugHelper->logInfo("-- block testing: Esi Options = ".print_r($blockObject->getEsiOptions(), true));
        }        
        if ($esiHelper->shouldResponseUseEsi() &&
                $blockObject instanceof Mage_Core_Block_Template &&
                $esiOptions = $blockObject->getEsiOptions()) {

            if ((isset($esiOptions['disableEsiInjection'])) && ($esiOptions['disableEsiInjection'] == 1)) { 
                if ($esiHelper->getEsiBlockLogEnabled()) {
                    $debugHelper->logInfo("-- ESI Injection disabled");
                }
                return;
            }

            if (Mage::app()->getStore()->getCode() == 'admin') {
                // admin blocks are not allowed to be cached for now
                $debugHelper->logWarn(
                    'Ignoring attempt to inject adminhtml block: %s',
                    $blockObject->getNameInLayout() ? $blockObject->getNameInLayout() : $blockObject->getModuleName() );
                return;
            } elseif ($esiHelper->getEsiBlockLogEnabled()) {
                $debugHelper->logInfo('Block check passed, injecting block: %s',
                    $blockObject->getNameInLayout() ? $blockObject->getNameInLayout() : $blockObject->getModuleName());
            }
            Varien_Profiler::start('turpentine::observer::esi::injectEsi');
            $ttlParam = $esiHelper->getEsiTtlParam();
            $cacheTypeParam = $esiHelper->getEsiCacheTypeParam();
            $dataParam = $esiHelper->getEsiDataParam();
            $methodParam = $esiHelper->getEsiMethodParam();
            $hmacParam = $esiHelper->getEsiHmacParam();
            $scopeParam = $esiHelper->getEsiScopeParam();
            $referrerParam = $esiHelper->getEsiReferrerParam();

            $esiOptions = $this->_getDefaultEsiOptions($esiOptions);

            // change the block's template to the stripped down ESI template
            switch ($esiOptions[$methodParam]) {
                case 'ajax':
                    $blockObject->setTemplate('turpentine/ajax.phtml');
                    break;

                case 'esi':
                default:
                    $blockObject->setTemplate('turpentine/esi.phtml');
                    // flag request for ESI processing
                    Mage::register('turpentine_esi_flag', true, true);
            }

            // esi data is the data needed to regenerate the ESI'd block
            $esiData = $this->_getEsiData($blockObject, $esiOptions)->toArray();
            ksort($esiData);
            $frozenData = $dataHelper->freeze($esiData);
            $urlOptions = array(
                $methodParam    => $esiOptions[$methodParam],
                $cacheTypeParam => $esiOptions[$cacheTypeParam],
                $ttlParam       => $esiOptions[$ttlParam],
                $hmacParam      => $dataHelper->getHmac($frozenData),
                $dataParam      => $frozenData,
            );
            if ($esiOptions[$methodParam] == 'ajax') {
                $urlOptions['_secure'] = Mage::app()->getStore()
                    ->isCurrentlySecure();
            }
            if ($esiOptions[$scopeParam] == 'page') {
                $urlOptions[$referrerParam] = Mage::helper('core')->urlEncode(
                    Mage::getUrl('*/*/*', array('_use_rewrite' => true, '_current' => true))
                );
            }

            /**
             * Keep params from original url
             */
            $urlOptions['_query'] = Mage::app()->getRequest()->getParams();
            
            $esiUrl = Mage::getUrl('turpentine/esi/getBlock', $urlOptions);
            if ($esiOptions[$methodParam] == 'esi') {
                // setting [web/unsecure/base_url] can be https://... but ESI can never be HTTPS
                $esiUrl = preg_replace('|^https://|i', 'http://', $esiUrl);
            }
            $blockObject->setEsiUrl($esiUrl);
            // avoid caching the ESI template output to prevent the double-esi-
            // include/"ESI processing not enabled" bug
            foreach (array('lifetime', 'tags', 'key') as $dataKey) {
                $blockObject->unsetData('cache_'.$dataKey);
            }
            if (strlen($esiUrl) > 2047) {
                Mage::helper('turpentine/debug')->logWarn(
                    'ESI url is probably too long (%d > 2047 characters): %s',
                    strlen($esiUrl), $esiUrl );
            }
            Varien_Profiler::stop('turpentine::observer::esi::injectEsi');
        } // else handle the block like normal and cache it inline with the page
    }
422503
public function controllerActionLayoutLoadBefore(Varien_Event_Observer $observer)
    {
        if (!$this->_getHelper()->isActive()) {
            return;
        }
        
        $updateModel = $observer->getLayout()->getUpdate();
        $handles = $updateModel->getHandles();
        $allowedEsi = $this->_getHelper()->getIsEsiAllowed();
        foreach ($handles as $handle) {
            if ($handle == 'customer_logged_in' 
                && !$this->_getHelper()->getIsInternal()) {
                $updateModel->removeHandle($handle);
                // Emulate always guest session
                $updateModel->addHandle('customer_logged_out');
            }
            
            if ($handle == 'default' && !$this->_getHelper()->getIsInternal()) {
                $updateModel->addHandle('default_varnish');
            }
            
            if ($allowedEsi && strtolower($handle) === $handle) {
                // Add handle only if handle is not starting from UPPERCASE code
                $updateModel->addHandle($handle . '_esi');
            }
        }
    }
458927
public function keyChanged(PersistenceEvent $event) {
    $object = $event->getObject();
    if ($object->getType() == $this->entityType) {
      $cache = ObjectFactory::getInstance('dynamicCache');
      $cache->clear($this->getId());
    }
  }
492005
public function unserialize($serializedObject)
    {
        $objectVars = unserialize($serializedObject);

        foreach ($objectVars as $key => $value) {
            $this->{$key} = $value;
        }
    }
916672
public function setHeaders(EventInterface $event) {
        $method = $event->getRequest()->getMethod();

        // Obviously we shouldn't bother doing any HTTP caching logic for non-GET/HEAD requests
        if ($method !== 'GET' && $method !== 'HEAD') {
            return;
        }

        $response = $event->getResponse();
        $headers = $event->getResponse()->headers;

        // Imbo defaults to 'public' as cache-control value - if it has changed from this value,
        // assume the resource requested has explicitly defined its own caching rules and fall back
        if ($headers->get('Cache-Control') !== 'public') {
            return;
        }

        // Get configured HTTP cache defaults from configuration, then apply them
        $config = $event->getConfig()['httpCacheHeaders'];

        if (isset($config['maxAge'])) {
            $response->setMaxAge((int) $config['maxAge']);
        }

        if (isset($config['sharedMaxAge'])) {
            $response->setSharedMaxAge($config['sharedMaxAge']);
        }

        if (isset($config['public']) && $config['public']) {
            $response->setPublic();
        } else if (isset($config['public'])) {
            $response->setPrivate();
        }

        if (isset($config['mustRevalidate']) && $config['mustRevalidate']) {
            $headers->addCacheControlDirective('must-revalidate');
        }
    }
485711
protected function setDomainObjectInProperty($object, $propertyName, $domainObject, $lastObject, array $objectArrayPropertyPath)
    {
        if (is_object($object)) {
            ObjectAccess::setProperty($object, $propertyName, $domainObject);
        } elseif (is_array($object)) {
            $this->injectDomainObjectInLastObject($domainObject, $lastObject, $objectArrayPropertyPath);
        }
    }
1088466
protected function refreshConfigurationValidationResult(ConfigurationObjectInstance $configurationObject)
    {
        $result = new Result;
        $formzConfigurationValidationResult = $this->configurationFactory
            ->getFormzConfiguration()
            ->getValidationResult();

        $result->merge($formzConfigurationValidationResult);

        $result->forProperty('forms.' . $this->formObject->getClassName())
            ->merge($configurationObject->getValidationResult());

        return $result;
    }
835573
public function dispatch($event, Event $eventObject)
    {
        if (!isset($this->listeners[$event])) {
            return;
        }
        
        foreach ($this->listeners[$event] as $listener) {
            call_user_func_array($listener, array($eventObject));
            
            if ($eventObject->propagationHalted()) {
                break;
            }
        }
    }