/**
  * @param $value
  * @param bool $forceDownload
  * @return string
  */
 public function getYouTubeImage($value, $forceDownload = false)
 {
     $baseDir = Mage::getBaseDir('media');
     $localDir = 'gallery' . DS . 'data' . DS . 'thumbnail';
     if (is_dir($localDir)) {
         mkdir($localDir, 0777, true);
     }
     $fileName = Varien_File_Uploader::getNewFileName($baseDir . DS . $localDir . DS . $value . '.jpg');
     $absPath = $baseDir . DS . $localDir . DS . $fileName;
     if ($forceDownload || !is_file($absPath)) {
         try {
             $url = sprintf('http://img.youtube.com/vi/%s/0.jpg', $value);
             $client = new Zend_Http_Client($url);
             $response = $client->request(Zend_Http_Client::GET);
             if (200 != $response->getStatus()) {
                 Mage::throwException("Can't download youtube thumbnail");
             }
             if (!is_dir($baseDir . DS . $localDir)) {
                 mkdir($baseDir . DS . $localDir, 0777, true);
             }
             file_put_contents($absPath, $response->getBody());
         } catch (Exception $e) {
             Mage::logException($e);
             return false;
         }
     }
     return $localDir . DS . $fileName;
 }
예제 #2
0
 public function saveAction()
 {
     $post_data = $this->getRequest()->getPost();
     if ($post_data) {
         try {
             $post_data['category'] = implode(',', $post_data['category']);
             //save image
             try {
                 if ((bool) $post_data['image']['delete'] == 1) {
                     $post_data['image'] = '';
                 } else {
                     unset($post_data['image']);
                     if (isset($_FILES)) {
                         if ($_FILES['image']['name']) {
                             if ($this->getRequest()->getParam("id")) {
                                 $model = Mage::getModel("gallery/image")->load($this->getRequest()->getParam("id"));
                                 if ($model->getData('image')) {
                                     $io = new Varien_Io_File();
                                     $io->rm(Mage::getBaseDir('media') . DS . implode(DS, explode('/', $model->getData('image'))));
                                 }
                             }
                             $path = Mage::getBaseDir('media') . DS . 'gallery' . DS . 'image' . DS;
                             $uploader = new Varien_File_Uploader('image');
                             $uploader->setAllowedExtensions(array('jpg', 'png', 'gif'));
                             $uploader->setAllowRenameFiles(false);
                             $uploader->setFilesDispersion(false);
                             $destFile = $path . $_FILES['image']['name'];
                             $filename = $uploader->getNewFileName($destFile);
                             $uploader->save($path, $filename);
                             $post_data['image'] = 'gallery/image/' . $filename;
                         }
                     }
                 }
             } catch (Exception $e) {
                 Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
                 $this->_redirect('*/*/edit', array('id' => $this->getRequest()->getParam('id')));
                 return;
             }
             //save image
             $model = Mage::getModel("gallery/image")->addData($post_data)->setId($this->getRequest()->getParam("id"))->save();
             Mage::getSingleton("adminhtml/session")->addSuccess(Mage::helper("adminhtml")->__("Image was successfully saved"));
             Mage::getSingleton("adminhtml/session")->setImageData(false);
             if ($this->getRequest()->getParam("back")) {
                 $this->_redirect("*/*/edit", array("id" => $model->getId()));
                 return;
             }
             $this->_redirect("*/*/");
             return;
         } catch (Exception $e) {
             Mage::getSingleton("adminhtml/session")->addError($e->getMessage());
             Mage::getSingleton("adminhtml/session")->setImageData($this->getRequest()->getPost());
             $this->_redirect("*/*/edit", array("id" => $this->getRequest()->getParam("id")));
             return;
         }
     }
     $this->_redirect("*/*/");
 }
예제 #3
0
 /**
  * Move file from tmp path to base path
  *
  * @param string $baseTmpPath
  * @param string $basePath
  * @param string $file
  * @return string
  */
 public function moveFileFromTmp($baseTmpPath, $basePath, $file)
 {
     $ioObject = new Varien_Io_File();
     $destDirectory = dirname($this->getFilePath($basePath, $file));
     try {
         $ioObject->open(array('path' => $destDirectory));
     } catch (Exception $e) {
         $ioObject->mkdir($destDirectory, 0777, true);
         $ioObject->open(array('path' => $destDirectory));
     }
     if (strrpos($file, '.tmp') == strlen($file) - 4) {
         $file = substr($file, 0, strlen($file) - 4);
     }
     $destFile = dirname($file) . $ioObject->dirsep() . Varien_File_Uploader::getNewFileName($this->getFilePath($basePath, $file));
     $result = $ioObject->mv($this->getFilePath($baseTmpPath, $file), $this->getFilePath($basePath, $file));
     return str_replace($ioObject->dirsep(), '/', $destFile);
 }
예제 #4
0
 public function moveImageFromTmp($file)
 {
     $ioObject = new Varien_Io_File();
     $destDirectory = Mage::getBaseDir('media') . '/option_image';
     try {
         $ioObject->open(array('path' => $destDirectory));
     } catch (Exception $e) {
         $ioObject->mkdir($destDirectory, 0777, true);
         $ioObject->open(array('path' => $destDirectory));
     }
     if (strrpos($file, '.tmp') == strlen($file) - 4) {
         $file = substr($file, 0, strlen($file) - 4);
     }
     $destFile = Varien_File_Uploader::getNewFileName($file);
     $dest = $destDirectory . '/' . $destFile;
     $ioObject->mv($this->_getMadiaConfig()->getTmpMediaPath($file), $dest);
     return $destFile;
 }
예제 #5
0
 public function uploadAction()
 {
     if (isset($_FILES)) {
         if ($_FILES['image']['size'] > 52428800) {
             //throw new Exception('Disallowed File size it should be less than 50 MB .');
             Mage::getSingleton('core/session')->addError('Disallowed File size it should be less than 50 MB .');
             echo "sizeerror";
             return;
         }
         $fileTypeArray = explode(".", $_FILES['image']['name']);
         $fileType = end($fileTypeArray);
         if (!in_array(strtolower($fileType), array('jpg', 'JPG', 'JPEG', 'jpeg', 'png', 'PNG', 'tiff', 'tif'))) {
             Mage::getSingleton('core/session')->addError('Disallowed File Type');
             echo "fileerror";
             return;
         }
         $path = Mage::getBaseDir('media') . DS . 'userUploads' . DS . 'image' . DS;
         //$path = Mage::getBaseDir()."/plupload/examples/uploads";
         $uploader = new Varien_File_Uploader('image');
         $uploader->setAllowedExtensions(array('jpg', 'jpeg', 'png', 'gif', 'tiff', 'tif'));
         $uploader->setAllowRenameFiles(false);
         $uploader->setFilesDispersion(false);
         $str = str_replace(' ', '', $_FILES['image']['name']);
         $destFile = $path . time() . $str;
         $filename = $uploader->getNewFileName($destFile);
         $uploader->save($path, $filename);
         $image = Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA) . 'userUploads/image/' . $filename;
         $path_parts = pathinfo($image);
         if ($path_parts['extension'] == "tif" || $path_parts['extension'] == "TIF" || $path_parts['extension'] == "tiff" || $path_parts['extension'] == "TIFF") {
             $changetype = new Imagick($image);
             $changetype->setImageFormat('jpg');
             $typeChangeImageName = time();
             $changetype->writeImage(Mage::getBaseDir('media') . DS . "userUploads" . DS . "image" . DS . $typeChangeImageName . ".jpg");
             $image = Mage::getBaseUrl('media') . DS . "userUploads" . DS . "image" . DS . $typeChangeImageName . ".jpg";
         }
         echo $image;
         return;
     }
 }
예제 #6
0
 /**
  * Check whether file to move exists. Getting unique name
  *
  * @param <type> $file
  * @param <type> $dirsep
  * @return string
  */
 protected function _getUniqueFileName($file, $dirsep)
 {
     if ($this->_checkDb()) {
         $destFile = Mage::helper('core/file_storage_database')->getUniqueFilename(Mage::getSingleton('catalog/product_media_config')->getBaseMediaUrlAddition(), $file);
     } else {
         $destFile = dirname($file) . $dirsep;
         if (version_compare(Mage::getVersion(), '1.5') > 0) {
             $destFile .= Mage_Core_Model_File_Uploader::getNewFileName($this->_getConfig()->getMediaPath($file));
         } else {
             $destFile .= Varien_File_Uploader::getNewFileName($this->_getConfig()->getMediaPath($file));
         }
     }
     return $destFile;
 }
예제 #7
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);
     //}
 }
예제 #8
0
 public function uploadFile($key)
 {
     try {
         $path = Mage::getBaseDir('media') . DS . 'formbuilder/frontend/uploaded_files' . DS;
         $uploader = new Varien_File_Uploader($key);
         //$uploader->setAllowedExtensions(array('jpg','png','gif'));
         $uploader->setAllowRenameFiles(false);
         $uploader->setFilesDispersion(false);
         $destFile = $path . $this->_fileObject[$key]['name'];
         $filename = $uploader->getNewFileName($destFile);
         $uploader->save($path, $filename);
         return "formbuilder/frontend/uploaded_files/" . $filename;
     } catch (Exception $e) {
         $this->_session->addError($this->_helper->__("Error uploading file"));
         return false;
     }
 }
 public function saveAction()
 {
     if ($data = $this->getRequest()->getPost()) {
         /*echo "<pre>";
         		print_r($data);
         		echo "</pre>";
         		exit();*/
         $model = Mage::getModel("formbuilder/forms")->load($this->getRequest()->getParam("id"));
         $currentFormId = $this->getRequest()->getParam("id");
         //save image
         try {
             if ((bool) $data['title_image']['delete'] == 1) {
                 $data['title_image'] = '';
             } else {
                 unset($data['title_image']);
                 if (isset($_FILES)) {
                     if ($_FILES['title_image']['name']) {
                         if ($this->getRequest()->getParam("id")) {
                             //$model = Mage::getModel("formbuilder/forms")->load($this->getRequest()->getParam("id"));
                             if ($model->getData('title_image')) {
                                 $io = new Varien_Io_File();
                                 $io->rm(Mage::getBaseDir('media') . DS . implode(DS, explode('/', $model->getData('title_image'))));
                             }
                         }
                         $path = Mage::getBaseDir('media') . DS . 'formbuilder/images' . DS;
                         $uploader = new Varien_File_Uploader('title_image');
                         $uploader->setAllowedExtensions(array('jpg', 'png', 'gif'));
                         $uploader->setAllowRenameFiles(false);
                         $uploader->setFilesDispersion(false);
                         $destFile = $path . $_FILES['title_image']['name'];
                         $filename = $uploader->getNewFileName($destFile);
                         $uploader->save($path, $filename);
                         $data['title_image'] = 'formbuilder/images/' . $filename;
                     }
                 }
             }
         } catch (Exception $e) {
             Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
             $this->_redirect('*/*/edit', array('id' => $this->getRequest()->getParam('id')));
             return;
         }
         //save image ends
         try {
             //$model = Mage::getModel("formbuilder/forms")->load($this->getRequest()->getParam("id"));
             if (isset($data['stores']) && !empty($data['stores'])) {
                 if (in_array('0', $data['stores'])) {
                     $data['stores'] = array(0);
                 }
                 //$stores = Mage::helper('core')->jsonEncode($data['stores']);
                 $data['stores'] = implode(',', $data['stores']);
             }
             if ($model->getCreatedTime() == NULL) {
                 $data['created_time'] = now();
             }
             $data['update_time'] = now();
             /*$fieldsModel = Mage::helper('formbuilder')->getFieldsModel();
             		$getFieldsCollection = $fieldsModel->getFieldsCollection($currentFormId);
             		$getNoOfFields = count($getFieldsCollection);
             		$data['no_of_fields'] = $getNoOfFields;*/
             /*if($data['title']=='' || $data['title']==NULL)
              	$data['title'] = $model['title'];*/
             /*$data['title'] = $data['in_toplinks'];
             		$data['title_image'] = $data['in_menu'];*/
             $model->addData($data)->setFormsIndex($this->getRequest()->getParam("id"))->save();
             if (!$currentFormId) {
                 $currentFormId = $model->getFormsIndex();
             }
             // saveFields
             $fieldsArray = $data['product']['options'];
             //Mage::helper('formbuilder')->saveFields($fieldsArray);
             $fieldsModel = Mage::helper('formbuilder')->getFieldsModel();
             $fieldsModel->saveFields($fieldsArray, $currentFormId);
             // saveFields
             //save no of fields
             $fieldsModel = Mage::helper('formbuilder')->getFieldsModel();
             $getFieldsCollection = $fieldsModel->getFieldsCollection($currentFormId);
             $getNoOfFields = count($getFieldsCollection);
             //$data['no_of_fields'] = $getNoOfFields;
             $formsModel = Mage::helper('formbuilder')->getFormsModel();
             $formsModel->load($currentFormId);
             $formsModel->setNoOfFields($getNoOfFields);
             $formsModel->save();
             //save no of fields ends
             //$this->createCmsPage($model);
             Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('formbuilder')->__('Form was successfully saved'));
             Mage::getSingleton('adminhtml/session')->setFormData(false);
             if ($this->getRequest()->getParam('back')) {
                 $this->_redirect('*/*/edit', array('id' => $model->getFormsIndex()));
                 return;
             }
             $this->_redirect('*/*/');
             return;
         } catch (Exception $e) {
             Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
             Mage::getSingleton('adminhtml/session')->setFormData($data);
             $this->_redirect('*/*/edit', array('id' => $this->getRequest()->getParam('id')));
             return;
         }
     }
     Mage::getSingleton('adminhtml/session')->addError(Mage::helper('formbuilder')->__('Unable to find Form to save'));
     $this->_redirect('*/*/');
 }
예제 #10
0
    /**
     * This method will run when the product is saved from the Magento Admin
     * Use this function to update the product model, process the
     * data or anything you like
     *
     * @param Varien_Event_Observer $observer
     */
    public function saveProductTabData(Varien_Event_Observer $observer)
    {
        if (self::$_singletonFlag) {
            return;
        }
        self::$_singletonFlag = true;

        $product = $observer->getEvent()->getProduct();
        $storeId = $product->getStoreId();
        try {

            $files = $this->_getRequest()->getPost('infofile_file');
            $names = $this->_getRequest()->getPost('infofile_name');
            $labels = $this->_getRequest()->getPost('infofile_label');

            for ($i = 1; $i < count($files); $i++) { // Skip $i=0, because it contains the template!
                $fileName = $files[$i];
                $originalName = $names[$i];

                // move the file from the tmp media folder to the real folder
                $currentFile = Mage::getSingleton('catalog/product_media_config')->getTmpMediaPath($fileName);
                $dispretionPath = Varien_File_Uploader::getDispretionPath($originalName);
                $destinationFolder = Mage::getSingleton('catalog/product_media_config')->getMediaPath($dispretionPath);
                $destFile = Mage::getSingleton('catalog/product_media_config')->getMediaPath($dispretionPath . DS . $originalName);
                if (!(@is_dir($destinationFolder) || @mkdir($destinationFolder, 0777, true))) {
                    throw new Exception("Unable to create directory '{$destinationFolder}'.");
                }
                // adds a counter to the filename
                $destFilename = $dispretionPath . DS . Varien_File_Uploader::getNewFileName($destFile);
                $destFile = Mage::getSingleton('catalog/product_media_config')
                                ->getMediaPath($destFilename);
                rename($currentFile, $destFile);

                // add entry in the database
                $model = Mage::getModel('n98infofiles/file');
                $model->setFilename($destFilename);

                $label = trim($labels[$i]);
                if (empty($label)) {
                    $label = $originalName;
                }
                $model->setLabel($label);
                $model->setProductId($product->getId());
                $model->setStoreId($storeId);
                $model->save();
            }

            // process existing files
            $exLabels = $this->_getRequest()->getPost('infofile_existing_label');
            $exRemove = $this->_getRequest()->getPost('infofile_existing_remove');
            if (count($exRemove) > 0) {
                foreach ($exLabels as $id => $label) {
                    $fileModel = Mage::getModel('n98infofiles/file');
                    $fileModel->load($id);

                    if (isset($exRemove[$id])) {
                        // delete file from disk
                        $filename = Mage::getSingleton('catalog/product_media_config')->getMediaPath($fileModel->getFilename());
                        unlink($filename);
                        // delete record
                        $fileModel->delete();
                        continue;
                    }

                    $fileModel->setLabel($label);
                    $fileModel->save();
                }
            }
        } catch (Exception $e) {
            Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
        }
    }
예제 #11
0
 public function saveAction()
 {
     if ($data = $this->getRequest()->getPost()) {
         $model = Mage::getModel('blog/post');
         if (isset($_FILES['featured_image']['name']) and file_exists($_FILES['featured_image']['tmp_name'])) {
             try {
                 $uploader = new Varien_File_Uploader('featured_image');
                 $uploader->setAllowedExtensions(array('jpg', 'jpeg', 'gif', 'png'));
                 $uploader->setAllowRenameFiles(false);
                 // setAllowRenameFiles(true) -> move your file in a folder the magento way
                 // setAllowRenameFiles(true) -> move your file directly in the $path folder
                 $uploader->setFilesDispersion(false);
                 $path = Mage::getBaseDir('media') . DS . 'wysiwyg/dgtthemes/blog/' . DS;
                 $destFile = $path . $_FILES['featured_image']['name'];
                 $filename = $uploader->getNewFileName($destFile);
                 $uploader->save($path, $filename);
                 $data[featured_image] = 'wysiwyg/dgtthemes/blog/' . $filename;
             } catch (Exception $e) {
             }
         } else {
             if (isset($data['featured_image']['delete']) && $data['featured_image']['delete'] == 1) {
                 $data['featured_image'] = '';
             } else {
                 unset($data['featured_image']);
             }
         }
         if (isset($data['tags'])) {
             if ($this->getRequest()->getParam('id')) {
                 $model->load($this->getRequest()->getParam('id'));
                 $originalTags = explode(",", $model->getTags());
             } else {
                 $originalTags = array();
             }
             $tags = explode(',', $data['tags']);
             array_walk($tags, 'trim');
             foreach ($tags as $key => $tag) {
                 $tags[$key] = Mage::helper('blog')->convertSlashes($tag, 'forward');
             }
             $tags = array_unique($tags);
             $commonTags = array_intersect($tags, $originalTags);
             $removedTags = array_diff($originalTags, $commonTags);
             $addedTags = array_diff($tags, $commonTags);
             if (count($tags)) {
                 $data['tags'] = trim(implode(',', $tags));
             } else {
                 $data['tags'] = '';
             }
         }
         if (isset($data['stores'])) {
             if ($data['stores'][0] == 0) {
                 unset($data['stores']);
                 $data['stores'] = array();
                 $stores = Mage::getSingleton('adminhtml/system_store')->getStoreCollection();
                 foreach ($stores as $store) {
                     $data['stores'][] = $store->getId();
                 }
             }
         }
         $model->setData($data)->setId($this->getRequest()->getParam('id'));
         try {
             $format = Mage::app()->getLocale()->getDateTimeFormat(Mage_Core_Model_Locale::FORMAT_TYPE_MEDIUM);
             if (isset($data['created_time']) && $data['created_time']) {
                 $dateFrom = Mage::app()->getLocale()->date($data['created_time'], $format);
                 $model->setCreatedTime(Mage::getModel('core/date')->gmtDate(null, $dateFrom->getTimestamp()));
                 $model->setUpdateTime(Mage::getModel('core/date')->gmtDate());
             } else {
                 $model->setCreatedTime(Mage::getModel('core/date')->gmtDate());
             }
             if ($this->getRequest()->getParam('user') == null) {
                 $model->setUser(Mage::getSingleton('admin/session')->getUser()->getFirstname() . " " . Mage::getSingleton('admin/session')->getUser()->getLastname())->setUpdateUser(Mage::getSingleton('admin/session')->getUser()->getFirstname() . " " . Mage::getSingleton('admin/session')->getUser()->getLastname());
             } else {
                 $model->setUpdateUser(Mage::getSingleton('admin/session')->getUser()->getFirstname() . " " . Mage::getSingleton('admin/session')->getUser()->getLastname());
             }
             $model->save();
             /* recount affected tags */
             if (isset($data['stores'])) {
                 $stores = $data['stores'];
             } else {
                 $stores = array(null);
             }
             $affectedTags = array_merge($addedTags, $removedTags);
             foreach ($affectedTags as $tag) {
                 foreach ($stores as $store) {
                     if (trim($tag)) {
                         Mage::getModel('blog/tag')->loadByName($tag, $store)->refreshCount();
                     }
                 }
             }
             Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('blog')->__('Post was successfully saved'));
             Mage::getSingleton('adminhtml/session')->setFormData(false);
             if ($this->getRequest()->getParam('back')) {
                 $this->_redirect('*/*/edit', array('id' => $model->getId()));
                 return;
             }
             $this->_redirect('*/*/');
             return;
         } catch (Exception $e) {
             Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
             Mage::getSingleton('adminhtml/session')->setFormData($data);
             $this->_redirect('*/*/edit', array('id' => $this->getRequest()->getParam('id')));
             return;
         }
     }
     Mage::getSingleton('adminhtml/session')->addError(Mage::helper('blog')->__('Unable to find post to save'));
     $this->_redirect('*/*/');
 }
예제 #12
0
 /**
  * Move image from temporary directory to normal
  *
  * @param string $file
  * @return string
  */
 protected function _moveImageFromTmp($file)
 {
     $ioObject = new Varien_Io_File();
     $destDirectory = dirname($this->_getConfig()->getMediaPath($file));
     try {
         $ioObject->open(array('path' => $destDirectory));
     } catch (Exception $e) {
         $ioObject->mkdir($destDirectory, 0777, true);
         $ioObject->open(array('path' => $destDirectory));
     }
     $destFile = dirname($file) . $ioObject->dirsep() . Varien_File_Uploader::getNewFileName($this->_getConfig()->getMediaPath($file));
     $ioObject->mv($this->_getConfig()->getTmpMediaPath($file), $this->_getConfig()->getMediaPath($destFile));
     return $destFile;
 }
예제 #13
0
 public function saveAction()
 {
     if ($data = $this->getRequest()->getPost()) {
         if (isset($_FILES['filename']['name']) && $_FILES['filename']['name'] != '') {
             try {
                 $path = Mage::getBaseDir('media') . DS . 'gallery' . DS;
                 $itemId = $this->getRequest()->getParam('id');
                 if ($itemId) {
                     $temporaryModel = Mage::getModel('gallery/gallery')->load($itemId);
                     $oldFile = $temporaryModel->getFilename();
                     if ($oldFile && $oldFile != '' && file_exists($path . $oldFile)) {
                         unlink($path . $oldFile);
                     }
                 }
                 /* Starting upload */
                 $uploader = new Varien_File_Uploader('filename');
                 // Any extention would work
                 $uploader->setAllowedExtensions(array('jpg', 'jpeg', 'gif', 'png'));
                 $uploader->setAllowRenameFiles(false);
                 // Set the file upload mode
                 // false -> get the file directly in the specified folder
                 // true -> get the file in the product like folders
                 //	(file.jpg will go in something like /media/f/i/file.jpg)
                 $uploader->setFilesDispersion(false);
                 // We set media as the upload dir
                 $destFile = $path . $_FILES['filename']['name'];
                 $filename = $uploader->getNewFileName($destFile);
                 $uploader->save($path, $filename);
             } catch (Exception $e) {
             }
             //this way the name is saved in DB
             $data['filename'] = $filename;
         }
         $model = Mage::getModel('gallery/gallery');
         $model->setData($data)->setId($this->getRequest()->getParam('id'));
         try {
             if ($model->getCreatedTime == NULL || $model->getUpdateTime() == NULL) {
                 $model->setCreatedTime(now())->setUpdateTime(now());
             } else {
                 $model->setUpdateTime(now());
             }
             $model->save();
             if (isset($_FILES['filename'])) {
                 $model->makeThumbnail(150, 120, true);
             }
             Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('gallery')->__('Item was successfully saved'));
             Mage::getSingleton('adminhtml/session')->setFormData(false);
             if ($this->getRequest()->getParam('back')) {
                 $this->_redirect('*/*/edit', array('id' => $model->getId()));
                 return;
             }
             $this->_redirect('*/*/');
             return;
         } catch (Exception $e) {
             Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
             Mage::getSingleton('adminhtml/session')->setFormData($data);
             $this->_redirect('*/*/edit', array('id' => $this->getRequest()->getParam('id')));
             return;
         }
     }
     Mage::getSingleton('adminhtml/session')->addError(Mage::helper('gallery')->__('Unable to find item to save'));
     $this->_redirect('*/*/');
 }
 /**
  * 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);
 }
예제 #15
0
 /**
  * Create preview image copy
  *
  * @return Mage_Core_Model_Theme
  */
 public function createPreviewImageCopy()
 {
     $filePath = $this->_getImagePathPreview() . DIRECTORY_SEPARATOR . $this->getPreviewImage();
     $destinationFileName = Varien_File_Uploader::getNewFileName($filePath);
     $this->_filesystem->copy($this->_getImagePathPreview() . DIRECTORY_SEPARATOR . $this->getPreviewImage(), $this->_getImagePathPreview() . DIRECTORY_SEPARATOR . $destinationFileName);
     $this->setPreviewImage($destinationFileName);
     return $this;
 }
예제 #16
0
 /**
  * Get filename which is not duplicated with other files in media temporary and media directories
  *
  * @param String $fileName
  * @param String $dispretionPath
  * @return String
  */
 protected function _getNotDuplicatedFilename($fileName, $dispretionPath)
 {
     $fileMediaName = $dispretionPath . DS . Varien_File_Uploader::getNewFileName($this->_getConfig()->getMediaPath($fileName));
     $fileTmpMediaName = $dispretionPath . DS . Varien_File_Uploader::getNewFileName($this->_getConfig()->getTmpMediaPath($fileName));
     if ($fileMediaName != $fileTmpMediaName) {
         if ($fileMediaName != $fileName) {
             return $this->_getNotDuplicatedFileName($fileMediaName, $dispretionPath);
         } elseif ($fileTmpMediaName != $fileName) {
             return $this->_getNotDuplicatedFilename($fileTmpMediaName, $dispretionPath);
         }
     }
     return $fileMediaName;
 }
예제 #17
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;
    }
예제 #18
0
 /**
  *
  * Move option image from Temp directory to Media directory
  *
  * @param string $fileName
  * @param int $attributeId
  * @param int $optionId
  * @return string
  */
 public function moveImageFromTemp($fileName, $attributeId, $optionId)
 {
     $ioObject = new Varien_Io_File();
     $targetDirectory = $this->_optionImageBasePath . $attributeId . DS . $optionId;
     try {
         $ioObject->rmdir($targetDirectory, true);
         $ioObject->mkdir($targetDirectory, 0777, true);
         $ioObject->open(array('path' => $targetDirectory));
     } catch (Exception $e) {
         return false;
     }
     $fileName = trim($fileName, '.tmp');
     $targetFile = Varien_File_Uploader::getNewFileName($fileName);
     $path = $targetDirectory . DS . $targetFile;
     $ioObject->mv(Mage::getSingleton('catalog/product_media_config')->getTmpMediaPath($fileName), $path);
     return $targetFile;
 }
예제 #19
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);
 }
예제 #20
0
파일: Video.php 프로젝트: xiaoguizhidao/bb
 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;
 }