/** * Prepare grid collection */ protected function _prepareCollection() { $collection = new Varien_Data_Collection(); $cache = Mage::helper('varnish')->getRedisCache()->getFrontend(); $ids = $cache->getIdsMatchingTags(array('VARNISH-CACHETYPE-PER-PAGE')); foreach ($ids as $id) { $data = unserialize($cache->load($id)); $item = new Varien_Object(); $item->setId($id); $item->setStoreId($data->getStoreId()); $item->setParentUrl($data->getParentUrl()); $item->setBlockName($data->getNameInLayout()); $item->setFingerprint($id); $item->setProbeUrl($data->getUrl()); $collection->addItem($item); } $this->setCollection($collection); $sort = $this->getParam($this->getVarNameSort()) ? $this->getParam($this->getVarNameSort()) : $this->getDefaultSort(); $dir = $this->getParam($this->getVarNameDir()) ? $this->getParam($this->getVarNameDir()) : $this->getDefaultDir(); $this->_sortCollectionBy($sort, $dir); return parent::_prepareCollection(); }
/** * Generate ESI data to be encoded in URL * * @param Mage_Core_Block_Template $blockObject * @param array $esiOptions * @return Varien_Object */ protected function _getEsiData($blockObject, $esiOptions) { Varien_Profiler::start('turpentine::observer::esi::_getEsiData'); $esiHelper = Mage::helper('turpentine/esi'); $cacheTypeParam = $esiHelper->getEsiCacheTypeParam(); $scopeParam = $esiHelper->getEsiScopeParam(); $methodParam = $esiHelper->getEsiMethodParam(); $esiData = new Varien_Object(); $esiData->setStoreId(Mage::app()->getStore()->getId()); $esiData->setDesignPackage(Mage::getDesign()->getPackageName()); $esiData->setDesignTheme(Mage::getDesign()->getTheme('layout')); $esiData->setNameInLayout($blockObject->getNameInLayout()); $esiData->setBlockType(get_class($blockObject)); $esiData->setLayoutHandles($this->_getBlockLayoutHandles($blockObject)); $esiData->setEsiMethod($esiOptions[$methodParam]); if ($esiOptions[$cacheTypeParam] == 'private' || $esiOptions[$cacheTypeParam] == 'customer_group') { if (is_array(@$esiOptions['flush_events'])) { $esiData->setFlushEvents(array_merge($esiHelper->getDefaultCacheClearEvents(), array_keys($esiOptions['flush_events']))); } else { $esiData->setFlushEvents($esiHelper->getDefaultCacheClearEvents()); } } if ($esiOptions[$scopeParam] == 'page') { $esiData->setParentUrl(Mage::app()->getRequest()->getRequestString()); } if (is_array($esiOptions['dummy_blocks'])) { $dummyBlocks = array(); foreach ($esiOptions['dummy_blocks'] as $key => $value) { $dummyBlocks[] = empty($value) && !is_numeric($key) ? $key : $value; } $esiData->setDummyBlocks($dummyBlocks); } else { Mage::helper('turpentine/debug')->logWarn('Invalid dummy_blocks for block: %s', $blockObject->getNameInLayout()); } $simpleRegistry = array(); $complexRegistry = array(); if (is_array($esiOptions['registry_keys'])) { foreach ($esiOptions['registry_keys'] as $key => $options) { $value = Mage::registry($key); if ($value) { if (is_object($value) && $value instanceof Mage_Core_Model_Abstract) { $complexRegistry[$key] = $this->_getComplexRegistryData($options, $value); } else { $simpleRegistry[$key] = $value; } } } } else { Mage::helper('turpentine/debug')->logWarn('Invalid registry_keys for block: %s', $blockObject->getNameInLayout()); } $esiData->setSimpleRegistry($simpleRegistry); $esiData->setComplexRegistry($complexRegistry); Varien_Profiler::stop('turpentine::observer::esi::_getEsiData'); return $esiData; }
public function writeTempFile($curr_page = 0, $length = 50, $filename = '') { $products = $this->getFeed()->getProductsCollection('', $curr_page, $length); $stock_collection = Mage::getResourceModel('cataloginventory/stock_item_collection'); $content = file_get_contents($this->getFeed()->getDirPath() . '/feed-' . $this->getFeed()->getId() . '-xml-product-block-template.tmp'); $fp = fopen($this->getFeed()->getTempFilePath(), 'a'); $log_fp = fopen(sprintf('%s/productsfeed/%s', Mage::getBaseDir('media'), 'log-' . $this->getFeed()->getId() . '.txt'), 'a'); $log_content = date("F j, Y, g:i:s a") . ', page:' . $curr_page . ', items selected:' . count($products) . "\n"; fwrite($log_fp, $log_content); fclose($log_fp); $store = Mage::getModel('core/store')->load($this->getFeed()->getStoreId()); $root_category = Mage::getModel('catalog/category')->load($store->getRootCategoryId()); if (Mage::getStoreConfig('gomage_feedpro/imagesettings/enable')) { $image_width = intval(Mage::getStoreConfig('gomage_feedpro/imagesettings/width')); $image_height = intval(Mage::getStoreConfig('gomage_feedpro/imagesettings/height')); } else { $image_width = 0; $image_height = 0; } foreach ($products as $_product) { $category_path = array(); $category = null; foreach ($_product->getCategoryIds() as $id) { $_category = $this->getFeed()->getCategoriesCollection()->getItemById($id); if (is_null($category) || $category && $_category && $category->getLevel() < $_category->getLevel()) { $category = $_category; } } if ($category) { $category_path = array($category->getName()); $parent_id = $category->getParentId(); if ($category->getLevel() > $root_category->getLevel()) { while ($_category = $this->getFeed()->getCategoriesCollection()->getItemById($parent_id)) { if ($_category->getLevel() <= $root_category->getLevel()) { break; } $category_path[] = $_category->getName(); $parent_id = $_category->getParentId(); } } } $product = new Varien_Object(); if ($category) { $product->setCategory($category->getName()); $product->setCategoryId($category->getEntityId()); $product->setCategorySubcategory(implode(' -> ', array_reverse($category_path))); } else { $product->setCategory(''); $product->setCategorySubcategory(''); } $template_attributes = $this->getAllVars($content); $custom_attributes = Mage::getResourceModel('gomage_feed/custom_attribute_collection'); $custom_attributes->load(); foreach ($template_attributes as $attribute_code) { $value = null; switch ($attribute_code) { case 'parent_sku': if (($parent_product = $this->getFeed()->getParentProduct($_product, $products)) && $parent_product->getEntityId() > 0) { $value = $parent_product->getSku(); } else { $value = ''; } break; case 'parent_base_image': if (($parent_product = $this->getFeed()->getParentProduct($_product, $products)) && $parent_product->getEntityId() > 0) { $_prod = Mage::getModel('catalog/product')->load($parent_product->getId()); } else { $_prod = Mage::getModel('catalog/product')->load($_product->getId()); } try { if ($image_width || $image_height) { $image_url = (string) Mage::helper('catalog/image')->init($_prod, 'image')->resize($image_width, $image_height); } else { $image_url = (string) Mage::helper('catalog/image')->init($_prod, 'image'); } } catch (Exception $e) { $image_url = ''; } $value = $image_url; break; case 'price': if (in_array($_product->getTypeId(), array(Mage_Catalog_Model_Product_Type::TYPE_GROUPED, Mage_Catalog_Model_Product_Type::TYPE_BUNDLE))) { $value = $store->convertPrice($_product->getMinimalPrice(), false, false); } else { $value = $store->convertPrice($_product->getPrice(), false, false); } break; case 'store_price': case 'final_price': $value = $store->convertPrice($_product->getFinalPrice(), false, false); break; case 'image': case 'gallery': case 'media_gallery': $_prod = Mage::getModel('catalog/product')->load($_product->getId()); try { if ($image_width || $image_height) { $image_url = (string) Mage::helper('catalog/image')->init($_prod, 'image')->resize($image_width, $image_height); } else { $image_url = (string) Mage::helper('catalog/image')->init($_prod, 'image'); } } catch (Exception $e) { $image_url = ''; } $product->setData($attribute_code, $image_url); break; case 'image_2': case 'image_3': case 'image_4': case 'image_5': if (!$_product->hasData('media_gallery_images')) { $_prod = Mage::getModel('catalog/product')->load($_product->getId()); $_product->setData('media_gallery_images', $_prod->getMediaGalleryImages()); } $i = 0; foreach ($_product->getMediaGalleryImages() as $_image) { $i++; if ('image_' . $i == $attribute_code) { if ($image_width || $image_height) { $product->setData($attribute_code, (string) Mage::helper('catalog/image')->init($_product, 'image', $_image->getFile())->resize($image_width, $image_height)); } else { $product->setData($attribute_code, $_image['url']); } } } break; case 'parent_url': if (($parent_product = $this->getFeed()->getParentProduct($_product, $products)) && $parent_product->getEntityId() > 0) { $product->setParentUrl($parent_product->getProductUrl(false)); break; } $product->setParentUrl($_product->getProductUrl(false)); break; case 'url': $product->setUrl($_product->getProductUrl(false)); break; default: if (strpos($attribute_code, 'custom:') === 0) { $custom_code = trim(str_replace('custom:', '', $attribute_code)); if ($custom_attribute = $custom_attributes->getItemByColumnValue('code', $custom_code)) { $options = Zend_Json::decode($custom_attribute->getData('data')); foreach ($options as $option) { foreach ($option['condition'] as $condition) { switch ($condition['attribute_code']) { case 'product_type': $attr_value = $_product->getTypeId(); break; case 'price': if (in_array($_product->getTypeId(), array(Mage_Catalog_Model_Product_Type::TYPE_GROUPED, Mage_Catalog_Model_Product_Type::TYPE_BUNDLE))) { $attr_value = $store->convertPrice($_product->getMinimalPrice(), false, false); } else { $attr_value = $store->convertPrice($_product->getPrice(), false, false); } break; case 'store_price': $attr_value = $store->convertPrice($_product->getFinalPrice(), false, false); break; case 'parent_url': if (($parent_product = $this->getFeed()->getParentProduct($_product, $products)) && $parent_product->getEntityId() > 0) { $attr_value = $parent_product->getProductUrl(false); break; } $attr_value = $_product->getProductUrl(false); break; case 'image': case 'gallery': case 'media_gallery': if (!$_product->hasData('product_base_image')) { $_prod = Mage::getModel('catalog/product')->load($_product->getId()); try { if ($image_width || $image_height) { $image_url = (string) Mage::helper('catalog/image')->init($_prod, 'image')->resize($image_width, $image_height); } else { $image_url = (string) Mage::helper('catalog/image')->init($_prod, 'image'); } } catch (Exception $e) { $image_url = ''; } $_product->setData('product_base_image', $image_url); $attr_value = $image_url; } else { $attr_value = $_product->getData('product_base_image'); } break; case 'url': $attr_value = $_product->getProductUrl(false); break; case 'qty': if ($stock_item = $stock_collection->getItemByColumnValue('product_id', $_product->getId())) { $attr_value = ceil($stock_collection->getItemByColumnValue('product_id', $_product->getId())->getQty()); } else { $attr_value = 0; } break; case 'is_in_stock': $attr_value = ceil(Mage::getModel('cataloginventory/stock_item')->loadByProduct($_product)->getIsInStock()); if (!$attr_value || $attr_value == '' || $attr_value == null) { $attr_value = 0; } // if($stock_item = $stock_collection->getItemByColumnValue('product_id', $_product->getId())){ // // $attr_value = $stock_collection->getItemByColumnValue('product_id', $_product->getId())->getData('is_in_stock'); // // }else{ // // $attr_value = 0; // // } break; case 'category': $attr_value = $product->getCategory(); break; case 'category_id': $attr_value = $_product->getCategoryIds(); break; default: $attr_value = $_product->getData($condition['attribute_code']); } $cond_value = $condition['value']; $is_multi = false; if ($product_attribute = $_product->getResource()->getAttribute($condition['attribute_code'])) { if ($product_attribute->getFrontendInput() == 'multiselect') { $is_multi = true; $attr_value = explode(',', $attr_value); } } if ($condition['attribute_code'] == 'category_id') { $is_multi = true; } switch ($condition['condition']) { case 'eq': if (!$is_multi && $attr_value == $cond_value || $is_multi && in_array($cond_value, $attr_value)) { continue 2; } else { continue 3; } break; case 'neq': if (!$is_multi && $attr_value != $cond_value || $is_multi && !in_array($cond_value, $attr_value)) { continue 2; } else { continue 3; } break; case 'gt': if ($attr_value > $cond_value) { continue 2; } else { continue 3; } break; case 'lt': if ($attr_value < $cond_value) { continue 2; } else { continue 3; } break; case 'gteq': if ($attr_value >= $cond_value) { continue 2; } else { continue 3; } break; case 'lteq': if ($attr_value <= $cond_value) { continue 2; } else { continue 3; } break; case 'like': if (strpos($attr_value, $cond_value) !== false) { continue 2; } else { continue 3; } break; case 'nlike': if (strpos($attr_value, $cond_value) === false) { continue 2; } else { continue 3; } break; } } if (in_array($option['value_type'], array('percent', 'attribute'))) { switch ($option['value_type_attribute']) { case 'price': if (in_array($_product->getTypeId(), array(Mage_Catalog_Model_Product_Type::TYPE_GROUPED, Mage_Catalog_Model_Product_Type::TYPE_BUNDLE))) { $attribute_value = $store->convertPrice($_product->getMinimalPrice(), false, false); } else { $attribute_value = $store->convertPrice($_product->getPrice(), false, false); } break; case 'store_price': $attribute_value = $store->convertPrice($_product->getFinalPrice(), false, false); break; case 'parent_url': if (($parent_product = $this->getFeed()->getParentProduct($_product, $products)) && $parent_product->getEntityId() > 0) { $attribute_value = $parent_product->getProductUrl(false); break; } $attribute_value = $_product->getProductUrl(false); break; case 'image': case 'gallery': case 'media_gallery': if (!$_product->hasData('product_base_image')) { $_prod = Mage::getModel('catalog/product')->load($_product->getId()); try { if ($image_width || $image_height) { $image_url = (string) Mage::helper('catalog/image')->init($_prod, 'image')->resize($image_width, $image_height); } else { $image_url = (string) Mage::helper('catalog/image')->init($_prod, 'image'); } } catch (Exception $e) { $image_url = ''; } $_product->setData('product_base_image', $image_url); $attribute_value = $image_url; } else { $attribute_value = $_product->getData('product_base_image'); } break; case 'url': $attribute_value = $_product->getProductUrl(false); break; case 'qty': $attribute_value = ceil(Mage::getModel('cataloginventory/stock_item')->loadByProduct($_product)->getQty()); if (!$attribute_value || $attribute_value == '' || $attribute_value == null) { $attribute_value = 0; } // if($stock_item = $stock_collection->getItemByColumnValue('product_id', $_product->getId())){ // // $attribute_value = ceil($stock_collection->getItemByColumnValue('product_id', $_product->getId())->getQty()); // // }else{ // // $attribute_value = 0; // // } break; case 'category': $attribute_value = $product->getCategory(); break; default: $attribute_value = $_product->getData($option['value_type_attribute']); } } if ($option['value_type'] == 'percent') { $value = floatval($attribute_value) / 100 * floatval($option['value']); } elseif ($option['value_type'] == 'attribute') { $value = $attribute_value; } else { $value = $option['value']; } break; } if ($value === null && $custom_attribute->getDefaultValue()) { switch ($custom_attribute->getDefaultValue()) { case 'price': if (in_array($_product->getTypeId(), array(Mage_Catalog_Model_Product_Type::TYPE_GROUPED, Mage_Catalog_Model_Product_Type::TYPE_BUNDLE))) { $value = $store->convertPrice($_product->getMinimalPrice(), false, false); } else { $value = $store->convertPrice($_product->getPrice(), false, false); } break; case 'store_price': $value = $store->convertPrice($_product->getFinalPrice(), false, false); break; case 'parent_url': if (($parent_product = $this->getFeed()->getParentProduct($_product, $products)) && $parent_product->getEntityId() > 0) { $value = $parent_product->getProductUrl(false); break; } $value = $_product->getProductUrl(false); break; case 'image': case 'gallery': case 'media_gallery': if (!$_product->hasData('product_base_image')) { $_prod = Mage::getModel('catalog/product')->load($_product->getId()); try { if ($image_width || $image_height) { $image_url = (string) Mage::helper('catalog/image')->init($_prod, 'image')->resize($image_width, $image_height); } else { $image_url = (string) Mage::helper('catalog/image')->init($_prod, 'image'); } } catch (Exception $e) { $image_url = ''; } $_product->setData('product_base_image', $image_url); $value = $image_url; } else { $value = $_product->getData('product_base_image'); } break; case 'url': $value = $_product->getProductUrl(false); break; case 'qty': $value = ceil(Mage::getModel('cataloginventory/stock_item')->loadByProduct($_product)->getQty()); if (!$value || $value == '' || $value == null) { $value = 0; } // if($stock_item = $stock_collection->getItemByColumnValue('product_id', $_product->getId())){ // // $value = ceil($stock_collection->getItemByColumnValue('product_id', $_product->getId())->getQty()); // // }else{ // // $value = 0; // // } break; case 'category': $value = $product->getCategory(); break; default: $value = $_product->getData($custom_attribute->getDefaultValue()); } } } } elseif ($attribute_model = $_product->getResource()->getAttribute($attribute_code)) { switch ($attribute_model->getFrontendInput()) { case 'select': case 'multiselect': $value = implode(', ', (array) $_product->getAttributeText($attribute_code)); break; default: $value = $_product->getData($attribute_code); break; } } break; } if ($value && !$product->getData($attribute_code)) { $product->setData($attribute_code, $value); } } $product->setDescription(strip_tags(preg_replace('/<br.*?>/s', "\r\n", $_product->getDescription()))); $product->setShortDescription(strip_tags(preg_replace('/<br.*?>/s', "\r\n", $_product->getShortDescription()))); $product->setQty(ceil(Mage::getModel('cataloginventory/stock_item')->loadByProduct($_product)->getQty())); fwrite($fp, parent::setVars($content, $product) . "\r\n"); } fclose($fp); }
/** * Called on * core_block_abstract_to_html_before * * Checks if the "esi" variable is set on a block. * If yes, the template of the block is replaced by varnish/esi.phtml which contains the <esi:include> tag * it also adds to the response the header X-magento-doesi which will be interpreted by varnish and tell it to do the esi processing * * @param array $eventObject */ public function injectEsi($eventObject) { //No ESI injection if the module is disabled or the request is made on HTTPS if (!Mage::helper('varnish')->isVarnishModuleEnabled() || Mage::app()->getRequest()->isSecure()) { return; } $block = $eventObject->getBlock(); if ($block instanceof Mage_Core_Block_Template) { $esi = $block->getEsi(); if ($esi == true) { //We don't allow ESI in admin, for now. Maybe in future releases. if (Mage::app()->getStore()->getCode() == 'admin') { throw new Mage_Adminhtml_Exception("ESI includes are forbidden in Admin"); } // We replace the template of the block by the varnish/esi.phtml template // The HTML of our template will replace the real HTML of the block $block->setTemplate('varnish/esi.phtml'); $src = new Varien_Object(); //Blocks change depending on the store id, so we keep track of that $src->setStoreId(Mage::app()->getStore()->getId()); //Blocks also change depending on the design so we keep track of the package and the theme of the current block $src->setDesignPackage(Mage::getDesign()->getPackageName()); $src->setDesignTheme(Mage::getDesign()->getTheme('layout')); $src->setNameInLayout($block->getNameInLayout()); /* * Set the cache type * per-client * per-page * global * * * per-client tells varnish to cache the block per-client basis. * per-page tells varnish to cache the content based on the url of the page. * global tells varnish to serve the same cached version to every client. * * The per-client cache is based on the frontend cookie of the client. * * We default the cache type to "global" */ if (empty($esi['cache_type'])) { $esi['cache_type'] = 'global'; } $src->setCacheType($esi['cache_type']); /** * If the block is cached on a per-page basis * we create an entry in our ESI table to keep track the URLs where the block appear * */ if ($src->getCacheType() === 'per-page') { $parentUrl = Mage::app()->getRequest()->getRequestString(); $src->setParentUrl($parentUrl); } /** * Expiry (or TTL in Varnish lingo). How lon will the object be stored in Varnish? * TODO: make sure the expiry is in format 1d 24h 1140m 86400s */ if (!empty($esi['expiry'])) { $src->setExpiry($esi['expiry']); } else { if ($src->getCacheType() === 'per-client') { $src->setExpiry(Mage::getStoreConfig('varnish/cache/per_client_default_expiry')); } else { if ($src->getCacheType() === 'per-page') { $src->setExpiry(Mage::getStoreConfig('varnish/cache/per_page_default_expiry')); } else { $src->setExpiry(Mage::getStoreConfig('varnish/cache/global_default_expiry')); } } } //We create a unique fingerprint with all our values foreach ($src->getData() as $value) { $this->_hash($value); } // $src is the source for our <esi:include> it is composed of all the above variables $src->setUrl("/varnish/cache/getBlock/cachetype/{$src->getCacheType()}/expiry/{$src->getExpiry()}/fingerprint/{$this->_hash()}"); /** * Registry save: * some block rely on values stored in the Mage::registry(). * For example, the product page relies on Mage::registry('current_product'); * The problem is that the Mage::registry is not persistent between requests. This means that once the request is served, * the registry looses its data. * This means that when Varnish makes the ESI request, the registry is empty and if the block makes a call to Mage::registry('current_product') * the function will return null. * In order to strive this problem, when you setEsi on a block using the mage registry, you need to specify in the layout which keys you want to keep. * These keys will be saved in the magento cache and thus be accessible when the ESI request is made */ if (!empty($esi['registry_keys'])) { // We create an array with the <registry_keys></registry_keys> set in the layout $registryKeys = explode(',', $esi['registry_keys']); // We iterate through each of the registrykey... foreach ($registryKeys as $registryKey) { $registryContent = Mage::registry($registryKey); if ($registryContent !== null) { // If the key exist we save the content in an array $registry[] = array("key" => $registryKey, "content" => $registryContent); } } $src->setRegistry($registry); } $src->setBlockType(get_class($block)); // and we save the content in the cache with the hash as the id $cache = Mage::helper('varnish')->getRedisCache(); $tags = array("VARNISH_CACHETYPE_{$src->getCacheType()}", "VARNISH_BLOCKTYPE_{$src->getBlockType()}", "VARNISH_BLOCKNAME_{$src->getNameInLayout()}"); $cache->save(serialize($src), $this->_hash(), $tags, null); $block->setSrc($src); // Tell varnish to do esi processing on the page Mage::getSingleton('varnish/cache')->setDoEsi(true); } } }