Пример #1
0
 protected function _generateStoreCss($x0b, $x0d)
 {
     if (!Mage::app()->getStore($x0d)->getIsActive()) {
         return;
     }
     $x11 = '_' . $x0d;
     $x12 = $x0b . $x11 . '.css';
     $x13 = Mage::helper('ultimo/cssgen')->getGeneratedCssDir() . $x12;
     $x14 = Mage::helper('ultimo/cssgen')->getTemplatePath() . $x0b . '.phtml';
     Mage::register('cssgen_store', $x0d);
     try {
         $x15 = Mage::app()->getLayout()->createBlock("core/template")->setData('area', 'frontend')->setTemplate($x14)->toHtml();
         if (empty($x15)) {
             throw new Exception(Mage::helper('ultimo')->__("Template file is empty or doesn't exist: %s", $x14));
         }
         $x16 = new Varien_Io_File();
         $x16->setAllowCreateFolders(true);
         $x16->open(array('path' => Mage::helper('ultimo/cssgen')->getGeneratedCssDir()));
         $x16->streamOpen($x13, 'w+', 0777);
         $x16->streamLock(true);
         $x16->streamWrite($x15);
         $x16->streamUnlock();
         $x16->streamClose();
     } catch (Exception $x17) {
         Mage::getSingleton('adminhtml/session')->addError(Mage::helper('ultimo')->__('Failed generating CSS file: %s in %s', $x12, Mage::helper('ultimo/cssgen')->getGeneratedCssDir()) . '<br/>Message: ' . $x17->getMessage());
         Mage::logException($x17);
     }
     Mage::unregister('cssgen_store');
 }
Пример #2
0
 public function getFile($downloadName)
 {
     Varien_Profiler::start('cdn_download_file_' . $downloadName);
     $adapter = $this->getAdapter();
     if ($adapter) {
         $fileName = Mage::helper('mycdn')->getRelativeFile($downloadName);
         $image = $adapter->downloadFile($fileName);
         if ($image) {
             $bn = new Zend_Filter_BaseName();
             $image_name = $bn->filter($downloadName);
             $dn = new Zend_Filter_Dir();
             $image_path = $dn->filter($downloadName);
             $file = new Varien_Io_File();
             $file->setAllowCreateFolders(true);
             $file->open(['path' => $image_path]);
             $file->streamOpen($image_name);
             $file->streamLock(true);
             $file->streamWrite($image);
             $file->streamUnlock();
             $file->streamClose();
             Mage::helper('mycdn')->addLog('[DOWNLOADED] File downloaded to ' . $downloadName);
             Varien_Profiler::stop('cdn_download_file_' . $downloadName);
             //saving to cache
             Mage::helper('mycdn')->savePathInCache($fileName, $this->getUrl($fileName));
             return true;
         } else {
             Mage::helper('mycdn')->addLog('[NOT DOWNLOADED] File not downloaded to ' . $downloadName);
         }
     }
     Varien_Profiler::stop('cdn_download_file_' . $downloadName);
     return false;
 }
Пример #3
0
 private function _printList($cards, $path)
 {
     try {
         $io = new Varien_Io_File();
         $fullPath = Mage::getBaseDir() . $path;
         $parts = pathinfo($fullPath);
         if (!isset($parts['extension']) || strtolower($parts['extension']) != 'csv') {
             Mage::throwException('Error in file extension. Only *.csv files are supported');
         }
         $delimiter = ';';
         $enclosure = '"';
         $io->open(array('path' => $parts['dirname']));
         $io->streamOpen($fullPath, 'w+');
         $io->streamLock(true);
         $header = array('card_id' => 'Gift Card Code', 'amount' => 'Card Amount');
         $io->streamWriteCsv($header, $delimiter, $enclosure);
         $content = array();
         foreach ($cards as $card) {
             $content['card_id'] = $card['code'];
             $content['amount'] = $card['amount'];
             $io->streamWriteCsv($content, $delimiter, $enclosure);
         }
         $io->streamUnlock();
         $io->streamClose();
         $list = Mage::getModel('giftcards/cardslist')->load($fullPath, 'file_path');
         $list->setFilePath($fullPath)->save();
     } catch (Mage_Core_Exception $e) {
         Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
     } catch (Exception $e) {
         Mage::getSingleton('adminhtml/session')->addError(Mage::helper('giftcards')->__('An error occurred while save cards list.'));
     }
 }
Пример #4
0
 protected function generateStoreCss($type, $storeCode)
 {
     if (!Mage::app()->getStore($storeCode)->getIsActive()) {
         return;
     }
     $str1 = '_' . $storeCode;
     $str2 = $type . $str1 . '.css';
     $str3 = Mage::helper('mango/cssconfig')->getCssConfigDir() . $str2;
     $str4 = 'mango/css/' . $type . '.phtml';
     Mage::register('cssgen_store', $storeCode);
     try {
         $block = Mage::app()->getLayout()->createBlock("core/template")->setData('area', 'frontend')->setTemplate($str4)->toHtml();
         if (empty($block)) {
             throw new Exception(Mage::helper('mango')->__("Template file is empty or doesn't exist: %s", $str4));
         }
         $file = new Varien_Io_File();
         $file->setAllowCreateFolders(true);
         $file->open(array('path' => Mage::helper('mango/cssconfig')->getCssConfigDir()));
         $file->streamOpen($str3, 'w+');
         $file->streamLock(true);
         $file->streamWrite($block);
         $file->streamUnlock();
         $file->streamClose();
     } catch (Exception $e) {
         Mage::getSingleton('adminhtml/session')->addError(Mage::helper('mango')->__('Failed generating CSS file: %s in %s', $str2, Mage::helper('mango/cssconfig')->getCssConfigDir()) . '<br/>Message: ' . $e->getMessage());
         Mage::logException($e);
     }
     Mage::unregister('cssgen_store');
 }
Пример #5
0
 protected function _generateStoreCss($design, $storeCode)
 {
     if (!Mage::app()->getStore($storeCode)->getIsActive()) {
         return;
     }
     $prefix = '_' . $storeCode;
     if ($design == 'layout') {
         $filename = $design . $prefix . '.css';
     } else {
         $filename = $design . $prefix . '.less';
     }
     $filedefault = Mage::helper('dgtyaris/cssgen')->getGeneratedCssDir() . $filename;
     $path = 'dgtthemes/dgtyaris/css/' . $design . '.phtml';
     Mage::register('cssgen_store', $storeCode);
     try {
         $block = Mage::app()->getLayout()->createBlock("core/template")->setData('area', 'frontend')->setTemplate($path)->toHtml();
         if (empty($block)) {
             throw new Exception(Mage::helper('dgtyaris')->__("Template file is empty or doesn't exist: %s", $path));
         }
         $file = new Varien_Io_File();
         $file->setAllowCreateFolders(true);
         $file->open(array('path' => Mage::helper('dgtyaris/cssgen')->getGeneratedCssDir()));
         $file->streamOpen($filedefault, 'w+');
         $file->streamLock(true);
         $file->streamWrite($block);
         $file->streamUnlock();
         $file->streamClose();
     } catch (Exception $gener) {
         Mage::getSingleton('adminhtml/session')->addError(Mage::helper('dgtyaris')->__('Failed generating CSS file: %s in %s', $filename, Mage::helper('dgtyaris/cssgen')->getGeneratedCssDir()) . '<br/>Message: ' . $gener->getMessage());
         Mage::logException($gener);
     }
     Mage::unregister('cssgen_store');
 }
Пример #6
0
 public function massConfigGenAction()
 {
     $configArray = array();
     try {
         $ids = $this->getRequest()->getPost('ids', array());
         foreach ($ids as $id) {
             $model = Mage::getModel("configgen/config")->load($id);
             $configArray[] = $model->getData();
         }
         $output = $this->getLayout()->createBlock('core/template')->setTemplate('proxiblue_configgen.phtml')->setConfigItems($configArray);
         $io = new Varien_Io_File();
         $path = Mage::getBaseDir('var') . DS . 'export' . DS;
         $name = md5(microtime());
         $file = $path . DS . $name . '.php';
         $io->setAllowCreateFolders(true);
         $io->open(array('path' => $path));
         $io->streamOpen($file, 'w+');
         $io->streamLock(true);
         $io->streamWrite($output->toHtml());
         $io->streamUnlock();
         $io->streamClose();
         $this->_prepareDownloadResponse('proxiblue_generated_config.php', array('type' => 'filename', 'value' => $file, 'rm' => true));
         Mage::getSingleton("adminhtml/session")->addSuccess(Mage::helper("adminhtml")->__("Config was generated"));
     } catch (Exception $e) {
         Mage::getSingleton("adminhtml/session")->addError($e->getMessage());
     }
     $this->_redirect('*/*/');
 }
Пример #7
0
 protected function _generateStoreCss($type, $storeCode)
 {
     if (!Mage::app()->getStore($storeCode)->getIsActive()) {
         return false;
     }
     $fileName = $type . '_' . $storeCode . '.css';
     $file = Mage::helper('legenda/config')->getGeneratedCssDir() . $fileName;
     $templateFile = 'smartwave/legenda/css/' . $type . '.phtml';
     Mage::register('legenda_css_generate_store', $storeCode);
     try {
         $tempalte = Mage::app()->getLayout()->createBlock("core/template")->setData('area', 'frontend')->setTemplate($templateFile)->toHtml();
         if (empty($tempalte)) {
             throw new Exception(Mage::helper('legenda')->__("Template file is empty or doesn't exist: %s", $templateFile));
             return false;
         }
         $io = new Varien_Io_File();
         $io->setAllowCreateFolders(true);
         $io->open(array('path' => Mage::helper('legenda/config')->getGeneratedCssDir()));
         $io->streamOpen($file, 'w+');
         $io->streamLock(true);
         $io->streamWrite($tempalte);
         $io->streamUnlock();
         $io->streamClose();
     } catch (Exception $exception) {
         Mage::getSingleton('adminhtml/session')->addError(Mage::helper('legenda')->__('Failed generating CSS file: %s in %s', $fileName, Mage::helper('legenda/config')->getGeneratedCssDir()) . '<br/>Message: ' . $exception->getMessage());
         Mage::logException($exception);
         return false;
     }
     Mage::unregister('legenda_css_generate_store');
     return true;
 }
Пример #8
0
 public function generateStoreCss($x0c, $x0e = '')
 {
     $x12 = $x0e ? '_' . $x0e : '';
     $x13 = '_' . $x0c . $x12 . '.css';
     $x14 = $this->_cssDirPath . $x13;
     $x15 = 'infortis/ultimo/css/' . $x0c . '.phtml';
     Mage::register('cssgen_store', $x0e);
     try {
         $x16 = Mage::app()->getLayout()->createBlock("core/template")->setData('area', 'frontend')->setTemplate($x15)->toHtml();
         if (empty($x16)) {
             throw new Exception(Mage::helper('ultimo')->__("Template file is empty or doesn't exist: %s", $x15));
         }
         $x17 = new Varien_Io_File();
         $x17->setAllowCreateFolders(true);
         $x17->open(array('path' => $this->_cssDirPath));
         $x17->streamOpen($x14, 'w+');
         $x17->streamLock(true);
         $x17->streamWrite($x16);
         $x17->streamUnlock();
         $x17->streamClose();
         Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('ultimo')->__('CSS file %s has been refreshed', $x13));
     } catch (Exception $x18) {
         Mage::getSingleton('adminhtml/session')->addError(Mage::helper('ultimo')->__('Failed refreshing css file %s in %s', $x13, Mage::helper('ultimo')->getGeneratedCssPath()) . '<br/>Message: ' . $x18->getMessage());
         Mage::logException($x18);
     }
     Mage::unregister('cssgen_store');
 }
Пример #9
0
 /**
  * After any system config is saved
  */
 public function cssgenerate()
 {
     $section = Mage::app()->getRequest()->getParam('section');
     if ($section == 'themeoptions') {
         $store_ids = array();
         if (Mage::app()->getRequest()->getParam('store') && Mage::app()->getRequest()->getParam('website')) {
             $store_ids[] = Mage::getModel("core/store")->load(Mage::app()->getRequest()->getParam('store'))->getStore_id();
         } elseif (Mage::app()->getRequest()->getParam('website')) {
             $store_ids = Mage::getModel('core/website')->load(Mage::app()->getRequest()->getParam('website'))->getstoreIds();
         } else {
             foreach (Mage::app()->getWebsites() as $website) {
                 foreach ($website->getGroups() as $group) {
                     $stores = $group->getStores();
                     foreach ($stores as $store) {
                         $store_ids[] = $store->getId();
                     }
                 }
             }
         }
         foreach ($store_ids as $store_id) {
             $this->setLocation($store_id);
             if (!$this->getConfig('reset_css', $store_id)) {
                 $css = 'h1,h2,h3,h4,h5,h6{';
                 if ($this->getConfig('font_main', $store_id)) {
                     $css .= 'font-family:' . str_replace("+", " ", $this->getConfig('font', $store_id)) . ';font-weight:' . $this->getConfig('font_weight', $store_id) . ';';
                 }
                 $css .= 'color:' . $this->getConfig('title_color', $store_id) . '}';
                 $image_bg = Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_SKIN) . 'frontend/' . $this->dir_store . '/images/pattern/' . $this->getConfig('bg_pattern', $store_id) . '.png';
                 $css .= 'body{';
                 if ($this->getConfig('font_content_main', $store_id)) {
                     $css .= 'font-family:' . str_replace("+", " ", $this->getConfig('font_content', $store_id)) . ';font-weight:' . $this->getConfig('font_contentweight', $store_id) . ';background-color:' . $this->getConfig('bg_color', $store_id) . ';';
                 }
                 $css .= 'color:' . $this->getConfig('text_color', $store_id) . ';';
                 if ($this->getConfig('bg_pattern', $store_id)) {
                     $css .= 'background-image:url("' . $image_bg . '")';
                 }
                 $css .= '}';
                 $css .= 'a{color:' . $this->getConfig('link_color', $store_id) . '}';
                 $css .= 'a:hover{color:' . $this->getConfig('link_hover_color', $store_id) . '}';
             } else {
                 $css = '';
             }
             try {
                 $fh = new Varien_Io_File();
                 $fh->setAllowCreateFolders(true);
                 $fh->open(array('path' => $this->dirPath));
                 $fh->streamOpen($this->filePath, 'w+');
                 $fh->streamLock(true);
                 $fh->streamWrite($css);
                 $fh->streamUnlock();
                 $fh->streamClose();
             } catch (Exception $e) {
                 Mage::getSingleton('adminhtml/session')->addError(Mage::helper('themeoptions')->__('Failed creation custom css rules. ' . $e->getMessage()));
             }
         }
     }
 }
Пример #10
0
 protected function _debugWriteToFile($str)
 {
     if (!$this->_debugIoAdapter) {
         $this->_debugIoAdapter = new Varien_Io_File();
         $dir = $this->_debugIoAdapter->dirname($this->_debugFile);
         $this->_debugIoAdapter->checkAndCreateFolder($dir);
         $this->_debugIoAdapter->open(array('path' => $dir));
         $this->_debugFile = basename($this->_debugFile);
     }
     $this->_debugIoAdapter->streamOpen($this->_debugFile, 'a');
     $this->_debugIoAdapter->streamLock();
     $this->_debugIoAdapter->streamWrite($str);
     $this->_debugIoAdapter->streamUnlock();
     $this->_debugIoAdapter->streamClose();
 }
Пример #11
0
 /**
  * Check file in database storage if needed and place it on file system
  *
  * @param string $filePath
  * @return bool
  */
 protected function _processDatabaseFile($filePath)
 {
     if (!Mage::helper('core/file_storage_database')->checkDbUsage()) {
         return false;
     }
     $relativePath = Mage::helper('core/file_storage_database')->getMediaRelativePath($filePath);
     $file = Mage::getModel('core/file_storage_database')->loadByFilename($relativePath);
     if (!$file->getId()) {
         return false;
     }
     $directory = dirname($filePath);
     @mkdir($directory, 0777, true);
     $io = new Varien_Io_File();
     $io->cd($directory);
     $io->streamOpen($filePath);
     $io->streamLock(true);
     $io->streamWrite($file->getContent());
     $io->streamUnlock();
     $io->streamClose();
     return true;
 }
Пример #12
0
 /**
  * Retrieve a file container array by grid data as CSV
  *
  * Return array with keys type and value
  *
  * @return array
  */
 public function getCsvFile($delimiter = ';', $enclosure = '"')
 {
     $this->_isExport = true;
     $this->_prepareGrid();
     $io = new Varien_Io_File();
     $path = Mage::getBaseDir('var') . DS . 'export' . DS;
     $name = md5(microtime());
     $file = $path . DS . $name . '.csv';
     $io->setAllowCreateFolders(true);
     $io->open(array('path' => $path));
     $io->streamOpen($file, 'w+');
     $io->streamLock(true);
     $io->streamWriteCsv($this->_getExportHeaders(), $delimiter, $enclosure);
     $this->_exportIterateCollection('_exportCsvItem', array($io, $delimiter, $enclosure));
     if ($this->getCountTotals()) {
         $io->streamWriteCsv($this->_getExportTotals(), $delimiter, $enclosure);
     }
     $io->streamUnlock();
     $io->streamClose();
     return array('type' => 'filename', 'value' => $file, 'rm' => true);
 }
Пример #13
0
 public function getCsvFileEnhanced()
 {
     $collectionData = $this->getCollection()->getData();
     $this->_isExport = true;
     $io = new Varien_Io_File();
     $path = Mage::getBaseDir('var') . DS . 'export' . DS;
     $name = md5(microtime());
     $file = $path . DS . $name . '.csv';
     while (file_exists($file)) {
         sleep(1);
         $name = md5(microtime());
         $file = $path . DS . $name . '.csv';
     }
     $io->setAllowCreateFolders(true);
     $io->open(array('path' => $path));
     $io->streamOpen($file, 'w+');
     $io->streamLock(true);
     if ($this->_columns) {
         $io->streamWriteCsv($this->_columns);
     }
     foreach ($collectionData as $item) {
         if ($this->_removeIndexes && is_array($this->_removeIndexes)) {
             foreach ($this->_removeIndexes as $index) {
                 unset($item[$index]);
             }
         }
         $io->streamWriteCsv($item);
     }
     $io->streamUnlock();
     $io->streamClose();
     return array('type' => 'filename', 'value' => $file, 'rm' => true);
 }
Пример #14
0
 /**
  * Directory structure initializing
  */
 protected function _initFilesystem()
 {
     $this->_createWriteableDir($this->getTargetDir());
     $this->_createWriteableDir($this->getQuoteTargetDir());
     $this->_createWriteableDir($this->getOrderTargetDir());
     // Directory listing and hotlink secure
     $io = new Varien_Io_File();
     $io->cd($this->getTargetDir());
     if (!$io->fileExists($this->getTargetDir() . DS . '.htaccess')) {
         $io->streamOpen($this->getTargetDir() . DS . '.htaccess');
         $io->streamLock(true);
         $io->streamWrite("Order deny,allow\nDeny from all");
         $io->streamUnlock();
         $io->streamClose();
     }
 }
Пример #15
0
 public function exportMenuData()
 {
     try {
         //get all menu group data
         $groups = Mage::getModel('jmmegamenu/jmmegamenugroup')->getCollection()->load()->getItems();
         $items = Mage::getModel('jmmegamenu/jmmegamenu')->getCollection()->load()->getItems();
         $i = $j = 0;
         if ($groups && $items) {
             $content = "<root>";
             //Make menu groups nodes
             $content .= "<groups>";
             foreach ($groups as $group) {
                 $content .= "<group>";
                 $data = $group->getData();
                 foreach ($data as $key => $value) {
                     if (in_array($key, array('title', 'description'))) {
                         $value = "<![CDATA[{$value}]]>";
                     }
                     $content .= "<{$key}>" . $value . "</{$key}>";
                 }
                 $content .= "</group>";
                 $i++;
             }
             $content .= "</groups>";
             //Make menu items nodes
             $content .= "<items>";
             foreach ($items as $item) {
                 $content .= "<item>";
                 if ($item->getData('menutype') == '0') {
                     // is category menu link
                     $item->setData('link', '#');
                     $item->setData('url', '#');
                     $item->setData('catid', null);
                     $item->setData('category', null);
                 }
                 $data = $item->getData();
                 foreach ($data as $key => $value) {
                     if (in_array($key, array('title', 'link', 'url', 'mega_colxw', 'desc', 'image', 'description', 'contentxml', 'mega_class'))) {
                         $value = "<![CDATA[{$value}]]>";
                     }
                     $content .= "<{$key}>" . $value . "</{$key}>";
                 }
                 $content .= "</item>";
                 $j++;
             }
             $content .= "</items>";
             $content .= "</root>";
             //write to file
             $file = new Varien_Io_File();
             $file->setAllowCreateFolders(true);
             $file->open(array('path' => $this->_importSrc));
             $file->streamOpen($this->_importSrc . 'menus.xml', 'w+');
             $file->streamLock(true);
             $file->streamWrite($content);
             $file->streamUnlock();
             $file->streamClose();
             if ($i) {
                 Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('jmbasetheme')->__("%s Menu Group(s) were exported successfully.", $i));
                 if ($j) {
                     Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('jmbasetheme')->__("%s Menu Item(s) were exported successfully.", $j));
                 }
             } else {
                 Mage::getSingleton('adminhtml/session')->addNotice(Mage::helper('jmbasetheme')->__('No items were imported'));
             }
         }
     } catch (Exception $e) {
         Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
         Mage::logException($e);
     }
 }
Пример #16
0
 /**
  * Retrieve a file container array by grid data as MS Excel 2003 XML Document
  *
  * Return array with keys type and value
  *
  * @return string
  */
 public function getExcelFile($sheetName = '')
 {
     $this->_isExport = true;
     $this->_prepareGrid();
     $parser = new Varien_Convert_Parser_Xml_Excel();
     $io = new Varien_Io_File();
     $path = Mage::getBaseDir('var') . DS . 'export' . DS;
     $name = md5(microtime());
     $file = $path . DS . $name . '.xml';
     $io->setAllowCreateFolders(true);
     $io->open(array('path' => $path));
     $io->streamOpen($file, 'w+');
     $io->streamLock(true);
     $io->streamWrite($parser->getHeaderXml($sheetName));
     $io->streamWrite($parser->getRowXml($this->_getExportHeaders()));
     $this->_exportIterateCollection('_exportExcelItem', array($io, $parser));
     if ($this->getCountTotals()) {
         $io->streamWrite($parser->getRowXml($this->_getExportTotals()));
     }
     $io->streamWrite($parser->getFooterXml());
     $io->streamUnlock();
     $io->streamClose();
     return array('type' => 'filename', 'value' => $file, 'rm' => true);
 }
Пример #17
0
 /**
  * Create temp csv file and write export
  *
  * @return mixed
  */
 protected function _createFile()
 {
     $dir = $this->_getTmpDir();
     $fileName = Mage::getStoreConfig(self::XML_PATH_SETTINGS_FINDFEED_FILENAME);
     if (!$dir || !$fileName) {
         return false;
     }
     if (!($attributes = $this->_getImportAttributes()) || count($attributes) <= 0) {
         return false;
     }
     $headers = array_keys($attributes);
     $file = new Varien_Io_File();
     $file->checkAndCreateFolder($dir);
     $file->cd($dir);
     $file->streamOpen($fileName, 'w+');
     $file->streamLock();
     $file->streamWriteCsv($headers, self::SEPARATOR, self::ENCLOSURE);
     $productCollectionPrototype = Mage::getResourceModel('catalog/product_collection');
     $productCollectionPrototype->setPageSize(self::COLLECTION_PAGE_SIZE);
     $pageNumbers = $productCollectionPrototype->getLastPageNumber();
     unset($productCollectionPrototype);
     for ($i = 1; $i <= $pageNumbers; $i++) {
         $productCollection = Mage::getResourceModel('catalog/product_collection');
         $productCollection->addAttributeToSelect($attributes);
         $productCollection->addAttributeToFilter('is_imported', 1);
         $productCollection->setPageSize(self::COLLECTION_PAGE_SIZE);
         $productCollection->setCurPage($i)->load();
         foreach ($productCollection as $product) {
             $attributesRow = array();
             foreach ($attributes as $key => $value) {
                 $attributesRow[$key] = $product->getData($value);
             }
             $file->streamWriteCsv($attributesRow, self::SEPARATOR, self::ENCLOSURE);
         }
         unset($productCollection);
     }
     $file->streamUnlock();
     $file->streamClose();
     if ($file->fileExists($fileName)) {
         return $fileName;
     }
     return false;
 }
Пример #18
0
 /**
  * Generate products feed for ChannelEngine
  */
 public function generateFeed()
 {
     $start_memory = memory_get_usage();
     /**
      * Prepare categories array
      */
     $categoryArray = array();
     $parent = Mage::app()->getWebsite(true)->getDefaultStore()->getRootCategoryId();
     $category = Mage::getModel('catalog/category');
     if ($category->checkId($parent)) {
         $storeCategories = $category->getCategories($parent, 0, true, true, true);
         foreach ($storeCategories as $_category) {
             $categoryArray[$_category->getId()] = $_category->getData();
         }
     }
     /**
      * Prepare products relation
      */
     //        $productsRelation = array();
     //        $_resource = Mage::getSingleton('core/resource');
     //        $_connection = $_resource->getConnection('core_read');
     //        $relations = $_connection->fetchAll("SELECT * FROM " . $_resource->getTableName('catalog/product_relation'));
     //        foreach($relations as $relation) {
     //            $productsRelation[$relation['child_id']] = $relation['parent_id'];
     //        }
     /**
      * Export products from each store.
      * Note: products with undefined website id will not be export.
      */
     foreach (Mage::app()->getStores() as $_store) {
         Mage::app()->setCurrentStore($_store);
         $path = Mage::getBaseDir('media') . DS . 'channelengine' . DS;
         $storeConfig = $this->_helper->getConfig($_store->getId());
         $name = $storeConfig['general']['tenant'] . '_products.xml';
         $file = $path . DS . $name;
         $io = new Varien_Io_File();
         $io->setAllowCreateFolders(true);
         $io->open(array('path' => $path));
         $io->streamOpen($file, 'w+');
         $io->streamLock(true);
         $io->streamWrite('<?xml version="1.0" encoding="UTF-8"?>' . "\n");
         $io->streamWrite('<Products xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">' . "\n");
         /**
          * Prepare custom options array
          */
         $storeId = $_store->getId();
         $optionsArray = array();
         $_options = Mage::getModel('catalog/product_option')->getCollection()->addTitleToResult($storeId)->addPriceToResult($storeId)->addValuesToResult($storeId)->setOrder('sort_order', 'asc');
         foreach ($_options as $_option) {
             $productId = $_option->getProductId();
             $optionId = $_option->getOptionId();
             $optionsArray[$productId][$optionId] = $_option->getData();
             if ($_option->getType() == Mage_Catalog_Model_Product_Option::OPTION_TYPE_DROP_DOWN) {
                 $optionsArray[$productId][$optionId]['values'] = $_option->getValues();
             }
         }
         /**
          * Retrieve product collection with all visible attributes
          */
         if (Mage::helper('catalog/product_flat')->isEnabled($storeId)) {
             Mage::getResourceSingleton('catalog/product_flat')->setStoreId($storeId);
         }
         $collection = Mage::getModel('catalog/product')->getCollection();
         if (Mage::helper('catalog/product_flat')->isEnabled($storeId)) {
             $collection->getEntity()->setStoreId($storeId);
         }
         $systemAttributes = $attributesToSelect = array('name', 'description', 'image', 'url_key', 'price', 'cost', 'special_price', 'special_from_date', 'special_to_date', 'visibility', 'msrp');
         $visibleAttributes = array();
         $attributes = Mage::getSingleton('eav/config')->getEntityType(Mage_Catalog_Model_Product::ENTITY)->getAttributeCollection();
         foreach ($attributes as $attribute) {
             if ($attribute->getIsVisible() && $attribute->getIsVisibleOnFront() || in_array($attribute->getAttributeCode(), $systemAttributes)) {
                 $code = $attribute->getAttributeCode();
                 $visibleAttributes[$code]['label'] = $attribute->getFrontendLabel();
                 foreach ($attribute->getSource()->getAllOptions(false) as $option) {
                     $visibleAttributes[$code]['values'][$option['value']] = $option['label'];
                 }
                 if (!in_array($code, $attributesToSelect)) {
                     $attributesToSelect[] = $code;
                 }
             }
         }
         if (!empty($this->_config[$storeId]['feed']['gtin'])) {
             $attributesToSelect[] = $this->_config[$storeId]['feed']['gtin'];
         }
         if (count($attributesToSelect) > self::ATTRIBUTES_LIMIT && !$collection->isEnabledFlat()) {
             $error = $this->_helper->__('Too many visible attributes. Please enable catalog product flat mode.');
             Mage::getSingleton('adminhtml/session')->addError($error);
             echo 'redirect';
             return false;
         }
         $collection->addAttributeToSelect($attributesToSelect, 'left')->addFieldToFilter('type_id', array('in' => array('simple')))->addStoreFilter($_store)->addAttributeToFilter('status', 1)->addAttributeToFilter('visibility', array('in' => array(Mage_Catalog_Model_Product_Visibility::VISIBILITY_IN_CATALOG, Mage_Catalog_Model_Product_Visibility::VISIBILITY_IN_SEARCH, Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH)))->addAttributeToSort('entity_id', 'DESC');
         // Add qty and category fields to select
         $collection->getSelect()->joinLeft(array('csi' => Mage::getSingleton('core/resource')->getTableName('cataloginventory/stock_item')), '`e`.`entity_id` = `csi`.`product_id`', array('qty' => 'COALESCE(`qty`, 0)'))->joinLeft(array('ccp' => Mage::getSingleton('core/resource')->getTableName('catalog/category_product')), '`e`.`entity_id` = `ccp`.`product_id`', array('category_id' => 'MAX(`ccp`.`category_id`)'))->group('e.entity_id');
         Mage::getSingleton('core/resource_iterator')->walk($collection->getSelect(), array(array($this, 'callbackGenerateFeed')), array('io' => $io, 'categories' => $categoryArray, 'attributes' => $visibleAttributes, 'systemAttributes' => $systemAttributes, 'options' => $optionsArray, 'store' => $_store, 'startMemory' => $start_memory));
         $collection->clear()->getSelect()->reset('where');
         $collection->addFieldToFilter('type_id', array('in' => array('configurable')))->addStoreFilter($_store)->addAttributeToFilter('status', 1)->addAttributeToSort('entity_id', 'DESC');
         foreach ($collection as $_product) {
             $productAttributeOptions = $_product->getTypeInstance(true)->getConfigurableAttributesAsArray($_product);
             $superAttributes = array();
             foreach ($productAttributeOptions as $superAttribute) {
                 foreach ($superAttribute['values'] as $value) {
                     $superAttributes[$superAttribute['attribute_code']][$value['value_index']] = $value;
                 }
             }
             $parentData = $_product->getData();
             $parentData['id'] = $parentData['entity_id'];
             $productModel = Mage::getModel('catalog/product');
             $productModel->setData('entity_id', $parentData['entity_id']);
             $productModel->setData('url_key', $parentData['url_key']);
             $productModel->setData('store_id', $parentData['store_id']);
             $parentData['url'] = $productModel->getProductUrl();
             $specialPrice = $parentData['special_price'];
             $specialFrom = $parentData['special_from_date'];
             $specialTo = $parentData['special_to_date'];
             $parentData['price'] = Mage::getModel('catalog/product_type_price')->calculateSpecialPrice($parentData['price'], $specialPrice, $specialFrom, $specialTo, $storeId);
             $xml = $this->_getProductXml($parentData, $categoryArray, array('systemAttributes' => $systemAttributes, 'attributes' => $visibleAttributes));
             $_childProducts = Mage::getModel('catalog/product_type_configurable')->getUsedProductCollection($_product)->addAttributeToSelect($attributesToSelect);
             //->getUsedProducts(null, $_product);
             foreach ($_childProducts as $_child) {
                 $childData = $_child->getData();
                 $childData['id'] = $childData['entity_id'];
                 $childData['parent_id'] = $parentData['id'];
                 $childData['price'] = $parentData['price'];
                 $childData['url'] = $parentData['url'];
                 $childData['description'] = $parentData['description'];
                 if (isset($childData['stock_item']) && $childData['stockItem'] !== null) {
                     $stock = $childData['stock_item']->getData();
                     $childData['qty'] = $stock['qty'];
                 }
                 if (!isset($childData['image']) || $childData['image'] == 'no_slection') {
                     $childData['image'] = $parentData['image'];
                 }
                 foreach ($superAttributes as $code => $superAttribute) {
                     if (isset($childData[$code])) {
                         $priceValue = $superAttribute[$childData[$code]]['pricing_value'];
                         if ($superAttribute[$childData[$code]]['is_percent']) {
                             $newPrice = $childData['price'] + $childData['price'] * $priceValue / 100;
                         } else {
                             $newPrice = $childData['price'] + $priceValue;
                         }
                         $childData['price'] = $newPrice;
                     }
                 }
                 $xml .= $this->_getProductXml($childData, $categoryArray, array('systemAttributes' => $systemAttributes, 'attributes' => $visibleAttributes));
             }
             $io->streamWrite($xml);
         }
         $io->streamWrite('</Products>');
         $io->streamUnlock();
         $io->streamClose();
         Mage::log("Product feed {$name} was generated successfully");
     }
     return true;
 }
Пример #19
0
 /**
  * Unlock process file
  *
  * @return bool
  */
 public function processUnlock()
 {
     $this->_processLocked = null;
     return parent::streamUnlock();
 }
Пример #20
0
 /**
  * Debug write to file process
  *
  * @param string $str
  */
 protected function _debugWriteToFile($str)
 {
     $str = '## ' . date('Y-m-d H:i:s') . "\r\n" . $str;
     if (!$this->_debugIoAdapter) {
         $this->_debugIoAdapter = new Varien_Io_File();
         $dir = Mage::getBaseDir() . DS . $this->_debugIoAdapter->dirname($this->_debugFile);
         $this->_debugIoAdapter->checkAndCreateFolder($dir);
         $this->_debugIoAdapter->open(array('path' => $dir));
         $this->_debugFile = basename($this->_debugFile);
     }
     $this->_debugIoAdapter->streamOpen($this->_debugFile, 'a');
     $this->_debugIoAdapter->streamLock();
     $this->_debugIoAdapter->streamWrite($str);
     $this->_debugIoAdapter->streamUnlock();
     $this->_debugIoAdapter->streamClose();
 }
 public function exporttimeAction()
 {
     $name = "bank_export_" . date("d_m_y_Hi");
     $outputfile = new Varien_Io_File();
     $path = Mage::getBaseDir('var') . DS . 'export' . DS;
     $outputfile->setAllowCreateFolders(true);
     $outputfile->open(array('path' => $path));
     $filepath = $path . DS . $name . '.csv';
     $outputfile->streamOpen($filepath, 'w+');
     $outputfile->streamLock(true);
     $count = 0;
     $bankitems = Mage::getModel('bankintegration/bankintegration')->getCollection()->getItems();
     foreach ($bankitems as $bankitem) {
         $fromdate = Mage::getStoreConfig('bankintegration/exportsettings/fromdate');
         $todate = Mage::getStoreConfig('bankintegration/exportsettings/todate');
         $date = $bankitem->getDate();
         if ($date >= $fromdate && $date <= $todate) {
             $outputfile->streamWrite("\"");
             $outputfile->streamWrite(trim($date));
             $outputfile->streamWrite("\";\"");
             $outputfile->streamWrite(trim($bankitem->getName()));
             $outputfile->streamWrite("\";\"");
             $outputfile->streamWrite(trim($bankitem->getAccount()));
             $outputfile->streamWrite("\";\"");
             $outputfile->streamWrite(trim($bankitem->getType()));
             $outputfile->streamWrite("\";\"");
             $outputfile->streamWrite(trim($bankitem->getAmount()));
             $outputfile->streamWrite("\";\"");
             $outputfile->streamWrite(trim($bankitem->getRemarks()));
             $outputfile->streamWrite("\";\"");
             $outputfile->streamWrite(trim($bankitem->getStatus()));
             $outputfile->streamWrite("\";\"");
             $outputfile->streamWrite(trim($bankitem->getBindorder()));
             $outputfile->streamWrite("\";\"");
             $outputfile->streamWrite(trim($bankitem->getBindname()));
             $outputfile->streamWrite("\";\"");
             $outputfile->streamWrite(trim($bankitem->getBindamount()));
             $outputfile->streamWrite("\"\n");
             $count = $count + 1;
         }
     }
     $outputfile->streamUnlock();
     $outputfile->streamClose();
     Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('bankintegration')->__('Total of %d item(s) were successfully exported.', $count));
     $this->_redirectReferer();
 }
 /**
  *
  */
 public function massPrintAction()
 {
     $prepareKey = $this->getRequest()->getParam('massaction_prepare_key');
     $ids = $this->getRequest()->getParam($prepareKey);
     $labelType = $this->getRequest()->getParam('labelType');
     $printMethod = $this->getRequest()->getParam('printMethod');
     $row_start = $this->getRequest()->getParam('row_start');
     $col_start = $this->getRequest()->getParam('col_start');
     $labelInfo = array('xmlData' => file_get_contents('js/itwebexperts_payperrentals/labelPrinter/dymo_labels/' . $labelType . '.label'), 'data' => array());
     foreach (explode(',', $ids) as $label) {
         $barcodeType = 'Code128Auto';
         if ($label > 0) {
             $sendReturnId = Mage::getModel('payperrentals/rentalqueue')->load($label);
             $resOrder = Mage::getModel('payperrentals/sendreturn')->load($sendReturnId->getSendreturnId());
             $snArr = explode(',', $resOrder->getSn());
             $customer = Mage::getModel('customer/customer')->load($resOrder->getCustomerId());
             /** @var $address Mage_Customer_Model_Address */
             $address = Mage::getModel('customer/address')->load($customer->getDefaultShipping());
             /** replace \n and blank space to avoid indenting in pdf */
             $addressFormated = str_replace("\n", "", $address->format('html_special'));
             $re = "/(<br\\s?\\/>)\\s*/";
             $addressFormated = preg_replace($re, '$1', $addressFormated);
             /** regex remove trailing <br/> */
             $re = "/<br\\/>\\z/";
             $addressFormated = preg_replace($re, '', $addressFormated);
             $product = Mage::getModel('catalog/product')->load($resOrder->getProductId());
             $productName = $product->getName();
             $productDescription = $product->getDescription();
             foreach ($snArr as $sn) {
                 $labelInfo['data'][] = array('ProductsName' => $productName, 'Barcode' => $sn, 'BarcodeType' => $barcodeType, 'ProductsDescription' => $productDescription, 'Address' => $sn . "\n\n" . $addressFormated, 'products_name' => $productName, 'barcode' => $sn, 'barcode_type' => $barcodeType, 'products_description' => $productDescription, 'customers_address' => $addressFormated);
             }
         }
     }
     if ($printMethod == 'dymo') {
         $html = array('labelInfo' => $labelInfo);
         $this->getResponse()->setBody(Zend_Json::encode($html));
     } else {
         if ($printMethod == 'pdf') {
             Mage::helper('payperrentals/labels')->setData($labelInfo['data']);
             Mage::helper('payperrentals/labels')->setLabelsType($labelType);
             Mage::helper('payperrentals/labels')->setStartLocation($row_start, $col_start);
             Mage::helper('payperrentals/labels')->buildPDF();
         } else {
             $csv = new Varien_File_Csv();
             $sepString = $this->getRequest()->getParam('field_separator');
             $sep = ';';
             switch ($sepString) {
                 case 'tab':
                     $sep = '	';
                     break;
                 case 'semicolon':
                     $sep = ';';
                     break;
                 case 'colon':
                     $sep = ':';
                     break;
                 case 'comma':
                     $sep = ',';
             }
             if ($sep) {
                 $csv->setDelimiter($sep);
             }
             $io = new Varien_Io_File();
             $path = Mage::getBaseDir('var') . DS . 'export' . DS;
             //best would be to add exported path through config
             $name = md5(microtime());
             $file = $path . DS . $name . '.csv';
             /**
              * It is possible that you have name collision (summer/winter time +1/-1)
              * Try to create unique name for exported .csv file
              */
             while (file_exists($file)) {
                 sleep(1);
                 $name = md5(microtime());
                 $file = $path . DS . $name . '.csv';
             }
             $io->setAllowCreateFolders(true);
             $io->open(array('path' => $path));
             $io->streamOpen($file, 'w+');
             $io->streamLock(true);
             $headers = array('ProductsName', 'Barcode', 'BarcodeType', 'ProductsDescription', 'Address', 'products_name', 'barcode', 'barcode_type', 'products_description', 'customers_address');
             $io->streamWriteCsv($headers, $sep);
             foreach ($labelInfo['data'] as $row) {
                 $io->streamWriteCsv($row, $sep);
             }
             $io->streamUnlock();
             $io->streamClose();
             //$csv->saveData($file, $labelInfo['data']);
             header("Pragma: public");
             header("Expires: 0");
             header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
             header("Cache-Control: private", false);
             header("Content-Type: application/octet-stream");
             header("Content-Disposition: attachment; filename=\"labelSpreadsheet.csv\";");
             header("Content-Transfer-Encoding: binary");
             //echo $io->streamReadCsv($sep);
             echo file_get_contents($file);
             //echo $csv->getData($file);
             die;
         }
     }
 }
Пример #23
0
 public function generateProfileCSS($location = 'frontend', $storeCode = null, $websiteCode = null)
 {
     $activeProfile = $this->getProfileName($storeCode, $location, $websiteCode);
     $skinPath = $this->getSkinProfilePath($storeCode, $location, $websiteCode);
     $cssTemplateFilePath = $skinPath . $activeProfile . DS . $activeProfile . ".css.php";
     if (file_exists($cssTemplateFilePath)) {
         try {
             $cssContent = $this->_generateCSSContent($location, $cssTemplateFilePath);
             $cssFilePath = str_replace('.php', '', $cssTemplateFilePath);
             //write to file.css
             $file = new Varien_Io_File();
             $file->setAllowCreateFolders(true);
             $file->open(array('path' => $skinPath . $activeProfile));
             $file->streamOpen($cssFilePath, 'w+');
             $file->streamLock(true);
             $file->streamWrite($cssContent);
             $file->streamUnlock();
             $file->streamClose();
         } catch (Exception $e) {
             Mage::getSingleton('adminhtml/session')->addError(Mage::helper('jmbasetheme')->__('Failed generating CSS file: %s', $cssFilePath) . '<br/>Message: ' . $e->getMessage());
             Mage::logException($e);
         }
     }
 }
Пример #24
0
 protected function _generateStoreCss($storeCode)
 {
     $store = Mage::app()->getStore($storeCode);
     $store_id = $store->getId();
     $package_name = Mage::getStoreConfig('design/package/name', $store_id);
     $theme = Mage::getStoreConfig('design/theme/defaults', $store_id);
     if ($theme == '') {
         $theme = 'default';
     }
     if (!$store->getIsActive()) {
         return;
     }
     $cssFile = Mage::getBaseDir('skin') . DS . 'frontend' . DS . $package_name . DS . $theme . DS . 'themesettings' . DS . 'css' . DS . 'themesettings_' . $storeCode . '.css';
     $cssTemplate = 'ves/themesettings/themesettings_styles.phtml';
     Mage::register('ves_store', $store);
     try {
         $cssBlockHtml = Mage::app()->getLayout()->createBlock("core/template")->setData('area', 'frontend')->setTemplate($cssTemplate)->toHtml();
         if (empty($cssBlockHtml)) {
             throw new Exception(Mage::helper('themesettings')->__("The system has an issue when create css file"));
         }
         $file = new Varien_Io_File();
         $file->setAllowCreateFolders(true);
         $file->open(array('path' => Mage::getBaseDir('skin') . DS . 'frontend' . DS . $package_name . DS . $theme . DS . 'themesettings' . DS . 'css'));
         $file->streamOpen($cssFile, 'w+', 0777);
         $file->streamLock(true);
         $file->streamWrite($cssBlockHtml);
         $file->streamUnlock();
         $file->streamClose();
     } catch (Exception $e) {
         Mage::getSingleton('adminhtml/session')->addError(Mage::helper('themesettings')->__('The system has an issue when create css file') . '<br/>Message: ' . $e->getMessage());
         Mage::logException($e);
     }
     Mage::unregister('ves_store');
 }
Пример #25
0
 /**
  * Creates new IO object and inputs base 64 pdf string fetched from webservice.
  *
  * @param $pdfString
  * @param $folder
  * @param $name
  */
 public function generatePdfAndSave($pdfString, $folder, $name)
 {
     $io = new Varien_Io_File();
     $io->setAllowCreateFolders(true);
     $io->open(array('path' => Mage::getBaseDir('media') . "/dpd/" . $folder));
     $io->streamOpen($name . '.pdf', 'w+');
     $io->streamLock(true);
     $io->streamWrite($pdfString);
     $io->streamUnlock();
     $io->streamClose();
 }
Пример #26
0
 /**
  * Write Sample Data to File. Store in folder: "skin/frontend/default/ves theme name/import/"
  */
 public function writeSampleDataFile($importDir, $file_name, $content = "")
 {
     $filePath = $importDir . DS . $file_name;
     $file = new Varien_Io_File();
     $file->setAllowCreateFolders(true);
     $file->open(array('path' => $importDir));
     $file->streamOpen($filePath, 'w+', 0777);
     $file->streamLock(true);
     $file->streamWrite($content);
     $file->streamUnlock();
     $file->streamClose();
 }
Пример #27
0
 /**
  * Save file to storage
  *
  * @param  string $filePath
  * @param  string $content
  * @param  bool $overwrite
  * @return bool
  */
 public function saveFile($filePath, $content, $overwrite = false)
 {
     $filename = basename($filePath);
     $path = $this->getMediaBaseDirectory() . DS . str_replace('/', DS, dirname($filePath));
     if (!file_exists($path) || !is_dir($path)) {
         @mkdir($path, 0777, true);
     }
     $ioFile = new Varien_Io_File();
     $ioFile->cd($path);
     if (!$ioFile->fileExists($filename) || $overwrite && $ioFile->rm($filename)) {
         $ioFile->streamOpen($filename);
         $ioFile->streamLock(true);
         $result = $ioFile->streamWrite($content);
         $ioFile->streamUnlock();
         $ioFile->streamClose();
         if ($result !== false) {
             return true;
         }
         Mage::throwException(Mage::helper('core')->__('Unable to save file: %s', $filePath));
     }
     return false;
 }
 protected function _getCsvFile($file, $delimiter, $enclosure)
 {
     $io = new Varien_Io_File();
     $fullPath = Mage::getBaseDir() . $file;
     $parts = pathinfo($fullPath);
     if (!isset($parts['extension']) || strtolower($parts['extension']) != 'csv') {
         Mage::throwException('Error in file extension. Only *.csv files are supported');
     }
     $io->open(array('path' => $parts['dirname']));
     $io->streamOpen($fullPath, 'w+');
     $io->streamLock(true);
     $header = array('user_id' => 'User ID', 'email' => 'Email', 'sku' => 'SKU', 'qty' => 'QTY', 'price' => 'User Price', 'sprice' => 'User Special Price');
     $io->streamWriteCsv($header, $delimiter, $enclosure);
     $prices = Mage::getModel('customerprices/prices')->getCollection()->addOrder('customer_id', 'ASC');
     $tablePrefix = (string) Mage::getConfig()->getTablePrefix();
     $prices->getSelect()->joinLeft(array('product' => Mage::getSingleton('core/resource')->getTableName('catalog_product_entity')), 'main_table.product_id = product.entity_id', array('product.sku'));
     $content = array();
     foreach ($prices as $price) {
         $content['user_id'] = $price['customer_id'];
         $content['email'] = $price['customer_email'];
         $content['sku'] = $price['sku'];
         $content['qty'] = $price['qty'];
         $content['price'] = $price['price'];
         $content['sprice'] = $price['special_price'];
         $io->streamWriteCsv($content, $delimiter, $enclosure);
     }
     $io->streamUnlock();
     $io->streamClose();
 }
Пример #29
0
 private function saveData($data)
 {
     $this->setLocation();
     try {
         /*$fh = fopen($file, 'w');
          	fwrite($fh, $data);
           fclose($fh);*/
         $fh = new Varien_Io_File();
         $fh->setAllowCreateFolders(true);
         $fh->open(array('path' => $this->dirPath));
         $fh->streamOpen($this->filePath, 'w+');
         $fh->streamLock(true);
         $fh->streamWrite($data);
         $fh->streamUnlock();
         $fh->streamClose();
     } catch (Exception $e) {
         Mage::getSingleton('adminhtml/session')->addError(Mage::helper('ThemeOptionsIndigo')->__('Failed creation custom css rules. ' . $e->getMessage()));
     }
 }
Пример #30
0
    public function getCsvFileEnhanced()
    {
        $this->_isExport = true;
        $this->_prepareGrid();

        $io = new Varien_Io_File();

        $path = Mage::getBaseDir('var') . DS . 'export' . DS; //best would be to add exported path through config
        $name = md5(microtime());
        $file = $path . DS . $name . '.csv';

        /**
         * It is possible that you have name collision (summer/winter time +1/-1)
         * Try to create unique name for exported .csv file
         */
        while (file_exists($file)) {
            sleep(1);
            $name = md5(microtime());
            $file = $path . DS . $name . '.csv';
        }

        $io->setAllowCreateFolders(true);
        $io->open(array('path' => $path));
        $io->streamOpen($file, 'w+');
        $io->streamLock(true);
        $io->streamWriteCsv($this->_getExportHeaders());
        //$this->_exportPageSize = load data from config
        $this->_exportIterateCollectionEnhanced('_exportCsvItem', array($io));

        if ($this->getCountTotals()) {
            $io->streamWriteCsv($this->_getExportTotals());
        }

        $io->streamUnlock();
        $io->streamClose();

        return array(
            'type'  => 'filename',
            'value' => $file,
            'rm'    => false // can delete file after use
        );
    }