示例#1
0
 public function getExtensions()
 {
     $data = array();
     try {
         $file = 'http://d52ndf1ixk2tu.cloudfront.net/media/featured_product.csv';
         /* https does not work */
         $content = $this->urlGetContents($file);
         if ($content == false) {
             $file = 'https://www.iwdagency.com/extensions/media/featured_product.csv';
             $content = $this->urlGetContents($file);
             if ($content == false) {
                 return "";
             }
         }
         $path = Mage::getBaseDir('media') . DS . 'import' . DS . 'featured_product.csv';
         if (!file_exists(Mage::getBaseDir('media') . DS . 'import')) {
             mkdir(Mage::getBaseDir('media') . DS . 'import');
         }
         file_put_contents($path, $content);
         $csv = new Varien_File_Csv();
         $data = $csv->getData($path);
         @unlink($path);
     } catch (Exception $e) {
         Mage::logException($e);
     }
     return $data;
 }
 public function importMotorsDataAction()
 {
     $helper = Mage::helper('M2ePro/Component_Ebay_Motors');
     $motorsType = $this->getRequest()->getPost('motors_type');
     if (!$motorsType || empty($_FILES['source']['tmp_name'])) {
         $this->getSession()->addError(Mage::helper('M2ePro')->__('Some of required fields are not filled up.'));
         return $this->_redirect('*/*/index');
     }
     $csvParser = new Varien_File_Csv();
     $tempCsvData = $csvParser->getData($_FILES['source']['tmp_name']);
     $csvData = array();
     $headers = array_shift($tempCsvData);
     foreach ($tempCsvData as $csvRow) {
         $csvData[] = array_combine($headers, $csvRow);
     }
     $added = 0;
     $existedItems = $this->getExistedMotorsItems();
     $connWrite = Mage::getSingleton('core/resource')->getConnection('core/write');
     $tableName = $helper->getDictionaryTable($motorsType);
     foreach ($csvData as $csvRow) {
         if (!($insertsData = $this->getPreparedInsertData($csvRow, $existedItems))) {
             continue;
         }
         $added++;
         $connWrite->insert($tableName, $insertsData);
     }
     $this->_getSession()->addSuccess("Successfully added '{$added}' compatibility records.");
     return $this->_redirect('*/*/index');
 }
示例#3
0
 public function importDataAction()
 {
     try {
         if ($this->getRequest()->getPost()) {
             if (isset($_FILES['import_file']['name']) && $_FILES['import_file']['name'] != '') {
                 $uploaderFile = new Varien_File_Uploader('import_file');
                 $uploaderFile->setAllowedExtensions(array('csv'));
                 $uploaderFile->setAllowRenameFiles(true);
                 $uploaderFile->setFilesDispersion(false);
                 $uploaderFilePath = Mage::getBaseDir('cache') . DS . 'mgs' . DS . 'brand' . DS . 'import' . DS . 'csv' . DS;
                 $uploaderFile->save($uploaderFilePath, $_FILES['import_file']['name']);
                 $filePath = $uploaderFilePath . $uploaderFile->getUploadedFileName();
                 $csv = new Varien_File_Csv();
                 $brands = $csv->getData($filePath);
                 $i = 0;
                 foreach ($brands as $brand) {
                     if ($i > 0) {
                         Mage::helper('brand')->import($brand);
                     }
                     $i++;
                 }
                 $urlRewriteCollection = Mage::getModel('core/url_rewrite')->getCollection()->addFieldToFilter('id_path', 'brand/index/');
                 foreach ($urlRewriteCollection as $url) {
                     $url->delete();
                 }
                 $urlRewrite = Mage::getModel('core/url_rewrite')->loadByIdPath('brand/index')->setIdPath('brand/index');
                 if (Mage::helper('brand')->urlKey() != '') {
                     $urlRewrite->setRequestPath(Mage::helper('brand')->urlKey());
                 } else {
                     $urlRewrite->setRequestPath('brand');
                 }
                 $urlRewrite->setTargetPath('brand/index/index');
                 $urlRewrite->setIsSystem(1);
                 $urlRewrite->save();
                 $collection = Mage::getModel('brand/brand')->getCollection();
                 foreach ($collection as $brand) {
                     $urlRewriteCollection = Mage::getModel('core/url_rewrite')->getCollection()->addFieldToFilter('id_path', 'brand/view/' . $brand->getId());
                     foreach ($urlRewriteCollection as $url) {
                         $url->delete();
                     }
                     $urlRewrite = Mage::getModel('core/url_rewrite')->loadByIdPath('brand/view/' . $brand->getId())->setIdPath('brand/view/' . $brand->getId());
                     if (Mage::helper('brand')->urlKey() != '') {
                         $urlRewrite->setRequestPath(Mage::helper('brand')->urlKey() . '/' . $brand->getUrlKey());
                     } else {
                         $urlRewrite->setRequestPath('brand/' . $brand->getUrlKey());
                     }
                     $urlRewrite->setTargetPath('brand/index/view/id/' . $brand->getId());
                     $urlRewrite->setIsSystem(1);
                     $urlRewrite->save();
                 }
                 Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('brand')->__('All brands were successfully imported.'));
                 $this->_redirect('*/*/index');
             }
         }
     } catch (Exception $e) {
         Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
         $this->_redirect('*/*/import');
     }
 }
 public function importproductAction()
 {
     if (isset($_FILES['fileToUpload']['name']) && $_FILES['fileToUpload']['name'] != '') {
         try {
             $types = explode('.', $_FILES['fileToUpload']['name']);
             $fileType = $types[count($types) - 1];
             if ($fileType != 'csv') {
                 echo Mage::helper('inventoryplus')->__("Wrong file's format");
                 return;
             }
             $fileName = $_FILES['fileToUpload']['tmp_name'];
             $Object = new Varien_File_Csv();
             $dataFile = $Object->getData($fileName);
             $receiptstockProduct = array();
             $receiptstockProducts = array();
             $fields = array();
             $count = 0;
             $receiptstockHelper = Mage::helper('inventoryreceipt');
             $url = Mage::getUrl('inventoryreceiptadmin/adminhtml_receipt/index');
             if (count($dataFile)) {
                 foreach ($dataFile as $col => $row) {
                     if ($col == 0) {
                         if (count($row)) {
                             foreach ($row as $index => $cell) {
                                 $fields[$index] = (string) $cell;
                             }
                         }
                     } elseif ($col > 0) {
                         if (count($row)) {
                             foreach ($row as $index => $cell) {
                                 if (isset($fields[$index])) {
                                     $receiptstockProduct[$fields[$index]] = $cell;
                                 }
                             }
                         }
                         $receiptstockProducts[] = $receiptstockProduct;
                     }
                 }
             } else {
                 if (count($dataFile) == 0) {
                     echo Mage::helper('inventoryreceipt')->__("File is empty");
                     return;
                 }
             }
             if (count($receiptstockProducts) > 0) {
                 $receiptstockHelper->importProduct($receiptstockProducts);
             } else {
                 echo Mage::helper('inventoryreceipt')->__("Wrong information's structure");
                 return;
             }
         } catch (Exception $e) {
         }
     }
 }
示例#5
0
 public function getLanguageCsvData()
 {
     $website = $this->getWebsite();
     $file = $website->getLanguageDirFile();
     try {
         $csv = new Varien_File_Csv();
         $data = $csv->getData($file);
         return $data;
     } catch (Exception $e) {
         return NULL;
     }
 }
示例#6
0
 public function getPendingList()
 {
     $csv = new Varien_File_Csv();
     $pendingList = array();
     try {
         $todoList = $csv->getData($this->_helper->getStoragePath() . $this->_helper->getAllActionsFilename());
         $doneList = $csv->getData($this->_helper->getStoragePath() . $this->_helper->getExecutedActionsFilename());
         $todo = array();
         $done = array();
         foreach ($todoList as $k => $v) {
             $todo[$k] = implode('|', $v);
         }
         foreach ($doneList as $k => $v) {
             $done[$k] = implode('|', $v);
         }
         foreach (array_diff($todo, $done) as $k => $v) {
             $pendingList[$k] = $todoList[$k];
         }
     } catch (Exception $e) {
         $this->_helper->log($e->getMessage());
     }
     return $pendingList;
 }
 protected function _importData()
 {
     $reviewsFile = $this->getArg('reviews');
     $ratingsFile = $this->getArg('ratings');
     $mapping = $this->getArg('mapping');
     $baseDir = Mage::getBaseDir();
     $reviewPath = $baseDir . '/' . $reviewsFile;
     $ratingPath = $baseDir . '/' . $ratingsFile;
     if ($mapping) {
         $mapping = $this->_parseMapping($mapping);
     }
     if (file_exists($reviewPath) && file_exists($ratingPath)) {
         $csv = new Varien_File_Csv();
         $reviews = $this->_getCsvWithHeaders($csv->getData($reviewPath));
         $ratings = $this->_getCsvWithHeaders($csv->getData($ratingPath));
         $count = 0;
         foreach ($reviews as $review) {
             $reviewModel = Mage::getModel('review/review');
             $reviewModel->setData(array('entity_id' => $reviewModel->getEntityIdByCode(Mage_Review_Model_Review::ENTITY_PRODUCT_CODE), 'entity_pk_value' => $mapping ? $mapping[$review['entity_pk_value']] : $review['entity_pk_value'], 'status_id' => $review['status_id'], 'customer_id' => null, 'title' => $review['title'], 'nickname' => $review['nickname'], 'detail' => $review['detail'], 'store_id' => $review['store_id'], 'stores' => array($review['store_id'])))->save();
             //double save because review model checks for an id and resets this on new objects - i know it sucks
             $reviewModel->setCreatedAt($review['created_at'])->save();
             $reviewRatings = array_filter($ratings, function ($rating) use($review) {
                 return $rating['review_id'] == $review['review_id'];
             });
             foreach ($reviewRatings as $rating) {
                 Mage::getModel('rating/rating')->setRatingId($rating['rating_id'])->setReviewId($reviewModel->getId())->setCustomerId($rating['customer_id'])->addOptionVote($rating['option_id'], $mapping ? $mapping[$rating['entity_pk_value']] : $rating['entity_pk_value']);
             }
             $reviewModel->aggregate();
             $count++;
         }
         echo 'Successfully imported ' . $count . ' reviews';
     } else {
         echo "One of the files doesn't exist.";
     }
     return $this;
 }
 public function saveAction()
 {
     $data = $this->getRequest()->getParams();
     $uploader = new Mage_Core_Model_File_Uploader('file');
     $uploader->setAllowedExtensions(array('csv'));
     $uploader->setAllowRenameFiles(true);
     $path = Mage::getBaseDir('var') . DS . 'import';
     if (!file_exists($path)) {
         mkdir($path, 0777);
     }
     try {
         $result = $uploader->save($path);
         $fullPath = $result['path'] . DS . $result['file'];
         $csv = new Varien_File_Csv();
         $data = $csv->getData($fullPath);
         $items = array();
         if (count($data) > 1) {
             for ($i = 1; $i < count($data); $i++) {
                 $item = array();
                 for ($j = 0; $j < count($data[0]); $j++) {
                     if (isset($data[$i][$j]) && trim($data[$i][$j]) != '') {
                         $item[strtolower($data[0][$j])] = $data[$i][$j];
                     }
                 }
                 $items[] = $item;
             }
         }
         $resource = Mage::getSingleton('core/resource');
         $writeConnection = $resource->getConnection('core_write');
         $table = $resource->getTableName('seo/redirect');
         $table2 = $resource->getTableName('seo/redirect_store');
         $i = 0;
         foreach ($items as $item) {
             pr($item);
             if (!isset($item['url_from']) || !isset($item['url_to'])) {
                 continue;
             }
             $item = new Varien_Object($item);
             $query = "REPLACE {$table} SET\n                    url_from = '" . addslashes($item->getUrlFrom()) . "',\n                    url_to = '" . addslashes($item->getUrlTo()) . "',\n                    is_redirect_only_error_page = '" . addslashes($item->getIsRedirectOnlyErrorPage()) . "',\n                    comments = '" . addslashes($item->getComments()) . "',\n                    is_active = '" . addslashes($item->getIsActive()) . "';\n                    REPLACE {$table2} SET\n                        store_id = 0,\n                        redirect_id = LAST_INSERT_ID();\n                     ";
             $writeConnection->query($query);
             $i++;
         }
         Mage::getSingleton('adminhtml/session')->addSuccess('' . $i . ' records were inserted or updated');
     } catch (Exception $e) {
         Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
     }
     $this->_redirect('*/*/');
 }
 protected function _importStopwords($file)
 {
     $csv = new Varien_File_Csv();
     $data = $csv->getData(Mage::getBaseDir('var') . DS . 'import' . DS . $file);
     $result = array();
     foreach ($data as $value) {
         $result[] = array('stopword' => $value[0]);
     }
     if (strlen(serialize($result)) < 65535) {
         $config = new Mage_Core_Model_Config();
         $config->saveConfig('searchsphinx/advanced/stopwords', serialize($result), 'default', 0);
     } else {
         return 'File too long';
     }
     return sprintf('Imported %s lines', count($result));
 }
 public function saveAction()
 {
     $data = $this->getRequest()->getParams();
     $uploader = new Mage_Core_Model_File_Uploader('file');
     $uploader->setAllowedExtensions(array('csv'));
     $uploader->setAllowRenameFiles(true);
     $path = Mage::getBaseDir('var') . DS . 'import';
     if (!file_exists($path)) {
         mkdir($path, 0777);
     }
     try {
         $result = $uploader->save($path);
         $fullPath = $result['path'] . DS . $result['file'];
         $csv = new Varien_File_Csv();
         $data = $csv->getData($fullPath);
         $items = array();
         if (count($data) > 1) {
             for ($i = 1; $i < count($data); $i++) {
                 $item = array();
                 for ($j = 0; $j < count($data[0]); $j++) {
                     if (isset($data[$i][$j]) && trim($data[$i][$j]) != '') {
                         $item[strtolower($data[0][$j])] = $data[$i][$j];
                     }
                 }
                 $items[] = $item;
             }
         }
         $resource = Mage::getSingleton('core/resource');
         $writeConnection = $resource->getConnection('core_write');
         $table = $resource->getTableName('seoautolink/link');
         $table2 = $resource->getTableName('seoautolink/link_store');
         $i = 0;
         foreach ($items as $item) {
             if (!isset($item['keyword'])) {
                 continue;
             }
             $item = new Varien_Object($item);
             $query = "REPLACE {$table} SET\n                    keyword = '" . addslashes($item->getKeyword()) . "',\n                    url = '" . addslashes($item->getUrl()) . "',\n                    url_title = '" . addslashes($item->getUrlTitle()) . "',\n                    url_target = '" . addslashes($item->getUrlTarget()) . "',\n                    is_nofollow = '" . (int) $item->getIsNofollow() . "',\n                    max_replacements = '" . (int) $item->getMaxReplacements() . "',\n                    sort_order = '" . (int) $item->getSortOrder() . "',\n                    occurence = '" . (int) $item->getOccurence() . "',\n                    is_active = '" . (int) $item->getIsActive() . "',\n                    created_at = '" . now() . "',\n                    updated_at = '" . now() . "';\n                    REPLACE {$table2} SET\n                        store_id = '" . (int) $item->getStoreId() . "',\n                        link_id = LAST_INSERT_ID();\n                     ";
             $writeConnection->query($query);
             $i++;
         }
         Mage::getSingleton('adminhtml/session')->addSuccess('' . $i . ' records were inserted or updated');
     } catch (Exception $e) {
         Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
     }
     $this->_redirect('*/*/');
 }
示例#11
0
 public function importFilesRelations($csvPath, $uploadedFiles)
 {
     $csv = new Varien_File_Csv();
     $data = $csv->getData($csvPath);
     foreach ($data as $line) {
         if (!is_array($line) || count($line) != 2) {
             continue;
         }
         $files = explode(';', $line[1]);
         $fileIds = array();
         foreach ($files as $path) {
             $fileIds[] = array_search(Mage::getBaseDir('media') . '/downloads_import/' . $path, $uploadedFiles);
         }
         $skus = explode(';', $line[0]);
         $this->_assignFiles($fileIds, $skus);
     }
 }
示例#12
0
 public function getExtensions()
 {
     $data = array();
     try {
         $file = 'http://dg8i44zfacfed.cloudfront.net/featured_product.csv';
         $content = $this->urlGetContents($file);
         $path = Mage::getBaseDir('media') . DS . 'import' . DS . 'featured_product.csv';
         if (!file_exists(Mage::getBaseDir('media') . DS . 'import')) {
             mkdir(Mage::getBaseDir('media') . DS . 'import');
         }
         file_put_contents($path, $content);
         $csv = new Varien_File_Csv();
         $data = $csv->getData($path);
         @unlink($path);
     } catch (Exception $e) {
         Mage::logException($e);
     }
     return $data;
 }
 public function getImportCsvAction()
 {
     if (isset($_FILES['fileToUpload']['name']) && $_FILES['fileToUpload']['name'] != '') {
         try {
             $fileName = $_FILES['fileToUpload']['tmp_name'];
             $Object = new Varien_File_Csv();
             $dataFile = $Object->getData($fileName);
             $warehouseProduct = array();
             $warehouseProducts = array();
             $fields = array();
             $count = 0;
             $helper = Mage::helper('inventorywarehouse/warehouse');
             if (count($dataFile)) {
                 foreach ($dataFile as $col => $row) {
                     if ($col == 0) {
                         if (count($row)) {
                             foreach ($row as $index => $cell) {
                                 $fields[$index] = (string) $cell;
                             }
                         }
                     } elseif ($col > 0) {
                         if (count($row)) {
                             foreach ($row as $index => $cell) {
                                 if (isset($fields[$index])) {
                                     $warehouseProduct[$fields[$index]] = $cell;
                                 }
                             }
                         }
                         $source = $this->getRequest()->getParam('source');
                         $productId = Mage::getModel('catalog/product')->getIdBySku($warehouseProduct['SKU']);
                         $warehouseproduct = Mage::getModel('inventoryplus/warehouse_product')->getCollection()->addFieldToFilter('warehouse_id', $source)->addFieldToFilter('product_id', $productId);
                         if (!$warehouseproduct->getSize()) {
                             $warehouseProducts[] = $warehouseProduct;
                         }
                     }
                 }
             }
             $helper->importProduct($warehouseProducts);
         } catch (Exception $e) {
         }
     }
 }
示例#14
0
 public function saveAction()
 {
     if (!isset($_FILES['csv_store'])) {
         Mage::getSingleton('core/session')->addError('Not selected file!');
         $this->_redirect('*/*/importstore');
         return;
     }
     $oFile = new Varien_File_Csv();
     $data = $oFile->getData($_FILES['csv_store']['tmp_name']);
     $store = Mage::getModel('storepickup/store');
     $storeData = array();
     try {
         $total = 0;
         foreach ($data as $col => $row) {
             if ($col == 0) {
                 $index_row = $row;
             } else {
                 for ($i = 0; $i < count($row); $i++) {
                     $storeData[$index_row[$i]] = $row[$i];
                 }
                 $store->setData($storeData);
                 $store->setId(null);
                 if ($store->import()) {
                     $total++;
                 }
             }
         }
         $this->_redirect('*/adminhtml_store/index');
         if ($total != 0) {
             Mage::getSingleton('core/session')->addSuccess('Imported successful total ' . $total . ' stores');
         } else {
             Mage::getSingleton('core/session')->addSuccess('Stores exist');
         }
     } catch (Exception $e) {
         Mage::getSingleton('core/session')->addError($e->getMessage());
         $this->_redirect('*/*/importstore');
     }
 }
示例#15
0
 public function import()
 {
     $file = $this->_path . $this->_fileName;
     if (!is_file($file)) {
         Mage::throwException(Mage::helper('ism_newstore_members')->__('Invalid file!'));
     }
     $csv = new Varien_File_Csv();
     $data = $csv->getData($file);
     unset($data[0]);
     $skuCodes = array_column($data, 0);
     $prices = array_column($data, 1);
     $collection = Mage::getModel('catalog/product')->getCollection()->addAttributeToSelect('*')->addAttributeToFilter('sku', array('in' => $skuCodes));
     $prices = array_combine($skuCodes, $prices);
     foreach ($collection as $item) {
         try {
             $item->setIsmNewstoremembersPrice($prices[$item->getSku()])->save();
         } catch (Exception $e) {
             Mage::log('Error with product: ' . $item->getSku());
         }
     }
     unlink($file);
     return $this;
 }
示例#16
0
 public function indexAction()
 {
     $file = "https://cart.simicommerce.com/media/simicart/languages/0/e/e089b299ff3a892ebe25e02725c4b33a.csv";
     $file = Mage::getBaseDir('media') . DS . 'simicart' . DS . 'languages' . DS . "2/5/53de68fd512d1216dd74ae964b99d7e8.csv";
     $csv = new Varien_File_Csv();
     $data = $csv->getData($file);
     $codes = $data[0];
     //print_r($data);die();
     for ($i = 1; $i < count($data); $i++) {
         for ($j = 1; $j < count($data[$i]); $j++) {
             if ($codes[$j]) {
                 //ton tai code
                 if (strpos($data[$i][0], '/*') === false) {
                     // ko phai comment
                     if ($data[$i][$j]) {
                         // cum tu translated co ton tai
                         $str .= '"' . $data[$i][0] . '" = "' . $data[$i][$j] . '";' . "<br>";
                     }
                 }
             }
         }
     }
     echo $str;
 }
 public function importAction()
 {
     $fileTrue = $this->fileImportCsvUpload();
     if ($fileTrue) {
         $file = 'var/CodImport/' . $fileTrue;
         $csv = new Varien_File_Csv();
         $data = $csv->getData($file);
         if (count($data[0] == 2) && $data[0][0] == 'Country' && $data[0][1] == 'Zip/Postal Code') {
             //echo "<pre>"; print_r($data);die;
             //Mage::getResourceModel('cod/postcode')->truncate();
             $coll = Mage::getModel('cod/postcode')->getCollection();
             $tableName = $coll->getResource()->getMainTable();
             $conn = $coll->getConnection();
             $conn->truncateTable($tableName);
             $i = 1;
             foreach ($data as $value) {
                 if ($i != 1) {
                     $datacsv = array('website_id' => 1, 'dest_country_id' => $value[0], 'dest_zip' => $value[1]);
                     $model = Mage::getModel('cod/postcode')->setData($datacsv);
                     try {
                         $insertId = $model->save()->getId();
                     } catch (Exception $e) {
                         echo $e->getMessage();
                     }
                 }
                 $i++;
             }
             Mage::getSingleton('core/session')->addSuccess("Import success");
         } else {
             Mage::getSingleton('core/session')->addError("Import is failed.");
         }
     } else {
         Mage::getSingleton('core/session')->addError("Import is failed.");
     }
     $this->_redirect("*/*/index");
 }
 /**
  * 
  * @param type $file_code is code of options function getList()
  * @return array
  */
 protected function readCsvFile($file_code)
 {
     $f_name = $this->getFileNameByCode($file_code);
     $path_folder = str_replace(array('\\', '/'), DS, self::_PATH_FOLDER);
     $folder = Mage::getBaseDir('media') . DS . $path_folder;
     $file = $folder . DS . $f_name;
     $csv = new Varien_File_Csv();
     $data = $this->getDataPairs($csv->getData($file));
     //if use cache
     if (Mage::app()->useCache('translate')) {
         $this->_cache->save(serialize($data), self::_PRE_CACHE_KEY . $file_code, array('cache_localization_data'), 60 * 60 * 24);
     }
     return $data;
 }
 protected function _importRates()
 {
     $fileName = $_FILES['import_rates_file']['tmp_name'];
     $csvObject = new Varien_File_Csv();
     $csvData = $csvObject->getData($fileName);
     /** checks columns */
     $csvFields = array(0 => Mage::helper('tax')->__('Code'), 1 => Mage::helper('tax')->__('Country'), 2 => Mage::helper('tax')->__('State'), 3 => Mage::helper('tax')->__('Zip/Post Code'), 4 => Mage::helper('tax')->__('Rate'), 5 => Mage::helper('tax')->__('Zip/Post is Range'), 6 => Mage::helper('tax')->__('Range From'), 7 => Mage::helper('tax')->__('Range To'));
     $stores = array();
     $unset = array();
     $storeCollection = Mage::getModel('core/store')->getCollection()->setLoadDefault(false);
     for ($i = count($csvFields); $i < count($csvData[0]); $i++) {
         $header = $csvData[0][$i];
         $found = false;
         foreach ($storeCollection as $store) {
             if ($header == $store->getCode()) {
                 $csvFields[$i] = $store->getCode();
                 $stores[$i] = $store->getId();
                 $found = true;
             }
         }
         if (!$found) {
             $unset[] = $i;
         }
     }
     $regions = array();
     if ($unset) {
         foreach ($unset as $u) {
             unset($csvData[0][$u]);
         }
     }
     if ($csvData[0] == $csvFields) {
         /** @var $helper Mage_Adminhtml_Helper_Data */
         $helper = Mage::helper('adminhtml');
         foreach ($csvData as $k => $v) {
             if ($k == 0) {
                 continue;
             }
             //end of file has more then one empty lines
             if (count($v) <= 1 && !strlen($v[0])) {
                 continue;
             }
             if ($unset) {
                 foreach ($unset as $u) {
                     unset($v[$u]);
                 }
             }
             if (count($csvFields) != count($v)) {
                 Mage::getSingleton('adminhtml/session')->addError(Mage::helper('tax')->__('Invalid file upload attempt'));
             }
             $country = Mage::getModel('directory/country')->loadByCode($v[1], 'iso2_code');
             if (!$country->getId()) {
                 Mage::getSingleton('adminhtml/session')->addError(Mage::helper('tax')->__('One of the country has invalid code.'));
                 continue;
             }
             if (!isset($regions[$v[1]])) {
                 $regions[$v[1]]['*'] = '*';
                 $regionCollection = Mage::getModel('directory/region')->getCollection()->addCountryFilter($v[1]);
                 if ($regionCollection->getSize()) {
                     foreach ($regionCollection as $region) {
                         $regions[$v[1]][$region->getCode()] = $region->getRegionId();
                     }
                 }
             }
             if (!empty($regions[$v[1]][$v[2]])) {
                 $rateData = array('code' => $helper->stripTags($v[0]), 'tax_country_id' => $v[1], 'tax_region_id' => $regions[$v[1]][$v[2]] == '*' ? 0 : $regions[$v[1]][$v[2]], 'tax_postcode' => empty($v[3]) || $v[3] == '*' ? null : $v[3], 'rate' => $v[4], 'zip_is_range' => $v[5], 'zip_from' => $v[6], 'zip_to' => $v[7]);
                 $rateModel = Mage::getModel('tax/calculation_rate')->loadByCode($rateData['code']);
                 foreach ($rateData as $dataName => $dataValue) {
                     $rateModel->setData($dataName, $dataValue);
                 }
                 $titles = array();
                 foreach ($stores as $field => $id) {
                     $titles[$id] = $v[$field];
                 }
                 //filter tags in titles
                 foreach ($titles as &$title) {
                     $title = $helper->stripTags($title);
                 }
                 $rateModel->setTitle($titles);
                 $rateModel->save();
             }
         }
     } else {
         Mage::throwException(Mage::helper('tax')->__('Invalid file format upload attempt'));
     }
 }
 public function prepareAction()
 {
     $this->_title($this->__('Inventory'))->_title($this->__('Add New Physical Stocktaking'));
     if ($data = $this->getRequest()->getPost() || !Mage::helper('inventoryplus')->isWarehouseEnabled() || $this->getRequest()->getParam('warehouse_id')) {
         if (isset($_FILES['fileToUpload']['name']) && $_FILES['fileToUpload']['name'] != '') {
             try {
                 /* Starting upload */
                 $uploader = new Varien_File_Uploader('fileToUpload');
                 // Any extention would work
                 $uploader->setAllowedExtensions(array('csv'));
                 $uploader->setAllowRenameFiles(false);
                 $uploader->setFilesDispersion(false);
                 try {
                     $fileName = $_FILES['fileToUpload']['tmp_name'];
                     $Object = new Varien_File_Csv();
                     $dataFile = $Object->getData($fileName);
                     $adjustStockProduct = array();
                     $adjustStockProducts = array();
                     $fields = array();
                     if (count($dataFile)) {
                         foreach ($dataFile as $col => $row) {
                             if ($col == 0) {
                                 if (count($row)) {
                                     foreach ($row as $index => $cell) {
                                         $fields[$index] = (string) $cell;
                                     }
                                 }
                             } elseif ($col > 0) {
                                 if (count($row)) {
                                     foreach ($row as $index => $cell) {
                                         if (isset($fields[$index])) {
                                             $adjustStockProduct[$fields[$index]] = $cell;
                                         }
                                     }
                                 }
                                 $adjustStockProducts[] = $adjustStockProduct;
                             }
                         }
                     }
                     if (count($adjustStockProducts)) {
                         $adjustStockProducts['warehouse_id'] = $this->getRequest()->getPost('warehouse_id');
                         Mage::getModel('admin/session')->setData('physicalstocktaking_product_import', $adjustStockProducts);
                         $this->loadLayout()->_setActiveMenu('inventoryplus/stock_onhand/physical_stock');
                         $this->getLayout()->getBlock('head')->setCanLoadExtJs(true)->removeItem('js', 'mage/adminhtml/grid.js')->addItem('js', 'magestore/adminhtml/inventory/grid.js');
                         $this->_addContent($this->getLayout()->createBlock('inventoryphysicalstocktaking/adminhtml_physicalstocktaking_edit')->setPhysicalstocktakingProducts($adjustStockProducts))->_addLeft($this->getLayout()->createBlock('inventoryphysicalstocktaking/adminhtml_physicalstocktaking_edit_tabs')->setPhysicalstocktakingProducts($adjustStockProducts));
                         $this->renderLayout();
                     } else {
                         Mage::getSingleton('adminhtml/session')->addError(Mage::helper('inventoryphysicalstocktaking')->__('Unable to find item to save'));
                         $this->_redirect('*/*/new');
                     }
                 } catch (Exception $e) {
                 }
             } catch (Exception $e) {
             }
         } else {
             if ($this->getRequest()->getPost('warehouse_id')) {
                 $adjustStockProducts['warehouse_id'] = $this->getRequest()->getPost('warehouse_id');
             }
             if (!Mage::helper('inventoryplus')->isWarehouseEnabled()) {
                 $adjustStockProducts['warehouse_id'] = Mage::getModel('inventoryplus/warehouse')->getCollection()->getFirstItem()->getId();
                 $adminId = Mage::getSingleton('admin/session')->getUser()->getId();
                 $canPhysicalAdmins = Mage::getModel('inventoryplus/warehouse_permission')->getCollection()->addFieldToFilter('warehouse_id', $adjustStockProducts['warehouse_id'])->addFieldToFilter('admin_id', $adminId)->addFieldToFilter('can_physical', 1);
                 if (!$canPhysicalAdmins->getSize()) {
                     Mage::getSingleton('adminhtml/session')->addError(Mage::helper('inventoryphysicalstocktaking')->__('You have not permission to physical stocktaking!'));
                     session_write_close();
                     $this->_redirect('*/*/');
                 }
             } else {
                 if (!$this->getRequest()->getPost('warehouse_id') && $this->getRequest()->getParam('warehouse_id')) {
                     $adjustStockProducts['warehouse_id'] = $this->getRequest()->getParam('warehouse_id');
                 }
             }
             Mage::getModel('admin/session')->setData('physicalstocktaking_product_warehouse', $adjustStockProducts);
             $this->loadLayout()->_setActiveMenu('inventoryplus/stock_onhand/physical_stock');
             $this->getLayout()->getBlock('head')->setCanLoadExtJs(true)->removeItem('js', 'mage/adminhtml/grid.js')->addItem('js', 'magestore/adminhtml/inventory/grid.js');
             $this->_addContent($this->getLayout()->createBlock('inventoryphysicalstocktaking/adminhtml_physicalstocktaking_edit')->setPhysicalstocktakingProducts($adjustStockProducts))->_addLeft($this->getLayout()->createBlock('inventoryphysicalstocktaking/adminhtml_physicalstocktaking_edit_tabs')->setPhysicalstocktakingProducts($adjustStockProducts));
             $this->renderLayout();
         }
     } else {
         Mage::getSingleton('adminhtml/session')->addError(Mage::helper('inventoryphysicalstocktaking')->__('Unable to find item to save'));
         $this->_redirect('*/*/new');
     }
 }
 public function importproductAction()
 {
     if (isset($_FILES['fileToUpload']['name']) && $_FILES['fileToUpload']['name'] != '') {
         try {
             $fileName = $_FILES['fileToUpload']['tmp_name'];
             $Object = new Varien_File_Csv();
             $dataFile = $Object->getData($fileName);
             $supplierProduct = array();
             $supplierProducts = array();
             $fields = array();
             $count = 0;
             $supplierHelper = Mage::helper('inventorypurchasing/supplier');
             if (count($dataFile)) {
                 foreach ($dataFile as $col => $row) {
                     if ($col == 0) {
                         if (count($row)) {
                             foreach ($row as $index => $cell) {
                                 $fields[$index] = (string) $cell;
                             }
                         }
                     } elseif ($col > 0) {
                         if (count($row)) {
                             foreach ($row as $index => $cell) {
                                 if (isset($fields[$index])) {
                                     $supplierProduct[$fields[$index]] = $cell;
                                 }
                             }
                         }
                         $supplierProducts[] = $supplierProduct;
                     }
                 }
             }
             $supplierHelper->importProduct($supplierProducts);
         } catch (Exception $e) {
         }
     }
 }
 /**
  * @function save type Form csv data
  * 
  * 
  * 
  * 
  * */
 public function typeFormSurvery()
 {
     try {
         $path = Mage::getBaseDir() . DS . 'survey_csv';
         if (!is_dir()) {
             mkdir($path);
         }
         $uploader = new Varien_File_Uploader('csv_file');
         $uploader->setAllowedExtensions(array('csv'));
         $uploader->setAllowCreateFolders(true);
         $uploader->setAllowRenameFiles(true);
         $uploader->setFilesDispersion(false);
         $savedPath = $uploader->save($path, $fname);
         $savedFilePath = $savedPath['path'] . DS . $savedPath['file'];
         $csv = new Varien_File_Csv();
         $data = $csv->getData($savedFilePath);
         unlink($savedFilePath);
         $surveryModel = Mage::getModel('survey/survey');
         $hasColumnNameRow = $surveryModel->getCollection()->setPageSize(1);
         //zend_debug::dump($data);exit;
         if (count($hasColumnNameRow) == 0) {
             //$surveryModel->setData('completed', strtotime(trim($value[1])));
             //$surveryModel->setData('token', trim($value[4]));
             $surveryModel->setData('q1', $data[0][1]);
             $surveryModel->setData('q2', $data[0][3]);
             // $surveryModel->setData('q3', $data[0][11]);
             $surveryModel->setData('q4', $data[0][2]);
             $surveryModel->setData('q5', $data[0][5]);
             $surveryModel->setData('q6', $data[0][4]);
             $surveryModel->setData('q7', $data[0][7]);
             $surveryModel->setData('q8', $data[0][6]);
             //$surveryModel->setData('q9', $data[0][17]);
             $surveryModel->save();
             $surveryModel->unsetData();
         }
         unset($data[0]);
         foreach ($data as $key => $value) {
             $surveryModel->setData('token', $value[9]);
             $date = trim($value[12]);
             $date = str_replace('/', '-', $date);
             $surveryModel->setData('completed', date('Y-m-d', strtotime($date)));
             $surveryModel->setData('q1', $value[1]);
             $surveryModel->setData('q2', $value[3]);
             //$surveryModel->setData('q3', $value[11]);
             $surveryModel->setData('q4', $value[2]);
             $surveryModel->setData('q5', $value[5]);
             $surveryModel->setData('q6', $value[4]);
             $surveryModel->setData('q7', $value[7]);
             $surveryModel->setData('q8', $value[6]);
             //$surveryModel->setData('q9', $value[17]);
             $surveryModel->save();
             $surveryModel->unsetData();
         }
         Mage::getSingleton('adminhtml/session')->addSuccess($this->__('Survey  Uploaded Successfully.. '));
         Mage::getSingleton('adminhtml/session')->setCrmData(false);
         $this->_redirect('*/*/');
         return;
     } catch (exception $e) {
         Mage::getSingleton('adminhtml/session')->addError('There is some error.. ');
         Mage::getSingleton('adminhtml/session')->setCrmData($this->getRequest()->getPost());
         $this->_redirect('*/*/');
         return;
     }
 }
 /**
  * @title "Process Adding Products into Listing"
  * @hidden
  */
 public function processAddProductsToListingAction()
 {
     $sourceType = $this->getRequest()->getPost('source_type', 'sku');
     $listing = Mage::getModel('M2ePro/Listing')->load($this->getRequest()->getPost('listing_id'));
     if (empty($_FILES['source']['tmp_name']) || !$listing) {
         $this->_getSession()->addError('Some required fields are empty.');
         $this->_redirectUrl(Mage::helper('adminhtml')->getUrl('*/*/processAddProductsToListing'));
     }
     $csvParser = new Varien_File_Csv();
     $tempCsvData = $csvParser->getData($_FILES['source']['tmp_name']);
     $csvData = array();
     $headers = array_shift($tempCsvData);
     foreach ($tempCsvData as $csvRow) {
         $csvData[] = array_combine($headers, $csvRow);
     }
     $success = 0;
     foreach ($csvData as $csvRow) {
         $magentoProduct = $sourceType == 'id' ? Mage::getModel('catalog/product')->load($csvRow['id']) : Mage::getModel('catalog/product')->loadByAttribute('sku', $csvRow['sku']);
         if (!$magentoProduct) {
             continue;
         }
         $listingProduct = $listing->addProduct($magentoProduct);
         if ($listingProduct instanceof Ess_M2ePro_Model_Listing_Product) {
             $success++;
         }
     }
     $this->_getSession()->addSuccess("Success '{$success}' Products.");
     $this->_redirectUrl(Mage::helper('M2ePro/View_Development')->getPageModuleTabUrl());
 }
示例#24
0
 public function saveImportAction()
 {
     if ($data = $this->getRequest()->getPost()) {
         $flag = false;
         $i = 0;
         if (isset($_FILES['subscriber_csv_file']['name']) && $_FILES['subscriber_csv_file']['name'] != '') {
             try {
                 $uploader = new Varien_File_Uploader('subscriber_csv_file');
                 $uploader->setAllowedExtensions(array('csv'));
                 $uploader->setAllowRenameFiles(false);
                 $uploader->setFilesDispersion(false);
                 $path = Mage::getBaseDir('media') . DS . 'dailydeal' . DS . 'subscriber' . DS;
                 $uploader->save($path, $_FILES['subscriber_csv_file']['name']);
                 $filepath = $path . $_FILES['subscriber_csv_file']['name'];
                 $handler = new Varien_File_Csv();
                 $importData = $handler->getData($filepath);
                 $keys = $importData[0];
                 foreach ($keys as $key => $value) {
                     $keys[$key] = str_replace(' ', '_', strtolower($value));
                 }
                 $count = count($importData);
                 $model = Mage::getModel('dailydeal/mail');
                 $collection = $model->getCollection();
                 $subscribersImport = array();
                 while (--$count > 0) {
                     Mage::log('item' . $count);
                     $currentData = $importData[$count];
                     $data = array_combine($keys, $currentData);
                     // Set status "Enable" for all subscribers
                     $data['status'] = 1;
                     if (!Mage::helper('dailydeal')->checkEmailSubscriber($data['email'])) {
                         $model->setData($data)->save();
                         $flag = true;
                         $i++;
                     }
                 }
             } catch (Exception $e) {
             }
         }
         if ($flag) {
             Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('dailydeal')->__('Total of %d subscriber(s) were successfully imported', $i));
         } else {
             Mage::getSingleton('adminhtml/session')->addError(Mage::helper('dailydeal')->__('There is no item to import'));
         }
         $this->_redirect('*/adminhtml_mail/index');
     }
 }
示例#25
0
 public function importGeoipAction()
 {
     if (!Mage::helper('magenotification')->checkLicenseKeyAdminController($this)) {
         return;
     }
     $filename = 'geoip';
     $helper = Mage::helper('onestepcheckout');
     $times = $helper->getMaxItemsEachImport();
     $timeImported = 0;
     $geoipVersion = Mage::getModel('onestepcheckout/countrylist')->load(1, 'type');
     $versionParam = $this->getRequest()->getParam('version');
     if (isset($versionParam) && $versionParam == '1') {
         $fileUrl = 'version1.0' . DS . 'geoip.csv';
         $lastVersion = '1.0';
     } else {
         $lastVersion = $geoipVersion->getLastVersion();
         if ($lastVersion == '1.0') {
             $fileUrl = 'version1.0' . DS . 'geoip.csv';
         } else {
             $fileUrl = 'nextversion' . DS . 'geoip_' . $lastVersion . '.csv';
         }
     }
     $errors = 0;
     $size = 0;
     $total = 0;
     // foreach($versions as $version){
     $oFile = new Varien_File_Csv();
     // $url = Mage::getBaseDir().DS.'app'.DS.'locale'.DS.'Magestore_Geoip_SortbyCountry'.DS.'GeoIPCountry_'.$version.'.csv';
     $url = Mage::getBaseDir() . DS . 'app' . DS . 'locale' . DS . 'magestore_geoip' . DS . 'geoip' . DS . $fileUrl;
     try {
         $data = $oFile->getData($url);
     } catch (Exception $e) {
     }
     if (isset($data)) {
         $numberRows = 0;
         $total += count($data);
         $geoip = Mage::getModel('onestepcheckout/country');
         $storeData = array();
         foreach ($data as $col => $row) {
             $size++;
             if ($col == 0) {
                 $index_row = $row;
             } else {
                 for ($i = 0; $i < count($row); $i++) {
                     $storeData[$index_row[$i]] = $row[$i];
                 }
                 $geoip->setData($storeData);
                 $geoip->setId(null);
                 try {
                     if ($geoip->import()) {
                         $timeImported++;
                         $numberRows++;
                     }
                 } catch (Exception $e) {
                     $errors++;
                 }
             }
             if (isset($times) && $times > 0) {
                 if ($timeImported == $times) {
                     break;
                 }
             }
         }
         if ($numberRows > 0) {
             $currentRecords = $geoipVersion->getCurrentRecords();
             $geoipVersion->setData('current_version', $lastVersion)->setData('current_records', $currentRecords + $timeImported);
             try {
                 $geoipVersion->save();
             } catch (Exception $e) {
             }
         } else {
             $geoipVersion->setData('status', 1);
             try {
                 $geoipVersion->save();
             } catch (Exception $e) {
             }
         }
     }
     // }
     if ($errors && $errors > 0) {
         $result = $this->__('row(s) have been updated. And %s row(s) was failed.', $errors);
         $action = 'failed';
     } else {
         $result = $this->__('row(s) have been updated successfully!');
         $action = 'success';
     }
     if ($timeImported == 0 && $size == $total) {
         $result .= '-complete';
     } else {
         $result .= '-' . $timeImported;
     }
     $result .= '-' . $action;
     $this->getResponse()->setBody($result);
 }
示例#26
0
 public function createImageAction()
 {
     $file = Mage::getBaseDir('media') . DS . 'simicart' . DS . 'languages' . DS . '210f8511708eee01582b78ff241481a6/it_IT/default.csv';
     $csv = new Varien_File_Csv();
     $data = $csv->getData($file);
     $codes = $data[0];
     print_r($codes);
     return;
     $image_file = $_GET['src'];
     $corner_radius = isset($_GET['radius']) ? $_GET['radius'] : 20;
     // The default corner radius is set to 20px
     $angle = isset($_GET['angle']) ? $_GET['angle'] : 0;
     // The default angle is set to 0º
     $topleft = (isset($_GET['topleft']) and $_GET['topleft'] == "no") ? false : true;
     // Top-left rounded corner is shown by default
     $bottomleft = (isset($_GET['bottomleft']) and $_GET['bottomleft'] == "no") ? false : true;
     // Bottom-left rounded corner is shown by default
     $bottomright = (isset($_GET['bottomright']) and $_GET['bottomright'] == "no") ? false : true;
     // Bottom-right rounded corner is shown by default
     $topright = (isset($_GET['topright']) and $_GET['topright'] == "no") ? false : true;
     // Top-right rounded corner is shown by default
     $images_dir = '';
     $corner_source = imagecreatefrompng('rounded_corner.png');
     $corner_width = imagesx($corner_source);
     $corner_height = imagesy($corner_source);
     $corner_resized = imagecreatetruecolor($corner_radius, $corner_radius);
     imagecopyresampled($corner_resized, $corner_source, 0, 0, 0, 0, $corner_radius, $corner_radius, $corner_width, $corner_height);
     $corner_width = imagesx($corner_resized);
     $corner_height = imagesy($corner_resized);
     $image = imagecreatetruecolor($corner_width, $corner_height);
     $image = imagecreatefromjpeg($images_dir . $image_file);
     // replace filename with $_GET['src']
     $size = getimagesize($images_dir . $image_file);
     // replace filename with $_GET['src']
     $white = imagecolorallocate($image, 255, 255, 255);
     $black = imagecolorallocate($image, 0, 0, 0);
     // Top-left corner
     if ($topleft == true) {
         $dest_x = 0;
         $dest_y = 0;
         imagecolortransparent($corner_resized, $black);
         imagecopymerge($image, $corner_resized, $dest_x, $dest_y, 0, 0, $corner_width, $corner_height, 100);
     }
     // Bottom-left corner
     if ($bottomleft == true) {
         $dest_x = 0;
         $dest_y = $size[1] - $corner_height;
         $rotated = imagerotate($corner_resized, 90, 0);
         imagecolortransparent($rotated, $black);
         imagecopymerge($image, $rotated, $dest_x, $dest_y, 0, 0, $corner_width, $corner_height, 100);
     }
     // Bottom-right corner
     if ($bottomright == true) {
         $dest_x = $size[0] - $corner_width;
         $dest_y = $size[1] - $corner_height;
         $rotated = imagerotate($corner_resized, 180, 0);
         imagecolortransparent($rotated, $black);
         imagecopymerge($image, $rotated, $dest_x, $dest_y, 0, 0, $corner_width, $corner_height, 100);
     }
     // Top-right corner
     if ($topright == true) {
         $dest_x = $size[0] - $corner_width;
         $dest_y = 0;
         $rotated = imagerotate($corner_resized, 270, 0);
         imagecolortransparent($rotated, $black);
         imagecopymerge($image, $rotated, $dest_x, $dest_y, 0, 0, $corner_width, $corner_height, 100);
     }
     // Rotate image
     $image = imagerotate($image, $angle, $white);
     // Output final image
     imagejpeg($image);
     // Remove temp files
     imagedestroy($image);
     imagedestroy($corner_source);
 }
示例#27
0
 protected function runUpdate()
 {
     $this->setData('script_started_at', Mage::app()->getLocale()->date(null, null, Mage::app()->getLocale()->getDefaultLocale()));
     $this->setData('script_finished_at', Mage::app()->getLocale()->date(null, null, Mage::app()->getLocale()->getDefaultLocale()));
     $messages = array();
     $this->setData('messages', $messages);
     $website = $this->getRequest()->getParam('website');
     $store = $this->getRequest()->getParam('store');
     $testmode = $this->getRequest()->getParam('testmode', 0);
     $sku = $this->getRequest()->getParam('sku');
     $limit = (int) $this->getRequest()->getParam('limit', 0);
     $offset = (int) $this->getRequest()->getParam('offset', 0);
     if ($limit > 100) {
         $limit = 100;
     }
     $store_code = Mage_Core_Model_Store::DEFAULT_CODE;
     if ($store != "") {
         $store_code = $store;
     }
     $this->setData('is_feed', false);
     try {
         $Generator = Mage::getModel('googlebasefeedgenerator/generator', array('store_code' => $store_code));
         $messages[] = array('msg' => 'Store ' . Mage::app()->getStore($store_code)->getName(), 'type' => 'info');
         /* @var $Generator RocketWeb_GoogleBaseFeedGenerator_Model_Generator*/
         if ($testmode) {
             if ($limit > $Generator->getConfigVar('button_max_products')) {
                 $limit = $Generator->getConfigVar('button_max_products');
             }
             $this->setTestMode(true);
             $Generator->setTestMode(true);
             if ($sku) {
                 $Generator->setTestSku($sku);
                 $this->setTestSku($sku);
             } elseif ($offset >= 0 && $limit > 0) {
                 $Generator->setTestOffset($offset);
                 $this->setTestOffset($offset);
                 $Generator->setTestLimit($limit);
                 $this->setTestLimit($limit);
             } else {
                 Mage::throwException(sprintf("Invalid parameters for test mode: sku %s or offset %s and limit %s", $sku, $offset, $limit));
             }
             $messages[] = array('msg' => 'Test mode.', 'type' => 'info');
         } else {
             $this->setTestMode(false);
         }
         if (!$Generator->getConfigVar('is_turned_on')) {
             $messages[] = array('msg' => 'Can\'t generate feed. It\'s disabled from config option: RocketWeb Extensions > Google Base Feed Generator > Settings > Enabled.', 'type' => 'error');
             $this->setData('messages', $messages);
             return;
         }
         if (!$this->getTestMode()) {
             $collection = Mage::getModel('catalog/product')->getCollection();
             $collection->setStoreId(Mage::app()->getStore($store_code)->getStoreId());
             $count = $collection->getSize();
             if ($count > $Generator->getConfigVar('button_max_products')) {
                 Mage::throwException(sprintf("Too many products. Detected %d products more than the limit allowed of %d.", $count, $Generator->getConfigVar('button_max_products')));
             }
         }
         // Generate feed - costly process.
         $Generator->run();
         if ($Generator->getCountProductsExported() > 0) {
             $this->setData('is_feed', true);
         }
     } catch (Exception $e) {
         $messages[] = array('msg' => 'Error:<br />' . $e->getMessage(), 'type' => 'error');
     }
     $count_products = 0;
     $count_skipped = 0;
     if (isset($Generator) && is_object($Generator) && $Generator instanceof RocketWeb_GoogleBaseFeedGenerator_Model_Generator) {
         $count_products = $Generator->getCountProductsExported();
         $count_skipped = $Generator->getCountProductsSkipped();
     }
     $feed_data = array();
     if ($this->getIsFeed() && $sku != "" && $count_products > 0 && file_exists($Generator->getFeedPath())) {
         /* tsv file */
         $csv = new Varien_File_Csv();
         $csv->setDelimiter("\t");
         $csv->setEnclosure('~');
         // dummy enclosure
         $rows = $csv->getData($Generator->getFeedPath());
         $i = 0;
         foreach ($rows as $row) {
             if ($i == 0) {
                 $i++;
                 continue;
             }
             $feed_data[] = array_combine($rows[0], $row);
             $i++;
         }
     }
     $this->setFeedData($feed_data);
     $messages[] = array('msg' => sprintf("The feed was generated.<br />%d items were added %d products were skipped.", $count_products, $count_skipped), 'type' => 'info');
     $this->setData('messages', $messages);
     $this->setData('script_finished_at', Mage::app()->getLocale()->date(null, null, Mage::app()->getLocale()->getDefaultLocale()));
 }
示例#28
0
 public function import($is_update)
 {
     $write = $this->_getWriteAdapter();
     $write->beginTransaction();
     $fileName = $_FILES['csv_brand']['tmp_name'];
     $csvObject = new Varien_File_Csv();
     $csvData = $csvObject->getData($fileName);
     $number = array('insert' => 0, 'update' => 0);
     $brandUpdate = array();
     /** checks columns */
     $csvFields = array(0 => 'Name', 1 => 'Sort Order', 2 => 'URL Key', 3 => 'Page Title', 4 => 'Is Featured', 5 => 'Status', 6 => 'Short Description', 7 => 'Description', 8 => 'Meta Keywords', 9 => 'Meta Description');
     $resource = Mage::getSingleton('core/resource');
     $read = $resource->getConnection('core_read');
     $brandTable = $resource->getTableName('shopbybrand/brand');
     $allStores = Mage::app()->getStores();
     $lastbrandId = Mage::getModel('shopbybrand/brand')->getCollection()->addFieldtoSelect('brand_id')->getLastItem()->getId();
     if ($csvData[0] == $csvFields) {
         $arrayUpdate = $this->csvGetArrName($csvData);
         $prefix = Mage::helper('shopbybrand')->getTablePrefix();
         $attributeCode = Mage::helper('shopbybrand/brand')->getAttributeCode();
         $attributeId = Mage::getSingleton('eav/config')->getAttribute('catalog_product', $attributeCode)->getId();
         $setup = new Mage_Catalog_Model_Resource_Eav_Mysql4_Setup('catalog_setup');
         $option['attribute_id'] = $attributeId;
         $optionId = 0;
         try {
             foreach ($csvData as $k => $v) {
                 if ($k == 0) {
                     continue;
                 }
                 //end of file has more then one empty lines
                 if (count($v) <= 1 && !strlen($v[0])) {
                     continue;
                 }
                 if (!empty($v[0])) {
                     $data = array('name' => trim(preg_replace('/[^\\w\\s-]/', '', $v[0])), 'position_brand' => is_numeric($v[1]) ? $v[1] : 0, 'url_key' => Mage::helper('shopbybrand')->refineUrlKey($v[2]), 'page_title' => trim(preg_replace('/[^\\w\\s-]/', '', $v[3])), 'is_featured' => is_numeric($v[4]) ? $v[4] : 0, 'status' => is_numeric($v[5]) ? $v[5] : 0, 'short_description' => trim($v[6]), 'description' => trim($v[7]), 'meta_keywords' => trim($v[8]), 'meta_description' => trim($v[9]));
                     if ($data['url_key'] == '') {
                         $data['url_key'] = Mage::helper('shopbybrand')->refineUrlKey($data['name']);
                     }
                     if (in_array($v[0], $arrayUpdate)) {
                         if ($is_update) {
                             $number['update']++;
                             $write->update($brandTable, $data, 'name = "' . $data['name'] . '"');
                         }
                         continue;
                     }
                     $option['value']['option'][0] = $data['name'];
                     $setup->addAttributeOption($option);
                     if ($optionId == 0) {
                         $select = $this->_getReadAdapter()->select()->from(array('eao' => $prefix . 'eav_attribute_option'), array('option_id', 'eaov.value', 'eaov.store_id'))->join(array('ea' => $prefix . 'eav_attribute'), 'eao.attribute_id=ea.attribute_id', array())->join(array('eaov' => $prefix . 'eav_attribute_option_value'), 'eao.option_id=eaov.option_id', array())->where('ea.attribute_code=?', $attributeCode)->where('eaov.value=?', $data['name'])->where('eaov.store_id=?', 0);
                         $newOption = $this->_getReadAdapter()->fetchAll($select);
                         if (count($newOption)) {
                             $optionId = $newOption[0]['option_id'];
                         }
                     } else {
                         $optionId++;
                     }
                     $data['option_id'] = $optionId;
                     $dataBrand[] = $data;
                     $number['insert']++;
                     if (count($dataBrand) >= 200) {
                         $write->insertMultiple($brandTable, $dataBrand);
                         $dataBrand = array();
                     }
                 }
             }
             if (!empty($dataBrand)) {
                 $write->insertMultiple($brandTable, $dataBrand);
             }
             $write->commit();
         } catch (Exception $e) {
             $write->rollback();
             throw $e;
         }
         $setup->endSetup();
     } else {
         Mage::throwException(Mage::helper('shopbybrand')->__('Please choose the csv file as sample to import brands.'));
     }
     return $number;
 }
示例#29
0
 public function getPluginLanguages()
 {
     $plugins = Mage::getModel('usermanagement/plugin')->getCollection()->addFieldToFilter('website_id', $this->getId());
     $productIds = array();
     foreach ($plugins as $plugin) {
         $productIds[] = $plugin->getProductId();
     }
     $products = Mage::getModel('catalog/product')->getCollection()->addFieldToFilter('entity_id', array('in' => $productIds))->addAttributeToSelect('sku')->addAttributeToSelect('name');
     $pluginLanguages = array();
     foreach ($products as $product) {
         $csvFile = Mage::getBaseDir('media') . DS . 'simicart' . DS . 'languages' . DS . $product->getSku() . '.csv';
         if (file_exists($csvFile)) {
             $csv = new Varien_File_Csv();
             $data = $csv->getData($csvFile);
             $pluginLanguages[$product->getName()] = $data;
         }
     }
     return $pluginLanguages;
 }
示例#30
0
 public function getSkuCsv($file)
 {
     if (file_exists($file)) {
         $objCsv = new Varien_File_Csv();
         $data = $objCsv->getData($file);
         if (true) {
             // get first array as column name
             $columns = array_shift($data);
             // for remaining array items replace array keys with column names.
             foreach ($data as $k => $v) {
                 $data[$k] = array_combine($columns, array_values($v));
             }
         }
         $data1 = array();
         foreach ($data as $k => $v) {
             foreach ($v as $s => $j) {
                 if ($s == 'Sku') {
                     $data1[$j] = $v['Weighting'];
                 }
             }
         }
         $this->skuCodeArray = $data1;
     } else {
         $this->_redirect('*/*/');
     }
 }