Ejemplo n.º 1
0
 /**
  * Rotate all files in var/log which ends with .log
  */
 public function rotateLogs()
 {
     $var = Mage::getBaseDir('log');
     $logDir = new Varien_Io_File();
     $logDir->cd($var);
     $logFiles = $logDir->ls(Varien_Io_File::GREP_FILES);
     foreach ($logFiles as $logFile) {
         if ($logFile['filetype'] == 'log') {
             $filename = $logFile['text'];
             if (extension_loaded('zlib')) {
                 $zipname = $var . DS . $this->getArchiveName($filename);
                 $zip = gzopen($zipname, 'wb9');
                 gzwrite($zip, $logDir->read($filename));
                 gzclose($zip);
             } else {
                 $logDir->cp($filename, $this->getArchiveName($filename));
             }
             foreach ($this->getFilesOlderThan(self::MAX_FILE_DAYS, $var, $filename) as $oldFile) {
                 $logDir->rm($oldFile['text']);
             }
             $logDir->rm($filename);
         }
     }
     $logDir->close();
 }
Ejemplo n.º 2
0
 public static function setUpBeforeClass()
 {
     $fixtureDir = dirname(__DIR__) . DIRECTORY_SEPARATOR . '_files';
     Mage::app()->getConfig()->getOptions()->setDesignDir($fixtureDir . DIRECTORY_SEPARATOR . 'design');
     Varien_Io_File::rmdirRecursive(Mage::app()->getConfig()->getOptions()->getMediaDir() . '/skin');
     $ioAdapter = new Varien_Io_File();
     $ioAdapter->cp(Mage::app()->getConfig()->getOptions()->getJsDir() . '/prototype/prototype.js', Mage::app()->getConfig()->getOptions()->getJsDir() . '/prototype/prototype.min.js');
     self::$_developerMode = Mage::getIsDeveloperMode();
 }
Ejemplo n.º 3
0
 public static function setUpBeforeClass()
 {
     $mediaDir = Mage::app()->getConfig()->getOptions()->getMediaDir();
     $filesystem = Mage::getObjectManager()->create('Magento_Filesystem');
     $filesystem->delete($mediaDir . '/theme/frontend');
     $filesystem->delete($mediaDir . '/theme/_merged');
     $ioAdapter = new Varien_Io_File();
     $ioAdapter->cp(Mage::app()->getConfig()->getOptions()->getJsDir() . '/prototype/prototype.js', Mage::app()->getConfig()->getOptions()->getJsDir() . '/prototype/prototype.min.js');
     self::$_developerMode = Mage::getIsDeveloperMode();
 }
Ejemplo n.º 4
0
 /**
  * Publish the specified feed file.
  *
  * @param string $filepath
  * @param array $params
  * @return Grommet_ProductFeed_Model_Feed_Publisher_File
  */
 public function publish($filepath, array $params = array())
 {
     if (empty($params['destination_path'])) {
         throw new Mage_Core_Exception('Invalid parameters - destination_path must be set.');
     }
     $ioAdapter = new Varien_Io_File();
     $ioAdapter->setAllowCreateFolders(true);
     $ioAdapter->createDestinationDir(pathinfo($params['destination_path'], PATHINFO_DIRNAME));
     $writeResult = $ioAdapter->cp($filepath, $params['destination_path']);
     if (!$writeResult) {
         throw new Mage_Core_Exception('Unable to write file ' . $params['destination_path'] . ' to FTP.');
     }
     return $this;
 }
Ejemplo n.º 5
0
 protected function _copyImage($file)
 {
     try {
         $ioObject = new Varien_Io_File();
         $destDirectory = dirname($this->_getConfig()->getMediaPath($file));
         $ioObject->open(array('path' => $destDirectory));
         $destFile = $this->_getUniqueFileName($file, $ioObject->dirsep());
         if (!$ioObject->fileExists($this->_getConfig()->getMediaPath($file), true)) {
             throw new Exception('File not exists');
         }
         if ($this->_checkDb()) {
             Mage::helper('core/file_storage_database')->copyFile($this->_getConfig()->getMediaShortUrl($file), $this->_getConfig()->getMediaShortUrl($destFile));
             $ioObject->rm($this->_getConfig()->getMediaPath($destFile));
         } else {
             $ioObject->cp($this->_getConfig()->getMediaPath($file), $this->_getConfig()->getMediaPath($destFile));
         }
     } catch (Exception $e) {
         $file = $this->_getConfig()->getMediaPath($file);
         Mage::throwException(Mage::helper('ampaction')->__('Failed to copy file %s. Please, delete media with non-existing images and try again.', $file));
         $e = $e;
         // for zend debugger
     }
     return str_replace($ioObject->dirsep(), '/', $destFile);
 }
 /**
  * Retrieve custom size image url
  *
  * @param string $imageFile
  * @param int $width
  * @param int $height
  * @return string|bool
  */
 public function getCustomSizeImageUrl($imageFile, $width = 100, $height = 100)
 {
     /** @var $imageHelper Mage_XmlConnect_Helper_Image */
     $imageHelper = Mage::helper('xmlconnect/image');
     $screenSize = $width . 'x' . $height;
     $customDir = $imageHelper->getMediaPath('custom' . DS . $screenSize);
     $ioFile = new Varien_Io_File();
     $ioFile->checkAndCreateFolder($customDir);
     $filePath = self::getBasePath() . DS . $imageFile;
     $isImagePng = true;
     if (!$ioFile->fileExists($filePath)) {
         return false;
     }
     $originalImageType = $this->_getImageType($filePath);
     if ($originalImageType !== IMAGETYPE_PNG) {
         $imageFile = $this->_convertFileExtensionToPng($imageFile);
         $isImagePng = false;
     }
     $customSizeFile = $customDir . DS . $imageFile;
     if (!file_exists($customSizeFile)) {
         if (!$isImagePng) {
             $filePath = $this->_forcedConvertPng($filePath, $customSizeFile, $originalImageType);
         }
         $image = new Varien_Image($filePath);
         $widthOriginal = $image->getOriginalWidth();
         $heightOriginal = $image->getOriginalHeight();
         if ($width != $widthOriginal) {
             $widthOriginal = $width;
         }
         if ($height != $heightOriginal) {
             $heightOriginal = $height;
         }
         if ($widthOriginal != $image->getOriginalWidth() || $heightOriginal != $image->getOriginalHeight()) {
             $image->keepTransparency(true);
             $image->keepFrame(true);
             $image->keepAspectRatio(true);
             $image->backgroundColor(array(0, 0, 0));
             $image->resize($widthOriginal, $heightOriginal);
             $image->save($customDir, basename($imageFile));
         } else {
             $ioFile->cp($filePath, $customSizeFile);
         }
     }
     return $imageHelper->getMediaUrl("custom/{$screenSize}/" . basename($imageFile));
 }
Ejemplo n.º 7
0
 protected function _copy($file)
 {
     $ioAdapter = new Varien_Io_File();
     if (!$ioAdapter->fileExists($file)) {
         Mage::throwException(Mage::helper('dataflow')->__('File "%s" does not exist.', $file));
     }
     $ioAdapter->setAllowCreateFolders(true);
     $ioAdapter->createDestinationDir($this->getBatchModel()->getIoAdapter()->getPath());
     return $ioAdapter->cp($file, $this->getBatchModel()->getIoAdapter()->getFile(true));
 }
Ejemplo n.º 8
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;
    }
Ejemplo n.º 9
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.'));
     }
     Mage::dispatchEvent('catalog_product_media_add_image', array('product' => $product, 'image' => $file));
     $pathinfo = pathinfo($file);
     $imgExtensions = array('jpg', 'jpeg', 'gif', 'png');
     if (!isset($pathinfo['extension']) || !in_array(strtolower($pathinfo['extension']), $imgExtensions)) {
         Mage::throwException(Mage::helper('catalog')->__('Invalid image file type.'));
     }
     $fileName = Mage_Core_Model_File_Uploader::getCorrectFileName($pathinfo['basename']);
     $dispretionPath = Mage_Core_Model_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));
         /** @var $storageHelper Mage_Core_Helper_File_Storage_Database */
         $storageHelper = Mage::helper('core/file_storage_database');
         if ($move) {
             $ioAdapter->mv($file, $this->_getConfig()->getTmpMediaPath($fileName));
             //If this is used, filesystem should be configured properly
             $storageHelper->saveFile($this->_getConfig()->getTmpMediaShortUrl($fileName));
         } else {
             $ioAdapter->cp($file, $this->_getConfig()->getTmpMediaPath($fileName));
             $storageHelper->saveFile($this->_getConfig()->getTmpMediaShortUrl($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, 'defaultimg' => (int) $exclude);
     $product->setData($attrCode, $mediaGalleryData);
     if (!is_null($mediaAttribute)) {
         $this->setMediaAttribute($product, $mediaAttribute, $fileName);
     }
     return $fileName;
 }
Ejemplo n.º 10
0
 /**
  * Copy image and return new filename.
  *
  * @param string $file
  * @return string
  */
 protected function _copyImage($file)
 {
     try {
         $ioObject = new Varien_Io_File();
         $destDirectory = dirname($this->_getConfig()->getMediaPath($file));
         $ioObject->open(array('path' => $destDirectory));
         $destFile = dirname($file) . $ioObject->dirsep() . Varien_File_Uploader::getNewFileName($this->_getConfig()->getMediaPath($file));
         if (!$ioObject->fileExists($this->_getConfig()->getMediaPath($file), true)) {
             throw new Exception();
         }
         $ioObject->cp($this->_getConfig()->getMediaPath($file), $this->_getConfig()->getMediaPath($destFile));
     } catch (Exception $e) {
         Mage::throwException(Mage::helper('catalog')->__('Failed to copy file %s. Please, delete media with non-existing images and try again.', $this->_getConfig()->getMediaPath($file)));
     }
     return str_replace($ioObject->dirsep(), '/', $destFile);
 }
Ejemplo n.º 11
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));
 }
 /**
  * Copying rating button images from skin to media folder
  *
  * @param string      $image    Button image file name
  * @param null|string $language For language specific rating button images
  *
  * @return void
  */
 protected function _copyTrustedratingRateusButtonImageToMediaDir($image, $language = null)
 {
     $src = '';
     $dest = '';
     $src .= $this->_getTrustedratingRateusButtonImageSkinImageDir($language);
     $src .= DS;
     $src .= $image;
     $dest .= $this->_getTrustedratingRateusButtonImageMediaDir();
     $dest .= DS;
     $dest .= $image;
     if (!is_file($dest) && is_file($src)) {
         $ioF = new Varien_Io_File();
         Mage::getSingleton('adminhtml/session')->addNotice($this->getHelper()->__('%s has been copied to the media folder (%s)!', $image, 'media/' . Symmetrics_TrustedRating_Model_Trustedrating::RATEUS_BUTTON_IMAGE_SUBPATH));
         $ioF->cp($src, $dest);
     }
 }
Ejemplo n.º 13
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);
     //}
 }
 protected function _testFileSize($testFile, $line)
 {
     $mediaDir = Mage::getBaseDir('media') . '/';
     $fileName = 'am_sitemap_test' . rand(1, 1000) . '.xml';
     $io = new Varien_Io_File();
     $io->cp($testFile, $mediaDir . $fileName);
     $io->setAllowCreateFolders(true);
     $io->open(array('path' => $mediaDir));
     $io->streamOpen($fileName, 'a+');
     $io->streamWrite($line);
     $io->streamWrite('</urlset>');
     $io->streamClose();
     $fileSize = filesize($mediaDir . $fileName);
     unlink($mediaDir . $fileName);
     return $fileSize;
 }
Ejemplo n.º 15
0
 /**
  * Reset themes color changes
  * Copy /xmlconnect/etc/themes/* to media/xmlconnect/themes/*
  *
  * @throws Mage_Core_Exception
  * @param null $theme
  * @return null
  */
 public function resetTheme($theme = null)
 {
     $themeDir = $this->getMediaThemePath();
     $defaultThemeDir = $this->_getDefaultThemePath();
     $ioFile = new Varien_Io_File();
     $ioFile->open(array('path' => $defaultThemeDir));
     $fileList = $ioFile->ls(Varien_Io_File::GREP_FILES);
     foreach ($fileList as $file) {
         $f = $file['text'];
         $src = $defaultThemeDir . DS . $f;
         $dst = $themeDir . DS . $f;
         if ($theme && $theme . '.xml' != $f) {
             continue;
         }
         if (!$ioFile->cp($src, $dst)) {
             Mage::throwException(Mage::helper('xmlconnect')->__('Can\'t copy file "%s" to "%s".', $src, $dst));
         } else {
             $ioFile->chmod($dst, 0755);
         }
     }
 }
Ejemplo n.º 16
0
 /**
  * Move images (Step 3)
  *
  * @param Pimgento_Core_Model_Task $task
  *
  * @return bool
  */
 public function moveImages($task)
 {
     $resource = $this->getResource();
     $adapter = $this->getAdapter();
     /* @var $helper Pimgento_Image_Helper_Data */
     $helper = Mage::helper('pimgento_image');
     $directory = $helper->getImageDir();
     $images = $helper->getFiles($directory);
     if (count($images) === 0) {
         $task->nextStep();
         $task->nextStep();
         $task->setMessage($helper->__('No image found'));
         return false;
     }
     /** @var $storageHelper Mage_Core_Helper_File_Storage_Database */
     $storageHelper = Mage::helper('core/file_storage_database');
     $ioAdapter = new Varien_Io_File();
     $ioAdapter->setAllowCreateFolders(true);
     $destination = $helper->getBaseMediaPath();
     foreach ($images as $sku => $pictures) {
         $exists = $adapter->fetchOne($adapter->select()->from($resource->getTable('catalog/product'), array($this->_zde(1)))->where('sku = ?', $sku)->limit(1));
         if (!$exists) {
             continue;
         }
         $data = array('code' => $sku);
         $gallery = array();
         $key = 0;
         foreach ($pictures as $picture) {
             $ioAdapter->open(array('path' => dirname($destination . $picture['name'])));
             if (Mage::getStoreConfig('pimdata/image/delete')) {
                 $ioAdapter->mv($picture['directory'] . $picture['file'], $destination . $picture['name']);
             } else {
                 $ioAdapter->cp($picture['directory'] . $picture['file'], $destination . $picture['name']);
             }
             $storageHelper->saveFile($destination . $picture['name']);
             if ($key === 0) {
                 $data['image'] = $picture['name'];
                 $data['small_image'] = $picture['name'];
                 $data['thumbnail'] = $picture['name'];
             }
             $gallery[] = $picture['name'];
             $key++;
         }
         $data['gallery'] = join(',', $gallery);
         $adapter->insert($this->getTable(), $data);
     }
     return true;
 }
 /**
  * Copy image and return new filename.
  *
  * @param string $file
  * @return string
  */
 protected function _copyImage($file)
 {
     $ioObject = new Varien_Io_File();
     $destDirectory = dirname($this->_getConfig()->getMediaPath($file));
     $ioObject->open(array('path' => $destDirectory));
     $destFile = dirname($file) . $ioObject->dirsep() . Varien_File_Uploader::getNewFileName($this->_getConfig()->getMediaPath($file));
     $ioObject->cp($this->_getConfig()->getMediaPath($file), $this->_getConfig()->getMediaPath($destFile));
     return str_replace($ioObject->dirsep(), '/', $destFile);
 }
Ejemplo n.º 18
0
 /**
  * Reset all theme color changes
  * Copy media/xmlconnect/themes/default/* to media/xmlconnect/themes/*
  *
  * @return void
  */
 public function resetAllThemes()
 {
     $themeDir = Mage::getBaseDir('media') . DS . 'xmlconnect' . DS . 'themes';
     $defaultThemeDir = Mage::getBaseDir('media') . DS . 'xmlconnect' . DS . 'themes' . DS . 'default';
     $io = new Varien_Io_File();
     $io->open(array('path' => $defaultThemeDir));
     $fileList = $io->ls(Varien_Io_File::GREP_FILES);
     foreach ($fileList as $file) {
         $f = $file['text'];
         $src = $defaultThemeDir . DS . $f;
         $dst = $themeDir . DS . $f;
         if ($io->isWriteable($dst)) {
             try {
                 if (!$io->cp($src, $dst)) {
                     Mage::throwException(Mage::helper('xmlconnect')->__('Can\\t copy file "%s" to "%s".', $src, $dst));
                 } else {
                     $io->chmod($dst, 0755);
                 }
             } catch (Exception $e) {
                 Mage::logException($e);
             }
         }
     }
 }
Ejemplo n.º 19
0
 /**
  *
  * especially developed for copying when we get incoming data as an image collection
  * instead of plain post...
  *
  */
 public function beforeSave($object)
 {
     $storeId = $object->getStoreId();
     $attributeId = $this->getAttribute()->getId();
     $entityId = $object->getId();
     $entityIdField = $this->getEntityIdField();
     $entityTypeId = $this->getAttribute()->getEntity()->getTypeId();
     $connection = $this->getConnection('write');
     $values = $object->getData($this->getAttribute()->getName());
     if (!is_array($values) && is_object($values)) {
         foreach ((array) $values->getItems() as $image) {
             // TOFIX
             $io = new Varien_Io_File();
             $value = $image->getData();
             $data = array();
             $data[$entityIdField] = $entityId;
             $data['attribute_id'] = $attributeId;
             $data['position'] = $value['position'];
             $data['entity_type_id'] = $entityTypeId;
             $data['store_id'] = $storeId;
             if ($entityId) {
                 $connection->insert($this->getTable(), $data);
                 $lastInsertId = $connection->lastInsertId();
             } else {
                 continue;
             }
             unset($newFileName);
             $types = $this->getImageTypes();
             foreach ($types as $type) {
                 try {
                     $io->open();
                     $path = Mage::getStoreConfig('system/filesystem/upload', 0);
                     $io->cp($path . '/' . $type . '/' . 'image_' . $entityId . '_' . $value['value_id'] . '.' . 'jpg', $path . '/' . $type . '/' . 'image_' . $entityId . '_' . $lastInsertId . '.' . 'jpg');
                     $io->close();
                 } catch (Exception $e) {
                     continue;
                 }
                 $newFileName = 'image_' . $entityId . '_' . $lastInsertId . '.' . 'jpg';
             }
             $condition = array($connection->quoteInto('value_id = ?', $lastInsertId));
             if (isset($newFileName)) {
                 $data = array();
                 $data['value'] = $newFileName;
                 $connection->update($this->getTable(), $data, $condition);
             } else {
                 $connection->delete($this->getTable(), $condition);
             }
         }
         $object->setData($this->getAttribute()->getName(), array());
     }
     return parent::beforeSave($object);
 }
Ejemplo n.º 20
0
 /**
  * Download products media
  *
  * @param Varien_Object|null $item
  * @return array
  */
 public function downloadProductImages($item = null)
 {
     $ioAdapter = new Varien_Io_File();
     $tmpDirectory = Mage::getBaseDir('var') . DS . 'api' . DS . uniqid();
     $ioAdapter->checkAndCreateFolder($tmpDirectory);
     $ioAdapter->open(array('path' => $tmpDirectory));
     if (!$item) {
         $items = Mage::getModel('retailops_api/catalog_media_item')->getCollection();
         $limit = $this->getHelper()->getConfig('media_processing_products_limit');
         if (!is_numeric($limit)) {
             $limit = self::CRON_DOWNLOAD_LIMIT;
         }
         $items->getSelect()->limit($limit);
     } else {
         $items = array($item);
     }
     $result = array();
     /** @var $item RetailOps_Api_Model_Catalog_Media_Item */
     foreach ($items as $item) {
         $productId = $item->getProductId();
         $product = Mage::getModel('catalog/product')->load($productId);
         $product->setStoreId(0);
         //using default store for images import
         $gallery = $this->_getGalleryAttribute($product);
         $data = json_decode($item->getMediaData(), true);
         $allImages = $this->_getResource()->getProductMedia($productId);
         $this->_mediaKeys = array();
         $this->_fileNames = array();
         foreach ($allImages as $image) {
             $this->_mediaKeys[] = $image['retailops_mediakey'];
             $this->_fileNames[] = $image['value'];
         }
         $sku = $product->getSku();
         $result[$sku] = array();
         try {
             $imageResult = array();
             $newImages = array();
             foreach ($data as $newImage) {
                 if ($this->_imageExists($newImage)) {
                     continue;
                 }
                 try {
                     $url = $newImage['download_url'];
                     if (!$this->_httpFileExists($url)) {
                         Mage::throwException('Image does not exist.');
                     }
                     $fileName = $this->_getFileName($url, $newImage['mediakey']);
                     $fileName = $tmpDirectory . DS . $fileName;
                     $ioAdapter->cp($url, $fileName);
                     // Adding image to gallery
                     $file = $gallery->getBackend()->addImage($product, $fileName, null, true);
                     // Remove temporary directory
                     $ioAdapter->rmdir($tmpDirectory, true);
                     $newImages[$file] = $newImage['mediakey'];
                     $gallery->getBackend()->updateImage($product, $file, $newImage);
                     if (isset($newImage['types'])) {
                         $gallery->getBackend()->setMediaAttribute($product, $newImage['types'], $file);
                     }
                 } catch (Exception $e) {
                     $imageResult[] = sprintf('Could not save image %s, error message: %s', $newImage['mediakey'], $e->getMessage());
                 }
             }
             if ($imageResult) {
                 $result[$sku]['images'] = $imageResult;
             }
             $product->save();
             $this->_updateMediaKeys($product->getId(), $newImages);
             if ($item->getId()) {
                 $item->delete();
             }
             $product->clearInstance();
         } catch (Exception $e) {
             $result[$sku]['general'] = $e->getMessage();
         }
     }
     return $result;
 }
Ejemplo n.º 21
0
 /**
  * Copy current theme to specified file
  *
  * @param  $filePath
  * @return string new file
  */
 protected function _createCopy($filePath)
 {
     $currentThemeFileName = $this->_getThemeFile();
     $ioFile = new Varien_Io_File();
     if (!$ioFile->cp($currentThemeFileName, $filePath)) {
         Mage::throwException(Mage::helper('xmlconnect')->__('Can\'t copy file "%s" to "%s".', $currentThemeFileName, $filePath));
     } else {
         $ioFile->chmod($filePath, 0755);
     }
     return $filePath;
 }
Ejemplo n.º 22
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;
 }