/**
  * Return array of links
  *
  * @return array
  */
 public function getLinkData()
 {
     $linkArr = array();
     $prod = $this->getProduct();
     $prodType = $this->getProduct()->getTypeInstance(true);
     $links = $this->getProduct()->getTypeInstance(true)->getLinks($this->getProduct());
     $priceWebsiteScope = $this->getIsPriceWebsiteScope();
     foreach ($links as $item) {
         $tmpLinkItem = array('link_id' => $item->getId(), 'title' => $item->getTitle(), 'price' => $this->getCanReadPrice() ? $this->getPriceValue($item->getPrice()) : '', 'number_of_downloads' => $item->getNumberOfDownloads(), 'number_of_purchases' => $item->getNumberOfPurchases(), 'is_shareable' => $item->getIsShareable(), 'link_url' => $item->getLinkUrl(), 'link_type' => $item->getLinkType(), 'sample_file' => $item->getSampleFile(), 'sample_url' => $item->getSampleUrl(), 'sample_type' => $item->getSampleType(), 'sort_order' => $item->getSortOrder());
         $file = Mage::helper('downloadable/file')->getFilePath(Mage_Downloadable_Model_Link::getBasePath(), $item->getLinkFile());
         if ($item->getLinkFile() && !is_file($file)) {
             Mage::helper('core/file_storage_database')->saveFileToFilesystem($file);
         }
         if ($item->getLinkFile() && is_file($file)) {
             $name = '<a href="' . $this->getUrl('*/downloadable_product_edit/link', array('id' => $item->getId(), '_secure' => true)) . '">' . Mage::helper('downloadable/file')->getFileFromPathFile($item->getLinkFile()) . '</a>';
             $tmpLinkItem['file_save'] = array(array('file' => $item->getLinkFile(), 'name' => $name, 'size' => filesize($file), 'status' => 'old'));
         }
         $sampleFile = Mage::helper('downloadable/file')->getFilePath(Mage_Downloadable_Model_Link::getBaseSamplePath(), $item->getSampleFile());
         if ($item->getSampleFile() && is_file($sampleFile)) {
             $tmpLinkItem['sample_file_save'] = array(array('file' => $item->getSampleFile(), 'name' => Mage::helper('downloadable/file')->getFileFromPathFile($item->getSampleFile()), 'size' => filesize($sampleFile), 'status' => 'old'));
         }
         if ($item->getNumberOfDownloads() == '0') {
             $tmpLinkItem['is_unlimited'] = ' checked="checked"';
         }
         if ($this->getProduct()->getStoreId() && $item->getStoreTitle()) {
             $tmpLinkItem['store_title'] = $item->getStoreTitle();
         }
         if ($this->getProduct()->getStoreId() && $priceWebsiteScope) {
             $tmpLinkItem['website_price'] = $item->getWebsitePrice();
         }
         $linkArr[] = new Varien_Object($tmpLinkItem);
     }
     return $linkArr;
 }
예제 #2
0
 /**
  * Upload file controller action
  */
 public function uploadAction()
 {
     $type = $this->getRequest()->getParam('type');
     $tmpPath = '';
     if ($type == 'samples') {
         $tmpPath = Mage_Downloadable_Model_Sample::getBaseTmpPath();
     } elseif ($type == 'links') {
         $tmpPath = Mage_Downloadable_Model_Link::getBaseTmpPath();
     } elseif ($type == 'link_samples') {
         $tmpPath = Mage_Downloadable_Model_Link::getBaseSampleTmpPath();
     }
     $result = array();
     try {
         $uploader = new Mage_Core_Model_File_Uploader($type);
         $uploader->setAllowRenameFiles(true);
         $uploader->setFilesDispersion(true);
         $result = $uploader->save($tmpPath);
         if (isset($result['file'])) {
             $fullPath = rtrim($tmpPath, DS) . DS . ltrim($result['file'], DS);
             Mage::helper('Mage_Core_Helper_File_Storage_Database')->saveFile($fullPath);
         }
         $result['cookie'] = array('name' => session_name(), 'value' => $this->_getSession()->getSessionId(), 'lifetime' => $this->_getSession()->getCookieLifetime(), 'path' => $this->_getSession()->getCookiePath(), 'domain' => $this->_getSession()->getCookieDomain());
     } catch (Exception $e) {
         $result = array('error' => $e->getMessage(), 'errorcode' => $e->getCode());
     }
     $this->getResponse()->setBody(Mage::helper('Mage_Core_Helper_Data')->jsonEncode($result));
 }
 public function massImportAction()
 {
     $fotothekeIds = $this->getRequest()->getParam('fototheke');
     if (!is_array($fotothekeIds)) {
         Mage::getSingleton('adminhtml/session')->addError(Mage::helper('adminhtml')->__('Please select item(s)'));
     } else {
         try {
             $filePath = Mage_Downloadable_Model_Link::getBasePath();
             $i = 0;
             foreach ($fotothekeIds as $fotothekeId) {
                 $model = Mage::getModel('soapsync/ibramssync');
                 $added = $model->getCollection()->addDownloads($fotothekeId, false);
                 if ($added) {
                     $productmodel = Mage::getModel('catalog/product');
                     $product = $productmodel->load($fotothekeId);
                     $product->setStockData(array('use_config_manage_stock' => 1, 'manage_stock' => 1, 'qty' => 1, 'is_in_stock' => 1, 'min_sale_qty' => 0, 'max_sale_qty' => 1));
                     $product->setLinksPurchasedSeparately(1);
                     $product->setHasOptions(1);
                     $product->setRequiredOptions(1);
                     $product->save();
                     $i++;
                 }
             }
             Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('adminhtml')->__('Total of %d record(s) were successfully copied to filesystem and links saved to Database', $i));
         } catch (Exception $e) {
             Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
         }
     }
     $this->_redirect('*/*/');
 }
예제 #4
0
 /**
  * Upload file controller action
  */
 public function uploadAction()
 {
     $type = $this->getRequest()->getParam('type');
     $tmpPath = '';
     if ($type == 'samples') {
         $tmpPath = Mage_Downloadable_Model_Sample::getBaseTmpPath();
     } elseif ($type == 'links') {
         $tmpPath = Mage_Downloadable_Model_Link::getBaseTmpPath();
     } elseif ($type == 'link_samples') {
         $tmpPath = Mage_Downloadable_Model_Link::getBaseSampleTmpPath();
     }
     $result = array();
     try {
         $uploader = new Mage_Core_Model_File_Uploader($type);
         $uploader->setAllowRenameFiles(true);
         $uploader->setFilesDispersion(true);
         $result = $uploader->save($tmpPath);
         /**
          * Workaround for prototype 1.7 methods "isJSON", "evalJSON" on Windows OS
          */
         $result['tmp_name'] = str_replace(DS, "/", $result['tmp_name']);
         $result['path'] = str_replace(DS, "/", $result['path']);
         if (isset($result['file'])) {
             $fullPath = rtrim($tmpPath, DS) . DS . ltrim($result['file'], DS);
             Mage::helper('core/file_storage_database')->saveFile($fullPath);
         }
         $result['cookie'] = array('name' => session_name(), 'value' => $this->_getSession()->getSessionId(), 'lifetime' => $this->_getSession()->getCookieLifetime(), 'path' => $this->_getSession()->getCookiePath(), 'domain' => $this->_getSession()->getCookieDomain());
     } catch (Exception $e) {
         $result = array('error' => $e->getMessage(), 'errorcode' => $e->getCode());
     }
     $this->getResponse()->setBody(Mage::helper('core')->jsonEncode($result));
 }
 /**
  * Enter description here...
  *
  * @param Mage_Downloadable_Model_Link $link
  * @return string
  */
 public function getFormattedLinkPrice($link)
 {
     $price = $link->getPrice();
     if (0 == $price) {
         return '';
     }
     $_priceInclTax = Mage::helper('tax')->getPrice($link->getProduct(), $price, true);
     $_priceExclTax = Mage::helper('tax')->getPrice($link->getProduct(), $price);
     $priceStr = '<span class="price-notice">+';
     if (Mage::helper('tax')->displayPriceIncludingTax()) {
         $priceStr .= $this->helper('core')->currency($_priceInclTax, true, true);
     } elseif (Mage::helper('tax')->displayPriceExcludingTax()) {
         $priceStr .= $this->helper('core')->currency($_priceExclTax, true, true);
     } elseif (Mage::helper('tax')->displayBothPrices()) {
         $priceStr .= $this->helper('core')->currency($_priceExclTax, true, true);
         if ($_priceInclTax != $_priceExclTax) {
             $priceStr .= ' (+' . $this->helper('core')->currency($_priceInclTax, true, true) . ' ' . $this->__('Incl. Tax') . ')';
         }
     }
     $priceStr .= '</span>';
     return $priceStr;
 }
예제 #6
0
 /**
  * Download link action
  *
  */
 public function linkAction()
 {
     $linkId = $this->getRequest()->getParam('id', 0);
     $link = Mage::getModel('downloadable/link')->load($linkId);
     if ($link->getId()) {
         $resource = '';
         $resourceType = '';
         if ($link->getLinkType() == Mage_Downloadable_Helper_Download::LINK_TYPE_URL) {
             $resource = $link->getLinkUrl();
             $resourceType = Mage_Downloadable_Helper_Download::LINK_TYPE_URL;
         } elseif ($link->getLinkType() == Mage_Downloadable_Helper_Download::LINK_TYPE_FILE) {
             $resource = Mage::helper('downloadable/file')->getFilePath(Mage_Downloadable_Model_Link::getBasePath(), $link->getLinkFile());
             $resourceType = Mage_Downloadable_Helper_Download::LINK_TYPE_FILE;
         }
         try {
             $this->_processDownload($resource, $resourceType);
         } catch (Mage_Core_Exception $e) {
             Mage::getSingleton('udropship/session')->addError(Mage::helper('downloadable')->__('An error occurred while getting the requested content.'));
         }
     }
     exit(0);
 }
예제 #7
0
 /**
  * Upload file controller action
  */
 public function uploadAction()
 {
     $type = $this->getRequest()->getParam('type');
     $tmpPath = '';
     if ($type == 'samples') {
         $tmpPath = Mage_Downloadable_Model_Sample::getBaseTmpPath();
     } elseif ($type == 'links') {
         $tmpPath = Mage_Downloadable_Model_Link::getBaseTmpPath();
     } elseif ($type == 'link_samples') {
         $tmpPath = Mage_Downloadable_Model_Link::getBaseSampleTmpPath();
     }
     $result = array();
     try {
         $uploader = new Varien_File_Uploader($type);
         $uploader->setAllowRenameFiles(true);
         $uploader->setFilesDispersion(true);
         $result = $uploader->save($tmpPath);
         $result['cookie'] = array('name' => session_name(), 'value' => $this->_getSession()->getSessionId(), 'lifetime' => $this->_getSession()->getCookieLifetime(), 'path' => $this->_getSession()->getCookiePath(), 'domain' => $this->_getSession()->getCookieDomain());
     } catch (Exception $e) {
         $result = array('error' => $e->getMessage(), 'errorcode' => $e->getCode());
     }
     $this->getResponse()->setBody(Zend_Json::encode($result));
 }
예제 #8
0
 /**
  * Save Product downloadable information (links and samples)
  *
  * @param Mage_Catalog_Model_Product $product
  * @return Mage_Downloadable_Model_Product_Type
  */
 public function save($product = null)
 {
     parent::save($product);
     $product = $this->getProduct($product);
     /* @var Mage_Catalog_Model_Product $product */
     if ($data = $product->getDownloadableData()) {
         if (isset($data['sample'])) {
             $_deleteItems = array();
             foreach ($data['sample'] as $sampleItem) {
                 if ($sampleItem['is_delete'] == '1') {
                     if ($sampleItem['sample_id']) {
                         $_deleteItems[] = $sampleItem['sample_id'];
                     }
                 } else {
                     unset($sampleItem['is_delete']);
                     if (!$sampleItem['sample_id']) {
                         unset($sampleItem['sample_id']);
                     }
                     $sampleModel = Mage::getModel('downloadable/sample');
                     $files = array();
                     if (isset($sampleItem['file'])) {
                         $files = Mage::helper('core')->jsonDecode($sampleItem['file']);
                         unset($sampleItem['file']);
                     }
                     $sampleModel->setData($sampleItem)->setSampleType($sampleItem['type'])->setProductId($product->getId())->setStoreId($product->getStoreId());
                     if ($sampleModel->getSampleType() == Mage_Downloadable_Helper_Download::LINK_TYPE_FILE) {
                         $sampleFileName = Mage::helper('downloadable/file')->moveFileFromTmp(Mage_Downloadable_Model_Sample::getBaseTmpPath(), Mage_Downloadable_Model_Sample::getBasePath(), $files);
                         $sampleModel->setSampleFile($sampleFileName);
                     }
                     $sampleModel->save();
                 }
             }
             if ($_deleteItems) {
                 Mage::getResourceModel('downloadable/sample')->deleteItems($_deleteItems);
             }
         }
         if (isset($data['link'])) {
             $_deleteItems = array();
             foreach ($data['link'] as $linkItem) {
                 if ($linkItem['is_delete'] == '1') {
                     if ($linkItem['link_id']) {
                         $_deleteItems[] = $linkItem['link_id'];
                     }
                 } else {
                     unset($linkItem['is_delete']);
                     if (!$linkItem['link_id']) {
                         unset($linkItem['link_id']);
                     }
                     $files = array();
                     if (isset($linkItem['file'])) {
                         $files = Mage::helper('core')->jsonDecode($linkItem['file']);
                         unset($linkItem['file']);
                     }
                     $sample = array();
                     if (isset($linkItem['sample'])) {
                         $sample = $linkItem['sample'];
                         unset($linkItem['sample']);
                     }
                     $linkModel = Mage::getModel('downloadable/link')->setData($linkItem)->setLinkType($linkItem['type'])->setProductId($product->getId())->setStoreId($product->getStoreId())->setWebsiteId($product->getStore()->getWebsiteId())->setProductWebsiteIds($product->getWebsiteIds());
                     if (null === $linkModel->getPrice()) {
                         $linkModel->setPrice(0);
                     }
                     if ($linkModel->getIsUnlimited()) {
                         $linkModel->setNumberOfDownloads(0);
                     }
                     $sampleFile = array();
                     if ($sample && isset($sample['type'])) {
                         if ($sample['type'] == 'url' && $sample['url'] != '') {
                             $linkModel->setSampleUrl($sample['url']);
                         }
                         $linkModel->setSampleType($sample['type']);
                         $sampleFile = Mage::helper('core')->jsonDecode($sample['file']);
                     }
                     if ($linkModel->getLinkType() == Mage_Downloadable_Helper_Download::LINK_TYPE_FILE) {
                         $linkFileName = Mage::helper('downloadable/file')->moveFileFromTmp(Mage_Downloadable_Model_Link::getBaseTmpPath(), Mage_Downloadable_Model_Link::getBasePath(), $files);
                         $linkModel->setLinkFile($linkFileName);
                     }
                     if ($linkModel->getSampleType() == Mage_Downloadable_Helper_Download::LINK_TYPE_FILE) {
                         $linkSampleFileName = Mage::helper('downloadable/file')->moveFileFromTmp(Mage_Downloadable_Model_Link::getBaseSampleTmpPath(), Mage_Downloadable_Model_Link::getBaseSamplePath(), $sampleFile);
                         $linkModel->setSampleFile($linkSampleFileName);
                     }
                     $linkModel->save();
                 }
             }
             if ($_deleteItems) {
                 Mage::getResourceModel('downloadable/link')->deleteItems($_deleteItems);
             }
             if ($this->getProduct($product)->getLinksPurchasedSeparately()) {
                 $this->getProduct($product)->setIsCustomOptionChanged();
             }
         }
     }
     return $this;
 }
예제 #9
0
 /**
  * Get temporary path for downloadable product
  *
  * @param array $key            
  * @return array $tmpPathResult
  */
 public function getTmpPathForDownloadable($key)
 {
     $type = $tmpPath = '';
     $tmpPathResult = array();
     if (substr($key, 0, 5) == 'sampl') {
         $tmpPath = Mage_Downloadable_Model_Sample::getBaseTmpPath();
         $type = 'samples';
     }
     if (substr($key, 0, 5) == 'links') {
         $tmpPath = Mage_Downloadable_Model_Link::getBaseTmpPath();
         $type = 'links';
     }
     if (substr($key, 0, 5) == 'l_sam') {
         $tmpPath = Mage_Downloadable_Model_Link::getBaseSampleTmpPath();
         $type = 'link_samples';
     }
     $tmpPathResult['type'] = $type;
     $tmpPathResult['tmp_path'] = $tmpPath;
     return $tmpPathResult;
 }
예제 #10
0
 /**
  * Save title and price of link item
  *
  * @param Mage_Downloadable_Model_Link $linkObject
  * @return Mage_Downloadable_Model_Mysql4_link
  */
 public function saveItemTitleAndPrice($linkObject)
 {
     $stmt = $this->_getReadAdapter()->select()->from($this->getTable('downloadable/link_title'))->where('link_id = ?', $linkObject->getId())->where('store_id = ?', $linkObject->getStoreId());
     if ($this->_getReadAdapter()->fetchOne($stmt)) {
         $where = $this->_getReadAdapter()->quoteInto('link_id = ?', $linkObject->getId()) . ' AND ' . $this->_getReadAdapter()->quoteInto('store_id = ?', $linkObject->getStoreId());
         if ($linkObject->getUseDefaultTitle()) {
             $this->_getWriteAdapter()->delete($this->getTable('downloadable/link_title'), $where);
         } else {
             $this->_getWriteAdapter()->update($this->getTable('downloadable/link_title'), array('title' => $linkObject->getTitle()), $where);
         }
     } else {
         if (!$linkObject->getUseDefaultTitle()) {
             $this->_getWriteAdapter()->insert($this->getTable('downloadable/link_title'), array('link_id' => $linkObject->getId(), 'store_id' => $linkObject->getStoreId(), 'title' => $linkObject->getTitle()));
         }
     }
     $stmt = null;
     $stmt = $this->_getReadAdapter()->select()->from($this->getTable('downloadable/link_price'))->where('link_id = ?', $linkObject->getId())->where('website_id = ?', $linkObject->getWebsiteId());
     if ($this->_getReadAdapter()->fetchOne($stmt)) {
         $where = $this->_getReadAdapter()->quoteInto('link_id = ?', $linkObject->getId()) . ' AND ' . $this->_getReadAdapter()->quoteInto('website_id = ?', $linkObject->getWebsiteId());
         if ($linkObject->getUseDefaultPrice()) {
             $this->_getReadAdapter()->delete($this->getTable('downloadable/link_price'), $where);
         } else {
             $this->_getWriteAdapter()->update($this->getTable('downloadable/link_price'), array('price' => $linkObject->getPrice()), $where);
         }
     } else {
         if (!$linkObject->getUseDefaultPrice()) {
             $this->_getWriteAdapter()->insert($this->getTable('downloadable/link_price'), array('link_id' => $linkObject->getId(), 'website_id' => $linkObject->getWebsiteId(), 'price' => $linkObject->getPrice()));
         }
     }
     return $this;
 }
예제 #11
0
 /**
  * Delete data by item(s)
  *
  * @param Mage_Downloadable_Model_Link|array|int $items
  * @return Mage_Downloadable_Model_Resource_Link
  */
 public function deleteItems($items)
 {
     $writeAdapter = $this->_getWriteAdapter();
     $where = array();
     if ($items instanceof Mage_Downloadable_Model_Link) {
         $where = array('link_id = ?' => $items->getId());
     } elseif (is_array($items)) {
         $where = array('link_id in (?)' => $items);
     } else {
         $where = array('sample_id = ?' => $items);
     }
     if ($where) {
         $writeAdapter->delete($this->getMainTable(), $where);
         $writeAdapter->delete($this->getTable('downloadable/link_title'), $where);
         $writeAdapter->delete($this->getTable('downloadable/link_price'), $where);
     }
     return $this;
 }
예제 #12
0
 /**
  * Retrieve downloadable product links
  *
  * @param int|string $productId
  * @param string|int $store
  * @param string $identifierType ('sku'|'id')
  * @return array
  */
 public function items($productId, $store = null, $identifierType = null)
 {
     $product = $this->_getProduct($productId, $store, $identifierType);
     $linkArr = array();
     $links = $product->getTypeInstance(true)->getLinks($product);
     foreach ($links as $item) {
         $tmpLinkItem = array('link_id' => $item->getId(), 'title' => $item->getTitle(), 'price' => $item->getPrice(), 'number_of_downloads' => $item->getNumberOfDownloads(), 'is_shareable' => $item->getIsShareable(), 'link_url' => $item->getLinkUrl(), 'link_type' => $item->getLinkType(), 'sample_file' => $item->getSampleFile(), 'sample_url' => $item->getSampleUrl(), 'sample_type' => $item->getSampleType(), 'sort_order' => $item->getSortOrder());
         $file = Mage::helper('downloadable/file')->getFilePath(Mage_Downloadable_Model_Link::getBasePath(), $item->getLinkFile());
         if ($item->getLinkFile() && !is_file($file)) {
             Mage::helper('core/file_storage_database')->saveFileToFilesystem($file);
         }
         if ($item->getLinkFile() && is_file($file)) {
             $name = Mage::helper('downloadable/file')->getFileFromPathFile($item->getLinkFile());
             $tmpLinkItem['file_save'] = array(array('file' => $item->getLinkFile(), 'name' => $name, 'size' => filesize($file), 'status' => 'old'));
         }
         $sampleFile = Mage::helper('downloadable/file')->getFilePath(Mage_Downloadable_Model_Link::getBaseSamplePath(), $item->getSampleFile());
         if ($item->getSampleFile() && is_file($sampleFile)) {
             $tmpLinkItem['sample_file_save'] = array(array('file' => $item->getSampleFile(), 'name' => Mage::helper('downloadable/file')->getFileFromPathFile($item->getSampleFile()), 'size' => filesize($sampleFile), 'status' => 'old'));
         }
         if ($item->getNumberOfDownloads() == '0') {
             $tmpLinkItem['is_unlimited'] = 1;
         }
         if ($product->getStoreId() && $item->getStoreTitle()) {
             $tmpLinkItem['store_title'] = $item->getStoreTitle();
         }
         if ($product->getStoreId() && Mage::helper('downloadable')->getIsPriceWebsiteScope()) {
             $tmpLinkItem['website_price'] = $item->getWebsitePrice();
         }
         $linkArr[] = $tmpLinkItem;
     }
     unset($item);
     unset($tmpLinkItem);
     unset($links);
     $samples = $product->getTypeInstance(true)->getSamples($product)->getData();
     return array('links' => $linkArr, 'samples' => $samples);
 }
 /**
  * Download link action
  */
 public function linkAction()
 {
     $id = $this->getRequest()->getParam('id', 0);
     $linkPurchasedItem = Mage::getModel('downloadable/link_purchased_item')->load($id, 'link_hash');
     if (!$linkPurchasedItem->getId()) {
         $this->_getCustomerSession()->addNotice(Mage::helper('downloadable')->__("Requested link doesn't exist."));
         return $this->_redirect('*/customer/products');
     }
     if (!Mage::helper('downloadable')->getIsShareable($linkPurchasedItem)) {
         $customerId = $this->_getCustomerSession()->getCustomerId();
         if (!$customerId) {
             $product = Mage::getModel('catalog/product')->load($linkPurchasedItem->getProductId());
             if ($product->getId()) {
                 $notice = Mage::helper('downloadable')->__('Please log in to download your product or purchase <a href="%s">%s</a>.', $product->getProductUrl(), $product->getName());
             } else {
                 $notice = Mage::helper('downloadable')->__('Please log in to download your product.');
             }
             $this->_getCustomerSession()->addNotice($notice);
             $this->_getCustomerSession()->authenticate($this);
             $this->_getCustomerSession()->setBeforeAuthUrl(Mage::getUrl('downloadable/customer/products/'), array('_secure' => true));
             return;
         }
         $linkPurchased = Mage::getModel('downloadable/link_purchased')->load($linkPurchasedItem->getPurchasedId());
         if ($linkPurchased->getCustomerId() != $customerId) {
             $this->_getCustomerSession()->addNotice(Mage::helper('downloadable')->__("Requested link doesn't exist."));
             return $this->_redirect('*/customer/products');
         }
     }
     $downloadsLeft = $linkPurchasedItem->getNumberOfDownloadsBought() - $linkPurchasedItem->getNumberOfDownloadsUsed();
     if ($linkPurchasedItem->getStatus() == Mage_Downloadable_Model_Link_Purchased_Item::LINK_STATUS_AVAILABLE && ($downloadsLeft || $linkPurchasedItem->getNumberOfDownloadsBought() == 0)) {
         $resource = '';
         $resourceType = '';
         if ($linkPurchasedItem->getLinkType() == Mage_Downloadable_Helper_Download::LINK_TYPE_URL) {
             $resource = $linkPurchasedItem->getLinkUrl();
             $resourceType = Mage_Downloadable_Helper_Download::LINK_TYPE_URL;
         } elseif ($linkPurchasedItem->getLinkType() == Mage_Downloadable_Helper_Download::LINK_TYPE_FILE) {
             $resource = Mage::helper('downloadable/file')->getFilePath(Mage_Downloadable_Model_Link::getBasePath(), $linkPurchasedItem->getLinkFile());
             $resourceType = Mage_Downloadable_Helper_Download::LINK_TYPE_FILE;
         }
         try {
             $this->_processDownload($resource, $resourceType);
             $linkPurchasedItem->setNumberOfDownloadsUsed($linkPurchasedItem->getNumberOfDownloadsUsed() + 1);
             if ($linkPurchasedItem->getNumberOfDownloadsBought() != 0 && !($linkPurchasedItem->getNumberOfDownloadsBought() - $linkPurchasedItem->getNumberOfDownloadsUsed())) {
                 $linkPurchasedItem->setStatus(Mage_Downloadable_Model_Link_Purchased_Item::LINK_STATUS_EXPIRED);
             }
             $linkPurchasedItem->save();
             exit(0);
         } catch (Exception $e) {
             $this->_getCustomerSession()->addError(Mage::helper('downloadable')->__('Sorry, there was an error getting requested content. Please contact store owner.'));
         }
     } elseif ($linkPurchasedItem->getStatus() == Mage_Downloadable_Model_Link_Purchased_Item::LINK_STATUS_EXPIRED) {
         $this->_getCustomerSession()->addNotice(Mage::helper('downloadable')->__('Link has expired.'));
     } elseif ($linkPurchasedItem->getStatus() == Mage_Downloadable_Model_Link_Purchased_Item::LINK_STATUS_PENDING) {
         $this->_getCustomerSession()->addNotice(Mage::helper('downloadable')->__('Link is not available.'));
     } else {
         $this->_getCustomerSession()->addError(Mage::helper('downloadable')->__('Sorry, there was an error getting requested content. Please contact store owner.'));
     }
     return $this->_redirect('*/customer/products');
 }
예제 #14
0
 /**
  * Delete data by item(s)
  *
  * @param Mage_Downloadable_Model_Link|array|int $items
  * @return Mage_Downloadable_Model_Mysql4_Link
  */
 public function deleteItems($items)
 {
     $where = '';
     if ($items instanceof Mage_Downloadable_Model_Link) {
         $where = $this->_getReadAdapter()->quoteInto('link_id = ?', $items->getId());
     } elseif (is_array($items)) {
         $where = $this->_getReadAdapter()->quoteInto('link_id in (?)', $items);
     } else {
         $where = $this->_getReadAdapter()->quoteInto('sample_id = ?', $items);
     }
     if ($where) {
         $this->_getWriteAdapter()->delete($this->getTable('downloadable/link'), $where);
         $this->_getWriteAdapter()->delete($this->getTable('downloadable/link_title'), $where);
         $this->_getWriteAdapter()->delete($this->getTable('downloadable/link_price'), $where);
     }
     return $this;
 }
예제 #15
0
파일: Links.php 프로젝트: relue/magento2
 /**
  * Returns whether link checked by default or not
  *
  * @param Mage_Downloadable_Model_Link $link
  * @return bool
  */
 public function getIsLinkChecked($link)
 {
     $configValue = $this->getProduct()->getPreconfiguredValues()->getLinks();
     if (!$configValue || !is_array($configValue)) {
         return false;
     }
     return $configValue && in_array($link->getId(), $configValue);
 }
예제 #16
0
    /**
     * Save product (import)
     * 
     * @param array $importData 
     * @throws Mage_Core_Exception
     * @return bool 
     */
    public function saveRow(array $importData)
    {
        #$product = $this -> getProductModel();
        $product = $this->getProductModel()->reset();
        #$product -> setData( array() );
        #if ( $stockItem = $product -> getStockItem() ) {
        #$stockItem -> setData( array() );
        #}
        if (empty($importData['store'])) {
            if (!is_null($this->getBatchParams('store'))) {
                $store = $this->getStoreById($this->getBatchParams('store'));
            } else {
                $message = Mage::helper('catalog')->__('Skip import row, required field "%s" not defined', 'store');
                Mage::throwException($message);
                Mage::log(sprintf('Skip import row, required field "store" not defined', $message), null, 'ce_product_import_export_errors.log');
            }
        } else {
            $store = $this->getStoreByCode($importData['store']);
        }
        if ($store === false) {
            $message = Mage::helper('catalog')->__('Skip import row, store "%s" field not exists', $importData['store']);
            Mage::throwException($message);
            Mage::log(sprintf('Skip import row, store "' . $importData['store'] . '" field not exists', $message), null, 'ce_product_import_export_errors.log');
        }
        if (empty($importData['sku'])) {
            $message = Mage::helper('catalog')->__('Skip import row, required field "%s" not defined', 'sku');
            Mage::throwException($message);
            Mage::log(sprintf('Skip import row, required field "sku" not defined', $message), null, 'ce_product_import_export_errors.log');
        }
        $product->setStoreId($store->getId());
        $productId = $product->getIdBySku($importData['sku']);
        $iscustomoptions = "false";
        //sets currentcustomoptionstofalse
        $finalsuperattributepricing = "";
        $finalsuperattributetype = $importData['type'];
        if (isset($importData['super_attribute_pricing']) && $importData['super_attribute_pricing'] != "") {
            $finalsuperattributepricing = $importData['super_attribute_pricing'];
        }
        $new = true;
        // fix for duplicating attributes error
        if ($productId) {
            $product->load($productId);
            $new = false;
            // fix for duplicating attributes error
        } else {
            $productTypes = $this->getProductTypes();
            $productAttributeSets = $this->getProductAttributeSets();
            /**
             * Check product define type
             */
            if (empty($importData['type']) || !isset($productTypes[strtolower($importData['type'])])) {
                $value = isset($importData['type']) ? $importData['type'] : '';
                $message = Mage::helper('catalog')->__('Skip import row, is not valid value "%s" for field "%s"', $value, 'type');
                Mage::throwException($message);
                Mage::log(sprintf('Skip import row, is not valid value "' . $value . '" for field type', $message), null, 'ce_product_import_export_errors.log');
            }
            $product->setTypeId($productTypes[strtolower($importData['type'])]);
            /**
             * Check product define attribute set
             */
            if (empty($importData['attribute_set']) || !isset($productAttributeSets[$importData['attribute_set']])) {
                $value = isset($importData['attribute_set']) ? $importData['attribute_set'] : '';
                $message = Mage::helper('catalog')->__('Skip import row, is not valid value "%s" for field "%s"', $value, 'attribute_set');
                Mage::throwException($message);
                Mage::log(sprintf('Skip import row, is not valid value "' . $value . '" for field attribute_set', $message), null, 'ce_product_import_export_errors.log');
            }
            $product->setAttributeSetId($productAttributeSets[$importData['attribute_set']]);
            foreach ($this->_requiredFields as $field) {
                $attribute = $this->getAttribute($field);
                if (!isset($importData[$field]) && $attribute && $attribute->getIsRequired()) {
                    $message = Mage::helper('catalog')->__('Skip import row, required field "%s" for new products not defined', $field);
                    Mage::throwException($message);
                }
            }
        }
        $this->setProductTypeInstance($product);
        // delete disabled products
        // note "Disabled text should be converted to handle multi-lanugage values aka age::helper('catalog')->__(''); type deal
        if ($importData['status'] == 'Delete' || $importData['status'] == 'delete') {
            $product = Mage::getSingleton('catalog/product')->load($productId);
            $this->_removeFile(Mage::getSingleton('catalog/product_media_config')->getMediaPath($product->getData('image')));
            $this->_removeFile(Mage::getSingleton('catalog/product_media_config')->getMediaPath($product->getData('small_image')));
            $this->_removeFile(Mage::getSingleton('catalog/product_media_config')->getMediaPath($product->getData('thumbnail')));
            $media_gallery = $product->getData('media_gallery');
            foreach ($media_gallery['images'] as $image) {
                $this->_removeFile(Mage::getSingleton('catalog/product_media_config')->getMediaPath($image['file']));
            }
            $product->delete();
            return true;
        }
        $currentproducttype = $importData['type'];
        if ($importData['type'] == 'configurable') {
            $product->setCanSaveConfigurableAttributes(true);
            $configAttributeCodes = $this->userCSVDataAsArray($importData['config_attributes']);
            $usingAttributeIds = array();
            /***
             * Check the product's super attributes (see catalog_product_super_attribute table), and make a determination that way.
             **/
            $cspa = $product->getTypeInstance()->getConfigurableAttributesAsArray($product);
            $attr_codes = array();
            if (isset($cspa) && !empty($cspa)) {
                //found attributes
                foreach ($cspa as $cs_attr) {
                    //$attr_codes[$cs_attr['attribute_id']] = $cs_attr['attribute_code'];
                    $attr_codes[] = $cs_attr['attribute_id'];
                }
            }
            foreach ($configAttributeCodes as $attributeCode) {
                $attribute = $product->getResource()->getAttribute($attributeCode);
                if ($product->getTypeInstance()->canUseAttribute($attribute)) {
                    //if (!in_array($attributeCode,$attr_codes)) { // fix for duplicating attributes error
                    if ($new) {
                        // fix for duplicating attributes error // <---------- this must be true to fill $usingAttributes
                        $usingAttributeIds[] = $attribute->getAttributeId();
                    }
                }
            }
            if (!empty($usingAttributeIds)) {
                $product->getTypeInstance()->setUsedProductAttributeIds($usingAttributeIds);
                $updateconfigurablearray = array();
                $insidearraycount = 0;
                $finalarraytoimport = $product->getTypeInstance()->getConfigurableAttributesAsArray();
                $updateconfigurablearray = $product->getTypeInstance()->getConfigurableAttributesAsArray();
                foreach ($updateconfigurablearray as $eacharrayvalue) {
                    if ($this->getBatchParams('configurable_use_default') != "") {
                        $finalarraytoimport[$insidearraycount]['use_default'] = $this->getBatchParams('configurable_use_default');
                        //added in 1.5.x
                        //<var name="configurable_use_default"><![CDATA[1]]></var>
                    }
                    $finalarraytoimport[$insidearraycount]['label'] = $eacharrayvalue['frontend_label'];
                    #$finalarraytoimport[$insidearraycount]['values'] = array( );
                    #$attribute = Mage::getModel('catalog/product_type_configurable_attribute')->setProductAttribute($eacharrayvalue['attribute_id']);
                    #$attribute->setStoreLabel($eacharrayvalue['frontend_label']);
                    #print_r($attribute->getStoreLabel());
                    $insidearraycount += 1;
                }
                $product->setConfigurableAttributesData($finalarraytoimport);
                $product->setCanSaveConfigurableAttributes(true);
                $product->setCanSaveCustomOptions(true);
            }
            if (isset($importData['associated'])) {
                $product->setConfigurableProductsData($this->skusToIds($importData['associated'], $product));
            }
        }
        //THIS IS FOR DOWNLOADABLE PRODUCTS
        if ($importData['type'] == 'downloadable' && $importData['downloadable_options'] != "") {
            if ($new) {
                $downloadableitems = array();
                $filearrayforimport = array();
                $filenameforsamplearrayforimport = array();
                #$filenameforsamplearrayforimport = "";
                $downloadableitemsoptionscount = 0;
                //THIS IS FOR DOWNLOADABLE OPTIONS
                $commadelimiteddata = explode('|', $importData['downloadable_options']);
                foreach ($commadelimiteddata as $data) {
                    $configBundleOptionsCodes = $this->userCSVDataAsArray($data);
                    $downloadableitems['link'][$downloadableitemsoptionscount]['is_delete'] = 0;
                    $downloadableitems['link'][$downloadableitemsoptionscount]['link_id'] = 0;
                    $downloadableitems['link'][$downloadableitemsoptionscount]['title'] = $configBundleOptionsCodes[0];
                    $downloadableitems['link'][$downloadableitemsoptionscount]['price'] = $configBundleOptionsCodes[1];
                    $downloadableitems['link'][$downloadableitemsoptionscount]['number_of_downloads'] = $configBundleOptionsCodes[2];
                    $downloadableitems['link'][$downloadableitemsoptionscount]['is_shareable'] = 2;
                    if (isset($configBundleOptionsCodes[5])) {
                        #$downloadableitems['link'][$downloadableitemsoptionscount]['sample'] = '';
                        if ($configBundleOptionsCodes[3] == "file") {
                            #$filenameforsamplearrayforimport = $configBundleOptionsCodes[5];
                            $filenameforsamplearrayforimport[] = array('file' => '' . $configBundleOptionsCodes[5] . '', 'name' => '' . $configBundleOptionsCodes[0] . '', 'price' => '' . $configBundleOptionsCodes[1] . '');
                            //Create and send the JSON structure instead of the file  name
                            $tempSampleFile = '[{"file": "' . $configBundleOptionsCodes[5] . '", "status": "new"}]';
                            $downloadableitems['link'][$downloadableitemsoptionscount]['sample'] = array('file' => '' . $tempSampleFile . '', 'type' => 'file', 'url' => '');
                            //$downloadableitems['link'][$downloadableitemsoptionscount]['sample'] = array('file' => ''.$configBundleOptionsCodes[5].'', 'type' => 'file', 'url'  => '');
                        } else {
                            $downloadableitems['link'][$downloadableitemsoptionscount]['sample'] = array('file' => '[]', 'type' => 'url', 'url' => '' . $configBundleOptionsCodes[5] . '');
                        }
                    } else {
                        $downloadableitems['link'][$downloadableitemsoptionscount]['sample'] = '';
                    }
                    $downloadableitems['link'][$downloadableitemsoptionscount]['file'] = '';
                    $downloadableitems['link'][$downloadableitemsoptionscount]['type'] = $configBundleOptionsCodes[3];
                    #$downloadableitems['link'][$downloadableitemsoptionscount]['link_url'] = $configBundleOptionsCodes[4];
                    if ($configBundleOptionsCodes[3] == "file") {
                        #$filearrayforimport = array('file'  => 'media/import/mypdf.pdf' , 'name'  => 'asdad.txt', 'size'  => '316', 'status'  => 'old');
                        #$document_directory =  Mage :: getBaseDir( 'media' ) . DS . 'import' . DS;
                        #echo "DIRECTORY: " . $document_directory;
                        #$filearrayforimport = '[{"file": "/home/discou33/public_html/media/import/mypdf.pdf", "name": "mypdf.pdf", "status": "new"}]';
                        #$filearrayforimport = '[{"file": "mypdf.pdf", "name": "quickstart.pdf", "size": 324075, "status": "new"}]';
                        $filearrayforimport[] = array('file' => '' . $configBundleOptionsCodes[4] . '', 'name' => '' . $configBundleOptionsCodes[0] . '', 'price' => '' . $configBundleOptionsCodes[1] . '');
                        if (isset($configBundleOptionsCodes[5])) {
                            if ($configBundleOptionsCodes[5] == 0) {
                                $linkspurchasedstatus = 0;
                                $linkspurchasedstatustext = false;
                            } else {
                                $linkspurchasedstatus = 1;
                                $linkspurchasedstatustext = true;
                            }
                            $product->setLinksPurchasedSeparately($linkspurchasedstatus);
                            $product->setLinksPurchasedSeparately($linkspurchasedstatustext);
                        }
                        #$product->setLinksPurchasedSeparately(0);
                        #$product->setLinksPurchasedSeparately(false);
                        #$files = Zend_Json::decode($filearrayforimport);
                        #$files = "mypdf.pdf";
                        #$downloadableitems['link'][$downloadableitemsoptionscount]['file'] = $filearrayforimport;
                    } else {
                        if ($configBundleOptionsCodes[3] == "url") {
                            $downloadableitems['link'][$downloadableitemsoptionscount]['link_url'] = $configBundleOptionsCodes[4];
                        }
                    }
                    $downloadableitems['link'][$downloadableitemsoptionscount]['sort_order'] = 0;
                    $product->setDownloadableData($downloadableitems);
                    $downloadableitemsoptionscount += 1;
                }
                #print_r($downloadableitems);
            } else {
                //first delete all links then we update
                $download_info = Mage::getModel('downloadable/product_type');
                $download_info->setProduct($product);
                if ($download_info->hasLinks()) {
                    $_links = $download_info->getLinks();
                    foreach ($_links as $_link) {
                        $_link->delete();
                    }
                }
                //begin update
                $downloadableitems = array();
                $filearrayforimport = array();
                //$filenameforsamplearrayforimport = "";
                $filenameforsamplearrayforimport = array();
                //bug fix
                $downloadableitemsoptionscount = 0;
                //THIS IS FOR DOWNLOADABLE OPTIONS
                $commadelimiteddata = explode('|', $importData['downloadable_options']);
                foreach ($commadelimiteddata as $data) {
                    $configBundleOptionsCodes = $this->userCSVDataAsArray($data);
                    $downloadableitems['link'][$downloadableitemsoptionscount]['is_delete'] = 0;
                    $downloadableitems['link'][$downloadableitemsoptionscount]['link_id'] = 0;
                    $downloadableitems['link'][$downloadableitemsoptionscount]['title'] = $configBundleOptionsCodes[0];
                    $downloadableitems['link'][$downloadableitemsoptionscount]['price'] = $configBundleOptionsCodes[1];
                    $downloadableitems['link'][$downloadableitemsoptionscount]['number_of_downloads'] = $configBundleOptionsCodes[2];
                    $downloadableitems['link'][$downloadableitemsoptionscount]['is_shareable'] = 2;
                    if (isset($configBundleOptionsCodes[5])) {
                        #$downloadableitems['link'][$downloadableitemsoptionscount]['sample'] = '';
                        if ($configBundleOptionsCodes[3] == "file") {
                            #$filenameforsamplearrayforimport = $configBundleOptionsCodes[5];
                            $filenameforsamplearrayforimport[] = array('file' => '' . $configBundleOptionsCodes[5] . '', 'name' => '' . $configBundleOptionsCodes[0] . '', 'price' => '' . $configBundleOptionsCodes[1] . '');
                            //Create and send the JSON structure instead of the file  name
                            $tempSampleFile = '[{"file": "' . $configBundleOptionsCodes[5] . '", "status": "new"}]';
                            $downloadableitems['link'][$downloadableitemsoptionscount]['sample'] = array('file' => '' . $tempSampleFile . '', 'type' => 'file', 'url' => '');
                            //$downloadableitems['link'][$downloadableitemsoptionscount]['sample'] = array('file' => ''.$configBundleOptionsCodes[5].'', 'type' => 'file', 'url'  => '');
                        } else {
                            $downloadableitems['link'][$downloadableitemsoptionscount]['sample'] = array('file' => '[]', 'type' => 'url', 'url' => '' . $configBundleOptionsCodes[5] . '');
                        }
                    } else {
                        $downloadableitems['link'][$downloadableitemsoptionscount]['sample'] = '';
                    }
                    $downloadableitems['link'][$downloadableitemsoptionscount]['file'] = '';
                    $downloadableitems['link'][$downloadableitemsoptionscount]['type'] = $configBundleOptionsCodes[3];
                    #$downloadableitems['link'][$downloadableitemsoptionscount]['link_url'] = $configBundleOptionsCodes[4];
                    if ($configBundleOptionsCodes[3] == "file") {
                        #$filearrayforimport = array('file'  => 'media/import/mypdf.pdf' , 'name'  => 'asdad.txt', 'size'  => '316', 'status'  => 'old');
                        #$document_directory =  Mage :: getBaseDir( 'media' ) . DS . 'import' . DS;
                        #echo "DIRECTORY: " . $document_directory;
                        #$filearrayforimport = '[{"file": "/home/discou33/public_html/media/import/mypdf.pdf", "name": "mypdf.pdf", "status": "new"}]';
                        #$filearrayforimport = '[{"file": "mypdf.pdf", "name": "quickstart.pdf", "size": 324075, "status": "new"}]';
                        #echo "FILE: " . $configBundleOptionsCodes[4];
                        $filearrayforimport[] = array('file' => '' . $configBundleOptionsCodes[4] . '', 'name' => '' . $configBundleOptionsCodes[0] . '', 'price' => '' . $configBundleOptionsCodes[1] . '');
                        if (isset($configBundleOptionsCodes[5])) {
                            if ($configBundleOptionsCodes[5] == 0) {
                                $linkspurchasedstatus = 0;
                                $linkspurchasedstatustext = false;
                            } else {
                                $linkspurchasedstatus = 1;
                                $linkspurchasedstatustext = true;
                            }
                            $product->setLinksPurchasedSeparately($linkspurchasedstatus);
                            $product->setLinksPurchasedSeparately($linkspurchasedstatustext);
                        }
                        #$product->setLinksPurchasedSeparately(0);
                        #$product->setLinksPurchasedSeparately(false);
                        #$files = Zend_Json::decode($filearrayforimport);
                        #$files = "mypdf.pdf";
                        #$downloadableitems['link'][$downloadableitemsoptionscount]['file'] = $filearrayforimport;
                    } else {
                        if ($configBundleOptionsCodes[3] == "url") {
                            $downloadableitems['link'][$downloadableitemsoptionscount]['link_url'] = $configBundleOptionsCodes[4];
                        }
                    }
                    $downloadableitems['link'][$downloadableitemsoptionscount]['sort_order'] = 0;
                    $product->setDownloadableData($downloadableitems);
                    $downloadableitemsoptionscount += 1;
                }
            }
        }
        //THIS IS FOR BUNDLE PRODUCTS
        if ($importData['type'] == 'bundle') {
            if ($new) {
                $optionscount = 0;
                $items = array();
                //THIS IS FOR BUNDLE OPTIONS
                $commadelimiteddata = explode('|', $importData['bundle_options']);
                foreach ($commadelimiteddata as $data) {
                    $configBundleOptionsCodes = $this->userCSVDataAsArray($data);
                    $titlebundleselection = ucfirst(str_replace('_', ' ', $configBundleOptionsCodes[0]));
                    $items[$optionscount]['title'] = $titlebundleselection;
                    $items[$optionscount]['type'] = $configBundleOptionsCodes[1];
                    $items[$optionscount]['required'] = $configBundleOptionsCodes[2];
                    $items[$optionscount]['position'] = $configBundleOptionsCodes[3];
                    $items[$optionscount]['delete'] = 0;
                    $optionscount += 1;
                    if ($items) {
                        $product->setBundleOptionsData($items);
                    }
                    $options_id = $product->getOptionId();
                    $selections = array();
                    $bundleConfigData = array();
                    $optionscountselection = 0;
                    //THIS IS FOR BUNDLE SELECTIONS
                    $commadelimiteddataselections = explode('|', $importData['bundle_selections']);
                    foreach ($commadelimiteddataselections as $selection) {
                        $configBundleSelectionCodes = $this->userCSVDataAsArray($selection);
                        $selectionscount = 0;
                        foreach ($configBundleSelectionCodes as $selectionItem) {
                            $bundleConfigData = explode(':', $selectionItem);
                            $selections[$optionscountselection][$selectionscount]['option_id'] = $options_id;
                            $selections[$optionscountselection][$selectionscount]['product_id'] = $product->getIdBySku($bundleConfigData[0]);
                            $selections[$optionscountselection][$selectionscount]['selection_price_type'] = $bundleConfigData[1];
                            $selections[$optionscountselection][$selectionscount]['selection_price_value'] = $bundleConfigData[2];
                            $selections[$optionscountselection][$selectionscount]['is_default'] = $bundleConfigData[3];
                            if (isset($bundleConfigData) && isset($bundleConfigData[4]) && $bundleConfigData[4] != '') {
                                $selections[$optionscountselection][$selectionscount]['selection_qty'] = $bundleConfigData[4];
                                $selections[$optionscountselection][$selectionscount]['selection_can_change_qty'] = $bundleConfigData[5];
                            }
                            if (isset($bundleConfigData) && isset($bundleConfigData[6]) && $bundleConfigData[6] != '') {
                                $selections[$optionscountselection][$selectionscount]['position'] = $bundleConfigData[6];
                            }
                            $selections[$optionscountselection][$selectionscount]['delete'] = 0;
                            $selectionscount += 1;
                        }
                        $optionscountselection += 1;
                    }
                    if ($selections) {
                        $product->setBundleSelectionsData($selections);
                    }
                }
                if ($product->getPriceType() == '0') {
                    $product->setCanSaveCustomOptions(true);
                    if ($customOptions = $product->getProductOptions()) {
                        foreach ($customOptions as $key => $customOption) {
                            $customOptions[$key]['is_delete'] = 1;
                        }
                        $product->setProductOptions($customOptions);
                    }
                }
                $product->setCanSaveBundleSelections();
            }
        }
        if (isset($importData['related'])) {
            $linkIds = $this->skusToIds($importData['related'], $product);
            if (!empty($linkIds)) {
                $product->setRelatedLinkData($linkIds);
            }
        }
        if (isset($importData['upsell'])) {
            $linkIds = $this->skusToIds($importData['upsell'], $product);
            if (!empty($linkIds)) {
                $product->setUpSellLinkData($linkIds);
            }
        }
        if (isset($importData['crosssell'])) {
            $linkIds = $this->skusToIds($importData['crosssell'], $product);
            if (!empty($linkIds)) {
                $product->setCrossSellLinkData($linkIds);
            }
        }
        /*
        if ( isset( $importData['grouped'] ) ) {
        	$linkIds = $this -> skusToIds( $importData['grouped'], $product );
        	if ( !empty( $linkIds ) ) {
        		$product -> setGroupedLinkData( $linkIds );
        	} 
        } 
        */
        /* MODDED TO ALLOW FOR GROUP POSITION AS WELL AND SHOULD WORK IF NO POSITION IS SET AS WELL CAN COMBO */
        if (isset($importData['grouped']) && $importData['grouped'] != "") {
            $finalIDssthatneedtobeconvertedto = array();
            $finalskusthatneedtobeconvertedtoID = "";
            $groupedpositioncounter = 0;
            $finalskusforarraytoexplode = explode(",", $importData['grouped']);
            foreach ($finalskusforarraytoexplode as $productskuexploded) {
                $pos = strpos($productskuexploded, ":");
                if ($pos !== false) {
                    //if( isset($finalidsforarraytoexplode[1]) ) {
                    $finalidsforarraytoexplode = explode(":", $productskuexploded);
                    $finalIDssthatneedtobeconvertedto[$groupedpositioncounter]['position'] = $finalidsforarraytoexplode[0];
                    $finalIDssthatneedtobeconvertedto[$groupedpositioncounter]['sku'] = $finalidsforarraytoexplode[1];
                    $finalskusthatneedtobeconvertedtoID .= $finalidsforarraytoexplode[1] . ",";
                } else {
                    $finalskusthatneedtobeconvertedtoID .= $productskuexploded . ",";
                }
                $groupedpositioncounter++;
            }
            $linkIds = $this->skusToIds($finalskusthatneedtobeconvertedtoID, $product);
            if (!empty($linkIds)) {
                $product->setGroupedLinkData($linkIds);
            }
        }
        if (isset($importData['category_ids'])) {
            $product->setCategoryIds($importData['category_ids']);
        }
        if (isset($importData['tier_prices']) && !empty($importData['tier_prices'])) {
            $this->_editTierPrices($product, $importData['tier_prices'], $store);
        }
        if (isset($importData['categories']) && $importData['categories'] != "") {
            if (!empty($importData['store'])) {
                $cat_store = $this->_stores[$importData['store']];
            } else {
                $message = Mage::helper('catalog')->__('Skip import row, required field "store" for new products not defined', $field);
                Mage::throwException($message);
            }
            $categoryIds = $this->_addCategories($importData['categories'], $cat_store);
            if ($categoryIds) {
                $product->setCategoryIds($categoryIds);
            }
        }
        foreach ($this->_ignoreFields as $field) {
            if (isset($importData[$field])) {
                unset($importData[$field]);
            }
        }
        if ($store->getId() != 0) {
            $websiteIds = $product->getWebsiteIds();
            if (!is_array($websiteIds)) {
                $websiteIds = array();
            }
            if (!in_array($store->getWebsiteId(), $websiteIds)) {
                $websiteIds[] = $store->getWebsiteId();
            }
            $product->setWebsiteIds($websiteIds);
        }
        if (isset($importData['websites'])) {
            $websiteIds = $product->getWebsiteIds();
            if (!is_array($websiteIds)) {
                $websiteIds = array();
            }
            $websiteCodes = explode(',', $importData['websites']);
            foreach ($websiteCodes as $websiteCode) {
                try {
                    $website = Mage::app()->getWebsite(trim($websiteCode));
                    if (!in_array($website->getId(), $websiteIds)) {
                        $websiteIds[] = $website->getId();
                    }
                } catch (Exception $e) {
                }
            }
            $product->setWebsiteIds($websiteIds);
            unset($websiteIds);
        }
        $custom_options = array();
        foreach ($importData as $field => $value) {
            //SEEMS TO BE CONFLICTING ISSUES WITH THESE 2 CHOICES AND DOESNT SEEM TO REQUIRE THIS IN ALL THE TESTING SO LEAVING COMMENTED
            //if ( in_array( $field, $this -> _inventoryFields ) ) {
            //continue;
            //}
            /*
            if (in_array($field, $this->_inventorySimpleFields))
            {
            	continue;
            }
            */
            if (in_array($field, $this->_imageFields)) {
                continue;
            }
            $attribute = $this->getAttribute($field);
            if (!$attribute) {
                /* CUSTOM OPTION CODE */
                if (strpos($field, ':') !== FALSE && strlen($value)) {
                    $values = explode('|', $value);
                    if (count($values) > 0) {
                        $iscustomoptions = "true";
                        foreach ($values as $v) {
                            $parts = explode(':', $v);
                            $title = $parts[0];
                        }
                        //RANDOM ISSUE HERE SOMETIMES WITH TITLES OF LAST ITEM IN DROPDOWN SHOWING AS TITLE MIGHT NEED TO SEPERATE TITLE variables
                        @(list($title, $type, $is_required, $sort_order) = explode(':', $field));
                        $title2 = ucfirst(str_replace('_', ' ', $title));
                        $custom_options[] = array('is_delete' => 0, 'title' => $title2, 'previous_group' => '', 'previous_type' => '', 'type' => $type, 'is_require' => $is_required, 'sort_order' => $sort_order, 'values' => array());
                        foreach ($values as $v) {
                            $parts = explode(':', $v);
                            $title = $parts[0];
                            if (count($parts) > 1) {
                                $price_type = $parts[1];
                            } else {
                                $price_type = 'fixed';
                            }
                            if (count($parts) > 2) {
                                $price = $parts[2];
                            } else {
                                $price = 0;
                            }
                            if (count($parts) > 3) {
                                $sku = $parts[3];
                            } else {
                                $sku = '';
                            }
                            if (count($parts) > 4) {
                                $sort_order = $parts[4];
                            } else {
                                $sort_order = 0;
                            }
                            if (count($parts) > 5) {
                                $max_characters = $parts[5];
                            } else {
                                $max_characters = '';
                            }
                            if (count($parts) > 6) {
                                $file_extension = $parts[6];
                            } else {
                                $file_extension = '';
                            }
                            if (count($parts) > 7) {
                                $image_size_x = $parts[7];
                            } else {
                                $image_size_x = '';
                            }
                            if (count($parts) > 8) {
                                $image_size_y = $parts[8];
                            } else {
                                $image_size_y = '';
                            }
                            switch ($type) {
                                case 'file':
                                    /* TODO */
                                    $custom_options[count($custom_options) - 1]['price_type'] = $price_type;
                                    $custom_options[count($custom_options) - 1]['price'] = $price;
                                    $custom_options[count($custom_options) - 1]['sku'] = $sku;
                                    $custom_options[count($custom_options) - 1]['file_extension'] = $file_extension;
                                    $custom_options[count($custom_options) - 1]['image_size_x'] = $image_size_x;
                                    $custom_options[count($custom_options) - 1]['image_size_y'] = $image_size_y;
                                    break;
                                case 'field':
                                    $custom_options[count($custom_options) - 1]['max_characters'] = $max_characters;
                                case 'area':
                                    $custom_options[count($custom_options) - 1]['max_characters'] = $max_characters;
                                    /* NO BREAK */
                                /* NO BREAK */
                                case 'date':
                                case 'date_time':
                                case 'time':
                                    $custom_options[count($custom_options) - 1]['price_type'] = $price_type;
                                    $custom_options[count($custom_options) - 1]['price'] = $price;
                                    $custom_options[count($custom_options) - 1]['sku'] = $sku;
                                    break;
                                case 'drop_down':
                                case 'radio':
                                case 'checkbox':
                                case 'multiple':
                                default:
                                    $custom_options[count($custom_options) - 1]['values'][] = array('is_delete' => 0, 'title' => $title, 'option_type_id' => -1, 'price_type' => $price_type, 'price' => $price, 'sku' => $sku, 'sort_order' => $sort_order, 'max_characters' => $max_characters);
                                    break;
                            }
                        }
                    }
                }
                /* END CUSTOM OPTION CODE */
                continue;
            }
            $isArray = false;
            $setValue = $value;
            if ($attribute->getFrontendInput() == 'multiselect') {
                $value = explode(self::MULTI_DELIMITER, $value);
                $isArray = true;
                $setValue = array();
            }
            if ($value && $attribute->getBackendType() == 'decimal') {
                $setValue = $this->getNumber($value);
            }
            if ($attribute->usesSource()) {
                $options = $attribute->getSource()->getAllOptions(false);
                if ($isArray) {
                    foreach ($options as $item) {
                        if (in_array($item['label'], $value)) {
                            $setValue[] = $item['value'];
                        }
                    }
                } else {
                    $setValue = null;
                    foreach ($options as $item) {
                        #$item_label = (string)$item['label'];
                        #$item_value = (string)$value;
                        #echo "LABEL: " . $item_label . "<br>";
                        #echo "VALUE: " . $item_value  . "<br>";
                        #echo "COMPARE: " . strcmp(strtolower($item_label), strtolower($item_value)) . "<br>";
                        #if (trim($item_label) == trim($item_value) || strcmp(strtolower($item_label), strtolower($item_value)) == 0) {
                        if ($item['label'] == $value) {
                            $setValue = $item['value'];
                        }
                    }
                }
            }
            $product->setData($field, $setValue);
        }
        if (!$product->getVisibility()) {
            $product->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_NOT_VISIBLE);
        }
        $stockData = array();
        $inventoryFields = isset($this->_inventoryFieldsProductTypes[$product->getTypeId()]) ? $this->_inventoryFieldsProductTypes[$product->getTypeId()] : array();
        foreach ($inventoryFields as $field) {
            if (isset($importData[$field])) {
                if (in_array($field, $this->_toNumber)) {
                    $stockData[$field] = $this->getNumber($importData[$field]);
                } else {
                    $stockData[$field] = $importData[$field];
                }
            }
        }
        $product->setStockData($stockData);
        if ($new || $this->getBatchParams('reimport_images') == "true") {
            //starts CHECK FOR IF REIMPORTING IMAGES TO PRODUCTS IS TRUE
            //this is a check if we want to delete all images before import of images from csv
            if ($this->getBatchParams('deleteall_andreimport_images') == "true" && $importData["image"] != "" && $importData["small_image"] != "" && $importData["thumbnail"] != "") {
                $attributes = $product->getTypeInstance()->getSetAttributes();
                if (isset($attributes['media_gallery'])) {
                    $gallery = $attributes['media_gallery'];
                    //Get the images
                    $galleryData = $product->getMediaGallery();
                    if (!empty($galleryData)) {
                        foreach ($galleryData['images'] as $image) {
                            //If image exists
                            if ($gallery->getBackend()->getImage($product, $image['file'])) {
                                $gallery->getBackend()->removeImage($product, $image['file']);
                                //if ( file_exists(Mage::getBaseDir('media') . DS . 'catalog' . DS . 'product' . $image['file'] ) ) {
                                if (file_exists($image['file'])) {
                                    $ext = substr(strrchr($image['file'], '.'), 1);
                                    //if( strlen( $ext ) == 3 ) { //maybe needs to be 3
                                    if (strlen($ext) == 4) {
                                        unlink(Mage::getBaseDir('media') . DS . 'catalog' . DS . 'product' . $image['file']);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            if ($importData["image"] != "" || $importData["small_image"] != "" || $importData["thumbnail"] != "") {
                $mediaGalleryBackendModel = $this->getAttribute('media_gallery')->getBackend();
                $arrayToMassAdd = array();
                foreach ($product->getMediaAttributes() as $mediaAttributeCode => $mediaAttribute) {
                    if (isset($importData[$mediaAttributeCode])) {
                        $file = $importData[$mediaAttributeCode];
                        if (file_exists(Mage::getBaseDir('media') . DS . 'import' . $file)) {
                            if (trim($file) && !$mediaGalleryBackendModel->getImage($product, $file)) {
                                $arrayToMassAdd[] = array('file' => trim($file), 'mediaAttribute' => $mediaAttributeCode);
                            }
                        }
                    }
                }
                if ($this->getBatchParams('exclude_images') == "true") {
                    #$product -> addImageToMediaGallery( Mage :: getBaseDir( 'media' ) . DS . 'import/' . $file, $fields, false );
                    $addedFilesCorrespondence = $mediaGalleryBackendModel->addImagesWithDifferentMediaAttributes($product, $arrayToMassAdd, Mage::getBaseDir('media') . DS . 'import', false);
                } else {
                    #$product -> addImageToMediaGallery( Mage :: getBaseDir( 'media' ) . DS . 'import/' . $file, $fields, false, false );
                    $addedFilesCorrespondence = $mediaGalleryBackendModel->addImagesWithDifferentMediaAttributes($product, $arrayToMassAdd, Mage::getBaseDir('media') . DS . 'import', false, false);
                }
                foreach ($product->getMediaAttributes() as $mediaAttributeCode => $mediaAttribute) {
                    $addedFile = '';
                    if (isset($importData[$mediaAttributeCode . '_label'])) {
                        $fileLabel = trim($importData[$mediaAttributeCode . '_label']);
                        if (isset($importData[$mediaAttributeCode])) {
                            $keyInAddedFile = array_search($importData[$mediaAttributeCode], $addedFilesCorrespondence['alreadyAddedFiles']);
                            if ($keyInAddedFile !== false) {
                                $addedFile = $addedFilesCorrespondence['alreadyAddedFilesNames'][$keyInAddedFile];
                            }
                        }
                        if (!$addedFile) {
                            $addedFile = $product->getData($mediaAttributeCode);
                        }
                        if ($fileLabel && $addedFile) {
                            $mediaGalleryBackendModel->updateImage($product, $addedFile, array('label' => $fileLabel));
                        }
                    }
                }
            }
            //end check on empty values
            if (!empty($importData['gallery'])) {
                $galleryData = explode(',', $importData["gallery"]);
                foreach ($galleryData as $gallery_img) {
                    try {
                        if ($this->getBatchParams('exclude_gallery_images') == "true") {
                            $product->addImageToMediaGallery(Mage::getBaseDir('media') . DS . 'import' . $gallery_img, null, false, true);
                        } else {
                            $product->addImageToMediaGallery(Mage::getBaseDir('media') . DS . 'import' . $gallery_img, null, false, false);
                        }
                    } catch (Exception $e) {
                        Mage::log(sprintf('failed to import gallery images: %s', $e->getMessage()), null, 'ce_product_import_export_errors.log');
                    }
                }
            }
            #} // this ends check if enabled
        }
        // this else is for check for if we can reimport products
        $product->setIsMassupdate(true);
        $product->setExcludeUrlRewrite(true);
        //PATCH FOR Fatal error: Call to a member function getStoreId() on a non-object in D:\web\magento\app\code\core\Mage\Bundle\Model\Selection.php on line 52
        if (!Mage::registry('product')) {
            Mage::register('product', Mage::getModel('catalog/product')->setStoreId(0));
            //Mage::register('product', $product); maybe this is needed for when importing multi-store bundle vs above
        }
        $product->save();
        if (isset($importData['product_tags']) && $importData['product_tags'] != "") {
            #$configProductTags = $this->userCSVDataAsArray($importData['product_tags']);
            $configProductTags = explode(',', $importData['product_tags']);
            #foreach ($commadelimiteddata as $dataseperated) {
            foreach ($configProductTags as $tagName) {
                try {
                    $commadelimiteddata = explode(':', $tagName);
                    $tagName = $commadelimiteddata[1];
                    $tagModel = Mage::getModel('tag/tag');
                    $result = $tagModel->loadByName($tagName);
                    #echo $result;
                    #echo "PRODID: " . $product -> getIdBySku( $importData['sku'] ) . " Name: " . $tagName;
                    $tagModel->setName($tagName)->setStoreId($importData['store'])->setStatus($tagModel->getApprovedStatus())->save();
                    $tagRelationModel = Mage::getModel('tag/tag_relation');
                    /*$tagRelationModel->loadByTagCustomer($product -> getIdBySku( $importData['sku'] ), $tagModel->getId(), '13194', Mage::app()->getStore()->getId());*/
                    if ($importData['customerID'] != "NULL") {
                        $tagRelationModel->setTagId($tagModel->getId())->setCustomerId(trim($commadelimiteddata[0]))->setProductId($product->getIdBySku($importData['sku']))->setStoreId($importData['store'])->setCreatedAt(now())->setActive(1)->save();
                    } else {
                        #echo "HERE";
                        $data['tag_id'] = $tagModel->getId();
                        $data['name'] = trim($tagName);
                        $data['status'] = $tagModel->getApprovedStatus();
                        $data['first_customer_id'] = "0";
                        $data['first_store_id'] = "0";
                        $data['visible_in_store_ids'] = array();
                        $data['store_id'] = "1";
                        $data['base_popularity'] = isset($importData['base_popularity']) ? $importData['base_popularity'] : 0;
                        $data['store'] = $importData['store'];
                        $tagModel2 = Mage::getModel('tag/tag');
                        $tagModel2->addData($data);
                        $productIds[] = $product->getIdBySku($importData['sku']);
                        #print_r($productIds);
                        #print_r($tagModel2);
                        $tagRelationModel2 = Mage::getModel('tag/tag_relation');
                        $tagRelationModel2->addRelations($tagModel2, $productIds);
                        $tagModel2->save();
                        $tagModel2->aggregate();
                    }
                    $tagModel->aggregate();
                } catch (Exception $e) {
                    Mage::log(sprintf('failed to import product tags: %s', $e->getMessage()), null, 'ce_product_import_export_errors.log');
                }
            }
        }
        /* Add the custom options specified in the CSV import file */
        if (count($custom_options)) {
            /* Remove existing custom options attached to the product */
            foreach ($product->getOptions() as $o) {
                $o->getValueInstance()->deleteValue($o->getId());
                $o->deletePrices($o->getId());
                $o->deleteTitles($o->getId());
                $o->delete();
            }
            foreach ($custom_options as $option) {
                try {
                    $opt = Mage::getModel('catalog/product_option');
                    $opt->setProduct($product);
                    $opt->addOption($option);
                    $opt->saveOptions();
                } catch (Exception $e) {
                    Mage::log(sprintf('failed to import custom options: %s', $e->getMessage()), null, 'ce_product_import_export_errors.log');
                }
            }
        }
        if ($iscustomoptions == "true") {
            ######### CUSTOM QUERY FIX FOR DISAPPEARING OPTIONS #################
            // fetch write database connection that is used in Mage_Core module
            if ($currentproducttype == "simple") {
                $prefix = Mage::getConfig()->getNode('global/resources/db/table_prefix');
                $fixOptions = Mage::getSingleton('core/resource')->getConnection('core_write');
                // now $write is an instance of Zend_Db_Adapter_Abstract
                $fixOptions->query("UPDATE " . $prefix . "catalog_product_entity SET has_options = 1 WHERE type_id = 'simple' AND entity_id IN (SELECT distinct(product_id) FROM " . $prefix . "catalog_product_option)");
            } else {
                if ($currentproducttype == "configurable") {
                    $prefix = Mage::getConfig()->getNode('global/resources/db/table_prefix');
                    $fixOptions = Mage::getSingleton('core/resource')->getConnection('core_write');
                    // now $write is an instance of Zend_Db_Adapter_Abstract
                    $fixOptions->query("UPDATE " . $prefix . "catalog_product_entity SET has_options = 1 WHERE type_id = 'configurable' AND entity_id IN (SELECT distinct(product_id) FROM " . $prefix . "catalog_product_option)");
                }
            }
        }
        /* DOWNLOADBLE PRODUCT FILE METHOD START */
        #print_r($filearrayforimport);
        if (isset($filearrayforimport)) {
            $filecounterinternall = 1;
            foreach ($filearrayforimport as $fileinfo) {
                $document_directory = Mage::getBaseDir('media') . DS . 'import' . DS;
                $files = $fileinfo['file'];
                #echo "FILE: " . $fileinfo['file'];
                #echo "ID: " . $product->getId();
                $resource = Mage::getSingleton('core/resource');
                $prefix = Mage::getConfig()->getNode('global/resources/db/table_prefix');
                $write = $resource->getConnection('core_write');
                $read = $resource->getConnection('core_read');
                $select_qry = $read->query("SHOW TABLE STATUS LIKE '" . $prefix . "downloadable_link' ");
                $row = $select_qry->fetch();
                $next_id = $row['Auto_increment'];
                $okvalueformodelID = $next_id - $filecounterinternall;
                #echo "next_id: " . $okvalueformodelID;
                $linkModel = Mage::getModel('downloadable/link')->load($okvalueformodelID);
                $link_file = $document_directory . $files;
                $file = realpath($link_file);
                if (!$file || !file_exists($file)) {
                    Mage::throwException(Mage::helper('catalog')->__('Link  file ' . $file . ' not exists'));
                }
                $pathinfo = pathinfo($file);
                $linkfile = Varien_File_Uploader::getCorrectFileName($pathinfo['basename']);
                $dispretionPath = Varien_File_Uploader::getDispretionPath($linkfile);
                $linkfile = $dispretionPath . DS . $linkfile;
                $linkfile = $dispretionPath . DS . Varien_File_Uploader::getNewFileName(Mage_Downloadable_Model_Link::getBasePath() . DS . $linkfile);
                $ioAdapter = new Varien_Io_File();
                $ioAdapter->setAllowCreateFolders(true);
                $distanationDirectory = dirname(Mage_Downloadable_Model_Link::getBasePath() . DS . $linkfile);
                try {
                    $ioAdapter->open(array('path' => $distanationDirectory));
                    $ioAdapter->cp($file, Mage_Downloadable_Model_Link::getBasePath() . DS . $linkfile);
                    $ioAdapter->chmod(Mage_Downloadable_Model_Link::getBasePath() . DS . $linkfile, 0777);
                } catch (Exception $e) {
                    Mage::throwException(Mage::helper('catalog')->__('Failed to move file: %s', $e->getMessage()));
                    Mage::log(sprintf('failed to move file: %s', $e->getMessage()), null, 'ce_product_import_export_errors.log');
                }
                $linkfile = str_replace(DS, '/', $linkfile);
                #echo "SET: " . $linkfile;
                $linkModel->setLinkFile($linkfile);
                $linkModel->save();
                $intesdf = $next_id - $filecounterinternall;
                $write->query("UPDATE `" . $prefix . "downloadable_link_title` SET title = '" . $fileinfo['name'] . "' WHERE link_id = '" . $intesdf . "'");
                $write->query("UPDATE `" . $prefix . "downloadable_link_price` SET price = '" . $fileinfo['price'] . "' WHERE link_id = '" . $intesdf . "'");
                #$product->setLinksPurchasedSeparately(false);
                #$product->setLinksPurchasedSeparately(0);
                $filecounterinternall++;
            }
        }
        /* END DOWNLOADBLE METHOD */
        /* SAMPLE FILE DOWNLOADBLE PRODUCT SAMPLE FILE METHOD START */
        #print_r($filenameforsamplearrayforimport);
        if (isset($filenameforsamplearrayforimport)) {
            $filecounterinternall = 1;
            foreach ($filenameforsamplearrayforimport as $fileinfo) {
                $document_directory = Mage::getBaseDir('media') . DS . 'import';
                $samplefiles = $fileinfo['file'];
                #print_r($filenameforsamplearrayforimport);
                #echo "ID: " . $fileinfo['name'] ."<br/>";
                $resource = Mage::getSingleton('core/resource');
                $prefix = Mage::getConfig()->getNode('global/resources/db/table_prefix');
                $write = $resource->getConnection('core_write');
                $read = $resource->getConnection('core_read');
                $select_qry = $read->query("SHOW TABLE STATUS LIKE '" . $prefix . "downloadable_link' ");
                $row = $select_qry->fetch();
                $next_id = $row['Auto_increment'];
                $okvalueformodelID = $next_id - $filecounterinternall;
                #echo "next_id: " . $okvalueformodelID."<br/>";
                $linkSampleModel = Mage::getModel('downloadable/link')->load($okvalueformodelID);
                $link_sample_file = $document_directory . $samplefiles;
                $file = realpath($link_sample_file);
                if (!$file || !file_exists($file)) {
                    Mage::throwException(Mage::helper('catalog')->__('Link sample file ' . $file . ' not exists'));
                    Mage::log(sprintf('downloadable product sample file ' . $file . ' link does not exist: %s', $e->getMessage()), null, 'ce_product_import_export_errors.log');
                }
                $pathinfo = pathinfo($file);
                $linksamplefile = Varien_File_Uploader::getCorrectFileName($pathinfo['basename']);
                $dispretionPath = Varien_File_Uploader::getDispretionPath($linksamplefile);
                $linksamplefile = $dispretionPath . DS . $linksamplefile;
                $linksamplefile = $dispretionPath . DS . Varien_File_Uploader::getNewFileName(Mage_Downloadable_Model_Link::getBaseSamplePath() . DS . $linksamplefile);
                $ioAdapter = new Varien_Io_File();
                $ioAdapter->setAllowCreateFolders(true);
                $distanationDirectory = dirname(Mage_Downloadable_Model_Link::getBaseSamplePath() . DS . $linksamplefile);
                try {
                    $ioAdapter->open(array('path' => $distanationDirectory));
                    $ioAdapter->cp($file, Mage_Downloadable_Model_Link::getBaseSamplePath() . $linksamplefile);
                    $ioAdapter->chmod(Mage_Downloadable_Model_Link::getBaseSamplePath() . $linksamplefile, 0777);
                } catch (Exception $e) {
                    Mage::throwException(Mage::helper('catalog')->__('Failed to move sample file: %s', $e->getMessage()));
                    Mage::log(sprintf('Failed to move sample file: %s', $e->getMessage()), null, 'ce_product_import_export_errors.log');
                }
                $linksamplefile = str_replace(DS, '/', $linksamplefile);
                $linkSampleModel->setSampleFile($linksamplefile);
                $linkSampleModel->save();
                #$intesdf = $next_id-1;
                $intesdf = $next_id - $filecounterinternall;
                $write->query("UPDATE `" . $prefix . "downloadable_link_title` SET title = '" . $fileinfo['name'] . "' WHERE link_id = '" . $intesdf . "'");
                $write->query("UPDATE `" . $prefix . "downloadable_link_price` SET price = '" . $fileinfo['price'] . "' WHERE link_id = '" . $intesdf . "'");
                $filecounterinternall++;
            }
        }
        /* END SAMPLE FILE DOWNLOADBLE METHOD */
        /* START OF SUPER ATTRIBUTE PRICING */
        if ($finalsuperattributetype == 'configurable') {
            if ($finalsuperattributepricing != "") {
                $adapter = Mage::getSingleton('core/resource')->getConnection('core_write');
                $read = Mage::getSingleton('core/resource')->getConnection('core_read');
                $superProduct = Mage::getModel('catalog/product')->load($product->getId());
                $superArray = $superProduct->getTypeInstance()->getConfigurableAttributesAsArray();
                #print_r($superArray);
                $SuperAttributePricingData = array();
                $FinalSuperAttributeData = array();
                $SuperAttributePricingData = explode('|', $finalsuperattributepricing);
                $prefix = Mage::getConfig()->getNode('global/resources/db/table_prefix');
                foreach ($superArray as $key => $val) {
                    #$x = 0 ;
                    foreach ($val['values'] as $keyValues => $valValues) {
                        foreach ($SuperAttributePricingData as $singleattributeData) {
                            $FinalSuperAttributeData = explode(':', $singleattributeData);
                            if ($FinalSuperAttributeData[0] == $superArray[$key]['values'][$keyValues]['label']) {
                                if ($new) {
                                    $insertPrice = 'INSERT into ' . $prefix . 'catalog_product_super_attribute_pricing (product_super_attribute_id, value_index, is_percent, pricing_value) VALUES
														 ("' . $superArray[$key]['values'][$keyValues]['product_super_attribute_id'] . '", "' . $superArray[$key]['values'][$keyValues]['value_index'] . '", "' . $FinalSuperAttributeData[2] . '", "' . $FinalSuperAttributeData[1] . '");';
                                    #echo "SQL2: " . $insertPrice;
                                    $adapter->query($insertPrice);
                                } else {
                                    if ($FinalSuperAttributeData[1] != "") {
                                        $finalpriceforupdate = $FinalSuperAttributeData[1];
                                        $select_qry2 = $read->query("SELECT value_id FROM " . $prefix . "catalog_product_super_attribute_pricing WHERE product_super_attribute_id = '" . $superArray[$key]['values'][$keyValues]['product_super_attribute_id'] . "' AND value_index = '" . $superArray[$key]['values'][$keyValues]['value_index'] . "'");
                                        $newrowItemId2 = $select_qry2->fetch();
                                        $db_product_id = $newrowItemId2['value_id'];
                                        if ($db_product_id == "") {
                                            $insertPrice = 'INSERT into ' . $prefix . 'catalog_product_super_attribute_pricing (product_super_attribute_id, value_index, is_percent, pricing_value) VALUES
														 ("' . $superArray[$key]['values'][$keyValues]['product_super_attribute_id'] . '", "' . $superArray[$key]['values'][$keyValues]['value_index'] . '", "' . $FinalSuperAttributeData[2] . '", "' . $FinalSuperAttributeData[1] . '");';
                                            #echo "SQL2: " . $insertPrice;
                                            $adapter->query($insertPrice);
                                        } else {
                                            $updatePrice = "UPDATE " . $prefix . "catalog_product_super_attribute_pricing SET pricing_value = '" . $finalpriceforupdate . "' WHERE value_id = '" . $db_product_id . "'";
                                            #echo "SQL UPDATE: " . $updatePrice;
                                            $adapter->query($updatePrice);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        /* END OF SUPER ATTRIBUTE PRICING */
        /* ADDED FIX FOR IMAGE LABELS */
        if (isset($imagelabeldataforimport)) {
            #echo "PROD ID: " . $product->getId() . "<br/>";
            #echo "LABELS: " . $imagelabeldataforimport . "<br/>";
            $resource = Mage::getSingleton('core/resource');
            $prefix = Mage::getConfig()->getNode('global/resources/db/table_prefix');
            $prefixlabels = Mage::getConfig()->getNode('global/resources/db/table_prefix');
            $readlabels = $resource->getConnection('core_read');
            $writelabels = $resource->getConnection('core_write');
            $select_qry_labels = $readlabels->query("SELECT value_id FROM " . $prefixlabels . "catalog_product_entity_media_gallery WHERE entity_id = '" . $product->getId() . "'");
            $row_labels = $select_qry_labels->fetch();
            $value_id = $row_labels['value_id'];
            // now $write label to db
            $writelabels->query("UPDATE " . $prefix . "catalog_product_entity_media_gallery_value SET label = '" . $imagelabeldataforimport . "' WHERE value_id = '" . $value_id . "'");
            //this is for if you have flat product catalog enabled.. need to write values to both places
            #$writelabels->query("UPDATE ".$prefix."catalog_product_flat_1 SET image_label = '".$imagelabeldataforimport."' WHERE entity_id = '". $product->getId() ."'");
            #$writelabels->query("UPDATE ".$prefix."catalog_product_flat_1 SET image_label = '".$imagelabeldataforimport."' WHERE entity_id = '". $product->getId() ."'");
            #SELECT attribute_id FROM ".$prefixlabels."eav_attribute WHERE attribute_code = 'image_label';
            #$writelabels->query("UPDATE ".$prefix."catalog_product_entity_varchar SET value = '".$imagelabeldataforimport."' WHERE entity_id = '". $product->getId() ."' AND attribute_id = 101");
        }
        if (isset($smallimagelabeldataforimport)) {
            #echo "PROD ID: " . $product->getId() . "<br/>";
            #echo "LABELS: " . $smallimagelabeldataforimport . "<br/>";
            $resource = Mage::getSingleton('core/resource');
            $prefix = Mage::getConfig()->getNode('global/resources/db/table_prefix');
            $prefixlabels = Mage::getConfig()->getNode('global/resources/db/table_prefix');
            $readlabels = $resource->getConnection('core_read');
            $writelabels = $resource->getConnection('core_write');
            $select_qry_labels = $readlabels->query("SELECT value_id FROM " . $prefixlabels . "catalog_product_entity_media_gallery WHERE entity_id = '" . $product->getId() . "'");
            $row_labels = $select_qry_labels->fetch();
            $value_id = $row_labels['value_id'] + 1;
            // now $write label to db
            $writelabels->query("UPDATE " . $prefix . "catalog_product_entity_media_gallery_value SET label = '" . $smallimagelabeldataforimport . "' WHERE value_id = '" . $value_id . "'");
        }
        if (isset($thumbnailimagelabeldataforimport)) {
            #echo "PROD ID: " . $product->getId() . "<br/>";
            #echo "LABELS: " . $smallimagelabeldataforimport . "<br/>";
            $resource = Mage::getSingleton('core/resource');
            $prefix = Mage::getConfig()->getNode('global/resources/db/table_prefix');
            $prefixlabels = Mage::getConfig()->getNode('global/resources/db/table_prefix');
            $readlabels = $resource->getConnection('core_read');
            $writelabels = $resource->getConnection('core_write');
            $select_qry_labels = $readlabels->query("SELECT value_id FROM " . $prefixlabels . "catalog_product_entity_media_gallery WHERE entity_id = '" . $product->getId() . "'");
            $row_labels = $select_qry_labels->fetch();
            $value_id = $row_labels['value_id'] + 2;
            // now $write label to db
            $writelabels->query("UPDATE " . $prefix . "catalog_product_entity_media_gallery_value SET label = '" . $thumbnailimagelabeldataforimport . "' WHERE value_id = '" . $value_id . "'");
        }
        /* END FIX FOR IMAGE LABLES */
        return true;
    }
예제 #17
0
 public function addDownloads($_item_id, $new = true)
 {
     $model = Mage::getModel('soapsync/ibramssync');
     $item_id = $model->getCollection()->returnItemId($_item_id);
     $model->load($item_id);
     if (!($entity_id = $model->getMageId())) {
         Mage::getSingleton('adminhtml/session')->addError("Could not load product {$item_id}");
         //             continue;
         if (!$new) {
             return false;
         }
     }
     $type = 'links';
     $error = false;
     if (!$new) {
         Mage::helper('soapsync')->delLinks($entity_id);
     }
     $filePath = Mage_Downloadable_Model_Link::getBasePath();
     $jpg = str_replace(array('.JPG', '.jpeg', '.JPEG', '.psd', '.gif', '.tif', '.png', '.bmp', '.BMP'), '.jpg', $model->getFilename());
     if (is_file(Mage::getBaseDir('media') . DS . 'import' . DS . $jpg)) {
         $uploader = new Digiswiss_File_Uploader($jpg);
         $uploader->setAllowRenameFiles(true);
         $uploader->setFilesDispersion(true);
         try {
             $result = $uploader->save($filePath);
         } catch (Exception $e) {
             Mage::log($e->getMessage());
         }
         Mage::helper('soapsync')->saveLinkModel($result['file'], $entity_id, $this->_capt72);
     } else {
         $error = true;
         Mage::getSingleton('adminhtml/session')->addError("Downloadable 72dpi " . strtolower($model->getFilename()) . "  not found in media/import/");
     }
     // 				if (is_file(Mage::getBaseDir('media') . DS . 'import' . DS . $this->_folder150 . DS . $jpg)) {
     //     				$uploader = new Digiswiss_File_Uploader($jpg, $this->_folder150);
     //             $uploader->setAllowRenameFiles(true);
     //             $uploader->setFilesDispersion(true);
     //             try {
     //                 $result = $uploader->save($filePath);
     //             } catch(Exception $e) {
     //                 Mage::log($e->getMessage());
     //             }
     //     				Mage::helper('soapsync')->saveLinkModel($result['file'], $entity_id, $this->_capt150);
     //         } else {
     //             $error = true;
     //             Mage::getSingleton('adminhtml/session')->addError(
     //                       "Downloadable 150dpi " . strtolower($model->getFilename()) . "  not found in $this->_folder150"
     //                   );
     //         }
     if (is_file(Mage::getBaseDir('media') . DS . 'import' . DS . $this->_folder300 . DS . $jpg)) {
         $uploader = new Digiswiss_File_Uploader($jpg, $this->_folder300);
         $uploader->setAllowRenameFiles(true);
         $uploader->setFilesDispersion(true);
         try {
             $result = $uploader->save($filePath);
         } catch (Exception $e) {
             Mage::log($e->getMessage());
         }
         Mage::helper('soapsync')->saveLinkModel($result['file'], $entity_id, $this->_capt300);
     } else {
         $error = true;
         Mage::getSingleton('adminhtml/session')->addError("Downloadable 300dpi " . $jpg . "  not found in {$this->_folder300}");
     }
     //         $model->setId($item_id)->delete();
     if (!$new && !$error) {
         return true;
     }
 }
예제 #18
0
 /**
  * Download link action
  */
 public function linkAction()
 {
     $id = $this->getRequest()->getParam('id', 0);
     $linkPurchasedItem = Mage::getModel('downloadable/link_purchased_item')->load($id, 'link_hash');
     $order_item_id = $linkPurchasedItem->getOrderItemId();
     $checkGift = $this->checkGiftLink($order_item_id);
     if (!$linkPurchasedItem->getId()) {
         $this->_getCustomerSession()->addNotice(Mage::helper('downloadable')->__("Requested link does not exist."));
         return $this->_redirect('*/customer/products');
     }
     $product = Mage::getModel('catalog/product')->load($linkPurchasedItem->getProductId());
     //Modification. Put already loaded product into registry so it does not need to be loaded again
     //When checking for a copyright value.
     Mage::register('downloadable_product', $product);
     Mage::register('link_purchased_item', $linkPurchasedItem);
     if (!Mage::helper('downloadable')->getIsShareable($linkPurchasedItem)) {
         $customerId = $this->_getCustomerSession()->getCustomerId();
         if (!$customerId) {
             $product = Mage::getModel('catalog/product')->load($linkPurchasedItem->getProductId());
             if ($product->getId()) {
                 $notice = Mage::helper('downloadable')->__('Please log in to download your product or purchase <a href="%s">%s</a>.', $product->getProductUrl(), $product->getName());
             } else {
                 $notice = Mage::helper('downloadable')->__('Please log in to download your product.');
             }
             $this->_getCustomerSession()->addNotice($notice);
             $this->_getCustomerSession()->authenticate($this);
             $this->_getCustomerSession()->setBeforeAuthUrl(Mage::getUrl('downloadable/customer/products/'), array('_secure' => true));
             return;
         }
         $linkPurchased = Mage::getModel('downloadable/link_purchased')->load($linkPurchasedItem->getPurchasedId());
         if ($linkPurchased->getCustomerId() != $customerId) {
             $this->_getCustomerSession()->addNotice(Mage::helper('downloadable')->__("Requested link does not exist."));
             //return $this->_redirect('*/customer/products');
             return $this->_redirect('ecodes/account/products/');
         }
     }
     $downloadsLeft = $linkPurchasedItem->getNumberOfDownloadsBought() - $linkPurchasedItem->getNumberOfDownloadsUsed();
     $status = $linkPurchasedItem->getStatus();
     if ($status == Mage_Downloadable_Model_Link_Purchased_Item::LINK_STATUS_AVAILABLE && ($downloadsLeft || $linkPurchasedItem->getNumberOfDownloadsBought() == 0)) {
         $resource = '';
         $resourceType = '';
         if ($linkPurchasedItem->getLinkType() == Mage_Downloadable_Helper_Download::LINK_TYPE_URL) {
             $resource = $linkPurchasedItem->getLinkUrl();
             $resourceType = Mage_Downloadable_Helper_Download::LINK_TYPE_URL;
         } elseif ($linkPurchasedItem->getLinkType() == Mage_Downloadable_Helper_Download::LINK_TYPE_FILE) {
             $resource = Mage::helper('downloadable/file')->getFilePath(Mage_Downloadable_Model_Link::getBasePath(), $linkPurchasedItem->getLinkFile());
             $resourceType = Mage_Downloadable_Helper_Download::LINK_TYPE_FILE;
         }
         try {
             $linkPurchasedItem->setNumberOfDownloadsUsed($linkPurchasedItem->getNumberOfDownloadsUsed() + 1);
             if ($linkPurchasedItem->getNumberOfDownloadsBought() != 0 && !($downloadsLeft - 1)) {
                 $linkPurchasedItem->setStatus(Mage_Downloadable_Model_Link_Purchased_Item::LINK_STATUS_EXPIRED);
             }
             $linkPurchasedItem->save();
             /* Update in the volumelicense reports*/
             if (Mage::helper('core')->isModuleEnabled('ICC_Volumelicense')) {
                 $order_id = Mage::getResourceModel('sales/order_item_collection')->addAttributeToSelect('order_id')->addAttributeToFilter('item_id', $linkPurchasedItem->getOrderItemId())->getFirstItem()->getData();
                 if ($order_id) {
                     $order = Mage::getModel("sales/order")->load($order_id);
                     if ($order->getData('volume_license')) {
                         Mage::helper('volumelicense')->setReportsLog($order, FALSE, TRUE);
                         unset($order);
                     }
                 }
             }
             /* Update in the volumelicense reports code end*/
             // Ticket#2013121810000161, in case when PDF file has a huge size, we have to increase the value of NumberOfDownloadsUsed before downloading, to avoid killing the PHP script by web server by timeout
             $this->_processDownload($resource, $resourceType, $checkGift);
             exit(0);
         } catch (Exception $e) {
             $this->_getCustomerSession()->addError(Mage::helper('downloadable')->__('An error occurred while getting the requested content. Please contact the store owner.'));
         }
     } elseif ($status == Mage_Downloadable_Model_Link_Purchased_Item::LINK_STATUS_EXPIRED) {
         $this->_getCustomerSession()->addNotice(Mage::helper('downloadable')->__('The link has expired.'));
     } elseif ($status == Mage_Downloadable_Model_Link_Purchased_Item::LINK_STATUS_PENDING || $status == Mage_Downloadable_Model_Link_Purchased_Item::LINK_STATUS_PAYMENT_REVIEW) {
         $this->_getCustomerSession()->addNotice(Mage::helper('downloadable')->__('The link is not available.'));
     } else {
         $this->_getCustomerSession()->addError(Mage::helper('downloadable')->__('An error occurred while getting the requested content. Please contact the store owner.'));
     }
     //return $this->_redirect('*/customer/products');
     return $this->_redirect('ecodes/account/products/');
 }
예제 #19
0
 /**
  * Download link action
  *
  */
 public function linkAction()
 {
     $linkId = $this->getRequest()->getParam('id', 0);
     $link = AO::getModel('downloadable/link')->load($linkId);
     if ($link->getId()) {
         $resource = '';
         $resourceType = '';
         if ($link->getLinkType() == Mage_Downloadable_Helper_Download::LINK_TYPE_URL) {
             $resource = $link->getLinkUrl();
             $resourceType = Mage_Downloadable_Helper_Download::LINK_TYPE_URL;
         } elseif ($link->getLinkType() == Mage_Downloadable_Helper_Download::LINK_TYPE_FILE) {
             $resource = AO::helper('downloadable/file')->getFilePath(Mage_Downloadable_Model_Link::getBasePath(), $link->getLinkFile());
             $resourceType = Mage_Downloadable_Helper_Download::LINK_TYPE_FILE;
         }
         try {
             $this->_processDownload($resource, $resourceType);
         } catch (Mage_Core_Exception $e) {
             $this->_getCustomerSession()->addError(AO::helper('downloadable')->__('Sorry, there was an error getting requested content'));
         }
     }
 }
예제 #20
0
 /**
  * Decode file from base64 and upload it to donwloadable 'tmp' folder
  *
  * @param array $fileInfo
  * @param string $type
  * @return string
  */
 protected function _uploadFile($fileInfo, $type)
 {
     $tmpPath = '';
     if ($type == 'sample') {
         $tmpPath = Mage_Downloadable_Model_Sample::getBaseTmpPath();
     } elseif ($type == 'link') {
         $tmpPath = Mage_Downloadable_Model_Link::getBaseTmpPath();
     } elseif ($type == 'link_samples') {
         $tmpPath = Mage_Downloadable_Model_Link::getBaseSampleTmpPath();
     }
     $result = array();
     $url = $fileInfo['url'];
     $remoteFileName = $fileInfo['name'];
     $ioAdapter = new Varien_Io_File();
     $ioAdapter->checkAndCreateFolder($tmpPath);
     $ioAdapter->open(array('path' => $tmpPath));
     $fileName = $tmpPath . DS . Varien_File_Uploader::getCorrectFileName($remoteFileName);
     if ($ioAdapter->cp($url, $fileName)) {
         Mage::helper('core/file_storage_database')->saveFile($fileName);
     }
     $result['file'] = $remoteFileName;
     $result['status'] = 'new';
     $result['name'] = $remoteFileName;
     return Mage::helper('core')->jsonEncode(array($result));
 }
예제 #21
0
 protected function _processDownloadableProduct($product, &$importData)
 {
     // comment if --------------------------
     //if ($new) {
     $filearrayforimports = array();
     $downloadableitems = array();
     $downloadableitemsoptionscount = 0;
     //THIS IS FOR DOWNLOADABLE OPTIONS
     $commadelimiteddata = explode('|', $importData['downloadable_options']);
     foreach ($commadelimiteddata as $data) {
         $configBundleOptionsCodes = $this->userCSVDataAsArray($data);
         $downloadableitems['link'][$downloadableitemsoptionscount]['is_delete'] = 0;
         $downloadableitems['link'][$downloadableitemsoptionscount]['link_id'] = 0;
         $downloadableitems['link'][$downloadableitemsoptionscount]['title'] = $configBundleOptionsCodes[0];
         $downloadableitems['link'][$downloadableitemsoptionscount]['price'] = $configBundleOptionsCodes[1];
         $downloadableitems['link'][$downloadableitemsoptionscount]['number_of_downloads'] = $configBundleOptionsCodes[2];
         $downloadableitems['link'][$downloadableitemsoptionscount]['is_shareable'] = 2;
         if (isset($configBundleOptionsCodes[5])) {
             #$downloadableitems['link'][$downloadableitemsoptionscount]['sample'] = '';
             $downloadableitems['link'][$downloadableitemsoptionscount]['sample'] = array('file' => '[]', 'type' => 'url', 'url' => '' . $configBundleOptionsCodes[5] . '');
         } else {
             $downloadableitems['link'][$downloadableitemsoptionscount]['sample'] = '';
         }
         $downloadableitems['link'][$downloadableitemsoptionscount]['file'] = '';
         $downloadableitems['link'][$downloadableitemsoptionscount]['type'] = $configBundleOptionsCodes[3];
         #$downloadableitems['link'][$downloadableitemsoptionscount]['link_url'] = $configBundleOptionsCodes[4];
         if ($configBundleOptionsCodes[3] == "file") {
             #$filearrayforimport = array('file'  => 'media/import/mypdf.pdf' , 'name'  => 'asdad.txt', 'size'  => '316', 'status'  => 'old');
             #$document_directory =  Mage :: getBaseDir( 'media' ) . DS . 'import' . DS;
             #echo "DIRECTORY: " . $document_directory;
             #$filearrayforimport = '[{"file": "/home/discou33/public_html/media/import/mypdf.pdf", "name": "mypdf.pdf", "status": "new"}]';
             #$filearrayforimport = '[{"file": "mypdf.pdf", "name": "quickstart.pdf", "size": 324075, "status": "new"}]';
             #$product->setLinksPurchasedSeparately(0);
             #$product->setLinksPurchasedSeparately(false);
             #$files = Zend_Json::decode($filearrayforimport);
             #$files = "mypdf.pdf";
             //--------------- upload file ------------------
             $document_directory = Mage::getBaseDir('media') . DS . 'import' . DS . $this->__vendorName . DS;
             $files = '' . $configBundleOptionsCodes[4] . '';
             $link_file = $document_directory . $files;
             $file = realpath($link_file);
             if (!$file || !file_exists($file)) {
                 Mage::throwException(Mage::helper('catalog')->__($rowInfo . 'Link  file ' . $file . ' not exists'));
             }
             $pathinfo = pathinfo($file);
             $linkfile = Varien_File_Uploader::getCorrectFileName($pathinfo['basename']);
             $dispretionPath = Varien_File_Uploader::getDispretionPath($linkfile);
             $linkfile = $dispretionPath . DS . $linkfile;
             $linkfile = $dispretionPath . DS . Varien_File_Uploader::getNewFileName(Mage_Downloadable_Model_Link::getBaseTmpPath() . DS . $linkfile);
             $ioAdapter = new Varien_Io_File();
             $ioAdapter->setAllowCreateFolders(true);
             $distanationDirectory = dirname(Mage_Downloadable_Model_Link::getBaseTmpPath() . DS . $linkfile);
             try {
                 $ioAdapter->open(array('path' => $distanationDirectory));
                 $ioAdapter->cp($file, Mage_Downloadable_Model_Link::getBaseTmpPath() . DS . $linkfile);
                 $ioAdapter->chmod(Mage_Downloadable_Model_Link::getBaseTmpPath() . DS . $linkfile, 0777);
             } catch (exception $e) {
                 Mage::throwException(Mage::helper('catalog')->__('Failed to move file: %s', $e->getMessage()));
             }
             //{"file": "/2/_/2.jpg", "name": "2.jpg", "size": 23407, "status": "new"}
             $linkfile = str_replace(DS, '/', $linkfile);
             $filearrayforimports = array(array('file' => $linkfile, 'name' => $pathinfo['filename'] . '.' . $pathinfo['extension'], 'status' => 'new', 'size' => filesize($file)));
             if (isset($configBundleOptionsCodes[5])) {
                 if ($configBundleOptionsCodes[5] == 0) {
                     $linkspurchasedstatus = 0;
                     $linkspurchasedstatustext = false;
                 } else {
                     $linkspurchasedstatus = 1;
                     $linkspurchasedstatustext = true;
                 }
                 $product->setLinksPurchasedSeparately($linkspurchasedstatus);
                 $product->setLinksPurchasedSeparately($linkspurchasedstatustext);
             }
             //$downloadableitems['link'][$downloadableitemsoptionscount]['link_file'] = $linkfile;
             $downloadableitems['link'][$downloadableitemsoptionscount]['file'] = Mage::helper('core')->jsonEncode($filearrayforimports);
         } else {
             if ($configBundleOptionsCodes[3] == "url") {
                 $downloadableitems['link'][$downloadableitemsoptionscount]['link_url'] = $configBundleOptionsCodes[4];
             }
         }
         $downloadableitems['link'][$downloadableitemsoptionscount]['sort_order'] = 0;
         $product->setDownloadableData($downloadableitems);
         $downloadableitemsoptionscount += 1;
     }
     #print_r($downloadableitems);
     //}
 }
 /**
  * Enter description here...
  *
  * @return Mage_Downloadable_Model_Product_Type
  */
 public function save()
 {
     parent::save();
     $product = $this->getProduct();
     /* @var Mage_Catalog_Model_Product $product */
     if ($data = $product->getDownloadableData()) {
         if (isset($data['sample'])) {
             $_deleteItems = array();
             foreach ($data['sample'] as $sampleItem) {
                 if ($sampleItem['is_delete'] == '1') {
                     if ($sampleItem['sample_id']) {
                         $_deleteItems[] = $sampleItem['sample_id'];
                     }
                 } else {
                     unset($sampleItem['is_delete']);
                     if (!$sampleItem['sample_id']) {
                         unset($sampleItem['sample_id']);
                     }
                     $sampleModel = Mage::getModel('downloadable/sample');
                     $files = array();
                     if (isset($sampleItem['file'])) {
                         $files = Zend_Json::decode($sampleItem['file']);
                         unset($sampleItem['file']);
                     }
                     $sampleModel->setData($sampleItem)->setSampleType($sampleItem['type'])->setProductId($product->getId())->setStoreId($product->getStoreId());
                     $fileStatusNew = false;
                     if (isset($files[0]) && $sampleModel->getSampleType() == Mage_Downloadable_Helper_Download::LINK_TYPE_FILE) {
                         $sampleModel->setSampleFile($files[0]['file']);
                         if ($files[0]['status'] == 'new') {
                             $fileStatusNew = true;
                         }
                     }
                     $sampleModel->save();
                     if ($sampleModel->getSampleType() == Mage_Downloadable_Helper_Download::LINK_TYPE_FILE && $fileStatusNew) {
                         try {
                             Mage::helper('downloadable/file')->moveFileFromTmp(Mage_Downloadable_Model_Sample::getBaseTmpPath(), Mage_Downloadable_Model_Sample::getBasePath(), $files[0]['file']);
                         } catch (Exception $e) {
                             Mage::throwException(Mage::helper('downloadable')->__('An error occurred while saving the file(s).'));
                         }
                     }
                 }
             }
             if ($_deleteItems) {
                 Mage::getResourceModel('downloadable/sample')->deleteItems($_deleteItems);
             }
         }
         if (isset($data['link'])) {
             $_deleteItems = array();
             foreach ($data['link'] as $linkItem) {
                 if ($linkItem['is_delete'] == '1') {
                     if ($linkItem['link_id']) {
                         $_deleteItems[] = $linkItem['link_id'];
                     }
                 } else {
                     unset($linkItem['is_delete']);
                     if (!$linkItem['link_id']) {
                         unset($linkItem['link_id']);
                     }
                     $files = array();
                     if (isset($linkItem['file'])) {
                         $files = Zend_Json::decode($linkItem['file']);
                         unset($linkItem['file']);
                     }
                     $sample = array();
                     if (isset($linkItem['sample'])) {
                         $sample = $linkItem['sample'];
                         unset($linkItem['sample']);
                     }
                     $linkModel = Mage::getModel('downloadable/link')->setData($linkItem)->setLinkType($linkItem['type'])->setProductId($product->getId())->setStoreId($product->getStoreId())->setWebsiteId($product->getStore()->getWebsiteId());
                     if (null === $linkModel->getPrice()) {
                         $linkModel->setPrice(0);
                     }
                     if ($linkModel->getIsUnlimited()) {
                         $linkModel->setNumberOfDownloads(0);
                     }
                     $fileStatusNew = false;
                     if (isset($files[0]) && $linkModel->getLinkType() == Mage_Downloadable_Helper_Download::LINK_TYPE_FILE) {
                         $linkModel->setLinkFile($files[0]['file']);
                         if ($files[0]['status'] == 'new') {
                             $fileStatusNew = true;
                         }
                     }
                     $sampleFileNew = false;
                     if ($sample && isset($sample['type'])) {
                         if ($sample['type'] == 'url' && $sample['url'] != '') {
                             $linkModel->setSampleUrl($sample['url'])->setSampleType($sample['type']);
                         }
                         $sampleFile = Zend_Json::decode($sample['file']);
                         if ($sample['type'] == Mage_Downloadable_Helper_Download::LINK_TYPE_FILE && isset($sampleFile[0])) {
                             $linkModel->setSampleFile($sampleFile[0]['file'])->setSampleType($sample['type']);
                             if ($sampleFile[0]['status'] == 'new') {
                                 $sampleFileNew = true;
                             }
                         }
                     }
                     $linkModel->save();
                     if ($linkModel->getLinkType() == Mage_Downloadable_Helper_Download::LINK_TYPE_FILE && $fileStatusNew) {
                         try {
                             Mage::helper('downloadable/file')->moveFileFromTmp(Mage_Downloadable_Model_Link::getBaseTmpPath(), Mage_Downloadable_Model_Link::getBasePath(), $files[0]['file']);
                         } catch (Exception $e) {
                             Mage::throwException(Mage::helper('downloadable')->__('An error occurred while saving the file(s).'));
                         }
                     }
                     if ($linkModel->getSampleType() == Mage_Downloadable_Helper_Download::LINK_TYPE_FILE && $sampleFileNew) {
                         try {
                             Mage::helper('downloadable/file')->moveFileFromTmp(Mage_Downloadable_Model_Link::getBaseSampleTmpPath(), Mage_Downloadable_Model_Link::getBaseSamplePath(), $sampleFile[0]['file']);
                         } catch (Exception $e) {
                             Mage::throwException(Mage::helper('downloadable')->__('An error occurred while saving the file(s).'));
                         }
                     }
                 }
             }
             if ($_deleteItems) {
                 Mage::getResourceModel('downloadable/link')->deleteItems($_deleteItems);
             }
         }
     }
     return $this;
 }