Пример #1
0
 public function saveAction()
 {
     //        var_dump($this->getRequest()->getPost());exit;
     $path = Mage::getBaseDir('media') . DS . 'amlabel' . DS;
     if ($data = $this->getRequest()->getPost()) {
         /*
                     if(isset($_FILES['image']['name'])) {
                         die;
                     }*/
         $model = Mage::getModel('productdlabel/dlabel');
         $id = $this->getRequest()->getParam('id');
         if ($id) {
             $model->load($id);
         }
         $model->setData($data);
         Mage::getSingleton('adminhtml/session')->setFormData($data);
         try {
             if ($id) {
                 $model->setId($id);
             }
             //                var_dump($_FILES['image']);exit;
             $uploader = new Varien_File_Uploader('image');
             $uploader->setFilesDispersion(false);
             $uploader->setAllowRenameFiles(false);
             $uploader->setAllowedExtensions(array('png', 'gif', 'jpg', 'jpeg'));
             $name = $uploader->getCorrectFileName($_FILES['image']['name']);
             $uploader->save($path, $name);
             $model->setData('image', $name);
             $model->save();
             if (!$model->getId()) {
                 Mage::throwException(Mage::helper('productdlabel')->__('Error saving label'));
             }
             Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('productdlabel')->__('Label was successfully saved.'));
             Mage::getSingleton('adminhtml/session')->setFormData(false);
             // The following line decides if it is a "save" or "save and continue"
             if ($this->getRequest()->getParam('back')) {
                 $this->_redirect('*/*/edit', array('id' => $model->getId()));
             } else {
                 $this->_redirect('*/*/');
             }
         } catch (Exception $e) {
             Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
             if ($model && $model->getId()) {
                 $this->_redirect('*/*/edit', array('id' => $model->getId()));
             } else {
                 $this->_redirect('*/*/');
             }
         }
         return;
     }
     Mage::getSingleton('adminhtml/session')->addError(Mage::helper('productdlabel')->__('No data found to save'));
     $this->_redirect('*/*/');
 }
Пример #2
0
 public function saveAction()
 {
     if ($postData = $this->getRequest()->getPost()) {
         $model = Mage::getSingleton($this->posttype_model);
         if ($id = $this->getRequest()->getParam($this->posttype_id, null)) {
             $model->setData($this->posttype_id, $id);
         }
         try {
             $model->setData($this->posttype_name, $this->getRequest()->getParam($this->posttype_name, null));
             $swatch_options = array();
             $post_options = $this->getRequest()->getParam($this->posttype_options, array());
             foreach ($post_options as $key => $option) {
                 $image_id = $this->posttype_options . '_' . $key;
                 // set id if already exists
                 if (intval($key) > 0) {
                     $option['id'] = $key;
                 } elseif (isset($_FILES[$image_id]['name'])) {
                     $uploader = new Varien_File_Uploader($image_id);
                     $uploader->setAllowedExtensions(array('jpg', 'jpeg', 'gif', 'png'));
                     $uploader->setAllowRenameFiles(false);
                     $uploader->setFilesDispersion(false);
                     $path = $this->check_path(Mage::getBaseDir('media') . DS . 'catalog' . DS . 'swatches');
                     $image_name = $uploader->getCorrectFileName($_FILES[$image_id]['name']);
                     $uploader->save($path, $image_name);
                     $image_url = 'catalog/swatches/' . $image_name;
                     $this->resize_image($path . DS . $image_name);
                     $option['image'] = $image_url;
                 }
                 $swatch_options[] = $option;
             }
             $model->setData($this->posttype_options, $swatch_options);
             $model->save();
             Mage::getSingleton('adminhtml/session')->addSuccess($this->__('Your changes have been saved.'));
             if ($this->getRequest()->getParam('back')) {
                 $this->_redirect('*/*/edit', array($this->posttype_id => $model->getData($this->posttype_id)));
             } else {
                 $this->_redirect('*/*/');
             }
             return;
         } catch (Mage_Core_Exception $e) {
             Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
         } catch (Exception $e) {
             Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
         }
         Mage::getSingleton('adminhtml/session')->setData($this->posttype_data, $postData);
         $this->_redirectReferer();
     }
     $this->_redirect('*/*/');
 }
Пример #3
0
 public function getExportData($entityType, $collectionItem)
 {
     // Set return array
     $returnArray = array();
     $this->_writeArray =& $returnArray['webformscrf'];
     if (!$this->fieldLoadingRequired('webformscrf')) {
         return $returnArray;
     }
     // Fetch fields to export
     if ($entityType == Xtento_OrderExport_Model_Export::ENTITY_CUSTOMER) {
         $customer = Mage::getModel('customer/customer')->load($collectionItem->getObject()->getId());
     } else {
         $order = $collectionItem->getOrder();
         $customer = Mage::getModel('customer/customer')->load($order->getCustomerId());
         if (!$customer || !$customer->getId()) {
             return $returnArray;
         }
     }
     try {
         $webformId = Mage::getStoreConfig('webformscrf/registration/form', $customer->getStoreId());
         $group = Mage::getModel('customer/group')->load($customer->getGroupId());
         if ($group->getWebformId()) {
             $webformId = $group->getWebformId();
         }
         $collection = Mage::getModel('webforms/results')->getCollection()->addFilter('webform_id', $webformId)->addFilter('customer_id', $customer->getEntityId());
         $collection->getSelect()->order('created_time desc')->limit('1');
         $collection->load();
         if ($collection->count() > 0) {
             $result = $collection->getFirstItem();
             foreach ($result->getField() as $field_id => $value) {
                 $field = Mage::getModel('webforms/fields')->load($field_id);
                 switch ($field->getType()) {
                     case 'file':
                     case 'image':
                         $value = Varien_File_Uploader::getCorrectFileName($value);
                         $this->writeValue('field_' . $field_id . '_url', $result->getDownloadLink($field_id, $value));
                         break;
                 }
                 $this->writeValue('field_' . $field_id, $value);
                 if ($field->getCode()) {
                     $this->writeValue($field->getCode(), $value);
                 }
             }
         }
     } catch (Exception $e) {
     }
     // Done
     return $returnArray;
 }
 /**
  * This method will set “editing mode” if an ID was specified.
  * On the contrary, it will be set “creating mode” and an empty brand entity ready to be populated.
  */
 public function editAction()
 {
     $brand = Mage::getModel('boolfly_brand/brand');
     if ($brandId = $this->getRequest()->getParam('id', false)) {
         $brand->load($brandId);
         if ($brand->getId() < 1) {
             $this->_getSession()->addError($this->__('This brand no longer exist.'));
             return $this->_redirect('*/*/index');
         }
     }
     //Check $_POST data if the form was submitted
     if ($postData = $this->getRequest()->getPost()) {
         if (isset($_FILES['brand_image']['name']) && $_FILES['brand_image']['name'] != '') {
             try {
                 $uploader = new Varien_File_Uploader('brand_image');
                 $uploader->setAllowedExtensions('jpg', 'jpeg', 'gif', 'png');
                 $uploader->setAllowRenameFiles(false);
                 $uploader->setFilesDispersion(false);
                 $path = Mage::getBaseDir('media') . DS . 'brand/';
                 $uploader->save($path, $_FILES['brand_image']['name']);
                 $name = $uploader->getCorrectFileName($_FILES['brand_image']['name']);
                 $postData['brand_image'] = $name;
             } catch (Exception $e) {
                 Mage::logException($e);
                 $this->_getSession()->addError($e->getMessage());
             }
         }
         try {
             $brand->addData($postData);
             $brand->save();
             $this->_getSession()->addSuccess($this->__('The brand has been saved.'));
             return $this->_redirect('*/*/edit', array('id' => $brand->getId()));
         } catch (Exception $e) {
             Mage::logException($e);
             $this->_getSession()->addError($e->getMessage());
         }
     }
     //Make the current brand object available to blocks
     Mage::register('current_brand', $brand);
     //Instantiate the form container
     $brandEditBlock = $this->getLayout()->createBlock('boolfly_brand/adminhtml_brand_edit');
     $this->loadLayout()->_addContent($brandEditBlock)->renderLayout();
 }
 public function saveAction()
 {
     if (isset($_FILES['filecsv']['name']) and file_exists($_FILES['filecsv']['tmp_name'])) {
         try {
             $uploader = new Varien_File_Uploader('filecsv');
             $uploader->setAllowedExtensions(array('csv'));
             $uploader->setAllowRenameFiles(true);
             $path = Mage::getBaseDir('var') . DS . 'import' . DS;
             $filename = $uploader->getCorrectFileName($_FILES['filecsv']['name']);
             if (file_exists($path . $filename)) {
                 unlink($path . $filename);
             }
             $uploader->save($path, $filename);
             $this->_getHelper()->processfile($path . $filename);
             Mage::getSingleton('core/session')->addSuccess("File was succefully processed.");
         } catch (Exception $e) {
             Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
         }
     } else {
         Mage::getSingleton('adminhtml/session')->addError("File wasn't uploaded");
     }
     $this->_redirect('*/*/');
 }
Пример #6
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));
 }
Пример #7
0
 public function savePostResult($config = array())
 {
     try {
         $postData = Mage::app()->getRequest()->getPost();
         if (!empty($config['prefix'])) {
             $postData = Mage::app()->getRequest()->getPost($config['prefix']);
         }
         $result = Mage::getModel('webforms/results');
         $new_result = true;
         if (!empty($postData['result_id'])) {
             $new_result = false;
             $result->load($postData['result_id'])->addFieldArray();
         }
         $this->setData('post_data', $postData['field']);
         $errors = $this->validatePostResult();
         if (count($errors)) {
             foreach ($errors as $error) {
                 Mage::getSingleton('core/session')->addError($error);
                 Mage::getSingleton('core/session')->setData('webform_result_tmp_' . $this->getId(), $postData);
             }
             return false;
         }
         Mage::getSingleton('core/session')->setData('webform_result_tmp_' . $this->getId(), false);
         $iplong = ip2long(Mage::helper('webforms')->getRealIp());
         $files = $this->getUploadedFiles();
         foreach ($files as $field_name => $file) {
             $field_id = str_replace('file_', '', $field_name);
             if ($file['name']) {
                 $postData['field'][$field_id] = Varien_File_Uploader::getCorrectFileName($file['name']);
             }
             if (!empty($postData['delete_file_' . $field_id])) {
                 if ($result->getData('field_' . $field_id)) {
                     //delete the file
                     @unlink($result->getFileFullPath($field_id, $result->getData('field_' . $field_id)));
                 }
                 $postData['field'][$field_id] = '';
             }
         }
         $approve = 1;
         if ($this->getApprove()) {
             $approve = 0;
         }
         $result->setData('field', $postData['field'])->setWebformId($this->getId())->setStoreId(Mage::app()->getStore()->getId())->setCustomerId(Mage::getSingleton('customer/session')->getCustomerId())->setCustomerIp($iplong)->setApproved($approve)->save();
         $fields = Mage::getModel('webforms/fields')->setStoreId($this->getStoreId())->getCollection()->addFilter('webform_id', $this->getId());
         // upload files from $_FILE array
         foreach ($_FILES as $field_name => $file) {
             $field_id = str_replace('file_', '', $field_name);
             // check that field belongs to the form
             foreach ($fields as $field) {
                 if ($field_id == $field->getId()) {
                     if (isset($file['name']) && file_exists($file['tmp_name'])) {
                         try {
                             $uploader = new Varien_File_Uploader($field_name);
                             $uploader->setAllowRenameFiles(false);
                             $uploader->setFilesDispersion(false);
                             $path = $result->getFilePath($field_id);
                             $uploader->save($path, $file['name']);
                         } catch (Exception $e) {
                         }
                     }
                 }
             }
         }
         // upload Ajax files
         $ajax_files = $this->getAjaxFiles();
         foreach ($ajax_files as $field_name => $file) {
             $field_id = str_replace('file_', '', $field_name);
             if (isset($file['name']) && file_exists($file['tmp_name'])) {
                 $path = $result->getFilePath($field_id);
                 @mkdir($path, 0777, true);
                 rename($file['tmp_name'], $path . Varien_File_Uploader::getCorrectFileName($file['name']));
             }
         }
         Mage::dispatchEvent('webforms_result_submit', array('result' => $result, 'webform' => $this));
         // send e-mail
         if ($new_result) {
             $emailSettings = $this->getEmailSettings();
             $result = Mage::getModel('webforms/results')->load($result->getId());
             // send admin notification
             if ($emailSettings['email_enable']) {
                 $result->sendEmail();
             }
             // send customer notification
             if ($this->getDuplicateEmail()) {
                 $result->sendEmail('customer');
             }
             // email contact
             foreach ($fields as $field) {
                 foreach ($result->getData() as $key => $value) {
                     if ($key == 'field_' . $field->getId() && $value && $field->getType() == 'select/contact') {
                         $result->sendEmail('contact', $field->getContactArray($value));
                     }
                     if ($key == 'field_' . $field->getId() && $value && $field->getType() == 'subscribe') {
                         // subscribe to newsletter
                         $customer_email = $result->getCustomerEmail();
                         foreach ($customer_email as $email) {
                             Mage::getModel('newsletter/subscriber')->subscribe($email);
                         }
                     }
                 }
             }
         }
         return $result->getId();
     } catch (Exception $e) {
         Mage::getSingleton('core/session')->addError($e->getMessage());
         return false;
     }
 }
Пример #8
0
 /**
  * Add image to media gallery and return new filename
  *
  * @param Mage_Catalog_Model_Product $product
  * @param string                     $file              file path of image in file system
  * @param string|array               $mediaAttribute    code of attribute with type 'media_image',
  *                                                      leave blank if image should be only in gallery
  * @param boolean                    $move              if true, it will move source file
  * @param boolean                    $exclude           mark image as disabled in product page view
  * @return string
  */
 public function addImage(Mage_Catalog_Model_Product $product, $file, $mediaAttribute = null, $move = false, $exclude = true)
 {
     $file = realpath($file);
     if (!$file || !file_exists($file)) {
         Mage::throwException(Mage::helper('catalog')->__('Image does not exist.'));
     }
     $pathinfo = pathinfo($file);
     if (!isset($pathinfo['extension']) || !in_array(strtolower($pathinfo['extension']), array('jpg', 'jpeg', 'gif', 'png'))) {
         Mage::throwException(Mage::helper('catalog')->__('Invalid image file type.'));
     }
     $fileName = Varien_File_Uploader::getCorrectFileName($pathinfo['basename']);
     $dispretionPath = Varien_File_Uploader::getDispretionPath($fileName);
     $fileName = $dispretionPath . DS . $fileName;
     $fileName = $this->_getNotDuplicatedFilename($fileName, $dispretionPath);
     $ioAdapter = new Varien_Io_File();
     $ioAdapter->setAllowCreateFolders(true);
     $distanationDirectory = dirname($this->_getConfig()->getTmpMediaPath($fileName));
     try {
         $ioAdapter->open(array('path' => $distanationDirectory));
         if ($move) {
             $ioAdapter->mv($file, $this->_getConfig()->getTmpMediaPath($fileName));
         } else {
             $ioAdapter->cp($file, $this->_getConfig()->getTmpMediaPath($fileName));
             $ioAdapter->chmod($this->_getConfig()->getTmpMediaPath($fileName), 0777);
         }
     } catch (Exception $e) {
         Mage::throwException(Mage::helper('catalog')->__('Failed to move file: %s', $e->getMessage()));
     }
     $fileName = str_replace(DS, '/', $fileName);
     $attrCode = $this->getAttribute()->getAttributeCode();
     $mediaGalleryData = $product->getData($attrCode);
     $position = 0;
     if (!is_array($mediaGalleryData)) {
         $mediaGalleryData = array('images' => array());
     }
     foreach ($mediaGalleryData['images'] as &$image) {
         if (isset($image['position']) && $image['position'] > $position) {
             $position = $image['position'];
         }
     }
     $position++;
     $mediaGalleryData['images'][] = array('file' => $fileName, 'position' => $position, 'label' => '', 'disabled' => (int) $exclude);
     $product->setData($attrCode, $mediaGalleryData);
     if (!is_null($mediaAttribute)) {
         $this->setMediaAttribute($product, $mediaAttribute, $fileName);
     }
     return $fileName;
 }
 /**
  * Validate user input for option
  *
  * @throws Mage_Core_Exception
  * @param array $values All product option values, i.e. array (option_id => mixed, option_id => mixed...)
  * @return Mage_Catalog_Model_Product_Option_Type_Default
  */
 public function validateUserValue($values)
 {
     AO::getSingleton('checkout/session')->setUseNotice(false);
     $this->setIsValid(true);
     $option = $this->getOption();
     // Set option value from request (Admin/Front reorders)
     if (isset($values[$option->getId()]) && is_array($values[$option->getId()])) {
         if (isset($values[$option->getId()]['order_path'])) {
             $orderFileFullPath = AO::getBaseDir() . $values[$option->getId()]['order_path'];
         } else {
             $this->setUserValue(null);
             return $this;
         }
         $ok = is_file($orderFileFullPath) && is_readable($orderFileFullPath) && isset($values[$option->getId()]['secret_key']) && substr(md5(file_get_contents($orderFileFullPath)), 0, 20) == $values[$option->getId()]['secret_key'];
         $this->setUserValue($ok ? $values[$option->getId()] : null);
         return $this;
     } elseif ($this->getProduct()->getSkipCheckRequiredOption()) {
         $this->setUserValue(null);
         return $this;
     }
     /**
      * Upload init
      */
     $upload = new Zend_File_Transfer_Adapter_Http();
     $file = 'options_' . $option->getId() . '_file';
     try {
         $runValidation = $option->getIsRequire() || $upload->isUploaded($file);
         if (!$runValidation) {
             $this->setUserValue(null);
             return $this;
         }
         $fileInfo = $upload->getFileInfo($file);
         $fileInfo = $fileInfo[$file];
     } catch (Exception $e) {
         $this->setIsValid(false);
         AO::throwException(AO::helper('catalog')->__("Files upload failed"));
     }
     /**
      * Option Validations
      */
     // Image dimensions
     $_dimentions = array();
     if ($option->getImageSizeX() > 0) {
         $_dimentions['maxwidth'] = $option->getImageSizeX();
     }
     if ($option->getImageSizeY() > 0) {
         $_dimentions['maxheight'] = $option->getImageSizeY();
     }
     if (count($_dimentions) > 0) {
         $upload->addValidator('ImageSize', false, $_dimentions);
     }
     // File extension
     $_allowed = $this->_parseExtensionsString($option->getFileExtension());
     if ($_allowed !== null) {
         $upload->addValidator('Extension', false, $_allowed);
     } else {
         $_forbidden = $this->_parseExtensionsString($this->getConfigData('forbidden_extensions'));
         if ($_forbidden !== null) {
             $upload->addValidator('ExcludeExtension', false, $_forbidden);
         }
     }
     /**
      * Upload process
      */
     $this->_initFilesystem();
     if ($upload->isUploaded($file) && $upload->isValid($file)) {
         $extension = pathinfo(strtolower($fileInfo['name']), PATHINFO_EXTENSION);
         $fileName = Varien_File_Uploader::getCorrectFileName($fileInfo['name']);
         $dispersion = Varien_File_Uploader::getDispretionPath($fileName);
         $filePath = $dispersion;
         $destination = $this->getQuoteTargetDir() . $filePath;
         $this->_createWriteableDir($destination);
         $upload->setDestination($destination);
         $fileHash = md5(file_get_contents($fileInfo['tmp_name']));
         $filePath .= DS . $fileHash . '.' . $extension;
         $fileFullPath = $this->getQuoteTargetDir() . $filePath;
         $upload->addFilter('Rename', array('target' => $fileFullPath, 'overwrite' => true));
         if (!$upload->receive()) {
             $this->setIsValid(false);
             AO::throwException(AO::helper('catalog')->__("File upload failed"));
         }
         $_imageSize = @getimagesize($fileFullPath);
         if (is_array($_imageSize) && count($_imageSize) > 0) {
             $_width = $_imageSize[0];
             $_height = $_imageSize[1];
         } else {
             $_width = 0;
             $_height = 0;
         }
         $this->setUserValue(array('type' => $fileInfo['type'], 'title' => $fileInfo['name'], 'quote_path' => $this->getQuoteTargetDir(true) . $filePath, 'order_path' => $this->getOrderTargetDir(true) . $filePath, 'fullpath' => $fileFullPath, 'size' => $fileInfo['size'], 'width' => $_width, 'height' => $_height, 'secret_key' => substr($fileHash, 0, 20)));
     } elseif ($upload->getErrors()) {
         $errors = array();
         foreach ($upload->getErrors() as $errorCode) {
             if ($errorCode == Zend_Validate_File_ExcludeExtension::FALSE_EXTENSION) {
                 $errors[] = AO::helper('catalog')->__("The file '%s' for '%s' has an invalid extension", $fileInfo['name'], $option->getTitle());
             } elseif ($errorCode == Zend_Validate_File_Extension::FALSE_EXTENSION) {
                 $errors[] = AO::helper('catalog')->__("The file '%s' for '%s' has an invalid extension", $fileInfo['name'], $option->getTitle());
             } elseif ($errorCode == Zend_Validate_File_ImageSize::WIDTH_TOO_BIG || $errorCode == Zend_Validate_File_ImageSize::WIDTH_TOO_BIG) {
                 $errors[] = AO::helper('catalog')->__("Maximum allowed image size for '%s' is %sx%s px.", $option->getTitle(), $option->getImageSizeX(), $option->getImageSizeY());
             }
         }
         if (count($errors) > 0) {
             $this->setIsValid(false);
             AO::throwException(implode("\n", $errors));
         }
     } else {
         $this->setIsValid(false);
         AO::throwException(AO::helper('catalog')->__('Please specify the product required option(s)'));
     }
     return $this;
 }
Пример #10
0
 public function saveAction()
 {
     if ($data = $this->getRequest()->getPost()) {
         //Zend_Debug::dump($data);die();
         //var_dump($this->getRequest()->getParam('status'));exit;
         $data = $this->getRequest()->getPost();
         $program_id = $this->getRequest()->getParam('id');
         $model = Mage::getModel('rewardpoints/cartrules');
         try {
             if (isset($_FILES['promotion_image']['name']) && $_FILES['promotion_image']['name'] != '') {
                 try {
                     /* Starting upload */
                     $uploader = new Varien_File_Uploader('promotion_image');
                     // Any extention would work
                     $uploader->setAllowedExtensions(array('jpg', 'jpeg', 'gif', 'png', 'bmp'));
                     $uploader->setAllowRenameFiles(true);
                     // Set the file upload mode
                     // false -> get the file directly in the specified folder
                     // true -> get the file in the product like folders
                     //	(file.jpg will go in something like /media/f/i/file.jpg)
                     $uploader->setFilesDispersion(false);
                     $file_name = $uploader->getCorrectFileName($_FILES['promotion_image']['name']);
                     // We set media as the upload dir
                     $path = Mage::getBaseDir('media') . DS . "mw_rewardpoint";
                     $uploader->save($path, $file_name);
                 } catch (Exception $e) {
                 }
                 //this way the name is saved in DB
                 //$data['image_name'] = 'mw_affiliate/'.$_FILES['image_name']['name'];
                 $data['promotion_image'] = 'mw_rewardpoint/' . $file_name;
             } else {
                 if (isset($data['promotion_image']['delete']) && $data['promotion_image']['delete'] == 1) {
                     $data['promotion_image'] = '';
                 } else {
                     unset($data['promotion_image']);
                 }
             }
             $customer_group_ids = "";
             $store_view = "";
             if (isset($data["customer_group_ids"])) {
                 $customer_group_ids = implode(",", $data["customer_group_ids"]);
             }
             $data["customer_group_ids"] = $customer_group_ids;
             if (isset($data["store_view"])) {
                 if (in_array("0", $data["store_view"])) {
                     $store_view = '0';
                 } else {
                     $store_view = implode(",", $data["store_view"]);
                 }
             }
             $data["store_view"] = $store_view;
             if (!$data["reward_step"]) {
                 $data["reward_step"] = 0;
             }
             if ($data['rule_position'] == '') {
                 $data['rule_position'] = 0;
             }
             if ($program_id != '') {
                 if (Mage::app()->isSingleStoreMode()) {
                     $data['store_view'] = '0';
                 }
                 $model->setData($data)->setId($program_id);
                 $model->save();
                 // save conditions
                 if (isset($data['rule']['conditions'])) {
                     $data['conditions'] = $data['rule']['conditions'];
                 }
                 if (isset($data['rule']['actions'])) {
                     $data['actions'] = $data['rule']['actions'];
                 }
                 $model->load($program_id);
                 unset($data['rule']);
                 $model->loadPost($data);
                 $model->save();
             }
             if ($program_id == '') {
                 if (Mage::app()->isSingleStoreMode()) {
                     $data['store_view'] = '0';
                 }
                 //Zend_Debug::dump($data);die();
                 $model->setData($data)->save();
                 // save conditions
                 if (isset($data['rule']['conditions'])) {
                     $data['conditions'] = $data['rule']['conditions'];
                 }
                 if (isset($data['rule']['actions'])) {
                     $data['actions'] = $data['rule']['actions'];
                 }
                 unset($data['rule']);
                 $model->loadPost($data);
                 $model->save();
             }
             Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('rewardpoints')->__('The rule has successfully saved'));
             Mage::getSingleton('adminhtml/session')->setFormData(false);
             if ($this->getRequest()->getParam('back')) {
                 $this->_redirect('*/*/edit', array('id' => $model->getId()));
                 return;
             }
             $this->_redirect('*/*/');
             return;
         } catch (Exception $e) {
             Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
             Mage::getSingleton('adminhtml/session')->setFormData($data);
             $this->_redirect('*/*/edit', array('id' => $this->getRequest()->getParam('id')));
             return;
         }
     }
     Mage::getSingleton('adminhtml/session')->addError(Mage::helper('rewardpoints')->__('Unable to find rule to save'));
     $this->_redirect('*/*/');
 }
Пример #11
0
 protected function _beforeSave()
 {
     if (isset($_FILES['layout_file']) && $_FILES['layout_file']['name'] != '') {
         try {
             $uploader = new Varien_File_Uploader('layout_file');
             $uploader->setAllowedExtensions(array('jpg', 'jpeg', 'gif', 'png'));
             $uploader->setAllowRenameFiles(true);
             $uploader->setFilesDispersion(true);
             $this->setLayoutFileName($uploader->getCorrectFileName($_FILES['layout_file']['name']));
             $ext = pathinfo($_FILES['layout_file']['name'], PATHINFO_EXTENSION);
             $result = $uploader->save(Mage::getBaseDir('media') . DS . $this->getUploadPath(), uniqid() . "." . $ext);
             $this->setLayoutFile($this->getUploadPath() . $result['file']);
         } catch (Exception $e) {
             Mage::throwException($this->__('Invalid image format'));
         }
     } else {
         $layoutFile = $this->getLayoutFile();
         if (isset($layoutFile['delete']) && $layoutFile['delete'] == 1) {
             $this->setLayoutFile(NULL);
         } else {
             $this->setLayoutFile($this->layout_file["value"]);
         }
     }
     return parent::_beforeSave();
 }
Пример #12
0
 public function getDownloadLink($field_id, $filename)
 {
     $filename = Varien_File_Uploader::getCorrectFileName($filename);
     $path = Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA) . 'webforms/' . $this->getId() . '/' . $field_id . '/';
     if ($this->getData('key_' . $field_id)) {
         $path .= $this->getData('key_' . $field_id) . '/';
     }
     $path .= rawurlencode($filename);
     return $path;
 }
Пример #13
0
 /**
  *
  * Save the avatar image after checks
  */
 public function processImage()
 {
     $session = $this->_getSession();
     $upload = new Zend_File_Transfer_Adapter_Http();
     $file = 'photo';
     try {
         $runValidation = $upload->isUploaded($file);
         if (!$runValidation) {
             return array();
         }
         $fileInfo = $upload->getFileInfo($file);
         $fileInfo = $fileInfo[$file];
     } catch (Exception $e) {
         // when file exceeds the upload_max_filesize, $_FILES is empty
         if (isset($_SERVER['CONTENT_LENGTH']) && $_SERVER['CONTENT_LENGTH'] > $this->_getUploadMaxFilesize()) {
             $errors[] = Mage::helper('avatar')->__("The file you uploaded is larger than %s Megabytes allowed by server", $this->_bytesToMbytes($this->_getUploadMaxFilesize()));
             return $errors;
             /*Mage::throwException(
               Mage::helper('catalog')->__("The file you uploaded is larger than %s Megabytes allowed by server",
               $this->_bytesToMbytes($this->_getUploadMaxFilesize())
               )
               );*/
         } else {
             Mage::throwException(Mage::helper('avatar')->__("error uploading image"));
         }
     }
     /**
      * Option Validations
      */
     // Image dimensions
     $_dimentions = array();
     $_dimentions['maxwidth'] = '2000';
     $_dimentions['maxheight'] = '2000';
     if (count($_dimentions) > 0) {
         $upload->addValidator('ImageSize', false, $_dimentions);
     }
     // File extension
     $_allowed = $this->_parseExtensionsString("jpg/gif/png");
     if ($_allowed !== null) {
         $upload->addValidator('Extension', false, $_allowed);
     } else {
         $_forbidden = $this->_parseExtensionsString($this->getConfigData('forbidden_extensions'));
         if ($_forbidden !== null) {
             $upload->addValidator('ExcludeExtension', false, $_forbidden);
         }
     }
     // Maximum filesize
     $upload->addValidator('FilesSize', false, array('max' => $this->_getUploadMaxFilesize()));
     /**
      * Upload process
      */
     $this->_initFilesystem();
     if ($upload->isUploaded($file) && $upload->isValid($file)) {
         $extension = pathinfo(strtolower($fileInfo['name']), PATHINFO_EXTENSION);
         $fileName = Varien_File_Uploader::getCorrectFileName($fileInfo['name']);
         $dispersion = Varien_File_Uploader::getDispretionPath($fileName);
         $filePath = $dispersion;
         $destination = $this->getPhotoTargetDir() . $filePath;
         $this->_createWriteableDir($destination);
         $upload->setDestination($destination);
         $fileHash = md5(file_get_contents($fileInfo['tmp_name']));
         $filePath .= DS . $fileHash . '-' . time() . "." . $extension;
         $fileFullPath = $this->getPhotoTargetDir() . $filePath;
         $upload->addFilter('Rename', array('target' => $fileFullPath, 'overwrite' => true));
         if (!$upload->receive($file)) {
             Mage::throwException(Mage::helper('avatar')->__("File upload failed"));
         }
         $_imageSize = @getimagesize($fileFullPath);
         if (is_array($_imageSize) && count($_imageSize) > 0) {
             $_width = $_imageSize[0];
             $_height = $_imageSize[1];
         } else {
             $_width = 0;
             $_height = 0;
         }
         $imageObj = new Varien_Image($fileFullPath);
         $imageObj->constrainOnly(TRUE);
         $imageObj->keepAspectRatio(TRUE);
         $imageObj->keepTransparency(TRUE);
         $imageObj->resize(50);
         $imageObj->save($fileFullPath);
         return $filePath;
     } elseif ($upload->getErrors()) {
         $errors = array();
         foreach ($upload->getErrors() as $errorCode) {
             if ($errorCode == Zend_Validate_File_ExcludeExtension::FALSE_EXTENSION) {
                 $errors[] = Mage::helper('avatar')->__("The file '%s' has an invalid extension", $fileInfo['name']);
             } elseif ($errorCode == Zend_Validate_File_Extension::FALSE_EXTENSION) {
                 $errors[] = Mage::helper('avatar')->__("The file '%s' has an invalid extension", $fileInfo['name']);
             } elseif ($errorCode == Zend_Validate_File_ImageSize::WIDTH_TOO_BIG) {
                 $errors[] = Mage::helper('avatar')->__("Maximum allowed image width for '%s' is %s px.", $fileInfo['name'], $_dimentions['maxwidth']);
             } elseif ($errorCode == Zend_Validate_File_ImageSize::HEIGHT_TOO_BIG) {
                 $errors[] = Mage::helper('avatar')->__("Maximum allowed image height for '%s' is %s px.", $fileInfo['name'], $_dimentions['maxheight']);
             } elseif ($errorCode == Zend_Validate_File_FilesSize::TOO_BIG) {
                 $errors[] = Mage::helper('avatar')->__("The file you uploaded is larger than %s Megabytes allowed by server", $fileInfo['name'], $this->_bytesToMbytes($this->_getUploadMaxFilesize()));
             }
         }
         if (count($errors) > 0) {
             return $errors;
         }
     } else {
         $errors[] = Mage::helper('avatar')->__('File upload failed');
         return $errors;
     }
 }
Пример #14
0
 protected function _getFileName($url, $mediakey)
 {
     $fileName = Varien_File_Uploader::getCorrectFileName(basename($url));
     $fileName = str_replace($mediakey, '', $fileName);
     $fileName = trim($fileName, '_');
     return $fileName;
 }
 /**
  *
  */
 public function saveAction()
 {
     if ($this->getRequest()->getPost()) {
         try {
             $post_data = $this->getRequest()->getPost();
             $slider_id = $this->getRequest()->getParam('id');
             $slide_model = Mage::getModel('slider/slider');
             $destFolder = rtrim(BP, '/\\') . '/media/ismslider/';
             $timeMarker = time();
             foreach ($post_data['slides'] as $slideId => $values) {
                 if (!empty($values['deleteimage'])) {
                     @unlink($destFolder . $values['deleteimage']);
                     @unlink($destFolder . 'thumb-' . $values['deleteimage']);
                     $post_data['slides'][$slideId]['image'] = '';
                 }
             }
             foreach ($_FILES['slides']['name'] as $slideId => $values) {
                 if (empty($values['image'])) {
                     continue;
                 }
                 if (!is_writable($destFolder)) {
                     Mage::getSingleton('adminhtml/session')->addError('Destination folder is not writable or does not exists.');
                     continue;
                 }
                 $fileName = Varien_File_Uploader::getCorrectFileName($values['image']);
                 $destFile = $destFolder . $timeMarker . '_' . $fileName;
                 $result = move_uploaded_file($_FILES['slides']['tmp_name'][$slideId]['image'], $destFile);
                 if ($result) {
                     chmod($destFile, 0644);
                     $imageProcessor = new Varien_Image($destFile);
                     $imageProcessor->keepAspectRatio(true);
                     $imageProcessor->keepFrame(true);
                     $imageProcessor->keepTransparency(true);
                     $imageProcessor->constrainOnly(false);
                     $imageProcessor->backgroundColor(array(255, 255, 255));
                     $imageProcessor->quality(90);
                     $imageProcessor->resize(172, 60);
                     $imageProcessor->save($destFolder, 'thumb-' . $timeMarker . '_' . $fileName);
                     $post_data['slides'][$slideId]['image'] = $timeMarker . '_' . $fileName;
                     chmod($destFolder, 'thumb-' . $timeMarker . '_' . $fileName, 0644);
                 } else {
                     $post_data['slides'][$slideId]['image'] = '';
                     Mage::getSingleton('adminhtml/session')->addError('File ' . $fileName . ' was not uploaded.');
                 }
             }
             $slide_model->setId($slider_id)->setData($post_data);
             if ($slider_id !== null) {
                 $slide_model->setModifiedTime(new Zend_Db_Expr('NOW()'));
             } else {
                 $slide_model->setCreatedTime(new Zend_Db_Expr('NOW()'));
             }
             $slide_model->save();
             Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('adminhtml')->__('Slider was successfully saved'));
             if ($this->getRequest()->getParam('back')) {
                 $this->_redirect('*/*/edit', array('id' => $slide_model->getId()));
                 return;
             }
             $this->_redirect('*/*/');
             return;
         } catch (Exception $e) {
             Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
             $this->_redirect('*/*/edit', array('id' => $this->getRequest()->getParam('id')));
             return;
         }
     }
     $this->_redirect('*/*/');
 }
Пример #16
0
 public static function uploadBannerImage()
 {
     $banner_image_path = Mage::getBaseDir('media') . DS . 'bannerslider';
     $image = "";
     if (isset($_FILES['image']['name']) && $_FILES['image']['name'] != '') {
         try {
             /* Starting upload */
             $uploader = new Varien_File_Uploader('image');
             // Any extention would work
             $uploader->setAllowedExtensions(array('jpg', 'jpeg', 'gif', 'png'));
             $uploader->setAllowRenameFiles(true);
             $uploader->setFilesDispersion(true);
             $uploader->save($banner_image_path, $uploader->getCorrectFileName($_FILES['image']['name']));
             // Add by Hoang Vuong: 30/08/2013
             $image = substr(strrchr($uploader->getUploadedFileName(), "/"), 1);
         } catch (Exception $e) {
         }
         // $image = $_FILES['image']['name'];
     }
     return $image;
 }
Пример #17
0
 /**
  * Validate uploaded file
  *
  * @throws Mage_Core_Exception
  * @return Mage_Catalog_Model_Product_Option_Type_File
  */
 protected function _validateUploadedFile()
 {
     $option = $this->getOption();
     $processingParams = $this->_getProcessingParams();
     /**
      * Upload init
      */
     $upload = new Zend_File_Transfer_Adapter_Http();
     $file = $processingParams->getFilesPrefix() . 'options_' . $option->getId() . '_file';
     try {
         $runValidation = $option->getIsRequire() || $upload->isUploaded($file);
         if (!$runValidation) {
             $this->setUserValue(null);
             return $this;
         }
         $fileInfo = $upload->getFileInfo($file);
         $fileInfo = $fileInfo[$file];
         $fileInfo['title'] = $fileInfo['name'];
     } catch (Exception $e) {
         // when file exceeds the upload_max_filesize, $_FILES is empty
         if (isset($_SERVER['CONTENT_LENGTH']) && $_SERVER['CONTENT_LENGTH'] > $this->_getUploadMaxFilesize()) {
             $this->setIsValid(false);
             Mage::throwException(Mage::helper('catalog')->__("The file you uploaded is larger than %s Megabytes allowed by server", $this->_bytesToMbytes($this->_getUploadMaxFilesize())));
         } else {
             switch ($this->getProcessMode()) {
                 case Mage_Catalog_Model_Product_Type_Abstract::PROCESS_MODE_FULL:
                     Mage::throwException(Mage::helper('catalog')->__('Please specify the product\'s required option(s).'));
                     break;
                 default:
                     $this->setUserValue(null);
                     break;
             }
             return $this;
         }
     }
     /**
      * Option Validations
      */
     // Image dimensions
     $_dimentions = array();
     if ($option->getImageSizeX() > 0) {
         $_dimentions['maxwidth'] = $option->getImageSizeX();
     }
     if ($option->getImageSizeY() > 0) {
         $_dimentions['maxheight'] = $option->getImageSizeY();
     }
     if (count($_dimentions) > 0) {
         $upload->addValidator('ImageSize', false, $_dimentions);
     }
     // File extension
     $_allowed = $this->_parseExtensionsString($option->getFileExtension());
     if ($_allowed !== null) {
         $upload->addValidator('Extension', false, $_allowed);
     } else {
         $_forbidden = $this->_parseExtensionsString($this->getConfigData('forbidden_extensions'));
         if ($_forbidden !== null) {
             $upload->addValidator('ExcludeExtension', false, $_forbidden);
         }
     }
     // Maximum filesize
     $upload->addValidator('FilesSize', false, array('max' => $this->_getUploadMaxFilesize()));
     /**
      * Upload process
      */
     $this->_initFilesystem();
     if ($upload->isUploaded($file) && $upload->isValid($file)) {
         $extension = pathinfo(strtolower($fileInfo['name']), PATHINFO_EXTENSION);
         $fileName = Varien_File_Uploader::getCorrectFileName($fileInfo['name']);
         $dispersion = Varien_File_Uploader::getDispretionPath($fileName);
         $filePath = $dispersion;
         $fileHash = md5(file_get_contents($fileInfo['tmp_name']));
         $filePath .= DS . $fileHash . '.' . $extension;
         $fileFullPath = $this->getQuoteTargetDir() . $filePath;
         $upload->addFilter('Rename', array('target' => $fileFullPath, 'overwrite' => true));
         $this->getProduct()->getTypeInstance(true)->addFileQueue(array('operation' => 'receive_uploaded_file', 'src_name' => $file, 'dst_name' => $fileFullPath, 'uploader' => $upload, 'option' => $this));
         $_width = 0;
         $_height = 0;
         if (is_readable($fileInfo['tmp_name'])) {
             $_imageSize = getimagesize($fileInfo['tmp_name']);
             if ($_imageSize) {
                 $_width = $_imageSize[0];
                 $_height = $_imageSize[1];
             }
         }
         $this->setUserValue(array('type' => $fileInfo['type'], 'title' => $fileInfo['name'], 'quote_path' => $this->getQuoteTargetDir(true) . $filePath, 'order_path' => $this->getOrderTargetDir(true) . $filePath, 'fullpath' => $fileFullPath, 'size' => $fileInfo['size'], 'width' => $_width, 'height' => $_height, 'secret_key' => substr($fileHash, 0, 20)));
     } elseif ($upload->getErrors()) {
         $errors = $this->_getValidatorErrors($upload->getErrors(), $fileInfo);
         if (count($errors) > 0) {
             $this->setIsValid(false);
             Mage::throwException(implode("\n", $errors));
         }
     } else {
         $this->setIsValid(false);
         Mage::throwException(Mage::helper('catalog')->__('Please specify the product required option(s)'));
     }
     return $this;
 }
 public function customerAfterLoad($observer)
 {
     $customer = $observer->getCustomer();
     if (!Mage::registry('webformscrf_load_customer_' . $customer->getId())) {
         $result = $this->getCustomerResult($customer)->addFieldArray();
         if ($result->getId()) {
             $customer->setData('result_id', $result->getId());
             $customer->setData('webform_id', $result->getWebformId());
             $data = $result->getData('field');
             foreach ($data as $field_id => $value) {
                 $field = Mage::getModel('webforms/fields')->load($field_id);
                 switch ($field->getType()) {
                     case 'file':
                     case 'image':
                         $value = Varien_File_Uploader::getCorrectFileName($value);
                         $customer->setData('field_' . $field_id . '_url', $result->getDownloadLink($field_id, $value));
                         break;
                 }
                 $customer->setData('field_' . $field_id, $value);
                 if ($field->getCode()) {
                     $customer->setData($field->getCode(), $value);
                 }
             }
         }
     }
 }
Пример #19
0
 private function _uploadFile($keyFile, $fileId)
 {
     $result = array();
     if (isset($_FILES[$keyFile]['name']) && $_FILES[$keyFile]['name'] != '') {
         try {
             Mage::getSingleton('downloads/files')->removeDownloadsFile($fileId, false);
             $uploader = new Varien_File_Uploader($keyFile);
             $uploader->setAllowRenameFiles(false);
             $uploader->setFilesDispersion(false);
             $correctFilename = $uploader->getCorrectFileName($_FILES[$keyFile]['name']);
             $newFileName = Mage::helper('downloads')->getDownloadsPath($fileId) . $correctFilename;
             $uploader->save(Mage::helper('downloads')->getDownloadsPath($fileId), $correctFilename);
             if (!file_exists($newFileName) || !filesize($newFileName)) {
                 $result['error'] = true;
             }
             $result['size'] = $_FILES[$keyFile]['size'];
             $result['type'] = substr($_FILES[$keyFile]['name'], strrpos($_FILES[$keyFile]['name'], '.') + 1);
         } catch (Exception $e) {
             if ($e->getMessage()) {
                 Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
             }
         }
     }
     return $result;
 }
 private function _uploadImages()
 {
     if (!isset($_FILES['images']['name'])) {
         return false;
     }
     $names = array();
     $path = Mage::helper('stuntcoders_slideshow')->getImageSavePath();
     foreach ($_FILES['images']['name'] as $key => $image) {
         try {
             $uploader = new Varien_File_Uploader(array('name' => $_FILES['images']['name'][$key], 'type' => $_FILES['images']['type'][$key], 'tmp_name' => $_FILES['images']['tmp_name'][$key], 'error' => $_FILES['images']['error'][$key], 'size' => $_FILES['images']['size'][$key]));
             $uploader->setAllowedExtensions(array('jpg', 'jpeg', 'gif', 'png'));
             $imageName = $uploader->getCorrectFileName($_FILES['images']['name'][$key]);
             $uploader->save($path, $imageName);
             $names[] = $imageName;
         } catch (Exception $e) {
             Mage::logException($e);
             continue;
         }
     }
     return $names;
 }
Пример #21
0
 public function getDownloadLink(Varien_Object $row)
 {
     $field_id = str_replace('field_', '', $this->getColumn()->getIndex());
     $value = Varien_File_Uploader::getCorrectFileName($row->getData($this->getColumn()->getIndex()));
     $path = Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA) . 'webforms/' . $row->getId() . '/' . $field_id . '/';
     if ($row->getData('key_' . $field_id)) {
         $path .= $row->getData('key_' . $field_id) . '/';
     }
     $path .= $value;
     return $path;
 }
Пример #22
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;
    }
Пример #23
0
 public function getUploadedFileName()
 {
     return parent::getCorrectFileName($this->_file['name']);
 }
Пример #24
0
 public static function uploadImage($sizeWidth = null, $sizeHeight = null)
 {
     $image_path = Mage::getBaseDir('media') . DS . 'customerattribute/image';
     $image_file_name = "";
     if (isset($_FILES['image']['name']) && $_FILES['image']['name'] != '') {
         try {
             /* Starting upload */
             $uploader = new Varien_File_Uploader('image');
             // Any extention would work
             $uploader->setAllowedExtensions(array('jpg', 'jpeg', 'gif', 'png'));
             $uploader->setAllowRenameFiles(false);
             $uploader->setFilesDispersion(true);
             $result = $uploader->save($image_path, $uploader->getCorrectFileName($_FILES['image']['name']));
             $image_file_name = substr(strrchr($uploader->getUploadedFileName(), "/"), 1);
             //resize image
             if ($result) {
                 $image = new Varien_Image($image_path + '/' + $image_file_name);
                 if ($sizeWidth != null) {
                     $image->resize($sizeWidth, $sizeHeight);
                     $image->save();
                 }
             }
         } catch (Exception $e) {
             Mage::logException($e);
         }
     }
     return $image_file_name;
 }
 public function saveAction()
 {
     if ($data = $this->getRequest()->getPost()) {
         $group_ids = "";
         if (isset($data["group_id"])) {
             $group_ids = implode(",", $data["group_id"]);
         }
         $data["group_id"] = $group_ids;
         if (isset($data['store_view'])) {
             $stores = $data['store_view'];
             $storesCount = count($stores);
             $storesIndex = 1;
             $storesData = '';
             $check = 0;
             foreach ($stores as $store) {
                 if ($store == '0') {
                     $check = 1;
                 }
                 $storesData .= $store;
                 if ($storesIndex < $storesCount) {
                     $storesData .= ',';
                 }
                 $storesIndex++;
             }
             if ($check == 1) {
                 $data['store_view'] = '0';
             } else {
                 $data['store_view'] = $storesData;
             }
         }
         if (isset($_FILES['image_name']['name']) && $_FILES['image_name']['name'] != '') {
             try {
                 /* Starting upload */
                 $uploader = new Varien_File_Uploader('image_name');
                 // Any extention would work
                 $uploader->setAllowedExtensions(array('jpg', 'jpeg', 'gif', 'png', 'swf'));
                 $uploader->setAllowRenameFiles(true);
                 // Set the file upload mode
                 // false -> get the file directly in the specified folder
                 // true -> get the file in the product like folders
                 //	(file.jpg will go in something like /media/f/i/file.jpg)
                 $uploader->setFilesDispersion(false);
                 $file_name = $uploader->getCorrectFileName($_FILES['image_name']['name']);
                 // We set media as the upload dir
                 $path = Mage::getBaseDir('media') . DS . "mw_affiliate";
                 $uploader->save($path, $file_name);
             } catch (Exception $e) {
             }
             //this way the name is saved in DB
             //$data['image_name'] = 'mw_affiliate/'.$_FILES['image_name']['name'];
             $data['image_name'] = 'mw_affiliate/' . $file_name;
         } else {
             if (isset($data['image_name']['delete']) && $data['image_name']['delete'] == 1) {
                 $data['image_name'] = '';
             } else {
                 unset($data['image_name']);
             }
         }
         $model = Mage::getModel('affiliate/affiliatebanner');
         if (Mage::app()->isSingleStoreMode()) {
             $data['store_view'] = '0';
         }
         $model->setData($data)->setId($this->getRequest()->getParam('id'));
         try {
             $model->save();
             // save member to banner
             $_members = $this->getRequest()->getParam('addmember');
             $members = $_members['banner'];
             if (isset($members)) {
                 // xoa cac member trong group de update lai du lieu moi
                 $collection_members = Mage::getModel('affiliate/affiliatebannermember')->getCollection()->addFieldToFilter('banner_id', $model->getId());
                 if (sizeof($collection_members) > 0) {
                     foreach ($collection_members as $collection_member) {
                         $collection_member->delete();
                     }
                 }
                 $this->saveBannerMember($members, $model->getId());
             }
             Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('affiliate')->__('The banner has successfully saved'));
             Mage::getSingleton('adminhtml/session')->setFormData(false);
             if ($this->getRequest()->getParam('back')) {
                 $this->_redirect('*/*/edit', array('id' => $model->getId()));
                 return;
             }
             $this->_redirect('*/*/');
             return;
         } catch (Exception $e) {
             Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
             Mage::getSingleton('adminhtml/session')->setFormData($data);
             $this->_redirect('*/*/edit', array('id' => $this->getRequest()->getParam('id')));
             return;
         }
     }
     Mage::getSingleton('adminhtml/session')->addError(Mage::helper('affiliate')->__('Unable to find banner to save'));
     $this->_redirect('*/*/');
 }
Пример #26
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);
     //}
 }
Пример #27
0
 public function uploadThumbnail($thumbnail, $correctFile = null)
 {
     // If no thumbnail specified, use placeholder image
     if (!$thumbnail) {
         // Check if placeholder defined in config
         $isConfigPlaceholder = Mage::getStoreConfig("catalog/placeholder/image_placeholder");
         $configPlaceholder = '/placeholder/' . $isConfigPlaceholder;
         if ($isConfigPlaceholder && file_exists(Mage::getBaseDir('media') . '/catalog/product' . $configPlaceholder)) {
             $thumbnail = Mage::getBaseDir('media') . '/catalog/product' . $configPlaceholder;
         } else {
             // Replace file with skin or default skin placeholder
             $skinBaseDir = Mage::getDesign()->getSkinBaseDir();
             $skinPlaceholder = "/images/catalog/product/placeholder/image.jpg";
             $thumbnail = $skinPlaceholder;
             if (file_exists($skinBaseDir . $thumbnail)) {
                 $baseDir = $skinBaseDir;
             } else {
                 $baseDir = Mage::getDesign()->getSkinBaseDir(array('_theme' => 'default'));
                 if (!file_exists($baseDir . $thumbnail)) {
                     $baseDir = Mage::getDesign()->getSkinBaseDir(array('_theme' => 'default', '_package' => 'base'));
                 }
                 if (!file_exists($baseDir . $thumbnail)) {
                     $baseDir = Mage::getDesign()->getSkinBaseDir(array('_theme' => 'default', '_package' => 'default'));
                 }
             }
             $thumbnail = str_replace('adminhtml', 'frontend', $baseDir) . $thumbnail;
         }
     }
     if (!$correctFile) {
         $correctFile = basename($thumbnail);
     }
     $tempFile = null;
     if (Mage::helper('videogallery')->isUrl($thumbnail)) {
         // Get Temporary location where we can save thumbnail to
         $adapter = new Varien_Io_File();
         $tempFile = $adapter->getCleanPath(Mage::getBaseDir('tmp')) . $correctFile;
         // Download to the temp location
         $thumbData = Mage::helper('videogallery')->file_get_contents_curl($thumbnail);
         @file_put_contents($tempFile, $thumbData);
         @chmod($tempFile, 0777);
         unset($thumbData);
         $thumbnail = $tempFile;
     }
     // Getting ready to download and save thumbnail
     $fileName = Varien_File_Uploader::getCorrectFileName($correctFile);
     $dispretionPath = Varien_File_Uploader::getDispretionPath($fileName);
     //$fileName       = $dispretionPath . DS . $fileName;
     $fileName = $dispretionPath . DS . Varien_File_Uploader::getNewFileName($this->_getConfig()->getMediaPath($fileName));
     $ioAdapter = new Varien_Io_File();
     $ioAdapter->setAllowCreateFolders(true);
     $destinationDirectory = dirname($this->_getConfig()->getMediaPath($fileName));
     try {
         $ioAdapter->open(array('path' => $destinationDirectory));
         if (!$ioAdapter->cp($thumbnail, $this->_getConfig()->getMediaPath($fileName))) {
             return false;
         }
         $ioAdapter->chmod($this->_getConfig()->getMediaPath($fileName), 0777);
         if ($tempFile) {
             $ioAdapter->rm($tempFile);
         }
     } catch (Exception $e) {
         Mage::throwException(Mage::helper('videogallery')->__($e->getMessage()));
     }
     $fileName = str_replace(DS, '/', $fileName);
     return $fileName;
 }