Ejemplo n.º 1
0
 /**
  * @param InputInterface  $input
  * @param OutputInterface $output
  *
  * @return int|void
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $this->detectMagento($output, true);
     $noReinitOption = $input->getOption('no-reinit');
     if (!$noReinitOption) {
         $this->banUseCache();
     }
     if (!$this->initMagento()) {
         return;
     }
     \Mage::app()->loadAreaPart('adminhtml', 'events');
     \Mage::dispatchEvent('adminhtml_cache_flush_all', array('output' => $output));
     $result = \Mage::app()->getCacheInstance()->flush();
     if ($result) {
         $output->writeln('<info>Cache cleared</info>');
     } else {
         $output->writeln('<error>Failed to clear Cache</error>');
     }
     if (!$noReinitOption) {
         $this->reinitCache();
     }
     /* Since Magento 1.10 we have an own cache handler for FPC */
     if ($this->isEnterpriseFullPageCachePresent()) {
         $result = \Enterprise_PageCache_Model_Cache::getCacheInstance()->flush();
         if ($result) {
             $output->writeln('<info>FPC cleared</info>');
         } else {
             $output->writeln('<error>Failed to clear FPC</error>');
         }
     }
 }
Ejemplo n.º 2
0
 /**
  * Class constructor
  */
 public function __construct(array $args = array())
 {
     $this->_processor = isset($args['processor']) ? $args['processor'] : Mage::getSingleton('enterprise_pagecache/processor');
     $this->_config = isset($args['config']) ? $args['config'] : Mage::getSingleton('enterprise_pagecache/config');
     $this->_isEnabled = isset($args['enabled']) ? $args['enabled'] : Mage::app()->useCache('full_page');
     $this->_cacheInstance = isset($args['cacheInstance']) ? $args['cacheInstance'] : Enterprise_PageCache_Model_Cache::getCacheInstance();
 }
 /**
  * Request processing action
  */
 public function processAction()
 {
     $processor = Mage::getSingleton('enterprise_pagecache/processor');
     $content = Mage::registry('cached_page_content');
     $containers = Mage::registry('cached_page_containers');
     $cacheInstance = Enterprise_PageCache_Model_Cache::getCacheInstance();
     foreach ($containers as $container) {
         $container->applyInApp($content);
     }
     $this->getResponse()->appendBody($content);
     // save session cookie lifetime info
     $cacheId = $processor->getSessionInfoCacheId();
     $sessionInfo = $cacheInstance->load($cacheId);
     if ($sessionInfo) {
         $sessionInfo = unserialize($sessionInfo);
     } else {
         $sessionInfo = array();
     }
     $session = Mage::getSingleton('core/session');
     $cookieName = $session->getSessionName();
     $cookieInfo = array('lifetime' => $session->getCookie()->getLifetime(), 'path' => $session->getCookie()->getPath(), 'domain' => $session->getCookie()->getDomain(), 'secure' => $session->getCookie()->isSecure(), 'httponly' => $session->getCookie()->getHttponly());
     if (!isset($sessionInfo[$cookieName]) || $sessionInfo[$cookieName] != $cookieInfo) {
         $sessionInfo[$cookieName] = $cookieInfo;
         // customer cookies have to be refreshed as well as the session cookie
         $sessionInfo[Enterprise_PageCache_Model_Cookie::COOKIE_CUSTOMER] = $cookieInfo;
         $sessionInfo[Enterprise_PageCache_Model_Cookie::COOKIE_CUSTOMER_GROUP] = $cookieInfo;
         $sessionInfo[Enterprise_PageCache_Model_Cookie::COOKIE_CUSTOMER_LOGGED_IN] = $cookieInfo;
         $sessionInfo[Enterprise_PageCache_Model_Cookie::CUSTOMER_SEGMENT_IDS] = $cookieInfo;
         $sessionInfo[Enterprise_PageCache_Model_Cookie::COOKIE_MESSAGE] = $cookieInfo;
         $sessionInfo = serialize($sessionInfo);
         $cacheInstance->save($sessionInfo, $cacheId, array(Enterprise_PageCache_Model_Processor::CACHE_TAG));
     }
 }
 /**
  * Saves informational cache, containing parameters used to show poll.
  *
  * @param array $renderedParams
  * @return Enterprise_PageCache_Model_Container_Sidebar_Poll
  */
 protected function _saveInfoCache($renderedParams)
 {
     $data = serialize($renderedParams);
     $id = $this->_getInfoCacheId();
     $tags = array(Enterprise_PageCache_Model_Processor::CACHE_TAG);
     Enterprise_PageCache_Model_Cache::getCacheInstance()->save($data, $id, $tags);
     return $this;
 }
 /**
  * Render block HTML
  *
  * @return string
  */
 protected function _toHtml()
 {
     $configHelper = $this->getConfigHelper();
     // Module disabled
     if (!$configHelper->extensionEnabled()) {
         return '';
     }
     if (Mage::getEdition() === Mage::EDITION_ENTERPRISE) {
         // Recreate the widget parameter cache on FPC cleared or just created
         if (!$this->getFullPageCacheEnvironment() && $this->getUniqueId()) {
             $id = RapidCampaign_Promotions_Model_Fpc_Placeholder::CACHE_PREFIX . $this->getUniqueId() . '_params';
             Enterprise_PageCache_Model_Cache::getCacheInstance()->save(serialize($this->getData()), $id);
         }
     }
     if (!$this->validateRules()) {
         return '';
     }
     /** @var RapidCampaign_Promotions_Model_Storage $promotionsStorage */
     $promotionsStorage = Mage::getModel('rapidcampaign_promotions/storage');
     try {
         $promotionModel = $promotionsStorage->getPromotionsModel();
     } catch (Exception $e) {
         $promotionModel = $promotionsStorage->getCachedPromotionsModel();
     }
     $promotion = $promotionModel->load($this->getData('promotion'));
     // Promotion does not exist
     if ($promotion->isEmpty()) {
         return '';
     }
     $urlParams = $this->getUrlParams($promotion);
     $promotionData = $promotion->getData();
     $iframeUrl = $promotionData['embed_url'] . '?' . http_build_query($urlParams);
     $iframeWidth = $promotionData['width'] ?: self::IFRAME_WIDTH;
     $iframeHeight = $promotionData['height'] ?: self::IFRAME_HEIGHT;
     if ($configHelper->testModeEnabled()) {
         $embedScript = self::IFRAME_JS_TEST_BASE_URL;
     } else {
         $embedScript = self::IFRAME_JS_BASE_URL;
     }
     $isModalEnabled = $this->getData('modal_enabled');
     $hideDiv = $isModalEnabled ? "display:none" : "";
     if (preg_match('/sales/i', $promotionData['promotion_category'])) {
         $embedScript .= self::IFRAME_SALES_EMBED;
         $iframeString = sprintf('<div class="_rc_iframe %s" style="%s" data-url="%s" data-width="%s" data-height="%s"></div>', $this->getIframeClass($this->getUniqueId()), $hideDiv, $iframeUrl, $iframeWidth, $iframeHeight);
     } else {
         $embedScript .= self::IFRAME_MARKETING_EMBED;
         $iframeString = sprintf('<div class="_rc_miframe %s" style="%s" data-url="%s"></div>', $this->getIframeClass($this->getUniqueId()), $hideDiv, $iframeUrl);
     }
     $jsString = sprintf('<script type="text/javascript" src="%s"></script>', $embedScript);
     $html = $iframeString . $jsString;
     if ($isModalEnabled) {
         $html .= $this->getPromotionModalJs($promotion);
     }
     return $html;
 }
 /**
  * Set cart hash in cookie on quote change
  *
  * @param Varien_Event_Observer $observer
  * @return Enterprise_PageCache_Model_Observer
  */
 public function registerQuoteChange(Varien_Event_Observer $observer)
 {
     if (!$this->isCacheEnabled()) {
         return $this;
     }
     try {
         $cacheId = TriggeredMessaging_DigitalDataLayer_Model_Container_Ddl::getCacheId();
         Enterprise_PageCache_Model_Cache::getCacheInstance()->remove($cacheId);
     } catch (Exception $e) {
     }
     return $this;
 }
 /**
  * Retrieve encryption salt
  *
  * @return null|sting
  */
 protected function _getSalt()
 {
     if ($this->_salt === null) {
         $saltCacheId = 'full_page_cache_key';
         $this->_salt = Enterprise_PageCache_Model_Cache::getCacheInstance()->load($saltCacheId);
         if (!$this->_salt) {
             $this->_salt = md5(microtime() . rand());
             Enterprise_PageCache_Model_Cache::getCacheInstance()->save($this->_salt, $saltCacheId, array(Enterprise_PageCache_Model_Processor::CACHE_TAG));
         }
     }
     return $this->_salt;
 }
Ejemplo n.º 8
0
 /**
  * Saves informational cache, containing parameters used to show banners.
  * We don't use _saveCache() method internally, because it replaces sid in cache, that can be done only
  * after app is started, while this method can be called without app after rendering serie/shuffle banners.
  *
  * @param array $renderedParams
  * @return Enterprise_PageCache_Model_Container_Banner
  */
 protected function _saveInfoCache($renderedParams)
 {
     $data = serialize($renderedParams);
     $id = $this->_getInfoCacheId();
     $tags = array(Enterprise_PageCache_Model_Processor::CACHE_TAG);
     $lifetime = $this->_placeholder->getAttribute('cache_lifetime');
     if (!$lifetime) {
         $lifetime = false;
     }
     Enterprise_PageCache_Model_Cache::getCacheInstance()->save($data, $id, $tags, $lifetime);
     return $this;
 }
Ejemplo n.º 9
0
 /**
  * Clean old cache entries.
  * This method will be called via a Magento crontab task.
  *
  * @param void
  * @return void
  */
 public function clean()
 {
     $startTime = time();
     Mage::app()->getCache()->clean(Zend_Cache::CLEANING_MODE_OLD);
     $duration = time() - $startTime;
     Mage::log('[CACHECLEANER] Cleaning cache (duration: ' . $duration . ')');
     if (Mage::helper('core')->isModuleEnabled('Enterprise_PageCache')) {
         $startTime = time();
         Enterprise_PageCache_Model_Cache::getCacheInstance()->getFrontend()->getBackend()->clean(Zend_Cache::CLEANING_MODE_OLD);
         $duration = time() - $startTime;
         Mage::log('[CACHECLEANER] Cleaning full page cache (duration: ' . $duration . ')');
     }
 }
 /**
  * Render block content from placeholder
  *
  * @return false|string
  */
 protected function _renderBlock()
 {
     $block = $this->_getPlaceHolderBlock();
     // Set block parameters
     $id = $this->_getCacheId() . '_params';
     if ($parameters = Enterprise_PageCache_Model_Cache::getCacheInstance()->load($id)) {
         $block->addData(unserialize($parameters));
         // Set environment information on block
         $block->setFullPageCacheEnvironment(true);
     }
     Mage::dispatchEvent('render_block', array('block' => $block, 'placeholder' => $this->_placeholder));
     return $block->toHtml();
 }
Ejemplo n.º 11
0
 /**
  * @param $page Mage_Cms_Model_Page
  */
 protected function _clearCache($page)
 {
     $session = Mage::getSingleton('adminhtml/session');
     /** @var Varien_Simplexml_Element $varnishModelConfig */
     $varnishModelConfig = Mage::getConfig()->getModuleConfig('MageStack_Varnish');
     if ((string) $varnishModelConfig->active == 'true') {
         Mage::helper('varnish')->purge(array($this->_getRelativeUrl($page)));
         $session->addSuccess("Cleared Varnish for URL: " . $this->_getRelativeUrl($page));
     }
     $cacheTag = 'cms_page_' . $page->getId();
     $cacheInstance = Enterprise_PageCache_Model_Cache::getCacheInstance();
     $cacheInstance->clean(array($cacheTag));
     $session->addSuccess("Cleared FPC for: " . $cacheTag);
     return $this;
 }
Ejemplo n.º 12
0
 /**
  * @param \Symfony\Component\Console\Input\InputInterface $input
  * @param \Symfony\Component\Console\Output\OutputInterface $output
  * @return int|void
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $this->detectMagento($output, true);
     if ($this->initMagento()) {
         \Mage::app()->loadAreaPart('adminhtml', 'events');
         \Mage::dispatchEvent('adminhtml_cache_flush_all', array('output' => $output));
         \Mage::app()->getCacheInstance()->flush();
         $output->writeln('<info>Cache cleared</info>');
         /* Since Magento 1.10 we have an own cache handler for FPC */
         if ($this->_magentoEnterprise && version_compare(\Mage::getVersion(), '1.11.0.0', '>=')) {
             \Enterprise_PageCache_Model_Cache::getCacheInstance()->flush();
             $output->writeln('<info>FPC cleared</info>');
         }
     }
 }
Ejemplo n.º 13
0
 /**
  * Clean Cache
  *
  * @param Pimgento_Core_Model_Task $task
  *
  * @return bool
  */
 public function cleanCache($task)
 {
     $tags = $this->getConfig('cache');
     if ($tags) {
         Mage::app()->cleanCache(explode(',', $tags));
         if (strpos($tags, 'full_page') && $this->isEnterprise()) {
             Enterprise_PageCache_Model_Cache::getCacheInstance()->clean(Enterprise_PageCache_Model_Processor::CACHE_TAG);
             Mage::app()->getCacheInstance()->cleanType('full_page');
         }
         $task->setMessage(Mage::helper('pimgento_core')->__('Cache cleaned for: %s', $tags));
     } else {
         $task->setMessage(Mage::helper('pimgento_core')->__('No cache cleaned'));
     }
     return true;
 }
Ejemplo n.º 14
0
 /**
  * @param InputInterface $input
  * @param OutputInterface $output
  * @throws \RuntimeException
  * @return int|void
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $this->detectContao($output, true);
     if ($this->initContao()) {
         if ($input->hasOption('fpc') && $input->getOption('fpc')) {
             if (!class_exists('\\Enterprise_PageCache_Model_Cache')) {
                 throw new \RuntimeException('Enterprise page cache not found');
             }
             $cacheInstance = \Enterprise_PageCache_Model_Cache::getCacheInstance()->getFrontend();
         } else {
             $cacheInstance = \Mage::app()->getCache();
         }
         /* @var $cacheInstance \Varien_Cache_Core */
         $cacheIds = $cacheInstance->getIds();
         $table = array();
         foreach ($cacheIds as $cacheId) {
             if ($input->getOption('filter-id') !== null) {
                 if (!stristr($cacheId, $input->getOption('filter-id'))) {
                     continue;
                 }
             }
             $metaData = $cacheInstance->getMetadatas($cacheId);
             if ($input->getOption('filter-tag') !== null) {
                 if (count(array_intersect($metaData['tags'], explode(',', $input->getOption('filter-tag')))) <= 0) {
                     continue;
                 }
             }
             $row = array($cacheId, date('Y-m-d H:i:s', $metaData['expire']));
             if ($input->getOption('mtime')) {
                 $row[] = date('Y-m-d H:i:s', $metaData['mtime']);
             }
             if ($input->getOption('tags')) {
                 $row[] = implode(',', $metaData['tags']);
             }
             $table[] = $row;
         }
         $headers = array('ID', 'EXPIRE');
         if ($input->getOption('mtime')) {
             $headers[] = 'MTIME';
         }
         if ($input->getOption('tags')) {
             $headers[] = 'TAGS';
         }
         $this->getHelper('table')->setHeaders($headers)->renderByFormat($output, $table, $input->getOption('format'));
     }
 }
Ejemplo n.º 15
0
 /**
  * Cache instance static getter
  *
  * @return Mage_Core_Model_Cache
  */
 public static function getCacheInstance()
 {
     if (is_null(self::$_cache)) {
         $options = Mage::app()->getConfig()->getNode('global/full_page_cache');
         if (!$options) {
             self::$_cache = Mage::app()->getCacheInstance();
             return self::$_cache;
         }
         $options = $options->asArray();
         foreach (array('backend_options', 'slow_backend_options') as $tag) {
             if (!empty($options[$tag]['cache_dir'])) {
                 $options[$tag]['cache_dir'] = Mage::getBaseDir('var') . DS . $options[$tag]['cache_dir'];
                 Mage::app()->getConfig()->getOptions()->createDirIfNotExists($options[$tag]['cache_dir']);
             }
         }
         self::$_cache = Mage::getModel('core/cache', $options);
     }
     return self::$_cache;
 }
Ejemplo n.º 16
0
 /**
  * @param InputInterface $input
  * @param OutputInterface $output
  * @throws \RuntimeException
  * @return int|void
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $this->detectMagento($output, true);
     if ($this->initMagento()) {
         if ($input->hasOption('fpc') && $input->getOption('fpc')) {
             if (!class_exists('\\Enterprise_PageCache_Model_Cache')) {
                 throw new \RuntimeException('Enterprise page cache not found');
             }
             $cacheInstance = \Enterprise_PageCache_Model_Cache::getCacheInstance()->getFrontend();
         } else {
             $cacheInstance = \Mage::app()->getCache();
         }
         /* @var $cacheInstance \Varien_Cache_Core */
         $cacheData = $cacheInstance->load($input->getArgument('id'));
         if ($input->getOption('unserialize')) {
             $cacheData = unserialize($cacheData);
             $cacheData = print_r($cacheData, true);
         }
         $output->writeln($cacheData);
     }
 }
 /**
  * Prepare response body before caching
  *
  * @param Zend_Controller_Response_Http $response
  * @return string
  */
 public function prepareContent(Zend_Controller_Response_Http $response)
 {
     $cacheInstance = Enterprise_PageCache_Model_Cache::getCacheInstance();
     /** @var Enterprise_PageCache_Model_Processor */
     $processor = Mage::getSingleton('enterprise_pagecache/processor');
     $countLimit = Mage::getStoreConfig(Mage_Reports_Block_Product_Viewed::XML_PATH_RECENTLY_VIEWED_COUNT);
     // save recently viewed product count limit
     $cacheId = $processor->getRecentlyViewedCountCacheId();
     if (!$cacheInstance->getFrontend()->test($cacheId)) {
         $cacheInstance->save($countLimit, $cacheId, array(Enterprise_PageCache_Model_Processor::CACHE_TAG));
     }
     // save current product id
     $product = Mage::registry('current_product');
     if ($product) {
         $cacheId = $processor->getRequestCacheId() . '_current_product_id';
         $cacheInstance->save($product->getId(), $cacheId, array(Enterprise_PageCache_Model_Processor::CACHE_TAG));
         $processor->setMetadata(self::METADATA_PRODUCT_ID, $product->getId());
         Enterprise_PageCache_Model_Cookie::registerViewedProducts($product->getId(), $countLimit);
     }
     return parent::prepareContent($response);
 }
Ejemplo n.º 18
0
 /**
  * Refreshes caches for the provided cache types.
  *
  * @param  $types
  * @return void
  */
 public function refresh($types)
 {
     $updatedTypes = 0;
     if (!empty($types)) {
         foreach ($types as $type) {
             try {
                 if ($type == 'full_page') {
                     Enterprise_PageCache_Model_Cache::getCacheInstance()
                         ->clean(Enterprise_PageCache_Model_Processor::CACHE_TAG);
                 } else {
                     Mage::app()->getCacheInstance()->cleanType($type);
                 }
                 $updatedTypes++;
             } catch (Exception $e) {
                 echo $type . " cache unknown error:\n";
                 echo $e . "\n";
             }
         }
     }
     if ($updatedTypes > 0) {
         echo "$updatedTypes cache type(s) refreshed.\n";
     }
 }
Ejemplo n.º 19
0
 /**
  * Replace the config entry with search engine when enabling the module
  *
  * @param Varien_Object $observer
  *
  * @return void
  */
 public function setSearchEngine($observer)
 {
     $request = $observer->getControllerAction()->getRequest();
     if ($request->getParam('section') != 'factfinder') {
         return;
     }
     $groups = $request->getPost('groups');
     $website = $request->getParam('website');
     $store = $request->getParam('store');
     if (is_array($groups['search']) && is_array($groups['search']['fields']) && is_array($groups['search']['fields']['enabled']) && isset($groups['search']['fields']['enabled']['value'])) {
         $value = $groups['search']['fields']['enabled']['value'];
     } elseif ($store) {
         $value = Mage::app()->getWebsite($website)->getConfig('factfinder/search/enabled');
     } else {
         $value = (string) Mage::getConfig()->getNode('default/factfinder/search/enabled');
     }
     if (empty($value)) {
         Mage::app()->getConfig()->saveConfig('catalog/search/engine', self::DEFAULT_SEARCH_ENGINE);
         return;
     }
     $errors = Mage::helper('factfinder/backend')->checkConfigData($groups['search']['fields']);
     if (!empty($errors)) {
         foreach ($errors as $error) {
             Mage::getSingleton('adminhtml/session')->addError($error);
         }
         Mage::app()->getConfig()->saveConfig('catalog/search/engine', self::DEFAULT_SEARCH_ENGINE);
         Mage::app()->getConfig()->saveConfig('factfinder/search/enabled', 0);
     } else {
         Mage::app()->getConfig()->saveConfig('catalog/search/engine', self::SEARCH_ENGINE);
     }
     // this also helps with module managing
     Mage::app()->cleanCache();
     if (Mage::helper('core')->isModuleEnabled('Enterprise_PageCache')) {
         Enterprise_PageCache_Model_Cache::getCacheInstance()->clean(Enterprise_PageCache_Model_Processor::CACHE_TAG);
     }
 }
 /**
  * Save data to cache storage. Store many block instances in one cache record depending on additional cache ids.
  *
  * @param string $data
  * @param string $id
  * @param array $tags
  * @param null|int $lifetime
  * @return Enterprise_PageCache_Model_Container_Advanced_Abstract
  */
 protected function _saveCache($data, $id, $tags = array(), $lifetime = null)
 {
     $additionalCacheId = $this->_getAdditionalCacheId();
     if (!$additionalCacheId) {
         Mage::throwException(Mage::helper('enterprise_pagecache')->__('Additional id should not be empty'));
     }
     $tags[] = Enterprise_PageCache_Model_Processor::CACHE_TAG;
     $tags = array_merge($tags, $this->_getPlaceHolderBlock()->getCacheTags());
     if (is_null($lifetime)) {
         $lifetime = $this->_placeholder->getAttribute('cache_lifetime') ? $this->_placeholder->getAttribute('cache_lifetime') : false;
     }
     Enterprise_PageCache_Helper_Data::prepareContentPlaceholders($data);
     $result = array();
     $cacheRecord = parent::_loadCache($id);
     if ($cacheRecord) {
         $cacheRecord = json_decode($cacheRecord, true);
         if ($cacheRecord) {
             $result = $cacheRecord;
         }
     }
     $result[$additionalCacheId] = $data;
     Enterprise_PageCache_Model_Cache::getCacheInstance()->save(json_encode($result), $id, $tags, $lifetime);
     return $this;
 }
 /**
  * Clear request path cache by tag
  * (used for redirects invalidation)
  *
  * @param Varien_Event_Observer $observer
  * @return $this
  */
 public function clearRequestCacheByTag(Varien_Event_Observer $observer)
 {
     if (!$this->isCacheEnabled()) {
         return $this;
     }
     $redirect = $observer->getEvent()->getRedirect();
     Enterprise_PageCache_Model_Cache::getCacheInstance()->clean(array(Enterprise_PageCache_Helper_Url::prepareRequestPathTag($redirect->getData('identifier')), Enterprise_PageCache_Helper_Url::prepareRequestPathTag($redirect->getData('target_path')), Enterprise_PageCache_Helper_Url::prepareRequestPathTag($redirect->getOrigData('identifier')), Enterprise_PageCache_Helper_Url::prepareRequestPathTag($redirect->getOrigData('target_path'))));
     return $this;
 }
<?php

$mageFilename = 'app/Mage.php';
require_once $mageFilename;
umask(0);
Mage::app('admin');
try {
    Mage::app()->cleanAllSessions();
    Mage::app()->getCacheInstance()->flush();
    Mage::app()->cleanCache();
    $allTypes = Mage::app()->useCache();
    foreach ($allTypes as $type => $blah) {
        Mage::app()->getCacheInstance()->cleanType($type);
    }
} catch (Exception $e) {
    // do something
    error_log($e->getMessage());
}
# make this last in case we aren't using EE, it will error (but ok)
try {
    # UI fires this event, but cmdline doesn't
    Enterprise_PageCache_Model_Cache::getCacheInstance()->clean(Enterprise_PageCache_Model_Processor::CACHE_TAG);
} catch (Exception $e) {
}
# eat silently
echo "Caches flushed\n";
 /**
  * Render block HTML
  *
  * @return string
  */
 protected function _toHtml()
 {
     /** @var RapidCampaign_Promotions_Helper_Config $configHelper */
     $configHelper = Mage::helper('rapidcampaign_promotions/config');
     // Module disabled
     if (!$configHelper->extensionEnabled()) {
         return '';
     }
     if (Mage::getEdition() === Mage::EDITION_ENTERPRISE) {
         // Recreate the widget parameter cache on FPC cleared or just created
         if (!$this->getFullPageCacheEnvironment() && $this->getUniqueId()) {
             $id = RapidCampaign_Promotions_Model_Fpc_Placeholder::CACHE_PREFIX . $this->getUniqueId() . '_params';
             Enterprise_PageCache_Model_Cache::getCacheInstance()->save(serialize($this->getData()), $id);
         }
     }
     // The rules not valid
     if (!$this->validateRules()) {
         return '';
     }
     /** @var RapidCampaign_Promotions_Model_Storage $promotionsStorage */
     $promotionsStorage = Mage::getModel('rapidcampaign_promotions/storage');
     try {
         $promotionModel = $promotionsStorage->getPromotionsModel();
     } catch (Exception $e) {
         $promotionModel = $promotionsStorage->getCachedPromotionsModel();
     }
     $promotion = $promotionModel->load($this->getData('promotion'));
     // Promotion does not exist
     if ($promotion->isEmpty()) {
         return '';
     }
     $promotionData = $promotion->getData();
     /** @var Mage_Customer_Model_Session $sessionModel */
     $sessionModel = Mage::getSingleton('customer/session');
     $urlParams = array('promo_id' => $promotionData['slug'], 'customer_group' => $sessionModel->getCustomerGroupId(), 'cart_value' => $this->getCartTotal());
     if ($sessionModel->isLoggedIn()) {
         $customer = $sessionModel->getCustomer();
         if ($customer->getFirstname()) {
             $urlParams['first_name'] = $customer->getFirstname();
         }
         if ($customer->getLastname()) {
             $urlParams['last_name'] = $customer->getLastname();
         }
     }
     // Parameter encryption enabled
     if ($configHelper->encryptionEnabled()) {
         $urlParams = $this->encryptParameters($urlParams);
     }
     $iframeUrl = $promotionData['embed_url'] . '?' . http_build_query($urlParams);
     $iframeWidth = $promotionData['width'] ?: self::IFRAME_WIDTH;
     $iframeHeight = $promotionData['height'] ?: self::IFRAME_HEIGHT;
     if ($configHelper->testModeEnabled()) {
         $embedScript = self::IFRAME_JS_TEST_BASE_URL;
     } else {
         $embedScript = self::IFRAME_JS_BASE_URL;
     }
     if (preg_match('/sales/i', $promotionData['promotion_category'])) {
         $embedScript .= self::IFRAME_SALES_EMBED;
         $iframeString = sprintf('<div class="_rc_iframe" data-url="%s" data-width="%s" data-height="%s"></div>', $iframeUrl, $iframeWidth, $iframeHeight);
     } else {
         $embedScript .= self::IFRAME_MARKETING_EMBED;
         $iframeString = sprintf('<div class="_rc_miframe" data-url="%s"></div>', $iframeUrl);
     }
     $jsString = sprintf('<script type="text/javascript" src="%s"></script>', $embedScript);
     return $iframeString . $jsString;
 }
Ejemplo n.º 24
0
 /**
  * Load cache metadata from storage
  */
 protected function _loadMetadata()
 {
     if ($this->_metaData === null) {
         $cacheMetadata = Enterprise_PageCache_Model_Cache::getCacheInstance()->load($this->getRequestCacheId() . self::METADATA_CACHE_SUFFIX);
         if ($cacheMetadata) {
             $cacheMetadata = unserialize($cacheMetadata);
         }
         $this->_metaData = empty($cacheMetadata) || !is_array($cacheMetadata) ? array() : $cacheMetadata;
     }
 }
 /**
  * Save cache info for items list, for randomizing
  *
  * @return Enterprise_PageCache_Model_Container_CatalogProductItem
  */
 protected function _prepareListItems()
 {
     $data = array();
     $cacheRecord = Enterprise_PageCache_Model_Container_Abstract::_loadCache($this->_getCacheId());
     if ($cacheRecord) {
         $cacheRecord = json_decode($cacheRecord, true);
         if ($cacheRecord) {
             $data = $cacheRecord;
         }
     }
     $data[$this->_getInfoCacheId()]['ids'] = $this->_getParentBlock()->getAllIds();
     $data[$this->_getInfoCacheId()]['shuffle'] = $this->_getParentBlock()->isShuffled();
     $data = json_encode($data);
     $tags = array(Enterprise_PageCache_Model_Processor::CACHE_TAG);
     $lifetime = $this->_placeholder->getAttribute('cache_lifetime');
     if (!$lifetime) {
         $lifetime = false;
     }
     Enterprise_PageCache_Model_Cache::getCacheInstance()->save($data, $this->_getCacheId(), $tags, $lifetime);
     return $this;
 }
Ejemplo n.º 26
0
 /**
  * Resave exception rules to cache storage
  *
  * @param Varien_Event_Observer $observer
  * @return Enterprise_PageCache_Model_Observer
  */
 public function registerDesignExceptionsChange(Varien_Event_Observer $observer)
 {
     $object = $observer->getDataObject();
     Enterprise_PageCache_Model_Cache::getCacheInstance()->save($object->getValue(), Enterprise_PageCache_Model_Processor::DESIGN_EXCEPTION_KEY, array(Enterprise_PageCache_Model_Processor::CACHE_TAG));
     return $this;
 }
Ejemplo n.º 27
0
 /**
  * Get shared info param
  *
  * @param string|null $key
  * @return mixed
  */
 protected function _getSharedParam($key = null)
 {
     $placeholderName = $this->_placeholder->getName();
     $info = self::$_sharedInfoData[$placeholderName]['info'];
     if (is_null($info)) {
         $info = array();
         $cacheRecord = Enterprise_PageCache_Model_Cache::getCacheInstance()->load($this->_getCacheId());
         if ($cacheRecord) {
             $cacheRecord = json_decode($cacheRecord, true);
             if ($cacheRecord && array_key_exists($this->_getInfoCacheId(), $cacheRecord)) {
                 $info = $cacheRecord[$this->_getInfoCacheId()];
             }
         }
         self::$_sharedInfoData[$placeholderName]['info'] = $info;
     }
     return isset($key) ? isset($info[$key]) ? $info[$key] : null : $info;
 }
Ejemplo n.º 28
0
 /**
  * clearEntityCache
  *
  * @param Mage_Core_Model_Abstract $entity
  * @param array $ids
  * @return void
  */
 public function clearEntityCache(Mage_Core_Model_Abstract $entity, array $ids)
 {
     $cacheTags = array();
     foreach ($ids as $entityId) {
         $entity->setId($entityId);
         $cacheTags = array_merge($cacheTags, $entity->getCacheIdTags());
     }
     if (!empty($cacheTags)) {
         Enterprise_PageCache_Model_Cache::getCacheInstance()->clean($cacheTags);
     }
 }
Ejemplo n.º 29
0
 /**
  * Save data to cache storage
  *
  * @param string $data
  * @param string $id
  * @param array $tags
  * @param null|int $lifetime
  * @return Enterprise_PageCache_Model_Container_Abstract
  */
 protected function _saveCache($data, $id, $tags = array(), $lifetime = null)
 {
     $tags[] = Enterprise_PageCache_Model_Processor::CACHE_TAG;
     if (is_null($lifetime)) {
         $lifetime = $this->_placeholder->getAttribute('cache_lifetime') ? $this->_placeholder->getAttribute('cache_lifetime') : false;
     }
     /**
      * Replace all occurrences of session_id with unique marker
      */
     Enterprise_PageCache_Helper_Url::replaceSid($data);
     Enterprise_PageCache_Model_Cache::getCacheInstance()->save($data, $id, $tags, $lifetime);
     return $this;
 }
 /**
  * Save rendered block content to cache storage
  *
  * @param string $blockContent
  * @param array $tags
  * @return Enterprise_PageCache_Model_Container_Abstract
  */
 public function saveCache($blockContent, $tags = array())
 {
     $blockCacheId = $this->_getBlockCacheId();
     if ($blockCacheId) {
         $categoryCacheId = $this->_getCategoryCacheId();
         if ($categoryCacheId) {
             $categoryUniqueClasses = '';
             $classes = array();
             $classesCount = preg_match_all('/< *li[^>]*class *= *["\']?([^"\']*)/i', $blockContent, $classes);
             for ($i = 0; $i < $classesCount; $i++) {
                 $classAttribute = $classes[0][$i];
                 $classValue = $classes[1][$i];
                 if (false === strpos($classAttribute, 'active')) {
                     continue;
                 }
                 $classInactive = preg_replace('/\\s+active|active\\s+|active/', '', $classAttribute);
                 $blockContent = str_replace($classAttribute, $classInactive, $blockContent);
                 $matches = array();
                 if (preg_match('/(?<=\\s|^)nav-.+?(?=\\s|$)/', $classValue, $matches)) {
                     $categoryUniqueClasses .= ($categoryUniqueClasses ? ' ' : '') . $matches[0];
                 }
             }
             $this->_saveCache($categoryUniqueClasses, $categoryCacheId);
         }
         if (!Enterprise_PageCache_Model_Cache::getCacheInstance()->getFrontend()->test($blockCacheId)) {
             $this->_saveCache($blockContent, $blockCacheId, $tags);
         }
     }
     return $this;
 }