Exemple #1
0
 public function open($product_id)
 {
     $this->_product = Mage::getModel('catalog/product')->load($product_id);
     if ($this->_product->getId()) {
         $this->url($this->_product->getProductUrl());
         return $this;
     }
     throw new Exception("product not found");
 }
Exemple #2
0
 /**
  * Set current attribute to entry (for specified product)
  *
  * @param Mage_Catalog_Model_Product $product
  * @param Google_Service_ShoppingContent_Product $shoppingProduct
  * @return Google_Service_ShoppingContent_Product
  */
 public function convertAttribute($product, $shoppingProduct)
 {
     $url = $product->getProductUrl(false);
     if ($url) {
         $config = Mage::getSingleton('googleshoppingapi/config');
         if (!Mage::getStoreConfigFlag('web/url/use_store') && $config->getAddStoreCodeToUrl()) {
             Mage::log($config->getAddStoreCodeToUrl() ? "true" : "false");
             $urlInfo = parse_url($url);
             $store = $product->getStore()->getCode();
             if (isset($urlInfo['query']) && $urlInfo['query'] != '') {
                 $url .= '&___store=' . $store;
             } else {
                 $url .= '?___store=' . $store;
             }
         }
         if ($config->getAddUtmSrcGshopping($product->getStoreId())) {
             $url .= '&utm_source=GoogleShopping';
         }
         if ($customUrlParameters = $config->getCustomUrlParameters($product->getStoreId())) {
             $url .= $customUrlParameters;
         }
         $shoppingProduct->setLink($url);
     }
     return $shoppingProduct;
 }
Exemple #3
0
 /**
  * Set current attribute to entry (for specified product)
  *
  * @param Mage_Catalog_Model_Product $product
  * @param Varien_Gdata_Gshopping_Entry $entry
  * @return Varien_Gdata_Gshopping_Entry
  */
 public function convertAttribute($product, $entry)
 {
     $url = $product->getProductUrl(false);
     if ($url) {
         if (!Mage::getStoreConfigFlag('web/url/use_store')) {
             $urlInfo = parse_url($url);
             $store = $product->getStore()->getCode();
             if (isset($urlInfo['query']) && $urlInfo['query'] != '') {
                 $url .= '&___store=' . $store;
             } else {
                 $url .= '?___store=' . $store;
             }
         }
         $links = $entry->getLink();
         if (!is_array($links)) {
             $links = array();
         }
         $link = $entry->getService()->newLink();
         $link->setHref($url);
         $link->setRel('alternate');
         $link->setType('text/html');
         if ($product->getName()) {
             $link->setTitle($product->getName());
         }
         $links[0] = $link;
         $entry->setLink($links);
     }
     return $entry;
 }
 public function getItemBaseInfo()
 {
     $helper = Mage::helper('catalog/image');
     $helper->init($this->product, $this->getProductImageType())->keepAspectRatio($this->_keepAspectRatio)->keepFrame($this->_keepFrame);
     $this->item['item_id'] = $this->product->getId();
     $this->item['item_title'] = $this->product->getName();
     $this->item['item_url'] = $this->product->getProductUrl();
     $this->item['cid'] = $this->product->getCategoryIds();
     $this->item['qty'] = $this->product->getStockItem()->getQty();
     $this->item['thumbnail_pic_url'] = (string) $helper->resize($this->thumbnail_with, $this->thumbnail_height);
     $this->item['main_pic_url'] = (string) $helper->resize($this->main_with, $this->main_height);
     $this->item['is_virtual'] = $this->product->isVirtual();
     $this->item['item_status'] = $this->product->isSaleable() ? 'instock' : 'outofstock';
     if (!$this->product->getRatingSummary()) {
         Mage::getModel('review/review')->getEntitySummary($this->product, Mage::app()->getStore()->getId());
     }
     $this->item['allow_add_to_cart'] = !$this->HasOptions();
     $this->item['rating_score'] = round((int) $this->product->getRatingSummary()->getRatingSummary() / 20);
     $this->item['rating_count'] = $this->product->getRatingSummary()->getReviewsCount();
     $this->item['sales_type'] = $this->product->isInStock() ? 'stock' : 'distribute';
     $this->item['qty_min_unit'] = 1;
     $stockItem = $this->product->getStockItem();
     if ($stockItem) {
         if ($stockItem->getMinSaleQty() && $stockItem->getMinSaleQty() > 0) {
             $this->item['qty_min_unit'] = $stockItem->getMinSaleQty();
         }
     }
     $this->item['item_type'] = $this->product->getTypeId();
     return $this->item;
 }
 /**
  * Redirect to product page
  *
  * @param \Mage_Catalog_Model_Product $product
  */
 public function redirectToProductPage(Mage_Catalog_Model_Product $product)
 {
     $response = Mage::app()->getResponse();
     $response->setRedirect($product->getProductUrl());
     $response->sendResponse();
     exit;
 }
Exemple #6
0
 /**
  * Retrieve product attributes as xml object
  *
  * @param Mage_Catalog_Model_Product $product
  * @param string $itemNodeName
  * @return Mage_XmlConnect_Model_Simplexml_Element
  */
 public function productToXmlObject(Mage_Catalog_Model_Product $product, $itemNodeName = 'item')
 {
     /** @var $item Mage_XmlConnect_Model_Simplexml_Element */
     $item = Mage::getModel('xmlconnect/simplexml_element', '<' . $itemNodeName . '></' . $itemNodeName . '>');
     if ($product && $product->getId()) {
         $item->addChild('entity_id', $product->getId());
         $item->addChild('name', $item->escapeXml($product->getName()));
         $item->addChild('entity_type', $product->getTypeId());
         $item->addChild('short_description', $item->escapeXml($product->getShortDescription()));
         $description = Mage::helper('xmlconnect')->htmlize($item->xmlentities($product->getDescription()));
         $item->addChild('description', $description);
         $item->addChild('link', $product->getProductUrl());
         if ($itemNodeName == 'item') {
             $imageToResize = Mage::helper('xmlconnect/image')->getImageSizeForContent('product_small');
             $propertyToResizeName = 'small_image';
         } else {
             $imageToResize = Mage::helper('xmlconnect/image')->getImageSizeForContent('product_big');
             $propertyToResizeName = 'image';
         }
         $icon = clone Mage::helper('catalog/image')->init($product, $propertyToResizeName)->resize($imageToResize);
         $iconXml = $item->addChild('icon', $icon);
         $file = Mage::helper('xmlconnect')->urlToPath($icon);
         $iconXml->addAttribute('modification_time', filemtime($file));
         $item->addChild('in_stock', (int) $product->getIsInStock());
         $item->addChild('is_salable', (int) $product->isSalable());
         /**
          * By default all products has gallery (because of collection not load gallery attribute)
          */
         $hasGallery = 1;
         if ($product->getMediaGalleryImages()) {
             $hasGallery = sizeof($product->getMediaGalleryImages()) > 0 ? 1 : 0;
         }
         $item->addChild('has_gallery', $hasGallery);
         /**
          * If product type is grouped than it has options as its grouped items
          */
         if ($product->getTypeId() == Mage_Catalog_Model_Product_Type_Grouped::TYPE_CODE || $product->getTypeId() == Mage_Catalog_Model_Product_Type_Configurable::TYPE_CODE) {
             $product->setHasOptions(true);
         }
         $item->addChild('has_options', (int) $product->getHasOptions());
         if ($minSaleQty = $this->_getMinimalQty($product)) {
             $item->addChild('min_sale_qty', (int) $minSaleQty);
         }
         if (!$product->getRatingSummary()) {
             Mage::getModel('review/review')->getEntitySummary($product, Mage::app()->getStore()->getId());
         }
         $item->addChild('rating_summary', round((int) $product->getRatingSummary()->getRatingSummary() / 10));
         $item->addChild('reviews_count', $product->getRatingSummary()->getReviewsCount());
         if ($this->getChild('product_price')) {
             $this->getChild('product_price')->setProduct($product)->setProductXmlObj($item)->collectProductPrices();
         }
         if ($this->getChild('additional_info')) {
             $this->getChild('additional_info')->addAdditionalData($product, $item);
         }
     }
     return $item;
 }
 public function getProductUrl($useSid = null)
 {
     if (is_callable(array($this->getTypeInstance(), 'hasConfigurableProductParentId')) && $this->getTypeInstance()->hasConfigurableProductParentId()) {
         $confProdId = $this->getTypeInstance()->getConfigurableProductParentId();
         return Mage::getModel('catalog/product')->load($confProdId)->getProductUrl();
     } else {
         return parent::getProductUrl($useSid);
     }
 }
 /**
  * @covers Mage_Catalog_Model_Product::getProductUrl
  * @covers Mage_Catalog_Model_Product::getUrlInStore
  */
 public function testGetProductUrl()
 {
     $this->assertStringEndsWith('catalog/product/view/', $this->_model->getProductUrl());
     $this->assertStringEndsWith('catalog/product/view/', $this->_model->getUrlInStore());
     $this->_model->setId(999);
     $url = $this->_model->getProductUrl();
     $this->assertContains('catalog/product/view', $url);
     $this->assertContains('id/999', $url);
     $storeUrl = $this->_model->getUrlInStore();
     $this->assertEquals($storeUrl, $url);
 }
 /**
  * get the longest url for a product
  * from http://magento.stackexchange.com/questions/52969/get-product-path-from-id-with-category-path-in-url
  * @param  Mage_Catalog_Model_Product|null $product [description]
  * @return String full url of the product
  */
 public static function getFullProductUrl(Mage_Catalog_Model_Product $product = null)
 {
     // Force display deepest child category as request path.
     $categories = $product->getCategoryCollection();
     $deepCatId = 0;
     $path = '';
     $productPath = false;
     foreach ($categories as $category) {
         // Look for the deepest path and save.
         if (substr_count($category->getData('path'), '/') > substr_count($path, '/')) {
             $path = $category->getData('path');
             $deepCatId = $category->getId();
         }
     }
     // Load category.
     $category = Mage::getModel('catalog/category')->load($deepCatId);
     // Remove .html from category url_path.
     $categoryPath = str_replace('.html', '', $category->getData('url_path'));
     // Get product url path if set.
     $productUrlPath = $product->getData('url_path');
     // Get product request path if set.
     $productRequestPath = $product->getData('request_path');
     // If URL path is not found, try using the URL key.
     if ($productUrlPath === null && $productRequestPath === null) {
         $productUrlPath = $product->getData('url_key');
     }
     // Now grab only the product path including suffix (if any).
     if ($productUrlPath) {
         $path = explode('/', $productUrlPath);
         $productPath = array_pop($path);
     } elseif ($productRequestPath) {
         $path = explode('/', $productRequestPath);
         $productPath = array_pop($path);
     }
     // Now set product request path to be our full product url including deepest category url path.
     if ($productPath !== false) {
         if ($categoryPath) {
             // Only use the category path is one is found.
             $product->setData('request_path', $categoryPath . '/' . $productPath);
         } else {
             $product->setData('request_path', $productPath);
         }
     }
     return $product->getProductUrl();
 }
 /**
  * Create Product array from Mage_Catalog_Model_Product
  *
  * @param Mage_Catalog_Model_Product $product
  * @return array
  */
 public function getProductData(Mage_Catalog_Model_Product $product)
 {
     try {
         $data = array('url' => $product->getProductUrl(), 'title' => htmlspecialchars($product->getName()), 'spider' => 1, 'price' => $product->getPrice(), 'description' => urlencode($product->getDescription()), 'tags' => htmlspecialchars($product->getMetaKeyword()), 'images' => array(), 'vars' => array('sku' => $product->getSku(), 'storeId' => '', 'typeId' => $product->getTypeId(), 'status' => $product->getStatus(), 'categoryId' => $product->getCategoryId(), 'categoryIds' => $product->getCategoryIds(), 'websiteIds' => $product->getWebsiteIds(), 'storeIds' => $product->getStoreIds(), 'groupPrice' => $product->getGroupPrice(), 'formatedPrice' => $product->getFormatedPrice(), 'calculatedFinalPrice' => $product->getCalculatedFinalPrice(), 'minimalPrice' => $product->getMinimalPrice(), 'specialPrice' => $product->getSpecialPrice(), 'specialFromDate' => $product->getSpecialFromDate(), 'specialToDate' => $product->getSpecialToDate(), 'relatedProductIds' => $product->getRelatedProductIds(), 'upSellProductIds' => $product->getUpSellProductIds(), 'getCrossSellProductIds' => $product->getCrossSellProductIds(), 'isSuperGroup' => $product->isSuperGroup(), 'isGrouped' => $product->isGrouped(), 'isConfigurable' => $product->isConfigurable(), 'isSuper' => $product->isSuper(), 'isSalable' => $product->isSalable(), 'isAvailable' => $product->isAvailable(), 'isVirtual' => $product->isVirtual(), 'isRecurring' => $product->isRecurring(), 'isInStock' => $product->isInStock(), 'weight' => $product->getSku()));
         // Add product images
         if (self::validateProductImage($product->getImage())) {
             $data['images']['full'] = array("url" => $product->getImageUrl());
         }
         if (self::validateProductImage($product->getSmallImage())) {
             $data['images']['smallImage'] = array("url" => $product->getSmallImageUrl($width = 88, $height = 77));
         }
         if (self::validateProductImage($product->getThumbnail())) {
             $data['images']['thumb'] = array("url" => $product->getThumbnailUrl($width = 75, $height = 75));
         }
         return $data;
         return $data;
     } catch (Exception $e) {
         Mage::logException($e);
     }
 }
Exemple #11
0
 /**
  * Set current attribute to entry (for specified product)
  *
  * @param Mage_Catalog_Model_Product $product
  * @param Google_Service_ShoppingContent_Product $shoppingProduct
  * @return Google_Service_ShoppingContent_Product
  */
 public function convertAttribute($product, $shoppingProduct)
 {
     $parentId = Mage::getModel('catalog/product_type_configurable')->getParentIdsByChild($product->getId());
     $parentItem = Mage::getModel('catalog/product')->load($parentId);
     $category = Mage::getModel('catalog/category')->load();
     if (!Mage::getStoreConfig('web/seo/use_rewrites')) {
         if ($product->getTypeId() == 'simple' && $parentItem->getTypeId() == 'configurable' || 'bundle' || 'grouped') {
             $url = $parentItem->getProductUrl(false);
         } else {
             $url = $product->getProductUrl(false);
         }
     } else {
         if ($product->getTypeId() == 'simple' && $parentItem->getTypeId() == 'configurable' || 'bundle' || 'grouped') {
             $url = sprintf('%s%s', Mage::getBaseUrl(), $parentItem->getUrlPath($category));
         } else {
             $url = sprintf('%s%s', Mage::getBaseUrl(), $product->getUrlPath($category));
         }
     }
     if ($url) {
         if (!Mage::getStoreConfigFlag('web/url/use_store')) {
             $urlInfo = parse_url($url);
             $store = $product->getStore()->getCode();
             if (isset($urlInfo['query']) && $urlInfo['query'] != '') {
                 $url .= '&___store=' . $store;
             } else {
                 $url .= '?___store=' . $store;
             }
         }
         $config = Mage::getSingleton('googleshoppingapi/config');
         if ($config->getAddUtmSrcGshopping($product->getStoreId())) {
             $url .= '&utm_source=GoogleShopping';
         }
         if ($customUrlParameters = $config->getCustomUrlParameters($product->getStoreId())) {
             $url .= $customUrlParameters;
         }
         $shoppingProduct->setLink($url);
     }
     return $shoppingProduct;
 }
Exemple #12
0
 /**
  * Retrieve url for add product to cart
  * Rewrited for Product List and has required options products
  *
  * @param  Mage_Catalog_Model_Product $product
  * @param array $additional
  * @return string
  */
 public function getAddToCartUrl($product, $additional = array())
 {
     if ($product->hasRequiredOptions()) {
         $url = $product->getProductUrl();
         $link = strpos($url, '?') !== false ? '&' : '?';
         return $url . $link . 'options=cart';
     }
     return parent::getAddToCartUrl($product, $additional);
 }
 public function getObject(Mage_Catalog_Model_Product $product)
 {
     $defaultData = array();
     $transport = new Varien_Object($defaultData);
     Mage::dispatchEvent('algolia_product_index_before', array('product' => $product, 'custom_data' => $transport));
     $defaultData = $transport->getData();
     $defaultData = is_array($defaultData) ? $defaultData : explode("|", $defaultData);
     $customData = array('objectID' => $product->getId(), 'name' => $product->getName(), 'url' => $product->getProductUrl(), 'description' => $product->getDescription());
     foreach (array('price', 'price_with_tax', 'special_price_from_date', 'special_price_to_date', 'special_price', 'special_price_with_tax', 'special_price_formated', 'special_price_with_tax_formated', 'price_formated', 'price_with_tax_formated') as $price) {
         $customData[$price] = array();
     }
     $this->handlePrice($product, $customData);
     if ($this->config->isCustomerGroupsEnabled()) {
         foreach ($groups = Mage::getModel('customer/group')->getCollection() as $group) {
             $group_id = (int) $group->getData('customer_group_id');
             $this->handlePrice($product, $customData, $group_id);
         }
     }
     $categories = array();
     $categories_with_path = array();
     foreach ($this->getProductActiveCategories($product, $product->getStoreId()) as $categoryId) {
         $category = Mage::getModel('catalog/category')->load($categoryId);
         $categoryName = $category->getName();
         if ($categoryName) {
             $categories[] = $categoryName;
         }
         $category->getUrlInstance()->setStore($product->getStoreId());
         $path = array();
         foreach ($category->getPathIds() as $treeCategoryId) {
             $name = $this->getCategoryName($treeCategoryId, $product->getStoreId());
             if ($name) {
                 $path[] = $name;
             }
         }
         $categories_with_path[] = $path;
     }
     foreach ($categories_with_path as $result) {
         for ($i = count($result) - 1; $i > 0; $i--) {
             $categories_with_path[] = array_slice($result, 0, $i);
         }
     }
     $categories_with_path = array_intersect_key($categories_with_path, array_unique(array_map('serialize', $categories_with_path)));
     $categories_hierarchical = array();
     $level_name = 'level';
     foreach ($categories_with_path as $category) {
         for ($i = 0; $i < count($category); $i++) {
             if (isset($categories_hierarchical[$level_name . $i]) === false) {
                 $categories_hierarchical[$level_name . $i] = array();
             }
             $categories_hierarchical[$level_name . $i][] = implode(' /// ', array_slice($category, 0, $i + 1));
         }
     }
     foreach ($categories_hierarchical as &$level) {
         $level = array_values(array_unique($level));
     }
     foreach ($categories_with_path as &$category) {
         $category = implode(' /// ', $category);
     }
     $customData['categories'] = $categories_hierarchical;
     //array_values($categories_with_path);
     $customData['categories_without_path'] = $categories;
     if (false === isset($defaultData['thumbnail_url'])) {
         try {
             $customData['thumbnail_url'] = $product->getThumbnailUrl();
             $customData['thumbnail_url'] = str_replace(array('https://', 'http://'), '//', $customData['thumbnail_url']);
         } catch (\Exception $e) {
         }
     }
     if (false === isset($defaultData['image_url'])) {
         try {
             $customData['image_url'] = $product->getImageUrl();
             $customData['image_url'] = str_replace(array('https://', 'http://'), '//', $customData['image_url']);
         } catch (\Exception $e) {
         }
     }
     $additionalAttributes = $this->config->getProductAdditionalAttributes($product->getStoreId());
     $sub_products = null;
     if ($product->getTypeId() == 'configurable' || $product->getTypeId() == 'grouped') {
         if ($product->getTypeId() == 'grouped') {
             $sub_products = $product->getTypeInstance(true)->getAssociatedProducts($product);
         }
         if ($product->getTypeId() == 'configurable') {
             $sub_products = $product->getTypeInstance(true)->getUsedProducts(null, $product);
         }
         $min = PHP_INT_MAX;
         $max = 0;
         $min_with_tax = PHP_INT_MAX;
         $max_with_tax = 0;
         foreach ($sub_products as $sub_product) {
             $sub_product = Mage::getModel('catalog/product')->load($sub_product->getId());
             $price = $sub_product->getPrice();
             $price_with_tax = Mage::helper('tax')->getPrice($sub_product, $price, true, null, null, null, null, false);
             $min = min($min, $price);
             $max = max($max, $price);
             $min_with_tax = min($min_with_tax, $price_with_tax);
             $max_with_tax = max($max_with_tax, $price_with_tax);
         }
         $customData['min_formated'] = Mage::helper('core')->formatPrice($min, false);
         $customData['max_formated'] = Mage::helper('core')->formatPrice($max, false);
         $customData['min_with_tax_formated'] = Mage::helper('core')->formatPrice($min_with_tax, false);
         $customData['max_with_tax_formated'] = Mage::helper('core')->formatPrice($max_with_tax, false);
     }
     if (false === isset($defaultData['in_stock'])) {
         $stockItem = $product->getStockItem();
         $customData['in_stock'] = (int) $stockItem->getIsInStock();
     }
     // skip default calculation if we have provided these attributes via the observer in $defaultData
     if (false === isset($defaultData['ordered_qty']) && false === isset($defaultData['stock_qty'])) {
         $ordered_qty = Mage::getResourceModel('reports/product_collection')->addOrderedQty()->addAttributeToFilter('sku', $product->getSku())->setOrder('ordered_qty', 'desc')->getFirstItem()->ordered_qty;
         $customData['ordered_qty'] = (int) $ordered_qty;
         $customData['stock_qty'] = (int) Mage::getModel('cataloginventory/stock_item')->loadByProduct($product)->getQty();
         if ($product->getTypeId() == 'configurable' || $product->getTypeId() == 'grouped') {
             $ordered_qty = 0;
             $stock_qty = 0;
             foreach ($sub_products as $sub_product) {
                 $stock_qty += (int) Mage::getModel('cataloginventory/stock_item')->loadByProduct($sub_product)->getQty();
                 $ordered_qty += (int) $this->getReportForProduct($sub_product)->ordered_qty;
             }
             $customData['ordered_qty'] = $ordered_qty;
             $customData['stock_qty'] = $stock_qty;
         }
         if ($this->isAttributeEnabled($additionalAttributes, 'ordered_qty') == false) {
             unset($customData['ordered_qty']);
         }
         if ($this->isAttributeEnabled($additionalAttributes, 'stock_qty') == false) {
             unset($customData['stock_qty']);
         }
     }
     if ($this->isAttributeEnabled($additionalAttributes, 'rating_summary')) {
         $summaryData = Mage::getModel('review/review_summary')->setStoreId($product->getStoreId())->load($product->getId());
         if ($summaryData['rating_summary']) {
             $customData['rating_summary'] = $summaryData['rating_summary'];
         }
     }
     foreach ($additionalAttributes as $attribute) {
         if (isset($customData[$attribute['attribute']])) {
             continue;
         }
         $value = $product->getData($attribute['attribute']);
         $attribute_ressource = $product->getResource()->getAttribute($attribute['attribute']);
         if ($attribute_ressource) {
             $attribute_ressource = $attribute_ressource->setStoreId($product->getStoreId());
             if ($value === null) {
                 /** Get values as array in children */
                 if ($product->getTypeId() == 'configurable' || $product->getTypeId() == 'grouped') {
                     $values = array();
                     foreach ($sub_products as $sub_product) {
                         $sub_product = Mage::getModel('catalog/product')->load($sub_product->getId());
                         $value = $sub_product->getData($attribute['attribute']);
                         if ($value) {
                             $value_text = $sub_product->getAttributeText($attribute['attribute']);
                             if ($value_text) {
                                 $values[] = $value_text;
                             } else {
                                 $values[] = $attribute_ressource->getFrontend()->getValue($sub_product);
                             }
                         }
                     }
                     if (count($values) > 0) {
                         $customData[$attribute['attribute']] = $values;
                     }
                 }
             } else {
                 $value_text = $product->getAttributeText($attribute['attribute']);
                 if ($value_text) {
                     $value = $value_text;
                 } else {
                     $attribute_ressource = $attribute_ressource->setStoreId($product->getStoreId());
                     $value = $attribute_ressource->getFrontend()->getValue($product);
                 }
                 if ($value) {
                     $customData[$attribute['attribute']] = $value;
                 }
             }
         }
     }
     $customData = array_merge($customData, $defaultData);
     $customData['type_id'] = $product->getTypeId();
     $this->castProductObject($customData);
     return $customData;
 }
 /**
  * Remove "child_run.php/" from product URLs. This gets around some weirdness in
  * core Magento that adds SCRIPT_NAME to generated URLs.
  *
  * @param Mage_Catalog_Model_Product $product
  * @return string
  */
 public function getCleanProductUrl(Mage_Catalog_Model_Product $product)
 {
     return str_replace("child_run.php/", "", $product->getProductUrl());
 }
 /**
  * @param Mage_Core_Controller_Varien_Action
  * @param Mage_Catalog_Model_Product
  */
 protected function redirectToProductUrl(Mage_Core_Controller_Varien_Action $controllerAction, Mage_Catalog_Model_Product $product)
 {
     $controllerAction->getResponse()->setRedirect($product->getProductUrl());
 }
 /**
  * @param Mage_Catalog_Model_Product $product
  * @return array
  */
 public function getProductData(Mage_Catalog_Model_Product $product)
 {
     $data = array('id' => $product->getId(), 'url' => $product->getProductUrl(), 'imageUrl' => (string) Mage::helper('catalog/image')->init($product, 'image')->resize(265), 'thumbnailUrl' => (string) Mage::helper('catalog/image')->init($product, 'thumbnail')->resize(75, 75), 'name' => $product->getName(), 'unitPrice' => (double) $product->getPrice(), 'unitSalePrice' => (double) $product->getFinalPrice(), 'currency' => $this->_getCurrency(), 'description' => strip_tags($product->getShortDescription()), 'skuCode' => $product->getSku());
     $data['stock'] = (int) Mage::getModel('cataloginventory/stock_item')->loadByProduct($product)->getQty();
     $catIndex = $catNames = array();
     $limit = 2;
     $k = 0;
     foreach ($product->getCategoryIds() as $catId) {
         if (++$k > $limit) {
             break;
         }
         if (!isset($catIndex[$catId])) {
             $catIndex[$catId] = Mage::getModel('catalog/category')->load($catId);
         }
         $catNames[] = $catIndex[$catId]->getName();
     }
     if (isset($catNames[0])) {
         $data['category'] = $catNames[0];
     }
     if (isset($catNames[1])) {
         $data['subcategory'] = $catNames[1];
     }
     return $data;
 }
 public function getObject(Mage_Catalog_Model_Product $product)
 {
     $type = $this->config->getMappedProductType($product->getTypeId());
     $this->logger->start('CREATE RECORD ' . $product->getId() . ' ' . $this->logger->getStoreName($product->storeId));
     $this->logger->log('Product type (' . $product->getTypeId() . ', mapped to: ' . $type . ')');
     $defaultData = array();
     $transport = new Varien_Object($defaultData);
     Mage::dispatchEvent('algolia_product_index_before', array('product' => $product, 'custom_data' => $transport));
     $defaultData = $transport->getData();
     $defaultData = is_array($defaultData) ? $defaultData : explode('|', $defaultData);
     $visibility = (int) $product->getVisibility();
     /** @var Mage_Catalog_Model_Product_Visibility $catalogProductVisibility */
     $catalogProductVisibility = Mage::getSingleton('catalog/product_visibility');
     $visibleInCatalog = $catalogProductVisibility->getVisibleInCatalogIds();
     $visibleInSearch = $catalogProductVisibility->getVisibleInSearchIds();
     $customData = array('objectID' => $product->getId(), 'name' => $product->getName(), 'url' => $product->getProductUrl(), 'visibility_search' => (int) in_array($visibility, $visibleInSearch), 'visibility_catalog' => (int) in_array($visibility, $visibleInCatalog));
     $additionalAttributes = $this->config->getProductAdditionalAttributes($product->getStoreId());
     $groups = null;
     if ($this->isAttributeEnabled($additionalAttributes, 'description')) {
         $customData['description'] = $product->getDescription();
     }
     $categories = array();
     $categories_with_path = array();
     $_categoryIds = $product->getCategoryIds();
     if (is_array($_categoryIds) && count($_categoryIds) > 0) {
         $categoryCollection = Mage::getResourceModel('catalog/category_collection')->addAttributeToSelect('name')->addAttributeToFilter('entity_id', $_categoryIds)->addFieldToFilter('level', array('gt' => 1))->addIsActiveFilter();
         if ($this->config->showCatsNotIncludedInNavigation($product->getStoreId()) == false) {
             $categoryCollection->addAttributeToFilter('include_in_menu', '1');
         }
         $rootCat = Mage::app()->getStore($product->getStoreId())->getRootCategoryId();
         /** @var Mage_Catalog_Model_Category $category */
         foreach ($categoryCollection as $category) {
             // Check and skip all categories that is not
             // in the path of the current store.
             $path = $category->getPath();
             $path_parts = explode('/', $path);
             if (isset($path_parts[1]) && $path_parts[1] != $rootCat) {
                 continue;
             }
             $categoryName = $category->getName();
             if ($categoryName) {
                 $categories[] = $categoryName;
             }
             $category->getUrlInstance()->setStore($product->getStoreId());
             $path = array();
             foreach ($category->getPathIds() as $treeCategoryId) {
                 $name = $this->getCategoryName($treeCategoryId, $product->getStoreId());
                 if ($name) {
                     $path[] = $name;
                 }
             }
             $categories_with_path[] = $path;
         }
     }
     if ($this->config->indexWholeCategoryTree($product->getStoreId())) {
         foreach ($categories_with_path as $result) {
             for ($i = count($result) - 1; $i > 0; $i--) {
                 $categories_with_path[] = array_slice($result, 0, $i);
             }
         }
     }
     $categories_with_path = array_intersect_key($categories_with_path, array_unique(array_map('serialize', $categories_with_path)));
     $categories_hierarchical = array();
     $mainCategories = array();
     $level_name = 'level';
     /** @var array $category */
     foreach ($categories_with_path as $category) {
         $categoriesCount = count($category);
         for ($i = 0; $i < $categoriesCount; $i++) {
             if (isset($categories_hierarchical[$level_name . $i]) === false) {
                 $categories_hierarchical[$level_name . $i] = array();
             }
             $mainCategories[$level_name . $i][] = $category[$i];
             if ($this->config->indexWholeCategoryTree($product->getStoreId())) {
                 $categories_hierarchical[$level_name . $i][] = implode(' /// ', array_slice($category, 0, $i + 1));
             } else {
                 if ($i === $categoriesCount - 1) {
                     $categories_hierarchical[$level_name . $i][] = implode(' /// ', $category);
                 }
             }
         }
     }
     foreach ($categories_hierarchical as &$level) {
         $level = array_values(array_unique($level));
     }
     foreach ($mainCategories as &$level) {
         $level = array_values(array_unique($level));
     }
     foreach ($categories_with_path as &$category) {
         $category = implode(' /// ', $category);
     }
     $customData['categories'] = $categories_hierarchical;
     $customData['categories_without_path'] = $categories;
     if ($this->isAttributeEnabled($additionalAttributes, 'main_categories')) {
         $customData['main_categories'] = $mainCategories;
     }
     /** @var Algolia_Algoliasearch_Helper_Image $imageHelper */
     $imageHelper = Mage::helper('algoliasearch/image');
     if (false === isset($defaultData['thumbnail_url'])) {
         /** @var Algolia_Algoliasearch_Helper_Image $thumb */
         $thumb = $imageHelper->init($product, 'thumbnail')->resize(75, 75);
         try {
             $customData['thumbnail_url'] = $thumb->toString();
         } catch (\Exception $e) {
             $this->logger->log($e->getMessage());
             $this->logger->log($e->getTraceAsString());
             $placeholderUrl = Mage::getDesign()->getSkinUrl($thumb->getPlaceholder());
             $customData['thumbnail_url'] = $imageHelper->removeProtocol($placeholderUrl);
         }
     }
     if (false === isset($defaultData['image_url'])) {
         /** @var Algolia_Algoliasearch_Helper_Image $image */
         $image = $imageHelper->init($product, $this->config->getImageType())->resize($this->config->getImageWidth(), $this->config->getImageHeight());
         try {
             $customData['image_url'] = $image->toString();
         } catch (\Exception $e) {
             $this->logger->log($e->getMessage());
             $this->logger->log($e->getTraceAsString());
             $placeholderUrl = Mage::getDesign()->getSkinUrl($image->getPlaceholder());
             $customData['image_url'] = $imageHelper->removeProtocol($placeholderUrl);
         }
         if ($this->isAttributeEnabled($additionalAttributes, 'media_gallery')) {
             $product->load('media_gallery');
             $customData['media_gallery'] = array();
             foreach ($product->getMediaGalleryImages() as $image) {
                 $customData['media_gallery'][] = $imageHelper->removeProtocol($image->getUrl());
             }
         }
     }
     $sub_products = null;
     $ids = null;
     if ($type == 'configurable' || $type == 'grouped' || $type == 'bundle') {
         if ($type == 'bundle') {
             $ids = array();
             $selection = $product->getTypeInstance(true)->getSelectionsCollection($product->getTypeInstance(true)->getOptionsIds($product), $product);
             foreach ($selection as $option) {
                 $ids[] = $option->product_id;
             }
         }
         if ($type == 'configurable' || $type == 'grouped') {
             $ids = $product->getTypeInstance(true)->getChildrenIds($product->getId());
             $ids = call_user_func_array('array_merge', $ids);
         }
         if (count($ids)) {
             $collection = $this->getProductCollectionQuery($product->getStoreId(), $ids, false);
             $sub_products = $collection->load();
         } else {
             $sub_products = array();
         }
     }
     if (false === isset($defaultData['in_stock'])) {
         $stockItem = $product->getStockItem();
         $customData['in_stock'] = (int) $stockItem->getIsInStock();
     }
     // skip default calculation if we have provided these attributes via the observer in $defaultData
     if (false === isset($defaultData['ordered_qty']) && $this->isAttributeEnabled($additionalAttributes, 'ordered_qty')) {
         $customData['ordered_qty'] = (int) $product->getOrderedQty();
     }
     if (false === isset($defaultData['total_ordered']) && $this->isAttributeEnabled($additionalAttributes, 'total_ordered')) {
         $customData['total_ordered'] = (int) $product->getTotalOrdered();
     }
     if (false === isset($defaultData['stock_qty']) && $this->isAttributeEnabled($additionalAttributes, 'stock_qty')) {
         $customData['stock_qty'] = (int) $product->getStockQty();
     }
     if (Mage::helper('core')->isModuleEnabled('Mage_Review')) {
         if ($this->isAttributeEnabled($additionalAttributes, 'rating_summary')) {
             $customData['rating_summary'] = (int) $product->getRatingSummary();
         }
     }
     $this->setNoAttributes($additionalAttributes);
     foreach ($additionalAttributes as $attribute) {
         $attribute_name = $attribute['attribute'];
         if (isset($customData[$attribute_name])) {
             continue;
         }
         $value = $product->getData($attribute_name);
         /** @var Mage_Catalog_Model_Resource_Eav_Attribute $attribute_resource */
         $attribute_resource = $product->getResource()->getAttribute($attribute_name);
         if ($attribute_resource) {
             $attribute_resource->setStoreId($product->getStoreId());
             /**
              * if $value is missing or if the attribute is SKU,
              * use values from child products.
              */
             if (($value === null || 'sku' == $attribute_name) && ($type == 'configurable' || $type == 'grouped' || $type == 'bundle')) {
                 if ($value === null) {
                     $values = array();
                 } else {
                     $values = array($this->getValueOrValueText($product, $attribute_name, $attribute_resource));
                 }
                 $all_sub_products_out_of_stock = true;
                 if ($type !== 'bundle' || in_array($attribute_name, $this->excludedAttrsFromBundledProducts, true) === false) {
                     foreach ($sub_products as $sub_product) {
                         $isInStock = (int) $sub_product->getStockItem()->getIsInStock();
                         if ($isInStock == false && $this->config->indexOutOfStockOptions($product->getStoreId()) == false) {
                             continue;
                         }
                         $all_sub_products_out_of_stock = false;
                         $value = $sub_product->getData($attribute_name);
                         if ($value) {
                             $values[] = $this->getValueOrValueText($sub_product, $attribute_name, $attribute_resource);
                         }
                     }
                 }
                 if (is_array($values) && count($values) > 0) {
                     $customData[$attribute_name] = array_values(array_unique($values, SORT_REGULAR));
                 }
                 // Set main product out of stock if all
                 // sub-products are out of stock.
                 if ($customData['in_stock'] && $all_sub_products_out_of_stock) {
                     $customData['in_stock'] = 0;
                 }
             } elseif (!is_array($value)) {
                 $value = $this->getValueOrValueText($product, $attribute_name, $attribute_resource);
             }
             if ($value && !isset($customData[$attribute_name])) {
                 $customData[$attribute_name] = $value;
             }
         }
     }
     $msrpEnabled = method_exists(Mage::helper('catalog'), 'canApplyMsrp') ? (bool) Mage::helper('catalog')->canApplyMsrp($product) : false;
     if (false === $msrpEnabled) {
         $this->handlePrice($product, $sub_products, $customData);
     } else {
         unset($customData['price']);
     }
     $transport = new Varien_Object($customData);
     Mage::dispatchEvent('algolia_subproducts_index', array('custom_data' => $transport, 'sub_products' => $sub_products));
     $customData = $transport->getData();
     $customData = array_merge($customData, $defaultData);
     $customData['type_id'] = $type;
     $this->castProductObject($customData);
     $customData = $this->clearNoValues($customData);
     $this->logger->stop('CREATE RECORD ' . $product->getId() . ' ' . $this->logger->getStoreName($product->storeId));
     return $customData;
 }
 public function getProductEntity(Mage_Catalog_Model_Product $product, $storeId, $includeExtras = true)
 {
     $result = array();
     $result['entity_id'] = $product->getEntityId();
     $result['sku'] = $product->getSku();
     $result['name'] = $product->getName();
     $result['price'] = $product->getPrice();
     $result['special_price'] = $product->getSpecialPrice();
     $result['special_from_date'] = $product->getSpecialFromDate();
     $result['special_to_date'] = $product->getSpecialToDate();
     $result['cost'] = $product->getCost();
     $result['description'] = $product->getDescription();
     $result['short_description'] = $product->getShortDescription();
     $result['weight'] = $product->getWeight();
     if ($product->isVisibleInSiteVisibility()) {
         $prodUrlStr = $product->getProductUrl();
         $prodUrl = Mage::getSingleton('core/url')->parseUrl($prodUrlStr);
         $result['url_path'] = substr($prodUrl->getPath(), 1);
     }
     $parentProduct = $this->_getParentProduct($product);
     if ($parentProduct != null) {
         $result['parent_id'] = $parentProduct->getEntityId();
         $result['parent_sku'] = $parentProduct->getSku();
         if (!$product->isVisibleInSiteVisibility()) {
             $result['name'] = $parentProduct->getName();
             if ($parentProduct->isVisibleInSiteVisibility()) {
                 $prodUrlStr = $parentProduct->getProductUrl();
                 $prodUrl = Mage::getSingleton('core/url')->parseUrl($prodUrlStr);
                 $result['url_path'] = substr($prodUrl->getPath(), 1);
             }
         }
         if ($includeExtras && Mage_Catalog_Model_Product_Type::TYPE_CONFIGURABLE == $parentProduct->getTypeId()) {
             $result['purchasable'] = $this->_isPurchasable($product, $parentProduct);
             $attributes = $parentProduct->getTypeInstance(true)->getUsedProductAttributes($parentProduct);
             foreach ($attributes as $attribute) {
                 if (!array_key_exists('configurable_attributes', $result)) {
                     $result['configurable_attributes'] = array();
                 }
                 $attr = array();
                 $attr['attribute_name'] = $attribute->getFrontend()->getLabel();
                 $attr['value'] = $product->getAttributeText($attribute->getAttributeCode());
                 $result['configurable_attributes'][] = $attr;
             }
         }
     }
     if (!isset($result['purchasable'])) {
         $result['purchasable'] = $this->_isPurchasable($product);
     }
     $images = $this->_getProductImages($product);
     if (isset($images['image'])) {
         $result['image'] = $images['image'];
     }
     if (isset($images['small_image'])) {
         $result['small_image'] = $images['small_image'];
     }
     if (isset($images['thumbnail'])) {
         $result['thumbnail'] = $images['thumbnail'];
     }
     if ($includeExtras) {
         // Metas
         $metas = $this->_getMetas($storeId, $product, $parentProduct);
         if ($metas != null) {
             //if(isset($metas['meta1'])) $result['meta1'] = $metas['meta1'];
             //if(isset($metas['meta2'])) $result['meta2'] = $metas['meta2'];
             if (isset($metas['meta3'])) {
                 $result['meta3'] = $metas['meta3'];
             }
             if (isset($metas['meta4'])) {
                 $result['meta4'] = $metas['meta4'];
             }
             if (isset($metas['meta5'])) {
                 $result['meta5'] = $metas['meta5'];
             }
         }
         // Brand and Category
         $brandAndCategoryProduct = !$parentProduct || $product->isVisibleInSiteVisibility() ? $product : $parentProduct;
         $setSettings = $this->_getProductAttributeSetSettings($brandAndCategoryProduct);
         if ($setSettings['brandAttribute'] != null) {
             $result['brand'] = $brandAndCategoryProduct->getAttributeText($setSettings['brandAttribute']);
         }
         if ($setSettings['catFromMagento']) {
             $cats = $this->_getCategoryInformation($storeId, $brandAndCategoryProduct);
             if (isset($cats['category'])) {
                 $result['category'] = $cats['category'];
             }
             if (isset($cats['sub_category'])) {
                 $result['sub_category'] = $cats['sub_category'];
             }
         } else {
             if ($setSettings['catFromAttributes']) {
                 if ($setSettings['categoryAttribute'] != null) {
                     $result['category'] = $brandAndCategoryProduct->getAttributeText($setSettings['categoryAttribute']);
                 }
                 if ($setSettings['subcategoryAttribute'] != null) {
                     $result['sub_category'] = $brandAndCategoryProduct->getAttributeText($setSettings['subcategoryAttribute']);
                 }
             }
         }
         // Inventory
         $result['in_stock'] = $product->isAvailable() ? "true" : "false";
         $stockItem = $product->getStockItem();
         if ($stockItem) {
             $result['qty_on_hand'] = $stockItem->getStockQty();
         }
         // Related Products
         $result['links'] = $this->_getProductLinks($product);
     }
     $result['type'] = $product->getTypeId();
     return $result;
 }
 public function getObject(Mage_Catalog_Model_Product $product)
 {
     $type = $this->config->getMappedProductType($product->getTypeId());
     $this->logger->start('CREATE RECORD ' . $product->getId() . ' ' . $this->logger->getStoreName($product->storeId));
     $this->logger->log('Product type (' . $product->getTypeId() . ', mapped to: ' . $type . ')');
     $defaultData = array();
     $transport = new Varien_Object($defaultData);
     Mage::dispatchEvent('algolia_product_index_before', array('product' => $product, 'custom_data' => $transport));
     $defaultData = $transport->getData();
     $defaultData = is_array($defaultData) ? $defaultData : explode("|", $defaultData);
     $customData = array('objectID' => $product->getId(), 'name' => $product->getName(), 'url' => $product->getProductUrl());
     $additionalAttributes = $this->config->getProductAdditionalAttributes($product->getStoreId());
     $groups = null;
     if ($this->isAttributeEnabled($additionalAttributes, 'description')) {
         $customData['description'] = $product->getDescription();
     }
     $categories = array();
     $categories_with_path = array();
     $_categoryIds = $product->getCategoryIds();
     if (is_array($_categoryIds) && count($_categoryIds) > 0) {
         $categoryCollection = Mage::getResourceModel('catalog/category_collection')->addAttributeToSelect('name')->addAttributeToFilter('entity_id', $_categoryIds)->addFieldToFilter('level', array('gt' => 1))->addIsActiveFilter();
         foreach ($categoryCollection as $category) {
             $categoryName = $category->getName();
             if ($categoryName) {
                 $categories[] = $categoryName;
             }
             $category->getUrlInstance()->setStore($product->getStoreId());
             $path = array();
             foreach ($category->getPathIds() as $treeCategoryId) {
                 $name = $this->getCategoryName($treeCategoryId, $product->getStoreId());
                 if ($name) {
                     $path[] = $name;
                 }
             }
             $categories_with_path[] = $path;
         }
     }
     foreach ($categories_with_path as $result) {
         for ($i = count($result) - 1; $i > 0; $i--) {
             $categories_with_path[] = array_slice($result, 0, $i);
         }
     }
     $categories_with_path = array_intersect_key($categories_with_path, array_unique(array_map('serialize', $categories_with_path)));
     $categories_hierarchical = array();
     $level_name = 'level';
     foreach ($categories_with_path as $category) {
         for ($i = 0; $i < count($category); $i++) {
             if (isset($categories_hierarchical[$level_name . $i]) === false) {
                 $categories_hierarchical[$level_name . $i] = array();
             }
             $categories_hierarchical[$level_name . $i][] = implode(' /// ', array_slice($category, 0, $i + 1));
         }
     }
     foreach ($categories_hierarchical as &$level) {
         $level = array_values(array_unique($level));
     }
     foreach ($categories_with_path as &$category) {
         $category = implode(' /// ', $category);
     }
     $customData['categories'] = $categories_hierarchical;
     $customData['categories_without_path'] = $categories;
     if (false === isset($defaultData['thumbnail_url'])) {
         $thumb = Mage::helper('algoliasearch/image')->init($product, 'thumbnail')->resize(75, 75);
         try {
             $customData['thumbnail_url'] = $thumb->toString();
             $customData['thumbnail_url'] = str_replace(array('https://', 'http://'), '//', $customData['thumbnail_url']);
         } catch (\Exception $e) {
             $this->logger->log($e->getMessage());
             $this->logger->log($e->getTraceAsString());
             $customData['thumbnail_url'] = str_replace(array('https://', 'http://'), '//', Mage::getDesign()->getSkinUrl($thumb->getPlaceholder()));
         }
     }
     if (false === isset($defaultData['image_url'])) {
         $image = Mage::helper('algoliasearch/image')->init($product, $this->config->getImageType())->resize($this->config->getImageWidth(), $this->config->getImageHeight());
         try {
             $customData['image_url'] = $image->toString();
             $customData['image_url'] = str_replace(array('https://', 'http://'), '//', $customData['image_url']);
         } catch (\Exception $e) {
             $this->logger->log($e->getMessage());
             $this->logger->log($e->getTraceAsString());
             $customData['image_url'] = str_replace(array('https://', 'http://'), '//', Mage::getDesign()->getSkinUrl($image->getPlaceholder()));
         }
         if ($this->isAttributeEnabled($additionalAttributes, 'media_gallery')) {
             $product->load('media_gallery');
             $customData['media_gallery'] = array();
             foreach ($product->getMediaGalleryImages() as $image) {
                 $customData['media_gallery'][] = str_replace(array('https://', 'http://'), '//', $image->getUrl());
             }
         }
     }
     $sub_products = null;
     $ids = null;
     if ($type == 'configurable' || $type == 'grouped' || $type == 'bundle') {
         if ($type == 'bundle') {
             $ids = array();
             $selection = $product->getTypeInstance(true)->getSelectionsCollection($product->getTypeInstance(true)->getOptionsIds($product), $product);
             foreach ($selection as $option) {
                 $ids[] = $option->product_id;
             }
         }
         if ($type == 'configurable' || $type == 'grouped') {
             $ids = $product->getTypeInstance(true)->getChildrenIds($product->getId());
         }
         if (count($ids)) {
             $sub_products = $this->getProductCollectionQuery($product->getStoreId(), $ids, false)->load();
         } else {
             $sub_products = array();
         }
     }
     if (false === isset($defaultData['in_stock'])) {
         $stockItem = $product->getStockItem();
         $customData['in_stock'] = (int) $stockItem->getIsInStock();
     }
     // skip default calculation if we have provided these attributes via the observer in $defaultData
     if (false === isset($defaultData['ordered_qty']) && $this->isAttributeEnabled($additionalAttributes, 'ordered_qty')) {
         $customData['ordered_qty'] = (int) $product->getOrderedQty();
     }
     if (false === isset($defaultData['stock_qty']) && $this->isAttributeEnabled($additionalAttributes, 'stock_qty')) {
         $customData['stock_qty'] = (int) $product->getStockQty();
     }
     if (Mage::helper('core')->isModuleEnabled('Mage_Review')) {
         if ($this->isAttributeEnabled($additionalAttributes, 'rating_summary')) {
             $customData['rating_summary'] = (int) $product->getRatingSummary();
         }
     }
     foreach ($additionalAttributes as $attribute) {
         if (isset($customData[$attribute['attribute']])) {
             continue;
         }
         $value = $product->getData($attribute['attribute']);
         $attribute_ressource = $product->getResource()->getAttribute($attribute['attribute']);
         if ($attribute_ressource) {
             $attribute_ressource = $attribute_ressource->setStoreId($product->getStoreId());
             if ($value === null) {
                 /** Get values as array in children */
                 if ($type == 'configurable' || $type == 'grouped' || $type == 'bundle') {
                     $values = array();
                     foreach ($sub_products as $sub_product) {
                         $stock = (int) $sub_product->getStockItem()->getIsInStock();
                         if ($stock == false) {
                             continue;
                         }
                         $value = $sub_product->getData($attribute['attribute']);
                         if ($value) {
                             $value_text = $sub_product->getAttributeText($attribute['attribute']);
                             if ($value_text) {
                                 $values[] = $value_text;
                             } else {
                                 $values[] = $attribute_ressource->getFrontend()->getValue($sub_product);
                             }
                         }
                     }
                     if (is_array($values) && count($values) > 0) {
                         $customData[$attribute['attribute']] = array_values(array_unique($values));
                     }
                 }
             } else {
                 $value_text = $product->getAttributeText($attribute['attribute']);
                 if ($value_text) {
                     $value = $value_text;
                 } else {
                     $attribute_ressource = $attribute_ressource->setStoreId($product->getStoreId());
                     $value = $attribute_ressource->getFrontend()->getValue($product);
                 }
                 if ($value) {
                     $customData[$attribute['attribute']] = $value;
                 }
             }
         }
     }
     $this->handlePrice($product, $sub_products, $customData);
     $transport = new Varien_Object($customData);
     Mage::dispatchEvent('algolia_subproducts_index', array('custom_data' => $transport, 'sub_products' => $sub_products));
     $customData = $transport->getData();
     $customData = array_merge($customData, $defaultData);
     $customData['type_id'] = $type;
     $this->castProductObject($customData);
     $this->logger->stop('CREATE RECORD ' . $product->getId() . ' ' . $this->logger->getStoreName($product->storeId));
     return $customData;
 }
Exemple #20
0
 protected function _getOfferUrl()
 {
     //        return Mage::getModel('core/url')->setStore($this->_storeId)->getUrl('catalog/product/view', array('id'=>$this->_product->getId()));
     return $this->_product->getProductUrl();
 }
 /**
  * @param Mage_Catalog_Model_Product $product
  * @return array
  */
 public function getProductData(Mage_Catalog_Model_Product $product)
 {
     $id = $product->getId();
     if (!$this->helper()->shouldUseRealProductId()) {
         $id = $product->getSku() ? $product->getSku() : md5($id);
     }
     $data = array('id' => $id, 'url' => $product->getProductUrl(), 'name' => $product->getName(), 'unit_price' => (double) $product->getPrice(), 'unit_sale_price' => (double) $product->getFinalPrice(), 'currency' => $this->_getCurrency(), 'description' => strip_tags($product->getShortDescription()), 'sku_code' => $product->getSku());
     if ($this->helper()->shouldShowProductStockInfo()) {
         $data['stock'] = (int) Mage::getModel('cataloginventory/stock_item')->loadByProduct($product)->getQty();
     }
     $catIndex = $catNames = array();
     $limit = 2;
     $k = 0;
     foreach ($product->getCategoryIds() as $catId) {
         if (++$k > $limit) {
             break;
         }
         if (!isset($catIndex[$catId])) {
             $catIndex[$catId] = Mage::getModel('catalog/category')->load($catId);
         }
         $catNames[] = $catIndex[$catId]->getName();
     }
     if (isset($catNames[0])) {
         $data['category'] = $catNames[0];
     }
     if (isset($catNames[1])) {
         $data['subcategory'] = $catNames[1];
     }
     return $data;
 }
Exemple #22
0
 /**
  * Add URLs to the queue by product model
  *
  * @param Mage_Catalog_Model_Product $product
  * @return int
  */
 public function addProductToCrawlerQueue($product)
 {
     $productUrls = array();
     $origStore = Mage::app()->getStore();
     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), '/');
         }
     }
     Mage::app()->setCurrentStore($origStore);
     return $this->addUrlsToCrawlerQueue($productUrls);
 }
 /**
  * Retrieve the relative product URL
  *
  * @param Mage_Catalog_Model_Product $product Product
  *
  * @return string
  */
 public function getProductUrl(Mage_Catalog_Model_Product $product)
 {
     /* @var Mage_Core_Model_Url $urlParser */
     $urlParser = Mage::getSingleton('core/url');
     $urlParser->parseUrl($product->getProductUrl());
     return substr($urlParser->getPath(), 1);
 }
 public function __construct(Mage_Catalog_Model_Product $product)
 {
     $this->id = $product->getId();
     $this->sku = $product->getSku();
     $this->name = $product->getName();
     $statuses = Mage::getModel('catalog/product_status')->getOptionArray();
     $this->status = $statuses[$product->getStatus()];
     $options = Mage::getModel('catalog/product_visibility')->getOptionArray();
     $this->visibility = $options[$product->getVisibility()];
     $this->price = (double) number_format($product->getPrice(), 2, '.', '');
     $this->specialPrice = (double) number_format($product->getSpecialPrice(), 2, '.', '');
     $this->url = $product->getProductUrl();
     $this->imagePath = Mage::getModel('catalog/product_media_config')->getMediaUrl($product->getSmallImage());
     $stock = Mage::getModel('cataloginventory/stock_item')->loadByProduct($product);
     $this->stock = (double) number_format($stock->getQty(), 2, '.', '');
     $short_description = $product->getShortDescription();
     //limit short description
     if (strlen($short_description) > 250) {
         $short_description = substr($short_description, 0, 250);
     }
     $this->short_description = $short_description;
     //category data
     $count = 0;
     $categoryCollection = $product->getCategoryCollection()->addNameToResult();
     foreach ($categoryCollection as $cat) {
         $this->categories[$count]['Id'] = $cat->getId();
         $this->categories[$count]['Name'] = $cat->getName();
         $count++;
     }
     //website data
     $count = 0;
     $websiteIds = $product->getWebsiteIds();
     foreach ($websiteIds as $websiteId) {
         $website = Mage::app()->getWebsite($websiteId);
         $this->websites[$count]['Id'] = $website->getId();
         $this->websites[$count]['Name'] = $website->getName();
         $count++;
     }
     //bundle product options
     if ($product->getTypeId() == Mage_Catalog_Model_Product_Type::TYPE_BUNDLE) {
         $optionCollection = $product->getTypeInstance()->getOptionsCollection();
         $selectionCollection = $product->getTypeInstance()->getSelectionsCollection($product->getTypeInstance()->getOptionsIds());
         $options = $optionCollection->appendSelections($selectionCollection);
         foreach ($options as $option) {
             $count = 0;
             $title = str_replace(' ', '', $option->getDefaultTitle());
             $selections = $option->getSelections();
             $sOptions = array();
             foreach ($selections as $selection) {
                 $sOptions[$count]['name'] = $selection->getName();
                 $sOptions[$count]['sku'] = $selection->getSku();
                 $sOptions[$count]['id'] = $selection->getProductId();
                 $sOptions[$count]['price'] = (double) number_format($selection->getPrice(), 2, '.', '');
                 $count++;
             }
             $this->{$title} = $sOptions;
         }
     }
     //configurable product options
     if ($product->getTypeId() == Mage_Catalog_Model_Product_Type::TYPE_CONFIGURABLE) {
         $productAttributeOptions = $product->getTypeInstance(true)->getConfigurableAttributesAsArray($product);
         foreach ($productAttributeOptions as $productAttribute) {
             $count = 0;
             $label = strtolower(str_replace(' ', '', $productAttribute['label']));
             $options = array();
             foreach ($productAttribute['values'] as $attribute) {
                 $options[$count]['option'] = $attribute['default_label'];
                 $options[$count]['price'] = (double) number_format($attribute['pricing_value'], 2, '.', '');
                 $count++;
             }
             $this->{$label} = $options;
         }
     }
 }
 /**
  * Get product request path
  *
  * @param Mage_Catalog_Model_Product $product
  * @return string
  * @deprecated since 1.13.0.2
  */
 protected function _getProductRequestPath(Mage_Catalog_Model_Product $product)
 {
     /**
      * Initialize request_path value
      */
     $product->getProductUrl();
     /** @var $helper Enterprise_Catalog_Helper_Data */
     $helper = $this->_factory->getHelper('enterprise_catalog');
     return $helper->getProductRequestPath($product->getRequestPath(), $product->getStoreId());
 }
Exemple #26
0
 /**
  * Adding grouped product to cart
  *
  * @param   Mage_Catalog_Model_Product $product
  * @return  Mage_Checkout_Model_Cart
  */
 protected function _addGroupedProduct(Mage_Catalog_Model_Product $product)
 {
     $groupedProducts = $product->getGroupedProducts();
     if (!is_array($groupedProducts) || empty($groupedProducts)) {
         $this->getCheckoutSession()->setRedirectUrl($product->getProductUrl());
         $this->getCheckoutSession()->setUseNotice(true);
         Mage::throwException(Mage::helper('checkout')->__('Please specify the product option(s)'));
     }
     $added = false;
     foreach ($product->getTypeInstance()->getAssociatedProducts() as $subProduct) {
         if (isset($groupedProducts[$subProduct->getId()])) {
             $qty = $groupedProducts[$subProduct->getId()];
             if (!empty($qty)) {
                 $subProduct->setSuperProduct($product);
                 $this->getQuote()->addCatalogProduct($subProduct, $qty);
                 $added = true;
             }
         }
     }
     if (!$added) {
         Mage::throwException(Mage::helper('checkout')->__('Please specify the product(s) quantity'));
     }
     return $this;
 }
 public function getProductUrl(Mage_Catalog_Model_Product $product)
 {
     return substr(Mage::getSingleton('core/url')->parseUrl($product->getProductUrl())->getPath(), 1);
 }
Exemple #28
0
 /**
  * Function used to add product to queue
  * @param Mage_Catalog_Model_Product $product
  * @param Varien_Object $buyRequest
  * @param bool $isGroup
  * @return string
  */
 public function addProductToQueue($product, Varien_Object $buyRequest, $isGroup = false)
 {
     if ($this->hasMembership($product->getId())) {
         if ($isGroup) {
             $success = false;
             $url = $product->getProductUrl();
             foreach ($product->getTypeInstance(true)->getAssociatedProducts($product) as $iProduct) {
                 $collItem2 = Mage::getModel('payperrentals/rentalqueue')->getCollection()->addCustomerIdFilter(Mage::getSingleton('customer/session')->getCustomerId())->addSelectFilter('sendreturn_id="0"')->addProductIdFilter($iProduct->getId());
                 if ($collItem2->getSize() > 0) {
                     Mage::getSingleton('core/session')->addError(Mage::helper('payperrentals')->__('Product') . ' ' . $iProduct->getName() . ' ' . Mage::helper('payperrentals')->__('is already in queue'));
                     continue;
                 }
                 $collItem = Mage::getModel('payperrentals/rentalqueue')->getCollection()->addCustomerIdFilter(Mage::getSingleton('customer/session')->getCustomerId())->addSelectFilter('sendreturn_id="0"')->addOrderFilter('sort_order DESC');
                 if ($collItem->getSize() > 0) {
                     $sortMax = $collItem->getFirstItem()->getSortOrder() + 1;
                 } else {
                     $sortMax = 0;
                 }
                 /** @var $ex ITwebexperts_Payperrentals_Model_Rentalqueue */
                 $ex = Mage::getModel('payperrentals/rentalqueue')->setProductId($iProduct->getId())->setCustomerId(Mage::getSingleton('customer/session')->getCustomerId())->setStoreId(Mage::app()->getStore()->getId())->setSortOrder($sortMax)->setDateAdded(date('Y-m-d H:i:s'))->setCustomOptions(serialize($buyRequest));
                 try {
                     $ex->save();
                 } catch (Exception $_e) {
                     Mage::logException($_e);
                 }
                 Mage::getSingleton('core/session')->addSuccess(Mage::helper('payperrentals')->__('Product') . ' ' . $iProduct->getName() . ' ' . Mage::helper('payperrentals')->__('was added to queue'));
                 $success = true;
             }
             if ($success) {
                 $url = Mage::getUrl('payperrentals_front/customer_rentalqueue/index');
             }
             Mage::app()->getFrontController()->getResponse()->setRedirect($url)->sendResponse();
             exit;
         } else {
             $url = Mage::getUrl('payperrentals_front/customer_rentalqueue/index');
             $collItem2 = Mage::getModel('payperrentals/rentalqueue')->getCollection()->addCustomerIdFilter(Mage::getSingleton('customer/session')->getCustomerId())->addSelectFilter('sendreturn_id="0"')->addProductIdFilter($product->getId());
             if ($collItem2->getSize() > 0) {
                 Mage::getSingleton('core/session')->addError(Mage::helper('payperrentals')->__('Product is already in queue'));
                 $grouped_product_model = Mage::getModel('catalog/product_type_grouped');
                 $groupedParentId = $grouped_product_model->getParentIdsByChild($product->getId());
                 //todo check $groupedParentId[0] to be reservation product although in 99% will be. add checking type for parents and redirect if parent is reservation
                 if (isset($groupedParentId[0])) {
                     $product = Mage::getModel('catalog/product')->load($groupedParentId[0]);
                 }
                 Mage::app()->getFrontController()->getResponse()->setRedirect($product->getProductUrl())->sendResponse();
                 exit;
             }
             $collItem = Mage::getModel('payperrentals/rentalqueue')->getCollection()->addCustomerIdFilter(Mage::getSingleton('customer/session')->getCustomerId())->addSelectFilter('sendreturn_id="0"')->addOrderFilter('sort_order DESC');
             if ($collItem->getSize() > 0) {
                 $sortMax = $collItem->getFirstItem()->getSortOrder() + 1;
             } else {
                 $sortMax = 0;
             }
             /** @var $ex ITwebexperts_Payperrentals_Model_Rentalqueue */
             $ex = Mage::getModel('payperrentals/rentalqueue')->setProductId($product->getId())->setCustomerId(Mage::getSingleton('customer/session')->getCustomerId())->setStoreId(Mage::app()->getStore()->getId())->setSortOrder($sortMax)->setDateAdded(date('Y-m-d H:i:s'))->setCustomOptions(serialize($buyRequest));
             try {
                 $ex->save();
             } catch (Exception $_e) {
                 Mage::logException($_e);
             }
             Mage::getSingleton('core/session')->addSuccess(Mage::helper('payperrentals')->__('Product was added to queue'));
             Mage::app()->getFrontController()->getResponse()->setRedirect($url)->sendResponse();
             exit;
         }
     } else {
         Mage::getSingleton('core/session')->addError(Mage::helper('payperrentals')->__('You do not have a rental membership for this product or you are not logged in. Please either login ') . '<a href="' . Mage::getUrl('customer/account/login') . '">' . Mage::helper('payperrentals')->__('here') . '</a>, ' . Mage::helper('payperrentals')->__('or purchase a rental membership below.'));
         $_categoryId = Mage::helper('payperrentals/config')->getMembershipCategoryId(Mage::app()->getStore()->getId());
         if ($_categoryId) {
             $_category = Mage::getModel('catalog/category')->load($_categoryId);
             /** @method Mage_Catalog_Model_Category getUrl() */
             /** @var $_category Mage_Catalog_Model_Category */
             $_url = $_category->getUrl();
             Mage::app()->getFrontController()->getResponse()->setRedirect($_url)->sendResponse();
             exit;
         }
         return '';
     }
 }
Exemple #29
0
 /**
  * create deep link for the product
  *
  * @param Mage_Catalog_Model_Product $product
  * @param Mage_Catalog_Model_Product $parentItem
  *
  * @return string
  */
 public function getDeepLink($product, $parentItem = null)
 {
     $deepLink = $product->getProductUrl(true);
     if ($parentItem && $product->getVisibility() == Mage_Catalog_Model_Product_Visibility::VISIBILITY_NOT_VISIBLE) {
         $deepLink = $parentItem->getProductUrl(true);
     }
     return $this->parseUrl($deepLink);
 }
Exemple #30
0
 /**
  * @param Mage_Catalog_Model_Product $product
  *
  * @return array
  */
 public static function createFromProduct(Mage_Catalog_Model_Product $product)
 {
     $article = array('id' => $product->getId(), 'name' => $product->getName(), 'description' => substr($product->getDescription(), 0, 255), 'url' => $product->getProductUrl(), 'image_url' => $product->getImageUrl());
     return $article;
 }